diff --git a/Cargo.lock b/Cargo.lock
index 0c34a6a952..f3e85a08a7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -978,11 +978,33 @@ dependencies = [
"ruzstd",
]
+[[package]]
+name = "craft-codepage"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
+
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
+[[package]]
+name = "craft-dxf"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
+dependencies = [
+ "craft-codepage",
+ "encoding_rs",
+ "kurbo 0.13.1",
+ "log",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "craft-eps"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
+
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
@@ -1057,6 +1079,21 @@ dependencies = [
"unicode-normalization",
]
+[[package]]
+name = "craft-svg"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
+dependencies = [
+ "craft-xml",
+ "flate2",
+ "kurbo 0.13.1",
+ "roxmltree 0.21.2",
+ "thiserror 2.0.21",
+ "usvg 0.48.1",
+ "vectorcraft-geom 0.18.0",
+ "vectorcraft-pathops 0.18.0",
+]
+
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -1146,6 +1183,15 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "craft-xml"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
+dependencies = [
+ "quick-xml 0.41.0",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -6340,8 +6386,8 @@ dependencies = [
"pollster 1.0.1",
"raw-window-handle",
"rfd",
+ "rustix 1.1.6",
"serde_json",
- "smithay-clipboard",
"socket2",
"tempfile",
"vectorcraft-engine",
@@ -6387,13 +6433,14 @@ dependencies = [
"serde_json",
"vectorcraft-color",
"vectorcraft-doc",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
]
[[package]]
name = "vectorcraft-cad"
version = "0.24.1"
dependencies = [
+ "craft-dxf",
"image",
"kurbo 0.13.1",
"serde_json",
@@ -6401,8 +6448,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom",
- "vectorcraft-pathops",
+ "vectorcraft-geom 0.24.1",
+ "vectorcraft-pathops 0.24.1",
"vectorcraft-text",
]
@@ -6419,7 +6466,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-mcp",
"vectorcraft-render",
"vectorcraft-svg",
@@ -6456,7 +6503,7 @@ dependencies = [
"thiserror 2.0.21",
"tiff",
"vectorcraft-color",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"zune-jpeg 0.5.15",
]
@@ -6471,8 +6518,8 @@ dependencies = [
"svgtypes 0.16.1",
"vectorcraft-color",
"vectorcraft-doc",
- "vectorcraft-geom",
- "vectorcraft-pathops",
+ "vectorcraft-geom 0.24.1",
+ "vectorcraft-pathops 0.24.1",
"vectorcraft-plugins",
"vectorcraft-text",
"vectorcraft-three-d",
@@ -6516,10 +6563,10 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-eps",
"vectorcraft-format",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-js",
"vectorcraft-metafile",
- "vectorcraft-pathops",
+ "vectorcraft-pathops 0.24.1",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
@@ -6538,6 +6585,7 @@ dependencies = [
name = "vectorcraft-eps"
version = "0.24.1"
dependencies = [
+ "craft-eps",
"craft-pdf",
"encoding_rs",
"fax",
@@ -6553,9 +6601,9 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-metafile",
- "vectorcraft-pathops",
+ "vectorcraft-pathops 0.24.1",
"vectorcraft-pdf",
"vectorcraft-render",
"vectorcraft-testkit",
@@ -6574,10 +6622,20 @@ dependencies = [
"serde_json",
"thiserror 2.0.21",
"vectorcraft-doc",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
]
+[[package]]
+name = "vectorcraft-geom"
+version = "0.18.0"
+source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
+dependencies = [
+ "kurbo 0.13.1",
+ "serde",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "vectorcraft-geom"
version = "0.24.1"
@@ -6612,7 +6670,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-render",
"vectorcraft-svg",
"vectorcraft-testkit",
@@ -6629,10 +6687,21 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-text",
]
+[[package]]
+name = "vectorcraft-pathops"
+version = "0.18.0"
+source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
+dependencies = [
+ "kurbo 0.13.1",
+ "linesweeper",
+ "thiserror 2.0.21",
+ "vectorcraft-geom 0.18.0",
+]
+
[[package]]
name = "vectorcraft-pathops"
version = "0.24.1"
@@ -6641,7 +6710,7 @@ dependencies = [
"linesweeper",
"proptest",
"thiserror 2.0.21",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
]
@@ -6666,6 +6735,7 @@ dependencies = [
"serde",
"serde_json",
"sha2",
+ "siphasher",
"skrifa 0.47.0",
"smallvec",
"thiserror 2.0.21",
@@ -6673,7 +6743,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
"weezl 0.2.1",
@@ -6692,7 +6762,7 @@ dependencies = [
"thiserror 2.0.21",
"vectorcraft-color",
"vectorcraft-doc",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"wasmi",
"wat",
"web-time",
@@ -6717,7 +6787,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-plugins",
"vectorcraft-testkit",
"vectorcraft-text",
@@ -6741,6 +6811,7 @@ name = "vectorcraft-svg"
version = "0.24.1"
dependencies = [
"craft-docpath",
+ "craft-svg",
"flate2",
"image",
"kurbo 0.13.1",
@@ -6752,13 +6823,14 @@ dependencies = [
"skrifa 0.47.0",
"svgtypes 0.16.1",
"thiserror 2.0.21",
+ "unicode-bidi",
"usvg 0.48.1",
"vectorcraft-brush",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom",
- "vectorcraft-pathops",
+ "vectorcraft-geom 0.24.1",
+ "vectorcraft-pathops 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
]
@@ -6776,7 +6848,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-render",
"vectorcraft-svg",
]
@@ -6796,7 +6868,7 @@ dependencies = [
"unicode-script",
"unicode-segmentation",
"vectorcraft-doc",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vello_cpu",
"windows-registry",
"write-fonts",
@@ -6806,8 +6878,8 @@ dependencies = [
name = "vectorcraft-three-d"
version = "0.24.1"
dependencies = [
- "vectorcraft-geom",
- "vectorcraft-pathops",
+ "vectorcraft-geom 0.24.1",
+ "vectorcraft-pathops 0.24.1",
]
[[package]]
@@ -6822,8 +6894,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom",
- "vectorcraft-pathops",
+ "vectorcraft-geom 0.24.1",
+ "vectorcraft-pathops 0.24.1",
"vectorcraft-text",
]
@@ -6836,7 +6908,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
]
[[package]]
@@ -6865,7 +6937,7 @@ dependencies = [
"vectorcraft-engine",
"vectorcraft-eps",
"vectorcraft-format",
- "vectorcraft-geom",
+ "vectorcraft-geom 0.24.1",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
diff --git a/Cargo.toml b/Cargo.toml
index 5bed166e17..c7856d589e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -25,6 +25,12 @@ craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", re
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
+# SVG parsing, limits, SVGZ and writer (craft-libs#778).
+craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2", features = ["tree"] }
+# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
+craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
+# DXF tags, reader and writer (craft-libs#778, #926, #927).
+craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
diff --git a/ROADMAP.md b/ROADMAP.md
index b5a2f43c7a..dabed3eb94 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -18,6 +18,8 @@ gate: all six core workflows (path drawing and editing, paint and style, type, l
production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without
blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
+> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged.
+
## Headline numbers
| | Value | Kind |
@@ -96,6 +98,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| Simplified Chinese | `zh-hans` | partial (messages in English) | 85% |
| Spanish | `es` | full | 100% |
| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner |
+| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial |
| Arabic | `ar` | none (no right-to-left interface) | 0% |
| French | `fr` | full | 100% |
| Portuguese (Brazil) | `pt-br` | full | 100% |
@@ -121,8 +124,11 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
+- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
+
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
+- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
@@ -141,6 +147,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged.
- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
+- 2026-11-13: Gradient panel › Method: Hue Clockwise and Hue Counterclockwise mix a linear, radial, conic or diamond gradient's colors around the hue wheel in one direction, so red to blue passes through magenta one way and through yellow and green the other (`paint.editGradient` `method`: `hue-clockwise`, `hue-counterclockwise`); SVG and PDF exports write such a gradient as an image.
- 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`).
- 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged.
@@ -216,6 +223,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
+| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. |
@@ -224,6 +232,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| 2026-11-03 | minor | UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. |
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
+| 2026-11-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) |
+| 2026-11-11 | minor | Gujarati (`gu`): 4,235-row machine-assisted interface catalog, one/other plurals, desktop Gujarati font fallback; messages not yet translated; native review pending |
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs
index 0d4deca36f..b66c15070f 100644
--- a/apps/vectorcraft-cli/src/main.rs
+++ b/apps/vectorcraft-cli/src/main.rs
@@ -418,10 +418,18 @@ fn convert(args: &[String]) -> Result<(), String> {
// Save as Template writes every artboard, with the .ai options.
("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy}))
} else {
- // A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
- // PSD).
- let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy});
+ let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy});
let mut params = with_pixel_scale(params, &output, scale, ppi);
+ // An option the format doesn't read comes back in the warnings, so each goes out only
+ // when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the
+ // formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects,
+ // written hidden.
+ if outline_text {
+ params["outlineText"] = json!(true);
+ }
+ if vectorcraft_engine::cmd::fileio::writable_format(None, Some(&output)).is_ok_and(|f| f.options.iter().any(|o| o.name == "hiddenLayers")) {
+ params["hiddenLayers"] = json!(true);
+ }
if let Some(decimals) = decimals {
params["decimals"] = json!(decimals);
}
diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs
index 71044be4a5..cdb16d28d3 100644
--- a/apps/vectorcraft-cli/tests/it/fileio.rs
+++ b/apps/vectorcraft-cli/tests/it/fileio.rs
@@ -177,6 +177,27 @@ fn convert_reports_import_warnings() {
assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}");
}
+/// A conversion sends each format only the options it reads, so its warnings name an unused
+/// option only when the command line gave one: `--outline-text` for a format without it.
+#[test]
+fn convert_warns_about_an_unused_option_only_when_one_was_given() {
+ let svg = tmp("unused-option.svg");
+ std::fs::write(&svg, r#""#).unwrap();
+ let unused = |out: &Value| -> Vec {
+ let w = out["warnings"].as_array().unwrap_or_else(|| panic!("{out}"));
+ w.iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
+ };
+ for ext in ["png", "jpg", "pdf", "ai", "eps", "psd", "dxf", "svg", "txt", "vectorcraft", "vctemplate"] {
+ let path = tmp(&format!("unused-option.{ext}"));
+ let out: Value = serde_json::from_str(ok(&["convert", &svg, &path]).trim()).unwrap();
+ assert!(unused(&out).is_empty(), "{ext}: {out}");
+ }
+ let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.svg"), "--outline-text"]).trim()).unwrap();
+ assert!(unused(&out).is_empty(), "{out}");
+ let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.png"), "--outline-text"]).trim()).unwrap();
+ assert_eq!(unused(&out), ["`outlineText` was not used: PNG files don't read it"], "{out}");
+}
+
#[test]
fn convert_writes_legacy_ai_with_its_options() {
// Two artboards, a shown rectangle and a hidden one.
diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml
index 55b9e344e7..9a1b11e350 100644
--- a/apps/vectorcraft/Cargo.toml
+++ b/apps/vectorcraft/Cargo.toml
@@ -58,7 +58,10 @@ pollster = "1"
# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which
# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`,
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
-windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
+# Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and
+# Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the
+# display's color profile for the canvas.
+windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# The renderer's worker count follows those cores (src/windows_cores.rs).
vectorcraft-render = { workspace = true }
@@ -93,29 +96,34 @@ winit = { version = "0.30", default-features = false, features = ["wayland-csd-a
# A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a
# second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build
# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs).
-x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] }
+# RandR reads a display's `_ICC_PROFILE` for the canvas (src/display_profile.rs).
+x11rb = { version = "0.13", default-features = false, features = ["randr", "xinput", "xkb"] }
# Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs),
-# so Automatic draws on that one. Both are already in the build through winit.
+# so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's
+# core data-device protocol on the window's connection (src/clipboard.rs), where arboard has neither
+# data-control (GNOME) nor X11 (a Flatpak on a Wayland session). Both are already in the build
+# through winit.
wayland-client = "0.31"
-# Copy and Paste of text through the compositor's core data-device protocol on the window's
-# connection (src/clipboard.rs), where arboard has neither data-control (GNOME) nor X11 (a Flatpak
-# on a Wayland session). MIT, already in the build through egui-winit.
-smithay-clipboard = "0.7"
wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
# The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
# through winit and rfd.
wayland-backend = { version = "0.3", features = ["client_system"] }
-# Waits for the screen color sampler's portal answer and for the portal leaving the bus at the same
-# time (src/linux_screen_color/request.rs). Apache-2.0 OR MIT, already in the build through zbus.
-futures-lite = "2"
+# The Wayland clipboard's pipes (src/clipboard.rs): `poll` and the nonblocking flag give up a read
+# or send when the other app moves no data for a while. Apache-2.0 WITH LLVM-exception OR
+# Apache-2.0 OR MIT, already in the build through the workspace.
+rustix = { workspace = true, features = ["std", "event", "fs"] }
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
# exactly: review the diff before bumping.
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
zbus = "=5.19.0"
+# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal
+# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build
+# through zbus.
+futures-lite = "2"
# Tells whether arboard reads through the compositor's data-control protocol or through X11, the
# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through
# arboard.
diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs
index 4827772444..dddaf0a91e 100644
--- a/apps/vectorcraft/src/app.rs
+++ b/apps/vectorcraft/src/app.rs
@@ -108,37 +108,14 @@ impl eframe::App for App {
self.app.start_pending_update();
#[cfg(target_os = "macos")]
super::mac_cursor::release();
+ // Dropping the app can wait for the clipboard handles to let go: the windows leave the
+ // screen first (`quit_windows`).
#[cfg(not(any(target_os = "macos", windows)))]
- hide_before_teardown(self.winit_window.as_deref());
+ super::quit_windows::before_teardown(self.winit_window.as_deref());
end_before_teardown(self.frames);
}
}
-/// The main window as [`hide_before_teardown`] sees it.
-#[cfg(not(any(target_os = "macos", windows)))]
-pub(crate) trait QuittingWindow {
- fn hide(&self);
-}
-
-#[cfg(not(any(target_os = "macos", windows)))]
-impl QuittingWindow for winit::window::Window {
- fn hide(&self) {
- self.set_visible(false);
- }
-}
-
-/// On Linux and the BSDs, hide the main window before eframe drops the app. Dropping the app waits
-/// up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the clipboard handles to let go, and
-/// the window would stay on screen for that time. The window is hidden, not closed: the Wayland
-/// clipboard reads text on the window's connection. winit hides X11 windows (XWayland included) and
-/// cannot hide a Wayland window.
-#[cfg(not(any(target_os = "macos", windows)))]
-pub(crate) fn hide_before_teardown(window: Option<&W>) {
- if let Some(window) = window {
- window.hide();
- }
-}
-
impl App {
/// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a
/// focused, shown window whose windows had input waits for the renderer and the next frame,
@@ -219,6 +196,9 @@ impl App {
self.app.services.dock_monitors = window::dock_monitors(w, zoom);
self.monitors_listed = Some((now, zoom));
}
+ if let Some(w) = &self.winit_window {
+ self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx);
+ }
self.app.tick(ctx);
if self.pending_maximize {
if let Some(w) = &self.winit_window {
diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs
index 1daccc22f1..17b9327956 100644
--- a/apps/vectorcraft/src/clipboard.rs
+++ b/apps/vectorcraft/src/clipboard.rs
@@ -10,8 +10,9 @@
//! Linux arboard reads no other formats). On Wayland, arboard's data-control
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
//! copied), falling back to X11 where the compositor lacks the protocol, and where there is no
-//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection,
-//! text only. A clipboard that can't be opened is tried again after a wait that grows to a
+//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection:
+//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads SVG,
+//! text and PNG. A clipboard that can't be opened is tried again after a wait that grows to a
//! minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app
//! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at
//! once; a paste then waits for that read's answer off the UI thread.
@@ -24,8 +25,8 @@ use std::path::PathBuf;
use vectorcraft_engine::cmd::clipboard::{BITMAP, EPS, FILE_HEAD, Flavour, PDF, PNG, SVG, TEXT, file_flavour};
use vectorcraft_ui_egui::{ClipboardRead, SystemClipboard};
-/// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text where
-/// arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11).
+/// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text, SVG and
+/// PNG where arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11).
pub fn system_clipboard(window: Option>) -> Box {
#[cfg(windows)]
let cb = {
@@ -629,6 +630,10 @@ mod portable {
enum Ours {
Text(String),
Image(usize, usize),
+ /// A Copy through the Wayland core protocol, whose data source tells whether the
+ /// clipboard still holds it.
+ #[cfg(target_os = "linux")]
+ Source,
}
/// A read of arboard's clipboard.
@@ -858,18 +863,14 @@ mod portable {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
impl Late {
/// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The
- /// core protocol's text is waited for as long, until [`IMAGE_WAIT`] after its read was
- /// sent, then read again, and pasted unless it is empty, what `ours` put on the clipboard,
- /// or doesn't come.
+ /// core protocol's answer is waited for as long, until [`IMAGE_WAIT`] after its read was
+ /// sent; then the clipboard is read again and pasted as at once, unless it holds the Copy
+ /// made here ([`super::wayland::Unanswered::paste`]).
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option {
match self {
Self::Arboard(unanswered) => unanswered.paste(ours, mimes),
#[cfg(target_os = "linux")]
- Self::Wayland(unanswered) => {
- let text = unanswered.text(IMAGE_WAIT).ok().filter(|t| !t.is_empty())?;
- let held = matches!(ours, Some(Ours::Text(t)) if *t == text);
- (!held).then(|| Flavour { mime: TEXT, data: text.into_bytes() })
- }
+ Self::Wayland(unanswered) => unanswered.paste(mimes, IMAGE_WAIT),
}
}
}
@@ -962,14 +963,15 @@ mod portable {
/// An open clipboard connection.
enum Backend {
Arboard(Arboard),
- /// The compositor's core data-device protocol on the window's connection (text only).
+ /// The compositor's core data-device protocol on the window's connection.
#[cfg(target_os = "linux")]
- Wayland(super::wayland::TextClipboard),
+ Wayland(super::wayland::DataClipboard),
}
- /// What a write of a picture says where the clipboard carries text only.
+ /// What a bitmap read or write says on the core protocol, which carries pictures as PNG data
+ /// only ([`Clipboard::write`], [`Clipboard::read_now_or_later`]).
#[cfg(target_os = "linux")]
- const TEXT_ONLY: &str = "this clipboard carries text only";
+ const PNG_ONLY: &str = "this clipboard carries pictures as PNG data";
impl Backend {
/// arboard (Wayland data-control, else X11), else the core protocol on `window`'s
@@ -979,7 +981,10 @@ mod portable {
|| Arboard::open().map(Self::Arboard),
|| {
#[cfg(target_os = "linux")]
- return window.and_then(|w| super::wayland::TextClipboard::new(w.clone())).map(Self::Wayland).ok_or("not a Wayland window");
+ return window
+ .and_then(|w| super::wayland::DataClipboard::new(w.clone()))
+ .map(Self::Wayland)
+ .ok_or("not a Wayland window with a seat and a data-device manager");
#[cfg(not(target_os = "linux"))]
{
let _ = window;
@@ -993,7 +998,7 @@ mod portable {
match self {
Self::Arboard(_) => "arboard",
#[cfg(target_os = "linux")]
- Self::Wayland(_) => "the Wayland core protocol (text only)",
+ Self::Wayland(_) => "the Wayland core protocol",
}
}
@@ -1001,7 +1006,7 @@ mod portable {
match self {
Self::Arboard(cb) => cb.read(Request::Text).text(),
#[cfg(target_os = "linux")]
- Self::Wayland(cb) => cb.get_text(),
+ Self::Wayland(cb) => cb.text(),
}
}
@@ -1009,10 +1014,17 @@ mod portable {
match self {
Self::Arboard(cb) => cb.cb.set_text(text).map_err(|e| e.to_string()),
#[cfg(target_os = "linux")]
- Self::Wayland(cb) => {
- cb.set_text(text);
- Ok(())
- }
+ Self::Wayland(cb) => cb.copy(&[Flavour { mime: TEXT, data: text.as_bytes().to_vec() }]),
+ }
+ }
+
+ /// Whether the clipboard holds the core protocol's last Copy made here (never for arboard,
+ /// whose writes are checked by what they wrote).
+ #[cfg(target_os = "linux")]
+ fn holds_source(&mut self) -> bool {
+ match self {
+ Self::Arboard(_) => false,
+ Self::Wayland(cb) => cb.holds_ours(),
}
}
@@ -1025,7 +1037,7 @@ mod portable {
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))]
Self::Arboard(cb) => cb.read(Request::Image).image(),
#[cfg(target_os = "linux")]
- Self::Wayland(_) => Err(TEXT_ONLY.into()),
+ Self::Wayland(_) => Err(PNG_ONLY.into()),
}
}
@@ -1041,7 +1053,7 @@ mod portable {
Ok(Box::new(move || Ok(image)))
}
#[cfg(target_os = "linux")]
- Self::Wayland(_) => Err(TEXT_ONLY.into()),
+ Self::Wayland(_) => Err(PNG_ONLY.into()),
}
}
@@ -1049,7 +1061,7 @@ mod portable {
match self {
Self::Arboard(cb) => cb.cb.set_image(img).map_err(|e| e.to_string()),
#[cfg(target_os = "linux")]
- Self::Wayland(_) => Err(TEXT_ONLY.into()),
+ Self::Wayland(_) => Err(PNG_ONLY.into()),
}
}
@@ -1057,15 +1069,12 @@ mod portable {
match self {
Self::Arboard(cb) => cb.cb.clear().map_err(|e| e.to_string()),
#[cfg(target_os = "linux")]
- Self::Wayland(cb) => {
- cb.set_text("");
- Ok(())
- }
+ Self::Wayland(cb) => cb.copy(&[]),
}
}
/// The read that got no answer in its wait, when a paste of one of `mimes` can take its
- /// answer ([`Arboard::unanswered`], [`TextReads::unanswered`](super::wayland::TextReads::unanswered)).
+ /// answer ([`Arboard::unanswered`], [`Reads::unanswered`](super::wayland::Reads::unanswered)).
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn unanswered(&mut self, mimes: &[&'static str]) -> Option {
match self {
@@ -1223,9 +1232,15 @@ mod portable {
Some(ClipboardRead::Later(Box::new(move || unanswered.paste(ours.as_ref(), &mimes))))
}
- /// Text and copied files are read here, and work that reads arboard's image comes back.
+ /// Text and copied files are read here, and work that reads arboard's image comes back. On
+ /// the Wayland core protocol the first of `mimes` the clipboard offers is read: text here,
+ /// SVG and PNG by the work that comes back, which waits [`IMAGE_WAIT`] at most.
fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option {
let cb = self.cb(Asker::User).ok()?;
+ #[cfg(target_os = "linux")]
+ if let Backend::Wayland(cb) = cb {
+ return cb.read(mimes, IMAGE_WAIT);
+ }
if let Some(f) = copied_file(cb.file_list(), mimes) {
return Some(ClipboardRead::Now(f));
}
@@ -1247,13 +1262,23 @@ mod portable {
}
impl SystemClipboard for Clipboard {
+ /// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the
+ /// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)).
fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> {
+ let cb = self.cb(Asker::User)?;
+ #[cfg(target_os = "linux")]
+ if let Backend::Wayland(wl) = cb {
+ wl.copy(flavours)?;
+ // What a read got late was on the clipboard before this write.
+ wl.forget_unanswered();
+ self.ours = wl.holds_ours().then_some(Ours::Source);
+ return Ok(());
+ }
let text = text_of(flavours);
let image = match &text {
Some(_) => None,
None => flavours.iter().find(|f| f.mime == PNG).and_then(|f| decode_png(&f.data)),
};
- let cb = self.cb(Asker::User)?;
let ours = match (text, image) {
(Some(t), _) => {
cb.set_text(t.as_str())?;
@@ -1281,6 +1306,8 @@ mod portable {
match &self.ours {
Some(Ours::Text(t)) => cb.get_text().is_ok_and(|now| now == *t),
Some(Ours::Image(w, h)) => cb.image_now().is_ok_and(|now| (now.width, now.height) == (*w, *h)),
+ #[cfg(target_os = "linux")]
+ Some(Ours::Source) => cb.holds_source(),
None => false,
}
}
@@ -1307,7 +1334,8 @@ mod portable {
read
}
- /// Text, and on macOS vector art or a bitmap (by the pasteboard's types). Linux has no
+ /// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland
+ /// core protocol SVG, text or PNG (by the types offered, nothing read). arboard has no
/// cheap way to ask for a bitmap (reading one costs as much as pasting it): the paste keys
/// take it, the menu item waits for text.
fn has(&mut self, mimes: &[&'static str]) -> bool {
@@ -1315,7 +1343,12 @@ mod portable {
if super::mac::has(mimes) {
return true;
}
- mimes.contains(&TEXT) && self.cb(Asker::Probe).is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty()))
+ let Ok(cb) = self.cb(Asker::Probe) else { return false };
+ #[cfg(target_os = "linux")]
+ if let Backend::Wayland(wl) = cb {
+ return wl.has(mimes);
+ }
+ mimes.contains(&TEXT) && cb.get_text().is_ok_and(|t| !t.is_empty())
}
}
@@ -1656,45 +1689,58 @@ mod portable {
#[cfg(target_os = "linux")]
#[test]
fn a_paste_after_an_unanswered_core_protocol_text_read_waits_for_its_answer() {
- use super::super::wayland::TextReads;
+ use std::sync::{Arc, Mutex};
+
+ use super::super::wayland::{Reads, Seen};
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
- /// Core protocol text reads whose owner answers with `text` only once the sender
+ /// Core protocol reads of a clipboard offering `types`, whose owner answers each read
+ /// of a text type with `text` and of `image/png` with `png`, only once the sender
/// returned is used or dropped.
- fn slow_text(text: &'static str) -> (TextReads, std::sync::mpsc::Sender<()>) {
+ fn slow_owner(types: &[&str], text: &'static str, png: &'static [u8]) -> (Reads, Arc>, std::sync::mpsc::Sender<()>) {
let (release, gate) = std::sync::mpsc::channel::<()>();
- let loads = Loads::spawn("test", Duration::ZERO, move |()| {
+ let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
let _ = gate.recv();
- Ok(text.to_string())
+ Ok(if wire == PNG { png.to_vec() } else { text.as_bytes().to_vec() })
})
.unwrap();
- (TextReads::new(loads), release)
+ let seen = Arc::new(Mutex::new(Seen::offering(types)));
+ (Reads::new(loads, seen.clone()), seen, release)
}
- // Text was copied here; the clipboard's owner answers the check with `text` late.
- let paste_after_check = |text: &'static str| {
- let (mut reads, release) = slow_text(text);
+ // The clipboard's owner answers the check with `text` late; `copied_here` when the
+ // clipboard holds the Copy made here meanwhile.
+ let paste_after_check = |text: &'static str, copied_here: bool| {
+ let (mut reads, seen, release) = slow_owner(&["text/plain;charset=utf-8", PNG], text, b"\x89PNG");
// The check whether the clipboard still holds what was copied here gets no answer
// in its wait (2 s on the UI thread, none here).
- assert!(reads.get(Duration::ZERO).is_err());
+ assert!(reads.text(Duration::ZERO).is_err());
// The paste's own read fails at once while the owner hasn't answered.
- assert!(reads.get(Duration::from_secs(600)).is_err());
+ assert!(reads.text(Duration::from_secs(600)).is_err());
// A paste of a bitmap alone can't take text: the read stays kept.
assert!(reads.unanswered(&[BITMAP]).is_none());
let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste"));
- let ours = Ours::Text("copied here".into());
- let paste = std::thread::spawn(move || late.paste(Some(&ours), &PASTE_ORDER));
+ if copied_here {
+ let mut seen = seen.lock().unwrap();
+ seen.copy(vec!["text/plain;charset=utf-8", PNG]);
+ seen.selection(vec!["text/plain;charset=utf-8".into(), PNG.into()]);
+ }
+ let paste = std::thread::spawn(move || late.paste(None, &PASTE_ORDER));
drop(release);
paste.join().ok().flatten()
};
- let pasted = paste_after_check("copied elsewhere").expect("the other app's text is pasted");
+ let pasted = paste_after_check("copied elsewhere", false).expect("the other app's text is pasted");
assert_eq!((pasted.mime, pasted.data), (TEXT, b"copied elsewhere".to_vec()));
- // The text copied here, or nothing: the paste takes the internal clipboard.
- assert!(paste_after_check("copied here").is_none());
- assert!(paste_after_check("").is_none());
+ // Text that only names a picture goes with it: the picture is pasted, as at once.
+ let pasted = paste_after_check("https://example.com/art.png", false).expect("the picture is pasted");
+ assert_eq!((pasted.mime, pasted.data), (PNG, b"\x89PNG".to_vec()));
+ // The Copy made here, by its data source: the paste takes the internal clipboard.
+ assert!(paste_after_check("copied elsewhere", true).is_none());
+ // Empty text is not pasted: the picture beside it is.
+ assert_eq!(paste_after_check("", false).map(|f| f.mime), Some(PNG));
// An answer that came before the paste may be old: it is dropped, not pasted.
- let (mut reads, release) = slow_text("old");
- assert!(reads.get(Duration::ZERO).is_err());
+ let (mut reads, _, release) = slow_owner(&["text/plain"], "old", b"");
+ assert!(reads.text(Duration::ZERO).is_err());
drop(release);
while reads.waiting() {
std::thread::yield_now();
@@ -1705,14 +1751,14 @@ mod portable {
// again and takes the new owner's text.
let (release, gate) = std::sync::mpsc::channel::<()>();
let mut texts_read = 0;
- let loads = Loads::spawn("test", Duration::ZERO, move |()| {
+ let loads = Loads::spawn("test", Duration::ZERO, move |_: String| {
let _ = gate.recv();
texts_read += 1;
- Ok(if texts_read == 1 { "old owner" } else { "new owner" }.to_string())
+ Ok(if texts_read == 1 { "old owner" } else { "new owner" }.as_bytes().to_vec())
})
.unwrap();
- let mut reads = TextReads::new(loads);
- assert!(reads.get(Duration::ZERO).is_err());
+ let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&["UTF8_STRING"]))));
+ assert!(reads.text(Duration::ZERO).is_err());
let late = Late::Wayland(reads.unanswered(&[TEXT]).expect("the read is kept for the paste"));
let paste = std::thread::spawn(move || late.paste(None, &[TEXT]));
drop(release);
@@ -1737,81 +1783,398 @@ mod portable {
/// The compositor's clipboard through the core data-device protocol (`wl_data_device`), on the
/// window's own Wayland connection: what Copy and Paste use where the compositor lacks the
/// data-control protocol arboard needs (GNOME) and there is no X11 to fall back on (the Flatpak on
-/// a Wayland session). Text only (smithay-clipboard), and only while the window has focus, as the
-/// protocol has it. A read waits [`LOAD_WAIT`] at most: smithay-clipboard waits for the owner's
-/// data with no limit, so reads run on a worker of their own. A read that gets no answer in that
-/// time is kept for a paste to wait for off the UI thread, as arboard's are.
+/// a Wayland session). A Copy offers its SVG as `image/svg+xml`, its PNG as `image/png` and its
+/// text under each of [`TEXT_TYPES`]; Paste reads the clipboard's SVG, text and PNG, and the paste
+/// check looks at the types offered without reading any data. The protocol gives the clipboard to
+/// the window with the keyboard focus only. A worker thread handles the protocol's events and
+/// starts a thread for each paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads
+/// run on another worker and take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, SVG and
+/// PNG as long as a paste's bitmap from arboard. A read that gets no answer in its wait is kept for
+/// a paste to wait for off the UI thread, as arboard's are. A read or send whose pipe moves no data
+/// for [`IDLE_WAIT`] fails and closes the pipe, which frees its worker or thread.
#[cfg(target_os = "linux")]
mod wayland {
- use std::sync::{Arc, mpsc};
+ use std::io::{ErrorKind, Read, Write};
+ use std::os::fd::{AsFd, BorrowedFd};
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+ use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc};
use std::time::{Duration, Instant};
- use super::TEXT;
+ use rustix::event::{PollFd, PollFlags, Timespec};
+ use vectorcraft_engine::cmd::clipboard::names_a_picture;
+ use vectorcraft_ui_egui::ClipboardRead;
+ use wayland_client::backend::ObjectData;
+ use wayland_client::globals::{GlobalListContents, registry_queue_init};
+ use wayland_client::protocol::wl_callback::{self, WlCallback};
+ use wayland_client::protocol::wl_data_device::{self, WlDataDevice};
+ use wayland_client::protocol::wl_data_device_manager::{self, WlDataDeviceManager};
+ use wayland_client::protocol::wl_data_offer::{self, WlDataOffer};
+ use wayland_client::protocol::wl_data_source::{self, WlDataSource};
+ use wayland_client::protocol::wl_keyboard::{self, WlKeyboard};
+ use wayland_client::protocol::wl_pointer::{self, WlPointer};
+ use wayland_client::protocol::wl_registry::{self, WlRegistry};
+ use wayland_client::protocol::wl_seat::{self, WlSeat};
+ use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
+
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
+ use super::{BITMAP, Flavour, PNG, SVG, TEXT};
- /// What a text read gives.
- type Text = Result;
+ /// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
+ /// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`.
+ const TEXT_TYPES: [&str; 3] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"];
+ /// The most bytes a read takes from the app that copied (untrusted data), VectorCraft's own
+ /// limit: a read of more fails.
+ const MAX_BYTES: usize = 64 << 20;
+ /// The most pastes of a Copy's data that are sent at once; a paste beyond them gets nothing.
+ const MAX_SENDS: usize = 8;
+ /// The most types of an offer that are kept (untrusted data).
+ const MAX_TYPES: usize = 256;
+ /// How long a read or send waits for the other app to move a byte through the pipe before it
+ /// fails, VectorCraft's own limit; the wait starts again after each byte moved.
+ const IDLE_WAIT: Duration = LOAD_WAIT;
+ /// The most bytes a read takes from the pipe at a time.
+ const CHUNK: usize = 64 << 10;
- pub struct TextClipboard {
- /// Writes: a store only hands the text to smithay-clipboard's thread.
- cb: smithay_clipboard::Clipboard,
- /// Reads, on a worker with a second clipboard on the same connection.
- reads: TextReads,
- /// Held as long as the clipboards: their connection is the window's.
- _window: Arc,
+ /// What a read gives: the bytes, or why there are none.
+ type Got = Result, String>;
+
+ fn lock(m: &Mutex) -> MutexGuard<'_, T> {
+ m.lock().unwrap_or_else(PoisonError::into_inner)
}
- /// Text reads on a worker, and the last one that got no answer in its wait.
- pub(super) struct TextReads {
- loads: Loads<(), Text>,
- /// The last read that got no answer in its wait, until a paste takes it or the next read
- /// is sent.
+ /// The types a Copy of `flavours` offers, each with its data: SVG as `image/svg+xml`, PNG as
+ /// `image/png` and text under each of [`TEXT_TYPES`]. Flavours with no data and other flavours
+ /// (PDF) are not offered.
+ fn copy_types(flavours: &[Flavour]) -> Vec<(&'static str, Arc<[u8]>)> {
+ let mut out: Vec<(&'static str, Arc<[u8]>)> = vec![];
+ for f in flavours.iter().filter(|f| !f.data.is_empty()) {
+ let types: &[&'static str] = match f.mime {
+ SVG => &[SVG],
+ PNG => &[PNG],
+ TEXT => &TEXT_TYPES,
+ _ => &[],
+ };
+ let data: Arc<[u8]> = f.data.as_slice().into();
+ for &t in types {
+ if !out.iter().any(|(o, _)| *o == t) {
+ out.push((t, data.clone()));
+ }
+ }
+ }
+ out
+ }
+
+ /// The type among `offered` that a read of `mime` asks for, in any letter case: SVG as
+ /// `image/svg+xml`, text as the first of [`TEXT_TYPES`] offered, a bitmap as `image/png`.
+ fn wire_type<'a>(mime: &str, offered: &'a [String]) -> Option<&'a str> {
+ let wanted: &[&str] = match mime {
+ SVG => &[SVG],
+ TEXT => &TEXT_TYPES,
+ BITMAP | PNG => &[PNG],
+ _ => &[],
+ };
+ wanted.iter().find_map(|w| offered.iter().find(|o| o.eq_ignore_ascii_case(w))).map(String::as_str)
+ }
+
+ /// The flavour a read of `mime` makes of `data`: SVG as it is, a bitmap as PNG, text with its
+ /// line ends as `\n`. None when `data` is empty.
+ fn flavour(mime: &'static str, data: Vec) -> Option {
+ if data.is_empty() {
+ return None;
+ }
+ Some(match mime {
+ TEXT => Flavour { mime: TEXT, data: String::from_utf8_lossy(&data).replace("\r\n", "\n").replace('\r', "\n").into_bytes() },
+ BITMAP | PNG => Flavour { mime: PNG, data },
+ _ => Flavour { mime, data },
+ })
+ }
+
+ /// What a paste of one of `mimes` takes from a clipboard offering `offered`, `read` reading the
+ /// offer's type for each one tried: the first of `mimes` offered with data, except that text
+ /// that is blank or only names a picture gives way to the PNG when `mimes` has a bitmap
+ /// (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`).
+ fn pick(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option>) -> Option {
+ let mut take = |mime: &'static str| flavour(mime, read(wire_type(mime, offered)?)?);
+ let first = mimes.iter().find_map(|&m| take(m))?;
+ if first.mime == TEXT && mimes.contains(&BITMAP) {
+ let text = String::from_utf8_lossy(&first.data);
+ if text.trim().is_empty() || names_a_picture(&text) {
+ return take(BITMAP).or(Some(first));
+ }
+ }
+ Some(first)
+ }
+
+ /// The time `idle` from now; None when that is past the clock's range (no limit).
+ fn idle_until(idle: Duration) -> Option {
+ Instant::now().checked_add(idle)
+ }
+
+ /// Makes `fd` nonblocking, its other flags kept.
+ fn nonblocking(fd: BorrowedFd<'_>) -> std::io::Result<()> {
+ let flags = rustix::fs::fcntl_getfl(fd)?;
+ rustix::fs::fcntl_setfl(fd, flags | rustix::fs::OFlags::NONBLOCK)?;
+ Ok(())
+ }
+
+ /// Waits until `fd` is ready for `events`, closed or failed (true), or `until` passes (false);
+ /// None waits without a limit. A wait a signal cuts short goes on until `until`.
+ fn ready(fd: BorrowedFd<'_>, events: PollFlags, until: Option) -> std::io::Result {
+ loop {
+ let left = until.map(|t| t.saturating_duration_since(Instant::now()));
+ let timeout = left.and_then(|d| Timespec::try_from(d).ok());
+ let mut fds = [PollFd::new(&fd, events)];
+ match rustix::event::poll(&mut fds, timeout.as_ref()) {
+ Ok(n) => return Ok(n > 0),
+ Err(rustix::io::Errno::INTR) => {}
+ Err(e) => return Err(e.into()),
+ }
+ }
+ }
+
+ /// `from` read to its end, `cap` bytes at most: more is an error, as is a failed read and a
+ /// pipe that is left open with no byte coming for `idle`. A read that fails gives none of the
+ /// bytes it took, and closes `from`.
+ fn read_capped(mut from: impl Read + AsFd, cap: usize, idle: Duration) -> Got {
+ let failed = |e: std::io::Error| format!("couldn't read the clipboard's data: {e}");
+ nonblocking(from.as_fd()).map_err(failed)?;
+ let (mut data, mut chunk) = (vec![], vec![0u8; CHUNK]);
+ let mut until = idle_until(idle);
+ loop {
+ match from.read(&mut chunk) {
+ Ok(0) => return Ok(data),
+ Ok(n) => {
+ let got = chunk.get(..n).ok_or_else(|| failed(ErrorKind::InvalidData.into()))?;
+ if data.len() + got.len() > cap {
+ return Err(format!("the clipboard's data is larger than {} MiB", cap >> 20));
+ }
+ data.extend_from_slice(got);
+ until = idle_until(idle);
+ }
+ Err(e) if e.kind() == ErrorKind::Interrupted => {}
+ Err(e) if e.kind() == ErrorKind::WouldBlock => {
+ if !ready(from.as_fd(), PollFlags::IN, until).map_err(failed)? {
+ return Err("the app that copied stopped sending the clipboard's data".to_string());
+ }
+ }
+ Err(e) => return Err(failed(e)),
+ }
+ }
+ }
+
+ /// `data` written to `to`: an error when the app that pastes closes its end (the process
+ /// ignores `SIGPIPE`) or takes no byte for `idle`.
+ fn send(mut to: impl Write + AsFd, data: &[u8], idle: Duration) -> std::io::Result<()> {
+ nonblocking(to.as_fd())?;
+ let (mut sent, mut until) = (0, idle_until(idle));
+ while let Some(rest) = data.get(sent..).filter(|rest| !rest.is_empty()) {
+ match to.write(rest) {
+ Ok(0) => return Err(ErrorKind::WriteZero.into()),
+ Ok(n) => {
+ sent += n;
+ until = idle_until(idle);
+ }
+ Err(e) if e.kind() == ErrorKind::Interrupted => {}
+ Err(e) if e.kind() == ErrorKind::WouldBlock => {
+ if !ready(to.as_fd(), PollFlags::OUT, until)? {
+ return Err(ErrorKind::TimedOut.into());
+ }
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ Ok(())
+ }
+
+ /// The threads that send a Copy's data to the apps that paste it, counted.
+ #[derive(Clone)]
+ struct Sends {
+ running: Arc,
+ /// How long a send waits for the app that pastes to take a byte.
+ idle: Duration,
+ }
+
+ impl Default for Sends {
+ fn default() -> Self {
+ Self { running: Arc::default(), idle: IDLE_WAIT }
+ }
+ }
+
+ impl Sends {
+ /// `data` written to `to` on a thread of its own ([`send`]), which then closes `to`; an app
+ /// that closes its end early or takes no byte for the send's idle wait ends the write.
+ /// While [`MAX_SENDS`] are being written `to` is closed at once with nothing written → false.
+ fn start(&self, to: impl Write + AsFd + Send + 'static, data: Arc<[u8]>) -> bool {
+ if self.running.fetch_add(1, Ordering::SeqCst) >= MAX_SENDS {
+ self.running.fetch_sub(1, Ordering::SeqCst);
+ return false;
+ }
+ let (count, idle) = (self.running.clone(), self.idle);
+ let work = move || {
+ let _ = send(to, &data, idle);
+ count.fetch_sub(1, Ordering::SeqCst);
+ };
+ if std::thread::Builder::new().name("wayland-clipboard-send".into()).spawn(work).is_err() {
+ self.running.fetch_sub(1, Ordering::SeqCst);
+ return false;
+ }
+ true
+ }
+
+ /// How many are being written.
+ #[cfg(test)]
+ fn running(&self) -> usize {
+ self.running.load(Ordering::SeqCst)
+ }
+ }
+
+ /// What the protocol worker has seen of the clipboard.
+ #[derive(Default)]
+ pub(super) struct Seen {
+ /// The types of the clipboard's offer, none when it is empty.
+ offered: Vec,
+ /// The types of this connection's last Copy, until its data source is canceled.
+ copied: Option>,
+ /// Whether the clipboard holds that Copy.
+ ours: bool,
+ }
+
+ impl Seen {
+ /// A clipboard offering `types`, copied elsewhere.
+ #[cfg(test)]
+ pub(super) fn offering(types: &[&str]) -> Self {
+ Self { offered: types.iter().map(|t| t.to_string()).collect(), ..Self::default() }
+ }
+
+ /// A Copy of `types` (none: the clipboard emptied) was given the clipboard.
+ pub(super) fn copy(&mut self, types: Vec<&'static str>) {
+ self.ours = !types.is_empty();
+ self.copied = Some(types).filter(|t| !t.is_empty());
+ }
+
+ /// The clipboard's offer has `offered` now. It holds the last Copy while that Copy's data
+ /// source is not canceled and the offer has the Copy's types, no more and no fewer, as the
+ /// compositor offers a source's types. An offer made before the Copy and handled after it
+ /// makes the Copy not ours until the Copy's own offer comes.
+ pub(super) fn selection(&mut self, offered: Vec) {
+ self.ours = self.copied.as_ref().is_some_and(|c| c.len() == offered.len() && c.iter().all(|t| offered.iter().any(|o| o == t)));
+ self.offered = offered;
+ }
+
+ /// The last Copy's data source was canceled: another app holds the clipboard.
+ pub(super) fn cancelled(&mut self) {
+ self.copied = None;
+ self.ours = false;
+ }
+ }
+
+ /// Reads of the clipboard's offer on a worker, and the last one that got no answer in its wait.
+ pub(super) struct Reads {
+ /// Each request is the offer's type to read.
+ loads: Loads,
+ seen: Arc>,
+ /// The last text read that got no answer in its wait, until a paste takes it or the next
+ /// read is sent.
unanswered: Option,
}
/// A text read that got no answer in its wait.
pub(super) struct Unanswered {
- answer: mpsc::Receiver,
+ answer: mpsc::Receiver,
sent: Instant,
- /// The worker, for the read made again once the answer comes.
- reads: Asker<(), Text>,
+ /// The worker, for the reads made once the answer comes.
+ reads: Asker,
+ seen: Arc>,
}
impl Unanswered {
- /// The text, read again once this read's answer comes, waiting for that answer until
- /// `limit` after the read was sent, and for the new one as long, [`LOAD_WAIT`] at least.
- /// The late answer may come from an app that lost the clipboard while it was awaited.
- pub(super) fn text(self, limit: Duration) -> Text {
+ /// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until
+ /// `limit` after the read was sent: the clipboard read again as [`pick`] reads it, each read
+ /// waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may have lost the
+ /// clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
+ /// connection's Copy.
+ pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option {
let left = |now: Instant| (self.sent + limit).saturating_duration_since(now);
- let _late = wait_for_answer(&self.answer, left(Instant::now()))?;
- wait_for_answer(&self.reads.ask(())?, LOAD_WAIT.max(left(Instant::now())))?
+ let _late = wait_for_answer(&self.answer, left(Instant::now())).ok()?;
+ let offered = {
+ let seen = lock(&self.seen);
+ if seen.ours {
+ return None;
+ }
+ seen.offered.clone()
+ };
+ pick(&offered, mimes, |wire| wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok())
}
}
- impl TextReads {
- pub(super) fn new(loads: Loads<(), Text>) -> Self {
- Self { loads, unanswered: None }
+ impl Reads {
+ pub(super) fn new(loads: Loads, seen: Arc>) -> Self {
+ Self { loads, seen, unanswered: None }
}
- /// The text, waiting `wait` at most. A read that gets no answer in that time is kept
- /// ([`Self::unanswered`]) for a paste to wait for off the UI thread; a read sent means the
- /// one kept has been answered, and its answer is dropped.
- pub(super) fn get(&mut self, wait: Duration) -> Text {
+ /// The offer's type for `mime`, when it has one.
+ fn wire(&self, mime: &str) -> Option {
+ wire_type(mime, &lock(&self.seen).offered).map(str::to_string)
+ }
+
+ /// The text, waiting `wait` at most; empty when the clipboard has none. A read that gets no
+ /// answer in that time is kept ([`Self::unanswered`]) for a paste to wait for off the UI
+ /// thread; a read sent means the one kept has been answered, and its answer is dropped.
+ pub(super) fn text(&mut self, wait: Duration) -> Result {
+ let Some(wire) = self.wire(TEXT) else { return Ok(String::new()) };
let sent = Instant::now();
- let answer = self.loads.ask(())?;
+ let answer = self.loads.ask(wire)?;
self.unanswered = None;
match wait_for_answer(&answer, wait) {
- Ok(text) => text,
+ Ok(got) => Ok(flavour(TEXT, got?).map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default()),
Err(why) => {
if why != GONE {
- self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker() });
+ self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone() });
}
Err(why)
}
}
}
- /// The read that got no answer in its wait, while its answer has still not come and a
+ /// What a paste of one of `mimes` reads: the first the clipboard offers. Text is read here,
+ /// [`LOAD_WAIT`] at most, and pasted unless it is empty; SVG and PNG are asked for here and
+ /// waited for, `wait` at most, by the work that comes back. When that read fails or is
+ /// empty, the work reads the rest of `mimes` as [`pick`] does, each read waiting until
+ /// `wait` after the first was sent, [`LOAD_WAIT`] at least.
+ pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option {
+ mimes.iter().enumerate().find_map(|(i, &mime)| {
+ let wire = self.wire(mime)?;
+ if mime == TEXT {
+ let text = self.text(LOAD_WAIT).ok().filter(|t| !t.is_empty())?;
+ return Some(ClipboardRead::Now(Flavour { mime: TEXT, data: text.into_bytes() }));
+ }
+ let sent = Instant::now();
+ let answer = self.loads.ask(wire).ok()?;
+ self.unanswered = None;
+ let (reads, seen, rest) = (self.loads.asker(), self.seen.clone(), mimes.get(i + 1..).unwrap_or_default().to_vec());
+ Some(ClipboardRead::Later(Box::new(move || {
+ if let Some(f) = wait_for_answer(&answer, wait).ok().and_then(Result::ok).and_then(|data| flavour(mime, data)) {
+ return Some(f);
+ }
+ let offered = lock(&seen).offered.clone();
+ let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
+ pick(&offered, &rest, |wire| wait_for_answer(&reads.ask(wire.to_string()).ok()?, left()).ok()?.ok())
+ })))
+ })
+ }
+
+ /// Whether the clipboard offers one of `mimes`; nothing is read.
+ pub(super) fn has(&self, mimes: &[&'static str]) -> bool {
+ let seen = lock(&self.seen);
+ mimes.iter().any(|m| wire_type(m, &seen.offered).is_some())
+ }
+
+ /// Whether the clipboard holds this connection's last Copy.
+ pub(super) fn holds_ours(&self) -> bool {
+ lock(&self.seen).ours
+ }
+
+ /// The text read that got no answer in its wait, while its answer has still not come and a
/// paste of one of `mimes` can take text. Once it has come the answer may be old, and it is
/// dropped: a new read is made.
pub(super) fn unanswered(&mut self, mimes: &[&'static str]) -> Option {
@@ -1819,6 +2182,11 @@ mod wayland {
self.loads.waiting().then_some(unanswered)
}
+ /// Drops the read that got no answer in its wait: a paste no longer takes its answer.
+ pub(super) fn forget_unanswered(&mut self) {
+ self.unanswered = None;
+ }
+
/// Whether a read sent is still unanswered.
#[cfg(test)]
pub(super) fn waiting(&self) -> bool {
@@ -1826,55 +2194,646 @@ mod wayland {
}
}
- /// The read worker's clipboard and the window whose connection it uses, dropped in that order.
- struct Loader {
- cb: smithay_clipboard::Clipboard,
+ /// The protocol objects of a [`DataClipboard`], kept up to date by its worker.
+ #[derive(Default)]
+ struct Objects {
+ device: Option,
+ keyboard: Option,
+ pointer: Option,
+ /// The serial of the last key press, click or keyboard focus, which a Copy takes the
+ /// clipboard with.
+ serial: Option,
+ /// The clipboard's offer.
+ selection: Option,
+ /// The offer of a drag over the window.
+ drag: Option,
+ /// The last Copy's data source.
+ source: Option,
+ }
+
+ /// An offer's types, as its events give them.
+ #[derive(Default)]
+ struct OfferData(Mutex>);
+
+ /// A Copy's types with their data.
+ struct SourceData(Vec<(&'static str, Arc<[u8]>)>);
+
+ /// What the protocol worker's event handlers change.
+ struct State {
+ objects: Arc>,
+ seen: Arc>,
+ sends: Sends,
+ }
+
+ impl State {
+ /// Lets go of every object, once the clipboard is dropped.
+ fn close(&mut self, seat: &WlSeat) {
+ let mut o = lock(&self.objects);
+ for offer in [o.selection.take(), o.drag.take()].into_iter().flatten() {
+ offer.destroy();
+ }
+ if let Some(source) = o.source.take() {
+ source.destroy();
+ }
+ if let Some(device) = o.device.take().filter(|d| d.version() >= 2) {
+ device.release();
+ }
+ if let Some(keyboard) = o.keyboard.take().filter(|k| k.version() >= 3) {
+ keyboard.release();
+ }
+ if let Some(pointer) = o.pointer.take().filter(|p| p.version() >= 3) {
+ pointer.release();
+ }
+ if seat.version() >= 5 {
+ seat.release();
+ }
+ }
+ }
+
+ impl Dispatch for State {
+ fn event(_: &mut Self, _: &WlRegistry, _: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle) {}
+ }
+
+ impl Dispatch for State {
+ fn event(_: &mut Self, _: &WlCallback, _: wl_callback::Event, _: &(), _: &Connection, _: &QueueHandle) {}
+ }
+
+ impl Dispatch for State {
+ fn event(_: &mut Self, _: &WlDataDeviceManager, _: wl_data_device_manager::Event, _: &(), _: &Connection, _: &QueueHandle) {}
+ }
+
+ impl Dispatch for State {
+ fn event(state: &mut Self, seat: &WlSeat, event: wl_seat::Event, _: &(), _: &Connection, qh: &QueueHandle) {
+ let wl_seat::Event::Capabilities { capabilities: WEnum::Value(caps) } = event else { return };
+ let mut o = lock(&state.objects);
+ if !caps.contains(wl_seat::Capability::Keyboard) {
+ if let Some(keyboard) = o.keyboard.take().filter(|k| k.version() >= 3) {
+ keyboard.release();
+ }
+ } else if o.keyboard.is_none() {
+ o.keyboard = Some(seat.get_keyboard(qh, ()));
+ }
+ if !caps.contains(wl_seat::Capability::Pointer) {
+ if let Some(pointer) = o.pointer.take().filter(|p| p.version() >= 3) {
+ pointer.release();
+ }
+ } else if o.pointer.is_none() {
+ o.pointer = Some(seat.get_pointer(qh, ()));
+ }
+ }
+ }
+
+ /// The serial a Copy takes the clipboard with after the keyboard event `event`, `serial` before
+ /// it: a key or the keyboard focus coming in sets it, the focus leaving clears it, and other
+ /// events leave it. A modifier change's serial is not an input event's, and the release of Ctrl
+ /// after Ctrl+C comes before the Copy's data is ready.
+ fn keyboard_serial(event: &wl_keyboard::Event, serial: Option) -> Option {
+ match event {
+ wl_keyboard::Event::Enter { serial, .. } | wl_keyboard::Event::Key { serial, .. } => Some(*serial),
+ wl_keyboard::Event::Leave { .. } => None,
+ _ => serial,
+ }
+ }
+
+ impl Dispatch for State {
+ fn event(state: &mut Self, _: &WlKeyboard, event: wl_keyboard::Event, _: &(), _: &Connection, _: &QueueHandle) {
+ let mut o = lock(&state.objects);
+ o.serial = keyboard_serial(&event, o.serial);
+ }
+ }
+
+ impl Dispatch for State {
+ fn event(state: &mut Self, _: &WlPointer, event: wl_pointer::Event, _: &(), _: &Connection, _: &QueueHandle) {
+ if let wl_pointer::Event::Button { serial, .. } = event {
+ lock(&state.objects).serial = Some(serial);
+ }
+ }
+ }
+
+ impl Dispatch for State {
+ fn event(state: &mut Self, _: &WlDataDevice, event: wl_data_device::Event, _: &(), _: &Connection, _: &QueueHandle) {
+ let mut o = lock(&state.objects);
+ match event {
+ wl_data_device::Event::Selection { id } => {
+ let mut offered = id.as_ref().and_then(|offer| offer.data::()).map(|d| lock(&d.0).clone()).unwrap_or_default();
+ offered.dedup();
+ if let Some(old) = std::mem::replace(&mut o.selection, id) {
+ old.destroy();
+ }
+ lock(&state.seen).selection(offered);
+ }
+ wl_data_device::Event::Enter { id, .. } => {
+ if let Some(old) = std::mem::replace(&mut o.drag, id) {
+ old.destroy();
+ }
+ }
+ wl_data_device::Event::Leave | wl_data_device::Event::Drop => {
+ if let Some(old) = o.drag.take() {
+ old.destroy();
+ }
+ }
+ _ => {}
+ }
+ }
+
+ /// The one event of a data device that makes an object is `data_offer`.
+ fn event_created_child(_: u16, qh: &QueueHandle) -> Arc {
+ qh.make_data::(OfferData::default())
+ }
+ }
+
+ impl Dispatch for State {
+ fn event(_: &mut Self, _: &WlDataOffer, event: wl_data_offer::Event, data: &OfferData, _: &Connection, _: &QueueHandle) {
+ if let wl_data_offer::Event::Offer { mime_type } = event {
+ let mut types = lock(&data.0);
+ if types.len() < MAX_TYPES {
+ types.push(mime_type);
+ }
+ }
+ }
+ }
+
+ impl Dispatch for State {
+ fn event(state: &mut Self, source: &WlDataSource, event: wl_data_source::Event, data: &SourceData, _: &Connection, _: &QueueHandle) {
+ match event {
+ // A type the Copy doesn't offer gets nothing: dropping `fd` closes it.
+ wl_data_source::Event::Send { mime_type, fd } => {
+ if let Some((_, bytes)) = data.0.iter().find(|(t, _)| t.eq_ignore_ascii_case(&mime_type)) {
+ state.sends.start(std::fs::File::from(fd), bytes.clone());
+ }
+ }
+ wl_data_source::Event::Cancelled => {
+ source.destroy();
+ let mut o = lock(&state.objects);
+ if o.source.as_ref() == Some(source) {
+ o.source = None;
+ lock(&state.seen).cancelled();
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+
+ /// Reads the clipboard's offer for the read worker.
+ struct Receiver {
+ conn: Connection,
+ objects: Arc>,
+ /// Held as long as the connection, which is the window's.
_window: Arc,
}
- impl Loader {
- fn load(&self) -> Result {
- self.cb.load().map_err(|e| e.to_string())
+ impl Receiver {
+ /// The clipboard's data of type `wire`, read until the app that copied closes the pipe,
+ /// [`MAX_BYTES`] at most; an error when that app sends no byte for [`IDLE_WAIT`].
+ fn receive(&self, wire: String) -> Got {
+ let offer = lock(&self.objects).selection.clone().ok_or("the clipboard is empty")?;
+ let (from, to) = std::io::pipe().map_err(|e| format!("couldn't open a pipe for the clipboard's data: {e}"))?;
+ offer.receive(wire, to.as_fd());
+ // The request carries a copy of the write end: once it is sent, the app that copied
+ // holds the only one, and the read ends when that app closes it.
+ drop(to);
+ self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))?;
+ read_capped(from, MAX_BYTES, IDLE_WAIT)
}
}
- impl TextClipboard {
- /// None when `window` isn't a Wayland window or the read worker can't start.
- #[allow(unsafe_code)]
+ pub struct DataClipboard {
+ reads: Reads,
+ objects: Arc>,
+ manager: WlDataDeviceManager,
+ conn: Connection,
+ qh: QueueHandle,
+ /// Tells the protocol worker to stop.
+ stop: Arc,
+ /// Held as long as the connection, which is the window's.
+ _window: Arc,
+ }
+
+ impl DataClipboard {
+ /// None when `window` isn't a Wayland window, the compositor has no data-device manager or
+ /// seat, or a worker can't start.
pub fn new(window: Arc) -> Option {
- use winit::raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle};
- let RawDisplayHandle::Wayland(d) = window.display_handle().ok()?.as_raw() else { return None };
- let display = d.display.as_ptr();
- // SAFETY: the display is winit's open `wl_display`, which outlives `window`; each
- // clipboard is held beside a clone of `window` and dropped before it. smithay-clipboard
- // makes its own event queue on the display and doesn't close it.
- let (cb, reader) = unsafe { (smithay_clipboard::Clipboard::new(display), smithay_clipboard::Clipboard::new(display)) };
- let loader = Loader { cb: reader, _window: window.clone() };
- // `loader.load()`, not `loader.cb.load()`: a closure moves only the fields it names,
- // and the worker must hold the window as long as its clipboard.
+ let conn = connection(&window)?;
+ let (globals, mut queue) = registry_queue_init::(&conn).ok()?;
+ let qh = queue.handle();
+ let manager: WlDataDeviceManager = globals.bind(&qh, 1..=3, ()).ok()?;
+ let seat: WlSeat = globals.bind(&qh, 1..=5, ()).ok()?;
+ let (objects, seen) = (Arc::>::default(), Arc::>::default());
+ lock(&objects).device = Some(manager.get_data_device(&seat, &qh, ()));
+ let mut state = State { objects: objects.clone(), seen: seen.clone(), sends: Sends::default() };
+ // The seat's keyboard and pointer, and the clipboard's offer when the window has focus.
+ queue.roundtrip(&mut state).ok()?;
+ let receiver = Receiver { conn: conn.clone(), objects: objects.clone(), _window: window.clone() };
// Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the
// app copied on when the last one goes.
- let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |()| loader.load())?;
- Some(Self { cb, reads: TextReads::new(loads), _window: window })
+ let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |wire| receiver.receive(wire))?;
+ let stop = Arc::new(AtomicBool::new(false));
+ let (stopped, held) = (stop.clone(), window.clone());
+ let work = move || {
+ while !stopped.load(Ordering::SeqCst) && queue.blocking_dispatch(&mut state).is_ok() {}
+ state.close(&seat);
+ let _ = queue.flush();
+ drop(held);
+ };
+ std::thread::Builder::new().name("wayland-clipboard".into()).spawn(work).ok()?;
+ Some(Self { reads: Reads::new(loads, seen), objects, manager, conn, qh, stop, _window: window })
}
- pub fn get_text(&mut self) -> Result {
- self.reads.get(LOAD_WAIT)
+ /// Gives the clipboard to a Copy of `flavours` ([`copy_types`]); none empties it. Err when
+ /// the seat has no data device or the window has had no input to take the clipboard with.
+ pub fn copy(&mut self, flavours: &[Flavour]) -> Result<(), String> {
+ let offered = copy_types(flavours);
+ let mut o = lock(&self.objects);
+ let device = o.device.clone().ok_or("the seat has no clipboard")?;
+ let serial = o.serial.ok_or("the window has had no key press or click to copy with")?;
+ let types: Vec<&'static str> = offered.iter().map(|(t, _)| *t).collect();
+ let source = (!offered.is_empty()).then(|| {
+ let source = self.manager.create_data_source(&self.qh, SourceData(offered));
+ for t in &types {
+ source.offer(t.to_string());
+ }
+ source
+ });
+ device.set_selection(source.as_ref(), serial);
+ if let Some(old) = std::mem::replace(&mut o.source, source) {
+ old.destroy();
+ }
+ lock(&self.reads.seen).copy(types);
+ drop(o);
+ self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))
}
- pub fn set_text(&self, text: &str) {
- self.cb.store(text);
+ pub fn text(&mut self) -> Result {
+ self.reads.text(LOAD_WAIT)
+ }
+
+ /// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for `wait` at
+ /// most.
+ pub fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option {
+ self.reads.read(mimes, wait)
+ }
+
+ pub fn has(&self, mimes: &[&'static str]) -> bool {
+ self.reads.has(mimes)
+ }
+
+ pub fn holds_ours(&self) -> bool {
+ self.reads.holds_ours()
}
/// The read that got no answer in its wait, when a paste of one of `mimes` can take its
- /// answer ([`TextReads::unanswered`]).
+ /// answer ([`Reads::unanswered`]).
pub(super) fn unanswered(&mut self, mimes: &[&'static str]) -> Option {
self.reads.unanswered(mimes)
}
/// Drops the read that got no answer in its wait: a paste no longer takes its answer.
pub fn forget_unanswered(&mut self) {
- self.reads.unanswered = None;
+ self.reads.forget_unanswered();
+ }
+ }
+
+ impl Drop for DataClipboard {
+ /// Stops the protocol worker, which a sync request's answer wakes.
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::SeqCst);
+ let _ = self.conn.display().sync(&self.qh, ());
+ let _ = self.conn.flush();
+ }
+ }
+
+ /// A connection on `window`'s Wayland display.
+ #[allow(unsafe_code)]
+ fn connection(window: &winit::window::Window) -> Option {
+ use wayland_backend::sys::client::Backend;
+ use winit::raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle};
+ let RawDisplayHandle::Wayland(d) = window.display_handle().ok()?.as_raw() else { return None };
+ // SAFETY: the display is winit's open `wl_display`, which outlives `window`; every user of
+ // the connection holds a clone of `window`. A backend made from a foreign display does not
+ // close it when dropped.
+ let backend = unsafe { Backend::from_foreign_display(d.display.as_ptr().cast()) };
+ Some(Connection::from_backend(backend))
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ fn flavour_of(mime: &'static str, data: &[u8]) -> Flavour {
+ Flavour { mime, data: data.to_vec() }
+ }
+
+ fn offered(types: &[&str]) -> Vec {
+ types.iter().map(|t| t.to_string()).collect()
+ }
+
+ #[test]
+ fn a_copy_offers_its_svg_png_and_text_each_with_its_own_data() {
+ let flavours = [flavour_of(TEXT, b""), flavour_of(SVG, b""), flavour_of(super::super::PDF, b"%PDF"), flavour_of(PNG, b"png")];
+ let types: Vec<(&str, Vec)> = copy_types(&flavours).into_iter().map(|(t, d)| (t, d.to_vec())).collect();
+ assert_eq!(
+ types,
+ [
+ ("text/plain;charset=utf-8", b"".to_vec()),
+ ("UTF8_STRING", b"".to_vec()),
+ ("text/plain", b"".to_vec()),
+ (SVG, b"".to_vec()),
+ (PNG, b"png".to_vec()),
+ ]
+ );
+ // With Include SVG Code off the engine makes no SVG flavour, and none is offered; a
+ // flavour with no data is not offered either.
+ let types: Vec<&str> = copy_types(&[flavour_of(PNG, b"png"), flavour_of(TEXT, b"")]).into_iter().map(|(t, _)| t).collect();
+ assert_eq!(types, [PNG]);
+ assert!(copy_types(&[]).is_empty());
+ }
+
+ #[test]
+ fn a_read_asks_for_the_offers_own_type() {
+ let all = offered(&["text/plain", "TEXT", "UTF8_STRING", "Image/PNG", "image/svg+xml", "application/pdf"]);
+ assert_eq!(wire_type(TEXT, &all), Some("UTF8_STRING"));
+ assert_eq!(wire_type(TEXT, &offered(&["text/plain", "text/plain;charset=UTF-8"])), Some("text/plain;charset=UTF-8"));
+ assert_eq!(wire_type(BITMAP, &all), Some("Image/PNG"));
+ assert_eq!(wire_type(SVG, &all), Some("image/svg+xml"));
+ // PDF, EPS and metafiles are not read here, nor types no reader knows.
+ assert_eq!(wire_type(super::super::PDF, &all), None);
+ assert_eq!(wire_type(TEXT, &offered(&["text/html", "image/jpeg"])), None);
+ assert_eq!(wire_type(SVG, &[]), None);
+ }
+
+ /// What a paste of `mimes` takes from a clipboard holding `data` by type, and the types read.
+ fn pasted(data: &[(&str, &[u8])], mimes: &[&'static str]) -> (Option, Vec) {
+ let types: Vec = data.iter().map(|(t, _)| t.to_string()).collect();
+ let mut read = vec![];
+ let f = pick(&types, mimes, |wire| {
+ read.push(wire.to_string());
+ data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec())
+ });
+ (f, read)
+ }
+
+ #[test]
+ fn a_paste_takes_svg_then_text_then_png() {
+ use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
+ let svg: (&str, &[u8]) = (SVG, b"