diff --git a/Cargo.lock b/Cargo.lock index 4a2423c33..d18855a94 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1056,12 +1056,41 @@ dependencies = [ "rustversion", ] +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + [[package]] name = "cookie-factory" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -2826,6 +2855,22 @@ dependencies = [ "zbus", ] +[[package]] +name = "figcraft-agent" +version = "0.19.0" +dependencies = [ + "base64 0.22.1", + "figcraft-color", + "figcraft-engine", + "figcraft-mcp", + "getrandom 0.4.3", + "log", + "proptest", + "serde", + "serde_json", + "ureq", +] + [[package]] name = "figcraft-cli" version = "0.19.0" @@ -3155,6 +3200,7 @@ dependencies = [ "craft-window", "egui", "egui_extras", + "figcraft-agent", "figcraft-color", "figcraft-doc", "figcraft-engine", @@ -7484,12 +7530,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" dependencies = [ "base64 0.23.1", + "cookie_store", "flate2", "log", "percent-encoding", "rustls", "rustls-pki-types", "rustls-platform-verifier", + "serde", + "serde_json", "ureq-proto", "utf8-zero", "webpki-roots", diff --git a/Cargo.toml b/Cargo.toml index 9bee84b02..30526c430 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ figcraft-ui-egui = { path = "crates/ui-egui" } figcraft-mcp = { path = "crates/mcp" } figcraft-collab-net = { path = "crates/collab-net" } figcraft-plugin = { path = "crates/plugin" } +figcraft-agent = { path = "crates/agent" } # Keep every craft-libs crate on one rev. # Which paths stored in a document may be followed (craft-libs). @@ -151,6 +152,10 @@ crc32fast = "1" wasmi = { version = "2", default-features = false, features = ["std", "stable", "validate", "portable-dispatch"] } wat = "1.261" +# The agent's HTTP client: blocking, rustls (the TLS provider collab-net already uses), pure Rust +# and forbidden from `unsafe`. Already in the lock through craft-update. +ureq = { version = "3.5", features = ["json"] } + # ui egui = "0.37" egui_extras = { version = "0.37", default-features = false } diff --git a/ROADMAP.md b/ROADMAP.md index 21097e14c..b417fce13 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-12-01 · **Change:** minor (M1: saved files refresh across desktop app instances, with bounded retries and conflicting saves refused (#1388, #1392); macOS DMGs are built with `hdiutil create -fs HFS+` and the app is verified in the finished image and an installation copy (#387); variables export and import as DTCG design tokens (#1687); Uno C# Markup code generation for layers, with auto layout and vectors as paths; M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; M9: clients accept complete legacy welcomes without a reconnect secret and re-authenticate on reconnect (#2365); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below; CLI scales reject repeated x suffixes; CLI help and docs name the first non-divider page as the default for export and render; invalid browser-page server endpoints are ignored before they replace the sharing default; the browser crate docs no longer repeat an obsolete same-computer-only live-session restriction; document HTTP(S) links without a host are refused before opening; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-12-01 · **Change:** minor (M1: saved files refresh across desktop app instances, with bounded retries and conflicting saves refused (#1388, #1392); keyframe animation: the Motion timeline, inspector and easing panel with 10 `motion.*` commands; macOS DMGs are built with `hdiutil create -fs HFS+` and the app is verified in the finished image and an installation copy (#387); variables export and import as DTCG design tokens (#1687); Uno C# Markup code generation for layers, with auto layout and vectors as paths; M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; M9: clients accept complete legacy welcomes without a reconnect secret and re-authenticate on reconnect (#2365); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below; CLI scales reject repeated x suffixes; CLI help and docs name the first non-divider page as the default for export and render; invalid browser-page server endpoints are ignored before they replace the sharing default; the browser crate docs no longer repeat an obsolete same-computer-only live-session restriction; document HTTP(S) links without a host are refused before opening; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -138,6 +138,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). - **2026-12-01** · Saving a file open in two desktop app instances (M1, #1388): a filesystem watcher notices saved changes without repainting stable files, and `file.refresh` reloads clean native tabs, keeping their identity and view. Local edits, gestures, text and version previews, live sessions and open branch tabs are kept; conflicting saves are refused, including an explicit Save path or Save as to the same file. Path aliases reuse the open tab, and Save as cannot replace another open tab's file. Unsaved edits between independent processes still need a live session. Numbers unchanged. +- **2026-12-01** · Motion: keyframe animation (the Motion panel) lands — the timeline, the inspector and the easing panel all drive the engine commands (`motion.keyframe`, `motion.keyframeMove`, `motion.keyframeDelete`, `motion.keyframeEase`, `motion.clip`, `motion.clipUpdate`, `motion.clipDelete`, `motion.track`, `motion.replace`, `motion.timeline`), so a motion edit is one undo step and a read-only document refuses it; Animation is an entry beside Prototype in the mode switcher and opens the Motion timeline, and the preview renders the document at the playhead without ever swapping it into the document. The command set is registered and driven by the timeline, inspector and easing panels, and is exercised by the engine and UI unit tests; the engine command count rises by 10. - **2026-11-07** · M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. - **2026-11-05** · M2, #1823: Suggest auto layout is its own command. `layout.suggest` used to run `layout.add` and made one row of everything. It now splits a frame's layers into rows or columns by the gaps between them, wraps each band of several layers in a hugging frame without fill and repeats inside it, so the design gets as many auto layout frames as it needs and keeps its placement where the gaps are even (the frame keeps its size). Uneven gaps, bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes are reported as `warnings`, and instances and layers inside them are refused. `layout.add` is unchanged. Tests in `layout_suggest_tests.rs`. Numbers unchanged. - **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the selected local variables as one undo step (`command.batch`); inherited variables can be selected but are left out, since they change in their own collection, and the bulk menu needs two or more local variables selected (otherwise the row shows its own menu). Rename and value edits stay single-row. diff --git a/apps/figcraft/src/services.rs b/apps/figcraft/src/services.rs index e23294567..4d3d70b73 100644 --- a/apps/figcraft/src/services.rs +++ b/apps/figcraft/src/services.rs @@ -493,6 +493,10 @@ pub(crate) fn remembering(last: Arc>>, pick: DialogFuture, } impl Services for Desktop { + fn agent_config_path(&self) -> Option { + crate::services::config_dir().map(|d| d.join("agents.json")) + } + fn pick_open(&mut self, title: &str, exts: &[&str]) -> DialogFuture { let pick = picked(self.dialog_in_last_folder(title).add_filter("Supported files", exts).pick_file()); remembering(self.last_folder.clone(), pick, false) diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml new file mode 100644 index 000000000..eb23823a2 --- /dev/null +++ b/crates/agent/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "figcraft-agent" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "FigCraft's in-app agent: provider adapters, the tool-call loop and the bridge to the open window" + +[lints] +workspace = true + +[dependencies] +figcraft-mcp = { workspace = true } +figcraft-color = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +base64 = { workspace = true } +# The MCP endpoint's bearer token (the OS random source collab-net's session secrets use). +getrandom = "0.4" +log = { workspace = true } +# Blocking HTTP with rustls (the same TLS provider collab-net uses), no async runtime. +ureq = { workspace = true } + +[dev-dependencies] +figcraft-engine = { workspace = true } +proptest = { workspace = true } diff --git a/crates/agent/src/anthropic.rs b/crates/agent/src/anthropic.rs new file mode 100644 index 000000000..20cd67601 --- /dev/null +++ b/crates/agent/src/anthropic.rs @@ -0,0 +1,295 @@ +//! The Anthropic Messages dialect. + +use std::collections::BTreeMap; +use std::sync::atomic::AtomicBool; + +use serde_json::{Value, json}; + +use crate::config::Provider; +use crate::http::{Http, read_error}; +use crate::neutral::{Block, Message, Role}; +use crate::{Invocation, Step}; + +const ANTHROPIC_VERSION: &str = "2023-06-01"; + +pub fn payload(provider: &Provider, system: &str, messages: &[Message], tools: &[Value]) -> Value { + let mut body = json!({ + "model": provider.model, + "max_tokens": provider.max_tokens.max(1), + "system": system, + "messages": wire_messages(messages), + "stream": true, + }); + let tools = crate::neutral::anthropic_tools(tools); + if !tools.is_empty() { + body["tools"] = json!(tools); + } + body +} + +fn wire_messages(messages: &[Message]) -> Vec { + let mut out: Vec = Vec::new(); + for m in messages { + let role = match m.role { + Role::User => "user", + Role::Assistant => "assistant", + }; + let mut content = Vec::new(); + for b in &m.blocks { + match b { + Block::Text(t) => content.push(json!({"type": "text", "text": t})), + Block::Image(i) => content.push(json!({ + "type": "image", + "source": {"type": "base64", "media_type": i.mime, "data": i.data}, + })), + Block::ToolCall { id, name, args } => content.push(json!({ + "type": "tool_use", + "id": id, + "name": name, + "input": args, + })), + Block::ToolResult { id, ok, text, images, .. } => { + let mut blocks = vec![json!({"type": "text", "text": text})]; + for i in images { + blocks.push(json!({ + "type": "image", + "source": {"type": "base64", "media_type": i.mime, "data": i.data}, + })); + } + content.push(json!({ + "type": "tool_result", + "tool_use_id": id, + "content": blocks, + "is_error": !ok, + })); + } + } + } + if content.is_empty() { + continue; + } + // Anthropic wants alternating roles; two user messages in a row (text, then tool results) + // are merged into one. + if let Some(last) = out.last_mut() + && last["role"].as_str() == Some(role) + && let Some(parts) = last["content"].as_array_mut() + { + parts.extend(content); + continue; + } + out.push(json!({"role": role, "content": content})); + } + out +} + +fn headers(provider: &Provider, session: &str) -> Vec<(&'static str, String)> { + let mut h = vec![ + ("x-api-key", provider.api_key.trim().to_string()), + ("anthropic-version", ANTHROPIC_VERSION.to_string()), + ("accept", "text/event-stream".to_string()), + ]; + if provider.base_url.contains("opencode.ai") { + h.push(("x-opencode-session", session.to_string())); + } + h +} + +pub fn stream( + http: &Http, + provider: &Provider, + system: &str, + messages: &[Message], + tools: &[Value], + session: &str, + on_text: &mut dyn FnMut(&str), + cancel: &AtomicBool, +) -> Result { + let reply = http.post(&provider.endpoint(), &headers(provider, session), &payload(provider, system, messages, tools))?; + if reply.status >= 400 { + return Err(read_error(reply.status, reply.body)); + } + let events = crate::sse::spawn_events(reply.body); + let mut step = Step::default(); + let mut pending: BTreeMap = BTreeMap::new(); + // `message_stop` ends a whole answer; a stream that ends before it was cut off. + let mut stopped = false; + while let Some(event) = crate::sse::next(&events, cancel)? { + if event.data.trim().is_empty() { + continue; + } + let v: Value = match serde_json::from_str(&event.data) { + Ok(v) => v, + Err(_) => continue, + }; + match event.name.as_str() { + "message_stop" => { + stopped = true; + break; + } + "message_start" => { + if let Some(u) = v.get("message").and_then(|m| m.get("usage")) { + step.usage.input = u.get("input_tokens").and_then(Value::as_u64).unwrap_or(step.usage.input); + step.usage.output = u.get("output_tokens").and_then(Value::as_u64).unwrap_or(step.usage.output); + } + } + "content_block_start" => { + let index = v.get("index").and_then(Value::as_u64).unwrap_or(0); + let block = &v["content_block"]; + match block.get("type").and_then(Value::as_str) { + Some("tool_use") => { + let id = block.get("id").and_then(Value::as_str).unwrap_or("").to_string(); + let name = block.get("name").and_then(Value::as_str).unwrap_or("").to_string(); + // The start carries `input: {}` as a placeholder before the streamed + // fragments; it is the input only when no fragment follows. + let initial = block.get("input").filter(|i| !i.is_null()).map(|i| i.to_string()).unwrap_or_default(); + pending.insert(index, Pending { id, name, initial, streamed: String::new() }); + } + Some("text") => { + if let Some(t) = block.get("text").and_then(Value::as_str) + && !t.is_empty() + { + step.text.push_str(t); + on_text(t); + } + } + _ => {} + } + } + "content_block_delta" => { + let index = v.get("index").and_then(Value::as_u64).unwrap_or(0); + let delta = &v["delta"]; + match delta.get("type").and_then(Value::as_str) { + Some("text_delta") => { + if let Some(t) = delta.get("text").and_then(Value::as_str) { + step.text.push_str(t); + on_text(t); + } + } + Some("input_json_delta") => { + if let Some(partial) = delta.get("partial_json").and_then(Value::as_str) + && let Some(entry) = pending.get_mut(&index) + { + entry.streamed.push_str(partial); + } + } + _ => {} + } + } + "message_delta" => { + if let Some(reason) = v.get("delta").and_then(|d| d.get("stop_reason")).and_then(Value::as_str) { + step.stop = reason.to_string(); + } + if let Some(u) = v.get("usage") { + step.usage.output = u.get("output_tokens").and_then(Value::as_u64).unwrap_or(step.usage.output); + } + } + "error" => { + let msg = + v.get("error").and_then(|e| e.get("message")).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| event.data.clone()); + return Err(msg); + } + _ => {} + } + } + if !stopped { + return Err(crate::openai::INTERRUPTED.to_string()); + } + for (i, p) in pending { + if let Some(call) = p.into_call(i) { + step.calls.push(call); + } + } + Ok(step) +} + +/// A tool call being built: the input its start gave, and the fragments streamed after it. +struct Pending { + id: String, + name: String, + initial: String, + streamed: String, +} + +impl Pending { + fn into_call(self, index: u64) -> Option { + if self.name.is_empty() { + return None; + } + let id = if self.id.is_empty() { format!("toolu_{index}") } else { self.id }; + let raw = if self.streamed.trim().is_empty() { self.initial } else { self.streamed }; + let args = if raw.trim().is_empty() { json!({}) } else { serde_json::from_str(&raw).unwrap_or(Value::Null) }; + Some(Invocation { id, name: self.name, args, args_raw: raw }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::ApiKind; + + fn provider() -> Provider { + let mut p = Provider::new("Anthropic", ApiKind::AnthropicMessages, "https://api.anthropic.com/v1"); + p.model = "claude-sonnet-5".into(); + p.api_key = "sk-ant".into(); + p.max_tokens = 4096; + p + } + + #[test] + fn the_system_prompt_is_top_level_and_max_tokens_is_sent() { + let messages = vec![Message::user_text("hi")]; + let body = payload(&provider(), "you design", &messages, &[]); + assert_eq!(body["system"], "you design"); + assert_eq!(body["max_tokens"], 4096); + assert_eq!(body["messages"][0]["content"][0]["text"], "hi"); + } + + #[test] + fn tool_results_are_user_blocks_with_images_inside() { + let messages = vec![Message { + role: Role::User, + blocks: vec![Block::ToolResult { + id: "toolu_1".into(), + name: "screenshot".into(), + ok: true, + text: "the page".into(), + images: vec![crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() }], + }], + }]; + let body = payload(&provider(), "s", &messages, &[]); + let block = &body["messages"][0]["content"][0]; + assert_eq!(block["type"], "tool_result"); + assert_eq!(block["content"][1]["type"], "image"); + assert_eq!(block["content"][1]["source"]["data"], "AAAA"); + } + + #[test] + fn consecutive_user_messages_are_merged() { + let messages = vec![Message::user_text("look"), Message::user_text("again")]; + let body = payload(&provider(), "s", &messages, &[]); + let wire = body["messages"].as_array().cloned().unwrap_or_default(); + assert_eq!(wire.len(), 1, "Anthropic requires alternating roles"); + assert_eq!(wire[0]["content"].as_array().map(Vec::len), Some(2)); + } + + fn call(initial: &str, fragments: &[&str]) -> Option { + let streamed = fragments.concat(); + Pending { id: "toolu_1".into(), name: "load_skill".into(), initial: initial.into(), streamed }.into_call(0) + } + + #[test] + fn streamed_arguments_replace_the_placeholder_input() { + let c = call("{}", &["{\"name\":", "\"Design review\"}"]).expect("a call"); + assert_eq!(c.args["name"], "Design review"); + let none = call("{}", &[]).expect("a call"); + assert_eq!(none.args, json!({}), "no fragments: the start's input is the input"); + } + + #[test] + fn headers_use_x_api_key_not_bearer() { + let h = headers(&provider(), "s"); + assert!(h.iter().any(|(k, v)| *k == "x-api-key" && v == "sk-ant")); + assert!(h.iter().any(|(k, _)| *k == "anthropic-version")); + assert!(!h.iter().any(|(k, _)| *k == "authorization")); + } +} diff --git a/crates/agent/src/bridge.rs b/crates/agent/src/bridge.rs new file mode 100644 index 000000000..13bb6d3dc --- /dev/null +++ b/crates/agent/src/bridge.rs @@ -0,0 +1,104 @@ +//! The bridge to the open window. +//! +//! The agent runs on its own thread and must not touch the session (it lives on the UI thread). +//! Every tool call becomes a [`Call`] the UI drains into its control queue, exactly like a request +//! from `figcraft-cli mcp --attach`; the reply comes back on the call's channel. Implementing +//! [`figcraft_mcp::Backend`] over that channel is what lets the agent reuse the MCP tool set +//! unchanged, with the same behaviour an external MCP client gets. + +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::Duration; + +use serde_json::{Value, json}; + +/// One control request from the agent thread to the UI thread. +pub struct Call { + pub method: String, + pub params: Value, + pub reply: Sender>, +} + +/// The UI side: the calls the agent thread is waiting for. +pub struct Bridge { + pub calls: Receiver, +} + +/// The agent side: sends calls and waits for their answers. +#[derive(Clone)] +pub struct Remote { + tx: Sender, + /// The name every command runs as, so the app shows the agent's avatar and signs its comments. + agent: String, + /// Wakes the window, which is idle between frames while the agent waits for an answer. + wake: Arc, +} + +/// A fresh pair: the UI keeps the bridge, the agent thread keeps the remote. +pub fn pair(agent: impl Into, wake: Arc) -> (Bridge, Remote) { + let (tx, rx) = channel(); + (Bridge { calls: rx }, Remote { tx, agent: agent.into(), wake }) +} + +impl Remote { + /// How long one tool call waits for the UI before giving up. + const WAIT: Duration = Duration::from_secs(600); + + /// Send one control method and wait for its answer. + pub fn request(&self, method: &str, params: Value) -> Result { + self.send(method, params) + } + + fn send(&self, method: &str, mut params: Value) -> Result { + if method == "engine.execute" { + // The app shows an AI agent's presence from this, and signs its comments. + params["agent"] = json!(self.agent); + } + let (reply, answer) = channel(); + self.tx.send(Call { method: method.to_string(), params, reply }).map_err(|_| "the window closed".to_string())?; + (self.wake)(); + match answer.recv_timeout(Self::WAIT) { + Ok(r) => r, + Err(_) => Err(format!("the window did not answer `{method}` in time")), + } + } +} + +impl figcraft_mcp::Backend for Remote { + fn call(&mut self, method: &str, params: Value) -> Result { + self.send(method, params) + } + + fn has_ui(&self) -> bool { + true + } + + fn describe(&self) -> String { + "the open window".to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_call_carries_the_agent_name_and_its_reply() { + let (bridge, mut remote) = pair("FigCraft Agent", Arc::new(|| {})); + let t = std::thread::spawn(move || figcraft_mcp::Backend::call(&mut remote, "engine.execute", json!({"command": "frame.create"}))); + let call = bridge.calls.recv().expect("a call"); + assert_eq!(call.method, "engine.execute"); + assert_eq!(call.params["agent"], "FigCraft Agent"); + call.reply.send(Ok(json!({"id": 7}))).expect("reply"); + assert_eq!(t.join().expect("thread"), Ok(json!({"id": 7}))); + } + + #[test] + fn a_closed_window_fails_the_call_instead_of_hanging() { + let (bridge, remote) = pair("Agent", Arc::new(|| {})); + drop(bridge); + let mut remote = remote; + let err = figcraft_mcp::Backend::call(&mut remote, "document.inspect", json!({})).unwrap_err(); + assert!(err.contains("window closed")); + } +} diff --git a/crates/agent/src/brief.rs b/crates/agent/src/brief.rs new file mode 100644 index 000000000..c3215e098 --- /dev/null +++ b/crates/agent/src/brief.rs @@ -0,0 +1,898 @@ +//! The file's design system and the page it lives on, `00 · Design System`: the choices behind +//! it (product, colour, type, shape, icons, voice) become variables, styles, review settings and +//! a guidelines text on that page, in one step the agent takes with the `design_system` tool. +//! +//! The foundations follow what public design-system guides cover (Material 3, IBM Carbon, Apple's +//! Human Interface Guidelines, Atlassian, Shopify Polaris, and the W3C Design Tokens format +//! 2025.10): colour roles with light and dark modes, a type scale, a 4 or 8 spacing step, radius, +//! elevation, an icon set and style, voice, and contrast targets. The idea of starting a file from +//! a design library with variables and themes comes from pen.dev's public documentation +//! (docs.pencil.dev: design systems, variables, AI agents). Ideas only; nothing here is copied. +//! +//! [`Brief::steps`] builds the commands for the engine's `command.batch`, so making (or updating) +//! the system is one undo step and works the same from the panel, the CLI or MCP. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_color::{Color, Oklch}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +/// The collections and their modes the steps make. +pub const PRIMITIVES: &str = "Primitives"; +pub const THEME: &str = "Theme"; +pub const SIZES: &str = "Sizes"; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Platform { + Mobile, + #[default] + Web, + Both, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Neutral { + Cool, + #[default] + Neutral, + Warm, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Modes { + Light, + Dark, + #[default] + Both, +} + +impl Modes { + pub fn names(self) -> &'static [&'static str] { + match self { + Modes::Light => &["Light"], + Modes::Dark => &["Dark"], + Modes::Both => &["Light", "Dark"], + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TypeScale { + /// 14 px body, sizes 1.2 apart. + Compact, + /// 16 px body, 1.25 apart. + #[default] + Default, + /// 18 px body, 1.25 apart. + Large, +} + +impl TypeScale { + fn base_ratio(self) -> (f64, f64) { + match self { + TypeScale::Compact => (14.0, 1.2), + TypeScale::Default => (16.0, 1.25), + TypeScale::Large => (18.0, 1.25), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Radius { + Sharp, + #[default] + Soft, + Round, + Pill, +} + +impl Radius { + /// Small, medium, large. + fn values(self) -> [f64; 3] { + match self { + Radius::Sharp => [2.0, 4.0, 6.0], + Radius::Soft => [4.0, 8.0, 12.0], + Radius::Round => [8.0, 16.0, 24.0], + Radius::Pill => [12.0, 20.0, 28.0], + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Elevation { + Flat, + #[default] + Subtle, + Raised, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum IconStyle { + #[default] + Outline, + Filled, + Duotone, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Contrast { + #[default] + Aa, + Aaa, +} + +/// Open-source icon sets a brief can name: (name, licence, what it looks like). Nothing is +/// downloaded; the agent draws icons in the set's manner, or the person imports them. +pub const ICON_SETS: &[(&str, &str, &str)] = &[ + ("Lucide", "ISC", "Clean outline icons on a 24 grid, 2 px strokes, round caps; a wide everyday set."), + ("Heroicons", "MIT", "Outline (1.5 px) and solid versions at 24, with smaller solid sizes; plain and friendly."), + ("Tabler Icons", "MIT", "A very large outline set on a 24 grid with 2 px strokes; consistent and neutral."), + ("Phosphor", "MIT", "One set in six weights from thin to fill plus duotone; soft, rounded shapes."), + ("Feather", "MIT", "A small, light outline set on a 24 grid with 2 px strokes; minimal."), + ("Material Symbols", "Apache-2.0", "Google's set with fill, weight and size variations; geometric and familiar on Android."), +]; + +/// What the file's design system should be. Every field has a default, so an older or partial +/// brief reads back. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Brief { + pub version: u32, + // The product. + pub product: String, + pub description: String, + pub audience: String, + pub platform: Platform, + /// The language the copy is written in. + pub language: String, + // Colour (hex). + pub primary: String, + pub secondary: String, + pub accent: String, + pub neutral: Neutral, + pub success: String, + pub warning: String, + pub danger: String, + pub info: String, + pub modes: Modes, + // Type. + pub heading_font: String, + pub body_font: String, + pub mono_font: String, + pub scale: TypeScale, + // Shape. + /// 4 or 8. + pub spacing: u8, + pub radius: Radius, + pub elevation: Elevation, + pub border: f64, + // Icons. + /// A name from [`ICON_SETS`], or anything the person typed. + pub icon_set: String, + pub icon_style: IconStyle, + pub icon_stroke: f64, + pub icon_size: u8, + // Voice and rules. + pub tone: String, + pub imagery: String, + pub contrast: Contrast, + pub notes: String, +} + +impl Default for Brief { + fn default() -> Self { + Self { + version: 1, + product: String::new(), + description: String::new(), + audience: String::new(), + platform: Platform::Web, + language: String::new(), + primary: "#2563EB".into(), + secondary: String::new(), + accent: String::new(), + neutral: Neutral::Neutral, + success: "#16A34A".into(), + warning: "#D97706".into(), + danger: "#DC2626".into(), + info: "#0284C7".into(), + modes: Modes::Both, + heading_font: "Inter".into(), + body_font: "Inter".into(), + mono_font: "JetBrains Mono".into(), + scale: TypeScale::Default, + spacing: 4, + radius: Radius::Soft, + elevation: Elevation::Subtle, + border: 1.0, + icon_set: "Lucide".into(), + icon_style: IconStyle::Outline, + icon_stroke: 2.0, + icon_size: 24, + tone: String::new(), + imagery: String::new(), + contrast: Contrast::Aa, + notes: String::new(), + } + } +} + +/// The ramp steps every colour gets. +pub const STEPS: [u16; 10] = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]; +/// OKLCH lightness per step, light to dark. +const RAMP_L: [f32; 10] = [0.97, 0.93, 0.87, 0.79, 0.70, 0.61, 0.52, 0.44, 0.36, 0.28]; +/// Share of the colour's own chroma per step (pale and deep ends are calmer). +const RAMP_C: [f32; 10] = [0.15, 0.3, 0.5, 0.75, 0.92, 1.0, 0.95, 0.85, 0.72, 0.6]; + +/// Ten shades of `hex` from 50 (palest) to 900 (deepest), keeping its hue; `None` if it is not a +/// colour. +pub fn ramp(hex: &str) -> Option> { + let base = Oklch::from_color(Color::from_hex(hex)?); + Some(ramp_of(base.c, base.h)) +} + +fn ramp_of(chroma: f32, hue: f32) -> Vec { + (0..STEPS.len()).map(|i| Oklch { l: RAMP_L[i], c: chroma * RAMP_C[i], h: hue }.to_color().to_css_hex()).collect() +} + +/// A grey ramp, tinted cool (blue), warm (sand) or not at all. +fn neutral_ramp(tone: Neutral) -> Vec { + match tone { + Neutral::Cool => ramp_of(0.02, 255.0), + Neutral::Neutral => ramp_of(0.0, 0.0), + Neutral::Warm => ramp_of(0.018, 70.0), + } +} + +/// `hex` made lighter, for the dark mode of a status colour. +fn lighter(hex: &str) -> String { + match Color::from_hex(hex) { + Some(c) => { + let o = Oklch::from_color(c); + Oklch { l: (o.l + 0.12).min(0.85), ..o }.to_color().to_css_hex() + } + None => hex.to_string(), + } +} + +/// What a file already has, so running the steps again updates rather than duplicates. +#[derive(Clone, Debug, Default)] +pub struct Existing { + /// Collection name → its mode names. + pub collections: BTreeMap>, + /// (collection name, variable name) → the variable's id, so an update names that one variable + /// even when another collection has one of the same name. + pub variables: BTreeMap<(String, String), String>, + pub styles: BTreeSet, +} + +impl Existing { + /// Read `variable.list` and `style.list` results. + pub fn from_lists(variables: &Value, styles: &Value) -> Self { + let mut e = Existing::default(); + let mut by_id = BTreeMap::new(); + for c in variables.get("collections").and_then(Value::as_array).into_iter().flatten() { + let (Some(id), Some(name)) = (c.get("id").and_then(Value::as_str), c.get("name").and_then(Value::as_str)) else { continue }; + let modes = c + .get("modes") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|m| m.get("name").and_then(Value::as_str)) + .map(str::to_string); + e.collections.insert(name.to_string(), modes.collect()); + by_id.insert(id.to_string(), name.to_string()); + } + for v in variables.get("variables").and_then(Value::as_array).into_iter().flatten() { + let (Some(c), Some(name)) = (v.get("collection").and_then(Value::as_str), v.get("name").and_then(Value::as_str)) else { continue }; + if let Some(cname) = by_id.get(c) { + let id = v.get("id").and_then(Value::as_str).unwrap_or(name); + e.variables.insert((cname.clone(), name.to_string()), id.to_string()); + } + } + for s in styles.as_array().into_iter().flatten() { + if let Some(name) = s.get("name").and_then(Value::as_str) { + e.styles.insert(name.to_string()); + } + } + e + } +} + +/// A variable's value per mode: a colour, a number, or an alias to another variable. +#[derive(Clone, Debug)] +enum Val { + Lit(Value), + Alias(String), +} + +impl Val { + fn json(&self) -> Value { + match self { + Val::Lit(v) => v.clone(), + Val::Alias(name) => json!({"alias": name}), + } + } +} + +impl Brief { + /// Read a brief kept as page data; a damaged one gives the defaults back. + pub fn from_json(text: &str) -> Option { + serde_json::from_str(text).ok() + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + fn hex_or<'a>(value: &'a str, fallback: &'a str) -> &'a str { + if Color::from_hex(value).is_some() { value } else { fallback } + } + + /// The colour ramps of the Primitives collection: (group name, ten shades). + fn ramps(&self) -> Vec<(&'static str, Vec)> { + let mut out = vec![("Primary", ramp(Self::hex_or(&self.primary, "#2563EB")).unwrap_or_default())]; + for (name, hex) in [("Secondary", &self.secondary), ("Accent", &self.accent)] { + if let Some(r) = ramp(hex) { + out.push((name, r)); + } + } + out.push(("Neutral", neutral_ramp(self.neutral))); + out + } + + /// The Theme roles: (name, Light value, Dark value). + fn roles(&self) -> Vec<(String, Val, Val)> { + let a = |s: &str| Val::Alias(s.to_string()); + let lit = |s: &str| Val::Lit(json!(s)); + // Text on the primary colour: white or near-black, whichever reads better on Primary/600. + let primary = ramp(Self::hex_or(&self.primary, "#2563EB")).unwrap_or_default(); + let on_primary = primary + .get(6) + .and_then(|p| Color::from_hex(p)) + .map(|p| { + let (white, ink) = (Color::new(1.0, 1.0, 1.0, 1.0), Color::from_hex("#111111").unwrap_or(Color::new(0.07, 0.07, 0.07, 1.0))); + if p.contrast(white) >= p.contrast(ink) { "#FFFFFF" } else { "#111111" } + }) + .unwrap_or("#FFFFFF"); + let mut roles = vec![ + ("Background".to_string(), lit("#FFFFFF"), a("Neutral/900")), + ("Surface".into(), a("Neutral/50"), a("Neutral/800")), + ("Surface raised".into(), lit("#FFFFFF"), a("Neutral/700")), + ("Text".into(), a("Neutral/900"), a("Neutral/50")), + ("Text muted".into(), a("Neutral/600"), a("Neutral/300")), + ("Border".into(), a("Neutral/200"), a("Neutral/700")), + ("Primary".into(), a("Primary/600"), a("Primary/400")), + ("Primary hover".into(), a("Primary/700"), a("Primary/300")), + ("On primary".into(), lit(on_primary), a("Neutral/900")), + ("Focus".into(), a("Primary/500"), a("Primary/400")), + ]; + for (name, hex) in [("Secondary", &self.secondary), ("Accent", &self.accent)] { + if Color::from_hex(hex).is_some() { + roles.push((name.into(), a(&format!("{name}/600")), a(&format!("{name}/400")))); + } + } + for (name, hex, fallback) in [ + ("Success", &self.success, "#16A34A"), + ("Warning", &self.warning, "#D97706"), + ("Danger", &self.danger, "#DC2626"), + ("Info", &self.info, "#0284C7"), + ] { + let hex = Self::hex_or(hex, fallback); + roles.push((name.into(), lit(hex), Val::Lit(json!(lighter(hex))))); + } + roles + } + + /// The Sizes collection: (name, value). + fn sizes(&self) -> Vec<(String, f64)> { + let base = if self.spacing == 8 { 8.0 } else { 4.0 }; + let mut out: Vec<(String, f64)> = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 16.0] + .iter() + .map(|m| { + let v = base * m; + (format!("Space/{v}"), v) + }) + .collect(); + let [s, m, l] = self.radius.values(); + out.extend([("Radius/S".to_string(), s), ("Radius/M".into(), m), ("Radius/L".into(), l), ("Radius/Full".into(), 9999.0)]); + out.extend([ + ("Border/Default".to_string(), self.border.clamp(0.5, 4.0)), + ("Border/Focus".into(), 2.0), + ("Icon/Size".into(), f64::from(self.icon_size.clamp(12, 48))), + ("Icon/Stroke".into(), self.icon_stroke.clamp(0.5, 4.0)), + ]); + out + } + + /// Text styles: (name, size, weight, line height, family). + fn type_styles(&self) -> Vec<(&'static str, f64, u16, f64, String)> { + let (b, r) = self.scale.base_ratio(); + let size = |step: i32| (b * r.powi(step)).round(); + let font = |f: &str, fallback: &str| if f.trim().is_empty() { fallback.to_string() } else { f.trim().to_string() }; + let (head, body, mono) = (font(&self.heading_font, "Inter"), font(&self.body_font, "Inter"), font(&self.mono_font, "JetBrains Mono")); + let tight = |s: f64| (s * 1.2 / 2.0).round() * 2.0; + let loose = |s: f64| (s * 1.5 / 2.0).round() * 2.0; + let list: [(&str, i32, u16, bool, &str); 10] = [ + ("Display", 5, 700, true, "h"), + ("Heading 1", 4, 700, true, "h"), + ("Heading 2", 3, 600, true, "h"), + ("Heading 3", 2, 600, true, "h"), + ("Body large", 1, 400, false, "b"), + ("Body", 0, 400, false, "b"), + ("Body small", -1, 400, false, "b"), + ("Caption", -2, 400, false, "b"), + ("Label", -1, 500, false, "b"), + ("Code", -1, 400, false, "m"), + ]; + list.iter() + .map(|(name, step, weight, heading, fam)| { + let s = size(*step); + let family = match *fam { + "h" => head.clone(), + "m" => mono.clone(), + _ => body.clone(), + }; + (*name, s, *weight, if *heading { tight(s) } else { loose(s) }, family) + }) + .collect() + } + + /// Shadow styles: (name, y offset, blur, spread, opacity). + fn shadows(&self) -> [(&'static str, f64, f64, f64, f64); 3] { + let k = match self.elevation { + Elevation::Flat => 0.5, + Elevation::Subtle => 1.0, + Elevation::Raised => 1.6, + }; + [("Shadow/S", 1.0, 2.0, 0.0, 0.06 * k), ("Shadow/M", 4.0, 10.0, -2.0, 0.08 * k), ("Shadow/L", 12.0, 28.0, -6.0, 0.11 * k)] + } + + /// The file's design review settings (`design.configure`) from the brief: its spacing step as + /// the grid, its corners as the radii, its colours as the brand, and the contrast target. + pub fn review_settings(&self) -> Value { + let preset = match self.contrast { + Contrast::Aa => "recommended", + Contrast::Aaa => "accessibility", + }; + let brand: Vec = [&self.primary, &self.secondary, &self.accent] + .into_iter() + .filter_map(|h| Color::from_hex(h).map(|c| c.to_css_hex())) + .chain(ramp(Self::hex_or(&self.primary, "#2563EB")).unwrap_or_default().into_iter().skip(4).take(4)) + .collect(); + json!({ + "preset": preset, + "grid": if self.spacing == 8 { 8 } else { 4 }, + "radii": self.radius.values(), + "brand": brand, + }) + } + + /// The commands that make (or bring up to date) the file's variables and styles, for + /// `command.batch`: `[{command, params}]`. + pub fn steps(&self, existing: &Existing) -> Vec { + let mut out = Vec::new(); + // Primitives: one mode, the colour ramps. + let mut prim: Vec<(String, Vec)> = Vec::new(); + for (group, shades) in self.ramps() { + for (step, hex) in STEPS.iter().zip(shades) { + prim.push((format!("{group}/{step}"), vec![Val::Lit(json!(hex))])); + } + } + collection(&mut out, existing, PRIMITIVES, &["Default"], "color", prim); + // Theme: the roles, per mode. + let modes = self.modes.names(); + let theme = self + .roles() + .into_iter() + .map(|(name, light, dark)| { + let values = modes.iter().map(|m| if *m == "Dark" { dark.clone() } else { light.clone() }).collect(); + (name, values) + }) + .collect(); + collection(&mut out, existing, THEME, modes, "color", theme); + // Sizes. + let sizes = self.sizes().into_iter().map(|(n, v)| (n, vec![Val::Lit(json!(v))])).collect(); + collection(&mut out, existing, SIZES, &["Default"], "number", sizes); + // Text styles. + for (name, size, weight, line, family) in self.type_styles() { + let value = json!({"fontFamily": family, "fontSize": size, "fontWeight": weight, "lineHeight": line}); + out.push(if existing.styles.contains(name) { + json!({"command": "style.update", "params": {"style": name, "value": value}}) + } else { + json!({"command": "style.create", "params": {"type": "text", "name": name, "value": value}}) + }); + } + // FigCraft's design review checks against the same choices. + out.push(json!({"command": "design.configure", "params": self.review_settings()})); + // Shadows. + for (name, y, blur, spread, alpha) in self.shadows() { + let a = (alpha.clamp(0.0, 1.0) * 255.0).round() as u8; + let value = json!([{"type": "dropShadow", "color": format!("#0F172A{a:02X}"), "offset": [0.0, y], "radius": blur, "spread": spread}]); + out.push(if existing.styles.contains(name) { + json!({"command": "style.update", "params": {"style": name, "value": value}}) + } else { + json!({"command": "style.create", "params": {"type": "effect", "name": name, "value": value}}) + }); + } + out + } + + /// The design guidelines as written on the design system page. + pub fn guidelines(&self) -> String { + let mut lines = vec![GUIDELINES.to_string()]; + let opt = |label: &str, v: &str| if v.trim().is_empty() { None } else { Some(format!("{label}: {}", v.trim())) }; + lines.extend(opt("Product", &self.product)); + lines.extend(opt("What it does", &self.description)); + lines.extend(opt("For", &self.audience)); + lines.push(format!( + "Platform: {}", + match self.platform { + Platform::Mobile => "mobile app (390 x 844 frames)", + Platform::Web => "web (1440 wide desktop frames, plus 390 mobile when asked)", + Platform::Both => "mobile app and web", + } + )); + lines.extend(opt("Write the copy in", &self.language)); + lines.push(format!( + "Colour: primary {}{}{}; status colours success {}, warning {}, danger {}, info {}; modes {}. Use the Theme variables (Background, Surface, Text, Text muted, Border, Primary, On primary…) for every colour once they exist.", + self.primary, + if self.secondary.trim().is_empty() { String::new() } else { format!(", secondary {}", self.secondary.trim()) }, + if self.accent.trim().is_empty() { String::new() } else { format!(", accent {}", self.accent.trim()) }, + self.success, + self.warning, + self.danger, + self.info, + self.modes.names().join(" and "), + )); + let (base, ratio) = self.scale.base_ratio(); + lines.push(format!( + "Type: headings in {}, body in {}, code in {}; body {base} px, sizes {ratio} apart. Use the text styles (Display, Heading 1-3, Body, Body small, Caption, Label, Code).", + self.heading_font, self.body_font, self.mono_font + )); + lines.push(format!( + "Shape: spacing in steps of {} (Sizes/Space variables), corners {:?} (Radius variables), elevation {:?} (Shadow styles), borders {} px.", + if self.spacing == 8 { 8 } else { 4 }, + self.radius, + self.elevation, + self.border + )); + let set = ICON_SETS.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(self.icon_set.trim())); + lines.push(format!( + "Icons: {} ({:?}, {} px stroke, {} px){}. Draw each icon as vector paths in that set's manner on a {} grid, or use an icon the user imported; never emoji.", + if self.icon_set.trim().is_empty() { "a line icon set" } else { self.icon_set.trim() }, + self.icon_style, + self.icon_stroke, + self.icon_size, + set.map(|(_, _, d)| format!(": {d}")).unwrap_or_default(), + self.icon_size + )); + lines.extend(opt("Voice", &self.tone)); + lines.extend(opt("Imagery", &self.imagery)); + lines.push(match self.contrast { + Contrast::Aa => "Accessibility: WCAG AA (text 4.5:1, large text and controls 3:1), touch targets at least 44.".to_string(), + Contrast::Aaa => "Accessibility: WCAG AAA (text 7:1, large text 4.5:1), touch targets at least 44.".to_string(), + }); + lines.extend(opt("Also", &self.notes)); + lines.join("\n") + } +} + +/// Steps for one collection: create it (or add missing modes), then create or set each variable. +fn collection(out: &mut Vec, existing: &Existing, name: &str, modes: &[&str], kind: &str, vars: Vec<(String, Vec)>) { + match existing.collections.get(name) { + None => out.push(json!({"command": "variable.createCollection", "params": {"name": name, "modes": modes}})), + Some(have) => { + for m in modes { + if !have.iter().any(|h| h == m) { + out.push(json!({"command": "variable.addMode", "params": {"collection": name, "name": m}})); + } + } + } + } + for (var, values) in vars { + if let Some(id) = existing.variables.get(&(name.to_string(), var.clone())) { + for (m, v) in modes.iter().zip(&values) { + out.push(json!({"command": "variable.set", "params": {"variable": id, "mode": m, "value": v.json()}})); + } + } else { + let values: serde_json::Map = modes.iter().map(ToString::to_string).zip(values.iter().map(Val::json)).collect(); + out.push(json!({"command": "variable.create", "params": {"collection": name, "name": var, "type": kind, "values": values}})); + } + } +} + +/// The tool the model reads and makes the design system page with. +pub const TOOL_NAME: &str = "design_system"; + +/// The page every file's design system lives on, first in the file. +pub const PAGE: &str = "00 · Design System"; + +/// The text layer on that page holding the choices tokens can't hold (icons, voice, rules). +pub const GUIDELINES: &str = "Design guidelines"; + +/// The `design_system` tool, as the tool list has it. +pub fn tool_definition() -> Value { + json!({ + "name": TOOL_NAME, + "description": "The file's design system, which lives on the page '00 · Design System'. With no arguments: whether that page exists, its frames, its design guidelines and the variable collections. With `spec`: make or update it in one undo step: the page (first in the file), the variables (colour ramps, Theme roles with Light/Dark, Sizes), text and shadow styles, the review settings design.audit uses, and a 'Design guidelines' text on the page with the choices tokens can't hold. Spec fields (all optional): product, description, audience, platform (mobile|web|both), language, primary, secondary, accent (hex), neutral (cool|neutral|warm), success, warning, danger, info (hex), modes (light|dark|both), headingFont, bodyFont, monoFont, scale (compact|default|large), spacing (4|8), radius (sharp|soft|round|pill), elevation (flat|subtle|raised), border, iconSet (e.g. Lucide, Heroicons, Tabler Icons, Phosphor, Feather, Material Symbols), iconStyle (outline|filled|duotone), iconStroke, iconSize, tone, imagery, contrast (aa|aaa), notes.", + "inputSchema": { + "type": "object", + "properties": { + "spec": {"type": "object", "description": "Design system choices to make (others take defaults)"} + } + } + }) +} + +/// Run a command on the file the operation started in (`document`, from `doc.list`), so a tab the +/// person switches to meanwhile is never written to; a file closed meanwhile fails the call. +fn exec(b: &mut dyn figcraft_mcp::Backend, document: Option, cmd: &str, params: Value) -> Result { + let mut request = json!({"command": cmd, "params": params}); + if let Some(d) = document { + request["document"] = json!(d); + } + b.call("engine.execute", request) +} + +/// The id of the file in front, which the whole operation then works in. +fn front_document(b: &mut dyn figcraft_mcp::Backend) -> Option { + let list = exec(b, None, "doc.list", json!({})).ok()?; + list.as_array()?.iter().find(|d| d.get("active").and_then(Value::as_bool) == Some(true))?.get("id")?.as_u64() +} + +/// Whether a page name is the design system page (its number and words, however typed). +pub fn is_page(name: &str) -> bool { + let spaced: String = name.to_lowercase().chars().map(|c| if c.is_alphanumeric() { c } else { ' ' }).collect(); + spaced.split_whitespace().collect::>().join(" ") == "00 design system" +} + +/// The design system page (id) and the guidelines text layer on it (id, text), if there. +/// The design system page's id, and its guidelines text layer (id, text), each if there. +type Found = (Option, Option<(u64, String)>); + +fn find(b: &mut dyn figcraft_mcp::Backend, doc: Option) -> Result { + let pages = exec(b, doc, "page.list", json!({}))?; + let Some(page) = pages + .as_array() + .into_iter() + .flatten() + .find(|p| p.get("name").and_then(Value::as_str).is_some_and(is_page)) + .and_then(|p| p.get("id").and_then(Value::as_u64)) + else { + return Ok((None, None)); + }; + let found = exec(b, doc, "node.find", json!({"name": GUIDELINES, "root": page, "type": "text"}))?; + let ids: Vec = found.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect(); + for id in ids { + let node = exec(b, doc, "node.get", json!({"id": id}))?; + if let Some(text) = node.get("characters").or_else(|| node.get("text")).and_then(Value::as_str) { + return Ok((Some(page), Some((id, text.to_string())))); + } + } + Ok((Some(page), None)) +} + +/// Answer a `design_system` call through the window (or file) the agent works in: the text for +/// the model, and whether it worked. +pub fn call(b: &mut dyn figcraft_mcp::Backend, args: &Value) -> (String, bool) { + match run(b, args) { + Ok(text) => (text, true), + Err(e) => (format!("design_system failed: {e}"), false), + } +} + +fn run(b: &mut dyn figcraft_mcp::Backend, args: &Value) -> Result { + let doc = front_document(b); + let (page, guidelines) = find(b, doc)?; + let vars = exec(b, doc, "variable.list", json!({}))?; + let styles = exec(b, doc, "style.list", json!({}))?; + let existing = Existing::from_lists(&vars, &styles); + let collections: Vec<&String> = existing.collections.keys().collect(); + let Some(fields) = args.get("spec").or_else(|| args.get("brief")).and_then(Value::as_object) else { + return Ok(match page { + None => format!( + "This file has no '{PAGE}' page yet. Variable collections: {}.", + if collections.is_empty() { "none".to_string() } else { format!("{collections:?}") } + ), + Some(id) => format!( + "'{PAGE}' is page {id}; read its frames with design_context. Variable collections: {collections:?}.\n{}", + guidelines.map(|(_, t)| t).unwrap_or_else(|| "It has no 'Design guidelines' text yet.".into()) + ), + }); + }; + let mut merged = serde_json::to_value(Brief::default()).map_err(|e| e.to_string())?; + if let Some(obj) = merged.as_object_mut() { + for (k, v) in fields { + let v = match v { + Value::String(s) + if matches!(k.as_str(), "platform" | "neutral" | "modes" | "scale" | "radius" | "elevation" | "iconStyle" | "contrast") => + { + Value::String(s.to_lowercase()) + } + other => other.clone(), + }; + obj.insert(k.clone(), v); + } + } + let spec: Brief = serde_json::from_value(merged).map_err(|e| format!("the spec has a field with a wrong value: {e}"))?; + // The page (first in the file), the tokens, styles and review settings, and the guidelines + // text, in one batch: one undo step, and nothing changed when any part fails. + let text = spec.guidelines(); + let tokens = spec.steps(&existing); + let made = tokens.iter().filter(|s| matches!(s["command"].as_str(), Some("variable.create" | "style.create"))).count(); + let mut steps = Vec::with_capacity(tokens.len() + 3); + let page_ref = match page { + Some(id) => json!(id), + None => { + steps.push(json!({"command": "page.add", "params": {"name": PAGE}, "as": "dsPage"})); + json!({"$ref": "dsPage"}) + } + }; + steps.push(json!({"command": "page.move", "params": {"id": page_ref, "index": 0}})); + steps.extend(tokens); + steps.push(match guidelines { + Some((id, _)) => json!({"command": "node.set", "params": {"ids": [id], "props": {"characters": text}}}), + None => json!({"command": "node.create", "params": { + "type": "text", "parent": page_ref, "name": GUIDELINES, "x": -560, "y": 0, "characters": text, "select": false, + "props": {"width": 480, "textAutoResize": "height", "fontSize": 14, "lineHeight": 22}}}), + }); + exec(b, doc, "command.batch", json!({"label": "Design system", "commands": steps}))?; + let (page, _) = find(b, doc)?; + let page = page.ok_or("the design system page is missing after it was made")?; + Ok(format!( + "'{PAGE}' is page {page} (first in the file), with {made} new variables and styles: {PRIMITIVES} (colour ramps 50-900), {THEME} (roles, modes {}), {SIZES} (Space/…, Radius/S|M|L|Full, Border/…, Icon/…); text styles Display, Heading 1-3, Body large, Body, Body small, Caption, Label, Code; shadow styles Shadow/S, M, L; design.audit settings from the spec; and a 'Design guidelines' text. Lay out the foundations and base components on that page next (the 'Design system setup' skill).\n{text}", + spec.modes.names().join(", ") + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_brief_reads_back_and_an_old_one_takes_the_defaults() { + let b = Brief { product: "Klinik".into(), icon_set: "Phosphor".into(), ..Brief::default() }; + assert_eq!(Brief::from_json(&b.to_json()), Some(b)); + let old = Brief::from_json(r#"{"product": "X"}"#).expect("a partial brief"); + assert_eq!(old.product, "X"); + assert_eq!(old.spacing, Brief::default().spacing); + } + + #[test] + fn a_ramp_goes_from_pale_to_deep_in_the_colours_hue() { + let r = ramp("#2563EB").expect("a colour"); + assert_eq!(r.len(), STEPS.len()); + let lum: Vec = r.iter().filter_map(|h| Color::from_hex(h)).map(Color::luminance).collect(); + assert!(lum.windows(2).all(|w| w[0] > w[1]), "each step darker: {r:?}"); + assert!(ramp("not a colour").is_none()); + } + + #[test] + fn running_again_updates_instead_of_making_copies() { + let b = Brief::default(); + let fresh = b.steps(&Existing::default()); + let creates = |steps: &[Value], cmd: &str| steps.iter().filter(|s| s["command"] == cmd).count(); + assert!(creates(&fresh, "variable.createCollection") == 3); + assert!(creates(&fresh, "variable.create") > 40); + assert!(creates(&fresh, "style.create") >= 13); + + let mut existing = Existing::default(); + for s in &fresh { + let p = &s["params"]; + match s["command"].as_str() { + Some("variable.createCollection") => { + let modes = p["modes"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + existing.collections.insert(p["name"].as_str().unwrap_or_default().to_string(), modes); + } + Some("variable.create") => { + let name: String = p["name"].as_str().unwrap_or_default().into(); + existing.variables.insert((p["collection"].as_str().unwrap_or_default().into(), name.clone()), name); + } + Some("style.create") => { + existing.styles.insert(p["name"].as_str().unwrap_or_default().into()); + } + _ => {} + } + } + let again = b.steps(&existing); + assert_eq!(creates(&again, "variable.createCollection") + creates(&again, "variable.create") + creates(&again, "style.create"), 0); + assert!(creates(&again, "variable.set") > 0 && creates(&again, "style.update") > 0); + } + + #[test] + fn the_prompt_names_the_icon_set_and_its_style() { + let b = Brief { icon_set: "Phosphor".into(), icon_style: IconStyle::Duotone, ..Brief::default() }; + let p = b.guidelines(); + assert!(p.contains("Phosphor") && p.contains("Duotone")); + assert!(p.contains("never emoji")); + } + + #[test] + fn only_the_design_system_page_itself_counts() { + assert!(is_page("00 · Design System") && is_page("00 - design system") && is_page("00_Design_System")); + assert!(!is_page("00 · Design System exploration")); + assert!(!is_page("Design System")); + } + + #[test] + fn an_update_names_the_variable_of_its_own_collection() { + let vars = json!({ + "collections": [{"id": "c1", "name": "Other", "modes": [{"name": "Default"}]}, {"id": "c2", "name": SIZES, "modes": [{"name": "Default"}]}], + "variables": [{"id": "v1", "collection": "c1", "name": "Radius/S"}, {"id": "v2", "collection": "c2", "name": "Radius/S"}], + }); + let existing = Existing::from_lists(&vars, &json!([])); + let steps = Brief::default().steps(&existing); + let set = steps.iter().find(|s| s["command"] == "variable.set" && s["params"]["variable"].as_str().is_some_and(|v| v.starts_with('v'))); + assert_eq!(set.map(|s| s["params"]["variable"].clone()), Some(json!("v2"))); + } + + /// The engine as the agent's tools see it, without a window. + struct Engine(figcraft_engine::Session); + + impl figcraft_mcp::Backend for Engine { + fn call(&mut self, method: &str, params: Value) -> Result { + match method { + "engine.execute" => { + let cmd = params["command"].as_str().unwrap_or_default().to_string(); + self.0.execute(&cmd, ¶ms["params"]).map_err(|e| e.to_string()) + } + other => Err(format!("not here: {other}")), + } + } + + fn has_ui(&self) -> bool { + false + } + + fn describe(&self) -> String { + "test".into() + } + } + + #[test] + fn the_agent_makes_the_design_system_page_with_one_call_and_reads_it_back() { + let mut engine = Engine(figcraft_engine::Session::new()); + let (text, ok) = call(&mut engine, &json!({})); + assert!(ok && text.contains("no '00 · Design System' page"), "{text}"); + + let spec = json!({"spec": {"product": "Klinik", "primary": "#0F766E", "radius": "Round", "iconSet": "Phosphor", "spacing": 8}}); + let (text, ok) = call(&mut engine, &spec); + assert!(ok, "{text}"); + let pages = engine.0.execute("page.list", &json!({})).expect("pages"); + assert_eq!(pages[0]["name"], PAGE, "first in the file: {pages}"); + + // A later conversation finds the page and the guidelines on it. + let (text, ok) = call(&mut engine, &json!({})); + assert!(ok && text.contains("Phosphor") && text.contains("Klinik"), "{text}"); + let vars = engine.0.execute("variable.list", &json!({})).expect("variables"); + assert!(vars["collections"].as_array().into_iter().flatten().any(|c| c["name"] == THEME)); + let audit = engine.0.execute("design.audit", &json!({"scope": "page"})).expect("an audit"); + assert_eq!(audit["grid"], json!(8.0), "the spacing step is the review grid"); + + // One call is one undo step. + let undo_to = engine.0.undo_depth().0; + let (_, ok) = call(&mut engine, &json!({"spec": {"iconSet": "Feather"}})); + assert!(ok); + assert_eq!(engine.0.undo_depth().0, undo_to + 1, "one undo step"); + + // Again: the same page and guidelines, updated, not copied. + let (_, ok) = call(&mut engine, &json!({"spec": {"iconSet": "Lucide"}})); + assert!(ok); + let pages = engine.0.execute("page.list", &json!({})).expect("pages"); + assert_eq!(pages.as_array().into_iter().flatten().filter(|p| p["name"] == PAGE).count(), 1); + let (text, _) = call(&mut engine, &json!({})); + assert!(text.contains("Lucide")); + let found = engine.0.execute("node.find", &json!({"name": GUIDELINES, "root": pages[0]["id"]})).expect("find"); + assert_eq!(found["total"], json!(1)); + } +} diff --git a/crates/agent/src/cli.rs b/crates/agent/src/cli.rs new file mode 100644 index 000000000..8ba330c38 --- /dev/null +++ b/crates/agent/src/cli.rs @@ -0,0 +1,667 @@ +//! Connections through an installed command-line agent: Claude Code, Codex or OpenCode. +//! +//! The person signs in to those programs with their own plan; FigCraft never sees that login. A +//! turn runs the program once, non-interactively, with FigCraft's tools attached over MCP +//! ([`crate::mcp_http`]) and its own built-in tools left out, and reads its JSON event stream. The +//! program keeps the conversation; the next turn resumes it by the session id it reported. + +use std::io::{BufRead, BufReader, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::channel; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::Usage; +use crate::config::ApiKind; + +/// Whether a command-line agent can be used. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Status { + /// Not found on this computer. + Missing, + /// Installed but not signed in. + SignedOut(PathBuf), + /// Installed and signed in (or the program could not tell; the first turn will). + Ready(PathBuf), +} + +/// Find the program: the `PATH` the app was started with, then the folders installers use (an app +/// opened from the Finder gets a short `PATH`). +pub fn locate(kind: ApiKind) -> Option { + let name = kind.program()?; + let exe = if cfg!(windows) { format!("{name}.exe") } else { name.to_string() }; + let mut dirs: Vec = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); + if let Some(home) = home() { + for d in [".local/bin", ".opencode/bin", ".bun/bin", ".npm-global/bin", ".claude/local", ".cargo/bin", "bin"] { + dirs.push(home.join(d)); + } + } + for d in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"] { + dirs.push(PathBuf::from(d)); + } + dirs.into_iter().map(|d| d.join(&exe)).find(|p| p.is_file()) +} + +fn home() -> Option { + std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from) +} + +/// Whether the program is there and signed in. Runs it briefly, so call it off the UI thread. +pub fn status(kind: ApiKind) -> Status { + let Some(path) = locate(kind) else { return Status::Missing }; + let signed_in = match kind { + ApiKind::ClaudeCode => output(&path, &["auth", "status"]).map(|o| { + serde_json::from_str::(&o).ok().and_then(|v| v.get("loggedIn").and_then(Value::as_bool)).unwrap_or(!o.contains("Not logged in")) + }), + ApiKind::Codex => output(&path, &["login", "status"]).map(|o| !o.to_ascii_lowercase().contains("not logged in")), + ApiKind::OpenCode => output(&path, &["auth", "list"]).map(|o| o.lines().any(|l| l.contains("stored") || l.contains("environment"))), + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => None, + }; + match signed_in { + Some(false) => Status::SignedOut(path), + _ => Status::Ready(path), + } +} + +/// The models the program offers, when it can list them (OpenCode); `None` keeps the preset's. +pub fn models(kind: ApiKind) -> Option> { + if kind != ApiKind::OpenCode { + return None; + } + let path = locate(kind)?; + let out = output(&path, &["models"])?; + let ids: Vec = out.lines().map(str::trim).filter(|l| l.contains('/') && !l.contains(' ')).map(str::to_string).collect(); + if ids.is_empty() { None } else { Some(ids) } +} + +/// Run `program args`, giving up after 20 seconds; its standard output, or `None`. +fn output(program: &Path, args: &[&str]) -> Option { + let mut child = Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().ok()?; + let mut stdout = child.stdout.take()?; + let mut stderr = child.stderr.take()?; + let (tx, rx) = channel(); + std::thread::spawn(move || { + let mut s = String::new(); + let _ = stdout.read_to_string(&mut s); + let mut e = String::new(); + let _ = stderr.read_to_string(&mut e); + let _ = tx.send(format!("{s}\n{e}")); + }); + match rx.recv_timeout(Duration::from_secs(20)) { + Ok(s) => { + let _ = child.wait(); + Some(s) + } + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + None + } + } +} + +/// Everything one turn needs to start the program. +pub struct Turn<'a> { + pub kind: ApiKind, + pub program: &'a Path, + pub model: &'a str, + /// The conversation to continue, from the last turn. + pub session: Option<&'a str>, + pub prompt: &'a str, + /// FigCraft's rules for the agent, added to the program's own. + pub system: &'a str, + pub mcp_url: &'a str, + pub mcp_token: &'a str, + /// The folder the program runs in (it keeps nothing of the person's there). + pub workdir: &'a Path, + /// Images the person attached to this request. + pub images: &'a [crate::neutral::Image], +} + +/// The token's environment variable for Codex, which reads a bearer token from one. +const TOKEN_ENV: &str = "FIGCRAFT_MCP_TOKEN"; + +/// The command for one turn. `files` are the attached images written to disk, for the programs +/// that take images as files (Codex, OpenCode); Claude Code reads them from its input instead +/// ([`stdin_message`]). +pub fn command(turn: &Turn<'_>, files: &[PathBuf]) -> Command { + let mut cmd = Command::new(turn.program); + let piped = turn.kind == ApiKind::ClaudeCode && !turn.images.is_empty(); + cmd.current_dir(turn.workdir).stdin(if piped { Stdio::piped() } else { Stdio::null() }).stdout(Stdio::piped()).stderr(Stdio::piped()); + match turn.kind { + ApiKind::ClaudeCode => { + let config = json!({"mcpServers": {"figcraft": { + "type": "http", + "url": turn.mcp_url, + "headers": {"Authorization": format!("Bearer {}", turn.mcp_token)}, + }}}); + cmd.args(["-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages"]); + // Only FigCraft's tools: no shell, no file edits, no other MCP servers. + cmd.args(["--strict-mcp-config", "--mcp-config"]).arg(config.to_string()); + cmd.args(["--tools", "", "--allowedTools", "mcp__figcraft", "--disable-slash-commands"]); + cmd.arg("--append-system-prompt").arg(turn.system); + if !turn.model.trim().is_empty() { + cmd.arg("--model").arg(turn.model.trim()); + } + if let Some(s) = turn.session { + cmd.arg("--resume").arg(s); + } + if piped { + // The request, images included, arrives as one message on standard input. + cmd.args(["--input-format", "stream-json"]); + } else { + cmd.arg("--").arg(turn.prompt); + } + } + ApiKind::Codex => { + cmd.env(TOKEN_ENV, turn.mcp_token); + // `exec`'s own options come before `resume`: that subcommand doesn't take them, and a + // resumed turn must keep the read-only sandbox. + cmd.arg("exec"); + cmd.args(["--json", "--skip-git-repo-check", "--sandbox", "read-only"]); + cmd.arg("-c").arg(format!("mcp_servers.figcraft.url={}", toml_string(turn.mcp_url))); + cmd.arg("-c").arg(format!("mcp_servers.figcraft.bearer_token_env_var={}", toml_string(TOKEN_ENV))); + if !turn.model.trim().is_empty() { + cmd.arg("--model").arg(turn.model.trim()); + } + if let Some(s) = turn.session { + cmd.args(["resume", s]); + } + for f in files { + cmd.arg("--image").arg(f); + } + // Codex has no flag for added instructions: the first turn carries them. + let prompt = if turn.session.is_none() { format!("{}\n\n---\n\n{}", turn.system, turn.prompt) } else { turn.prompt.to_string() }; + cmd.arg("--").arg(prompt); + } + ApiKind::OpenCode => { + let config = json!({ + "$schema": "https://opencode.ai/config.json", + "mcp": {"figcraft": { + "type": "remote", + "url": turn.mcp_url, + "enabled": true, + "headers": {"Authorization": format!("Bearer {}", turn.mcp_token)}, + }}, + "agent": {"figcraft": { + "description": "Designs in the open FigCraft window", + "mode": "primary", + "prompt": turn.system, + "tools": {"*": false, "figcraft_*": true}, + }}, + }); + cmd.env("OPENCODE_CONFIG_CONTENT", config.to_string()); + cmd.args(["run", "--format", "json", "--agent", "figcraft"]); + if !turn.model.trim().is_empty() { + cmd.arg("--model").arg(turn.model.trim()); + } + if let Some(s) = turn.session { + cmd.arg("--session").arg(s); + } + for f in files { + cmd.arg("--file").arg(f); + } + cmd.arg("--").arg(turn.prompt); + } + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => {} + } + cmd +} + +/// Claude Code's input when the request carries images: one user message, text and images. +pub fn stdin_message(turn: &Turn<'_>) -> String { + let mut content = vec![json!({"type": "text", "text": turn.prompt})]; + for i in turn.images { + content.push(json!({"type": "image", "source": {"type": "base64", "media_type": i.mime, "data": i.data}})); + } + json!({"type": "user", "message": {"role": "user", "content": content}}).to_string() +} + +/// A folder of copies made for one run, removed when it is dropped (after the program has exited). +struct Staged(Option); + +impl Drop for Staged { + fn drop(&mut self) { + if let Some(dir) = self.0.take() { + let _ = std::fs::remove_dir_all(dir); + } + } +} + +/// Write the attached images where the program can read them, in a folder of this run's own that +/// goes away with `staged`; their paths, in order. +fn write_images(turn: &Turn<'_>, staged: &mut Staged) -> Result, String> { + if turn.images.is_empty() || turn.kind == ApiKind::ClaudeCode { + return Ok(Vec::new()); + } + use base64::Engine as _; + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let dir = turn.workdir.join("attachments").join(format!("{stamp}-{}", std::process::id())); + std::fs::create_dir_all(&dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + staged.0 = Some(dir.clone()); + let mut out = Vec::new(); + for (n, i) in turn.images.iter().enumerate() { + let ext = match i.mime.as_str() { + "image/jpeg" => "jpg", + "image/webp" => "webp", + "image/gif" => "gif", + _ => "png", + }; + let bytes = base64::engine::general_purpose::STANDARD.decode(i.data.as_bytes()).map_err(|e| format!("an attached image is damaged: {e}"))?; + let path = dir.join(format!("{n}.{ext}")); + std::fs::write(&path, bytes).map_err(|e| format!("can't write {}: {e}", path.display()))?; + out.push(path); + } + Ok(out) +} + +fn toml_string(s: &str) -> String { + format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) +} + +/// One thing read off the program's event stream. +#[derive(Clone, Debug, PartialEq)] +pub enum Parsed { + /// The conversation id to resume next time. + Session(String), + Text(String), + /// Tokens this event used (added to the turn's total). + Usage(Usage), + Error(String), +} + +/// Reads one program's JSON lines into [`Parsed`] events. +pub struct Parser { + kind: ApiKind, + /// Claude Code sends text twice (deltas, then the whole message); once deltas came, the whole + /// message is skipped. + deltas: bool, + /// Whether any text was given yet, so a later block starts a new paragraph. + wrote: bool, +} + +impl Parser { + pub fn new(kind: ApiKind) -> Self { + Self { kind, deltas: false, wrote: false } + } + + fn text(&mut self, out: &mut Vec, t: &str, new_block: bool) { + if t.is_empty() { + return; + } + if new_block && self.wrote { + out.push(Parsed::Text("\n\n".into())); + } + self.wrote = true; + out.push(Parsed::Text(t.to_string())); + } + + pub fn line(&mut self, line: &str) -> Vec { + let mut out = Vec::new(); + let Ok(v) = serde_json::from_str::(line.trim()) else { return out }; + let ty = v.get("type").and_then(Value::as_str).unwrap_or(""); + let s = |p: &str| v.pointer(p).and_then(Value::as_str).unwrap_or("").to_string(); + let n = |x: &Value, p: &str| x.pointer(p).and_then(Value::as_u64).unwrap_or(0); + match self.kind { + ApiKind::ClaudeCode => match ty { + "system" if s("/subtype") == "init" => out.push(Parsed::Session(s("/session_id"))), + "stream_event" => { + let e = &v["event"]; + match e.get("type").and_then(Value::as_str) { + Some("content_block_start") if e.pointer("/content_block/type").and_then(Value::as_str) == Some("text") => { + self.deltas = true; + let t = e.pointer("/content_block/text").and_then(Value::as_str).unwrap_or(""); + if self.wrote { + out.push(Parsed::Text("\n\n".into())); + } + self.wrote = true; + if !t.is_empty() { + out.push(Parsed::Text(t.to_string())); + } + } + Some("content_block_delta") if e.pointer("/delta/type").and_then(Value::as_str) == Some("text_delta") => { + self.deltas = true; + self.wrote = true; + let t = e.pointer("/delta/text").and_then(Value::as_str).unwrap_or(""); + if !t.is_empty() { + out.push(Parsed::Text(t.to_string())); + } + } + _ => {} + } + } + "assistant" if !self.deltas => { + for block in v.pointer("/message/content").and_then(Value::as_array).into_iter().flatten() { + if block.get("type").and_then(Value::as_str) == Some("text") { + let t = block.get("text").and_then(Value::as_str).unwrap_or("").to_string(); + self.text(&mut out, &t, true); + } + } + } + "result" => { + if !s("/session_id").is_empty() { + out.push(Parsed::Session(s("/session_id"))); + } + let u = &v["usage"]; + let input = n(u, "/input_tokens") + n(u, "/cache_creation_input_tokens") + n(u, "/cache_read_input_tokens"); + out.push(Parsed::Usage(Usage { input, output: n(u, "/output_tokens") })); + if v.get("is_error").and_then(Value::as_bool).unwrap_or(false) { + let why = if s("/result").is_empty() { s("/subtype") } else { s("/result") }; + out.push(Parsed::Error(why)); + } + } + _ => {} + }, + ApiKind::OpenCode => { + if let Some(id) = v.get("sessionID").and_then(Value::as_str) { + out.push(Parsed::Session(id.to_string())); + } + match ty { + "text" => { + let t = s("/part/text"); + self.text(&mut out, &t, true); + } + "step_finish" => { + let tk = &v["part"]["tokens"]; + let input = n(tk, "/input") + n(tk, "/cache/read") + n(tk, "/cache/write"); + out.push(Parsed::Usage(Usage { input, output: n(tk, "/output") + n(tk, "/reasoning") })); + } + "error" => { + let why = [s("/error/data/message"), s("/error/message"), s("/message")].into_iter().find(|m| !m.is_empty()); + out.push(Parsed::Error(why.unwrap_or_else(|| line.chars().take(300).collect()))); + } + _ => {} + } + } + ApiKind::Codex => match ty { + "thread.started" => out.push(Parsed::Session(s("/thread_id"))), + "item.completed" if s("/item/type") == "agent_message" => { + let t = s("/item/text"); + self.text(&mut out, &t, true); + } + "turn.completed" => { + let u = &v["usage"]; + out.push(Parsed::Usage(Usage { input: n(u, "/input_tokens"), output: n(u, "/output_tokens") })); + } + "turn.failed" => out.push(Parsed::Error(s("/error/message"))), + "error" => out.push(Parsed::Error(s("/message"))), + _ => {} + }, + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => {} + } + out + } +} + +/// What a finished run reports. +pub struct Outcome { + pub session: Option, + pub usage: Usage, + pub stopped: bool, + /// The error to show, when the run failed. + pub error: Option, +} + +/// Run one turn to the end, streaming text through `on_text`; Stop kills the program. +pub fn run(turn: &Turn<'_>, on_text: &mut dyn FnMut(&str), cancel: &Arc) -> Outcome { + let mut outcome = Outcome { session: turn.session.map(str::to_string), usage: Usage::default(), stopped: false, error: None }; + let _ = std::fs::create_dir_all(turn.workdir); + let name = turn.kind.label(); + // Declared before the child, so the copies outlive it: removed after it has exited. + let mut staged = Staged(None); + let files = match write_images(turn, &mut staged) { + Ok(f) => f, + Err(e) => { + outcome.error = Some(e); + return outcome; + } + }; + let mut child = match command(turn, &files).spawn() { + Ok(c) => c, + Err(e) => { + outcome.error = Some(format!("can't start {name} ({}): {e}", turn.program.display())); + return outcome; + } + }; + if let Some(mut stdin) = child.stdin.take() { + use std::io::Write as _; + let message = stdin_message(turn); + // Closing standard input after the message ends the request. + std::thread::spawn(move || { + let _ = stdin.write_all(message.as_bytes()); + let _ = stdin.write_all(b"\n"); + }); + } + let (tx, rx) = channel::(); + if let Some(stdout) = child.stdout.take() { + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + let Ok(line) = line else { break }; + if tx.send(line).is_err() { + break; + } + } + }); + } + let (etx, erx) = channel::(); + if let Some(mut stderr) = child.stderr.take() { + std::thread::spawn(move || { + let mut s = String::new(); + let _ = stderr.read_to_string(&mut s); + let _ = etx.send(s); + }); + } + let mut parser = Parser::new(turn.kind); + let mut failed: Vec = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + let _ = child.kill(); + let _ = child.wait(); + outcome.stopped = true; + return outcome; + } + match rx.recv_timeout(Duration::from_millis(100)) { + Ok(line) => { + for p in parser.line(&line) { + match p { + Parsed::Session(s) if !s.is_empty() => outcome.session = Some(s), + Parsed::Session(_) => {} + Parsed::Text(t) => on_text(&t), + Parsed::Usage(u) => { + outcome.usage.input = outcome.usage.input.saturating_add(u.input); + outcome.usage.output = outcome.usage.output.saturating_add(u.output); + } + Parsed::Error(e) if !e.is_empty() => failed.push(e), + Parsed::Error(_) => {} + } + } + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + } + } + // The program closed its output but may still be running: Stop keeps working until it exits. + let status = loop { + if cancel.load(Ordering::Relaxed) { + let _ = child.kill(); + let _ = child.wait(); + outcome.stopped = true; + return outcome; + } + match child.try_wait() { + Ok(Some(s)) => break Ok(s), + Ok(None) => std::thread::sleep(Duration::from_millis(100)), + Err(e) => break Err(e), + } + }; + let stderr = erx.recv_timeout(Duration::from_secs(2)).unwrap_or_default(); + if !failed.is_empty() { + outcome.error = Some(format!("{name}: {}", failed.join("; "))); + } else if let Ok(s) = status + && !s.success() + { + let tail: String = stderr.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").chars().take(400).collect(); + outcome.error = Some(if tail.is_empty() { format!("{name} exited with {s}") } else { format!("{name}: {tail}") }); + } + outcome +} + +#[cfg(test)] +mod tests { + use super::*; + + fn texts(p: &[Parsed]) -> String { + p.iter() + .filter_map(|x| match x { + Parsed::Text(t) => Some(t.as_str()), + _ => None, + }) + .collect() + } + + #[test] + fn claude_code_text_arrives_once_and_blocks_are_paragraphs() { + let mut p = Parser::new(ApiKind::ClaudeCode); + let mut all = Vec::new(); + for line in [ + r#"{"type":"system","subtype":"init","session_id":"s-1"}"#, + r#"{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Making "}}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"a card."}}}"#, + r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Making a card."}]}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Done."}}}"#, + r#"{"type":"result","subtype":"success","is_error":false,"session_id":"s-1","usage":{"input_tokens":3,"cache_read_input_tokens":10,"output_tokens":5}}"#, + ] { + all.extend(p.line(line)); + } + assert_eq!(texts(&all), "Making a card.\n\nDone."); + assert!(all.contains(&Parsed::Session("s-1".into()))); + assert!(all.iter().any(|x| matches!(x, Parsed::Usage(u) if u.input > u.output))); + assert!(!all.iter().any(|x| matches!(x, Parsed::Error(_)))); + } + + #[test] + fn a_failed_claude_code_run_says_why() { + let mut p = Parser::new(ApiKind::ClaudeCode); + let out = p.line(r#"{"type":"result","subtype":"error","is_error":true,"result":"Not logged in · Please run /login","usage":{}}"#); + assert!(out.iter().any(|x| matches!(x, Parsed::Error(e) if e.contains("login")))); + } + + #[test] + fn opencode_parts_become_text_usage_and_a_session() { + let mut p = Parser::new(ApiKind::OpenCode); + let mut all = Vec::new(); + for line in [ + r#"{"type":"step_start","sessionID":"ses_1","part":{"type":"step-start"}}"#, + r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"First."}}"#, + r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"Second."}}"#, + r#"{"type":"step_finish","sessionID":"ses_1","part":{"tokens":{"input":70,"output":3,"reasoning":2,"cache":{"read":5,"write":0}}}}"#, + "not json", + ] { + all.extend(p.line(line)); + } + assert_eq!(texts(&all), "First.\n\nSecond."); + assert!(all.contains(&Parsed::Session("ses_1".into()))); + assert!(all.iter().any(|x| matches!(x, Parsed::Usage(u) if u.input == 75 && u.output == 5))); + } + + #[test] + fn codex_messages_and_failures_are_read() { + let mut p = Parser::new(ApiKind::Codex); + let mut all = Vec::new(); + for line in [ + r#"{"type":"thread.started","thread_id":"th-9"}"#, + r#"{"type":"item.completed","item":{"id":"i0","type":"reasoning","text":"thinking"}}"#, + r#"{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":"Built it."}}"#, + r#"{"type":"turn.completed","usage":{"input_tokens":20,"output_tokens":4}}"#, + r#"{"type":"turn.failed","error":{"message":"usage limit reached"}}"#, + ] { + all.extend(p.line(line)); + } + assert_eq!(texts(&all), "Built it.", "reasoning is not the answer"); + assert!(all.contains(&Parsed::Session("th-9".into()))); + assert!(all.iter().any(|x| matches!(x, Parsed::Error(e) if e.contains("limit")))); + } + + #[test] + fn claude_code_gets_only_figcraft_tools() { + let dir = std::env::temp_dir(); + let turn = Turn { + kind: ApiKind::ClaudeCode, + program: Path::new("claude"), + model: "", + session: Some("s-1"), + prompt: "--dangerous-looking prompt", + system: "rules", + mcp_url: "http://127.0.0.1:1/mcp", + mcp_token: "t", + workdir: &dir, + images: &[], + }; + let cmd = command(&turn, &[]); + let args: Vec = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let at = |flag: &str| args.iter().position(|a| a == flag).map(|i| args[i + 1].clone()); + assert_eq!(at("--tools").as_deref(), Some(""), "no built-in tools"); + assert_eq!(at("--allowedTools").as_deref(), Some("mcp__figcraft")); + assert!(args.contains(&"--strict-mcp-config".to_string()), "no other MCP servers"); + assert_eq!(at("--resume").as_deref(), Some("s-1")); + assert_eq!(at("--").as_deref(), Some("--dangerous-looking prompt"), "the prompt is never read as a flag"); + assert!(!args.iter().any(|a| a == "--model"), "the default model"); + } + + #[test] + fn a_resumed_codex_turn_keeps_the_read_only_sandbox() { + let dir = std::env::temp_dir(); + let turn = Turn { + kind: ApiKind::Codex, + program: Path::new("codex"), + model: "", + session: Some("th-1"), + prompt: "again", + system: "rules", + mcp_url: "http://127.0.0.1:1/mcp", + mcp_token: "t", + workdir: &dir, + images: &[], + }; + let args: Vec = command(&turn, &[]).get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let at = |a: &str| args.iter().position(|x| x == a); + let resume = at("resume").expect("resumes"); + assert!(at("--sandbox").is_some_and(|i| i < resume && args[i + 1] == "read-only"), "{args:?}"); + assert!(at("--json").is_some_and(|i| i < resume)); + } + + #[test] + fn attached_images_reach_each_program_its_own_way() { + let dir = std::env::temp_dir(); + let images = [crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() }]; + let mut turn = Turn { + kind: ApiKind::ClaudeCode, + program: Path::new("claude"), + model: "", + session: None, + prompt: "like this", + system: "rules", + mcp_url: "http://127.0.0.1:1/mcp", + mcp_token: "t", + workdir: &dir, + images: &images, + }; + let args = |c: &Command| c.get_args().map(|a| a.to_string_lossy().into_owned()).collect::>(); + let claude = args(&command(&turn, &[])); + assert!(claude.windows(2).any(|w| w == ["--input-format", "stream-json"]), "Claude Code reads the request from its input"); + assert!(!claude.contains(&"like this".to_string()), "the prompt is in the message, not an argument"); + let message: Value = serde_json::from_str(&stdin_message(&turn)).expect("json"); + assert_eq!(message.pointer("/message/content/1/type").and_then(Value::as_str), Some("image")); + turn.kind = ApiKind::OpenCode; + let file = PathBuf::from("/tmp/a.png"); + assert!(args(&command(&turn, std::slice::from_ref(&file))).windows(2).any(|w| w == ["--file", "/tmp/a.png"])); + turn.kind = ApiKind::Codex; + assert!(args(&command(&turn, std::slice::from_ref(&file))).windows(2).any(|w| w == ["--image", "/tmp/a.png"])); + } +} diff --git a/crates/agent/src/config.rs b/crates/agent/src/config.rs new file mode 100644 index 000000000..aa2225949 --- /dev/null +++ b/crates/agent/src/config.rs @@ -0,0 +1,512 @@ +//! The agent's settings: connected providers, the chosen model and how much the agent may do on +//! its own. Stored in `agents.json` beside the app's preferences, readable only by the user (it +//! holds API keys). + +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +/// Which wire dialect a provider speaks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ApiKind { + #[default] + OpenAiCompletions, + AnthropicMessages, + /// The person's own Claude Code install (`claude`), signed in with their Claude plan. + ClaudeCode, + /// The person's own Codex install (`codex`), signed in with their ChatGPT plan. + Codex, + /// The person's own OpenCode install (`opencode`), with the providers it is signed in to. + OpenCode, +} + +impl ApiKind { + pub fn label(self) -> &'static str { + match self { + ApiKind::OpenAiCompletions => "OpenAI Completions", + ApiKind::AnthropicMessages => "Anthropic Messages", + ApiKind::ClaudeCode => "Claude Code", + ApiKind::Codex => "Codex", + ApiKind::OpenCode => "OpenCode", + } + } + + /// Whether requests go through an installed command-line agent rather than an HTTP endpoint. + pub fn is_cli(self) -> bool { + matches!(self, ApiKind::ClaudeCode | ApiKind::Codex | ApiKind::OpenCode) + } + + /// The program a command-line connection runs. + pub fn program(self) -> Option<&'static str> { + match self { + ApiKind::ClaudeCode => Some("claude"), + ApiKind::Codex => Some("codex"), + ApiKind::OpenCode => Some("opencode"), + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => None, + } + } +} + +/// How much a reasoning model may think before answering (OpenAI-compatible endpoints; the +/// Anthropic adapter leaves its provider default alone). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Reasoning { + #[default] + Auto, + Low, + Medium, + High, +} + +impl Reasoning { + pub fn label(self) -> &'static str { + match self { + Reasoning::Auto => "Auto", + Reasoning::Low => "Low", + Reasoning::Medium => "Medium", + Reasoning::High => "High", + } + } + + /// The `reasoning_effort` value, `None` for Auto (the provider's own default). + pub fn effort(self) -> Option<&'static str> { + match self { + Reasoning::Auto => None, + Reasoning::Low => Some("low"), + Reasoning::Medium => Some("medium"), + Reasoning::High => Some("high"), + } + } + + pub const CHOICES: &'static [Reasoning] = &[Reasoning::Auto, Reasoning::Low, Reasoning::Medium, Reasoning::High]; +} + +/// How much the agent does without asking. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Permission { + /// Canvas edits run at once; anything that reads or writes a file, or reaches the network, + /// waits for the person's Allow. + #[default] + AskFiles, + /// Everything runs at once. File access is confined only when the app was started with + /// automation roots; a window opened normally has none. + Auto, +} + +/// One connected model endpoint. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Provider { + pub name: String, + #[serde(default)] + pub kind: ApiKind, + /// The API root, e.g. `https://opencode.ai/zen/go/v1`; the adapter adds `/chat/completions` + /// or `/messages`. + pub base_url: String, + #[serde(default)] + pub api_key: String, + #[serde(default)] + pub model: String, + /// Model ids seen from this endpoint (`/models`), for the picker. + #[serde(default)] + pub models: Vec, + /// The model's limits, in tokens. + #[serde(default = "default_context")] + pub context_window: u32, + #[serde(default = "default_max_tokens")] + pub max_tokens: u32, + /// Whether the model reads images (screenshots of the canvas). + #[serde(default = "default_true")] + pub vision: bool, + /// Reasoning effort, where the endpoint supports one. + #[serde(default)] + pub reasoning: Reasoning, + /// What the endpoint charges, in US dollars per million tokens; 0 leaves the estimate out. + #[serde(default)] + pub price_in: f64, + #[serde(default)] + pub price_out: f64, +} + +fn default_context() -> u32 { + 128_000 +} + +fn default_max_tokens() -> u32 { + 8_192 +} + +fn default_true() -> bool { + true +} + +impl Provider { + pub fn new(name: &str, kind: ApiKind, base_url: &str) -> Self { + Self { + name: name.to_string(), + kind, + base_url: base_url.trim_end_matches('/').to_string(), + api_key: String::new(), + model: String::new(), + models: Vec::new(), + context_window: default_context(), + max_tokens: default_max_tokens(), + vision: true, + reasoning: Reasoning::Auto, + price_in: 0.0, + price_out: 0.0, + } + } + + /// The endpoint a request goes to. + pub fn endpoint(&self) -> String { + let root = self.base_url.trim_end_matches('/'); + match self.kind { + ApiKind::OpenAiCompletions => format!("{root}/chat/completions"), + ApiKind::AnthropicMessages => format!("{root}/messages"), + ApiKind::ClaudeCode | ApiKind::Codex | ApiKind::OpenCode => String::new(), + } + } + + /// Whether enough is filled in to send a request. A command-line connection needs nothing: + /// an empty model means that program's own default. + pub fn ready(&self) -> bool { + self.kind.is_cli() || (!self.base_url.trim().is_empty() && !self.model.trim().is_empty()) + } + + /// The model as the panel shows it. + pub fn model_label(&self) -> &str { + if self.model.trim().is_empty() { "Default model" } else { self.model.as_str() } + } + + /// A connection to the preset, with its model filled in later by [`pick_model`]. + pub fn from_preset(preset: &Preset) -> Self { + Self::new(preset.name, preset.kind, preset.base_url) + } + + /// A connection to an installed command-line agent. + pub fn from_cli(cli: &CliPreset) -> Self { + let mut p = Self::new(cli.name, cli.kind, ""); + p.models = cli.models.iter().map(|m| m.to_string()).collect(); + p + } +} + +/// A provider the person connects with an API key (or nothing, for a local server); the model is +/// picked from the endpoint's list. +pub struct Preset { + pub name: &'static str, + pub kind: ApiKind, + pub base_url: &'static str, + /// One line under the name on the connection card. + pub blurb: &'static str, + /// Where the person gets a key; `None` for a local server, which needs none. + pub key_url: Option<&'static str>, + /// Model ids (or parts of them) to choose first, in order, after the list arrives. + pub prefer: &'static [&'static str], +} + +impl Preset { + pub fn needs_key(&self) -> bool { + self.key_url.is_some() + } +} + +pub const PRESETS: &[Preset] = &[ + Preset { + name: "Anthropic", + kind: ApiKind::AnthropicMessages, + base_url: "https://api.anthropic.com/v1", + blurb: "Claude models with an API key", + key_url: Some("https://console.anthropic.com/settings/keys"), + prefer: &["claude-sonnet", "claude-opus"], + }, + Preset { + name: "OpenAI", + kind: ApiKind::OpenAiCompletions, + base_url: "https://api.openai.com/v1", + blurb: "GPT models with an API key", + key_url: Some("https://platform.openai.com/api-keys"), + prefer: &["gpt-5", "gpt-4.1"], + }, + Preset { + name: "OpenCode Go", + kind: ApiKind::OpenAiCompletions, + base_url: "https://opencode.ai/zen/go/v1", + blurb: "Open models on the OpenCode Go plan", + key_url: Some("https://opencode.ai/auth"), + prefer: &["kimi-k3", "glm-5", "qwen", "deepseek"], + }, + Preset { + name: "OpenCode Zen", + kind: ApiKind::OpenAiCompletions, + base_url: "https://opencode.ai/zen/v1", + blurb: "Pay-as-you-go models from OpenCode", + key_url: Some("https://opencode.ai/auth"), + prefer: &["claude-sonnet", "gpt-5", "kimi"], + }, + Preset { + name: "OpenRouter", + kind: ApiKind::OpenAiCompletions, + base_url: "https://openrouter.ai/api/v1", + blurb: "Many providers behind one key", + key_url: Some("https://openrouter.ai/keys"), + prefer: &["anthropic/claude-sonnet", "openai/gpt-5"], + }, + Preset { + name: "DeepSeek", + kind: ApiKind::OpenAiCompletions, + base_url: "https://api.deepseek.com/v1", + blurb: "DeepSeek models with an API key", + key_url: Some("https://platform.deepseek.com/api_keys"), + prefer: &["deepseek-chat"], + }, + Preset { + name: "Ollama", + kind: ApiKind::OpenAiCompletions, + base_url: "http://localhost:11434/v1", + blurb: "Models running on this computer", + key_url: None, + prefer: &[], + }, + Preset { + name: "LM Studio", + kind: ApiKind::OpenAiCompletions, + base_url: "http://localhost:1234/v1", + blurb: "Models running on this computer", + key_url: None, + prefer: &[], + }, +]; + +/// An installed command-line agent the person signs in to with their own plan. +pub struct CliPreset { + pub name: &'static str, + pub kind: ApiKind, + pub blurb: &'static str, + /// How to install it, shown when it is missing. + pub install: &'static str, + /// How to sign in, shown when it is installed but signed out. + pub login: &'static str, + /// Models offered before the program is asked for its own list (empty: its default only). + pub models: &'static [&'static str], +} + +pub const SUBSCRIPTIONS: &[CliPreset] = &[ + CliPreset { + name: "Claude Code", + kind: ApiKind::ClaudeCode, + blurb: "Use your Claude Pro or Max plan", + install: "curl -fsSL https://claude.ai/install.sh | bash", + login: "claude auth login", + models: &["sonnet", "opus", "haiku"], + }, + CliPreset { + name: "Codex", + kind: ApiKind::Codex, + blurb: "Use your ChatGPT plan", + install: "brew install codex", + login: "codex login", + models: &[], + }, + CliPreset { + name: "OpenCode", + kind: ApiKind::OpenCode, + blurb: "Use the providers OpenCode is signed in to", + install: "curl -fsSL https://opencode.ai/install | bash", + login: "opencode auth login", + models: &[], + }, +]; + +/// The model to start with once an endpoint listed its models: the first id that matches one of +/// `prefer` (newest first, skipping small and non-chat models), else the first chat model. +pub fn pick_model(prefer: &[&str], models: &[String]) -> Option { + const NOT_CHAT: &[&str] = &["embed", "audio", "realtime", "tts", "transcribe", "moderation", "image", "search", "whisper", "dall-e"]; + const SMALL: &[&str] = &["nano", "mini", "haiku", "flash", "lite"]; + let chat: Vec<&String> = models.iter().filter(|m| !NOT_CHAT.iter().any(|n| m.to_ascii_lowercase().contains(n))).collect(); + for want in prefer { + let mut hits: Vec<&&String> = chat.iter().filter(|m| m.contains(want)).collect(); + hits.sort_by(|a, b| b.cmp(a)); + if let Some(m) = hits.iter().find(|m| !SMALL.iter().any(|s| m.contains(s))).or(hits.first()) { + return Some((**m).to_string()); + } + } + chat.iter().find(|m| !SMALL.iter().any(|s| m.contains(s))).or(chat.first()).map(|m| m.to_string()) +} + +/// Everything `agents.json` holds. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentsFile { + #[serde(default)] + pub providers: Vec, + /// Index into `providers`; out of range means the first. + #[serde(default)] + pub active: usize, + #[serde(default)] + pub permission: Permission, + /// Whether the app opens on the Agent tab (the rail's Agent button was the last one used). + #[serde(default)] + pub panel: bool, + /// Whether the agent looks at the canvas after a turn that changed it and fixes what it sees + /// (models that read images only). + #[serde(default = "default_true")] + pub review: bool, + /// How many versions one request builds (1: just the design, up to 3 side by side). + #[serde(default = "one")] + pub variants: u8, +} + +fn one() -> u8 { + 1 +} + +impl AgentsFile { + /// The provider requests go to. + pub fn active(&self) -> Option<&Provider> { + self.providers.get(self.active).or_else(|| self.providers.first()) + } + + pub fn active_mut(&mut self) -> Option<&mut Provider> { + let i = if self.active < self.providers.len() { self.active } else { 0 }; + self.providers.get_mut(i) + } + + /// Read the file; a missing one is an empty setup, a damaged one is an empty setup with the + /// reason kept for the panel. + pub fn load(path: Option<&Path>) -> (Self, Option) { + let Some(path) = path else { return (Self::default(), None) }; + let bytes = match std::fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::default(), None), + Err(e) => return (Self::default(), Some(format!("can't read {}: {e}", path.display()))), + }; + match serde_json::from_slice::(&bytes) { + Ok(mut f) => { + if f.active >= f.providers.len() { + f.active = 0; + } + (f, None) + } + Err(e) => (Self::default(), Some(format!("{} is damaged: {e}", path.display()))), + } + } + + /// Write the file, readable only by the user: it holds API keys. + pub fn save(&self, path: Option<&Path>) -> Result<(), String> { + let Some(path) = path else { return Err("this build has no settings folder to keep providers in".into()) }; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + } + let bytes = serde_json::to_vec_pretty(self).map_err(|e| format!("can't encode the agent settings: {e}"))?; + write_private(path, &bytes) + } +} + +/// Write `bytes` to `path` through a temporary file, keeping the file owner-only where the +/// platform has permissions. +pub fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + } + let mut tmp = path.to_path_buf(); + tmp.set_extension("json.tmp"); + { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + opts.mode(0o600); + } + let mut file = opts.open(&tmp).map_err(|e| format!("can't write {}: {e}", tmp.display()))?; + use std::io::Write as _; + file.write_all(bytes).map_err(|e| format!("can't write {}: {e}", tmp.display()))?; + file.flush().map_err(|e| format!("can't write {}: {e}", tmp.display()))?; + } + std::fs::rename(&tmp, path).map_err(|e| format!("can't replace {}: {e}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn endpoints_follow_the_dialect() { + let mut p = Provider::new("Go", ApiKind::OpenAiCompletions, "https://opencode.ai/zen/go/v1/"); + assert_eq!(p.endpoint(), "https://opencode.ai/zen/go/v1/chat/completions"); + p.kind = ApiKind::AnthropicMessages; + assert_eq!(p.endpoint(), "https://opencode.ai/zen/go/v1/messages"); + assert!(!p.ready(), "no model chosen"); + p.model = "claude-haiku-5-5".into(); + assert!(p.ready()); + } + + #[test] + fn the_first_model_is_a_capable_chat_model() { + let ids = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + let anthropic = ids(&["claude-haiku-5-5", "claude-opus-4-1", "claude-sonnet-4-5", "claude-sonnet-5-5"]); + assert_eq!(pick_model(&["claude-sonnet"], &anthropic).as_deref(), Some("claude-sonnet-5-5"), "the newest preferred"); + let openai = ids(&["gpt-5-nano", "gpt-5.5", "text-embedding-3", "gpt-5-mini"]); + assert_eq!(pick_model(&["gpt-5"], &openai).as_deref(), Some("gpt-5.5"), "not a small model"); + let local = ids(&["nomic-embed", "llama4"]); + assert_eq!(pick_model(&[], &local).as_deref(), Some("llama4"), "not an embedding model"); + assert_eq!(pick_model(&["x"], &[]), None); + } + + #[test] + fn a_command_line_connection_needs_no_model() { + let p = Provider::from_cli(&SUBSCRIPTIONS[0]); + assert!(p.ready()); + assert!(p.kind.is_cli()); + assert!(!p.models.is_empty()); + } + + #[test] + fn settings_round_trip_through_a_private_file() { + let dir = std::env::temp_dir().join(format!("figcraft-agent-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("agents.json"); + let mut f = AgentsFile::default(); + f.providers.push(Provider::new("Go", ApiKind::OpenAiCompletions, "https://example.test/v1")); + f.providers[0].api_key = "sk-secret".into(); + f.providers[0].model = "deepseek-v4.1-flash".into(); + f.providers[0].reasoning = Reasoning::Medium; + f.providers[0].price_in = 1.5; + f.providers[0].price_out = 6.0; + f.active = 0; + f.permission = Permission::Auto; + f.variants = 3; + f.save(Some(&path)).expect("saved"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let mode = std::fs::metadata(&path).map(|m| m.permissions().mode()).unwrap_or(0); + assert_eq!(mode & 0o777, 0o600, "the key file is owner-only"); + } + let (back, err) = AgentsFile::load(Some(&path)); + assert!(err.is_none()); + assert_eq!(back.providers[0].api_key, "sk-secret"); + assert_eq!(back.permission, Permission::Auto); + assert_eq!(back.providers[0].reasoning, Reasoning::Medium); + assert_eq!(back.providers[0].price_out, 6.0); + assert_eq!(back.variants, 3); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_damaged_file_is_reported_not_fatal() { + let dir = std::env::temp_dir().join(format!("figcraft-agent-bad-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("agents.json"); + std::fs::write(&path, b"{not json").expect("write"); + let (f, err) = AgentsFile::load(Some(&path)); + assert!(f.providers.is_empty()); + assert!(err.is_some()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/agent/src/http.rs b/crates/agent/src/http.rs new file mode 100644 index 000000000..4e3bccb0f --- /dev/null +++ b/crates/agent/src/http.rs @@ -0,0 +1,99 @@ +//! Blocking HTTP for the provider adapters: rustls, no async runtime (the shape `figcraft-mcp` +//! and `collab-net` already use). + +use std::io::{BufRead, BufReader}; +use std::time::Duration; + +use serde_json::Value; + +pub struct Http { + agent: ureq::Agent, +} + +/// A response whose body is still being read (the SSE stream of a model answer). +pub struct Reply { + pub status: u16, + pub body: Box, +} + +impl Http { + pub fn new() -> Self { + let config = ureq::Agent::config_builder() + // A streamed answer can run for minutes: no whole-request deadline, but a stuck + // connection is caught by the per-read limit. + .timeout_global(None) + .timeout_connect(Some(Duration::from_secs(20))) + .timeout_recv_response(Some(Duration::from_secs(120))) + .timeout_per_read(Some(Duration::from_secs(300))) + // A 4xx carries the provider's message: read it, don't turn it into a bare error. + .http_status_as_error(false) + .build(); + Self { agent: config.new_agent() } + } + + fn send(&self, request: ureq::RequestBuilder, headers: &[(&str, String)], body: &Value) -> Result { + let mut request = request; + for (name, value) in headers { + request = request.header(*name, value.clone()); + } + let response = request.send_json(body).map_err(network)?; + let status = response.status().as_u16(); + let body = Box::new(BufReader::new(response.into_body().into_reader())); + Ok(Reply { status, body }) + } + + /// POST JSON and stream the answer back. + pub fn post(&self, url: &str, headers: &[(&str, String)], body: &Value) -> Result { + self.send(self.agent.post(url), headers, body) + } + + /// GET JSON (model lists), with the response body read whole. + pub fn get_json(&self, url: &str, headers: &[(&str, String)]) -> Result { + let mut request = self.agent.get(url); + for (name, value) in headers { + request = request.header(*name, value.clone()); + } + let response = request.call().map_err(network)?; + let status = response.status().as_u16(); + let mut body = response.into_body(); + let text = body.read_to_string().map_err(|e| format!("reading the answer failed: {e}"))?; + if status >= 400 { + return Err(status_message(status, &text)); + } + serde_json::from_str(&text).map_err(|e| format!("the endpoint sent something that is not JSON: {e}")) + } +} + +impl Default for Http { + fn default() -> Self { + Self::new() + } +} + +fn network(e: ureq::Error) -> String { + match e { + ureq::Error::Timeout(t) => format!("the endpoint did not answer in time ({t})"), + ureq::Error::StatusCode(code) => format!("the endpoint answered {code}"), + ureq::Error::Io(e) => format!("network error: {e}"), + other => format!("request failed: {other}"), + } +} + +/// The provider's own error message when it sent one, else the status and the start of the body. +pub fn status_message(status: u16, body: &str) -> String { + if let Ok(v) = serde_json::from_str::(body) + && let Some(m) = v.get("error").and_then(|e| e.get("message")).and_then(Value::as_str) + { + return format!("{status}: {m}"); + } + let head: String = body.chars().take(400).collect(); + format!("{status}: {}", head.trim()) +} + +/// The whole body of a failed reply, for its message. +pub fn read_error(status: u16, body: Box) -> String { + use std::io::Read as _; + let mut text = String::new(); + let _ = body.take(64 * 1024).read_to_string(&mut text); + status_message(status, &text) +} diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs new file mode 100644 index 000000000..37dbcaaae --- /dev/null +++ b/crates/agent/src/lib.rs @@ -0,0 +1,257 @@ +//! FigCraft's in-app agent. +//! +//! Two provider dialects (OpenAI Chat Completions and Anthropic Messages), the tool-call loop on +//! top of [`figcraft_mcp`]'s tool set, and the bridge that lets the loop run on its own thread +//! while the session stays on the UI thread. +//! +//! The app shows a chat panel; the panel owns a [`Worker`], which owns an [`Agent`]. Every tool +//! call goes through [`figcraft_mcp::Backend`], so the in-app agent and an external MCP client +//! behave the same. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod anthropic; +pub mod bridge; +pub mod brief; +pub mod cli; +pub mod config; +pub mod http; +pub mod mcp_http; +pub mod neutral; +pub mod openai; +pub mod session; +pub mod skills; +pub mod sse; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; + +use serde_json::Value; + +pub use config::{AgentsFile, ApiKind, CliPreset, PRESETS, Permission, Preset, Provider, SUBSCRIPTIONS, pick_model}; +pub use session::{AGENT_NAME, Agent, ChatEvent, approval, system_prompt}; + +/// Token counts one request used. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Usage { + pub input: u64, + pub output: u64, +} + +/// One tool call the model asked for. +#[derive(Clone, Debug, PartialEq)] +pub struct Invocation { + pub id: String, + pub name: String, + /// The arguments; `Value::Null` when the model sent text that is not JSON. + pub args: Value, + pub args_raw: String, +} + +/// One streamed model step: its text, its tool calls and what it used. +#[derive(Clone, Debug, Default)] +pub struct Step { + pub text: String, + pub calls: Vec, + pub stop: String, + pub usage: Usage, +} + +/// What the panel tells the worker to do. +pub enum Command { + Turn { + text: String, + context: Option, + /// Images the person attached (references, a render of the selection). + images: Vec, + }, + /// Switch the model (or endpoint) without losing the conversation. + SetProvider(Provider), + /// Move the conversation to another file (the next document's chat): the current one is + /// saved first, then the new one is read if it exists. + SetHistory(Option), + Clear, + Shutdown, +} + +/// The agent thread the panel talks to. It lives as long as the conversation does, keeping the +/// messages (and the provider's prompt cache) between turns. +pub struct Worker { + commands: Sender, + /// Events of the running (or last) turn, drained by the panel every frame. + pub events: Receiver, + /// Set to stop the running turn; the worker clears it when the next one starts. + pub cancel: Arc, + /// 0: ask before file and network tools, 1: auto. + pub permission: Arc, + /// Whether a turn that changes the canvas ends with a look at it. + pub review: Arc, + /// The skills the model can load; the panel keeps it current. + pub skills: skills::SkillBook, + /// False once the thread ended (a panic included), so the panel can say so. + alive: Arc, + handle: Option>, +} + +/// Clears the worker's `alive` flag however the thread ends, a panic included. +struct Alive(Arc); + +impl Drop for Alive { + fn drop(&mut self) { + self.0.store(false, Ordering::Relaxed); + } +} + +impl Worker { + /// Start an agent thread for `provider`, whose tool calls go through `backend`. + pub fn spawn(provider: Provider, backend: bridge::Remote, wake: Arc) -> Self { + let (commands, inbox) = channel::(); + let (out, events) = channel::(); + let cancel = Arc::new(AtomicBool::new(false)); + let permission = Arc::new(AtomicU8::new(0)); + let review = Arc::new(AtomicBool::new(true)); + let skills: skills::SkillBook = Arc::new(std::sync::RwLock::new(skills::builtins())); + let thread_skills = skills.clone(); + let alive = Arc::new(AtomicBool::new(true)); + let thread_cancel = cancel.clone(); + let thread_permission = permission.clone(); + let thread_review = review.clone(); + let thread_alive = alive.clone(); + let handle = std::thread::Builder::new().name("figcraft-agent".into()).spawn(move || { + let _alive = Alive(thread_alive); + let mut agent = Agent::new(provider, backend); + agent.permission = thread_permission; + agent.review = thread_review; + agent.skills = thread_skills; + let mut history: Option = None; + // Every event wakes the window: it is idle between frames and would otherwise show + // the answer only on the next mouse move. + let shared: Arc = Arc::new(move |event: ChatEvent| { + let _ = out.send(event); + wake(); + }); + agent.sink = Some(shared.clone()); + let sink = |event: ChatEvent| shared(event); + while let Ok(command) = inbox.recv() { + match command { + Command::Turn { text, context, images } => { + thread_cancel.store(false, Ordering::Relaxed); + match agent.run_turn_with(&text, context, images, &sink, &thread_cancel) { + Ok(()) => {} + Err(e) => { + sink(ChatEvent::Error(e)); + sink(ChatEvent::Done { stopped: false }); + } + } + if let Some(path) = &history { + let _ = agent.save_history(path); + } + } + Command::Clear => { + agent.clear(); + if let Some(path) = &history { + let _ = agent.save_history(path); + } + } + Command::SetProvider(p) => agent.set_provider(p), + Command::SetHistory(path) => { + if let Some(old) = history.as_ref() { + let _ = agent.save_history(old); + } + history = path; + // The next conversation starts empty unless its own file holds one: the + // last one's messages must not carry over. + agent.clear(); + // A command-line agent runs beside the saved chats, never in a project. + if let Some(dir) = history.as_deref().and_then(std::path::Path::parent) { + agent.workdir = Some(dir.join("cli")); + } + if let Some(new) = history.as_ref() { + let _ = agent.load_history(new); + } + } + Command::Shutdown => break, + } + } + }); + Self { commands, events, cancel, permission, review, skills, alive, handle: handle.ok() } + } + + pub fn send_turn(&self, text: String, context: Option) -> Result<(), String> { + self.send_turn_with(text, context, Vec::new()) + } + + /// [`send_turn`](Self::send_turn) with images attached to the request. + pub fn send_turn_with(&self, text: String, context: Option, images: Vec) -> Result<(), String> { + self.commands.send(Command::Turn { text, context, images }).map_err(|_| "the agent thread stopped".to_string()) + } + + pub fn clear(&self) -> Result<(), String> { + self.commands.send(Command::Clear).map_err(|_| "the agent thread stopped".to_string()) + } + + pub fn set_provider(&self, provider: Provider) -> Result<(), String> { + self.commands.send(Command::SetProvider(provider)).map_err(|_| "the agent thread stopped".to_string()) + } + + /// Ask the running turn to stop; the layer edits it already made stay. + pub fn stop(&self) { + self.cancel.store(true, Ordering::Relaxed); + } + + pub fn set_auto(&self, auto: bool) { + self.permission.store(u8::from(auto), Ordering::Relaxed); + } + + pub fn set_review(&self, on: bool) { + self.review.store(on, Ordering::Relaxed); + } + + /// False once the agent thread ended (a panic included). + pub fn alive(&self) -> bool { + self.alive.load(Ordering::Relaxed) + } + + /// Move the conversation to another file (the next document's chat). + pub fn set_history(&self, path: Option) -> Result<(), String> { + self.commands.send(Command::SetHistory(path)).map_err(|_| "the agent thread stopped".to_string()) + } +} + +impl Drop for Worker { + fn drop(&mut self) { + let _ = self.commands.send(Command::Shutdown); + // The thread may be waiting on the network; it ends after that answer. Dropping the + // handle detaches it rather than blocking the UI thread here. + self.handle.take(); + } +} + +/// The model ids an endpoint lists (`GET {base}/models`). +pub fn list_models(provider: &Provider) -> Result, String> { + let http = http::Http::new(); + let url = format!("{}/models", provider.base_url.trim_end_matches('/')); + if provider.kind.is_cli() { + return cli::models(provider.kind).ok_or_else(|| format!("{} keeps its own model list", provider.kind.label())); + } + let mut headers: Vec<(&str, String)> = match provider.kind { + ApiKind::AnthropicMessages => vec![("x-api-key", provider.api_key.trim().to_string()), ("anthropic-version", "2023-06-01".to_string())], + _ => vec![("authorization", format!("Bearer {}", provider.api_key.trim()))], + }; + if provider.api_key.trim().is_empty() { + headers.retain(|(k, _)| *k == "anthropic-version"); + } + let v = http.get_json(&url, &headers)?; + let mut ids: Vec = v + .get("data") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|m| m.get("id").and_then(Value::as_str).map(str::to_string)).collect()) + .unwrap_or_default(); + ids.sort(); + ids.dedup(); + if ids.is_empty() { + return Err("the endpoint listed no models; type the model id instead".into()); + } + Ok(ids) +} diff --git a/crates/agent/src/mcp_http.rs b/crates/agent/src/mcp_http.rs new file mode 100644 index 000000000..3f95cd590 --- /dev/null +++ b/crates/agent/src/mcp_http.rs @@ -0,0 +1,458 @@ +//! FigCraft's tools for a command-line agent (Claude Code, Codex, OpenCode). +//! +//! Those programs run their own loop and reach tools over MCP. This serves the same tool set the +//! in-app loop uses ([`figcraft_mcp::Server`] over the [`Remote`](crate::bridge::Remote) bridge) on +//! a loopback HTTP endpoint for the length of the conversation: one JSON-RPC message per `POST`, +//! answered as `application/json` (MCP's Streamable HTTP transport without server-sent events). +//! +//! Only this app's child processes are meant to call it: it listens on 127.0.0.1 only, refuses a +//! request without the bearer token handed to the child, and refuses browser requests (an `Origin` +//! header, or a `Host` that is not loopback). Tool calls pass the same Ask/Auto gate as the in-app +//! loop, and report to the panel the same way. + +use std::io::{BufRead, BufReader, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::bridge::Remote; +use crate::session::ChatEvent; + +/// The largest request body accepted (tool arguments are small; an image goes the other way). +const MAX_BODY: usize = 16 * 1024 * 1024; +/// The largest header block accepted. +const MAX_HEADERS: usize = 64 * 1024; + +/// Where a tool call reports to the panel, and how much it may do without asking. +#[derive(Clone)] +pub struct Gate { + /// 0: ask before file and network tools, 1: auto (shared with the panel's toggle). + pub permission: Arc, + /// The panel's event stream. + pub sink: Arc, + /// Set by Stop: calls still arriving are refused. + pub cancel: Arc, + /// Set when a call changed the document, so the turn can end with a look at the canvas. + pub edited: Arc, + /// The skills `load_skill` answers from (a tool this endpoint adds to FigCraft's own). + pub skills: crate::skills::SkillBook, +} + +/// A running endpoint; dropping it stops the listener. +pub struct Endpoint { + pub url: String, + pub token: String, + stop: Arc, + port: u16, +} + +impl Drop for Endpoint { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + // Wake the blocking accept so the thread sees the flag. + let _ = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(200)); + } +} + +/// One JSON-RPC message on its way to the server thread, and where its answer goes. +type Job = (Value, Sender>); + +/// Start serving FigCraft's tools on a free loopback port. +pub fn start(remote: Remote, gate: Gate) -> std::io::Result { + let listener = TcpListener::bind(("127.0.0.1", 0))?; + let port = listener.local_addr()?.port(); + let token = new_token().map_err(std::io::Error::other)?; + let stop = Arc::new(AtomicBool::new(false)); + + // The MCP server is not `Send` (its backend is a trait object), so it lives on one thread and + // the connections hand it messages. + let (jobs, inbox) = channel::(); + std::thread::Builder::new().name("figcraft-agent-mcp".into()).spawn(move || serve_jobs(remote, gate, inbox))?; + + let accept_stop = stop.clone(); + let accept_token = token.clone(); + std::thread::Builder::new().name("figcraft-agent-mcp-accept".into()).spawn(move || { + for stream in listener.incoming() { + if accept_stop.load(Ordering::Relaxed) { + break; + } + let Ok(stream) = stream else { continue }; + let jobs = jobs.clone(); + let token = accept_token.clone(); + let _ = std::thread::Builder::new().name("figcraft-agent-mcp-conn".into()).spawn(move || connection(stream, &token, &jobs)); + } + })?; + Ok(Endpoint { url: format!("http://127.0.0.1:{port}/mcp"), token, stop, port }) +} + +fn serve_jobs(remote: Remote, gate: Gate, inbox: Receiver) { + let mut own = remote.clone(); + let mut server = figcraft_mcp::Server::new(Box::new(remote)); + while let Ok((msg, reply)) = inbox.recv() { + let answer = handle_gated(&mut server, &mut own, &gate, msg); + let _ = reply.send(answer); + } +} + +/// Run one message, with `tools/call` going through the Ask/Auto gate and reported to the panel. +fn handle_gated(server: &mut figcraft_mcp::Server, own: &mut Remote, gate: &Gate, msg: Value) -> Option { + match msg.get("method").and_then(Value::as_str) { + Some("tools/call") => {} + Some("tools/list") => { + let mut answer = server.handle(msg)?; + if let Some(tools) = answer.pointer_mut("/result/tools").and_then(Value::as_array_mut) { + tools.push(crate::skills::tool_definition()); + tools.push(crate::brief::tool_definition()); + } + return Some(answer); + } + _ => return server.handle(msg), + } + let id = msg.get("id").cloned().unwrap_or(Value::Null); + let params = msg.get("params").cloned().unwrap_or(Value::Null); + let name = params.get("name").and_then(Value::as_str).unwrap_or("").to_string(); + let args = params.get("arguments").cloned().unwrap_or_else(|| json!({})); + let call_id = id.to_string(); + let refuse = |text: String| Some(json!({"jsonrpc": "2.0", "id": id, "result": {"content": [{"type": "text", "text": text}], "isError": true}})); + + (gate.sink)(ChatEvent::ToolStart { id: call_id.clone(), name: name.clone(), args: args.clone() }); + // A call that arrives after Stop runs nothing, FigCraft's own tools included. + if gate.cancel.load(Ordering::Relaxed) { + (gate.sink)(ChatEvent::ToolEnd { id: call_id, name: name.clone(), ok: false, title: name, text: "Stopped by the user".into() }); + return refuse("Not run: the user stopped the agent".into()); + } + if name == crate::brief::TOOL_NAME { + let (text, ok) = crate::brief::call(own, &args); + if ok && (args.get("spec").is_some() || args.get("brief").is_some()) { + gate.edited.store(true, Ordering::Relaxed); + } + (gate.sink)(ChatEvent::ToolEnd { + id: call_id, + name: name.clone(), + ok, + title: crate::session::tool_title(&name, &args), + text: crate::session::summarize(&text), + }); + return Some(json!({"jsonrpc": "2.0", "id": id, "result": {"content": [{"type": "text", "text": text}], "isError": !ok}})); + } + if name == crate::skills::TOOL_NAME { + let (text, ok) = crate::skills::call(&gate.skills, &args); + (gate.sink)(ChatEvent::ToolEnd { + id: call_id, + name: name.clone(), + ok, + title: crate::session::tool_title(&name, &args), + text: crate::session::summarize(&text), + }); + return Some(json!({"jsonrpc": "2.0", "id": id, "result": {"content": [{"type": "text", "text": text}], "isError": !ok}})); + } + if let Some(reason) = crate::session::approval(&name, &args) + && gate.permission.load(Ordering::Relaxed) == 0 + { + let (tx, rx) = channel(); + (gate.sink)(ChatEvent::Permission { id: call_id.clone(), name: name.clone(), args: args.clone(), reason: reason.clone(), reply: tx }); + if !rx.recv_timeout(Duration::from_secs(600)).unwrap_or(false) { + (gate.sink)(ChatEvent::ToolEnd { id: call_id, name: name.clone(), ok: false, title: name, text: "Denied by the user".into() }); + return refuse(format!("Not run: the user denied this action ({reason})")); + } + // Stop may have come while the Allow was waiting. + if gate.cancel.load(Ordering::Relaxed) { + (gate.sink)(ChatEvent::ToolEnd { id: call_id, name: name.clone(), ok: false, title: name, text: "Stopped by the user".into() }); + return refuse("Not run: the user stopped the agent".into()); + } + } + let answer = server.handle(msg); + let result = answer.as_ref().and_then(|a| a.get("result")); + let ok = result.is_some_and(|r| !r.get("isError").and_then(Value::as_bool).unwrap_or(false)); + if ok && crate::session::mutating(&name, &args) { + gate.edited.store(true, Ordering::Relaxed); + } + let text = result + .and_then(|r| r.get("content")) + .and_then(Value::as_array) + .and_then(|c| c.iter().find_map(|b| b.get("text").and_then(Value::as_str))) + .map(str::to_string) + .or_else(|| answer.as_ref().and_then(|a| a.pointer("/error/message")).and_then(Value::as_str).map(str::to_string)) + .unwrap_or_default(); + (gate.sink)(ChatEvent::ToolEnd { + id: call_id, + name: name.clone(), + ok, + title: crate::session::tool_title(&name, &args), + text: crate::session::summarize(&text), + }); + answer +} + +/// Serve one keep-alive connection until it closes or sends something unreadable. +fn connection(stream: TcpStream, token: &str, jobs: &Sender) { + let _ = stream.set_read_timeout(Some(Duration::from_secs(900))); + let Ok(mut out) = stream.try_clone() else { return }; + let mut reader = BufReader::new(stream); + loop { + let request = match read_request(&mut reader) { + Ok(Some(r)) => r, + Ok(None) => return, + Err(status) => { + let _ = write_response(&mut out, &Response::status(status)); + return; + } + }; + let close = request.header("connection").is_some_and(|v| v.eq_ignore_ascii_case("close")); + let response = respond(&request, token, &mut |msg| { + let (tx, rx) = channel(); + if jobs.send((msg, tx)).is_err() { + return None; + } + rx.recv().ok().flatten() + }); + if write_response(&mut out, &response).is_err() || close { + return; + } + } +} + +/// One HTTP request as read off the socket. +pub struct Request { + pub method: String, + pub path: String, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Request { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) + } +} + +pub struct Response { + pub status: u16, + pub body: Vec, +} + +impl Response { + fn status(status: u16) -> Self { + Self { status, body: Vec::new() } + } +} + +/// Answer one request: the checks, then the JSON-RPC message (or batch) through `forward`. +pub fn respond(req: &Request, token: &str, forward: &mut dyn FnMut(Value) -> Option) -> Response { + if req.header("origin").is_some() { + return Response::status(403); + } + let host = req.header("host").unwrap_or(""); + let host_name = host.rsplit_once(':').map_or(host, |(h, _)| h); + if !matches!(host_name, "127.0.0.1" | "localhost" | "[::1]") { + return Response::status(403); + } + let authorized = req.header("authorization").and_then(|v| v.strip_prefix("Bearer ")).is_some_and(|t| same(t.trim(), token)); + if !authorized { + return Response::status(401); + } + if req.path.split('?').next() != Some("/mcp") { + return Response::status(404); + } + match req.method.as_str() { + "POST" => {} + // No server-initiated stream and no sessions to end. + _ => return Response::status(405), + } + let Ok(msg) = serde_json::from_slice::(&req.body) else { + let body = json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": "parse error"}}); + return Response { status: 400, body: body.to_string().into_bytes() }; + }; + let answer = match msg { + Value::Array(batch) => { + let answers: Vec = batch.into_iter().filter_map(&mut *forward).collect(); + if answers.is_empty() { None } else { Some(Value::Array(answers)) } + } + one => forward(one), + }; + match answer { + Some(a) => Response { status: 200, body: a.to_string().into_bytes() }, + // A notification or a client's response: accepted, nothing to say. + None => Response::status(202), + } +} + +/// Compare without stopping at the first different byte. +fn same(a: &str, b: &str) -> bool { + a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// Read one request; `Ok(None)` when the peer closed the connection between requests, `Err` with +/// the status to answer for a request this server will not read. +fn read_request(reader: &mut impl BufRead) -> Result, u16> { + let line = match read_line_limited(reader, MAX_HEADERS) { + Ok(Some(l)) => l, + Ok(None) => return Ok(None), + Err(LineError::TooLong) => return Err(431), + Err(LineError::Io) => return Ok(None), + }; + let mut parts = line.split_whitespace(); + let (Some(method), Some(path)) = (parts.next(), parts.next()) else { return Err(400) }; + let (method, path) = (method.to_string(), path.to_string()); + let mut headers = Vec::new(); + let mut size = line.len(); + loop { + let h = match read_line_limited(reader, MAX_HEADERS.saturating_sub(size)) { + Ok(Some(h)) => h, + Ok(None) | Err(LineError::Io) => return Err(400), + Err(LineError::TooLong) => return Err(431), + }; + size += h.len(); + if size > MAX_HEADERS { + return Err(431); + } + let h = h.trim_end_matches(['\r', '\n']); + if h.is_empty() { + break; + } + if let Some((k, v)) = h.split_once(':') { + headers.push((k.trim().to_string(), v.trim().to_string())); + } + } + let req = Request { method, path, headers, body: Vec::new() }; + if req.header("transfer-encoding").is_some() { + return Err(411); + } + let length = match req.header("content-length") { + Some(v) => v.parse::().map_err(|_| 400u16)?, + None => 0, + }; + if length > MAX_BODY { + return Err(413); + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).map_err(|_| 400u16)?; + Ok(Some(Request { body, ..req })) +} + +enum LineError { + TooLong, + Io, +} + +/// One line of at most `limit` bytes, read without keeping more than that; `None` at the end. +fn read_line_limited(reader: &mut impl BufRead, limit: usize) -> Result, LineError> { + use std::io::Read as _; + let mut bytes = Vec::new(); + let read = reader.by_ref().take(limit as u64 + 1).read_until(b'\n', &mut bytes).map_err(|_| LineError::Io)?; + if read == 0 { + return Ok(None); + } + if bytes.len() > limit { + return Err(LineError::TooLong); + } + Ok(Some(String::from_utf8_lossy(&bytes).into_owned())) +} + +fn write_response(out: &mut impl Write, r: &Response) -> std::io::Result<()> { + let reason = match r.status { + 200 => "OK", + 202 => "Accepted", + 400 => "Bad Request", + 401 => "Unauthorized", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 411 => "Length Required", + 413 => "Payload Too Large", + 431 => "Request Header Fields Too Large", + _ => "Error", + }; + let mut head = format!("HTTP/1.1 {} {reason}\r\nContent-Length: {}\r\n", r.status, r.body.len()); + if !r.body.is_empty() { + head.push_str("Content-Type: application/json\r\n"); + } + if r.status == 405 { + head.push_str("Allow: POST\r\n"); + } + head.push_str("\r\n"); + out.write_all(head.as_bytes())?; + out.write_all(&r.body)?; + out.flush() +} + +/// 128 random bits as hex, from the operating system's secure random number generator. +fn new_token() -> Result { + let mut b = [0u8; 16]; + getrandom::fill(&mut b).map_err(|e| format!("no secure random numbers: {e}"))?; + Ok(b.iter().map(|x| format!("{x:02x}")).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(headers: &[(&str, &str)], body: &str) -> Request { + Request { + method: "POST".into(), + path: "/mcp".into(), + headers: headers.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), + body: body.as_bytes().to_vec(), + } + } + + fn echo(msg: Value) -> Option { + msg.get("id").map(|id| json!({"jsonrpc": "2.0", "id": id, "result": {}})) + } + + #[test] + fn only_the_child_with_the_token_reaches_the_tools() { + let body = r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#; + let ok = respond(&request(&[("Host", "127.0.0.1:5"), ("Authorization", "Bearer secret")], body), "secret", &mut echo); + assert_eq!(ok.status, 200); + let none = respond(&request(&[("Host", "127.0.0.1:5")], body), "secret", &mut echo); + assert_eq!(none.status, 401); + let wrong = respond(&request(&[("Host", "127.0.0.1:5"), ("Authorization", "Bearer secreT")], body), "secret", &mut echo); + assert_eq!(wrong.status, 401); + let browser = respond( + &request(&[("Host", "127.0.0.1:5"), ("Origin", "https://x.test"), ("Authorization", "Bearer secret")], body), + "secret", + &mut echo, + ); + assert_eq!(browser.status, 403, "a page in a browser is refused even with the token"); + let rebound = respond(&request(&[("Host", "evil.test:5"), ("Authorization", "Bearer secret")], body), "secret", &mut echo); + assert_eq!(rebound.status, 403, "a rebound host name is refused"); + } + + #[test] + fn a_notification_is_accepted_without_a_body() { + let r = respond( + &request(&[("Host", "localhost:1"), ("Authorization", "Bearer t")], r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#), + "t", + &mut echo, + ); + assert_eq!(r.status, 202); + assert!(r.body.is_empty()); + } + + #[test] + fn a_request_is_read_with_its_body_and_the_next_one_waits() { + let raw = "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 2\r\n\r\n{}POST"; + let mut reader = BufReader::new(raw.as_bytes()); + let r = read_request(&mut reader).ok().flatten().expect("a request"); + assert_eq!(r.body, b"{}"); + assert!(read_request(&mut reader).is_err(), "a cut-off request is refused, not waited on forever"); + } + + #[test] + fn an_endless_header_is_refused_before_it_is_all_read() { + let raw = format!("POST /mcp HTTP/1.1\r\nX-Long: {}", "a".repeat(MAX_HEADERS * 2)); + let mut reader = BufReader::new(raw.as_bytes()); + assert_eq!(read_request(&mut reader).err(), Some(431)); + } + + #[test] + fn tokens_differ() { + assert_ne!(new_token(), new_token()); + assert_eq!(new_token().map(|t| t.len()), Ok(32)); + } +} diff --git a/crates/agent/src/neutral.rs b/crates/agent/src/neutral.rs new file mode 100644 index 000000000..a9d3d46ed --- /dev/null +++ b/crates/agent/src/neutral.rs @@ -0,0 +1,183 @@ +//! The conversation in a provider-neutral shape: messages made of text, image, tool-call and +//! tool-result blocks. Each adapter translates these to its wire format, so switching provider +//! keeps the history. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +/// One image travelling with a message: base64 data and its media type. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Image { + pub mime: String, + pub data: String, +} + +/// A piece of a message. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum Block { + Text(String), + Image(Image), + /// The model asked for a tool. + ToolCall { + id: String, + name: String, + args: Value, + }, + /// What the tool returned, for the model to read on the next step. + ToolResult { + id: String, + name: String, + ok: bool, + text: String, + images: Vec, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Role { + User, + Assistant, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Message { + pub role: Role, + pub blocks: Vec, +} + +impl Message { + pub fn user_text(text: impl Into) -> Self { + Self { role: Role::User, blocks: vec![Block::Text(text.into())] } + } + + /// The message as plain text (`None` when it holds anything but text). + pub fn as_text(&self) -> Option { + let mut out = String::new(); + for block in &self.blocks { + match block { + Block::Text(t) => out.push_str(t), + _ => return None, + } + } + Some(out) + } +} + +/// The MCP tool definitions as OpenAI Chat Completions tools. +pub fn openai_tools(defs: &[Value]) -> Vec { + defs.iter() + .filter_map(|d| { + let name = d.get("name")?.as_str()?; + Some(json!({ + "type": "function", + "function": { + "name": name, + "description": d.get("description").and_then(Value::as_str).unwrap_or(""), + "parameters": d.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object", "properties": {}})), + } + })) + }) + .collect() +} + +/// The MCP tool definitions as Anthropic Messages tools. +pub fn anthropic_tools(defs: &[Value]) -> Vec { + defs.iter() + .filter_map(|d| { + let name = d.get("name")?.as_str()?; + Some(json!({ + "name": name, + "description": d.get("description").and_then(Value::as_str).unwrap_or(""), + "input_schema": d.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object", "properties": {}})), + })) + }) + .collect() +} + +/// One tool result from an MCP [`figcraft_mcp::ToolResult`]: its text and any images. +pub fn tool_output(result: &figcraft_mcp::ToolResult) -> (String, Vec) { + let mut text = String::new(); + let mut images = Vec::new(); + for c in &result.content { + match c.get("type").and_then(Value::as_str) { + Some("text") => { + let t = c.get("text").and_then(Value::as_str).unwrap_or(""); + if !text.is_empty() && !t.is_empty() { + text.push('\n'); + } + text.push_str(t); + } + Some("image") => { + let mime = c.get("mimeType").and_then(Value::as_str).unwrap_or("image/png"); + if let Some(data) = c.get("data").and_then(Value::as_str) { + images.push(Image { mime: mime.to_string(), data: data.to_string() }); + } + } + _ => {} + } + } + (text, images) +} + +/// Cut a tool's text to a size a model can take, keeping both ends: the start names what ran and +/// the end holds the error or the summary. +pub fn clip(text: &str, max: usize) -> String { + if text.len() <= max { + return text.to_string(); + } + let keep = max.saturating_div(2); + let mut start = keep; + while start > 0 && !text.is_char_boundary(start) { + start -= 1; + } + let mut end = text.len() - keep; + while end < text.len() && !text.is_char_boundary(end) { + end += 1; + } + format!("{}\n…[{} bytes left out]…\n{}", &text[..start], end - start, &text[end..]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tools_keep_their_schema_in_both_dialects() { + let defs = vec![json!({ + "name": "create_node", + "description": "Create a layer", + "inputSchema": {"type": "object", "properties": {"type": {"type": "string"}}} + })]; + let o = openai_tools(&defs); + assert_eq!(o[0]["function"]["name"], "create_node"); + assert_eq!(o[0]["function"]["parameters"]["properties"]["type"]["type"], "string"); + let a = anthropic_tools(&defs); + assert_eq!(a[0]["name"], "create_node"); + assert_eq!(a[0]["input_schema"]["type"], "object"); + } + + #[test] + fn tool_output_separates_text_and_images() { + let r = figcraft_mcp::ToolResult { + content: vec![ + json!({"type": "text", "text": "hello"}), + json!({"type": "image", "mimeType": "image/png", "data": "AAAA"}), + json!({"type": "text", "text": "world"}), + ], + is_error: false, + }; + let (text, images) = tool_output(&r); + assert_eq!(text, "hello\nworld"); + assert_eq!(images.len(), 1); + assert_eq!(images[0].mime, "image/png"); + } + + #[test] + fn clipping_keeps_both_ends_and_stays_on_char_boundaries() { + let s = format!("start{}end", "é".repeat(100)); + let out = clip(&s, 40); + assert!(out.starts_with("start")); + assert!(out.ends_with("end")); + assert!(out.len() < s.len()); + } +} diff --git a/crates/agent/src/openai.rs b/crates/agent/src/openai.rs new file mode 100644 index 000000000..b52958c96 --- /dev/null +++ b/crates/agent/src/openai.rs @@ -0,0 +1,284 @@ +//! The OpenAI Chat Completions dialect: most gateways speak it (OpenAI, OpenCode Zen/Go, +//! OpenRouter, DeepSeek, Ollama, LM Studio and custom endpoints). + +use std::collections::BTreeMap; +use std::sync::atomic::AtomicBool; + +use serde_json::{Value, json}; + +use crate::config::Provider; +use crate::http::{Http, read_error}; +use crate::neutral::{Block, Message, Role}; +use crate::{Invocation, Step, Usage}; + +/// What a stream that ended before the answer did is reported as. +pub const INTERRUPTED: &str = "the connection closed before the answer finished; ask the agent to continue"; + +/// The request body for one step of the conversation. +pub fn payload(provider: &Provider, system: &str, messages: &[Message], tools: &[Value]) -> Value { + let mut body = json!({ + "model": provider.model, + "messages": wire_messages(system, messages), + "stream": true, + "stream_options": {"include_usage": true}, + }); + if let Some(effort) = provider.reasoning.effort() { + body["reasoning_effort"] = json!(effort); + } + let tools = crate::neutral::openai_tools(tools); + if !tools.is_empty() { + body["tools"] = json!(tools); + body["tool_choice"] = json!("auto"); + } + body +} + +fn wire_messages(system: &str, messages: &[Message]) -> Vec { + let mut out = vec![json!({"role": "system", "content": system})]; + for m in messages { + match m.role { + Role::Assistant => { + let mut text = String::new(); + let mut calls = Vec::new(); + for b in &m.blocks { + match b { + Block::Text(t) => text.push_str(t), + Block::ToolCall { id, name, args } => calls.push(json!({ + "id": id, + "type": "function", + "function": {"name": name, "arguments": serde_json::to_string(args).unwrap_or_else(|_| "{}".into())}, + })), + _ => {} + } + } + let mut msg = json!({"role": "assistant", "content": if text.is_empty() { Value::Null } else { json!(text) }}); + if !calls.is_empty() { + msg["tool_calls"] = json!(calls); + } + out.push(msg); + } + Role::User => { + let mut content = Vec::new(); + // Images from tool results cannot ride in the `tool` role's text, so they follow + // in a user message (every compatible endpoint accepts that). + let mut tool_images = Vec::new(); + for b in &m.blocks { + match b { + Block::Text(t) => content.push(json!({"type": "text", "text": t})), + Block::Image(i) => content.push(json!({"type": "image_url", "image_url": {"url": data_url(i)}})), + Block::ToolResult { id, text, images, .. } => { + out.push(json!({"role": "tool", "tool_call_id": id, "content": text})); + tool_images.extend(images.iter().map(data_url)); + } + Block::ToolCall { .. } => {} + } + } + if !content.is_empty() { + out.push(json!({"role": "user", "content": content})); + } + if !tool_images.is_empty() { + let mut parts = vec![json!({"type": "text", "text": "Images from the tool results above:"})]; + for url in tool_images { + parts.push(json!({"type": "image_url", "image_url": {"url": url}})); + } + out.push(json!({"role": "user", "content": parts})); + } + } + } + } + out +} + +fn data_url(image: &crate::neutral::Image) -> String { + format!("data:{};base64,{}", image.mime, image.data) +} + +fn headers(provider: &Provider, session: &str) -> Vec<(&'static str, String)> { + let mut h = vec![("authorization", format!("Bearer {}", provider.api_key.trim())), ("accept", "text/event-stream".to_string())]; + // OpenCode Zen/Go asks for one stable id per conversation, to route it to the same upstream + // and keep its prompt cache warm. + if provider.base_url.contains("opencode.ai") { + h.push(("x-opencode-session", session.to_string())); + } + h +} + +/// Send the conversation and read the streamed answer into a [`Step`]. +pub fn stream( + http: &Http, + provider: &Provider, + system: &str, + messages: &[Message], + tools: &[Value], + session: &str, + on_text: &mut dyn FnMut(&str), + cancel: &AtomicBool, +) -> Result { + let reply = http.post(&provider.endpoint(), &headers(provider, session), &payload(provider, system, messages, tools))?; + if reply.status >= 400 { + return Err(read_error(reply.status, reply.body)); + } + let events = crate::sse::spawn_events(reply.body); + let mut step = Step::default(); + // Whether the endpoint said the answer is over (`finish_reason` or `[DONE]`); a stream that + // just ends without it was cut off. + let mut finished = false; + // Tool calls arrive split across chunks: keyed by their `index`, their name once, their + // arguments as JSON text joined together. + let mut calls: BTreeMap = BTreeMap::new(); + while let Some(event) = crate::sse::next(&events, cancel)? { + let data = event.data.trim(); + if data.is_empty() { + continue; + } + if data == "[DONE]" { + finished = true; + break; + } + let v: Value = match serde_json::from_str(data) { + Ok(v) => v, + // An endpoint may send a keep-alive payload that is not JSON. + Err(_) => continue, + }; + if let Some(err) = v.get("error").filter(|e| !e.is_null()) { + let msg = err.get("message").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| err.to_string()); + return Err(msg); + } + if let Some(u) = v.get("usage").filter(|u| !u.is_null()) { + step.usage = Usage { + input: u.get("prompt_tokens").and_then(Value::as_u64).unwrap_or(step.usage.input), + output: u.get("completion_tokens").and_then(Value::as_u64).unwrap_or(step.usage.output), + }; + } + let Some(choice) = v.get("choices").and_then(|c| c.get(0)) else { continue }; + if let Some(delta) = choice.get("delta") { + match delta.get("content") { + Some(Value::String(t)) => { + step.text.push_str(t); + on_text(t); + } + Some(Value::Array(parts)) => { + for part in parts { + if part.get("type").and_then(Value::as_str) == Some("text") + && let Some(t) = part.get("text").and_then(Value::as_str) + { + step.text.push_str(t); + on_text(t); + } + } + } + _ => {} + } + if let Some(list) = delta.get("tool_calls").and_then(Value::as_array) { + for tc in list { + let index = tc.get("index").and_then(Value::as_u64).unwrap_or(0); + let entry = calls.entry(index).or_default(); + if let Some(id) = tc.get("id").and_then(Value::as_str) { + entry.0 = id.to_string(); + } + if let Some(name) = tc.get("function").and_then(|f| f.get("name")).and_then(Value::as_str) { + entry.1.push_str(name); + } + if let Some(args) = tc.get("function").and_then(|f| f.get("arguments")).and_then(Value::as_str) { + entry.2.push_str(args); + } + } + } + } + if let Some(reason) = choice.get("finish_reason").and_then(Value::as_str) { + step.stop = reason.to_string(); + finished = true; + } + } + if !finished { + return Err(INTERRUPTED.to_string()); + } + for (i, (id, name, raw)) in calls { + if name.is_empty() { + continue; + } + let id = if id.is_empty() { format!("call_{i}") } else { id }; + step.calls.push(Invocation { id, name, args: parse_args(&raw), args_raw: raw }); + } + Ok(step) +} + +fn parse_args(raw: &str) -> Value { + if raw.trim().is_empty() { + return json!({}); + } + serde_json::from_str(raw).unwrap_or(Value::Null) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::ApiKind; + + fn provider() -> Provider { + let mut p = Provider::new("Go", ApiKind::OpenAiCompletions, "https://opencode.ai/zen/go/v1"); + p.model = "deepseek-v4.1-flash".into(); + p.api_key = "sk-test".into(); + p + } + + #[test] + fn tool_calls_and_tool_results_use_the_compatible_shape() { + let mut messages = vec![Message::user_text("hi")]; + messages.push(Message { + role: Role::Assistant, + blocks: vec![ + Block::Text("looking".into()), + Block::ToolCall { id: "call_1".into(), name: "run_command".into(), args: json!({"command": "frame.create"}) }, + ], + }); + messages.push(Message { + role: Role::User, + blocks: vec![Block::ToolResult { id: "call_1".into(), name: "run_command".into(), ok: true, text: "{\"id\":3}".into(), images: vec![] }], + }); + let body = payload(&provider(), "system", &messages, &[]); + let wire = body["messages"].as_array().cloned().unwrap_or_default(); + assert_eq!(wire[0]["role"], "system"); + assert_eq!(wire[1]["content"][0]["text"], "hi"); + assert_eq!(wire[2]["tool_calls"][0]["function"]["name"], "run_command"); + assert_eq!(wire[3]["role"], "tool"); + assert_eq!(wire[3]["tool_call_id"], "call_1"); + } + + #[test] + fn an_image_comes_back_as_a_data_url_on_the_user_message() { + let messages = vec![Message { + role: Role::User, + blocks: vec![Block::Text("what is this".into()), Block::Image(crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() })], + }]; + let body = payload(&provider(), "s", &messages, &[]); + let parts = body["messages"][1]["content"].as_array().cloned().unwrap_or_default(); + assert_eq!(parts[0]["type"], "text"); + assert_eq!(parts[1]["image_url"]["url"], "data:image/png;base64,AAAA"); + } + + #[test] + fn reasoning_effort_is_sent_only_when_chosen() { + use crate::config::Reasoning; + let mut p = provider(); + let messages = vec![Message::user_text("hi")]; + assert!(payload(&p, "s", &messages, &[]).get("reasoning_effort").is_none(), "Auto leaves it to the endpoint"); + p.reasoning = Reasoning::High; + assert_eq!(payload(&p, "s", &messages, &[])["reasoning_effort"], "high"); + } + + #[test] + fn opencode_gets_a_stable_session_header() { + let h = headers(&provider(), "abc"); + assert!(h.iter().any(|(k, v)| *k == "x-opencode-session" && v == "abc")); + assert!(h.iter().any(|(k, v)| *k == "authorization" && v == "Bearer sk-test")); + } + + #[test] + fn arguments_that_do_not_parse_stay_null_for_the_loop_to_report() { + let mut calls: BTreeMap = BTreeMap::new(); + calls.insert(0, ("id".into(), "run_command".into(), "{broken".into())); + let (_, _, raw) = calls.remove(&0).unwrap_or_default(); + assert!(parse_args(&raw).is_null()); + } +} diff --git a/crates/agent/src/session.rs b/crates/agent/src/session.rs new file mode 100644 index 000000000..30019c840 --- /dev/null +++ b/crates/agent/src/session.rs @@ -0,0 +1,886 @@ +//! The agent loop: send the conversation, stream the answer, run the tools the model asks for on +//! the open window, feed the results back, and repeat until it stops asking for tools. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::mpsc::Sender; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::config::{ApiKind, Permission, Provider}; +use crate::http::Http; +use crate::neutral::{Block, Message, Role}; +use crate::{Invocation, Step, Usage}; + +/// How many model steps one request may take before the loop stops (each step may run tools). +const MAX_STEPS: usize = 60; +/// Characters of conversation kept before the oldest tool output is shortened, per the model's +/// context window (about three characters a token, with room for the answer). +const CHARS_PER_TOKEN: usize = 3; +/// Tool output longer than this is clipped before the model sees it. +const TOOL_TEXT_MAX: usize = 60_000; +/// The name every command runs as in the app (its avatar, its comment signature). +pub const AGENT_NAME: &str = "FigCraft Agent"; +/// What the agent is told when it is handed the canvas to check its own work. +const REVIEW_PROMPT: &str = "Automatic self-review: the canvas after your changes is attached. \ +Compare it with what the user asked for. Fix anything wrong with the tools (overlap, clipping, \ +spacing, hierarchy, contrast, text that does not fit). If it looks right, reply to the user in one \ +or two sentences; do not take another screenshot for review. +"; + +/// What the worker tells the panel while a request runs. +pub enum ChatEvent { + /// Streamed answer text. + Text(String), + /// A tool call started. + ToolStart { id: String, name: String, args: Value }, + /// A tool call finished (`text` is a short summary for the card). + ToolEnd { id: String, name: String, ok: bool, title: String, text: String }, + /// The agent wants to do something outside the canvas; `reply` takes the person's answer. + Permission { id: String, name: String, args: Value, reason: String, reply: Sender }, + /// Tokens used so far. + Usage(Usage), + /// The request failed (network, provider, a bad answer). + Error(String), + /// The request is over. `stopped`: the person pressed Stop. + Done { stopped: bool }, +} + +/// An agent bound to one window, with the conversation it has had so far. +pub struct Agent { + pub provider: Provider, + pub messages: Vec, + http: Http, + backend: crate::bridge::Remote, + system: String, + tools: Vec, + session: String, + usage: Usage, + /// 0: ask before file and network tools, 1: auto. Shared with the panel's toggle, so changing + /// it mid-request applies to the next tool call. + pub permission: Arc, + /// Whether a turn that changed the canvas ends with the agent looking at it once. + pub review: Arc, + did_edit: bool, + reviewed: bool, + /// The panel's event stream, for tool calls a command-line agent makes over MCP (they arrive + /// on another thread, outside [`run_turn`](Self::run_turn)'s `out`). + pub sink: Option>, + /// Where a command-line agent runs (beside the saved chats); a temporary folder without one. + pub workdir: Option, + /// The command-line agent's conversation to resume, and which program it belongs to. + cli_session: Option<(ApiKind, String)>, + /// FigCraft's tools served to a command-line agent, started on its first turn. + endpoint: Option, + /// Set by the endpoint when the command-line agent changed the document this turn. + cli_edited: Arc, + /// The skills `load_skill` answers from. + pub skills: crate::skills::SkillBook, +} + +impl Agent { + pub fn new(provider: Provider, backend: crate::bridge::Remote) -> Self { + let mut tools = figcraft_mcp::tool_definitions(); + tools.push(crate::skills::tool_definition()); + tools.push(crate::brief::tool_definition()); + let session = format!("figcraft-{}", now_id()); + Self { + provider, + messages: Vec::new(), + http: Http::new(), + backend, + system: system_prompt(), + tools, + session, + usage: Usage::default(), + permission: Arc::new(AtomicU8::new(0)), + review: Arc::new(AtomicBool::new(true)), + did_edit: false, + reviewed: false, + sink: None, + workdir: None, + cli_session: None, + endpoint: None, + cli_edited: Arc::new(AtomicBool::new(false)), + skills: Arc::new(std::sync::RwLock::new(crate::skills::builtins())), + } + } + + /// Switch the model or the connection. A command-line agent's conversation lives in that + /// program, so moving to another one starts a new conversation there. + pub fn set_provider(&mut self, provider: Provider) { + if self.cli_session.as_ref().is_some_and(|(kind, _)| *kind != provider.kind) { + self.cli_session = None; + } + self.provider = provider; + } + + /// The permission the panel's toggle holds now. + fn permission(&self) -> Permission { + if self.permission.load(Ordering::Relaxed) == 1 { Permission::Auto } else { Permission::AskFiles } + } + + pub fn usage(&self) -> Usage { + self.usage + } + + /// Forget the conversation (a new chat), keeping the provider and tools. + pub fn clear(&mut self) { + self.messages.clear(); + self.usage = Usage::default(); + self.cli_session = None; + } + + /// Run one request to completion. Reports everything through `out`; returns the error the + /// panel shows as a failed turn (the loop's own stops are not errors). + pub fn run_turn(&mut self, text: &str, context: Option, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Result<(), String> { + self.run_turn_with(text, context, Vec::new(), out, cancel) + } + + /// [`run_turn`](Self::run_turn) with images the person attached. + pub fn run_turn_with( + &mut self, + text: &str, + context: Option, + images: Vec, + out: &dyn Fn(ChatEvent), + cancel: &Arc, + ) -> Result<(), String> { + let mut prompt = String::new(); + if let Some(c) = context.filter(|c| !c.trim().is_empty()) { + prompt.push_str(&c); + prompt.push_str("\n\n"); + } + prompt.push_str(text); + if self.provider.kind.is_cli() { + return self.run_cli_turn(&prompt, &images, out, cancel); + } + let mut message = Message::user_text(prompt); + // A model that reads no images is told what was left out rather than failing the request. + if self.provider.vision { + message.blocks.extend(images.into_iter().map(Block::Image)); + } else if !images.is_empty() { + message.blocks.push(Block::Text(format!("[{} attached image(s) left out: this model does not read images]", images.len()))); + } + self.messages.push(message); + self.did_edit = false; + self.reviewed = false; + self.trim(); + if self.messages.last().map(message_chars).unwrap_or(0) > self.budget() { + self.messages.pop(); + return Err("this request is too large for the model's context window; attach fewer or smaller images, or shorten it".into()); + } + + for _step in 0..MAX_STEPS { + if cancel.load(Ordering::Relaxed) { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + let step = match self.stream(out, cancel) { + Ok(step) => step, + Err(e) if e == "stopped" => { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + Err(e) => return Err(e), + }; + let mut blocks = Vec::new(); + if !step.text.is_empty() { + blocks.push(Block::Text(step.text.clone())); + } + // An answer cut off at the output limit may end inside a tool call's arguments: keep + // its text, run none of its calls, and say so. + if matches!(step.stop.as_str(), "length" | "max_tokens") { + if !blocks.is_empty() { + self.messages.push(Message { role: Role::Assistant, blocks }); + } + return Err("the answer hit the model's output limit before it finished; ask the agent to continue".into()); + } + for call in &step.calls { + blocks.push(Block::ToolCall { id: call.id.clone(), name: call.name.clone(), args: call.args.clone() }); + } + if !blocks.is_empty() { + self.messages.push(Message { role: Role::Assistant, blocks }); + } + if step.calls.is_empty() { + // One look at the canvas after a turn that changed it, when the model can see. + if self.review.load(Ordering::Relaxed) && self.provider.vision && self.did_edit && !self.reviewed { + self.reviewed = true; + if self.review_once(out, cancel) { + continue; + } + } + out(ChatEvent::Usage(self.usage)); + out(ChatEvent::Done { stopped: false }); + return Ok(()); + } + let mut results = Vec::new(); + let mut stopped = false; + for call in step.calls { + // Every call gets a result, run or not: a call without one fails the next request. + if stopped || cancel.load(Ordering::Relaxed) { + stopped = true; + results.push(Block::ToolResult { + id: call.id, + name: call.name, + ok: false, + text: "Not run: the user stopped the agent".into(), + images: vec![], + }); + continue; + } + let outcome = self.run_tool(call, out, cancel); + results.push(outcome); + } + self.messages.push(Message { role: Role::User, blocks: results }); + if stopped { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + self.trim(); + } + out(ChatEvent::Done { stopped: false }); + Err(format!("the agent stopped after {MAX_STEPS} steps without finishing; ask it to continue")) + } + + /// One turn through an installed command-line agent: it runs its own loop and calls + /// FigCraft's tools over MCP; the tool cards reach the panel from the MCP side. + fn run_cli_turn( + &mut self, + prompt: &str, + images: &[crate::neutral::Image], + out: &dyn Fn(ChatEvent), + cancel: &Arc, + ) -> Result<(), String> { + self.cli_edited.store(false, Ordering::Relaxed); + if self.cli_pass(prompt, images, out, cancel)? { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + // One look at the canvas after a turn that changed it, as the API connections do: the + // program gets the picture in the same conversation and fixes what it sees. + if self.review.load(Ordering::Relaxed) + && self.cli_edited.load(Ordering::Relaxed) + && !cancel.load(Ordering::Relaxed) + && let Some(image) = self.look(out) + { + // The request itself is done; a model that can't take the picture leaves it at that. + match self.cli_pass(REVIEW_PROMPT, &[image], out, cancel) { + Ok(true) => { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + Ok(false) => {} + Err(e) => out(ChatEvent::Text(format!("(The check of the result did not run: {})", crate::neutral::clip(&e, 200)))), + } + } + out(ChatEvent::Done { stopped: false }); + Ok(()) + } + + /// Run the command-line agent once; `true` when the person stopped it. + fn cli_pass( + &mut self, + prompt: &str, + images: &[crate::neutral::Image], + out: &dyn Fn(ChatEvent), + cancel: &Arc, + ) -> Result { + let kind = self.provider.kind; + let program = crate::cli::locate(kind) + .ok_or_else(|| format!("{} is not installed on this computer; install it or pick another connection", kind.label()))?; + if self.endpoint.is_none() { + let sink = self.sink.clone().ok_or_else(|| "the agent has no panel to report to".to_string())?; + let gate = crate::mcp_http::Gate { + permission: self.permission.clone(), + sink, + cancel: cancel.clone(), + edited: self.cli_edited.clone(), + skills: self.skills.clone(), + }; + let endpoint = crate::mcp_http::start(self.backend.clone(), gate).map_err(|e| format!("can't serve FigCraft's tools: {e}"))?; + self.endpoint = Some(endpoint); + } + let endpoint = self.endpoint.as_ref().ok_or_else(|| "can't serve FigCraft's tools".to_string())?; + let workdir = self.workdir.clone().unwrap_or_else(|| std::env::temp_dir().join("figcraft-agent")); + let session = self.cli_session.as_ref().filter(|(k, _)| *k == kind).map(|(_, s)| s.clone()); + let system = app_rules(); + let turn = crate::cli::Turn { + kind, + program: &program, + model: &self.provider.model, + session: session.as_deref(), + prompt, + system: &system, + mcp_url: &endpoint.url, + mcp_token: &endpoint.token, + workdir: &workdir, + images, + }; + let mut on_text = |t: &str| out(ChatEvent::Text(t.to_string())); + let outcome = crate::cli::run(&turn, &mut on_text, cancel); + if let Some(s) = outcome.session { + self.cli_session = Some((kind, s)); + } + self.usage.input = self.usage.input.saturating_add(outcome.usage.input); + self.usage.output = self.usage.output.saturating_add(outcome.usage.output); + out(ChatEvent::Usage(self.usage)); + if outcome.stopped { + return Ok(true); + } + match outcome.error { + Some(e) => Err(e), + None => Ok(false), + } + } + + fn stream(&mut self, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Result { + let mut on_text = |t: &str| { + out(ChatEvent::Text(t.to_string())); + }; + // A model that reads no images gets none, also from earlier in the conversation (a chat + // begun on another connection); the saved conversation keeps them. + let filtered; + let messages: &[Message] = if self.provider.vision { + &self.messages + } else { + filtered = without_images(&self.messages); + &filtered + }; + let result = match self.provider.kind { + ApiKind::OpenAiCompletions => { + crate::openai::stream(&self.http, &self.provider, &self.system, messages, &self.tools, &self.session, &mut on_text, cancel) + } + ApiKind::AnthropicMessages => { + crate::anthropic::stream(&self.http, &self.provider, &self.system, messages, &self.tools, &self.session, &mut on_text, cancel) + } + ApiKind::ClaudeCode | ApiKind::Codex | ApiKind::OpenCode => Err("a command-line agent runs its own loop".to_string()), + }; + if let Ok(step) = &result { + self.usage.input = self.usage.input.saturating_add(step.usage.input); + self.usage.output = self.usage.output.saturating_add(step.usage.output); + out(ChatEvent::Usage(self.usage)); + } + result + } + + fn run_tool(&mut self, call: Invocation, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Block { + out(ChatEvent::ToolStart { id: call.id.clone(), name: call.name.clone(), args: call.args.clone() }); + let denied = |reason: String| Block::ToolResult { + id: call.id.clone(), + name: call.name.clone(), + ok: false, + text: format!("Not run: {reason}"), + images: vec![], + }; + if call.args.is_null() { + return denied("the model sent arguments that are not valid JSON; try again".into()); + } + if call.name == crate::brief::TOOL_NAME { + let (text, ok) = crate::brief::call(&mut self.backend, &call.args); + if ok && (call.args.get("spec").is_some() || call.args.get("brief").is_some()) { + self.did_edit = true; + } + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok, + title: tool_title(&call.name, &call.args), + text: summarize(&text), + }); + return Block::ToolResult { id: call.id, name: call.name, ok, text, images: vec![] }; + } + if call.name == crate::skills::TOOL_NAME { + let (text, ok) = crate::skills::call(&self.skills, &call.args); + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok, + title: tool_title(&call.name, &call.args), + text: summarize(&text), + }); + return Block::ToolResult { id: call.id, name: call.name, ok, text, images: vec![] }; + } + if let Some(reason) = approval(&call.name, &call.args) + && self.permission() == Permission::AskFiles + { + let (tx, rx) = std::sync::mpsc::channel(); + out(ChatEvent::Permission { id: call.id.clone(), name: call.name.clone(), args: call.args.clone(), reason: reason.clone(), reply: tx }); + let allowed = rx.recv_timeout(std::time::Duration::from_secs(600)).unwrap_or(false); + if !allowed { + let result = denied(format!("the user denied this action ({reason})")); + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok: false, + title: call.name.clone(), + text: "Denied by the user".into(), + }); + return result; + } + } + if cancel.load(Ordering::Relaxed) { + return denied("the user stopped the agent".into()); + } + let result = figcraft_mcp::call_tool(&mut self.backend, &call.name, &call.args); + if !result.is_error && mutating(&call.name, &call.args) { + self.did_edit = true; + } + let (text, mut images) = crate::neutral::tool_output(&result); + // A model that does not read images gets the text alone: sending one would fail the + // whole request (some endpoints reject it). + if !self.provider.vision { + images.clear(); + } + let text = crate::neutral::clip(&text, TOOL_TEXT_MAX); + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok: !result.is_error, + title: tool_title(&call.name, &call.args), + text: summarize(&text), + }); + Block::ToolResult { id: call.id, name: call.name, ok: !result.is_error, text, images } + } + + /// Capture the page and hand it back to the model for one review pass. `true` when the image + /// is now in the conversation (the loop continues); `false` when there is nothing to see. + fn review_once(&mut self, out: &dyn Fn(ChatEvent), cancel: &Arc) -> bool { + if cancel.load(Ordering::Relaxed) { + return false; + } + match self.look(out) { + Some(image) => { + self.messages.push(Message { role: Role::User, blocks: vec![Block::Text(REVIEW_PROMPT.into()), Block::Image(image)] }); + true + } + None => false, + } + } + + /// Capture the page for a review, shown as a step in the panel. + fn look(&mut self, out: &dyn Fn(ChatEvent)) -> Option { + let id = "self-review".to_string(); + out(ChatEvent::ToolStart { id: id.clone(), name: "screenshot".into(), args: json!({}) }); + let result = figcraft_mcp::call_tool(&mut self.backend, "screenshot", &json!({})); + let (text, images) = crate::neutral::tool_output(&result); + let image = images.into_iter().next().filter(|_| !result.is_error); + out(ChatEvent::ToolEnd { + id, + name: "screenshot".into(), + ok: image.is_some(), + title: "Checking the result".into(), + text: if image.is_some() { "Looking at the canvas".into() } else { crate::neutral::clip(&text, 200) }, + }); + image + } + + /// Save the model's conversation beside the document's chat. + pub fn save_history(&self, path: &Path) -> Result<(), String> { + let (cli_kind, cli_session) = match &self.cli_session { + Some((k, s)) => (Some(*k), Some(s.clone())), + None => (None, None), + }; + let file = ContextFile { version: 1, messages: self.messages.clone(), usage: self.usage, cli_kind, cli_session }; + let bytes = serde_json::to_vec(&file).map_err(|e| format!("can't encode the conversation: {e}"))?; + crate::config::write_private(path, &bytes) + } + + /// Read back a conversation saved by [`save_history`](Self::save_history). + pub fn load_history(&mut self, path: &Path) -> Result<(), String> { + let bytes = std::fs::read(path).map_err(|e| format!("can't read {}: {e}", path.display()))?; + let file: ContextFile = serde_json::from_slice(&bytes).map_err(|e| format!("{} is damaged: {e}", path.display()))?; + if file.version != 1 { + return Err(format!("{} was saved by another version", path.display())); + } + self.messages = file.messages; + self.usage = file.usage; + self.cli_session = file.cli_kind.zip(file.cli_session); + self.trim(); + Ok(()) + } + + /// Shorten the oldest tool output when the conversation grows past what the model's context + /// window takes, so a long session keeps its shape without resending megabytes. + fn trim(&mut self) { + let budget = self.budget(); + trim_messages(&mut self.messages, budget); + } + + /// Characters of conversation the model's context window takes, with room for the answer. + fn budget(&self) -> usize { + (self.provider.context_window as usize).saturating_mul(CHARS_PER_TOKEN).saturating_sub(24_000).clamp(60_000, 800_000) + } +} + +/// The conversation without its images, for a model that reads none; each left-out image is named +/// so the model knows something was there. +fn without_images(messages: &[Message]) -> Vec { + messages + .iter() + .map(|m| { + let mut blocks = Vec::with_capacity(m.blocks.len()); + for b in &m.blocks { + match b { + Block::Image(_) => blocks.push(Block::Text("[an image left out: this model does not read images]".into())), + Block::ToolResult { id, name, ok, text, images } if !images.is_empty() => blocks.push(Block::ToolResult { + id: id.clone(), + name: name.clone(), + ok: *ok, + text: format!("{text}\n[{} image(s) left out: this model does not read images]", images.len()), + images: vec![], + }), + other => blocks.push(other.clone()), + } + } + Message { role: m.role, blocks } + }) + .collect() +} + +/// Shorten the oldest messages until the conversation fits `budget`, keeping the last eight +/// messages whole: the recent steps are what the model is working from. First old tool output and +/// images go, then long old text; messages stay, so every tool call keeps its result. +fn trim_messages(messages: &mut [Message], budget: usize) { + let keep = messages.len().saturating_sub(8); + let mut total: usize = messages.iter().map(message_chars).sum(); + for pass in 0..2 { + let mut i = 0; + while total > budget && i < keep { + let before = message_chars(&messages[i]); + for block in &mut messages[i].blocks { + match block { + Block::ToolResult { text, images, .. } if pass == 0 => { + if text.len() > 200 { + *text = "[older tool output left out]".to_string(); + } + images.clear(); + } + Block::Image(_) if pass == 0 => *block = Block::Text("[older image left out]".into()), + Block::Text(t) if pass == 1 && t.len() > 2_000 => *t = "[older message shortened]".to_string(), + _ => {} + } + } + let after = message_chars(&messages[i]); + total = total.saturating_sub(before.saturating_sub(after)); + i += 1; + } + } +} + +#[derive(Serialize, Deserialize)] +struct ContextFile { + version: u32, + messages: Vec, + usage: Usage, + /// A command-line agent's conversation id, resumed on the next turn. + #[serde(default, skip_serializing_if = "Option::is_none")] + cli_kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + cli_session: Option, +} + +/// Whether a tool call can change what the canvas looks like (so a look at it is worth a review). +pub(crate) fn mutating(name: &str, args: &Value) -> bool { + match name { + "create_node" | "set_properties" | "batch" | "undo" | "redo" => true, + crate::brief::TOOL_NAME => args.get("spec").is_some() || args.get("brief").is_some(), + "run_command" => { + let cmd = args.get("command").and_then(Value::as_str).unwrap_or(""); + !(cmd.starts_with("inspect.") + || cmd.starts_with("variable.list") + || cmd.starts_with("style.list") + || cmd == "design.audit" + || cmd == "design.assert" + || cmd == "design.rules" + || cmd == "node.find" + || cmd == "comment.list" + || cmd == "text.fonts" + || cmd == "text.missingFonts" + || cmd == "image.presets" + || cmd == "list_commands") + } + _ => false, + } +} + +fn message_chars(m: &Message) -> usize { + m.blocks + .iter() + .map(|b| match b { + Block::Text(t) => t.len(), + Block::Image(i) => i.data.len(), + Block::ToolCall { name, args, .. } => name.len() + args.to_string().len(), + Block::ToolResult { text, images, .. } => text.len() + images.iter().map(|i| i.data.len()).sum::(), + }) + .sum() +} + +pub(crate) fn summarize(text: &str) -> String { + let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or("").trim(); + let mut s: String = first.chars().take(160).collect(); + if first.chars().count() > 160 { + s.push('…'); + } + s +} + +/// The card's title: the tool's own name plus what it acted on. +pub(crate) fn tool_title(name: &str, args: &Value) -> String { + if name == crate::skills::TOOL_NAME { + return format!("Skill: {}", args.get("name").and_then(Value::as_str).unwrap_or("")); + } + if name == crate::brief::TOOL_NAME { + return if args.get("spec").is_some() || args.get("brief").is_some() { + "Design system: make the 00 · Design System page".into() + } else { + "Design system: read the 00 · Design System page".into() + }; + } + if name == "run_command" + && let Some(cmd) = args.get("command").and_then(Value::as_str) + { + return cmd.to_string(); + } + name.to_string() +} + +/// Why a tool needs the person's Allow, or `None` when it only changes the canvas. +/// +/// Canvas edits (layers, styles, variables, components, layout, selection, undo) run at once; a +/// tool that reads or writes a file, joins a server, installs a plugin or downloads a font asks. +pub fn approval(tool: &str, args: &Value) -> Option { + match tool { + "open_file" => Some("reads a file".into()), + "save_file" => Some("writes the document to a file".into()), + "export" => Some("writes an export to a file".into()), + "export_assets" => Some("writes assets into a project folder".into()), + "sync_mappings" => Some("reads or writes figcraft.connect.json".into()), + "compare_design" => Some("reads a capture from disk".into()), + "component_mappings" => Some("reads a code project".into()), + "run_command" => { + let cmd = args.get("command").and_then(Value::as_str).unwrap_or(""); + command_reason(cmd).or_else(|| if cmd == "command.batch" { batch_reason(args.get("params"), 0) } else { None }) + } + "batch" => batch_reason(Some(args), 0), + _ => None, + } +} + +/// The first reason a step of a batch needs the person's Allow, nested batches included. +fn batch_reason(params: Option<&Value>, depth: usize) -> Option { + // Deeper than the engine accepts: refuse to guess, ask. + if depth > 16 { + return Some("runs deeply nested commands".into()); + } + params?.get("commands")?.as_array()?.iter().find_map(|step| { + let cmd = step.get("command").and_then(Value::as_str).unwrap_or(""); + command_reason(cmd).or_else(|| if cmd == "command.batch" { batch_reason(step.get("params"), depth + 1) } else { None }) + }) +} + +fn command_reason(cmd: &str) -> Option { + let file = [ + "file.open", + "file.save", + "file.saveAs", + "file.export", + "file.import", + "file.revert", + "file.recover", + "file.placeImage", + "file.exportSvg", + "file.exportLayers", + "file.exportFramesPdf", + "file.openRecent", + ]; + if file.iter().any(|p| cmd.starts_with(p)) { + return Some("reads or writes a file".into()); + } + if cmd.starts_with("collab.") { + return Some("reaches a collaboration server".into()); + } + if ["plugin.", "plugins.", "library.", "libraries."].iter().any(|p| cmd.starts_with(p)) { + return Some("installs or runs a plugin, or reaches a library server".into()); + } + if cmd == "pref.publishServer" { + return Some("changes where shared files are sent".into()); + } + if cmd.starts_with("font.download") { + return Some("downloads a font".into()); + } + if cmd.starts_with("variable.import") || cmd.starts_with("variable.export") || cmd.starts_with("codeConnect.") { + return Some("reads or writes a file".into()); + } + if cmd == "image.place" || cmd == "image.replace" { + return Some("reads an image file".into()); + } + None +} + +/// The instructions an in-app agent gets: the MCP conventions the external clients get, plus how +/// this one is expected to behave in front of the person. +pub fn system_prompt() -> String { + format!("{}\n\n---\n{}", figcraft_mcp::INSTRUCTIONS, app_rules()) +} + +/// How the in-app agent behaves in front of the person. A command-line agent gets these alone: +/// FigCraft's tool conventions reach it through the MCP server's own instructions. +pub fn app_rules() -> String { + "You are the FigCraft agent, running inside the window the user has open. \ +They see every change on the canvas as you make it.\n\ +- Work in small steps and verify with `screenshot` (or `design_context`) before claiming a screen is done.\n\ +- The user's current selection is given with each request; change that unless they name something else.\n\ +- Prefer auto layout, components and variables over absolutely placed copies.\n\ +- Read and change the file freely: every page and layer is yours to inspect (design_context, inspect_document, get_node, screenshot) \ +and to edit (create_node, set_properties, batch, run_command with any command: pages, layers, components, variables, styles, prototype). \ +Pages are part of the file's structure, like components: the request lists them with their frames. The design system lives on the page \ +'00 · Design System'; screens go on pages named by flow or area (create one with page.add when none fits). A page the user names with @ \ +means the frames on it.\n\ +- Keep the reply short: say what you changed and which frames it touched. Do not describe the tool calls one by one.\n\ +- If a tool is denied or fails, say so plainly and continue with what you can do.\n\ +\n\ +How you work on a design request (new screens, pages, flows or components; not small edits to existing layers):\n\ +1. Foundations first. The file must have the page '00 · Design System'. If the request's page list has none, call `design_system` (no arguments) to check, \ +then propose a design system from what the user said: product and platform, primary colour (and secondary or accent if it helps), greys, light/dark, \ +heading and body fonts, corners, shadows, an open-source icon set and its style, tone and copy language. Give it in a few short lines and ask the user \ +to confirm or change it; stop there. When the user confirms (or asked you to go ahead without asking), call `design_system` with the spec: it makes \ +the page, the variables, the styles and the guidelines. Then lay out the foundations and base components on that page (the `Design system setup` skill). \ +When the page exists, read it first (`design_system` with no arguments for its guidelines, design_context for its frames).\n\ +2. Design with the system: Theme colours as {$var: name}, Sizes for spacing and corners, the text and shadow styles, existing components; \ +icons drawn in the brief's set and style, never emoji. Add a raw value only when nothing fits, and say so.\n\ +3. Before you say it is done, load the `Design review` skill and follow it: `design.audit` on what you made, `design.fix` for what it can repair, \ +then a screenshot for what no rule measures; fix what is safe to fix." + .to_string() +} + +fn now_id() -> u128 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn canvas_edits_need_no_approval_but_files_do() { + assert!(approval("create_node", &json!({})).is_none()); + assert!(approval("set_properties", &json!({})).is_none()); + assert!(approval("run_command", &json!({"command": "node.set"})).is_none()); + assert!(approval("run_command", &json!({"command": "file.save"})).is_some()); + assert!(approval("run_command", &json!({"command": "collab.host"})).is_some()); + assert!(approval("save_file", &json!({})).is_some()); + for cmd in ["plugins.runLast", "libraries.publish", "pref.publishServer"] { + assert!(approval("run_command", &json!({"command": cmd})).is_some(), "{cmd}"); + } + assert!(approval("screenshot", &json!({})).is_none()); + // Pages and the canvas are the agent's to read and change. + for cmd in + ["page.add", "page.select", "page.rename", "page.move", "page.delete", "object.moveToPage", "node.set", "variable.create", "design.fix"] + { + assert!(approval("run_command", &json!({"command": cmd})).is_none(), "{cmd}"); + } + assert!(approval("design_system", &json!({"spec": {}})).is_none()); + } + + #[test] + fn a_file_command_inside_a_batch_still_asks() { + let nested = json!({"commands": [{"command": "node.set"}, {"command": "command.batch", "params": {"commands": [{"command": "file.save"}]}}]}); + assert!(approval("batch", &nested).is_some()); + assert!(approval("run_command", &json!({"command": "command.batch", "params": nested})).is_some()); + assert!(approval("batch", &json!({"commands": [{"command": "node.set"}]})).is_none()); + } + + #[test] + fn old_images_go_even_beside_short_text() { + let image = crate::neutral::Image { mime: "image/png".into(), data: "A".repeat(5_000) }; + let mut messages: Vec = (0..30) + .map(|_| Message { + role: Role::User, + blocks: vec![Block::ToolResult { + id: "t".into(), + name: "screenshot".into(), + ok: true, + text: "ok".into(), + images: vec![image.clone()], + }], + }) + .collect(); + trim_messages(&mut messages, 60_000); + let total: usize = messages.iter().map(message_chars).sum(); + assert!(total <= 60_000, "fits the budget: {total}"); + } + + #[test] + fn a_text_only_model_gets_no_image_from_earlier_in_the_chat() { + let messages = vec![Message { + role: Role::User, + blocks: vec![Block::Text("look".into()), Block::Image(crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() })], + }]; + let sent = without_images(&messages); + assert!(!sent[0].blocks.iter().any(|b| matches!(b, Block::Image(_)))); + assert!(matches!(messages[0].blocks[1], Block::Image(_)), "the conversation itself keeps it"); + } + + #[test] + fn trimming_shortens_the_oldest_output_and_keeps_the_last_steps_whole() { + let mut messages: Vec = (0..40) + .map(|_| Message { + role: Role::User, + blocks: vec![Block::ToolResult { + id: "t".into(), + name: "inspect_document".into(), + ok: true, + text: "x".repeat(5_000), + images: vec![], + }], + }) + .collect(); + let before: usize = messages.iter().map(message_chars).sum(); + let budget = 60_000; + assert!(before > budget); + trim_messages(&mut messages, budget); + let after: usize = messages.iter().map(message_chars).sum(); + assert!(after <= budget, "fits the budget"); + assert_eq!(messages.len(), 40, "messages stay, their bulk goes"); + match &messages[0].blocks[0] { + Block::ToolResult { text, .. } => assert_eq!(text, "[older tool output left out]"), + _ => panic!("a tool result"), + } + match &messages[39].blocks[0] { + Block::ToolResult { text, .. } => assert_eq!(text.len(), 5_000, "the newest step is untouched"), + _ => panic!("a tool result"), + } + } + + #[test] + fn the_conversation_round_trips_through_its_file() { + let dir = std::env::temp_dir().join(format!("figcraft-conv-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("dir"); + let path = dir.join("chat.context.json"); + let mut p = Provider::new("Go", ApiKind::OpenAiCompletions, "https://example.test/v1"); + p.model = "m".into(); + let (bridge, remote) = crate::bridge::pair("Test", Arc::new(|| {})); + drop(bridge); + let mut agent = Agent::new(p.clone(), remote); + agent.messages.push(Message::user_text("hello")); + agent.usage.input = 12; + agent.save_history(&path).expect("saved"); + let (bridge, remote) = crate::bridge::pair("Test", Arc::new(|| {})); + drop(bridge); + let mut back = Agent::new(p, remote); + back.load_history(&path).expect("loaded"); + assert_eq!(back.messages.len(), 1); + assert_eq!(back.usage.input, 12); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_card_title_names_the_command() { + assert_eq!(tool_title("run_command", &json!({"command": "frame.create"})), "frame.create"); + assert_eq!(tool_title("screenshot", &json!({})), "screenshot"); + } +} diff --git a/crates/agent/src/skills.rs b/crates/agent/src/skills.rs new file mode 100644 index 000000000..b00c58ec1 --- /dev/null +++ b/crates/agent/src/skills.rs @@ -0,0 +1,307 @@ +//! Skills: named instructions for a kind of work (a mobile screen, a landing page, a review…). +//! +//! A skill is a Markdown file with a small header: +//! +//! ```text +//! --- +//! name: Landing page +//! description: When to use it, in one line (the model reads this to decide). +//! --- +//! The instructions. +//! ``` +//! +//! The app ships a few (built in, read-only); the person's own live in `agent-skills/` beside +//! `agents.json`, and one with the same name as a built-in one replaces it. The person attaches a +//! skill to a request with `/` in the composer; the model sees the list (names and descriptions) +//! and loads one it needs with the `load_skill` tool, so only the skills used cost tokens. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; + +use serde_json::{Value, json}; + +/// The tool the model loads a skill with. +pub const TOOL_NAME: &str = "load_skill"; + +/// The longest skill body kept (a skill is instructions, not a document). +const MAX_BODY: usize = 20_000; + +#[derive(Clone, Debug, PartialEq)] +pub struct Skill { + pub name: String, + pub description: String, + pub body: String, + /// Shipped with the app (read-only). + pub builtin: bool, + /// The person's file, for one of their own. + pub file: Option, +} + +/// The skills the agent can load, shared between the panel (which keeps it current) and the agent +/// thread (which answers `load_skill`). +pub type SkillBook = Arc>>; + +/// Read a skill file's text: its header's name and description, and the body after it. +pub fn parse(text: &str) -> Option<(String, String, String)> { + let text = text.trim_start_matches('\u{feff}'); + let rest = text.strip_prefix("---")?; + let end = rest.find("\n---")?; + let (head, body) = (&rest[..end], &rest[end + 4..]); + let field = |key: &str| { + head.lines().find_map(|l| { + let (k, v) = l.split_once(':')?; + (k.trim().eq_ignore_ascii_case(key)).then(|| v.trim().trim_matches('"').to_string()) + }) + }; + let name = field("name").filter(|n| !n.is_empty())?; + let description = field("description").unwrap_or_default(); + let body = body.trim_start_matches(['\r', '\n']).trim_end().to_string(); + Some((name, description, body)) +} + +/// A skill as the text of its file. +pub fn to_text(name: &str, description: &str, body: &str) -> String { + let one_line = |s: &str| s.replace(['\r', '\n'], " ").trim().to_string(); + format!("---\nname: {}\ndescription: {}\n---\n{}\n", one_line(name), one_line(description), body.trim()) +} + +/// The built-in skills and the person's own from `dir` (theirs replace a built-in one of the same +/// name), sorted by name. +pub fn load(dir: Option<&Path>) -> Vec { + let mut skills = builtins(); + let mut own = Vec::new(); + if let Some(dir) = dir + && let Ok(entries) = std::fs::read_dir(dir) + { + for e in entries.flatten() { + let path = e.path(); + if path.extension().and_then(|x| x.to_str()) != Some("md") { + continue; + } + let Ok(text) = std::fs::read_to_string(&path) else { continue }; + if let Some((name, description, body)) = parse(&text) { + let body = crate::neutral::clip(&body, MAX_BODY); + own.push(Skill { name, description, body, builtin: false, file: Some(path) }); + } + } + } + for s in own { + skills.retain(|b| !b.name.eq_ignore_ascii_case(&s.name)); + skills.push(s); + } + skills.sort_by_key(|s| s.name.to_lowercase()); + skills +} + +/// Write one of the person's skills to `dir` (replacing `old`, its file before a rename). +pub fn save(dir: &Path, name: &str, description: &str, body: &str, old: Option<&Path>) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err("a skill needs a name".into()); + } + std::fs::create_dir_all(dir).map_err(|e| format!("can't create {}: {e}", dir.display()))?; + let path = dir.join(format!("{}.md", slug(name))); + let text = to_text(name, description, body); + let write_err = |e: std::io::Error| format!("can't write {}: {e}", path.display()); + // Two names can share a file name ("Brand voice", "Brand-voice"): only this skill's own file is + // replaced; any other file there, unreadable or not a skill included, is left alone. + let own = old == Some(path.as_path()) + || std::fs::read_to_string(&path).ok().and_then(|t| parse(&t)).is_some_and(|(other, _, _)| other.eq_ignore_ascii_case(name)); + if own { + std::fs::write(&path, text).map_err(write_err)?; + } else { + use std::io::Write as _; + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| { + if e.kind() == std::io::ErrorKind::AlreadyExists { + format!("another file is saved as {}; give this skill a different name", path.display()) + } else { + write_err(e) + } + })?; + file.write_all(text.as_bytes()).map_err(write_err)?; + } + if let Some(old) = old + && old != path + { + let _ = std::fs::remove_file(old); + } + Ok(path) +} + +/// A file name for a skill's name. +fn slug(name: &str) -> String { + let s: String = name.chars().map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect(); + let s = s.split('-').filter(|p| !p.is_empty()).collect::>().join("-"); + if s.is_empty() { "skill".into() } else { s.chars().take(60).collect() } +} + +/// The skill named `name` (case does not matter). +pub fn find(book: &SkillBook, name: &str) -> Option { + let name = name.trim().trim_start_matches('/'); + book.read().ok()?.iter().find(|s| s.name.eq_ignore_ascii_case(name)).cloned() +} + +/// What the model is told about the skills it can load. +pub fn catalog(skills: &[Skill]) -> Option { + if skills.is_empty() { + return None; + } + let mut text = format!( + "[Skills: instructions for kinds of work. When one fits the request, call `{TOOL_NAME}` with its name before you start, and follow it.]" + ); + for s in skills { + text.push_str(&format!("\n- {}: {}", s.name, s.description)); + } + Some(text) +} + +/// The `load_skill` tool, as the tool list has it. +pub fn tool_definition() -> Value { + json!({ + "name": TOOL_NAME, + "description": "Load a skill: instructions for a kind of work (the list of skills comes with the request). Call it before starting work that a skill fits.", + "inputSchema": { + "type": "object", + "properties": {"name": {"type": "string", "description": "The skill's name, as listed"}}, + "required": ["name"] + } + }) +} + +/// Answer a `load_skill` call: the skill's instructions, or why not (`false`). +pub fn call(book: &SkillBook, args: &Value) -> (String, bool) { + let name = args.get("name").and_then(Value::as_str).unwrap_or(""); + match find(book, name) { + Some(s) => (format!("Skill \"{}\":\n{}", s.name, s.body), true), + None => { + let names: Vec = book.read().map(|b| b.iter().map(|s| s.name.clone()).collect()).unwrap_or_default(); + (format!("No skill named \"{name}\". Skills: {}", names.join(", ")), false) + } + } +} + +fn builtin(name: &str, description: &str, body: &str) -> Skill { + Skill { name: name.into(), description: description.into(), body: body.trim().into(), builtin: true, file: None } +} + +/// The skills that come with the app (our own wording). +pub fn builtins() -> Vec { + vec![ + builtin( + "Mobile app screen", + "Designing a phone app screen or flow (iOS or Android).", + r#" +- One frame per screen, 390 x 844, named after the screen. Several screens sit in a row, 80 apart. +- Vertical auto layout for the screen; leave 47 at the top (status bar) and 34 at the bottom (home indicator). +- Padding 16 or 20 at the sides; spacing in steps of 4 (8, 12, 16, 24, 32). +- Touch targets at least 44 high; primary action at the bottom, full width, within thumb reach. +- Type: title 28-34 bold, section 17-20 semibold, body 15-17, caption 12-13. At most three sizes per screen. +- Navigation: a top bar with title and back, or a bottom tab bar with 3-5 items (icon and label). +- Use the file's variables, styles and components first; make a component for anything repeated. +- Real copy, not lorem ipsum, in the language the user writes in. +"#, + ), + builtin( + "Landing page", + "Designing a marketing website page or section (desktop first).", + r#" +- A 1440 wide frame, content at most 1200 wide and centred; vertical auto layout, sections 96-128 apart. +- Order: navigation, hero (headline, one-line value, primary and secondary action, visual), proof (logos or numbers), features (3-6, icon, title, one sentence), how it works or a showcase, testimonials, pricing if asked, FAQ, final call to action, footer. +- Hero headline 56-72, section titles 36-44, body 18. One primary colour for actions only. +- Each section is its own frame named after it, so it can be moved or reused. +- Real, specific copy for the product the user describes; no lorem ipsum. +- When asked for mobile too, add a 390 wide frame with the same section names, stacked to one column. +"#, + ), + builtin( + "Design review", + "Checking a design for problems (contrast, spacing, alignment, consistency) and fixing them.", + r#" +Measure first, then judge. FigCraft's own checker does the measuring; you do what it cannot. +1. If the file has a design brief, its spacing step, corners, brand colours and contrast target are already the review settings (design.configure); otherwise run design.configure with the grid, radii and brand colours the design uses. +2. run_command design.audit on the selection, or on the frames you made (ids), with the Theme mode you designed in (modes: {Theme: Light}). Read the score, the counts and each finding (rule, node, message, fixable). +3. run_command design.fix with the same scope (dryRun first if many layers change): it repairs the fixable findings in one undo step. Then design.audit again to confirm. +4. Fix the rest by hand where it is safe (text colour for contrast, a gap onto the step, a raw colour onto a Theme variable); leave content and naming to the user unless asked. +5. Then look: a screenshot of the frames, compared with the request, for what no rule measures: hierarchy, balance, alignment between sections, empty or crowded areas, copy that does not fit. +6. Report briefly: the score before and after, what you fixed, and what is left as a suggestion with where it is. +"#, + ), + builtin( + "Design system setup", + "Making or completing the file's design system on the page '00 · Design System': tokens, styles, foundations and base components.", + r#" +- Everything goes on the page '00 · Design System', first in the file. `design_system` with a spec makes the page, the variables (Primitives, Theme with Light/Dark, Sizes), the text and shadow styles, the review settings and a 'Design guidelines' text; call it first when they are missing, and use what it made instead of a second set. +- Lay the page out in sections side by side (frames with vertical auto layout, 80 apart, each with a heading in Heading 2): Colour (a swatch per Theme role, one frame per mode with variable.setMode), Type (a line per text style with its size and weight), Spacing and corners (bars and squares bound to the Sizes variables), Elevation (cards with Shadow/S, M, L), Icons (the set and style from the guidelines, with a few sample icons drawn as vectors on the icon grid), and the Design guidelines text. +- Components on the same page, in a "Components" section: Button (Primary, Secondary, Ghost; Default, Hover, Disabled), Input (Default, Focus, Error), Card, Badge, Icon button, as component sets with auto layout, every colour, radius and gap bound to the variables (variable.bind, fill {$var}) and text in the text styles. +- Check contrast of text on its background in both modes before finishing. +"#, + ), + builtin( + "Dark mode", + "Making a dark version of a design or adding a dark theme.", + r#" +- Prefer variables: add a Dark mode to the colour collection and set each semantic colour; switch the frame's mode instead of repainting layers. +- Without variables, duplicate the frame beside the original, named "... / Dark", and recolour it. +- Backgrounds near #0F1115-#1A1D23, surfaces a step lighter; text #E8EAED and muted #9AA0A6; keep 4.5:1 contrast. +- Lower the saturation of bright brand colours a little; shadows become subtle borders or lighter surfaces. +"#, + ), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_skill_file_reads_back_as_it_was_written() { + let text = to_text("Brand voice", "Writing copy\nfor us", "- Friendly\n- Short"); + let (name, description, body) = parse(&text).expect("a skill"); + assert_eq!(name, "Brand voice"); + assert_eq!(description, "Writing copy for us", "the description stays one line"); + assert_eq!(body, "- Friendly\n- Short"); + assert!(parse("no header here").is_none()); + assert!(parse("---\ndescription: x\n---\nbody").is_none(), "a skill needs a name"); + } + + #[test] + fn the_persons_skill_replaces_a_builtin_one_of_the_same_name() { + let dir = std::env::temp_dir().join(format!("figcraft-skills-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + save(&dir, "landing PAGE", "Ours", "Our rules", None).expect("saved"); + let skills = load(Some(&dir)); + let landing: Vec<&Skill> = skills.iter().filter(|s| s.name.eq_ignore_ascii_case("landing page")).collect(); + assert_eq!(landing.len(), 1); + assert!(!landing[0].builtin); + assert_eq!(landing[0].body, "Our rules"); + assert!(skills.iter().any(|s| s.builtin), "the other built-in skills stay"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_skill_never_overwrites_another_with_the_same_file_name() { + let dir = std::env::temp_dir().join(format!("figcraft-skills-clash-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let first = save(&dir, "Brand voice", "", "One", None).expect("saved"); + assert!(save(&dir, "Brand-voice", "", "Two", None).is_err(), "a different skill, the same file"); + save(&dir, "brand voice", "", "Edited", None).expect("the same skill saves again"); + save(&dir, "Brand voice", "", "Again", Some(&first)).expect("editing it in place"); + assert!(load(Some(&dir)).iter().any(|s| s.body == "Again")); + let notes = dir.join("notes.md"); + std::fs::write(¬es, "not a skill").expect("write"); + assert!(save(&dir, "Notes", "", "Mine", None).is_err(), "a file that is not a skill stays"); + assert_eq!(std::fs::read_to_string(¬es).ok().as_deref(), Some("not a skill")); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn load_skill_answers_with_the_instructions_or_the_names_there_are() { + let book: SkillBook = Arc::new(RwLock::new(builtins())); + let (text, ok) = call(&book, &json!({"name": "dark mode"})); + assert!(ok); + assert!(text.contains("variables")); + let (text, ok) = call(&book, &json!({"name": "nope"})); + assert!(!ok); + assert!(text.contains("Dark mode"), "it lists what there is"); + } +} diff --git a/crates/agent/src/sse.rs b/crates/agent/src/sse.rs new file mode 100644 index 000000000..00bf2d343 --- /dev/null +++ b/crates/agent/src/sse.rs @@ -0,0 +1,179 @@ +//! A Server-Sent Events reader: the provider streams one JSON object per `data:` line, ended by a +//! blank line. Hand-written because the crate has no async runtime. + +use std::io::{BufRead, Read}; +use std::sync::mpsc::{Receiver, sync_channel}; + +/// The longest line read from a stream; a provider sending more without a newline is refused. +pub const MAX_LINE: usize = 1024 * 1024; +/// The most data one event may join. +pub const MAX_EVENT: usize = 16 * 1024 * 1024; + +/// One event: its `event:` name when the stream set one, and its joined `data:` lines. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Event { + pub name: String, + pub data: String, +} + +pub struct Sse { + reader: R, +} + +impl Sse { + pub fn new(reader: R) -> Self { + Self { reader } + } + + /// One line, at most [`MAX_LINE`] long; `None` at the end of the stream. + fn line(&mut self) -> Result, String> { + let mut bytes = Vec::new(); + let read = + (&mut self.reader).take(MAX_LINE as u64 + 1).read_until(b'\n', &mut bytes).map_err(|e| format!("reading the stream failed: {e}"))?; + if read == 0 { + return Ok(None); + } + if bytes.len() > MAX_LINE && bytes.last() != Some(&b'\n') { + return Err(format!("the stream sent a line longer than {MAX_LINE} bytes")); + } + Ok(Some(String::from_utf8_lossy(&bytes).into_owned())) + } + + /// The next event, `None` at the end of the stream. + pub fn next_event(&mut self) -> Result, String> { + let mut name = String::new(); + let mut data: Vec = Vec::new(); + let mut size = 0usize; + loop { + let Some(line) = self.line()? else { + return Ok(if data.is_empty() && name.is_empty() { None } else { Some(Event { name, data: data.join("\n") }) }); + }; + let line = line.trim_end_matches(['\n', '\r']); + if line.is_empty() { + if data.is_empty() && name.is_empty() { + continue; + } + return Ok(Some(Event { name, data: data.join("\n") })); + } + if line.starts_with(':') { + continue; + } + if let Some(rest) = line.strip_prefix("event:") { + name = rest.trim().to_string(); + } else if let Some(rest) = line.strip_prefix("data:") { + let part = rest.strip_prefix(' ').unwrap_or(rest); + size = size.saturating_add(part.len() + 1); + if size > MAX_EVENT { + return Err(format!("the stream sent an event larger than {MAX_EVENT} bytes")); + } + data.push(part.to_string()); + } + // Other fields (`id:`, `retry:`) are not used by either dialect. + } + } +} + +/// Read the stream's events on their own thread, so the caller can stop waiting at any moment +/// (Stop) without depending on the network to answer. The thread ends at the end of the stream, +/// on an error, or at its next event once the receiver is dropped. +pub fn spawn_events(body: Box) -> Receiver> { + let (tx, rx) = sync_channel(64); + let spawned = std::thread::Builder::new().name("figcraft-agent-sse".into()).spawn(move || { + let mut sse = Sse::new(body); + loop { + match sse.next_event() { + Ok(Some(e)) => { + if tx.send(Ok(e)).is_err() { + return; + } + } + Ok(None) => return, + Err(e) => { + let _ = tx.send(Err(e)); + return; + } + } + } + }); + if let Err(e) = spawned { + let (tx, rx) = sync_channel(1); + let _ = tx.send(Err(format!("can't read the answer: {e}"))); + return rx; + } + rx +} + +/// The next event from [`spawn_events`], checking `cancel` while waiting: `Err("stopped")` when it +/// is set, `Ok(None)` at the end of the stream. +pub fn next(events: &Receiver>, cancel: &std::sync::atomic::AtomicBool) -> Result, String> { + use std::sync::atomic::Ordering; + use std::sync::mpsc::RecvTimeoutError; + loop { + if cancel.load(Ordering::Relaxed) { + return Err("stopped".to_string()); + } + match events.recv_timeout(std::time::Duration::from_millis(100)) { + Ok(Ok(e)) => return Ok(Some(e)), + Ok(Err(e)) => return Err(e), + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return Ok(None), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn events_join_data_lines_and_keep_their_name() { + let stream = "event: text\ndata: {\"a\":1}\ndata: {\"b\":2}\n\ndata: [DONE]\n\n"; + let mut sse = Sse::new(Cursor::new(stream.as_bytes())); + let first = sse.next_event().expect("read").expect("one event"); + assert_eq!(first.name, "text"); + assert_eq!(first.data, "{\"a\":1}\n{\"b\":2}"); + let second = sse.next_event().expect("read").expect("another"); + assert_eq!(second.name, ""); + assert_eq!(second.data, "[DONE]"); + assert!(sse.next_event().expect("read").is_none()); + } + + #[test] + fn comments_and_windows_newlines_are_tolerated() { + let stream = ": keep-alive\r\n\r\ndata: hi\r\n\r\n"; + let mut sse = Sse::new(Cursor::new(stream.as_bytes())); + let e = sse.next_event().expect("read").expect("one event"); + assert_eq!(e.data, "hi"); + } + + #[test] + fn an_unterminated_last_event_is_still_delivered() { + let mut sse = Sse::new(Cursor::new(b"data: last".as_slice())); + let e = sse.next_event().expect("read").expect("one event"); + assert_eq!(e.data, "last"); + assert!(sse.next_event().expect("read").is_none()); + } + + #[test] + fn an_endless_line_is_refused_instead_of_kept() { + let long = format!("data: {}", "x".repeat(MAX_LINE + 10)); + let mut sse = Sse::new(Cursor::new(long.into_bytes())); + assert!(sse.next_event().is_err()); + } + + #[test] + fn stop_ends_the_wait_without_the_stream_answering() { + // A reader that never sends anything. + struct Silent; + impl std::io::Read for Silent { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + std::thread::sleep(std::time::Duration::from_secs(30)); + Ok(0) + } + } + let events = spawn_events(Box::new(std::io::BufReader::new(Silent))); + let cancel = std::sync::atomic::AtomicBool::new(true); + assert_eq!(next(&events, &cancel), Err("stopped".to_string())); + } +} diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index 3485629f3..6ab12a81f 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -187,6 +187,7 @@ node_props! { Measurements => measurements, Board => board, ScaleFactor => scale_factor, + Motion => motion, } /// A document-level property. Lists of entries with ids (styles, comments, variable collections, @@ -263,6 +264,9 @@ pub enum Entry { Image(String), /// A voter's ballot in a board's vote (value: the layer ids voted on). Ballot(String), + /// A page's motion timeline settings (value: + /// [`TimelineSettings`](figcraft_doc::anim::motion::TimelineSettings)). + Timeline(NodeId), } /// One synced value a change writes: a node property, a document-level property or a @@ -362,7 +366,7 @@ impl Entry { Entry::Comment(_) => Some(Family::Comments), Entry::Collection(_) => Some(Family::Collections), Entry::Variable(_) => Some(Family::Variables), - Entry::DevSnapshot(_) | Entry::Image(_) | Entry::Ballot(_) => None, + Entry::DevSnapshot(_) | Entry::Image(_) | Entry::Ballot(_) | Entry::Timeline(_) => None, } } @@ -377,7 +381,7 @@ impl Entry { Entry::Variable(id) => Some(id_space(id, VARIABLE_ID_PREFIX)), Entry::Collection(id) => Some(id_space(id, COLLECTION_ID_PREFIX)), Entry::Comment(id) => Some(space_of(*id)), - Entry::DevSnapshot(_) | Entry::Image(_) | Entry::Ballot(_) => None, + Entry::DevSnapshot(_) | Entry::Image(_) | Entry::Ballot(_) | Entry::Timeline(_) => None, } } @@ -391,6 +395,7 @@ impl Entry { Entry::DevSnapshot(id) => format!("ready-for-dev snapshot of {id}"), Entry::Image(hash) => format!("image {hash}"), Entry::Ballot(voter) => format!("ballot of {voter}"), + Entry::Timeline(page) => format!("timeline of {page}"), } } @@ -401,7 +406,7 @@ impl Entry { Entry::Comment(_) => Some(Family::Comments), Entry::Collection(_) => Some(Family::Collections), Entry::Variable(_) => Some(Family::Variables), - Entry::DevSnapshot(_) | Entry::Image(_) | Entry::Ballot(_) => None, + Entry::DevSnapshot(_) | Entry::Image(_) | Entry::Ballot(_) | Entry::Timeline(_) => None, } } } diff --git a/crates/collab/src/delta_snapshot/encode.rs b/crates/collab/src/delta_snapshot/encode.rs index ae75952b3..e3f1275ca 100644 --- a/crates/collab/src/delta_snapshot/encode.rs +++ b/crates/collab/src/delta_snapshot/encode.rs @@ -162,8 +162,11 @@ fn estimate_decode_charge(meta: &WireMeta, vectors: &[VectorNetwork], records: & } fn encode_one_node(node: &Node, pos: String, seen: &HashMap, interner: &mut VectorInterner) -> Result { + // Motion has no field delta (a new wire variant needs a version bump): an instance animated + // differently from its source goes as a full record, or it would decode with the source's motion. if let Some(src_id) = node.source && let Some(src) = seen.get(&src_id) + && src.motion == node.motion { let deltas = diff_mirror_fields(src, node, interner)?; return Ok(WireRecord::Mirror(Box::new(MirrorWire { diff --git a/crates/collab/src/delta_snapshot/fields.rs b/crates/collab/src/delta_snapshot/fields.rs index 240242d6e..2358d4988 100644 --- a/crates/collab/src/delta_snapshot/fields.rs +++ b/crates/collab/src/delta_snapshot/fields.rs @@ -170,6 +170,8 @@ fn every_node_field_visited(n: &Node) { dev_resources: _, measurements: _, board: _, + // Not a delta: `encode_one_node` sends a node whose motion differs from its source in full. + motion: _, } = n; } diff --git a/crates/collab/src/delta_snapshot_tests.rs b/crates/collab/src/delta_snapshot_tests.rs index abe1a4100..19d3799ce 100644 --- a/crates/collab/src/delta_snapshot_tests.rs +++ b/crates/collab/src/delta_snapshot_tests.rs @@ -168,6 +168,27 @@ fn mirror_delta_preserves_paint_color_alpha_and_signed_zero() { assert_docs_json_eq(legacy.document(), decoded.document(), "legacy parity"); } +#[test] +fn a_mirror_keeps_its_own_motion() { + use figcraft_doc::anim::motion::{AnimProperty, AnimValue}; + let mut doc = Document::new("Motion"); + let page = doc.first_page().unwrap(); + let src = doc.create(page, NodeKind::Rectangle, "Src", 0.0, 0.0, 100.0, 50.0).unwrap(); + let mut mirror = doc.node(src).unwrap().clone(); + mirror.id = doc.alloc_id(); + mirror.parent = None; + mirror.source = Some(src); + mirror.motion.ensure_track(AnimProperty::Opacity).set_key(500, AnimValue::Scalar(0.25), None); + let id = mirror.id; + doc.insert(mirror, page, None).unwrap(); + doc.take_dirty(); + + let replica = Replica::new(doc); + let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 16 << 20, Limits::default().max_nodes).unwrap(); + assert!(!decoded.document().node(id).unwrap().motion.is_empty(), "the instance's own motion survives"); + assert_docs_json_eq(replica.document(), decoded.document(), "exact structural equality"); +} + #[test] fn corrupt_hash_image_matches_legacy_join_parity() { let mut doc = Document::new("BadImage"); diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index ee12befc7..493ca3bc9 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -177,6 +177,30 @@ fn style(id: &str) -> Style { } } +#[test] +fn timeline_settings_round_trip() { + let (a, page, _, _) = setup(); + let mut b = a.document().clone(); + b.timelines.insert(page, figcraft_doc::anim::motion::TimelineSettings { duration_ms: 4000, fps: 24, looping: true }); + let changes = round_trip(&a, &b); + assert!(matches!(changes.as_slice(), [Change::Put { entry: Entry::Timeline(p), .. }] if *p == page), "{changes:#?}"); + assert!(round_trip(&a, a.document()).is_empty(), "a file without timeline settings sends nothing"); + // Each page's timeline is its own entry, so two pages are two changes. + let a2 = diff(&a, &b).unwrap().replica; + let mut c = b.clone(); + let other = c.add_page("Second"); + c.timelines.insert(other, figcraft_doc::anim::motion::TimelineSettings { duration_ms: 1000, fps: 12, looping: false }); + let changes = round_trip(&a2, &c); + assert!( + changes.iter().any(|ch| matches!(ch, Change::Put { entry: Entry::Timeline(p), .. } if *p == other)), + "the new page's timeline travels on its own: {changes:#?}" + ); + assert!( + !changes.iter().any(|ch| matches!(ch, Change::Put { entry: Entry::Timeline(p), .. } if *p == page)), + "the page set up earlier is not sent again" + ); +} + #[test] fn document_level_data_round_trips() { let (a, page, _, kids) = setup(); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index 02750df70..472178deb 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -422,7 +422,9 @@ pub(crate) fn diff(a: &Document, b: &Document, out: &mut Vec) -> Result< VARIABLES.diff(a, b, out)?; diff_map(&a.dev_snapshots, &b.dev_snapshots, |x, y| Arc::ptr_eq(x, y) || x == y, |k| Entry::DevSnapshot(*k), Json::of, out)?; diff_map(&a.images, &b.images, |x, y| x == y, |k| Entry::Image(k.clone()), image_json, out)?; - diff_map(&a.votes, &b.votes, |x, y| x == y, |k| Entry::Ballot(k.clone()), Json::of, out) + diff_map(&a.votes, &b.votes, |x, y| x == y, |k| Entry::Ballot(k.clone()), Json::of, out)?; + // A timeline belongs to one page: two people setting up different pages both keep their edit. + diff_map(&a.timelines, &b.timelines, |x, y| x == y, |k| Entry::Timeline(*k), Json::of, out) } /// [`apply_indexed`] for one change on its own. @@ -499,6 +501,11 @@ pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Ind Entry::Ballot(k) => { doc.votes.insert(k.clone(), value.read("ballot")?); } + Entry::Timeline(k) => { + // `TimelineSettings` clamps on read (duration and fps), so an edit-capable peer + // cannot hand the ruler a duration it would loop to forever. + doc.timelines.insert(*k, value.read("timeline settings")?); + } }, Change::Remove { entry } => match entry { Entry::Style(k) => STYLES.remove(doc, k, index), @@ -523,6 +530,9 @@ pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Ind Entry::Ballot(k) => { doc.votes.remove(k); } + Entry::Timeline(k) => { + doc.timelines.remove(k); + } }, _ => return Err(Error::Invalid("not a document-level change".into())), } @@ -560,6 +570,7 @@ pub(crate) fn entry_value(doc: &Document, entry: &Entry) -> Result, Entry::DevSnapshot(k) => doc.dev_snapshots.get(k).map(|s| Json::of(s.as_ref())), Entry::Image(k) => doc.images.get(k).map(image_json), Entry::Ballot(k) => doc.votes.get(k).map(Json::of), + Entry::Timeline(k) => doc.timelines.get(k).map(Json::of), }; value.transpose() } @@ -574,6 +585,7 @@ pub(crate) fn has(doc: &Document, entry: &Entry) -> bool { Entry::DevSnapshot(k) => doc.dev_snapshots.contains_key(k), Entry::Image(k) => doc.images.contains_key(k), Entry::Ballot(k) => doc.votes.contains_key(k), + Entry::Timeline(k) => doc.timelines.contains_key(k), } } diff --git a/crates/collab/src/merge.rs b/crates/collab/src/merge.rs index 3b6ebdce8..717fc6a3d 100644 --- a/crates/collab/src/merge.rs +++ b/crates/collab/src/merge.rs @@ -104,6 +104,7 @@ impl fmt::Display for Key { Entry::DevSnapshot(k) => write!(f, "devSnapshot/{k}"), Entry::Image(k) => write!(f, "image/{k}"), Entry::Ballot(k) => write!(f, "ballot/{k}"), + Entry::Timeline(k) => write!(f, "timeline/{k}"), }, } } diff --git a/crates/doc/src/anim/mod.rs b/crates/doc/src/anim/mod.rs new file mode 100644 index 000000000..3085b0a5c --- /dev/null +++ b/crates/doc/src/anim/mod.rs @@ -0,0 +1,7 @@ +//! Animation: the timeline keyframe data model. +//! +//! The code stays free of any UI or rendering dependency so the engine, the canvas and the +//! timeline editor can all share it. Prototype transitions and Smart Animate play from +//! `present`, which already owns the poses and the interpolation. + +pub mod motion; diff --git a/crates/doc/src/anim/motion/clip.rs b/crates/doc/src/anim/motion/clip.rs new file mode 100644 index 000000000..5eef534ad --- /dev/null +++ b/crates/doc/src/anim/motion/clip.rs @@ -0,0 +1,499 @@ +//! Animation clips: one clip animates one property over a span. +//! +//! A clip animates one *kind* of change (position, scale, rotation, size, opacity) relative to +//! whatever the node would otherwise look like at that time. + +use super::easing::Ease; +use super::value::{AnimProperty, lerp_vec2}; +use figcraft_geom::Vec2; +use serde::{Deserialize, Serialize}; + +/// What a clip changes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ClipKind { + Position, + Scale, + Rotation, + /// Width and height. + Size, + Opacity, +} + +impl ClipKind { + pub const ALL: [ClipKind; 5] = [ClipKind::Position, ClipKind::Scale, ClipKind::Rotation, ClipKind::Size, ClipKind::Opacity]; + + pub fn name(&self) -> &'static str { + match self { + ClipKind::Position => "Position", + ClipKind::Scale => "Scale", + ClipKind::Rotation => "Rotation", + ClipKind::Size => "Size", + ClipKind::Opacity => "Opacity", + } + } + + /// Animatable properties this kind of clip drives. + pub fn properties(&self) -> &'static [AnimProperty] { + match self { + ClipKind::Position => &[AnimProperty::Position], + ClipKind::Scale => &[AnimProperty::Scale], + ClipKind::Rotation => &[AnimProperty::Rotation], + ClipKind::Size => &[AnimProperty::Width, AnimProperty::Height], + ClipKind::Opacity => &[AnimProperty::Opacity], + } + } + + /// Value that leaves the node unchanged (`.x` only for scalar kinds). + pub fn neutral(&self) -> Vec2 { + match self { + ClipKind::Position | ClipKind::Rotation => Vec2::ZERO, + ClipKind::Scale | ClipKind::Size => Vec2::new(1.0, 1.0), + ClipKind::Opacity => Vec2::new(1.0, 0.0), + } + } + + /// Directions the inspector offers for this kind. + pub fn directions(&self) -> &'static [ClipDirection] { + use ClipDirection::{ + Both, Bottom, BottomLeft, BottomRight, Clockwise, CounterClockwise, Horizontal, Left, Right, Top, TopLeft, TopRight, Vertical, + }; + match self { + ClipKind::Position => &[Top, Bottom, Left, Right, TopLeft, TopRight, BottomLeft, BottomRight], + ClipKind::Rotation => &[Clockwise, CounterClockwise], + ClipKind::Scale | ClipKind::Size => &[Both, Horizontal, Vertical], + ClipKind::Opacity => &[], + } + } + + pub fn default_direction(&self) -> ClipDirection { + match self { + ClipKind::Position => ClipDirection::Bottom, + ClipKind::Rotation => ClipDirection::Clockwise, + _ => ClipDirection::Both, + } + } + + /// What `amount` means: distance in px (Position), start/end factor (Scale, Size), degrees + /// (Rotation), start/end opacity (Opacity). + pub fn default_amount(&self) -> f32 { + match self { + ClipKind::Position => 100.0, + ClipKind::Scale | ClipKind::Size => 0.5, + ClipKind::Rotation => 90.0, + ClipKind::Opacity => 0.0, + } + } +} + +/// The "Type" dropdown of a clip. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ClipMode { + /// Slide in: starts away from the node's normal state and settles into it. + #[default] + In, + /// Slide out: starts at the normal state and moves away. + Out, + /// Free `from` / `to` values. + Custom, +} + +impl ClipMode { + /// Label for a kind, e.g. "Slide in" for Position, "Scale in" for Scale. + pub fn label(&self, kind: ClipKind) -> String { + let verb = match kind { + ClipKind::Position => "Slide", + ClipKind::Scale => "Scale", + ClipKind::Rotation => "Rotate", + ClipKind::Size => "Resize", + ClipKind::Opacity => "Fade", + }; + match self { + ClipMode::In => format!("{verb} in"), + ClipMode::Out => format!("{verb} out"), + ClipMode::Custom => "Custom".to_string(), + } + } +} + +/// Where a clip comes from / goes to, or how it turns. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ClipDirection { + Top, + Bottom, + Left, + Right, + TopLeft, + TopRight, + BottomLeft, + BottomRight, + Clockwise, + CounterClockwise, + /// Scale and size: both axes. + Both, + /// Scale and size: width only. + Horizontal, + /// Scale and size: height only. + Vertical, +} + +impl ClipDirection { + /// Unit vector in y-down parent space for the position directions. + pub fn vector(&self) -> Vec2 { + const D: f64 = std::f64::consts::FRAC_1_SQRT_2; + match self { + ClipDirection::Top => Vec2::new(0.0, -1.0), + ClipDirection::Bottom => Vec2::new(0.0, 1.0), + ClipDirection::Left => Vec2::new(-1.0, 0.0), + ClipDirection::Right => Vec2::new(1.0, 0.0), + ClipDirection::TopLeft => Vec2::new(-D, -D), + ClipDirection::TopRight => Vec2::new(D, -D), + ClipDirection::BottomLeft => Vec2::new(-D, D), + ClipDirection::BottomRight => Vec2::new(D, D), + _ => Vec2::ZERO, + } + } + + /// Axis mask for scale / size: which axes the amount applies to. + fn axes(&self) -> Vec2 { + match self { + ClipDirection::Horizontal => Vec2::new(1.0, 0.0), + ClipDirection::Vertical => Vec2::new(0.0, 1.0), + _ => Vec2::new(1.0, 1.0), + } + } + + /// Dropdown label: "From bottom" / "To bottom", "Clockwise", "Horizontal". + pub fn label(&self, mode: ClipMode) -> String { + let lead = if mode == ClipMode::Out { "To" } else { "From" }; + let side = |s: &str| format!("{lead} {s}"); + match self { + ClipDirection::Top => side("top"), + ClipDirection::Bottom => side("bottom"), + ClipDirection::Left => side("left"), + ClipDirection::Right => side("right"), + ClipDirection::TopLeft => side("top left"), + ClipDirection::TopRight => side("top right"), + ClipDirection::BottomLeft => side("bottom left"), + ClipDirection::BottomRight => side("bottom right"), + ClipDirection::Clockwise => "Clockwise".into(), + ClipDirection::CounterClockwise => "Counter-clockwise".into(), + ClipDirection::Both => "Both".into(), + ClipDirection::Horizontal => "Horizontal".into(), + ClipDirection::Vertical => "Vertical".into(), + } + } +} + +/// How often a clip's cycle runs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ClipRepeat { + #[default] + Once, + /// Run this many cycles (1 = once). + Times(u32), + /// Keep cycling until the end of the timeline. + Infinite, +} + +fn yes() -> bool { + true +} +fn is_yes(v: &bool) -> bool { + *v +} +fn is_no(v: &bool) -> bool { + !*v +} +fn is_zero(v: &Vec2) -> bool { + v.x == 0.0 && v.y == 0.0 +} +fn is_once(r: &ClipRepeat) -> bool { + *r == ClipRepeat::Once +} +fn default_duration() -> u32 { + 500 +} + +/// One clip on a node's timeline (a "Position", "Scale", ... bar). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Clip { + /// Unique among the node's clips; stable across edits so the UI can keep a selection. + pub id: u32, + pub kind: ClipKind, + /// Slide in / Slide out / Custom. + #[serde(default)] + pub mode: ClipMode, + #[serde(default = "default_direction")] + pub direction: ClipDirection, + /// Distance (px), scale or size factor, degrees, or opacity. + #[serde(default)] + pub amount: f32, + /// Custom mode start value (`.x` only for rotation and opacity). + #[serde(default, skip_serializing_if = "is_zero")] + pub from: Vec2, + /// Custom mode end value. + #[serde(default, skip_serializing_if = "is_zero")] + pub to: Vec2, + /// When the clip starts, in ms on the timeline ("Delay"). + #[serde(default)] + pub delay_ms: u32, + /// Length of one cycle in ms. + #[serde(default = "default_duration")] + pub duration_ms: u32, + #[serde(default)] + pub easing: Ease, + #[serde(default, skip_serializing_if = "is_once")] + pub repeat: ClipRepeat, + /// Odd cycles play backwards, so repeating clips go there and back (Pulse, Float). + #[serde(default, skip_serializing_if = "is_no")] + pub yoyo: bool, + /// The eye toggle: hidden clips contribute nothing. + #[serde(default = "yes", skip_serializing_if = "is_yes")] + pub visible: bool, +} + +fn default_direction() -> ClipDirection { + ClipDirection::Bottom +} + +impl Clip { + /// A clip of `kind` with the kind's default direction/amount, 500ms, ease out, at t = 0. + pub fn new(kind: ClipKind, mode: ClipMode) -> Self { + Self { + id: 0, + kind, + mode, + direction: kind.default_direction(), + amount: kind.default_amount(), + from: kind.neutral(), + to: kind.neutral(), + delay_ms: 0, + duration_ms: 500, + easing: Ease::EaseOut, + repeat: ClipRepeat::Once, + yoyo: false, + visible: true, + } + } + + pub fn dir(mut self, d: ClipDirection) -> Self { + self.direction = d; + self + } + pub fn amount(mut self, a: f32) -> Self { + self.amount = a; + self + } + pub fn custom(mut self, from: Vec2, to: Vec2) -> Self { + self.mode = ClipMode::Custom; + self.from = from; + self.to = to; + self + } + pub fn delay(mut self, ms: u32) -> Self { + self.delay_ms = ms; + self + } + pub fn dur(mut self, ms: u32) -> Self { + self.duration_ms = ms; + self + } + pub fn ease(mut self, e: Ease) -> Self { + self.easing = e; + self + } + pub fn repeat(mut self, r: ClipRepeat) -> Self { + self.repeat = r; + self + } + pub fn yoyo(mut self) -> Self { + self.yoyo = true; + self + } + + /// Clamps fields to usable values after loading or UI edits. + pub fn sanitize(&mut self) { + self.duration_ms = self.duration_ms.max(1); + if !self.amount.is_finite() { + self.amount = self.kind.default_amount(); + } + for v in [&mut self.from, &mut self.to] { + if !v.x.is_finite() || !v.y.is_finite() { + *v = self.kind.neutral(); + } + } + self.easing = self.easing.sanitized(); + if let ClipRepeat::Times(0) = self.repeat { + self.repeat = ClipRepeat::Once; + } + } + + /// Start and end value of one cycle in the kind's own value space. + pub fn endpoints(&self) -> (Vec2, Vec2) { + let n = self.kind.neutral(); + if self.mode == ClipMode::Custom { + return (self.from, self.to); + } + if self.kind == ClipKind::Rotation { + let amount = self.amount as f64; + let turn = if self.direction == ClipDirection::CounterClockwise { amount } else { -amount }; + return if self.mode == ClipMode::In { (Vec2::new(-turn, 0.0), n) } else { (n, Vec2::new(turn, 0.0)) }; + } + let amount = self.amount as f64; + let away = match self.kind { + ClipKind::Position => { + let v = self.direction.vector(); + Vec2::new(v.x * amount, v.y * amount) + } + ClipKind::Scale | ClipKind::Size => { + let ax = self.direction.axes(); + Vec2::new(1.0 + (amount - 1.0) * ax.x, 1.0 + (amount - 1.0) * ax.y) + } + _ => Vec2::new(amount, 0.0), + }; + if self.mode == ClipMode::In { (away, n) } else { (n, away) } + } + + /// Total length in ms of all cycles, `None` for an infinite clip. + pub fn total_ms(&self) -> Option { + let d = self.duration_ms.max(1); + match self.repeat { + ClipRepeat::Once => Some(d), + ClipRepeat::Times(n) => Some(d.saturating_mul(n.max(1))), + ClipRepeat::Infinite => None, + } + } + + /// End of the clip on the timeline; infinite clips end with the timeline. + pub fn end_ms(&self, timeline_duration_ms: u32) -> u32 { + match self.total_ms() { + Some(total) => self.delay_ms.saturating_add(total), + None => timeline_duration_ms.max(self.delay_ms.saturating_add(self.duration_ms.max(1))), + } + } + + /// Eased progress through the clip at timeline time `t_ms`. + pub fn progress_at(&self, t_ms: f64) -> f32 { + let local = t_ms - self.delay_ms as f64; + if local.is_nan() || local <= 0.0 { + return 0.0; + } + let n = local / self.duration_ms.max(1) as f64; + let cycles = match self.repeat { + ClipRepeat::Once => Some(1u32), + ClipRepeat::Times(k) => Some(k.max(1)), + ClipRepeat::Infinite => None, + }; + if let Some(k) = cycles + && n >= k as f64 + { + let reversed = self.yoyo && (k - 1) % 2 == 1; + return if reversed { 0.0 } else { 1.0 }; + } + let idx = n.floor(); + let frac = (n - idx) as f32; + let reversed = self.yoyo && (idx as u64) % 2 == 1; + self.easing.ease(if reversed { 1.0 - frac } else { frac }) + } + + /// The clip's value (kind's own space) at timeline time `t_ms`. + pub fn value_at(&self, t_ms: f64) -> Vec2 { + let (a, b) = self.endpoints(); + lerp_vec2(a, b, self.progress_at(t_ms) as f64) + } +} + +#[cfg(test)] +mod tests { + use super::{Clip, ClipDirection, ClipKind, ClipMode, ClipRepeat}; + use crate::anim::motion::Ease; + use figcraft_geom::Vec2; + + #[test] + fn every_kind_and_direction_rests_on_the_layer_at_its_end() { + for kind in ClipKind::ALL { + assert!(!kind.properties().is_empty(), "{kind:?} drives a property"); + let dirs: Vec = if kind.directions().is_empty() { vec![ClipDirection::Both] } else { kind.directions().to_vec() }; + for mode in [ClipMode::In, ClipMode::Out] { + assert_ne!(mode.label(kind), ClipMode::Custom.label(kind)); + let labels: std::collections::HashSet = dirs.iter().map(|d| d.label(mode)).collect(); + assert_eq!(labels.len(), dirs.len(), "{kind:?}: each direction has its own label"); + for d in &dirs { + let c = Clip::new(kind, mode).dir(*d).ease(Ease::Linear).dur(1000); + // In arrives at the layer; Out leaves from it. + let rest = if mode == ClipMode::In { c.value_at(1000.0) } else { c.value_at(0.0) }; + let n = kind.neutral(); + assert!((rest.x - n.x).abs() < 1e-6 && (rest.y - n.y).abs() < 1e-6, "{kind:?} {mode:?} {d:?}: {rest:?}"); + let away = if mode == ClipMode::In { c.value_at(0.0) } else { c.value_at(1000.0) }; + assert!(away != rest, "{kind:?} {mode:?} {d:?} moves the layer"); + } + } + } + // Each position direction points its own way. + let vectors: Vec = ClipKind::Position.directions().iter().map(ClipDirection::vector).collect(); + for (i, a) in vectors.iter().enumerate() { + assert!((a.hypot() - 1.0).abs() < 1e-9); + assert!(vectors.iter().skip(i + 1).all(|b| b != a)); + } + } + + fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-3 + } + + #[test] + fn slide_in_from_bottom_offsets_y() { + let c = Clip::new(ClipKind::Position, ClipMode::In).dir(ClipDirection::Bottom).amount(116.0).delay(997).dur(300).ease(Ease::Linear); + assert_eq!(c.endpoints(), (Vec2::new(0.0, 116.0), Vec2::ZERO)); + assert_eq!(c.value_at(0.0), Vec2::new(0.0, 116.0)); + assert!(close(c.value_at(997.0 + 150.0).y, 58.0)); + assert_eq!(c.value_at(1297.0), Vec2::ZERO); + } + + #[test] + fn slide_out_ends_away() { + let c = Clip::new(ClipKind::Position, ClipMode::Out).dir(ClipDirection::Left).amount(80.0).dur(200).ease(Ease::Linear); + assert_eq!(c.value_at(0.0), Vec2::ZERO); + assert_eq!(c.value_at(1000.0), Vec2::new(-80.0, 0.0)); + } + + #[test] + fn scale_opacity_rotation_endpoints() { + let s = Clip::new(ClipKind::Scale, ClipMode::In).amount(0.5); + assert_eq!(s.endpoints(), (Vec2::new(0.5, 0.5), Vec2::new(1.0, 1.0))); + let o = Clip::new(ClipKind::Opacity, ClipMode::In).amount(0.0); + assert_eq!(o.endpoints(), (Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0))); + let r = Clip::new(ClipKind::Rotation, ClipMode::In).amount(90.0).dir(ClipDirection::Clockwise); + assert_eq!(r.endpoints(), (Vec2::new(90.0, 0.0), Vec2::ZERO)); + let r = Clip::new(ClipKind::Rotation, ClipMode::Out).amount(90.0).dir(ClipDirection::Clockwise); + assert_eq!(r.endpoints(), (Vec2::ZERO, Vec2::new(-90.0, 0.0))); + } + + #[test] + fn repeat_and_yoyo() { + let c = Clip::new(ClipKind::Scale, ClipMode::Custom) + .custom(Vec2::new(1.0, 1.0), Vec2::new(2.0, 2.0)) + .ease(Ease::Linear) + .dur(100) + .repeat(ClipRepeat::Infinite) + .yoyo(); + assert!(close(c.value_at(50.0).x, 1.5)); + assert!(close(c.value_at(150.0).x, 1.5)); + assert!(close(c.value_at(110.0).x, 1.9)); + } + + #[test] + fn span_of_clips() { + let c = Clip::new(ClipKind::Opacity, ClipMode::In).delay(200).dur(300); + assert_eq!(c.end_ms(2000), 500); + assert_eq!(c.clone().repeat(ClipRepeat::Times(3)).end_ms(2000), 1100); + assert_eq!(c.clone().repeat(ClipRepeat::Infinite).end_ms(2000), 2000); + } + + #[test] + fn labels() { + assert_eq!(ClipMode::In.label(ClipKind::Position), "Slide in"); + assert_eq!(ClipDirection::Bottom.label(ClipMode::In), "From bottom"); + assert_eq!(ClipDirection::Bottom.label(ClipMode::Out), "To bottom"); + } +} diff --git a/crates/doc/src/anim/motion/easing.rs b/crates/doc/src/anim/motion/easing.rs new file mode 100644 index 000000000..50e49a15e --- /dev/null +++ b/crates/doc/src/anim/motion/easing.rs @@ -0,0 +1,558 @@ +//! Easing curves for Motion keyframes and clips. +//! +//! An [`Ease`] maps normalised segment time `t` in `0..=1` to normalised progress (0 at the start +//! value, 1 at the end value). Back and spring curves may leave `0..=1` in between; every curve is +//! exactly 0 at `t = 0` and 1 at `t = 1`. + +use serde::{Deserialize, Serialize}; + +/// Elasticity of the default custom spring. +pub const DEFAULT_ELASTICITY: f32 = 0.25; + +/// Usable elasticity: 0 is (near) critically damped, 1.2 is as bouncy as the mapping allows. +pub const ELASTICITY_RANGE: (f32, f32) = (0.0, 1.2); + +/// y(t) of the unit cubic bezier through (0,0), (x1,y1), (x2,y2), (1,1), i.e. CSS `cubic-bezier`. +pub fn cubic_bezier(c: [f32; 4], t: f32) -> f32 { + let [x1, y1, x2, y2] = c; + let (x1, x2) = (x1.clamp(0.0, 1.0), x2.clamp(0.0, 1.0)); + if !t.is_finite() { + return 0.0; + } + let t = t.clamp(0.0, 1.0); + if t == 0.0 || t == 1.0 { + return t; + } + let sample = |p1: f32, p2: f32, s: f32| { + let u = 1.0 - s; + 3.0 * u * u * s * p1 + 3.0 * u * s * s * p2 + s * s * s + }; + let dx = |s: f32| { + let u = 1.0 - s; + 3.0 * u * u * x1 + 6.0 * u * s * (x2 - x1) + 3.0 * s * s * (1.0 - x2) + }; + let mut s = t; + for _ in 0..8 { + let err = sample(x1, x2, s) - t; + if err.abs() < 1e-6 { + return sample(y1, y2, s); + } + let d = dx(s); + if d.abs() < 1e-6 { + break; + } + s -= err / d; + } + let (mut lo, mut hi) = (0.0f32, 1.0f32); + s = t; + for _ in 0..40 { + let x = sample(x1, x2, s); + if (x - t).abs() < 1e-6 { + break; + } + if x < t { + lo = s; + } else { + hi = s; + } + s = (lo + hi) / 2.0; + } + sample(y1, y2, s) +} + +/// Step response of a damped spring (starts at 0, rests at 1) in normalised units. +pub fn spring_step(zeta: f32, w0: f32, tau: f32) -> f32 { + if zeta < 1.0 - 1e-4 { + let wd = w0 * (1.0 - zeta * zeta).sqrt(); + let a = zeta * w0; + 1.0 - (-a * tau).exp() * ((wd * tau).cos() + a / wd * (wd * tau).sin()) + } else if zeta <= 1.0 + 1e-4 { + 1.0 - (-w0 * tau).exp() * (1.0 + w0 * tau) + } else { + let s = (zeta * zeta - 1.0).sqrt(); + let (r1, r2) = (-w0 * (zeta - s), -w0 * (zeta + s)); + 1.0 - (r2 * (r1 * tau).exp() - r1 * (r2 * tau).exp()) / (r2 - r1) + } +} + +fn spring_params(mass: f32, stiffness: f32, damping: f32) -> (f32, f32) { + let (m, k, c) = (mass.max(0.01), stiffness.max(0.01), damping.max(0.0)); + (c / (2.0 * (k * m).sqrt()), (k / m).sqrt()) +} + +/// Seconds a mass/stiffness/damping spring needs to settle (envelope below 0.1%), capped at 4s. +pub fn spring_settle_secs(mass: f32, stiffness: f32, damping: f32) -> f32 { + let (zeta, w0) = spring_params(mass, stiffness, damping); + let rate = if zeta < 1.0 { zeta * w0 } else { w0 * (zeta - (zeta * zeta - 1.0).sqrt()) }; + if rate <= 1e-3 { + return 4.0; + } + (6.9 / rate).clamp(0.1, 4.0) +} + +/// Spring step response at time `tau` seconds (starts at 0, settles at 1). +pub fn spring_at(mass: f32, stiffness: f32, damping: f32, tau: f32) -> f32 { + let (zeta, w0) = spring_params(mass, stiffness, damping); + spring_step(zeta, w0, tau) +} + +/// Settle threshold: a spring counts as settled once it is within 0.1% of its target. +pub const SPRING_SETTLE_EPS: f32 = 0.001; + +/// `K = −ln(SPRING_SETTLE_EPS)` = 6.9078, the constant of the elasticity → frequency mapping. +pub const SPRING_SETTLE_K: f32 = 6.907_755; + +/// Lowest damping ratio the mapping reaches (elasticity 1.2 and above). +const ZETA_MIN: f32 = 0.03; +/// Highest damping ratio the mapping reaches (elasticity 0), just short of critical damping. +const ZETA_MAX: f32 = 0.9999; + +/// Damping ratio of an elasticity: `ζ = clamp(1 − e, 0.03, 0.9999)`. +pub fn spring_damping_ratio(elasticity: f32) -> f32 { + let e = if elasticity.is_finite() { elasticity.clamp(ELASTICITY_RANGE.0, ELASTICITY_RANGE.1) } else { DEFAULT_ELASTICITY }; + (1.0 - e).clamp(ZETA_MIN, ZETA_MAX) +} + +/// How the settle envelope bounds the oscillation, and so how `ω₀` is recovered from it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SpringAlgorithm { + /// The triangle inequality's loose bound on `|cos + B sin|`, i.e. `1 + B` with + /// `B = ζ/√(1−ζ²)`. Never underestimates the envelope, so the settled frequency comes out + /// a little high and the curve finishes early. + #[default] + Envelope, + /// The auxiliary-angle amplitude `1/√(1−ζ²)` — the peak the oscillation can actually reach — + /// so `ω₀` is the exact frequency of a spring that has decayed to the settle epsilon at the + /// end of the segment. + Tight, +} + +/// Natural frequency of an elasticity under `algorithm`, in units of 1 / settle duration: +/// `Envelope` → `ω₀ = (K + ln(1 + ζ/√(1−ζ²))) / ζ`; `Tight` → `ω₀ = (K − ½ln(1−ζ²)) / ζ`. +pub fn spring_angular_frequency(elasticity: f32, algorithm: SpringAlgorithm) -> f32 { + let z = spring_damping_ratio(elasticity); + let root = (1.0 - z * z).max(1e-6).sqrt(); + let ln = match algorithm { + SpringAlgorithm::Envelope => (1.0 + z / root).ln(), + // ½·ln(1/(1−ζ²)) = −½·ln(1−ζ²). + SpringAlgorithm::Tight => -0.5 * (1.0 - z * z).max(1e-6).ln(), + }; + (SPRING_SETTLE_K + ln) / z +} + +/// `(stiffness, damping)` of an elasticity at `mass`: `k = mass·ω₀²`, `c = 2·mass·ζ·ω₀`. +pub fn spring_stiffness_damping(elasticity: f32, mass: f32, algorithm: SpringAlgorithm) -> (f32, f32) { + let m = if mass.is_finite() && mass > 0.0 { mass } else { 1.0 }; + let (z, w0) = (spring_damping_ratio(elasticity), spring_angular_frequency(elasticity, algorithm)); + (m * w0 * w0, 2.0 * m * z * w0) +} + +/// Height of the first overshoot peak, as a fraction of the travel (0 without overshoot). +pub fn spring_overshoot(elasticity: f32) -> f32 { + let z = spring_damping_ratio(elasticity); + if z >= 1.0 { + return 0.0; + } + (-std::f32::consts::PI * z / (1.0 - z * z).sqrt()).exp() +} + +/// Spring response: progress at `t`, the fraction of the settle duration. The curve is the +/// closed-form step response of the mass/stiffness/damping triple the mapping derives from `e`. +pub fn spring_unit_response(elasticity: f32, algorithm: SpringAlgorithm, t: f32) -> f32 { + if !t.is_finite() { + return 0.0; + } + let t = t.clamp(0.0, 1.0); + if t == 0.0 || t == 1.0 { + return t; + } + let (z, w0) = (spring_damping_ratio(elasticity), spring_angular_frequency(elasticity, algorithm)); + let y = spring_step(z, w0, t); + // The response ends a hair short of 1 (that is what "settled to 0.1%" means); straighten the + // residual so the segment lands exactly on the next keyframe. + let end = spring_step(z, w0, 1.0); + y + (1.0 - end) * t +} + +/// Easing of one keyframe segment or clip. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub enum Ease { + /// Keep the start value until the next keyframe, then jump (stepped). + Hold, + #[default] + Linear, + EaseIn, + EaseOut, + EaseInOut, + EaseInBack, + EaseOutBack, + EaseInOutBack, + /// CSS-style control points `[x1, y1, x2, y2]`; x values are clamped to 0..=1. + CustomBezier([f32; 4]), + SpringGentle, + SpringQuick, + SpringBouncy, + SpringSlow, + /// Duration-based spring: runs for exactly the segment; `elasticity` in + /// [`ELASTICITY_RANGE`], the single knob the editor exposes. + CustomSpring { + #[serde(alias = "bounce")] + elasticity: f32, + /// Which settle envelope recovers the frequency (the loose bound, or the tight one). + #[serde(default)] + algorithm: SpringAlgorithm, + /// Mass the stiffness and damping are expressed against; 1 by default, the value the + /// elasticity mapping is calibrated at. + #[serde(default = "unit_mass")] + mass: f32, + }, +} + +/// Default mass of a spring: the mapping's calibration point. +pub fn unit_mass() -> f32 { + 1.0 +} + +/// Which tab of the easing editor a curve belongs to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EaseFamily { + Hold, + Curve, + Spring, +} + +impl Ease { + /// Presets in dropdown order (no custom entries). + pub const PRESETS: [(&'static str, Ease); 12] = [ + ("Hold", Ease::Hold), + ("Linear", Ease::Linear), + ("Ease in", Ease::EaseIn), + ("Ease out", Ease::EaseOut), + ("Ease in and out", Ease::EaseInOut), + ("Ease in back", Ease::EaseInBack), + ("Ease out back", Ease::EaseOutBack), + ("Ease in and out back", Ease::EaseInOutBack), + ("Gentle", Ease::SpringGentle), + ("Quick", Ease::SpringQuick), + ("Bouncy", Ease::SpringBouncy), + ("Slow", Ease::SpringSlow), + ]; + + pub fn bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> Self { + Ease::CustomBezier([x1.clamp(0.0, 1.0), y1, x2.clamp(0.0, 1.0), y2]) + } + + pub fn spring(elasticity: f32) -> Self { + Ease::spring_with(elasticity, SpringAlgorithm::Envelope, unit_mass()) + } + + /// A spring with the settle envelope and mass spelled out. + pub fn spring_with(elasticity: f32, algorithm: SpringAlgorithm, mass: f32) -> Self { + let e = if elasticity.is_finite() { elasticity.clamp(ELASTICITY_RANGE.0, ELASTICITY_RANGE.1) } else { DEFAULT_ELASTICITY }; + let m = if mass.is_finite() && mass > 0.0 { mass } else { unit_mass() }; + Ease::CustomSpring { elasticity: e, algorithm, mass: m } + } + + pub fn is_linear(&self) -> bool { + matches!(self, Ease::Linear) + } + + pub fn family(&self) -> EaseFamily { + match self { + Ease::Hold => EaseFamily::Hold, + Ease::SpringGentle | Ease::SpringQuick | Ease::SpringBouncy | Ease::SpringSlow | Ease::CustomSpring { .. } => EaseFamily::Spring, + _ => EaseFamily::Curve, + } + } + + pub fn is_spring(&self) -> bool { + self.family() == EaseFamily::Spring + } + + /// Control points `[x1, y1, x2, y2]` of every bezier-based curve; `None` for Hold and springs. + pub fn control_points(&self) -> Option<[f32; 4]> { + Some(match self { + Ease::Linear => [0.0, 0.0, 1.0, 1.0], + Ease::EaseIn => [0.42, 0.0, 1.0, 1.0], + Ease::EaseOut => [0.0, 0.0, 0.58, 1.0], + Ease::EaseInOut => [0.42, 0.0, 0.58, 1.0], + Ease::EaseInBack => [0.3, -0.05, 0.7, -0.5], + Ease::EaseOutBack => [0.45, 1.45, 0.8, 1.0], + Ease::EaseInOutBack => [0.7, -0.4, 0.4, 1.4], + Ease::CustomBezier(c) => *c, + _ => return None, + }) + } + + /// Elasticity of every spring (presets included); `None` for non-springs. + pub fn elasticity(&self) -> Option { + match self { + Ease::SpringGentle => Some(0.25), + Ease::SpringQuick => Some(0.42), + Ease::SpringBouncy => Some(0.7), + Ease::SpringSlow => Some(0.0), + Ease::CustomSpring { elasticity, .. } => Some(*elasticity), + _ => None, + } + } + + /// Settle envelope of every spring; `None` for non-springs. + pub fn spring_algorithm(&self) -> Option { + match self { + Ease::SpringGentle | Ease::SpringQuick | Ease::SpringBouncy | Ease::SpringSlow => Some(SpringAlgorithm::Envelope), + Ease::CustomSpring { algorithm, .. } => Some(*algorithm), + _ => None, + } + } + + /// Mass every spring's stiffness and damping are expressed against; `None` for non-springs. + pub fn mass(&self) -> Option { + match self { + Ease::SpringGentle | Ease::SpringQuick | Ease::SpringBouncy | Ease::SpringSlow => Some(unit_mass()), + Ease::CustomSpring { mass, .. } => Some(*mass), + _ => None, + } + } + + /// Name shown in the preset dropdown. + pub fn name(&self) -> &'static str { + if let Some((n, _)) = Self::PRESETS.iter().find(|(_, p)| p == self) { + return n; + } + match self { + Ease::CustomBezier(_) => "Custom bezier", + Ease::CustomSpring { .. } => "Custom spring", + _ => "Custom", + } + } + + /// The same curve as an editable custom curve. + pub fn to_custom(&self) -> Ease { + if let Some(c) = self.control_points() { + Ease::CustomBezier(c) + } else if let Some(b) = self.elasticity() { + Ease::spring_with(b, self.spring_algorithm().unwrap_or_default(), self.mass().unwrap_or_else(unit_mass)) + } else { + *self + } + } + + /// The curve with its parameters clamped to usable ranges. + pub fn sanitized(&self) -> Ease { + match self { + Ease::CustomBezier(c) => { + let f = |v: f32, d: f32| if v.is_finite() { v } else { d }; + Ease::bezier(f(c[0], 0.0), f(c[1], 0.0), f(c[2], 1.0), f(c[3], 1.0)) + } + Ease::CustomSpring { elasticity, algorithm, mass } => { + let e = if elasticity.is_finite() { elasticity.clamp(ELASTICITY_RANGE.0, ELASTICITY_RANGE.1) } else { DEFAULT_ELASTICITY }; + let m = if mass.is_finite() && *mass > 0.0 { *mass } else { unit_mass() }; + Ease::CustomSpring { elasticity: e, algorithm: *algorithm, mass: m } + } + e => *e, + } + } + + /// Eased progress for linear segment progress `t` (clamped to 0..=1). + pub fn ease(&self, t: f32) -> f32 { + if !t.is_finite() { + return 0.0; + } + let t = t.clamp(0.0, 1.0); + match self { + Ease::Hold => { + if t >= 1.0 { + 1.0 + } else { + 0.0 + } + } + Ease::Linear => t, + e => match (e.control_points(), e.elasticity()) { + (Some(c), _) => cubic_bezier(c, t), + (None, Some(b)) => spring_unit_response(b, e.spring_algorithm().unwrap_or_default(), t), + (None, None) => t, + }, + } + } + + /// `n + 1` points `[t, ease(t)]` for `t = 0, 1/n .. 1`, for drawing the graph. + pub fn sample(&self, n: usize) -> Vec<[f32; 2]> { + let n = n.max(1); + let mut out: Vec<[f32; 2]> = (0..=n).map(|i| i as f32 / n as f32).map(|t| [t, self.ease(t)]).collect(); + if matches!(self, Ease::Hold) { + let last = out.len() - 1; + out.insert(last, [1.0, 0.0]); + } + out + } + + /// Vertical extent `(min, max)` of the curve, always including 0 and 1. + pub fn value_range(&self) -> (f32, f32) { + self.sample(100).iter().fold((0.0f32, 1.0f32), |(lo, hi), p| (lo.min(p[1]), hi.max(p[1]))) + } +} + +#[cfg(test)] +mod tests { + use super::{ + Ease, SPRING_SETTLE_EPS, SpringAlgorithm, spring_angular_frequency, spring_at, spring_damping_ratio, spring_overshoot, spring_settle_secs, + spring_stiffness_damping, + }; + + #[test] + fn every_curve_stays_finite_and_lands_on_its_ends() { + let mut curves: Vec = Ease::PRESETS.iter().map(|(_, e)| *e).collect(); + // Steep and crossing control points push the solver off its fast path. + curves.extend([Ease::bezier(1.0, 0.0, 0.0, 1.0), Ease::bezier(0.0, 1.5, 1.0, -0.5), Ease::bezier(1.0, 1.0, 1.0, 0.0)]); + curves.push(Ease::spring_with(0.6, SpringAlgorithm::default(), 1.0)); + for e in curves { + for i in 0..=20 { + assert!(e.ease(i as f32 / 20.0).is_finite(), "{e:?}"); + } + assert!((e.ease(1.0) - 1.0).abs() < 1e-3, "{e:?} ends at 1"); + assert!(e.ease(f32::NAN).is_finite(), "{e:?}"); + } + } + + #[test] + fn heavily_damped_springs_settle_without_overshoot() { + // Critically damped (c = 2 * sqrt(k * m)) and overdamped. + for damping in [20.0, 60.0] { + let mut last = 0.0; + for i in 1..=40 { + let v = spring_at(1.0, 100.0, damping, i as f32 * 0.05); + assert!(v >= last - 1e-5 && v <= 1.0 + 1e-5, "damping {damping}: {v} after {last}"); + last = v; + } + assert!(last > 0.9, "damping {damping} comes to rest near 1: {last}"); + let settle = spring_settle_secs(1.0, 100.0, damping); + assert!(settle > 0.0 && settle <= 4.0); + } + assert!(spring_settle_secs(1.0, 100.0, 60.0) > spring_settle_secs(1.0, 100.0, 20.0), "overdamped is slower"); + } + + #[test] + fn custom_curves_name_convert_and_sanitize() { + assert_ne!(Ease::bezier(0.2, 0.1, 0.3, 1.0).name(), Ease::Linear.name()); + assert_eq!(Ease::SpringBouncy.to_custom().elasticity(), Ease::SpringBouncy.elasticity()); + assert_eq!(Ease::EaseIn.to_custom().control_points(), Ease::EaseIn.control_points()); + assert_eq!(Ease::Hold.to_custom(), Ease::Hold); + let spring = Ease::CustomSpring { elasticity: f32::NAN, algorithm: SpringAlgorithm::default(), mass: -1.0 }.sanitized(); + assert!(spring.elasticity().is_some_and(f32::is_finite) && spring.mass().is_some_and(|m| m > 0.0)); + let bezier = Ease::CustomBezier([f32::NAN, f32::INFINITY, 0.5, 1.0]).sanitized(); + assert!(bezier.control_points().is_some_and(|c| c.iter().all(|v| v.is_finite()))); + } + + fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-3 + } + + fn all_curves() -> Vec { + let mut v: Vec = Ease::PRESETS.iter().map(|p| p.1).collect(); + v.extend([Ease::bezier(0.07, 0.97, 0.58, 1.0), Ease::spring(0.0), Ease::spring(0.25), Ease::spring(1.0), Ease::spring(1.2)]); + v + } + + #[test] + fn endpoints_are_exact() { + for e in all_curves() { + assert_eq!(e.ease(0.0), 0.0, "{e:?} start"); + assert_eq!(e.ease(1.0), 1.0, "{e:?} end"); + assert_eq!(e.ease(-3.0), 0.0); + assert_eq!(e.ease(7.0), 1.0); + assert_eq!(e.ease(f32::NAN), 0.0); + } + } + + #[test] + fn hold_steps() { + assert_eq!(Ease::Hold.ease(0.5), 0.0); + assert_eq!(Ease::Hold.ease(1.0), 1.0); + let pts = Ease::Hold.sample(4); + assert!(pts.contains(&[1.0, 0.0]) && pts.last() == Some(&[1.0, 1.0])); + } + + #[test] + fn standard_curves_have_expected_shape() { + assert!(Ease::EaseIn.ease(0.5) < 0.5); + assert!(Ease::EaseOut.ease(0.5) > 0.5); + assert!(close(Ease::EaseInOut.ease(0.5), 0.5)); + assert!(close(Ease::Linear.ease(0.3), 0.3)); + assert!((Ease::EaseInOut.ease(0.25) - 0.129).abs() < 0.01); + } + + #[test] + fn spring_mapping() { + // ζ = clamp(1 − e, .03, .9999); ω₀ = (K + ln(1 + ζ/√(1−ζ²)))/ζ; k = ω₀², c = 2ζω₀. + assert!(close(spring_damping_ratio(0.6), 0.4)); + assert!((spring_angular_frequency(0.6, SpringAlgorithm::Envelope) - 18.175).abs() < 0.01); + let (k, c) = spring_stiffness_damping(0.6, 1.0, SpringAlgorithm::Envelope); + assert!((k - 330.3).abs() < 0.5, "{k}"); + assert!((c - 14.54).abs() < 0.02, "{c}"); + // The mass only rescales the physical pair; ζ and ω₀ (and so the curve) stay put. + let (k2, c2) = spring_stiffness_damping(0.6, 2.0, SpringAlgorithm::Envelope); + assert!((k2 - 2.0 * k).abs() < 0.5 && (c2 - 2.0 * c).abs() < 0.05); + assert!((spring_overshoot(0.6) - 0.2538).abs() < 0.001); + // The mapping clamps at both ends; a higher elasticity is both faster and bouncier. + assert!(close(spring_damping_ratio(-2.0), 0.9999)); + assert!(close(spring_damping_ratio(5.0), 0.03)); + let env = SpringAlgorithm::Envelope; + assert!(spring_angular_frequency(1.0, env) > spring_angular_frequency(0.2, env)); + assert!(spring_overshoot(1.0) > spring_overshoot(0.2)); + // The segment is the settle duration: the curve peaks at 1 + overshoot and ends on 1. + for e in [0.0, 0.2, 0.5, 0.6, 0.8, 1.0] { + let unit = Ease::spring(e); + assert_eq!(unit.ease(1.0), 1.0); + let peak = (1..=1000).map(|i| unit.ease(i as f32 / 1000.0)).fold(0.0f32, f32::max); + assert!((peak - (1.0 + spring_overshoot(e))).abs() < 0.01, "{e}: {peak}"); + } + } + + #[test] + fn tight_envelope_is_the_exact_one() { + // Loose bound `1 + B` and auxiliary-angle amplitude `1/√(1−ζ²)` both hit the settle + // epsilon at t = 1, but the tight one is the peak the curve can actually reach, so it + // recovers a lower — exact — frequency and uses the whole segment. + for e in [0.0, 0.25, 0.6, 0.9] { + let z = spring_damping_ratio(e); + let root = (1.0 - z * z).sqrt(); + let a = spring_angular_frequency(e, SpringAlgorithm::Envelope); + let b = spring_angular_frequency(e, SpringAlgorithm::Tight); + assert!(b < a, "{e}: tight {b} should be below loose {a}"); + assert!(((-z * a).exp() * (1.0 + z / root) - SPRING_SETTLE_EPS).abs() < 2e-4, "{e} loose"); + assert!(((-z * b).exp() / root - SPRING_SETTLE_EPS).abs() < 2e-4, "{e} tight"); + } + // e = 0.6 → ζ = 0.4: (K − ½ln 0.84)/0.4 = 17.487. + assert!((spring_angular_frequency(0.6, SpringAlgorithm::Tight) - 17.487).abs() < 0.01); + // The tight curve runs at the lower, exact frequency, so at the same instant it has + // travelled a little less than the loose one. + let (loose, exact) = (Ease::spring(0.6), Ease::spring_with(0.6, SpringAlgorithm::Tight, 1.0)); + assert!(exact.ease(0.4) < loose.ease(0.4)); + assert_eq!(exact.ease(0.0), 0.0); + assert_eq!(exact.ease(1.0), 1.0); + } + + #[test] + fn springs_saved_as_bounce_still_load() { + let old: Ease = serde_json::from_str(r#"{"CustomSpring":{"bounce":0.4}}"#).unwrap(); + assert_eq!(old, Ease::spring(0.4)); + } + + #[test] + fn presets_and_names() { + assert_eq!(Ease::EaseOut.name(), "Ease out"); + assert_eq!(Ease::bezier(0.1, 0.2, 0.3, 0.4).name(), "Custom bezier"); + assert_eq!(Ease::spring(0.4).name(), "Custom spring"); + assert_eq!(Ease::SpringQuick.name(), "Quick"); + assert_eq!(Ease::default(), Ease::Linear); + } + + #[test] + fn serde_roundtrip() { + for e in all_curves() { + let back: Ease = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); + assert_eq!(back, e); + } + } +} diff --git a/crates/doc/src/anim/motion/eval.rs b/crates/doc/src/anim/motion/eval.rs new file mode 100644 index 000000000..7235e6315 --- /dev/null +++ b/crates/doc/src/anim/motion/eval.rs @@ -0,0 +1,416 @@ +//! Evaluating keyframes and clips at a point in time. +//! +//! Nothing here mutates the stored document. Two levels of API, cheapest first: +//! +//! * [`evaluate_node`]: pure function of one node and a time, returns the animated property values +//! as an [`EvaluatedNode`] (only the properties that are animated are `Some`). +//! * [`evaluate`]: one-shot convenience that returns an evaluated *copy* of the document. +//! +//! ## How a node's transform is animated +//! +//! `Node::transform` is decomposed around the node's centre `h = size / 2`: +//! +//! ```text +//! transform = T(position + h) * R(rotation) * S(scale) * T(-h) (shear of the base is kept) +//! ``` +//! +//! so `position` is the layout position of the unrotated, unscaled box (the X/Y fields), and +//! rotation and scale pivot about the centre without moving `position`. + +use super::clip::ClipKind; +use super::value::{AnimProperty, AnimValue}; +use crate::{Blur, Document, Effect, EffectKind, Node, NodeId, Shadow}; +use figcraft_color::{Color, PaintKind}; +use figcraft_geom::{Affine, Vec2}; + +/// Animated property values of one node at one time. A field is `Some` only when the node has a +/// keyframe track or a visible clip for it. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct EvaluatedNode { + pub position: Option, + pub scale: Option, + /// Degrees, counter-clockwise positive. + pub rotation: Option, + pub width: Option, + pub height: Option, + pub opacity: Option, + pub corner_radius: Option, + pub fill_color: Option, + pub stroke_color: Option, + pub stroke_weight: Option, + /// Offset (x), offset (y), blur and colour of the first drop shadow. + pub shadow_x: Option, + pub shadow_y: Option, + pub shadow_blur: Option, + pub shadow_color: Option, + /// Radius of the first layer blur. + pub blur_radius: Option, +} + +impl EvaluatedNode { + pub fn is_empty(&self) -> bool { + *self == EvaluatedNode::default() + } + + /// The evaluated value of `property`, if it is animated. + pub fn get(&self, property: AnimProperty) -> Option { + Some(match property { + AnimProperty::Position => AnimValue::Vec2(self.position?), + AnimProperty::Scale => AnimValue::Vec2(self.scale?), + AnimProperty::Rotation => AnimValue::Scalar(self.rotation?), + AnimProperty::Width => AnimValue::Scalar(self.width?), + AnimProperty::Height => AnimValue::Scalar(self.height?), + AnimProperty::Opacity => AnimValue::Scalar(self.opacity?), + AnimProperty::CornerRadius => AnimValue::Scalar(self.corner_radius?), + AnimProperty::FillColor => AnimValue::Color(self.fill_color?), + AnimProperty::StrokeColor => AnimValue::Color(self.stroke_color?), + AnimProperty::StrokeWeight => AnimValue::Scalar(self.stroke_weight?), + AnimProperty::ShadowX => AnimValue::Scalar(self.shadow_x?), + AnimProperty::ShadowY => AnimValue::Scalar(self.shadow_y?), + AnimProperty::ShadowBlur => AnimValue::Scalar(self.shadow_blur?), + AnimProperty::ShadowColor => AnimValue::Color(self.shadow_color?), + AnimProperty::BlurRadius => AnimValue::Scalar(self.blur_radius?), + }) + } + + /// Sets `property`; a value of the wrong shape is ignored. + pub fn set(&mut self, property: AnimProperty, value: AnimValue) { + match (property, value) { + (AnimProperty::Position, AnimValue::Vec2(v)) => self.position = Some(v), + (AnimProperty::Scale, AnimValue::Vec2(v)) => self.scale = Some(v), + (AnimProperty::Rotation, AnimValue::Scalar(v)) => self.rotation = Some(v), + (AnimProperty::Width, AnimValue::Scalar(v)) => self.width = Some(v), + (AnimProperty::Height, AnimValue::Scalar(v)) => self.height = Some(v), + (AnimProperty::Opacity, AnimValue::Scalar(v)) => self.opacity = Some(v), + (AnimProperty::CornerRadius, AnimValue::Scalar(v)) => self.corner_radius = Some(v), + (AnimProperty::FillColor, AnimValue::Color(v)) => self.fill_color = Some(v), + (AnimProperty::StrokeColor, AnimValue::Color(v)) => self.stroke_color = Some(v), + (AnimProperty::StrokeWeight, AnimValue::Scalar(v)) => self.stroke_weight = Some(v), + (AnimProperty::ShadowX, AnimValue::Scalar(v)) => self.shadow_x = Some(v), + (AnimProperty::ShadowY, AnimValue::Scalar(v)) => self.shadow_y = Some(v), + (AnimProperty::ShadowBlur, AnimValue::Scalar(v)) => self.shadow_blur = Some(v), + (AnimProperty::ShadowColor, AnimValue::Color(v)) => self.shadow_color = Some(v), + (AnimProperty::BlurRadius, AnimValue::Scalar(v)) => self.blur_radius = Some(v), + _ => {} + } + } + + /// Writes the animated values onto `out`, computing transform parts relative to `base`. + pub fn apply_to(&self, base: &Node, out: &mut Node) { + if let Some(o) = self.opacity { + out.opacity = if o.is_finite() { o.clamp(0.0, 1.0) as f32 } else { base.opacity }; + } + if let Some(r) = self.corner_radius.filter(|r| r.is_finite()) { + out.corners.radii = [r.max(0.0); 4]; + } + if let (Some(c), Some(i)) = (self.fill_color, first_solid(&base.fills)) + && let Some(p) = out.fills.get_mut(i) + { + p.kind = PaintKind::Solid { color: c }; + } + if let (Some(c), Some(i)) = (self.stroke_color, first_solid(&base.strokes)) + && let Some(p) = out.strokes.get_mut(i) + { + p.kind = PaintKind::Solid { color: c }; + } + if let Some(w) = self.stroke_weight.filter(|w| w.is_finite()) { + out.stroke.weight = w.max(0.0); + } + if let Some(i) = first_drop_shadow(&base.effects) + && let Some(Effect { kind: EffectKind::DropShadow(s), .. }) = out.effects.get_mut(i) + { + if let Some(v) = self.shadow_x.filter(|v| v.is_finite()) { + s.offset.0 = v; + } + if let Some(v) = self.shadow_y.filter(|v| v.is_finite()) { + s.offset.1 = v; + } + if let Some(v) = self.shadow_blur.filter(|v| v.is_finite()) { + s.radius = v.max(0.0); + } + if let Some(c) = self.shadow_color { + s.color = c; + } + } + if let (Some(r), Some(i)) = (self.blur_radius.filter(|r| r.is_finite()), first_layer_blur(&base.effects)) + && let Some(Effect { kind: EffectKind::LayerBlur(b), .. }) = out.effects.get_mut(i) + { + b.radius = r.max(0.0); + } + let transform_touched = + self.position.is_some() || self.scale.is_some() || self.rotation.is_some() || self.width.is_some() || self.height.is_some(); + if !transform_touched { + return; + } + let size = Vec2::new( + self.width.filter(|v| v.is_finite()).map_or(base.width, |v| v.max(0.0)), + self.height.filter(|v| v.is_finite()).map_or(base.height, |v| v.max(0.0)), + ); + out.width = size.x; + out.height = size.y; + let pos = self.position.filter(|p| p.x.is_finite() && p.y.is_finite()).unwrap_or_else(|| base_position(base)); + let dtheta = self.rotation.filter(|r| r.is_finite()).map_or(0.0, |r| -(r - base_rotation_deg(base)).to_radians()); + let k = self.scale.filter(|s| s.x.is_finite() && s.y.is_finite()).unwrap_or(Vec2::new(1.0, 1.0)); + let c = base.transform.as_coeffs(); + let linear = Affine::new([c[0], c[1], c[2], c[3], 0.0, 0.0]); + let l = Affine::rotate(dtheta) * linear * Affine::scale_non_uniform(k.x, k.y); + let lc = l.as_coeffs(); + let h = Vec2::new(size.x * 0.5, size.y * 0.5); + out.transform = + Affine::new([lc[0], lc[1], lc[2], lc[3], pos.x + h.x - (lc[0] * h.x + lc[2] * h.y), pos.y + h.y - (lc[1] * h.x + lc[3] * h.y)]); + } +} + +fn first_solid(paints: &[figcraft_color::Paint]) -> Option { + paints.iter().position(|p| matches!(p.kind, PaintKind::Solid { .. })) +} + +/// Index of the first drop shadow, the one the shadow properties animate. +pub fn first_drop_shadow(effects: &[Effect]) -> Option { + effects.iter().position(|e| matches!(e.kind, EffectKind::DropShadow(_))) +} + +/// Index of the first layer blur, the one [`AnimProperty::BlurRadius`] animates. +pub fn first_layer_blur(effects: &[Effect]) -> Option { + effects.iter().position(|e| matches!(e.kind, EffectKind::LayerBlur(_))) +} + +/// The node's static layout position. +pub fn base_position(node: &Node) -> Vec2 { + let c = node.transform.as_coeffs(); + let (hx, hy) = (node.width * 0.5, node.height * 0.5); + Vec2::new(c[4] - hx + (c[0] * hx + c[2] * hy), c[5] - hy + (c[1] * hx + c[3] * hy)) +} + +/// The node's static rotation in degrees, counter-clockwise positive. +pub fn base_rotation_deg(node: &Node) -> f64 { + let c = node.transform.as_coeffs(); + -c[1].atan2(c[0]).to_degrees() +} + +/// The static (un-animated) value of `property` on `node`. +pub fn base_value(node: &Node, property: AnimProperty) -> Option { + Some(match property { + AnimProperty::Position => AnimValue::Vec2(base_position(node)), + AnimProperty::Scale => AnimValue::Vec2(Vec2::new(1.0, 1.0)), + AnimProperty::Rotation => AnimValue::Scalar(base_rotation_deg(node)), + AnimProperty::Width => AnimValue::Scalar(node.width), + AnimProperty::Height => AnimValue::Scalar(node.height), + AnimProperty::Opacity => AnimValue::Scalar(node.opacity as f64), + AnimProperty::CornerRadius => AnimValue::Scalar(node.corners.radii[0]), + AnimProperty::FillColor => match node.fills.get(first_solid(&node.fills)?)?.kind { + PaintKind::Solid { color } => AnimValue::Color(color), + _ => return None, + }, + AnimProperty::StrokeColor => match node.strokes.get(first_solid(&node.strokes)?)?.kind { + PaintKind::Solid { color } => AnimValue::Color(color), + _ => return None, + }, + AnimProperty::StrokeWeight => AnimValue::Scalar(node.stroke.weight), + AnimProperty::ShadowX | AnimProperty::ShadowY | AnimProperty::ShadowBlur | AnimProperty::ShadowColor => { + let Effect { kind: EffectKind::DropShadow(Shadow { color, offset, radius, .. }), .. } = + node.effects.get(first_drop_shadow(&node.effects)?)? + else { + return None; + }; + match property { + AnimProperty::ShadowX => AnimValue::Scalar(offset.0), + AnimProperty::ShadowY => AnimValue::Scalar(offset.1), + AnimProperty::ShadowBlur => AnimValue::Scalar(*radius), + _ => AnimValue::Color(*color), + } + } + AnimProperty::BlurRadius => { + let Effect { kind: EffectKind::LayerBlur(Blur { radius, .. }), .. } = node.effects.get(first_layer_blur(&node.effects)?)? else { + return None; + }; + AnimValue::Scalar(*radius) + } + }) +} + +/// Evaluates a node's keyframes and clips at `t_ms`. +pub fn evaluate_node(node: &Node, t_ms: f64) -> EvaluatedNode { + let mut ev = EvaluatedNode::default(); + let m = &node.motion; + if m.is_empty() { + return ev; + } + let t = if t_ms.is_finite() { t_ms.max(0.0) } else { 0.0 }; + for tr in m.tracks.iter().filter(|tr| tr.visible) { + if let Some(v) = tr.value_at(t) { + ev.set(tr.property, v); + } + } + for c in m.clips.iter().filter(|c| c.visible) { + let v = c.value_at(t); + match c.kind { + ClipKind::Position => { + let cur = ev.position.unwrap_or_else(|| base_position(node)); + ev.position = Some(Vec2::new(cur.x + v.x, cur.y + v.y)); + } + ClipKind::Rotation => ev.rotation = Some(ev.rotation.unwrap_or_else(|| base_rotation_deg(node)) + v.x), + ClipKind::Scale => { + let cur = ev.scale.unwrap_or(Vec2::new(1.0, 1.0)); + ev.scale = Some(Vec2::new(cur.x * v.x, cur.y * v.y)); + } + ClipKind::Size => { + ev.width = Some(ev.width.unwrap_or(node.width) * v.x); + ev.height = Some(ev.height.unwrap_or(node.height) * v.y); + } + ClipKind::Opacity => ev.opacity = Some((ev.opacity.unwrap_or(node.opacity as f64) * v.x).clamp(0.0, 1.0)), + } + } + ev +} + +/// Value of `property` at `t_ms` including clips. +pub fn value_at(node: &Node, property: AnimProperty, t_ms: f64) -> Option { + evaluate_node(node, t_ms).get(property).or_else(|| base_value(node, property)) +} + +/// Value of `property` at `t_ms` from its keyframe track alone (clips ignored). +pub fn keyframed_value_at(node: &Node, property: AnimProperty, t_ms: f64) -> Option { + let t = if t_ms.is_finite() { t_ms.max(0.0) } else { 0.0 }; + node.motion.track(property).and_then(|tr| tr.value_at(t)).or_else(|| base_value(node, property)) +} + +/// Ids of the nodes below `page` (and the page itself) that have keyframes or clips, in paint order. +pub fn animated_nodes(doc: &Document, page: NodeId) -> Vec { + doc.subtree(page).into_iter().filter(|id| doc.node(*id).is_some_and(|n| !n.motion.is_empty())).collect() +} + +/// Evaluated nodes of one page at one time, sorted by id. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MotionFrame { + pub t_ms: f64, + pub nodes: Vec<(NodeId, EvaluatedNode)>, +} + +impl MotionFrame { + pub fn get(&self, id: NodeId) -> Option<&EvaluatedNode> { + self.nodes.binary_search_by_key(&id, |(i, _)| *i).ok().map(|i| &self.nodes[i].1) + } + + /// Writes the frame onto `out`, a copy of `base`. + pub fn apply(&self, base: &Document, out: &mut Document) { + for (id, ev) in &self.nodes { + let b = base.node(*id).cloned(); + if let (Some(b), Some(o)) = (b, out.node_mut(*id)) { + ev.apply_to(&b, o); + } + } + } +} + +/// Evaluates every animated node of `page` at `t_ms` without touching `doc`. +pub fn evaluate_frame(doc: &Document, page: NodeId, t_ms: f64) -> MotionFrame { + let mut nodes: Vec<(NodeId, EvaluatedNode)> = animated_nodes(doc, page) + .into_iter() + .filter_map(|id| doc.node(id).map(|n| (id, evaluate_node(n, t_ms)))) + .filter(|(_, e)| !e.is_empty()) + .collect(); + nodes.sort_by_key(|(id, _)| *id); + MotionFrame { t_ms, nodes } +} + +/// A copy of `doc` with the animation of `page` evaluated at `t_ms` baked into the node properties. +pub fn evaluate(doc: &Document, page: NodeId, t_ms: f64) -> Document { + let mut out = doc.clone(); + evaluate_frame(doc, page, t_ms).apply(doc, &mut out); + out +} + +#[cfg(test)] +mod tests { + use super::super::clip::{Clip, ClipKind, ClipMode, ClipRepeat}; + use super::super::track::Keyframe; + use super::super::value::AnimProperty; + use super::{AnimValue, Color, Document, Effect, NodeId, Vec2, base_position, base_value, evaluate, evaluate_node}; + use crate::NodeKind; + + fn doc_with_rect() -> (Document, NodeId, NodeId) { + let mut d = Document::new("t"); + let page = d.first_page().unwrap(); + let id = d.create(page, NodeKind::Rectangle, "Card", 100.0, 50.0, 80.0, 40.0).unwrap(); + (d, page, id) + } + + #[test] + fn keyframes_move_the_layout_position() { + let (mut d, page, id) = doc_with_rect(); + let n = d.node_mut(id).unwrap(); + let tr = n.motion.ensure_track(AnimProperty::Position); + tr.set_key(0, AnimValue::Vec2(Vec2::new(100.0, 50.0)), None); + tr.set_key(1000, AnimValue::Vec2(Vec2::new(300.0, 50.0)), None); + let n = d.node(id).unwrap(); + let ev = evaluate_node(n, 500.0); + assert_eq!(ev.position, Some(Vec2::new(200.0, 50.0))); + let out = evaluate(&d, page, 500.0); + let moved = out.node(id).unwrap(); + assert!((base_position(moved).x - 200.0).abs() < 1e-6); + assert!((moved.width - 80.0).abs() < 1e-6); + } + + #[test] + fn a_clip_fades_in() { + let (mut d, page, id) = doc_with_rect(); + let n = d.node_mut(id).unwrap(); + n.motion.clips.push(Clip::new(ClipKind::Opacity, ClipMode::In).amount(0.0).dur(1000)); + let out = evaluate(&d, page, 500.0); + let o = out.node(id).unwrap(); + assert!(o.opacity > 0.0 && o.opacity < 1.0, "{}", o.opacity); + let end = evaluate(&d, page, 2000.0); + assert!((end.node(id).unwrap().opacity - 1.0).abs() < 1e-6); + } + + #[test] + fn every_property_lands_on_its_last_keyframe() { + let (mut d, page, id) = doc_with_rect(); + let n = d.node_mut(id).unwrap(); + n.fills = vec![figcraft_color::Paint::solid(Color::new(1.0, 0.0, 0.0, 1.0))]; + n.strokes = vec![figcraft_color::Paint::solid(Color::new(0.0, 0.0, 1.0, 1.0))]; + n.stroke.weight = 2.0; + n.effects = vec![Effect::drop_shadow(), Effect::layer_blur()]; + for prop in AnimProperty::ALL { + let from = base_value(n, prop).unwrap_or_else(|| panic!("{prop:?} reads back from the layer")); + let to = match from { + AnimValue::Scalar(v) => AnimValue::Scalar(v * 0.5 + 0.1), + AnimValue::Vec2(v) => AnimValue::Vec2(Vec2::new(v.x + 10.0, v.y + 10.0)), + AnimValue::Color(_) => AnimValue::Color(Color::new(0.1, 0.6, 0.3, 1.0)), + }; + let tr = n.motion.ensure_track(prop); + tr.set_key(0, from, None); + tr.set_key(1000, to, None); + } + let out = evaluate(&d, page, 1000.0); + let (before, after) = (d.node(id).unwrap(), out.node(id).unwrap()); + // Scale reads back as 1 against the layer's own transform, so it has no base to compare. + for prop in AnimProperty::ALL.into_iter().filter(|p| *p != AnimProperty::Scale) { + assert_ne!(base_value(before, prop), base_value(after, prop), "{prop:?} moved to its key"); + } + assert_eq!(base_value(before, AnimProperty::Opacity), Some(AnimValue::Scalar(1.0)), "the base is untouched"); + } + + #[test] + fn a_hidden_track_is_ignored() { + let (mut d, page, id) = doc_with_rect(); + let n = d.node_mut(id).unwrap(); + let tr = n.motion.ensure_track(AnimProperty::Opacity); + tr.set_key(0, AnimValue::Scalar(0.0), None); + tr.set_key(1000, AnimValue::Scalar(1.0), None); + tr.visible = false; + let out = evaluate(&d, page, 500.0); + assert!((out.node(id).unwrap().opacity - 1.0).abs() < 1e-6); + } + + #[test] + fn a_clip_repeat_stays_finite() { + let c = Clip::new(ClipKind::Position, ClipMode::In).amount(50.0).dur(100).repeat(ClipRepeat::Times(3)); + for t in [0.0, 50.0, 250.0, 400.0] { + let v = c.value_at(t); + assert!(v.x.is_finite() && v.y.is_finite()); + } + let _ = Keyframe { time_ms: 0, value: AnimValue::Scalar(0.0), easing: super::super::easing::Ease::Linear }; + } +} diff --git a/crates/doc/src/anim/motion/mod.rs b/crates/doc/src/anim/motion/mod.rs new file mode 100644 index 000000000..f11926afe --- /dev/null +++ b/crates/doc/src/anim/motion/mod.rs @@ -0,0 +1,211 @@ +//! Motion: keyframe animation. +//! +//! The animation model, evaluation and edit helpers, with no UI: +//! +//! * [`TimelineSettings`]: duration, fps and loop, stored **per page**. +//! * [`NodeMotion`]: keyframe [`Track`]s, one per [`AnimProperty`], plus [`Clip`]s. +//! * [`Ease`]: hold, linear, bezier and spring easing for the segment that starts at a keyframe. +//! +//! Times are milliseconds. Keyframes sit on whole milliseconds; the playhead may be fractional. + +mod clip; +mod easing; +pub mod eval; +mod track; +mod value; + +pub use clip::{Clip, ClipDirection, ClipKind, ClipMode, ClipRepeat}; +pub use easing::{ + DEFAULT_ELASTICITY, ELASTICITY_RANGE, Ease, EaseFamily, SPRING_SETTLE_EPS, SPRING_SETTLE_K, SpringAlgorithm, cubic_bezier, + spring_angular_frequency, spring_at, spring_damping_ratio, spring_overshoot, spring_settle_secs, spring_step, spring_stiffness_damping, + spring_unit_response, unit_mass, +}; +pub use eval::{ + EvaluatedNode, MotionFrame, animated_nodes, base_position, base_rotation_deg, base_value, evaluate, evaluate_frame, evaluate_node, + first_drop_shadow, first_layer_blur, keyframed_value_at, value_at, +}; +pub use track::{Keyframe, NodeMotion, Track}; +pub use value::{AnimProperty, AnimValue, ValueKind, lerp_color, lerp_f64, lerp_vec2}; + +use serde::{Deserialize, Serialize}; + +fn default_duration() -> u32 { + 2000 +} +fn default_fps() -> u32 { + 60 +} + +/// Timeline settings of one page. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct TimelineSettings { + /// Length of the timeline in ms. Default 2000. + pub duration_ms: u32, + /// Frames per second used for stepping, snapping and export. Default 60. + pub fps: u32, + /// Whether playback loops (the Loop button). + #[serde(rename = "loop")] + pub looping: bool, +} + +/// The stored shape of [`TimelineSettings`], before the bounds are applied. +#[derive(Deserialize)] +struct RawTimeline { + #[serde(default = "default_duration")] + duration_ms: u32, + #[serde(default = "default_fps")] + fps: u32, + #[serde(default, rename = "loop")] + looping: bool, +} + +/// Reading a timeline clamps it to the bounds a `motion.timeline` command writes: a hand-edited +/// file or a collaborator's entry carrying an absurd duration would otherwise reach the ruler, +/// whose tick loop would then never end and hang the UI thread. +impl<'de> Deserialize<'de> for TimelineSettings { + fn deserialize>(d: D) -> Result { + let raw = RawTimeline::deserialize(d)?; + Ok(Self { duration_ms: raw.duration_ms, fps: raw.fps, looping: raw.looping }.sanitized()) + } +} + +impl Default for TimelineSettings { + fn default() -> Self { + Self { duration_ms: default_duration(), fps: default_fps(), looping: false } + } +} + +impl TimelineSettings { + pub const MAX_DURATION_MS: u32 = 10 * 60 * 1000; + pub const MAX_FPS: u32 = 240; + + pub fn is_default(&self) -> bool { + *self == Self::default() + } + + /// Clamps to a usable range: duration 1ms ..= 10min, fps 1 ..= 240. + pub fn sanitized(mut self) -> Self { + self.duration_ms = self.duration_ms.clamp(1, Self::MAX_DURATION_MS); + self.fps = self.fps.clamp(1, Self::MAX_FPS); + self + } + + /// Length of one frame in ms. + pub fn frame_ms(&self) -> f32 { + 1000.0 / self.fps.max(1) as f32 + } + + /// Number of frames of a render of the whole timeline (at least 1). + pub fn frame_count(&self) -> u32 { + ((self.duration_ms as f64 * self.fps.max(1) as f64 / 1000.0).ceil() as u32).max(1) + } + + /// Timeline time of frame `index`. + pub fn frame_time_ms(&self, index: u32) -> f32 { + index as f32 * self.frame_ms() + } + + /// Nearest frame boundary to `t_ms`. + pub fn snap_to_frame(&self, t_ms: f32) -> f32 { + let f = self.frame_ms(); + (t_ms / f).round() * f + } + + /// Maps a free-running playback clock to timeline time. + pub fn playback_time(&self, elapsed_ms: f32) -> f32 { + let d = self.duration_ms.max(1) as f32; + if self.looping { elapsed_ms.rem_euclid(d) } else { elapsed_ms.clamp(0.0, d) } + } + + /// Whether non-looping playback has reached the end at `elapsed_ms`. + pub fn finished(&self, elapsed_ms: f32) -> bool { + !self.looping && elapsed_ms >= self.duration_ms as f32 + } +} + +#[cfg(test)] +mod tests { + use super::{AnimProperty, AnimValue, Clip, ClipKind, ClipMode, Ease, TimelineSettings}; + + #[test] + fn defaults_are_two_seconds_at_60fps() { + let s = TimelineSettings::default(); + assert_eq!((s.duration_ms, s.fps, s.looping), (2000, 60, false)); + assert!(s.is_default()); + assert_eq!(s.frame_count(), 120); + assert!((s.frame_ms() - 16.6667).abs() < 1e-3); + } + + #[test] + fn serde_defaults_and_loop_name() { + let s: TimelineSettings = serde_json::from_str("{}").unwrap(); + assert!(s.is_default()); + let s: TimelineSettings = serde_json::from_str(r#"{"loop":true,"duration_ms":500}"#).unwrap(); + assert!(s.looping && s.duration_ms == 500 && s.fps == 60); + assert!(serde_json::to_string(&s).unwrap().contains("\"loop\":true")); + } + + #[test] + fn sanitize_and_playback_time() { + let s = TimelineSettings { duration_ms: 0, fps: 0, looping: false }.sanitized(); + assert_eq!((s.duration_ms, s.fps), (1, 1)); + let s = TimelineSettings { duration_ms: 1000, fps: 30, looping: true }; + assert!((s.playback_time(2500.0) - 500.0).abs() < 1e-3); + assert!(!s.finished(5000.0)); + } + + #[test] + fn a_stored_timeline_reads_back_within_its_bounds() { + // A hand-edited file, or a collaborator's entry, can carry any u32: the ruler's tick loop + // runs to the duration, so reading clamps the same way `motion.timeline` writes. + let s: TimelineSettings = serde_json::from_str(r#"{"duration_ms":4294967295,"fps":4294967295}"#).unwrap(); + assert_eq!((s.duration_ms, s.fps), (TimelineSettings::MAX_DURATION_MS, TimelineSettings::MAX_FPS)); + assert!(s.frame_count() <= TimelineSettings::MAX_DURATION_MS / 1000 * TimelineSettings::MAX_FPS + 1, "a finite frame count"); + } + + use crate::{Document, NodeKind}; + + fn animated() -> (Document, crate::NodeId, crate::NodeId) { + let mut d = Document::new("anim"); + let page = d.first_page().unwrap(); + let id = d.create(page, NodeKind::Rectangle, "Card", 10.0, 20.0, 100.0, 50.0).unwrap(); + let n = d.node_mut(id).unwrap(); + let pos = n.motion.ensure_track(AnimProperty::Position); + pos.set_key(0, AnimValue::Vec2(figcraft_geom::Vec2::new(10.0, 20.0)), Some(Ease::bezier(0.07, 0.97, 0.58, 1.0))); + pos.set_key(1500, AnimValue::Vec2(figcraft_geom::Vec2::new(300.0, 20.0)), None); + n.motion.clips = vec![Clip::new(ClipKind::Opacity, ClipMode::In)]; + d.timelines.insert(page, TimelineSettings { duration_ms: 4000, fps: 30, looping: true }); + (d, page, id) + } + + #[test] + fn document_roundtrip_keeps_animation_data() { + let (d, page, id) = animated(); + let json = serde_json::to_string(&d).unwrap(); + let back: Document = serde_json::from_str(&json).unwrap(); + assert_eq!(back.node(id).unwrap().motion, d.node(id).unwrap().motion); + assert_eq!(back.timelines.get(&page), d.timelines.get(&page)); + assert_eq!(serde_json::to_string(&back).unwrap(), json, "stable on a second pass"); + } + + #[test] + fn a_deleted_page_takes_its_timeline_with_it() { + let (mut d, page, _) = animated(); + let other = d.add_page("Other"); + assert!(d.timelines.contains_key(&page)); + d.remove(page).unwrap(); + assert!(!d.timelines.contains_key(&page), "the settings went with the page"); + assert!(d.pages.contains(&other)); + } + + #[test] + fn plain_documents_serialize_without_animation_fields() { + let mut d = Document::new("plain"); + let page = d.first_page().unwrap(); + d.create(page, NodeKind::Rectangle, "R", 0.0, 0.0, 5.0, 5.0).unwrap(); + let json = serde_json::to_string(&d).unwrap(); + assert!(!json.contains("\"motion\"") && !json.contains("\"timelines\""), "old files stay byte-identical in shape"); + let back: Document = serde_json::from_str(&json).unwrap(); + assert!(back.timelines.is_empty()); + } +} diff --git a/crates/doc/src/anim/motion/track.rs b/crates/doc/src/anim/motion/track.rs new file mode 100644 index 000000000..0d9ceedaa --- /dev/null +++ b/crates/doc/src/anim/motion/track.rs @@ -0,0 +1,351 @@ +//! Keyframe tracks and the per-node motion container. + +use super::clip::{Clip, ClipRepeat}; +use super::easing::Ease; +use super::value::{AnimProperty, AnimValue}; +use serde::{Deserialize, Serialize}; + +/// One keyframe: a value at a time, plus the easing of the segment that *starts* here. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Keyframe { + /// Position on the timeline in milliseconds. + pub time_ms: u32, + pub value: AnimValue, + /// Easing of the segment from this keyframe to the next. + #[serde(default, skip_serializing_if = "Ease::is_linear")] + pub easing: Ease, +} + +/// All keyframes of one property of one node, sorted by time with unique times. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Track { + pub property: AnimProperty, + pub keys: Vec, + /// The eye of the timeline's property row: a hidden track keeps its keyframes but is ignored + /// by evaluation, playback and export. + #[serde(default = "default_true", skip_serializing_if = "is_true")] + pub visible: bool, +} + +fn default_true() -> bool { + true +} + +fn is_true(v: &bool) -> bool { + *v +} + +impl Track { + pub fn new(property: AnimProperty) -> Self { + Self { property, keys: Vec::new(), visible: true } + } + + /// Sorts keys by time, dropping all but the last of keys sharing a time, and drops keys whose + /// value has the wrong shape or is not finite. + pub fn normalize(&mut self) { + let prop = self.property; + self.keys.retain(|k| prop.accepts(&k.value) && k.value.is_finite()); + self.keys.sort_by_key(|k| k.time_ms); + let mut out: Vec = Vec::with_capacity(self.keys.len()); + for k in self.keys.drain(..) { + match out.last_mut() { + Some(l) if l.time_ms == k.time_ms => *l = k, + _ => out.push(k), + } + } + self.keys = out; + } + + pub fn is_empty(&self) -> bool { + self.keys.is_empty() + } + + /// Index of the keyframe exactly at `time_ms`. + pub fn key_index(&self, time_ms: u32) -> Option { + self.keys.binary_search_by_key(&time_ms, |k| k.time_ms).ok() + } + + pub fn key_at(&self, time_ms: u32) -> Option<&Keyframe> { + self.key_index(time_ms).map(|i| &self.keys[i]) + } + + /// The keyframe closest to `time_ms` within `tolerance_ms`. + pub fn key_near(&self, time_ms: u32, tolerance_ms: u32) -> Option<&Keyframe> { + self.keys.iter().filter(|k| k.time_ms.abs_diff(time_ms) <= tolerance_ms).min_by_key(|k| k.time_ms.abs_diff(time_ms)) + } + + /// Inserts a keyframe, or replaces the one at the same time. + pub fn set_key(&mut self, time_ms: u32, value: AnimValue, easing: Option) { + match self.keys.binary_search_by_key(&time_ms, |k| k.time_ms) { + Ok(i) => { + self.keys[i].value = value; + if let Some(e) = easing { + self.keys[i].easing = e; + } + } + Err(i) => { + let inherited = if i > 0 { self.keys[i - 1].easing } else { Ease::Linear }; + self.keys.insert(i, Keyframe { time_ms, value, easing: easing.unwrap_or(inherited) }); + } + } + } + + pub fn remove_key(&mut self, time_ms: u32) -> Option { + self.key_index(time_ms).map(|i| self.keys.remove(i)) + } + + pub fn start_ms(&self) -> Option { + self.keys.first().map(|k| k.time_ms) + } + + pub fn end_ms(&self) -> Option { + self.keys.last().map(|k| k.time_ms) + } + + /// Time of the closest keyframe strictly before `time_ms`. + pub fn prev_key_time(&self, time_ms: u32) -> Option { + self.keys.iter().rev().find(|k| k.time_ms < time_ms).map(|k| k.time_ms) + } + + /// Time of the closest keyframe strictly after `time_ms`. + pub fn next_key_time(&self, time_ms: u32) -> Option { + self.keys.iter().find(|k| k.time_ms > time_ms).map(|k| k.time_ms) + } + + /// Index of the keyframe starting the segment that contains `t_ms`. + pub fn segment_start(&self, t_ms: f64) -> Option { + let n = self.keys.partition_point(|k| (k.time_ms as f64) <= t_ms); + n.checked_sub(1) + } + + /// Keyframed value at `t_ms`: the first value before the first key, the last value after the + /// last key, eased interpolation in between. `None` for an empty track. + pub fn value_at(&self, t_ms: f64) -> Option { + let first = self.keys.first()?; + let Some(i) = self.segment_start(t_ms) else { return Some(first.value) }; + let a = &self.keys[i]; + let Some(b) = self.keys.get(i + 1) else { return Some(a.value) }; + // Keys are sorted by construction, but a malformed change can still arrive unsorted or with + // two keys on one time. Saturate instead of letting the subtraction overflow, and hold the + // first key's value when the two sit on the same time instead of dividing by zero. + let span = b.time_ms.saturating_sub(a.time_ms) as f32; + if span <= 0.0 { + return Some(a.value); + } + let p = a.easing.ease((t_ms - a.time_ms as f64) as f32 / span); + Some(AnimValue::lerp(&a.value, &b.value, p as f64)) + } +} + +/// Animation data of one node: keyframe tracks plus clips. Empty for most nodes. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct NodeMotion { + /// One track per property at most, in creation order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tracks: Vec, + /// Clips, in creation order; composition is order independent. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub clips: Vec, +} + +/// Every path that reads a node's motion lands here, so the invariants hold after a file load, a +/// collaboration change and a whole-node read alike. +impl<'de> Deserialize<'de> for NodeMotion { + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + struct Repr { + #[serde(default)] + tracks: Vec, + #[serde(default)] + clips: Vec, + } + let r = Repr::deserialize(d)?; + let mut m = NodeMotion { tracks: r.tracks, clips: r.clips }; + m.normalize(); + Ok(m) + } +} + +impl NodeMotion { + pub fn is_empty(&self) -> bool { + self.tracks.is_empty() && self.clips.is_empty() + } + + pub fn track(&self, property: AnimProperty) -> Option<&Track> { + self.tracks.iter().find(|t| t.property == property) + } + + pub fn track_mut(&mut self, property: AnimProperty) -> Option<&mut Track> { + self.tracks.iter_mut().find(|t| t.property == property) + } + + /// The track for `property`, created empty when missing. + pub fn ensure_track(&mut self, property: AnimProperty) -> &mut Track { + let i = match self.tracks.iter().position(|t| t.property == property) { + Some(i) => i, + None => { + self.tracks.push(Track::new(property)); + self.tracks.len() - 1 + } + }; + &mut self.tracks[i] + } + + pub fn clip(&self, id: u32) -> Option<&Clip> { + self.clips.iter().find(|c| c.id == id) + } + + /// A clip id not used by any clip of this node. + pub fn next_clip_id(&self) -> u32 { + let mut id = self.clips.iter().map(|c| c.id).max().map_or(0, |m| m.saturating_add(1)); + while id != u32::MAX && self.clips.iter().any(|c| c.id == id) { + id += 1; + } + id + } + + /// Restores invariants after loading or bulk edits. + pub fn normalize(&mut self) { + let mut merged: Vec = Vec::new(); + for t in self.tracks.drain(..) { + match merged.iter_mut().find(|m| m.property == t.property) { + Some(m) => { + m.keys.extend(t.keys); + m.visible &= t.visible; + } + None => merged.push(t), + } + } + for t in &mut merged { + t.normalize(); + } + merged.retain(|t| !t.is_empty()); + self.tracks = merged; + let mut seen = std::collections::BTreeSet::new(); + let mut next = self.clips.iter().map(|c| c.id).max().map_or(0, |m| m.saturating_add(1)); + for c in &mut self.clips { + if !seen.insert(c.id) { + while next != u32::MAX && seen.contains(&next) { + next += 1; + } + c.id = next; + next = next.saturating_add(1); + seen.insert(c.id); + } + c.sanitize(); + } + } + + /// Sorted, deduplicated times of every keyframe across all tracks. + pub fn key_times(&self) -> Vec { + let mut v: Vec = self.tracks.iter().flat_map(|t| t.keys.iter().map(|k| k.time_ms)).collect(); + v.sort_unstable(); + v.dedup(); + v + } + + /// Closest keyframe time across all tracks strictly before `time_ms`. + pub fn prev_key_time(&self, time_ms: u32) -> Option { + self.tracks.iter().filter_map(|t| t.prev_key_time(time_ms)).max() + } + + /// Closest keyframe time across all tracks strictly after `time_ms`. + pub fn next_key_time(&self, time_ms: u32) -> Option { + self.tracks.iter().filter_map(|t| t.next_key_time(time_ms)).min() + } + + /// Time range covered by this node's animation. + pub fn span_ms(&self, timeline_duration_ms: u32) -> Option<(u32, u32)> { + let mut lo = u32::MAX; + let mut hi = 0u32; + let mut any = false; + for t in &self.tracks { + if let (Some(a), Some(b)) = (t.start_ms(), t.end_ms()) { + lo = lo.min(a); + hi = hi.max(b); + any = true; + } + } + for c in self.clips.iter().filter(|c| c.visible) { + lo = lo.min(c.delay_ms); + hi = hi.max(c.end_ms(timeline_duration_ms)); + any = true; + } + any.then_some((lo, hi)) + } + + /// Does this node animate `property` at all, via a track or a visible clip? + pub fn animates(&self, property: AnimProperty) -> bool { + self.track(property).is_some_and(|t| t.visible) || self.clips.iter().any(|c| c.visible && c.kind.properties().contains(&property)) + } + + /// Whether any clip repeats forever. + pub fn has_infinite_clip(&self) -> bool { + self.clips.iter().any(|c| c.visible && c.repeat == ClipRepeat::Infinite) + } +} + +#[cfg(test)] +mod tests { + use super::{AnimProperty, AnimValue, Ease, Keyframe, NodeMotion, Track}; + + fn s(v: f64) -> AnimValue { + AnimValue::Scalar(v) + } + + fn track(keys: &[(u32, f64)]) -> Track { + let mut t = Track::new(AnimProperty::Opacity); + for (ms, v) in keys { + t.set_key(*ms, s(*v), None); + } + t + } + + #[test] + fn keys_stay_sorted_and_unique() { + let t = track(&[(500, 0.5), (0, 0.0), (1000, 1.0), (500, 0.7)]); + let times: Vec = t.keys.iter().map(|k| k.time_ms).collect(); + assert_eq!(times, vec![0, 500, 1000]); + assert_eq!(t.key_at(500).unwrap().value, s(0.7)); + } + + #[test] + fn value_at_holds_outside_and_interpolates_inside() { + let t = track(&[(100, 0.0), (300, 1.0)]); + assert_eq!(t.value_at(0.0), Some(s(0.0))); + assert_eq!(t.value_at(200.0), Some(s(0.5))); + assert_eq!(t.value_at(900.0), Some(s(1.0))); + assert_eq!(Track::new(AnimProperty::Opacity).value_at(5.0), None); + } + + #[test] + fn new_key_inherits_easing_of_split_segment() { + let mut t = track(&[(0, 0.0), (1000, 1.0)]); + t.keys[0].easing = Ease::EaseOut; + t.set_key(400, s(0.9), None); + assert_eq!(t.key_at(400).unwrap().easing, Ease::EaseOut); + t.set_key(400, s(0.8), Some(Ease::Hold)); + assert_eq!(t.key_at(400).unwrap().easing, Ease::Hold); + } + + #[test] + fn normalize_repairs_hand_edited_data() { + let mut m = NodeMotion::default(); + m.tracks.push(Track { + property: AnimProperty::Opacity, + keys: vec![ + Keyframe { time_ms: 500, value: s(1.0), easing: Ease::Linear }, + Keyframe { time_ms: 0, value: s(0.0), easing: Ease::Linear }, + Keyframe { time_ms: 500, value: s(0.5), easing: Ease::Linear }, + Keyframe { time_ms: 700, value: AnimValue::Vec2(figcraft_geom::Vec2::ZERO), easing: Ease::Linear }, + ], + visible: true, + }); + m.tracks.push(Track::new(AnimProperty::Width)); + m.normalize(); + assert_eq!(m.tracks.len(), 1); + let times: Vec = m.tracks[0].keys.iter().map(|k| k.time_ms).collect(); + assert_eq!(times, vec![0, 500]); + assert_eq!(m.tracks[0].key_at(500).unwrap().value, s(0.5)); + } +} diff --git a/crates/doc/src/anim/motion/value.rs b/crates/doc/src/anim/motion/value.rs new file mode 100644 index 000000000..db2aaa572 --- /dev/null +++ b/crates/doc/src/anim/motion/value.rs @@ -0,0 +1,260 @@ +//! Animatable properties and their typed values. + +use figcraft_color::Color; +use figcraft_geom::Vec2; +use serde::{Deserialize, Serialize}; + +/// A node property that keyframes can animate. +/// +/// Units are model units, not display units: [`AnimProperty::display_factor`] converts opacity +/// and scale to the percentages the inspector shows. Rotation is in degrees, positive = +/// counter-clockwise, the same number the Rotation field shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum AnimProperty { + /// Layout position (x, y) of the node's unrotated, unscaled box in its parent, in px. + Position, + /// Scale factor (x, y) relative to the node's static transform, 1.0 = 100%. Applied about the + /// node's centre; negative values mirror. + Scale, + /// Rotation in degrees, counter-clockwise positive, about the node's centre. + Rotation, + Width, + Height, + /// 0.0 ..= 1.0. + Opacity, + /// Uniform corner radius in px; sets all four corners. + CornerRadius, + /// Colour of the first solid fill (a node without one cannot animate this). + FillColor, + /// Colour of the first solid stroke paint. + StrokeColor, + StrokeWeight, + /// Horizontal offset of the first drop shadow (a node without one cannot animate this). + ShadowX, + /// Vertical offset of the first drop shadow. + ShadowY, + /// Blur radius of the first drop shadow. + ShadowBlur, + /// Colour (with alpha) of the first drop shadow. + ShadowColor, + /// Radius of the first layer blur. + BlurRadius, +} + +/// The shape of an [`AnimValue`] a property takes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ValueKind { + Scalar, + Vec2, + Color, +} + +impl AnimProperty { + /// Every property in inspector order (Transform, Layout, Appearance, Fill, Stroke, Effects). + pub const ALL: [AnimProperty; 15] = [ + AnimProperty::Position, + AnimProperty::Scale, + AnimProperty::Rotation, + AnimProperty::Width, + AnimProperty::Height, + AnimProperty::Opacity, + AnimProperty::CornerRadius, + AnimProperty::FillColor, + AnimProperty::StrokeColor, + AnimProperty::StrokeWeight, + AnimProperty::ShadowX, + AnimProperty::ShadowY, + AnimProperty::ShadowBlur, + AnimProperty::ShadowColor, + AnimProperty::BlurRadius, + ]; + + /// Label of the timeline's property row. + pub fn name(&self) -> &'static str { + match self { + AnimProperty::Position => "Position", + AnimProperty::Scale => "Scale", + AnimProperty::Rotation => "Rotation", + AnimProperty::Width => "Width", + AnimProperty::Height => "Height", + AnimProperty::Opacity => "Opacity", + AnimProperty::CornerRadius => "Corner radius", + AnimProperty::FillColor => "Fill", + AnimProperty::StrokeColor => "Stroke", + AnimProperty::StrokeWeight => "Stroke weight", + AnimProperty::ShadowX => "Shadow X", + AnimProperty::ShadowY => "Shadow Y", + AnimProperty::ShadowBlur => "Shadow blur", + AnimProperty::ShadowColor => "Shadow color", + AnimProperty::BlurRadius => "Layer blur", + } + } + + pub fn kind(&self) -> ValueKind { + match self { + AnimProperty::Position | AnimProperty::Scale => ValueKind::Vec2, + AnimProperty::FillColor | AnimProperty::StrokeColor | AnimProperty::ShadowColor => ValueKind::Color, + _ => ValueKind::Scalar, + } + } + + /// Multiply the model value by this to get the number shown in the UI (100 for opacity and + /// scale which display as percentages, else 1). + pub fn display_factor(&self) -> f64 { + match self { + AnimProperty::Opacity | AnimProperty::Scale => 100.0, + _ => 1.0, + } + } + + /// Unit suffix of the displayed value ("px", "%", "°"; empty for colours). + pub fn unit(&self) -> &'static str { + match self { + AnimProperty::Opacity | AnimProperty::Scale => "%", + AnimProperty::Rotation => "°", + AnimProperty::FillColor | AnimProperty::StrokeColor | AnimProperty::ShadowColor => "", + _ => "px", + } + } + + /// Whether `v` has the right shape for this property. + pub fn accepts(&self, v: &AnimValue) -> bool { + v.kind() == self.kind() + } + + /// Neutral value used when a property has no base (e.g. before a first keyframe is read). + pub fn neutral(&self) -> AnimValue { + match self.kind() { + ValueKind::Scalar => AnimValue::Scalar(if matches!(self, AnimProperty::Opacity) { 1.0 } else { 0.0 }), + ValueKind::Vec2 => AnimValue::Vec2(if matches!(self, AnimProperty::Scale) { Vec2::new(1.0, 1.0) } else { Vec2::ZERO }), + ValueKind::Color => AnimValue::Color(Color::BLACK), + } + } +} + +/// A typed animated value. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub enum AnimValue { + Scalar(f64), + Vec2(Vec2), + Color(Color), +} + +impl AnimValue { + pub fn kind(&self) -> ValueKind { + match self { + AnimValue::Scalar(_) => ValueKind::Scalar, + AnimValue::Vec2(_) => ValueKind::Vec2, + AnimValue::Color(_) => ValueKind::Color, + } + } + + pub fn scalar(&self) -> Option { + match self { + AnimValue::Scalar(v) => Some(*v), + _ => None, + } + } + + pub fn vec2(&self) -> Option { + match self { + AnimValue::Vec2(v) => Some(*v), + _ => None, + } + } + + pub fn color(&self) -> Option { + match self { + AnimValue::Color(v) => Some(*v), + _ => None, + } + } + + pub fn is_finite(&self) -> bool { + match self { + AnimValue::Scalar(v) => v.is_finite(), + AnimValue::Vec2(v) => v.x.is_finite() && v.y.is_finite(), + AnimValue::Color(c) => c.r.is_finite() && c.g.is_finite() && c.b.is_finite() && c.a.is_finite(), + } + } + + /// Interpolates `a` to `b` at progress `t`. `t` is not clamped, so eased overshoot works; + /// colour channels are clamped to 0..=1 afterwards. Values of different kinds do not mix: `a` + /// is returned. + pub fn lerp(a: &AnimValue, b: &AnimValue, t: f64) -> AnimValue { + match (a, b) { + (AnimValue::Scalar(x), AnimValue::Scalar(y)) => AnimValue::Scalar(lerp_f64(*x, *y, t)), + (AnimValue::Vec2(x), AnimValue::Vec2(y)) => AnimValue::Vec2(lerp_vec2(*x, *y, t)), + (AnimValue::Color(x), AnimValue::Color(y)) => AnimValue::Color(lerp_color(*x, *y, t as f32)), + _ => *a, + } + } +} + +pub fn lerp_f64(a: f64, b: f64, t: f64) -> f64 { + a + (b - a) * t +} + +pub fn lerp_vec2(a: Vec2, b: Vec2, t: f64) -> Vec2 { + Vec2::new(lerp_f64(a.x, b.x, t), lerp_f64(a.y, b.y, t)) +} + +/// Colour interpolation: **premultiplied alpha in sRGB-encoded space**. +pub fn lerp_color(a: Color, b: Color, t: f32) -> Color { + let alpha = lerp_f32(a.a, b.a, t).clamp(0.0, 1.0); + let ch = |x: f32, y: f32| { + let p = lerp_f32(x * a.a, y * b.a, t); + if alpha > 1e-6 { p / alpha } else { lerp_f32(x, y, t) } + }; + Color { r: ch(a.r, b.r).clamp(0.0, 1.0), g: ch(a.g, b.g).clamp(0.0, 1.0), b: ch(a.b, b.b).clamp(0.0, 1.0), a: alpha } +} + +fn lerp_f32(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +#[cfg(test)] +mod tests { + use super::{AnimProperty, AnimValue, Color, Vec2, lerp_color}; + + #[test] + fn scalar_and_vec_lerp() { + let m = AnimValue::lerp(&AnimValue::Scalar(10.0), &AnimValue::Scalar(20.0), 0.25); + assert_eq!(m, AnimValue::Scalar(12.5)); + let v = AnimValue::lerp(&AnimValue::Vec2(Vec2::new(0.0, 10.0)), &AnimValue::Vec2(Vec2::new(10.0, 0.0)), 0.5); + assert_eq!(v, AnimValue::Vec2(Vec2::new(5.0, 5.0))); + // Overshoot is allowed for scalars. + assert_eq!(AnimValue::lerp(&AnimValue::Scalar(0.0), &AnimValue::Scalar(1.0), 1.2), AnimValue::Scalar(1.2)); + // Mismatched kinds keep the start value. + assert_eq!(AnimValue::lerp(&AnimValue::Scalar(1.0), &AnimValue::Vec2(Vec2::ZERO), 0.5), AnimValue::Scalar(1.0)); + } + + #[test] + fn color_midpoint_is_hex_average() { + let m = lerp_color(Color::BLACK, Color::WHITE, 0.5); + assert!((m.r - 0.5).abs() < 1e-5 && (m.a - 1.0).abs() < 1e-6); + assert_eq!(lerp_color(Color::BLACK, Color::WHITE, 0.0), Color::BLACK); + assert_eq!(lerp_color(Color::BLACK, Color::WHITE, 1.0), Color::WHITE); + } + + #[test] + fn color_fade_to_transparent_keeps_hue() { + let red = Color::from_rgb8_const(255, 0, 0); + let m = lerp_color(red, Color::TRANSPARENT, 0.5); + assert!((m.r - 1.0).abs() < 1e-5 && m.g.abs() < 1e-5, "{m:?}"); + assert!((m.a - 0.5).abs() < 1e-5); + let z = lerp_color(Color::TRANSPARENT, Color::TRANSPARENT, 0.5); + assert!(z.r.is_finite() && z.a == 0.0); + } + + #[test] + fn property_metadata() { + for p in AnimProperty::ALL { + assert!(p.accepts(&p.neutral()), "{p:?}"); + assert!(!p.name().is_empty()); + } + assert_eq!(AnimProperty::Opacity.display_factor(), 100.0); + assert_eq!(AnimProperty::Rotation.unit(), "°"); + assert_eq!(AnimProperty::Scale.neutral(), AnimValue::Vec2(Vec2::new(1.0, 1.0))); + } +} diff --git a/crates/doc/src/handoff_tests.rs b/crates/doc/src/handoff_tests.rs index 8a18151db..a884e0595 100644 --- a/crates/doc/src/handoff_tests.rs +++ b/crates/doc/src/handoff_tests.rs @@ -105,3 +105,18 @@ fn repair_relists_many_unlisted_pages_once_each() { assert_eq!(listed, want, "every page is listed again, once"); assert!(doc.validate().is_empty()); } + +/// Timeline settings belong to a page: repair drops the settings of a page that is gone, and keeps +/// those of the pages that are there. +#[test] +fn repair_drops_timeline_settings_of_pages_that_are_gone() { + use crate::NodeId; + use crate::anim::motion::TimelineSettings; + let mut doc = Document::new("d"); + let page = doc.first_page().unwrap(); + doc.timelines.insert(page, TimelineSettings { duration_ms: 3_000, fps: 30, looping: true }); + doc.timelines.insert(NodeId(9_999), TimelineSettings::default()); + doc.repair(); + assert!(doc.timelines.contains_key(&page), "a page that is there keeps its timeline"); + assert!(!doc.timelines.contains_key(&NodeId(9_999)), "a page that is gone loses its timeline"); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d01b94b42..fc4d7709f 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -8,6 +8,7 @@ //! live in higher crates. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod anim; pub mod board; mod board_code; mod board_mindmap; @@ -255,6 +256,10 @@ pub struct Document { /// Ended votes' results kept in the file, oldest first (at most [`VOTE_HISTORY_MAX`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub vote_history: Vec, + /// Motion timeline settings per page: duration, fps and loop. A page is the unit played and + /// exported, and pages at their defaults are left out of the file. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub timelines: BTreeMap, } impl Default for Document { @@ -299,6 +304,7 @@ impl Document { vote: None, votes: BTreeMap::new(), vote_history: Vec::new(), + timelines: BTreeMap::new(), } } @@ -571,6 +577,9 @@ impl Document { return Err(DocError::Invalid("a file needs at least one page".into())); } self.pages.retain(|p| *p != id); + // A page's timeline settings go with the page: leaving the entry behind would keep it + // in the saved and synchronized document until `repair` ran. + self.timelines.remove(&id); if self.current_page == Some(id) { self.current_page = self.pages.first().copied(); } @@ -905,7 +914,21 @@ impl Document { let nid = self.alloc_id(); map.insert(n.id, nid); } - self.paste_nodes(&src_nodes, &map, id, parent, index) + let root = self.paste_nodes(&src_nodes, &map, id, parent, index)?; + self.drop_figma_identity_in(root); + Ok(root) + } + + /// Drop the Figma identity (see [`Node::drop_figma_identity`]) from `root` and every layer under + /// it. For copies FigCraft makes of layers. + pub fn drop_figma_identity_in(&mut self, root: NodeId) { + for i in self.subtree(root) { + if self.node(i).is_some_and(Node::has_figma_identity) + && let Some(n) = self.node_mut(i) + { + n.drop_figma_identity(); + } + } } /// Deep-copy each of `ids`' subtrees to the end of `parent`, in order, returning the new root @@ -922,7 +945,12 @@ impl Document { } trees.push((id, src_nodes)); } - trees.into_iter().map(|(id, src_nodes)| self.paste_nodes(&src_nodes, &map, id, parent, None)).collect() + let roots: Vec = + trees.into_iter().map(|(id, src_nodes)| self.paste_nodes(&src_nodes, &map, id, parent, None)).collect::>()?; + for r in &roots { + self.drop_figma_identity_in(*r); + } + Ok(roots) } /// Insert copies of `nodes` (a subtree rooted at `root`, from this or another document) with ids @@ -1246,6 +1274,8 @@ impl Document { // A page listed twice would be imported, exported and walked once per listing. let mut listed = std::collections::BTreeSet::new(); self.pages.retain(|p| self.nodes.get(p).is_some_and(|n| n.is_page()) && Some(*p) != store && listed.insert(*p)); + // Timeline settings belong to a page: the settings of a page that is gone are dropped. + self.timelines.retain(|k, _| self.nodes.get(k).is_some_and(|n| n.is_page())); // Unlisted pages join the list; a set keeps many pages from making this quadratic (#1078). for (k, n) in self.nodes.iter() { if n.is_page() && Some(*k) != store && listed.insert(*k) { diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index cec38c5cb..5400cb12a 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -1,6 +1,7 @@ //! Nodes: one struct with the properties every node can have, and a kind with per-type data. use crate::NodeId; +use crate::anim::motion::NodeMotion; use crate::props::{ AutoLayout, ChildLayout, Constraints, Corners, Effect, EffectKind, ExportSetting, LayoutGrid, SPREAD_MITER_LIMIT, Shadow, StrokeAlign, StrokeCap, StrokeProps, @@ -149,6 +150,7 @@ pub enum NodeKind { fn page_bg() -> Color { Color::DEFAULT_PAGE } + fn tau() -> f64 { std::f64::consts::TAU } @@ -514,6 +516,9 @@ pub struct Node { pub exports: Vec, #[serde(default, skip_serializing_if = "is_default")] pub interactions: Vec, + /// Motion (keyframe) animation: property tracks and clips. Empty for most nodes. + #[serde(default, skip_serializing_if = "NodeMotion::is_empty")] + pub motion: NodeMotion, #[serde(default, skip_serializing_if = "is_default")] pub overflow: Overflow, #[serde(default, skip_serializing_if = "is_default")] @@ -694,7 +699,24 @@ mod guides_key { } } +/// The plugin-data keys that tie a main to the file it was pasted from (`fig.guid`, `fig.key`, +/// `fig.file`); `fig.main` (an instance's pointer at its main) is not among them. +pub const FIGMA_IDENTITY_KEYS: [&str; 3] = ["fig.guid", "fig.key", "fig.file"]; + impl Node { + /// Drop the Figma identity of a pasted main from this layer: a copy FigCraft makes is not that + /// main, and a second layer holding the identity would take later pastes. Keeps `fig.main`. + pub fn drop_figma_identity(&mut self) { + for k in FIGMA_IDENTITY_KEYS { + self.plugin_data.remove(k); + } + } + + /// Whether this layer carries a Figma identity (see [`Node::drop_figma_identity`]). + pub fn has_figma_identity(&self) -> bool { + FIGMA_IDENTITY_KEYS.iter().any(|k| self.plugin_data.contains_key(*k)) + } + /// A node with Figma's defaults for its kind. pub fn new(id: NodeId, kind: NodeKind, name: impl Into, width: f64, height: f64) -> Self { let fills = match &kind { @@ -750,6 +772,7 @@ impl Node { guides: Vec::new(), exports: Vec::new(), interactions: Vec::new(), + motion: NodeMotion::default(), overflow: Default::default(), scroll_position: Default::default(), styles: StyleRefs::default(), diff --git a/crates/doc/src/shared_tests.rs b/crates/doc/src/shared_tests.rs index b2b8d7f34..6ddd121de 100644 --- a/crates/doc/src/shared_tests.rs +++ b/crates/doc/src/shared_tests.rs @@ -8,9 +8,10 @@ use crate::*; fn node_kind_stays_compact_with_shared_text_and_vector_payloads() { use std::mem::size_of; // Before wrapping TextData (352 B) and VectorNetwork (72 B) in Shared, NodeKind was 352 B - // and Node was 1608 B. + // and Node was 1608 B. Node then sat at 1400 B; keyframe animation added `motion` (two empty + // `Vec`s, 48 B, kept inline so a layer without animation allocates nothing). assert!(size_of::() <= 144, "NodeKind grew unexpectedly: {} bytes", size_of::()); - assert!(size_of::() <= 1400, "Node grew unexpectedly: {} bytes", size_of::()); + assert!(size_of::() <= 1448, "Node grew unexpectedly: {} bytes", size_of::()); } #[test] diff --git a/crates/engine/src/assets/components.rs b/crates/engine/src/assets/components.rs index c8e569a2e..6a61c73df 100644 --- a/crates/engine/src/assets/components.rs +++ b/crates/engine/src/assets/components.rs @@ -54,8 +54,8 @@ pub use cycles::{ pub(crate) use diff::keep_inherited_overrides; pub use diff::{diff_groups, property_owners, set_boolean_default, set_value_default, variable_groups}; pub use guard::{check_override_edit, check_structure_edit, refused_override, unlink_layers}; -pub(crate) use instances::copy_group; pub use instances::{PROP_BINDING, copy_in_file, create_instance, create_instance_at, mains_to_instances, sync_instance}; +pub(crate) use instances::{copy_group, path_map}; pub use patch::sync_after_edit; #[cfg(test)] pub(crate) use patch::{FULL_REBUILD, PATCHED}; diff --git a/crates/engine/src/assets/components/instances.rs b/crates/engine/src/assets/components/instances.rs index 44aa6a6bb..1ba715d3d 100644 --- a/crates/engine/src/assets/components/instances.rs +++ b/crates/engine/src/assets/components/instances.rs @@ -41,6 +41,8 @@ pub fn create_instance_at(doc: &mut Document, component: NodeId, parent: NodeId, root.interactions.clear(); // So do the variable modes the main sets (see `Document::inherited_modes`). root.var_modes.clear(); + // The instance is not the main the file's pasted layers were matched to. + root.drop_figma_identity(); doc.insert(root, parent, index)?; sync_instance(doc, id); Ok(id) @@ -286,7 +288,7 @@ pub(crate) fn copy_group(from: &Node, to: &mut Node, g: &str) { /// Layer name paths below `root` ("Frame/Label", with `#n` for same-named siblings). With /// `src_names` (an instance's layers), layers are named after the main layer they mirror (renames /// don't break matching), and the content of slots holding the instance's own is left out. -pub(super) fn path_map(doc: &Document, root: NodeId, src_names: bool) -> BTreeMap { +pub(crate) fn path_map(doc: &Document, root: NodeId, src_names: bool) -> BTreeMap { let mut out = BTreeMap::new(); let mut stack = vec![(root, String::new())]; while let Some((id, prefix)) = stack.pop() { diff --git a/crates/engine/src/assets/components/sync.rs b/crates/engine/src/assets/components/sync.rs index b1ab2e9bf..250ca9f13 100644 --- a/crates/engine/src/assets/components/sync.rs +++ b/crates/engine/src/assets/components/sync.rs @@ -207,6 +207,8 @@ fn copy_layers( n.parent = Some(parent); n.children = orig.children.iter().filter_map(|c| map.get(c).copied()).collect(); n.source = Some(*s); + // The main's Figma identity stays on the main. + n.drop_figma_identity(); n.overrides.clear(); n.prop_refs.clear(); let prev = old.get(&nid); diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index ff87c2204..80c8b0c52 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -22,7 +22,7 @@ use figcraft_doc::{ }; use serde_json::Value; -use crate::components::inside_instance; +use crate::components::{inside_instance, path_map}; use crate::params::id_of; use crate::{EngineError, Result}; @@ -1384,6 +1384,88 @@ fn merge_components( Ok(remote) } +/// Match the mains of `src` (a design app's paste) that nothing else covers with the components of +/// `doc` that carry the same Figma identity: the same `fig.guid` from the same known file +/// (`fig.file`, present on both), or the same library `fig.key` from anywhere. A hit links the +/// main and each of its layers carrying a `fig.guid` to the layer of `doc`'s component with that +/// guid, so instances and their per-layer sources point into the component already there. +fn relink_by_identity( + doc: &Document, + src: &Document, + mains: &BTreeSet, + map: &BTreeMap, + remote: &mut BTreeMap, +) -> BTreeSet { + let mut matched = BTreeSet::new(); + let todo: Vec = mains + .iter() + .copied() + .filter(|m| !map.contains_key(m) && !remote.contains_key(m) && src.node(*m).is_some_and(|n| n.plugin_data.contains_key("fig.guid"))) + .collect(); + if todo.is_empty() { + return matched; + } + let pasted: BTreeSet = map.values().copied().collect(); + let mut by_guid: BTreeMap<(&str, &str), NodeId> = BTreeMap::new(); + let mut by_key: BTreeMap<&str, NodeId> = BTreeMap::new(); + for n in doc.nodes() { + if !matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. }) || pasted.contains(&n.id) || doc.is_remote(n.id) { + continue; + } + if let Some(g) = n.plugin_data.get("fig.guid") + && let Some(f) = n.plugin_data.get("fig.file") + { + by_guid.entry((f.as_str(), g.as_str())).or_insert(n.id); + } + if let Some(k) = n.plugin_data.get("fig.key") { + by_key.entry(k.as_str()).or_insert(n.id); + } + } + for m in todo { + let Some(theirs) = src.node(m) else { continue }; + let guid = theirs.plugin_data.get("fig.guid").map(String::as_str).unwrap_or_default(); + let found = theirs + .plugin_data + .get("fig.file") + .and_then(|f| by_guid.get(&(f.as_str(), guid))) + .or_else(|| theirs.plugin_data.get("fig.key").and_then(|k| by_key.get(k.as_str()))); + let Some(&mine) = found else { continue }; + remote.insert(m, mine); + matched.insert(m); + // A guid is unique within one file only: a main matched by its library key across files + // shares no layer guids with the component found, so its layers pair by name path. + let same_file = theirs.plugin_data.get("fig.file").is_some_and(|f| doc.node(mine).is_some_and(|n| n.plugin_data.get("fig.file") == Some(f))); + if !same_file { + for (t, d) in pair_by_path(src, m, doc, mine) { + remote.entry(t).or_insert(d); + } + continue; + } + let layers: BTreeMap<&str, NodeId> = + doc.subtree(mine).into_iter().filter_map(|i| Some((doc.node(i)?.plugin_data.get("fig.guid")?.as_str(), i))).collect(); + for l in src.subtree(m) { + if let Some(&target) = src.node(l).and_then(|n| n.plugin_data.get("fig.guid")).and_then(|g| layers.get(g.as_str())) { + remote.entry(l).or_insert(target); + } + } + } + matched +} + +/// `src`'s layers under `theirs` paired with `doc`'s under `mine` by name path (the paths the +/// instance sync matches layers by, so reordered siblings keep their own), roots included; a layer +/// whose path or kind has no counterpart is left out. +fn pair_by_path(src: &Document, theirs: NodeId, doc: &Document, mine: NodeId) -> Vec<(NodeId, NodeId)> { + let kind = |d: &Document, id: NodeId| d.node(id).map(|n| std::mem::discriminant(&n.kind)); + let mine_paths: BTreeMap = path_map(doc, mine, false).into_iter().map(|(id, p)| (p, id)).collect(); + let mut pairs = vec![(theirs, mine)]; + pairs.extend(path_map(src, theirs, false).into_iter().filter_map(|(t, p)| { + let d = *mine_paths.get(&p)?; + (kind(src, t) == kind(doc, d)).then_some((t, d)) + })); + pairs +} + /// When layers copied from another document `src` are pasted into `doc` (`map`: their ids → the /// pasted ids), point the instances among them at mains of `doc`: library copies are shared with /// (or brought along as) `doc`'s copies of the same library assets; components `src` publishes as @@ -1425,6 +1507,9 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>, } // Components `src` publishes: from its library. remote.extend(from_published(doc, src, src_path, &roots)?); + // Mains copied from a design app that this file already holds (pasted earlier): found by the + // identity recorded on them, layer by layer. + let relinked = relink_by_identity(doc, src, &mains, map, &mut remote); // Point the pasted layers at those mains; what stays behind gets ids of its own. let mut behind: BTreeMap = BTreeMap::new(); let mut follow = |doc: &mut Document, id: NodeId| -> NodeId { @@ -1460,6 +1545,13 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>, m.kind = k; } } + // An instance of a main matched by identity shows that main as this file has it: layers the + // copy there has and this one lacks would point at nothing (#2022). + for (theirs, mine) in map { + if src.node(*theirs).is_some_and(|n| matches!(n.kind, NodeKind::Instance { component, .. } if relinked.contains(&component))) { + crate::components::sync_instance(doc, *mine); + } + } Ok(()) } diff --git a/crates/engine/src/assets/library/tests.rs b/crates/engine/src/assets/library/tests.rs index 603d24e62..bdb743454 100644 --- a/crates/engine/src/assets/library/tests.rs +++ b/crates/engine/src/assets/library/tests.rs @@ -696,6 +696,50 @@ fn library_links_follow_a_moved_folder() { let _ = std::fs::remove_dir_all(&d); } +/// A component with a layer, both carrying the identity a paste from a design app records. +fn identified(d: &mut Document, name: &str, file: &str, main: &str, layer: &str, key: Option<&str>) -> (NodeId, NodeId) { + let page = d.pages[0]; + let kind = || NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }; + let c = d.create(page, kind(), name, 0.0, 0.0, 40.0, 20.0).unwrap(); + let l = d.create(c, NodeKind::Frame, "Face", 0.0, 0.0, 40.0, 20.0).unwrap(); + for (id, guid) in [(c, main), (l, layer)] { + let n = d.get_mut(id).unwrap(); + n.plugin_data.insert("fig.guid".into(), guid.into()); + n.plugin_data.insert("fig.file".into(), file.into()); + } + if let Some(k) = key { + d.get_mut(c).unwrap().plugin_data.insert("fig.key".into(), k.into()); + } + (c, l) +} + +#[test] +fn a_main_matched_by_library_key_maps_layers_by_guid_only_within_one_file() { + let relink = |their_file: &str, their_main: &str, extra: bool| { + let mut doc = Document::new("mine"); + let (mine, my_face) = identified(&mut doc, "Button", "F1", "1:20", "1:21", Some("btn")); + let mut src = Document::new("theirs"); + // Their layer carries the guid of `mine`'s main: unrelated layers in another file. + let (theirs, their_face) = identified(&mut src, "Button", their_file, their_main, "1:20", Some("btn")); + if extra { + src.create(theirs, NodeKind::Frame, "Badge", 0.0, 0.0, 4.0, 4.0).unwrap(); + } + let mut remote = BTreeMap::new(); + relink_by_identity(&doc, &src, &BTreeSet::from([theirs]), &BTreeMap::new(), &mut remote); + (remote, mine, my_face, theirs, their_face) + }; + let (remote, mine, my_face, theirs, their_face) = relink("F2", "1:19", false); + assert_eq!(remote.get(&theirs), Some(&mine), "the library key still links the main"); + assert_eq!(remote.get(&their_face), Some(&my_face), "another file: the layer in the same place, not the guid's"); + let (remote, mine, my_face, theirs, their_face) = relink("F2", "1:19", true); + assert_eq!(remote.get(&theirs), Some(&mine), "a main of another shape still links"); + assert_eq!(remote.get(&their_face), Some(&my_face), "and so does the layer both have"); + assert_eq!(remote.len(), 2, "the layer only theirs has pairs with nothing"); + let (remote, mine, _, theirs, their_face) = relink("F1", "1:19", false); + assert_eq!(remote.get(&theirs), Some(&mine)); + assert_eq!(remote.get(&their_face), Some(&mine), "the same file: the guid is the layer"); +} + /// A main component copied from a library file and pasted into another file is an instance of it /// from that library, which gets enabled, as pasting an instance of it is; a variant is an instance /// of that variant. A component the library doesn't offer pastes as a copy of itself, also one the diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index 3adf2ac50..60a5b91ac 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -72,7 +72,7 @@ impl Roots { /// The resolved path to use for `access` to `path`, or why it is refused. pub fn check(&self, path: &Path, access: Access) -> std::result::Result { - let asked = path.display(); + let asked = taken_as(path); let (roots, what) = match access { Access::Read => ([self.read.as_slice(), self.write.as_slice()].concat(), "read"), Access::Write => (self.write.clone(), "written"), @@ -86,7 +86,7 @@ impl Roots { } Some(Unresolved::Spelled(_)) => return Err(format!("automation path rejected: {asked} names a device, not a file")), // Where a link leads is only told by the usual message: it would say what is there. - Some(Unresolved::Linked) => return Err(outside(asked, &roots, what)), + Some(Unresolved::Linked) => return Err(outside(&asked, &roots, what)), None => {} } } @@ -97,7 +97,7 @@ impl Roots { Err(why) if inside_as_far_as_it_exists(path, &roots) => return Err(format!("automation path rejected: {asked}: {why}")), Err(_) => {} } - Err(outside(asked, &roots, what)) + Err(outside(&asked, &roots, what)) } /// The folders as JSON, resolved: `{read: [every folder that may be read], write: [the write roots]}`. @@ -111,10 +111,20 @@ impl Roots { } } +/// `path` as a refusal names it. A relative path also says what it was taken as: it is made absolute +/// against the working folder, which differs between a headless server and an app it attaches to. +/// That is done by name, so it tells nothing about what is on disk. +fn taken_as(path: &Path) -> String { + match std::path::absolute(path) { + Ok(abs) if path.is_relative() => format!("{} (taken as {})", path.display(), shown(&abs)), + _ => path.display().to_string(), + } +} + /// Why `asked` is refused: it is outside every one of `roots`, the folders that may be `what` /// ("read" or "written"). The message lists those folders, or says that no folder may be `what` /// when `roots` is empty. -fn outside(asked: std::path::Display<'_>, roots: &[PathBuf], what: &str) -> String { +fn outside(asked: &str, roots: &[PathBuf], what: &str) -> String { if roots.is_empty() { return format!("automation path rejected: no folder may be {what} (no root for it was given): {asked}"); } diff --git a/crates/engine/src/automation/file_access/tests.rs b/crates/engine/src/automation/file_access/tests.rs index 5b61fb246..4059c0bed 100644 --- a/crates/engine/src/automation/file_access/tests.rs +++ b/crates/engine/src/automation/file_access/tests.rs @@ -137,7 +137,14 @@ fn relative_paths_are_resolved_against_the_working_directory() { assert_eq!(here.check(Path::new("Cargo.toml"), Access::Read).unwrap(), std::fs::canonicalize("Cargo.toml").unwrap()); assert!(here.check(Path::new("src/../Cargo.toml"), Access::Read).is_ok()); let f = Fixture::new("relative"); - assert!(f.rw().check(Path::new("Cargo.toml"), Access::Read).is_err()); + // The refusal says what the relative path was taken as, since the working folder differs + // between a headless server and the app it attaches to (#2524). + let e = f.rw().check(Path::new("Cargo.toml"), Access::Read).unwrap_err(); + assert!(e.contains(&std::path::absolute("Cargo.toml").unwrap().to_string_lossy().into_owned()), "{e}"); + // So does a refusal inside a root (`..` below a missing folder; Windows folds it away by name). + if let Err(e) = here.check(Path::new("missing/../Cargo.toml"), Access::Read) { + assert!(e.contains(&std::path::absolute("missing/../Cargo.toml").unwrap().to_string_lossy().into_owned()), "{e}"); + } // Relative roots too. assert_eq!(Roots::new(&[".".into()], &[]).unwrap(), here); } diff --git a/crates/engine/src/branch_tests.rs b/crates/engine/src/branch_tests.rs index fc6159537..6ed189a1a 100644 --- a/crates/engine/src/branch_tests.rs +++ b/crates/engine/src/branch_tests.rs @@ -151,6 +151,21 @@ fn styles_variables_and_comments_merge() { assert!(doc.variables.variables.iter().any(|v| v.name == "accent")); } +#[test] +fn a_branch_review_lists_a_timeline_change_by_its_page() { + let (mut s, id, _) = branched(); + let page = s.ds().unwrap().page; + let name = s.doc().unwrap().node(page).unwrap().name.clone(); + ok(&mut s, "motion.timeline", json!({"page": page, "duration": 3000})); + let review = ok(&mut s, "branch.review", json!({"id": id})); + let what: Vec<&str> = review["branch"]["document"].as_array().unwrap().iter().map(|d| d["what"].as_str().unwrap()).collect(); + // The settings have no name of their own: the row says which page's timeline moved. + let want = format!("Timeline “{name}”"); + assert!(what.contains(&want.as_str()), "{what:?}"); + ok(&mut s, "branch.merge", json!({"id": id})); + assert_eq!(s.doc().unwrap().timelines.get(&page).unwrap().duration_ms, 3000); +} + #[test] fn branch_tabs_save_with_the_main_file_and_come_back() { let dir = std::env::temp_dir().join(format!("figcraft-branches-{}", std::process::id())); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index ca152baa3..11cbfdffa 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1,5 +1,6 @@ //! The command registry. Each area module exposes `specs()`; [`all_commands`] collects them once. +pub mod animation; pub mod arrange; pub mod comment; pub mod component; @@ -96,6 +97,7 @@ fn registry() -> &'static Registry { list.extend(library::specs()); list.extend(proto::specs()); list.extend(proto_actions::specs()); + list.extend(animation::specs()); list.extend(comment::specs()); list.extend(crate::vectoredit::specs()); list.extend(crate::shapebuilder::specs()); diff --git a/crates/engine/src/cmd/animation.rs b/crates/engine/src/cmd/animation.rs new file mode 100644 index 000000000..ff42b4778 --- /dev/null +++ b/crates/engine/src/cmd/animation.rs @@ -0,0 +1,393 @@ +//! Animation commands: keyframes, clips, a layer's motion and its timeline settings. +//! +//! The playback itself lives in `figcraft_doc::anim`; these commands are the one way the editor, the +//! control channel and MCP change a document's animation, so an edit is an undo step, a read-only +//! document refuses it, and every change is normalized the same way. +//! +//! A drag runs its command on every frame inside one interaction +//! ([`Session::begin_interaction`](crate::Session)): the interaction records the snapshot taken at +//! the press and the frames record nothing, so the whole gesture stays one step. + +use super::CommandSpec; +use crate::params::{boolean, num, opt_id, parse, req_id, req_num, req_string, req_targets, string}; +use crate::{EngineError, Result, Session, bad, spec}; +use figcraft_doc::anim::motion::{self, AnimProperty, Clip, ClipKind, ClipMode, Ease, NodeMotion}; +use serde_json::{Value, json}; + +pub(crate) fn specs() -> Vec { + vec![ + spec!( + "motion.keyframe", + "Keyframe", + "{ids?, property?, time?, value?, all?} (adds a keyframe at `time`: `property`'s value there, `value` when given, or every track the layer already animates with `all`)", + true, + keyframe_add + ), + spec!( + "motion.keyframeMove", + "Move keyframe", + "{node, property, time, to} (the keyframe at `time` goes to `to`, kept between its neighbours; returns the time it landed on)", + true, + keyframe_move + ), + spec!("motion.keyframeDelete", "Delete keyframe", "{node, property, time}", true, keyframe_delete), + spec!( + "motion.keyframeEase", + "Ease keyframe", + "{node, property, time, ease} (the easing of the segment that starts at the keyframe)", + true, + keyframe_ease + ), + spec!( + "motion.clip", + "Add animation", + "{ids?, kind, mode?, time?} (a clip of `kind` on the selected layers, starting at `time`; returns each layer's clip id)", + true, + clip_add + ), + spec!("motion.clipUpdate", "Edit animation clip", "{node, id, clip} (the whole clip, as the editor holds it)", true, clip_update), + spec!("motion.clipDelete", "Delete animation clip", "{node, id}", true, clip_delete), + spec!("motion.track", "Show/hide track", "{node, property, visible?} (without `visible`, the track flips)", true, track_visible), + spec!( + "motion.replace", + "Move animation", + "{node, motion} (a layer's whole motion: a timeline drag that slides or stretches it computes the result and sends it here)", + true, + motion_replace + ), + spec!( + "motion.timeline", + "Motion timeline", + "{page?, duration?, fps?, loop?} (a page's timeline; a page back at the defaults leaves the document)", + true, + motion_timeline + ), + ] +} + +/// The property a name picks (`Opacity`, `Position`, `Width`…), case-insensitively. +fn property_of(name: &str) -> Option { + AnimProperty::ALL.iter().copied().find(|p| p.name().eq_ignore_ascii_case(name)) +} + +fn prop_param(cmd: &str, p: &Value) -> Result { + let name = req_string(cmd, p, "property")?; + property_of(&name).ok_or_else(|| { + let names: Vec<&str> = AnimProperty::ALL.iter().map(AnimProperty::name).collect(); + bad(cmd, format!("`property` must be one of {}", names.join(", "))) + }) +} + +fn kind_of(name: &str) -> Option { + ClipKind::ALL.into_iter().find(|k| k.name().eq_ignore_ascii_case(name)) +} + +/// What a property's value looks like, for an error that says what to send instead. +fn shape(kind: motion::ValueKind) -> &'static str { + match kind { + motion::ValueKind::Scalar => "a single number", + motion::ValueKind::Vec2 => "a pair of numbers", + motion::ValueKind::Color => "a colour", + } +} + +fn mode_of(name: &str) -> Option { + match name.trim().to_ascii_lowercase().as_str() { + "in" => Some(ClipMode::In), + "out" => Some(ClipMode::Out), + "custom" => Some(ClipMode::Custom), + _ => None, + } +} + +/// The layer's motion, or an error naming the layer that isn't there. +fn motion_mut(doc: &mut figcraft_doc::Document, node: figcraft_doc::NodeId) -> Result<&mut NodeMotion> { + doc.node_mut(node).map(|n| &mut n.motion).ok_or(EngineError::NoNode(node)) +} + +fn keyframe_add(s: &mut Session, p: &Value) -> Result { + let time = num(p, "time").unwrap_or(0.0).max(0.0) as u32; + let value: Option = parse("motion.keyframe", p, "value")?; + let every_track = boolean(p, "all").unwrap_or(false); + let property = match string(p, "property") { + Some(_) => Some(prop_param("motion.keyframe", p)?), + None => None, + }; + if property.is_none() && !every_track { + return Err(bad("motion.keyframe", "`property` is required (or `all`, for every track the layer already animates)")); + } + let ids = req_targets("motion.keyframe", s, p)?; + // Every value has to fit the property it keys before anything is written. A scalar written into + // `Position` would replace a two-part key with a one-part one, and `normalize` would then drop + // that key: the command would report an addition after deleting animation data. + if let Some(v) = &value { + let doc = s.doc()?; + for id in &ids { + let props: Vec = + property.map_or_else(|| doc.node(*id).map(|n| n.motion.tracks.iter().map(|t| t.property).collect()).unwrap_or_default(), |p| vec![p]); + if let Some(prop) = props.iter().find(|prop| !prop.accepts(v)) { + return Err(bad("motion.keyframe", format!("`value` does not fit `{}`: it takes {}", prop.name(), shape(prop.kind())))); + } + } + } + let doc = s.doc_mut()?; + let mut added = 0; + for id in &ids { + let props: Vec = + property.map_or_else(|| doc.node(*id).map(|n| n.motion.tracks.iter().map(|t| t.property).collect()).unwrap_or_default(), |p| vec![p]); + let mut keys: Vec<(AnimProperty, motion::AnimValue)> = Vec::new(); + for prop in props { + let v = value.or_else(|| doc.node(*id).and_then(|n| motion::keyframed_value_at(n, prop, time as f64))); + if let Some(v) = v { + keys.push((prop, v)); + } + } + if let Some(n) = doc.node_mut(*id) { + for (prop, v) in keys { + n.motion.ensure_track(prop).set_key(time, v, None); + added += 1; + } + n.motion.normalize(); + } + } + doc.mark_dirty(ids); + Ok(json!({"added": added, "time": time})) +} + +fn keyframe_move(s: &mut Session, p: &Value) -> Result { + let node = req_id("motion.keyframeMove", p, "node")?; + let prop = prop_param("motion.keyframeMove", p)?; + let from = req_num("motion.keyframeMove", p, "time")?.max(0.0) as u32; + let to = req_num("motion.keyframeMove", p, "to")?.max(0.0) as u32; + let doc = s.doc_mut()?; + let m = motion_mut(doc, node)?; + let mut landed = from; + if let Some(tr) = m.track_mut(prop) { + // A keyframe stays between its neighbours: two keys at one time would leave a key the + // editor cannot address by time. + let lo = tr.prev_key_time(from).map_or(0, |p| p.saturating_add(1)); + let hi = tr.next_key_time(from).map_or(u32::MAX, |p| p.saturating_sub(1)); + let time = to.clamp(lo, hi); + if let Some(key) = tr.key_at(from).copied() + && let Some(idx) = tr.key_index(from) + { + tr.keys[idx] = motion::Keyframe { time_ms: time, ..key }; + landed = time; + } + } + m.normalize(); + doc.mark_dirty([node]); + Ok(json!({"time": landed})) +} + +fn keyframe_delete(s: &mut Session, p: &Value) -> Result { + let node = req_id("motion.keyframeDelete", p, "node")?; + let prop = prop_param("motion.keyframeDelete", p)?; + let time = req_num("motion.keyframeDelete", p, "time")?.max(0.0) as u32; + let doc = s.doc_mut()?; + let m = motion_mut(doc, node)?; + let mut removed = false; + if let Some(tr) = m.track_mut(prop) { + removed = tr.key_at(time).is_some(); + tr.remove_key(time); + } + m.normalize(); + doc.mark_dirty([node]); + Ok(json!({"removed": removed})) +} + +fn keyframe_ease(s: &mut Session, p: &Value) -> Result { + let node = req_id("motion.keyframeEase", p, "node")?; + let prop = prop_param("motion.keyframeEase", p)?; + let time = req_num("motion.keyframeEase", p, "time")?.max(0.0) as u32; + let ease = parse::("motion.keyframeEase", p, "ease")?.ok_or_else(|| bad("motion.keyframeEase", "`ease` is required"))?; + let ease = ease.sanitized(); + let doc = s.doc_mut()?; + let m = motion_mut(doc, node)?; + let mut eased = false; + if let Some(tr) = m.track_mut(prop) + && let Some(idx) = tr.key_index(time) + { + tr.keys[idx].easing = ease; + eased = true; + } + m.normalize(); + doc.mark_dirty([node]); + Ok(json!({"eased": eased})) +} + +fn clip_add(s: &mut Session, p: &Value) -> Result { + let name = req_string("motion.clip", p, "kind")?; + let kind = kind_of(&name).ok_or_else(|| { + let names: Vec<&str> = ClipKind::ALL.iter().map(ClipKind::name).collect(); + bad("motion.clip", format!("`kind` must be one of {}", names.join(", "))) + })?; + let mode = match string(p, "mode") { + Some(n) => mode_of(&n).ok_or_else(|| bad("motion.clip", "`mode` must be In, Out or Custom"))?, + None => ClipMode::In, + }; + let time = num(p, "time").unwrap_or(0.0).max(0.0) as u32; + let ids = req_targets("motion.clip", s, p)?; + let doc = s.doc_mut()?; + let mut clips = Vec::new(); + for id in &ids { + let Some(n) = doc.node_mut(*id) else { continue }; + let mut c = Clip::new(kind, mode); + c.id = n.motion.next_clip_id(); + c.delay_ms = time; + clips.push(json!({"node": id.0, "id": c.id})); + n.motion.clips.push(c); + n.motion.normalize(); + } + doc.mark_dirty(ids); + Ok(json!({"clips": clips})) +} + +fn clip_update(s: &mut Session, p: &Value) -> Result { + let node = req_id("motion.clipUpdate", p, "node")?; + let id = req_num("motion.clipUpdate", p, "id")?.max(0.0) as u32; + let mut clip = parse::("motion.clipUpdate", p, "clip")?.ok_or_else(|| bad("motion.clipUpdate", "`clip` is required"))?; + clip.id = id; + clip.sanitize(); + let doc = s.doc_mut()?; + let m = motion_mut(doc, node)?; + let Some(c) = m.clips.iter_mut().find(|c| c.id == id) else { + return Err(bad("motion.clipUpdate", format!("layer {} has no clip {id}", node.0))); + }; + *c = clip; + m.normalize(); + doc.mark_dirty([node]); + Ok(json!({"ok": true})) +} + +fn clip_delete(s: &mut Session, p: &Value) -> Result { + let node = req_id("motion.clipDelete", p, "node")?; + let id = req_num("motion.clipDelete", p, "id")?.max(0.0) as u32; + let doc = s.doc_mut()?; + let m = motion_mut(doc, node)?; + let before = m.clips.len(); + m.clips.retain(|c| c.id != id); + let removed = m.clips.len() != before; + m.normalize(); + doc.mark_dirty([node]); + Ok(json!({"removed": removed})) +} + +fn track_visible(s: &mut Session, p: &Value) -> Result { + let node = req_id("motion.track", p, "node")?; + let prop = prop_param("motion.track", p)?; + let wanted = boolean(p, "visible"); + let doc = s.doc_mut()?; + let m = motion_mut(doc, node)?; + let name = prop.name(); + let Some(tr) = m.track_mut(prop) else { + return Err(bad("motion.track", format!("layer {} has no {name} track", node.0))); + }; + tr.visible = wanted.unwrap_or(!tr.visible); + let visible = tr.visible; + doc.mark_dirty([node]); + Ok(json!({"visible": visible})) +} + +fn motion_replace(s: &mut Session, p: &Value) -> Result { + let node = req_id("motion.replace", p, "node")?; + let mut m = parse::("motion.replace", p, "motion")?.ok_or_else(|| bad("motion.replace", "`motion` is required"))?; + m.normalize(); + let doc = s.doc_mut()?; + *motion_mut(doc, node)? = m; + doc.mark_dirty([node]); + Ok(json!({"ok": true})) +} + +fn motion_timeline(s: &mut Session, p: &Value) -> Result { + let page = match opt_id("motion.timeline", p, "page")? { + Some(page) => page, + None => s.page()?, + }; + // Settings belong to a page: an entry under any other id would sit in the file until `repair`. + if !s.doc()?.node(page).is_some_and(|n| n.is_page()) { + return Err(bad("motion.timeline", format!("{} is not a page", page.0))); + } + let mut settings = s.doc()?.timelines.get(&page).copied().unwrap_or_default(); + if let Some(d) = num(p, "duration") { + settings.duration_ms = d.max(0.0) as u32; + } + if let Some(f) = num(p, "fps") { + settings.fps = f.max(0.0) as u32; + } + if let Some(l) = p.get("loop").and_then(Value::as_bool) { + settings.looping = l; + } + let settings = settings.sanitized(); + let doc = s.doc_mut()?; + if settings.is_default() { + doc.timelines.remove(&page); + } else { + doc.timelines.insert(page, settings); + } + doc.mark_dirty([page]); + Ok(json!({"duration": settings.duration_ms, "fps": settings.fps, "loop": settings.looping})) +} + +#[cfg(test)] +mod tests { + use crate::Session; + use serde_json::json; + + #[test] + fn setting_the_defaults_takes_the_page_out_of_the_timelines() { + let mut s = Session::new(); + let page = s.page().expect("a page"); + s.execute("motion.timeline", &json!({"duration": 5000, "fps": 30, "loop": true})).expect("set"); + assert!(s.doc().expect("doc").timelines.contains_key(&page)); + s.execute("motion.timeline", &json!({"duration": 2000, "fps": 60, "loop": false})).expect("reset"); + assert!(!s.doc().expect("doc").timelines.contains_key(&page), "a page at its defaults stays out of the file"); + } + + #[test] + fn keyframes_clips_and_tracks_edit_through_their_commands() { + let mut s = Session::new(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).expect("rect")["id"].clone(); + let node = figcraft_doc::NodeId(id.as_u64().expect("id")); + for t in [0, 500, 1000] { + s.execute("motion.keyframe", &json!({"ids": [id], "property": "Opacity", "time": t, "value": {"Scalar": 0.5}})).expect("key"); + } + let all = s.execute("motion.keyframe", &json!({"ids": [id], "all": true, "time": 250})).expect("all"); + assert_eq!(all["added"], 1, "`all` keys every track the layer has"); + // A key moves only between its neighbours. + let moved = s.execute("motion.keyframeMove", &json!({"node": id, "property": "Opacity", "time": 500, "to": 5000})).expect("move"); + let to = moved["time"].as_u64().expect("time"); + assert!(to > 500 && to < 1000, "stopped before the next key: {to}"); + let eased = s.execute("motion.keyframeEase", &json!({"node": id, "property": "Opacity", "time": 0, "ease": "EaseIn"})).expect("ease"); + assert_eq!(eased["eased"], true); + let delete = json!({"node": id, "property": "Opacity", "time": 0}); + assert_eq!(s.execute("motion.keyframeDelete", &delete).expect("delete")["removed"], true); + assert_eq!(s.execute("motion.keyframeDelete", &delete).expect("delete again")["removed"], false); + + assert!(s.execute("motion.clip", &json!({"ids": [id], "kind": "Wobble"})).is_err()); + assert!(s.execute("motion.clip", &json!({"ids": [id], "kind": "Scale", "mode": "Sideways"})).is_err()); + let added = s.execute("motion.clip", &json!({"ids": [id], "kind": "Scale", "mode": "Custom", "time": 100})).expect("clip"); + let clip_id = added["clips"][0]["id"].clone(); + let mut clip = s.doc().expect("doc").node(node).expect("node").motion.clips[0].clone(); + clip.duration_ms = 900; + s.execute("motion.clipUpdate", &json!({"node": id, "id": clip_id, "clip": clip})).expect("update"); + assert_eq!(s.doc().expect("doc").node(node).expect("node").motion.clips[0].duration_ms, 900); + assert!(s.execute("motion.clipUpdate", &json!({"node": id, "id": 99, "clip": clip})).is_err()); + + assert_eq!(s.execute("motion.track", &json!({"node": id, "property": "Opacity"})).expect("flip")["visible"], false); + assert_eq!(s.execute("motion.track", &json!({"node": id, "property": "Opacity", "visible": true})).expect("show")["visible"], true); + assert!(s.execute("motion.track", &json!({"node": id, "property": "Rotation"})).is_err(), "no such track"); + + let remove = json!({"node": id, "id": clip_id}); + assert_eq!(s.execute("motion.clipDelete", &remove).expect("remove")["removed"], true); + assert_eq!(s.execute("motion.clipDelete", &remove).expect("remove again")["removed"], false); + } + + #[test] + fn a_timeline_is_only_set_on_a_page() { + let mut s = Session::new(); + let layer = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).expect("rect")["id"].clone(); + assert!(s.execute("motion.timeline", &json!({"page": layer, "duration": 5000})).is_err()); + assert!(s.doc().expect("doc").timelines.is_empty()); + } +} diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index f67f57ec0..f65034a31 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -404,6 +404,8 @@ fn create(s: &mut Session, p: &Value) -> Result { let n = doc.get_mut(target)?; let was_group = matches!(n.kind, NodeKind::Group); n.kind = NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }; + // A new component is not the main it was made from. + n.drop_figma_identity(); if was_group { n.fills.clear(); n.clip = false; diff --git a/crates/engine/src/cmd/component/instance.rs b/crates/engine/src/cmd/component/instance.rs index f383304c5..090567134 100644 --- a/crates/engine/src/cmd/component/instance.rs +++ b/crates/engine/src/cmd/component/instance.rs @@ -31,6 +31,7 @@ pub(super) fn detach(s: &mut Session, p: &Value) -> Result { keep_main_modes(doc, i)?; let n = doc.get_mut(i)?; n.kind = NodeKind::Frame; + n.drop_figma_identity(); n.source = None; n.overrides.clear(); n.prop_refs.remove("mainComponent"); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index facb04d1b..59537faa7 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -26,7 +26,7 @@ mod nudge_rotated_parent_tests; mod vector_clipboard_tests; pub(crate) use clipboard::apply_copied_props; -pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into}; +pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, design_clipboard_file, paste_into}; use clipboard::{copy, copy_props, copy_props_of, cut, paste, paste_design_layers, paste_over, paste_props, paste_replace}; use props::{ batch_rename, effect_add, effect_copy, effect_paste, find_replace, paint_copy, paint_list, paint_paste, paint_set, pattern_fill, reparent, set, @@ -157,7 +157,7 @@ pub fn specs() -> Vec { spec!( "edit.pasteDesignLayers", "Paste design layers", - "{html (the clipboard's HTML) | data (base64 of the clipboard's design data, at most 256 MB), parent?, x?, y?} layers copied from another design app (a .fig canvas in the clipboard's HTML), read like a .fig file (best effort, with `warnings`), pasted as edit.paste pastes; `missingImages`: the names of pasted layers whose image the clipboard didn't carry (they show the missing-image placeholder)", + "{html (the clipboard's HTML) | data (base64 of the clipboard's design data, at most 256 MB), fileKey? (the Figma file the copy came from, with `data`; `html` carries it in its metadata; without one only a library key links instances to mains pasted earlier), parent?, x?, y?} layers copied from another design app (a .fig canvas in the clipboard's HTML), read like a .fig file (best effort, with `warnings`), pasted as edit.paste pastes; `missingImages`: the names of pasted layers whose image the clipboard didn't carry (they show the missing-image placeholder)", true, paste_design_layers ), @@ -758,8 +758,9 @@ impl Duplicated { } } -/// What Duplicate repeats: a move of the copies' centre in the page frame, then a turn about the -/// centre of the new copies. Size is not part of it. +/// What Duplicate repeats: the move of the copies' centre in the page frame, turned by `angle` (the +/// last copies' turn carries the move with it), then a turn about the centre of the new copies. +/// Size is not part of it. #[derive(Clone, Copy, Debug)] struct Step { dx: f64, @@ -801,6 +802,8 @@ fn duplicate_as(cmd: &str, s: &mut Session, p: &Value, as_instances: bool) -> Re let ds = s.ds()?; let roots_now = z_sorted(&ds.doc, &roots(&ds.doc, &ids)); let repeat = ds.last_duplicate.as_ref().filter(|d| !explicit && d.is_selection(&roots_now)).and_then(|d| d.step(&ds.doc)); + // The step is rigid, so its move turns with it: a move and a turn repeat round a ring (#2862). + let repeat_move = repeat.map(|st| figcraft_geom::rotate_about(Affine::IDENTITY, Point::ORIGIN, st.angle) * Point::new(st.dx, st.dy)); let doc = s.doc_mut()?; let ids = roots_now; let mut out = Vec::new(); @@ -818,8 +821,8 @@ fn duplicate_as(cmd: &str, s: &mut Session, p: &Value, as_instances: bool) -> Re _ if top_frame => (w + 100.0, 0.0), _ => (0.0, 0.0), }; - match repeat { - Some(st) => super::arrange::move_world(doc, nid, st.dx, st.dy)?, + match repeat_move { + Some(m) => super::arrange::move_world(doc, nid, m.x, m.y)?, None => { let nn = doc.get_mut(nid)?; nn.transform = Affine::translate((dx, dy)) * nn.transform; diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index 10e284a41..d16a53a0b 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -106,6 +106,29 @@ pub fn design_clipboard_buffer(html: &str) -> Option> { figcraft_format::fig::is_fig(&bytes).then_some(bytes) } +/// The markers around the copy's metadata (base64 of a JSON object) in the clipboard's HTML. +const META_OPEN: &str = "(figmeta)"; + +const META_CLOSE: &str = "(/figmeta)"; + +/// The key of the file the layers were copied from, from the metadata span of the clipboard's +/// HTML; a copy's layer ids are only unique within that file. `None` when the HTML has none. +pub fn design_clipboard_file(html: &str) -> Option { + use base64::Engine as _; + let start = html.find(META_OPEN)? + META_OPEN.len(); + let len = html.get(start..)?.find(META_CLOSE)?; + let span = html.get(start..start + len)?; + // Checked before the span is copied: the HTML may be hundreds of megabytes. + if span.len() > 64 * 1024 { + return None; + } + let b64: String = span.chars().filter(|c| !c.is_ascii_whitespace()).collect(); + let bytes = + base64::engine::general_purpose::STANDARD.decode(&b64).or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(&b64)).ok()?; + let meta: Value = serde_json::from_slice(&bytes).ok()?; + meta.get("fileKey").and_then(Value::as_str).filter(|k| !k.is_empty() && k.len() <= 128).map(str::to_string) +} + /// Paste design layers from clipboard HTML or base64 `data`: decode and reject missing, /// invalid or oversized data, load a temporary `.fig`, take its top-level page layers, /// store them as a foreign-file clipboard source with a bumped layers generation, then @@ -117,7 +140,20 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result { (None, Some(d)) => clip_base64(&d).ok_or_else(|| bad(CMD, "`data` is not base64 of at most 256 MB"))?, (None, None) => return Err(bad(CMD, "pass `html` or `data`")), }; - let other = crate::cmd::file::load_fig(&bytes, "Pasted layers").ok_or_else(|| bad(CMD, "the data is not copied design layers"))??; + let file_key = + string(p, "html").as_deref().and_then(design_clipboard_file).or_else(|| string(p, "fileKey").filter(|k| !k.is_empty() && k.len() <= 128)); + let mut other = crate::cmd::file::load_fig_pasted(&bytes, "Pasted layers").ok_or_else(|| bad(CMD, "the data is not copied design layers"))??; + if let Some(key) = &file_key { + // Layer ids are unique within one file only: mains keep the file they came from. + let ids: Vec = other.doc.ids().collect(); + for id in ids { + if let Ok(n) = other.doc.get_mut(id) + && (n.plugin_data.contains_key("fig.guid") || n.plugin_data.contains_key("fig.main")) + { + n.plugin_data.insert("fig.file".into(), key.clone()); + } + } + } let doc = std::sync::Arc::new(other.doc); let tops: Vec = doc.pages.iter().filter_map(|pg| doc.node(*pg)).flat_map(|pg| pg.children.iter().copied()).collect(); if tops.is_empty() { @@ -158,8 +194,20 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result { if !missing.is_empty() { out["missingImages"] = json!(missing); } - if !other.issues.is_empty() { - out["warnings"] = json!(other.issues); + let mut warnings: Vec = other.issues.clone(); + { + let d = s.doc()?; + let unlinked = pasted + .iter() + .flat_map(|r| d.subtree(*r)) + .filter_map(|i| d.node(i)) + .any(|n| matches!(&n.kind, NodeKind::Instance { component, .. } if !d.contains(*component))); + if unlinked { + warnings.push("instances of components not in this file stay unlinked (paste their main components first)".into()); + } + } + if !warnings.is_empty() { + out["warnings"] = json!(warnings); } Ok(out) } @@ -281,6 +329,10 @@ fn paste_layers(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>, as_vari r.transform = doc.world_transform(into).inverse() * shift * r.transform; } let pasted = doc.paste_nodes(&nodes, &map, *root, into, None)?; + // Layers from a file of this app are copies, not the mains pasted from the design app. + if clip.source_doc != 0 { + doc.drop_figma_identity_in(pasted); + } keep_a_cropped_images_proportions(doc, pasted, into); out.push(pasted); all.extend(map); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 13204976f..f93cc7cd5 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -34,8 +34,8 @@ use export::{export, export_frames_pdf, export_layers, pdf_bytes}; use load::font_report; pub use load::{MAX_DOCUMENT_FILE, load, load_bytes, load_path}; #[cfg(test)] -pub(crate) use load::{installed_family, sketch_line}; -pub(crate) use load::{load_fig, read_capped, recovered, recovered_from, variables_param, write}; +pub(crate) use load::{installed_family, load_fig, sketch_line}; +pub(crate) use load::{load_fig_pasted, read_capped, recovered, recovered_from, variables_param, write}; pub use open::MAX_RECENT; pub use open::RefreshFailure; #[cfg(test)] diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs index 88dd5f40d..9c0774204 100644 --- a/crates/engine/src/cmd/file/load.rs +++ b/crates/engine/src/cmd/file/load.rs @@ -437,10 +437,23 @@ fn installed_fonts_first() { } /// Gives `None` when `bytes` are not a `.fig` file. Then other readers can try. +#[cfg(test)] pub(crate) fn load_fig(bytes: &[u8], name: &str) -> Option> { load_fig_with_budget(bytes, name, false).map(|r| r.map(|(loaded, _)| loaded)) } +/// A `.fig` read (`None` when `bytes` are not one) for layers pasted from the clipboard, whose mains keep their Figma identity so +/// instances pasted later can link to them. +pub(crate) fn load_fig_pasted(bytes: &[u8], name: &str) -> Option> { + let r = figcraft_format::fig::try_import_pasted(bytes, name)?; + Some(r.map_err(|e| EngineError::Other(e.to_string())).map(|(mut doc, warnings)| { + link_instances(&mut doc); + installed_fonts_first(); + optical_size_follows_text_size(&mut doc); + figcraft_format::Loaded { issues: warnings, ..doc.into() } + })) +} + fn load_fig_with_budget(bytes: &[u8], name: &str, higher: bool) -> Option> { if !figcraft_format::fig::is_fig(bytes) { return None; diff --git a/crates/engine/src/cmd/page.rs b/crates/engine/src/cmd/page.rs index 814f6137c..0314375db 100644 --- a/crates/engine/src/cmd/page.rs +++ b/crates/engine/src/cmd/page.rs @@ -130,6 +130,11 @@ pub fn specs() -> Vec { let doc = s.doc_mut()?; let name = format!("Copy of {}", doc.get(src)?.name); let np = doc.add_page(&name); + // The copy plays like the page it came from: its timeline settings come along with the + // layers and their motion. + if let Some(settings) = doc.timelines.get(&src).copied() { + doc.timelines.insert(np, settings); + } // One copy with one id map, so navigation between the copied frames points at the copies; // then each layer and its copy (also those in sections), so flows can follow their start frames. let children = doc.get(src)?.children.clone(); diff --git a/crates/engine/src/design_paste_relink_tests.rs b/crates/engine/src/design_paste_relink_tests.rs new file mode 100644 index 000000000..b97373d87 --- /dev/null +++ b/crates/engine/src/design_paste_relink_tests.rs @@ -0,0 +1,515 @@ +//! Instances pasted from another design app link to the mains pasted earlier (#2022). The paste +//! carries the mains the instances use in a hidden canvas; those mains are matched with the +//! components this file already holds by the identity recorded on them at their own paste (the +//! layer guid within one file, or the library key). Payloads are synthetic, built in code. + +use base64::Engine as _; +use figcraft_format::fig::kiwi::Kv; +use serde_json::json; + +use figcraft_doc::NodeKind; + +use super::{NodeId, Session, params}; +use crate::cmd::edit::{CLIP_CLOSE, CLIP_OPEN}; + +const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; + +type Fields = Vec<(&'static str, Kv<'static>)>; + +fn o(f: Fields) -> Kv<'static> { + Kv::Object(f) +} + +fn g(local: u64) -> Kv<'static> { + o(vec![("sessionID", Kv::Uint(1)), ("localID", Kv::Uint(local))]) +} + +fn xy(x: f32, y: f32) -> Kv<'static> { + o(vec![("x", Kv::Float(x)), ("y", Kv::Float(y))]) +} + +fn node(id: u64, parent: Option<(u64, &str)>, ty: &'static str, name: &str, mut more: Fields) -> Kv<'static> { + let mut v = vec![("guid", if id == 0 { o(vec![("sessionID", Kv::Uint(0)), ("localID", Kv::Uint(0))]) } else { g(id) })]; + if let Some((p, pos)) = parent { + let pg = if p == 0 { o(vec![("sessionID", Kv::Uint(0)), ("localID", Kv::Uint(0))]) } else { g(p) }; + v.push(("parentIndex", o(vec![("guid", pg), ("position", Kv::Str(pos.into()))]))); + } + v.push(("type", Kv::Enum(ty))); + v.push(("name", Kv::Str(name.into()))); + v.append(&mut more); + o(v) +} + +fn main_nodes(parent: u64, id: u64, key: Option<&'static str>) -> Vec> { + let mut f = vec![("size", xy(40.0, 20.0))]; + if let Some(k) = key { + f.push(("key", Kv::Str(k.into()))); + } + vec![node(id, Some((parent, "!")), "SYMBOL", "Button", f), node(id + 1, Some((id, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))])] +} + +/// A paste of the main alone, as the first copy. +fn payload_main(id: u64, key: Option<&'static str>) -> Vec> { + let mut v = vec![node(0, None, "DOCUMENT", "Document", vec![]), node(1, Some((0, "!")), "CANVAS", "Page", vec![])]; + v.extend(main_nodes(1, id, key)); + v +} + +/// A paste of an instance of the main `id`, whose definition travels in the hidden canvas. +fn payload_instance(id: u64, key: Option<&'static str>, with_main: bool) -> Vec> { + let mut v = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node(30, Some((1, "!")), "INSTANCE", "Copy", vec![("size", xy(40.0, 20.0)), ("symbolData", o(vec![("symbolID", g(id))]))]), + ]; + if with_main { + v.extend(main_nodes(2, id, key)); + } + v +} + +fn html(nodes: Vec>, file: &str) -> String { + let bytes = figcraft_format::fig::pack_canvas(&schema(), &o(vec![("nodeChanges", Kv::Array(nodes))])).expect("packs"); + let meta = B64.encode(json!({"fileKey": file}).to_string()); + format!( + r#""#, + B64.encode(bytes) + ) +} + +fn paste(s: &mut Session, html: String) -> serde_json::Value { + // A paste goes into the selected frame: the main just pasted is not a place for its instances. + s.execute("select.set", &json!({"ids": []})).expect("clears"); + s.execute("edit.pasteDesignLayers", &json!({ "html": html })).expect("pastes") +} + +fn ids(r: &serde_json::Value) -> Vec { + r["ids"].as_array().unwrap().iter().filter_map(params::id_of).collect() +} + +fn components(s: &Session) -> Vec { + s.doc().unwrap().nodes().filter(|n| matches!(n.kind, NodeKind::Component { .. })).map(|n| n.id).collect() +} + +fn instance_main(s: &Session, instance: NodeId) -> NodeId { + match &s.doc().unwrap().node(instance).unwrap().kind { + NodeKind::Instance { component, .. } => *component, + k => panic!("not an instance: {k:?}"), + } +} + +#[test] +fn instances_pasted_after_their_mains_link_to_them() { + let mut s = Session::new(); + let a = paste(&mut s, html(payload_main(20, None), "F1")); + let main = ids(&a)[0]; + assert_eq!(components(&s), [main]); + let r = paste(&mut s, html(payload_instance(20, None, true), "F1")); + let copy = ids(&r)[0]; + assert_eq!(instance_main(&s, copy), main, "the instance shows the main pasted first"); + assert_eq!(components(&s), [main], "no second component came along"); + let doc = s.doc().unwrap(); + let face = doc.node(copy).unwrap().children[0]; + let source = doc.node(face).unwrap().source.expect("the layer is linked to the main's layer"); + assert!(doc.is_ancestor(main, source), "inside the main"); + assert!(r.get("warnings").is_none_or(|w| w.as_array().is_some_and(|w| w.is_empty())), "{r}"); + s.execute("select.set", &json!({"ids": [copy]})).unwrap(); + s.execute("component.goToMain", &json!({"id": copy})).expect("goToMain succeeds"); +} + +#[test] +fn one_undo_removes_the_pasted_instance_and_keeps_the_main() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + let copy = ids(&paste(&mut s, html(payload_instance(20, None, true), "F1")))[0]; + assert!(s.undo().unwrap()); + let doc = s.doc().unwrap(); + assert!(!doc.contains(copy)); + assert!(doc.contains(main)); + assert_eq!(components(&s), [main]); +} + +#[test] +fn a_main_from_another_figma_file_is_not_matched_by_guid_alone() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + let r = paste(&mut s, html(payload_instance(20, None, true), "F2")); + let copy = ids(&r)[0]; + assert_ne!(instance_main(&s, copy), main, "the same guid in another file is another component"); + assert_eq!(components(&s), [main], "no component came along with the instance"); + assert!(!s.doc().unwrap().contains(instance_main(&s, copy)), "its main stayed behind"); + assert!(r["warnings"].to_string().contains("stay unlinked"), "{r}"); +} + +#[test] +fn the_same_library_key_links_whatever_the_guids() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, Some("btn")), "F1")))[0]; + let r = paste(&mut s, html(payload_instance(77, Some("btn"), true), "F2")); + let copy = ids(&r)[0]; + assert_eq!(instance_main(&s, copy), main); + assert_eq!(components(&s), [main], "the pasted main did not come along as a second component"); + // Its layers follow the main's too, though their guids name nothing in this file. + let doc = s.doc().unwrap(); + let face = doc.node(copy).unwrap().children[0]; + let source = doc.node(face).unwrap().source.expect("linked"); + assert!(doc.contains(source) && doc.is_ancestor(main, source), "inside the main"); + s.execute("node.set", &json!({"ids": [source], "props": {"visible": false}})).unwrap(); + assert!(!s.doc().unwrap().node(face).unwrap().visible, "an edit to the main reaches the instance"); +} + +/// A paste from file `file` of an instance of library main `btn` whose layers are `layers` (name, +/// kind), in that order: the main there is another version of the one pasted first. +fn versioned(s: &mut Session, file: &str, layers: &[(&str, &'static str)]) -> NodeId { + let mut v = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node(30, Some((1, "!")), "INSTANCE", "Copy", vec![("size", xy(40.0, 20.0)), ("symbolData", o(vec![("symbolID", g(70))]))]), + node(70, Some((2, "!")), "SYMBOL", "Button", vec![("size", xy(40.0, 20.0)), ("key", Kv::Str("btn".into()))]), + ]; + for (i, (name, kind)) in layers.iter().enumerate() { + let at = ["!", "\"", "#"][i]; + v.push(node(71 + i as u64, Some((70, at)), kind, name, vec![("size", xy(10.0, 10.0))])); + } + ids(&paste(s, html(v, file)))[0] +} + +/// Each layer of instance `copy` by name, with the name of the main layer it mirrors (`None` when +/// that layer is not in the document). +fn mirrored(s: &Session, copy: NodeId, main: NodeId) -> Vec<(String, Option)> { + let doc = s.doc().unwrap(); + doc.node(copy) + .unwrap() + .children + .iter() + .map(|c| { + let n = doc.node(*c).unwrap(); + let src = n.source.and_then(|id| doc.node(id)).filter(|m| doc.is_ancestor(main, m.id)); + (n.name.clone(), src.map(|m| m.name.clone())) + }) + .collect() +} + +#[test] +fn layers_of_another_version_of_a_library_main_link_by_name() { + let two = [("Icon", "FRAME"), ("Label", "FRAME")]; + let mut first = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(20, Some((1, "!")), "SYMBOL", "Button", vec![("size", xy(40.0, 20.0)), ("key", Kv::Str("btn".into()))]), + ]; + for (i, (name, kind)) in two.iter().enumerate() { + first.push(node(21 + i as u64, Some((20, ["!", "\""][i])), kind, name, vec![("size", xy(10.0, 10.0))])); + } + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(first, "F1")))[0]; + // The same layers in the other order: each still mirrors its namesake, not the one in its place. + let swapped = versioned(&mut s, "F2", &[("Label", "FRAME"), ("Icon", "FRAME")]); + assert_eq!(instance_main(&s, swapped), main); + for (name, src) in mirrored(&s, swapped, main) { + assert_eq!(src.as_deref(), Some(name.as_str()), "{name}"); + } + // A layer the main here doesn't have: the others still link; none points outside the main. + let more = versioned(&mut s, "F3", &[("Icon", "FRAME"), ("Label", "FRAME"), ("Badge", "FRAME")]); + assert_eq!(instance_main(&s, more), main); + let layers = mirrored(&s, more, main); + assert!(layers.iter().all(|(name, src)| src.as_deref() == Some(name.as_str())), "{layers:?}"); + assert!(layers.iter().any(|(name, _)| name == "Label"), "{layers:?}"); + let doc = s.doc().unwrap(); + let label = doc.node(more).unwrap().children.iter().copied().find(|c| doc.node(*c).is_some_and(|n| n.name == "Label")).unwrap(); + let source = doc.node(label).unwrap().source.unwrap(); + s.execute("node.set", &json!({"ids": [source], "props": {"visible": false}})).unwrap(); + assert!(!s.doc().unwrap().node(label).unwrap().visible, "an edit to the main reaches the instance"); +} + +#[test] +fn an_instance_whose_main_never_arrives_stays_as_today() { + let mut s = Session::new(); + let r = paste(&mut s, html(payload_instance(20, None, true), "F1")); + let copy = ids(&r)[0]; + let main = instance_main(&s, copy); + assert!(!s.doc().unwrap().contains(main), "the main stayed behind"); + let warnings = r["warnings"].to_string(); + assert!(warnings.contains("stay unlinked"), "{warnings}"); + s.execute("component.restoreMain", &json!({"id": copy})).expect("the main can be restored"); +} + +/// A component set of two variants (`v1`, `v2`; each with one layer after it) under `parent`. +fn set_nodes(parent: u64, set: u64, v1: u64, v2: u64) -> Vec> { + let flag = vec![("isStateGroup", Kv::Bool(true)), ("size", xy(100.0, 20.0))]; + let mut v = vec![node(set, Some((parent, "!")), "FRAME", "Button", flag)]; + for (at, id, name) in [("!", v1, "State=Default"), ("\"", v2, "State=Hover")] { + v.push(node(id, Some((set, at)), "SYMBOL", name, vec![("size", xy(40.0, 20.0))])); + v.push(node(id + 1, Some((id, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))])); + } + v +} + +fn page_nodes() -> Vec> { + vec![node(0, None, "DOCUMENT", "Document", vec![]), node(1, Some((0, "!")), "CANVAS", "Page", vec![])] +} + +fn hidden_canvas() -> Kv<'static> { + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]) +} + +fn instance_of(id: u64, main: u64, parent: u64, pos: &'static str) -> Kv<'static> { + node(id, Some((parent, pos)), "INSTANCE", "Copy", vec![("size", xy(40.0, 20.0)), ("symbolData", o(vec![("symbolID", g(main))]))]) +} + +fn sets(s: &Session) -> usize { + s.doc().unwrap().nodes().filter(|n| matches!(n.kind, NodeKind::ComponentSet { .. })).count() +} + +#[test] +fn a_variant_instance_links_to_the_set_pasted_earlier() { + let mut s = Session::new(); + let mut first = page_nodes(); + first.extend(set_nodes(1, 20, 21, 23)); + paste(&mut s, html(first, "F1")); + let before = components(&s); + assert_eq!(before.len(), 2); + assert_eq!(sets(&s), 1); + let mut second = page_nodes(); + second.push(hidden_canvas()); + second.push(instance_of(30, 23, 1, "!")); + second.extend(set_nodes(2, 20, 21, 23)); + let r = paste(&mut s, html(second, "F1")); + let main = instance_main(&s, ids(&r)[0]); + assert!(before.contains(&main), "the instance's main is a variant already in the file"); + assert_eq!(s.doc().unwrap().node(main).unwrap().name, "State=Hover"); + assert_eq!(components(&s), before, "no variant came along"); + assert_eq!(sets(&s), 1, "no second set came along"); +} + +#[test] +fn a_nested_instance_inside_a_pasted_main_links_too() { + let mut s = Session::new(); + let outer = |parent: u64| { + vec![ + node(20, Some((parent, "!")), "SYMBOL", "Outer", vec![("size", xy(80.0, 40.0))]), + node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(80.0, 40.0))]), + instance_of(25, 40, 20, "\""), + ] + }; + let inner = |parent: u64, pos: &'static str| { + vec![ + node(40, Some((parent, pos)), "SYMBOL", "Inner", vec![("size", xy(40.0, 20.0))]), + node(41, Some((40, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + ] + }; + let mut first = page_nodes(); + + first.extend(outer(1)); + first.extend(inner(1, "\"")); + paste(&mut s, html(first, "F1")); + let main = s.doc().unwrap().nodes().find(|n| n.name == "Outer").unwrap().id; + let before = components(&s); + let mut second = page_nodes(); + second.push(hidden_canvas()); + second.push(instance_of(30, 20, 1, "!")); + second.extend(outer(2)); + second.extend(inner(2, "\"")); + let r = paste(&mut s, html(second, "F1")); + let copy = ids(&r)[0]; + assert_eq!(instance_main(&s, copy), main, "the copy shows the main pasted first"); + assert_eq!(components(&s), before, "no component came along"); + let doc = s.doc().unwrap(); + let nested: Vec = + doc.subtree(copy).into_iter().filter(|i| *i != copy && matches!(doc.node(*i).unwrap().kind, NodeKind::Instance { .. })).collect(); + assert_eq!(nested.len(), 1); + let in_main: Vec = doc.subtree(main).into_iter().filter(|i| matches!(doc.node(*i).unwrap().kind, NodeKind::Instance { .. })).collect(); + assert_eq!(in_main.len(), 1); + let inner = instance_main(&s, in_main[0]); + assert_eq!(instance_main(&s, nested[0]), inner, "the nested instance shows the inner main the first paste brought"); + assert!(doc.contains(inner)); +} + +#[test] +fn a_duplicated_main_does_not_take_later_pastes() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, Some("btn")), "F1")))[0]; + // An instance, detached, then made a component: a copy of the main that FigCraft made. + let inst = ids(&s.execute("edit.duplicate", &json!({"ids": [main]})).unwrap())[0]; + s.execute("component.detach", &json!({"ids": [inst]})).unwrap(); + s.execute("component.create", &json!({"ids": [inst]})).unwrap(); + assert!(matches!(s.doc().unwrap().node(inst).unwrap().kind, NodeKind::Component { .. })); + let copy_data = &s.doc().unwrap().node(inst).unwrap().plugin_data; + assert!(copy_data.keys().all(|k| !matches!(k.as_str(), "fig.guid" | "fig.key" | "fig.file")), "{copy_data:?}"); + let r = paste(&mut s, html(payload_instance(20, Some("btn"), true), "F1")); + assert_eq!(instance_main(&s, ids(&r)[0]), main, "the original takes the paste"); + // Without the original, the copy is not the pasted main. + s.execute("edit.delete", &json!({"ids": [main]})).unwrap(); + let r = paste(&mut s, html(payload_instance(20, Some("btn"), true), "F1")); + assert_ne!(instance_main(&s, ids(&r)[0]), inst, "the copy never carried the main's identity"); +} + +#[test] +fn a_duplicated_variant_does_not_carry_the_identity() { + let mut s = Session::new(); + let mut first = page_nodes(); + first.extend(set_nodes(1, 20, 21, 23)); + paste(&mut s, html(first, "F1")); + let before = components(&s); + let guids = |s: &Session| s.doc().unwrap().nodes().filter(|n| n.plugin_data.contains_key("fig.guid")).count(); + let n = guids(&s); + s.execute("edit.duplicate", &json!({"ids": [before[0]]})).unwrap(); + assert_eq!(components(&s).len(), 3, "the copy is a new variant"); + assert_eq!(guids(&s), n, "the copy carries none of the identity"); +} + +/// A `.fig` file with a main (guid 20) and an instance of it, as File > Open reads it. +fn fig_file(main_name: &str) -> String { + let mut v = page_nodes(); + v.push(node(20, Some((1, "!")), "SYMBOL", main_name, vec![("size", xy(40.0, 20.0)), ("key", Kv::Str("lib".into()))])); + v.push(node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))])); + v.push(instance_of(30, 20, 1, "\"")); + let bytes = figcraft_format::fig::pack_canvas(&schema(), &o(vec![("nodeChanges", Kv::Array(v))])).expect("packs"); + B64.encode(bytes) +} + +#[test] +fn mains_from_opened_files_carry_no_figma_identity() { + let mut s = Session::empty(); + s.execute("file.open", &json!({"data": fig_file("Button"), "name": "A.fig"})).unwrap(); + let doc = s.doc().unwrap(); + assert!(doc.nodes().any(|n| matches!(n.kind, NodeKind::Component { .. }))); + assert!(doc.nodes().all(|n| n.plugin_data.keys().all(|k| !k.starts_with("fig.")))); +} + +#[test] +fn an_instance_copied_between_two_opened_files_stays_unlinked() { + let mut s = Session::empty(); + s.execute("file.open", &json!({"data": fig_file("Button"), "name": "A.fig"})).unwrap(); + let a_main = components(&s)[0]; + s.execute("file.open", &json!({"data": fig_file("Other"), "name": "B.fig"})).unwrap(); + let instance = s.doc().unwrap().nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap().id; + s.execute("edit.copy", &json!({"ids": [instance]})).unwrap(); + s.active = 0; + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("edit.paste", &json!({})).unwrap(); + assert_ne!(instance_main(&s, ids(&r)[0]), a_main, "the same guid in an unrelated file is not the same component"); +} + +#[test] +fn a_main_from_an_opened_file_is_not_matched_to_a_pasted_one() { + let mut s = Session::empty(); + s.execute("file.open", &json!({"data": fig_file("Other"), "name": "B.fig"})).unwrap(); + let instance = s.doc().unwrap().nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap().id; + s.execute("edit.copy", &json!({"ids": [instance]})).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + // The paste above replaced the clipboard: copy again from the opened file. + s.active = 0; + s.execute("edit.copy", &json!({"ids": [instance]})).unwrap(); + s.active = 1; + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("edit.paste", &json!({})).unwrap(); + assert_ne!(instance_main(&s, ids(&r)[0]), main); +} + +/// The export schema, with the library `key` field the payloads of a library's components carry. +fn schema() -> String { + let schema = figcraft_format::fig::EXPORT_SCHEMA.replacen("message NodeChange ", "message NodeChange string key=9999, ", 1); + assert_ne!(schema, figcraft_format::fig::EXPORT_SCHEMA, "the key field was injected"); + schema +} + +fn data(nodes: Vec>) -> String { + B64.encode(figcraft_format::fig::pack_canvas(&schema(), &o(vec![("nodeChanges", Kv::Array(nodes))])).expect("packs")) +} + +fn paste_data(s: &mut Session, data: String, file: Option<&str>) -> serde_json::Value { + s.execute("select.set", &json!({"ids": []})).expect("clears"); + let mut p = json!({ "data": data }); + if let Some(f) = file { + p["fileKey"] = json!(f); + } + s.execute("edit.pasteDesignLayers", &p).expect("pastes") +} + +#[test] +fn data_with_a_file_key_links_by_guid_and_without_one_only_by_library_key() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + let r = paste_data(&mut s, data(payload_instance(20, None, true)), Some("F1")); + assert_eq!(instance_main(&s, ids(&r)[0]), main, "data + fileKey links by guid"); + // No file key: a guid alone never links, a library key does. + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, Some("btn")), "F1"))).first().copied().unwrap(); + let r = paste_data(&mut s, data(payload_instance(20, None, true)), None); + assert_ne!(instance_main(&s, ids(&r)[0]), main, "guid alone does not link"); + assert_eq!(components(&s), [main], "no component came along with the instance"); + assert!(r["warnings"].to_string().contains("stay unlinked"), "{r}"); + let r = paste_data(&mut s, data(payload_instance(77, Some("btn"), true)), None); + assert_eq!(instance_main(&s, ids(&r)[0]), main, "the library key links without a file key"); +} + +#[test] +fn the_first_main_with_a_library_key_takes_the_paste() { + let mut s = Session::new(); + let first = ids(&paste(&mut s, html(payload_main(20, Some("btn")), "F1")))[0]; + let second = ids(&paste(&mut s, html(payload_main(30, Some("btn")), "F2")))[0]; + assert_ne!(first, second); + let r = paste(&mut s, html(payload_instance(77, Some("btn"), true), "F3")); + assert_eq!(instance_main(&s, ids(&r)[0]), first, "the older component wins, every time"); + assert_eq!(components(&s).len(), 2, "no third component came along"); +} + +#[test] +fn pasting_the_main_after_its_instance_does_not_relink_it() { + let mut s = Session::new(); + let copy = ids(&paste(&mut s, html(payload_instance(20, None, true), "F1")))[0]; + let gone = instance_main(&s, copy); + paste(&mut s, html(payload_main(20, None), "F1")); + assert_eq!(instance_main(&s, copy), gone, "the earlier instance keeps pointing at its missing main"); + assert!(!s.doc().unwrap().contains(gone)); +} + +#[test] +fn a_copy_of_a_pasted_instance_keeps_its_main_pointer_and_drops_the_guid() { + let mut s = Session::new(); + let copy = ids(&paste(&mut s, html(payload_instance(20, None, true), "F1")))[0]; + let data = |s: &Session, i: NodeId| s.doc().unwrap().node(i).unwrap().plugin_data.clone(); + assert_eq!(data(&s, copy).get("fig.main").map(String::as_str), Some("1:20")); + let dup = ids(&s.execute("edit.duplicate", &json!({"ids": [copy]})).unwrap())[0]; + let d = data(&s, dup); + assert_eq!(d.get("fig.main").map(String::as_str), Some("1:20"), "{d:?}"); + assert!(!d.contains_key("fig.guid") && !d.contains_key("fig.key") && !d.contains_key("fig.file"), "{d:?}"); +} + +#[test] +fn layers_an_instance_expands_carry_no_identity() { + let mut s = Session::new(); + let mut first = page_nodes(); + first.extend([ + node(20, Some((1, "!")), "SYMBOL", "Outer", vec![("size", xy(80.0, 40.0))]), + instance_of(25, 40, 20, "!"), + node(40, Some((1, "\"")), "SYMBOL", "Inner", vec![("size", xy(40.0, 20.0))]), + node(41, Some((40, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + ]); + paste(&mut s, html(first, "F1")); + let doc = s.doc().unwrap(); + let inside: Vec<_> = + doc.nodes().filter(|n| doc.ancestors(n.id).into_iter().any(|a| matches!(doc.node(a).unwrap().kind, NodeKind::Instance { .. }))).collect(); + assert!(!inside.is_empty(), "the instance has layers of its own"); + assert!(inside.iter().all(|n| !n.plugin_data.contains_key("fig.guid")), "{:?}", inside.iter().map(|n| &n.plugin_data).collect::>()); +} + +#[test] +fn a_file_key_is_read_from_the_clipboard_metadata_only_when_it_is_sound() { + use crate::cmd::edit::design_clipboard_file; + let meta = |json: &str| format!("(figmeta){}(/figmeta)", B64.encode(json)); + assert_eq!(design_clipboard_file(&meta(r#"{"fileKey":"F1"}"#)).as_deref(), Some("F1")); + assert_eq!(design_clipboard_file(&meta(r#"{"fileKey":""}"#)), None, "empty"); + assert_eq!(design_clipboard_file(&meta(&format!(r#"{{"fileKey":"{}"}}"#, "k".repeat(129)))), None, "over 128 characters"); + assert_eq!(design_clipboard_file(&meta(&format!(r#"{{"fileKey":"{}"}}"#, "k".repeat(128)))).map(|k| k.len()), Some(128)); + assert_eq!(design_clipboard_file(&meta(r#"{"fileKey":7}"#)), None, "not a string"); + assert_eq!(design_clipboard_file("(figmeta)!!not base64!!(/figmeta)"), None, "malformed"); + assert_eq!(design_clipboard_file(&format!("(figmeta){}(/figmeta)", B64.encode("not json"))), None, "not json"); + assert_eq!(design_clipboard_file("(figmeta)e30="), None, "unclosed"); + assert_eq!(design_clipboard_file(&format!("(figmeta){}(/figmeta)", "A".repeat(64 * 1024 + 1))), None, "oversized"); + assert_eq!(design_clipboard_file(""), None, "empty html"); +} diff --git a/crates/engine/src/duplicate_spacing_tests.rs b/crates/engine/src/duplicate_spacing_tests.rs index f0b68c4bb..c68d9b15e 100644 --- a/crates/engine/src/duplicate_spacing_tests.rs +++ b/crates/engine/src/duplicate_spacing_tests.rs @@ -278,15 +278,42 @@ fn duplicate_repeats_the_copys_move_and_rotation() { ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}})); ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -15}})); assert!(near(centre(&s, c1).0, 200.0) && near(centre(&s, c1).1, 50.0)); + let (mut prev, mut step) = (centre(&s, c1), (150.0, 0.0)); for k in 1..=3 { let c = cmd_d(&mut s); let (x, y) = centre(&s, c); - let want = 200.0 + 150.0 * f64::from(k); - assert!(near(x, want) && near(y, 50.0), "repeat {k}: centre ({x}, {y})"); + // The move turns with the copies: each step is the last one turned -15. + step = turned(step, -15.0); + assert!(near(x, prev.0 + step.0) && near(y, prev.1 + step.1), "repeat {k}: centre ({x}, {y})"); assert!(near(turn(&s, c), -15.0 - 15.0 * f64::from(k)), "repeat {k}: rotation {}", turn(&s, c)); + prev = (x, y); } } +/// `v` turned by `deg` the way a layer's rotation turns it. +fn turned(v: (f64, f64), deg: f64) -> (f64, f64) { + let p = figcraft_geom::rotate_about(figcraft_geom::Affine::IDENTITY, figcraft_geom::Point::ORIGIN, deg) * figcraft_geom::Point::new(v.0, v.1); + (p.x, p.y) +} + +#[test] +fn a_moved_and_turned_copy_repeats_round_a_closed_ring() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0); + ex(&mut s, "select.set", json!({"ids": [a]})); + let c1 = cmd_d(&mut s); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 100}})); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -30}})); + // Twelve steps of -30 make a full turn: the eleventh repeat lands back on the original. + let mut last = c1; + for _ in 0..11 { + last = cmd_d(&mut s); + } + let (back, start) = (centre(&s, last), centre(&s, a)); + assert!((back.0 - start.0).hypot(back.1 - start.1) < 1e-6, "ring closes: {back:?} vs {start:?}"); + assert!(near(turn(&s, last), 0.0), "rotation {}", turn(&s, last)); +} + #[test] fn duplicate_repeats_a_rotation_in_place() { let mut s = Session::new(); @@ -336,11 +363,13 @@ fn duplicate_turns_several_layers_about_their_selection_centre() { let next: Vec = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); assert_eq!(next.len(), 2); let after = s.doc().unwrap().bounds_of(&next).unwrap().center(); - assert!(near(after.x, pair_before.x + 150.0) && near(after.y, pair_before.y), "pair centre {after:?}"); + // The +150 move, turned -15 with the pair. + let step = turned((150.0, 0.0), -15.0); + assert!(near(after.x, pair_before.x + step.0) && near(after.y, pair_before.y + step.1), "pair centre {after:?}"); for (i, c) in next.iter().enumerate() { assert!(near(turn(&s, *c), -30.0), "layer {i}: rotation {}", turn(&s, *c)); - // Expected: the layer's centre moved +150, then turned -15 about the moved pair's centre. - let moved = figcraft_geom::Affine::translate((before[i].0 + 150.0, before[i].1)); + // Expected: the layer's centre moved by the step, then turned -15 about the moved pair's centre. + let moved = figcraft_geom::Affine::translate((before[i].0 + step.0, before[i].1 + step.1)); let want = figcraft_geom::translation(figcraft_geom::rotate_about(moved, after, -15.0)); let got = centre(&s, *c); assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}"); @@ -423,10 +452,11 @@ fn several_uneven_layers_moved_and_turned_together_repeat_both() { let again = ex(&mut s, "edit.duplicate", json!({})); let next: Vec = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); assert_eq!(next.len(), 2); - let moved_pivot = figcraft_geom::Point::new(pivot.x + 150.0, pivot.y); + let step = turned((150.0, 0.0), -15.0); + let moved_pivot = figcraft_geom::Point::new(pivot.x + step.0, pivot.y + step.1); for (i, c) in next.iter().enumerate() { assert!(near(turn(&s, *c), -30.0), "layer {i}: rotation {}", turn(&s, *c)); - let moved = figcraft_geom::Affine::translate((before[i].0 + 150.0, before[i].1)); + let moved = figcraft_geom::Affine::translate((before[i].0 + step.0, before[i].1 + step.1)); let want = figcraft_geom::translation(figcraft_geom::rotate_about(moved, moved_pivot, -15.0)); let got = centre(&s, *c); assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}"); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 855c4bc67..dc3c2423f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -330,6 +330,8 @@ mod delivered_save_tests; #[cfg(test)] mod design_context_tests; #[cfg(test)] +mod design_paste_relink_tests; +#[cfg(test)] mod design_paste_tests; #[cfg(test)] mod dev_measurements_tests; diff --git a/crates/engine/src/page_target_tests.rs b/crates/engine/src/page_target_tests.rs index 6bcd47176..ba51e065d 100644 --- a/crates/engine/src/page_target_tests.rs +++ b/crates/engine/src/page_target_tests.rs @@ -86,6 +86,20 @@ fn page_commands_still_work_on_pages() { assert!(s.execute("page.delete", &json!({"id": first})).is_err(), "the last ordinary page stays"); } +#[test] +fn a_page_copies_its_timeline_and_deletes_it_with_the_page() { + let mut s = Session::new(); + let page = s.page().unwrap(); + ex(&mut s, "motion.timeline", json!({"page": page.0, "duration": 4000, "fps": 30, "loop": true})); + let copy = id_of(&ex(&mut s, "page.duplicate", json!({}))); + let timelines = &s.doc().unwrap().timelines; + assert_eq!(timelines.get(©).map(|t| (t.duration_ms, t.fps, t.looping)), Some((4000, 30, true)), "the copy plays like its source"); + assert_eq!(timelines.get(©), timelines.get(&page)); + ex(&mut s, "page.delete", json!({"id": page.0})); + assert!(!s.doc().unwrap().timelines.contains_key(&page), "the settings went with the page"); + assert!(s.doc().unwrap().timelines.contains_key(©), "the copy keeps its own"); +} + #[test] fn page_duplicate_rejects_a_frame() { let mut s = Session::new(); diff --git a/crates/engine/src/sharing/branches.rs b/crates/engine/src/sharing/branches.rs index bec539856..bd1e99110 100644 --- a/crates/engine/src/sharing/branches.rs +++ b/crates/engine/src/sharing/branches.rs @@ -592,6 +592,12 @@ fn entry_label(plan: &Plan, entry: &Entry, value: Option<&Value>) -> Option<(&'s Entry::Variable(_) => "variable", Entry::Collection(_) => "variable collection", Entry::Comment(_) => "comment", + // A timeline has no name of its own; it is the settings of a page, so it is listed by that + // page. Returning `None` dropped every timeline change from the review. + Entry::Timeline(page) => { + let name = plan.base().document().node(*page).map(|n| n.name.clone()).unwrap_or_else(|| format!("page {}", page.0)); + return Some(("timeline", figcraft_format::clip(&name, 60))); + } Entry::DevSnapshot(_) | Entry::Image(_) | Entry::Ballot(_) => return None, }; let base = plan.base().value(&Target::Entry(entry.clone())).ok().flatten(); diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index c9de8bca4..b8ce5b681 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -41,6 +41,8 @@ mod map; #[cfg(test)] mod missing_image_tests; #[cfg(test)] +mod paste_relink_tests; +#[cfg(test)] mod paste_style_tests; #[cfg(test)] mod prop_value_tests; @@ -73,14 +75,14 @@ use std::collections::BTreeMap; use figcraft_doc::{Document, FileKind}; -pub use export::export; +pub use export::{SCHEMA as EXPORT_SCHEMA, export, pack_canvas}; use crate::FormatError; #[cfg(test)] use craft_fig::rest::MAX_FIG_NODES; pub(crate) use craft_fig::rest::layer_budget; -use craft_fig::{Archive, Limits, decode_canvas, embedded_aliases, embedded_copies, kiwi}; -pub use craft_fig::{JAM_HEADER, is_fig}; +use craft_fig::{Archive, Limits, decode_canvas, embedded_aliases, embedded_copies}; +pub use craft_fig::{JAM_HEADER, is_fig, kiwi}; #[cfg(test)] use craft_fig::{MAX_CANVAS, chunks, network}; pub(crate) use craft_figma_rest::style_name; @@ -106,6 +108,14 @@ pub fn import(bytes: &[u8], name: &str) -> Result<(Document, Vec), Forma import_with_budget(bytes, name, false).map(|imported| (imported.doc, imported.warnings)).map_err(|e| e.error) } +/// [`try_import`] for layers pasted from the clipboard: each main also keeps the identity it had in +/// the design app (`fig.guid`, `fig.key`; instances keep `fig.main`) in its plugin data, so +/// instances pasted later can link to it (#2022). A file that is opened carries none. +pub fn try_import_pasted(bytes: &[u8], name: &str) -> Option), FormatError>> { + is_fig(bytes) + .then(|| import_inner(bytes, name, MAX_IMAGE_BYTES, false, true).map(|imported| (imported.doc, imported.warnings)).map_err(|e| e.error)) +} + /// Information about an import that reached a limit where a larger budget is available. #[derive(Debug)] pub struct ImportFailure { @@ -127,12 +137,12 @@ pub struct Imported { /// Try the same import with more room within the existing ceilings, on a 64-bit host. pub fn import_with_budget(bytes: &[u8], name: &str, higher: bool) -> Result { - import_inner(bytes, name, MAX_IMAGE_BYTES, higher) + import_inner(bytes, name, MAX_IMAGE_BYTES, higher, false) } #[cfg(test)] fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result<(Document, Vec), FormatError> { - import_inner(bytes, name, image_limit, false).map(|imported| (imported.doc, imported.warnings)).map_err(|e| e.error) + import_inner(bytes, name, image_limit, false, false).map(|imported| (imported.doc, imported.warnings)).map_err(|e| e.error) } /// More room for this file only, kept within the decoder and mapper's hard caps. @@ -147,7 +157,7 @@ fn budgets(packed: usize) -> ((usize, usize), (usize, usize)) { } } -fn import_inner(bytes: &[u8], name: &str, image_limit: u64, higher: bool) -> Result { +fn import_inner(bytes: &[u8], name: &str, image_limit: u64, higher: bool, identity: bool) -> Result { let mut archive = Archive::open_with(bytes, Limits { max_image: MAX_IMAGE, max_image_total: image_limit }).map_err(fig_err)?; // The budgets follow the compressed canvas, which the file itself bounds (its zip member may // inflate too). @@ -176,7 +186,11 @@ fn import_inner(bytes: &[u8], name: &str, image_limit: u64, higher: bool) -> Res canonical_image_refs(&mut json, &aliases); } let images = |r: &str| archive.image(r).or_else(|| embedded.get(r).map(|b| b.to_vec())); - let (mut doc, more) = crate::rest::import_with_networks(&json, &images, networks, max_nodes)?; + let (mut doc, more) = if identity { + crate::rest::import_with_identity(&json, &images, networks, max_nodes)? + } else { + crate::rest::import_with_networks(&json, &images, networks, max_nodes)? + }; let skipped = archive.images_skipped(); if skipped > 0 { warnings.push(format!("{skipped} ZIP image(s) skipped by the total ZIP image byte budget ({image_limit} bytes)")); diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index 357b1f51e..da75ab5b1 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -68,7 +68,7 @@ const AUX: u32 = 2; /// The schema written into every file: `enum Name A=value …`, `struct Name type field, …` (every /// field, in order) and `message Name type field=id, …`, with the names, kinds and numbers the /// format gives them. Only what the export writes. -pub(super) const SCHEMA: &str = " +pub const SCHEMA: &str = " enum MessageType JOIN_START=0 NODE_CHANGES=1 enum NodePhase CREATED=0 REMOVED=1 enum NodeType NONE=0 DOCUMENT=1 CANVAS=2 GROUP=3 FRAME=4 BOOLEAN_OPERATION=5 VECTOR=6 STAR=7 LINE=8 ELLIPSE=9 RECTANGLE=10 REGULAR_POLYGON=11 ROUNDED_RECTANGLE=12 TEXT=13 SLICE=14 SYMBOL=15 INSTANCE=16 SECTION=25 VARIABLE=28 VARIABLE_SET=31 TEXT_PATH=41 @@ -207,11 +207,7 @@ message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4 pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec, Vec), FormatError> { let mut x = Exporter::new(doc); let message = x.message(); - let fail = |e: craft_fig::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}")); - let schema = Schema::parse(SCHEMA).map_err(fail)?; - let root = schema.find("Message").ok_or_else(|| FormatError::Io(".fig export: the schema has no Message".into()))?; - let body = encode::message(&schema, root, &message).map_err(fail)?; - let canvas = craft_fig::encode_canvas(&encode::schema(&schema), &body).map_err(super::fig_err)?; + let canvas = pack_canvas(SCHEMA, &message)?; let background = doc.pages.first().and_then(|p| doc.node(*p)).and_then(|p| match &p.kind { NodeKind::Page { background, .. } => Some(*background), _ => None, @@ -220,6 +216,20 @@ pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec, Vec< Ok((bytes, x.warnings)) } +/// A `canvas.fig` holding `message` (a `Message` of the kiwi schema `schema_source`, normally +/// [`SCHEMA`], optionally extended with fields), as the design apps put it on the clipboard. +/// Returns the `canvas.fig` bytes (the schema, then the encoded message), or an error when the +/// schema does not parse, has no `Message`, or the message does not fit it. Public so tests in +/// other crates can build synthetic design-app payloads; the app itself only exports through +/// [`export`]. +pub fn pack_canvas(schema_source: &str, message: &Kv) -> Result, FormatError> { + let fail = |e: craft_fig::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}")); + let schema = Schema::parse(schema_source).map_err(fail)?; + let root = schema.find("Message").ok_or_else(|| FormatError::Io(".fig export: the schema has no Message".into()))?; + let body = encode::message(&schema, root, message).map_err(fail)?; + craft_fig::encode_canvas(&encode::schema(&schema), &body).map_err(super::fig_err) +} + /// The zip around `canvas.fig`. fn archive( name: &str, diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index e468e4cd3..78b3c66f0 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -331,7 +331,8 @@ impl<'d> Exporter<'d> { { self.warn("Developer Mode annotations, statuses, resources, measurements and code links were left out"); } - if !n.plugin_data.is_empty() { + // The identity a paste records (#2022) is FigCraft's own bookkeeping, not plugin data. + if n.plugin_data.keys().any(|k| k != "fig.main" && !figcraft_doc::FIGMA_IDENTITY_KEYS.contains(&k.as_str())) { self.warn("plugin data was left out"); } } diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index 8c2971086..682b354d4 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -75,6 +75,7 @@ pub(super) fn to_rest_for(msg: &Kv, name: &str, max_nodes: usize, board: bool) - let mut mapped = rest::to_rest(msg, name, &options); snap_table_cells(msg, &mut mapped.json, &mut mapped.warnings); connector_label_pills(&mut mapped.json, max_nodes, &mut mapped.warnings); + library_keys(msg, &mut mapped.json); // Each network passes the importer's own checks, as the JSON's `vectorNetwork` does. let networks: Vec> = mapped.networks.into_iter().map(|n| serde_json::to_value(n?).ok().and_then(|v| crate::rest::network(&v))).collect(); @@ -86,6 +87,53 @@ pub(super) fn to_rest_for(msg: &Kv, name: &str, max_nodes: usize, board: bool) - (mapped.json, mapped.warnings, networks) } +/// The library key of each main the file holds (a component, or a component set's frame), on its +/// mapped layer's source as `key`: a paste keeps it so instances pasted later find the main by it +/// (#2022). Copies an instance expands are left alone. Walks the document and the cached library +/// branches with an explicit stack, both already bounded by `max_nodes`. +fn library_keys(msg: &Kv, json: &mut Value) { + let keys: std::collections::HashMap = msg + .get("nodeChanges") + .map(Kv::list) + .unwrap_or_default() + .iter() + .filter_map(|n| { + let main = match n.get("type").and_then(Kv::str)? { + "SYMBOL" => true, + "FRAME" => n.get("isStateGroup").and_then(Kv::bool) == Some(true), + _ => false, + }; + let key = n.get("key").and_then(Kv::str).filter(|k| main && !k.is_empty() && k.len() <= 256)?; + Some((origin(n.get("guid")?)?, key)) + }) + .collect(); + if keys.is_empty() { + return; + } + let Value::Object(fields) = json else { return }; + let mut pending: Vec<&mut Value> = Vec::new(); + for (name, value) in fields.iter_mut() { + if name == "document" { + pending.push(value); + } else if name == craft_fig::rest::FIG_LIBRARY_CONTEXTS_FIELD + && let Some(branches) = value.as_array_mut() + { + pending.extend(branches.iter_mut()); + } + } + while let Some(layer) = pending.pop() { + if let Some(source) = layer.get_mut(craft_fig::rest::FIG_SOURCE_FIELD) + && source.get("expanded").and_then(Value::as_bool) == Some(false) + && let Some(key) = source.get("origin").and_then(Value::as_str).and_then(|o| keys.get(o)) + { + source["key"] = Value::from(*key); + } + if let Some(children) = layer.get_mut("children").and_then(Value::as_array_mut) { + pending.extend(children.iter_mut()); + } + } +} + /// Every layer of the mapped REST tree (already bounded by `max_nodes`), parents before their /// children, walked with an explicit stack so a deep file can't exhaust the call stack. fn each_tree_layer(json: &mut Value, f: &mut impl FnMut(&mut Value)) { diff --git a/crates/format/src/fig/paste_relink_tests.rs b/crates/format/src/fig/paste_relink_tests.rs new file mode 100644 index 000000000..bf83e6986 --- /dev/null +++ b/crates/format/src/fig/paste_relink_tests.rs @@ -0,0 +1,85 @@ +//! Layers pasted from another design app keep the identity they had there (#2022): a main's guid +//! (and its library key) lands in its plugin data, on the main and on every layer in it, so +//! instances pasted later can link to it. Built in code from synthetic payloads. + +use figcraft_doc::{Document, Node, NodeKind}; + +use super::kiwi::Kv; +use super::tests::{arr, canvas, g, node, o, s, schema, xy}; +use super::try_import_pasted; + +fn import(nodes: Vec>) -> Document { + let bytes = canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])); + try_import_pasted(&bytes, "Pasted layers").expect("design data").expect("it imports").0 +} + +fn named<'a>(doc: &'a Document, name: &str) -> &'a Node { + doc.nodes().find(|n| n.name == name).expect(name) +} + +#[test] +fn a_pasted_main_records_its_figma_identity() { + let doc = import(vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(20, Some((1, "!")), "SYMBOL", "Button", vec![("size", xy(40.0, 20.0)), ("key", s("btn"))]), + node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + node(30, Some((1, "\"")), "RECTANGLE", "Loose", vec![("size", xy(5.0, 5.0))]), + ]); + let main = named(&doc, "Button"); + assert!(matches!(main.kind, NodeKind::Component { .. })); + assert_eq!(main.plugin_data.get("fig.guid").map(String::as_str), Some("1:20")); + assert_eq!(main.plugin_data.get("fig.key").map(String::as_str), Some("btn")); + let face = named(&doc, "Face"); + assert_eq!(face.plugin_data.get("fig.guid").map(String::as_str), Some("1:21"), "every layer of a main"); + assert!(!face.plugin_data.contains_key("fig.key")); + assert!(named(&doc, "Loose").plugin_data.is_empty(), "layers outside mains record nothing"); +} + +#[test] +fn a_cached_main_in_the_internal_canvas_is_an_instance_main_in_the_store() { + let doc = import(vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node(30, Some((1, "!")), "INSTANCE", "Copy", vec![("size", xy(40.0, 20.0)), ("symbolData", o(vec![("symbolID", g(20))]))]), + node(20, Some((2, "!")), "SYMBOL", "Button", vec![("size", xy(40.0, 20.0))]), + node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + ]); + let copy = doc.nodes().find(|n| n.name == "Copy").expect("the instance"); + let NodeKind::Instance { component, .. } = ©.kind else { panic!("the top is not an instance: {:?}", copy.kind) }; + assert!(doc.is_remote(*component), "its main is in the library store"); + let main = doc.node(*component).expect("main"); + assert_eq!(main.plugin_data.get("fig.guid").map(String::as_str), Some("1:20")); + assert_eq!(copy.plugin_data.get("fig.main").map(String::as_str), Some("1:20")); +} + +fn exported_warnings(data: &[(&str, &str)]) -> Vec { + let mut doc = Document::new("x"); + let page = doc.first_page().expect("a page"); + let id = doc.alloc_id(); + let mut n = Node::new(id, NodeKind::Frame, "A", 10.0, 10.0); + for (k, v) in data { + n.plugin_data.insert((*k).into(), (*v).into()); + } + doc.insert(n, page, None).expect("inserts"); + super::export(&doc, None).expect("exports").1 +} + +#[test] +fn identity_keys_alone_do_not_warn_on_export_but_other_plugin_data_does() { + let has = |w: &[String]| w.iter().any(|m| m.contains("plugin data")); + assert!(!has(&exported_warnings(&[("fig.guid", "1:2"), ("fig.key", "k"), ("fig.file", "F"), ("fig.main", "1:3")]))); + assert!(has(&exported_warnings(&[("fig.guid", "1:2"), ("other", "x")]))); + assert!(has(&exported_warnings(&[("other", "x")]))); + let w = exported_warnings(&[("fig.notes", "x")]); + assert!(has(&w), "only the identity keys, not every key under that prefix: {w:?}"); +} + +#[test] +fn pack_canvas_refuses_a_schema_that_does_not_parse_or_has_no_message() { + let msg = o(vec![("nodeChanges", arr(vec![]))]); + assert!(super::pack_canvas("not a schema", &msg).is_err()); + assert!(super::pack_canvas("enum A X=0", &msg).is_err(), "no Message"); + assert!(super::pack_canvas(super::EXPORT_SCHEMA, &msg).is_ok()); +} diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index f6c7a6950..2b134be23 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -170,7 +170,7 @@ pub fn import(v: &Value, images: ImageResolver) -> Result<(Document, Vec /// in the file JSON (a `meta` with `variableCollections`, or `variableCollections` and /// `variables` at the top level) are read too; the first definition of an id wins. pub fn import_with(v: &Value, variables: Option<&Value>, images: ImageResolver) -> Result<(Document, Vec), FormatError> { - import_parts(v, variables, images, Vec::new(), MAX_NODES, false) + import_parts(v, variables, images, Vec::new(), MAX_NODES, false, false) } /// Internal .fig JSON path: GUID provenance is not part of the public REST import contract. @@ -189,7 +189,19 @@ pub(crate) fn import_with_networks( networks: Vec>, max_nodes: usize, ) -> Result<(Document, Vec), FormatError> { - import_parts(v, None, images, networks, max_nodes, true) + import_parts(v, None, images, networks, max_nodes, true, false) +} + +/// [`import_with_networks`] that also records each main's Figma identity in its plugin data +/// (`fig.guid`, `fig.key`, `fig.main`; see `Ctx::record_identity`). Only a clipboard paste asks +/// for it: a file that is opened carries no identity. +pub(crate) fn import_with_identity( + v: &Value, + images: ImageResolver, + networks: Vec>, + max_nodes: usize, +) -> Result<(Document, Vec), FormatError> { + import_parts(v, None, images, networks, max_nodes, true, true) } /// [`import_with_networks`] for imports other than `.fig` (no `.fig` source identities): the @@ -200,7 +212,7 @@ pub(crate) fn import_with_networks_plain( networks: Vec>, max_nodes: usize, ) -> Result<(Document, Vec), FormatError> { - import_parts(v, None, images, networks, max_nodes, false) + import_parts(v, None, images, networks, max_nodes, false, false) } fn import_parts( @@ -210,6 +222,7 @@ fn import_parts( networks: Vec>, max_nodes: usize, fig_sources: bool, + identity: bool, ) -> Result<(Document, Vec), FormatError> { let entries: Vec<&Value> = if is_document(v) { vec![v] } else { nodes_entries(v).collect() }; if entries.is_empty() { @@ -218,6 +231,7 @@ fn import_parts( let name = text(v, "name").filter(|n| !n.trim().is_empty()).map_or("Imported file", clip_str); let mut cx = Ctx::new(Document::new(name), images); cx.fig_sources = fig_sources.then(|| fig_sources::Sources::new(max_nodes)); + cx.keep_identity = identity; let blank = cx.doc.first_page(); let mut loose: Option = None; for e in &entries { @@ -427,6 +441,8 @@ pub(crate) struct Ctx<'a> { max_nodes: usize, /// Mains the `.fig` file has but its layer cap kept out ([`FIG_CAPPED_MAINS_FIELD`]). capped_mains: BTreeSet, + /// Whether mains keep their Figma identity in plugin data (a clipboard paste). + keep_identity: bool, /// The REST ids of the layers pattern paints tile, by the number each paint holds until /// [`Self::link_patterns`]. pattern_sources: Vec, @@ -461,6 +477,7 @@ impl<'a> Ctx<'a> { networks: Vec::new(), max_nodes: MAX_NODES, capped_mains: BTreeSet::new(), + keep_identity: false, pattern_sources: Vec::new(), } } @@ -570,6 +587,9 @@ impl<'a> Ctx<'a> { if let Some(sources) = &mut self.fig_sources { sources.record(id, j, primary); } + if primary && self.keep_identity { + self.record_identity(id, rid, ty, j); + } } match ty { "INSTANCE" => self.instances.push((id, j)), @@ -1195,6 +1215,40 @@ impl<'a> Ctx<'a> { } } + /// Keep the file's own identity of a main (and of every layer in it) in the layer's plugin data, + /// so instances pasted later can find mains pasted earlier: `fig.guid` (unique within one + /// file), `fig.key` (a library component's key, unique everywhere). Instances keep their + /// main's guid as `fig.main`. Only layers the file really holds (not the copies an instance + /// expands) are recorded. + fn record_identity(&mut self, id: NodeId, rest_id: &str, ty: &str, j: &Value) { + let meta = j.get(FIG_SOURCE_FIELD); + if meta.and_then(|m| m.get("expanded")).and_then(Value::as_bool) != Some(false) || rest_id.starts_with('I') || rest_id.len() > 41 { + return; + } + let is_main = matches!(ty, "COMPONENT" | "COMPONENT_SET"); + let in_main = is_main + || self + .doc + .ancestors(id) + .into_iter() + .any(|a| self.doc.node(a).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. }))); + let main = (ty == "INSTANCE").then(|| text(j, "componentId")).flatten().filter(|m| m.len() <= 41); + if !in_main && main.is_none() { + return; + } + let key = meta.and_then(|m| m.get("key")).and_then(Value::as_str).filter(|k| is_main && !k.is_empty()); + let Some(n) = self.doc.node_mut(id) else { return }; + if in_main { + n.plugin_data.insert("fig.guid".into(), rest_id.into()); + } + if let Some(k) = key { + n.plugin_data.insert("fig.key".into(), k.into()); + } + if let Some(m) = main { + n.plugin_data.insert("fig.main".into(), m.into()); + } + } + /// Point each pattern paint at the layer it tiles ([`props::pattern`]); one whose layer /// wasn't imported is dropped. fn link_patterns(&mut self) { diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index da0258399..a7f765050 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -52,5 +52,8 @@ egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-update = { workspace = true } +# The in-app agent: HTTP providers and a worker thread, so desktop only (the browser build shows +# the panel's setup card through the stub in `panels/layers.rs`). +figcraft-agent = { workspace = true } # Colour emoji (COLR, sbix, CBDT) in the UI from the system's emoji face; the web build has none. craft-ui = { workspace = true, features = ["color_fonts"] } diff --git a/crates/ui-egui/locales/ar.toml b/crates/ui-egui/locales/ar.toml index 82fef1539..9ed54e5b1 100644 --- a/crates/ui-egui/locales/ar.toml +++ b/crates/ui-egui/locales/ar.toml @@ -2198,6 +2198,16 @@ status = "draft — needs native review" "library.usage" = "استخدام المكتبة" "measure.distances" = "قياس المسافات" "measure.padding" = "قياس حشو التخطيط التلقائي" +"motion.clip" = "إضافة تحريك" +"motion.clipDelete" = "حذف مقطع التحريك" +"motion.clipUpdate" = "تحرير مقطع التحريك" +"motion.keyframe" = "إطار مفتاحي" +"motion.keyframeDelete" = "حذف الإطار المفتاحي" +"motion.keyframeEase" = "تنعيم الإطار المفتاحي" +"motion.keyframeMove" = "نقل الإطار المفتاحي" +"motion.replace" = "نقل التحريك" +"motion.timeline" = "الخط الزمني للحركة" +"motion.track" = "إظهار/إخفاء المسار" "node.create" = "إنشاء طبقة" "node.find" = "بحث عن الطبقات" "node.get" = "جلب طبقة" diff --git a/crates/ui-egui/locales/bn.toml b/crates/ui-egui/locales/bn.toml index 4b0ad0721..1a8233b6f 100644 --- a/crates/ui-egui/locales/bn.toml +++ b/crates/ui-egui/locales/bn.toml @@ -1904,6 +1904,16 @@ status = "draft — needs native review" "devMode.measurements" = "মাপের তালিকা" "devMode.removeMeasurement" = "মাপ সরান" "file.newBoard" = "নতুন বোর্ড" +"motion.clip" = "অ্যানিমেশন যোগ করুন" +"motion.clipDelete" = "অ্যানিমেশন ক্লিপ ডিলিট করুন" +"motion.clipUpdate" = "অ্যানিমেশন ক্লিপ এডিট" +"motion.keyframe" = "কীফ্রেম" +"motion.keyframeDelete" = "কীফ্রেম ডিলিট করুন" +"motion.keyframeEase" = "কীফ্রেম নরম করুন" +"motion.keyframeMove" = "কীফ্রেম সরান" +"motion.replace" = "অ্যানিমেশন সরান" +"motion.timeline" = "মোশন টাইমলাইন" +"motion.track" = "ট্র্যাক দেখান/লুকান" "tool.connector" = "সংযোগকারী" "tool.eraser" = "ইরেজার" "tool.highlighter" = "হাইলাইটার" diff --git a/crates/ui-egui/locales/cs.toml b/crates/ui-egui/locales/cs.toml index 5a3f2fbb9..370473968 100644 --- a/crates/ui-egui/locales/cs.toml +++ b/crates/ui-egui/locales/cs.toml @@ -2096,6 +2096,16 @@ status = "draft — needs native review" "library.usage" = "Použití knihovny" "measure.distances" = "Měřit vzdálenosti" "measure.padding" = "Měřit vnitřní odsazení automatického rozvržení" +"motion.clip" = "Přidat animaci" +"motion.clipDelete" = "Smazat animační klip" +"motion.clipUpdate" = "Upravit animační klip" +"motion.keyframe" = "Klíčový snímek" +"motion.keyframeDelete" = "Smazat klíčový snímek" +"motion.keyframeEase" = "Zjemnit klíčový snímek" +"motion.keyframeMove" = "Přesunout klíčový snímek" +"motion.replace" = "Přesunout animaci" +"motion.timeline" = "Časová osa pohybu" +"motion.track" = "Zobrazit/skrýt stopu" "node.create" = "Vytvořit vrstvu" "node.find" = "Najít vrstvy" "node.get" = "Získat vrstvu" diff --git a/crates/ui-egui/locales/de.toml b/crates/ui-egui/locales/de.toml index 57aa40180..91b2fb646 100644 --- a/crates/ui-egui/locales/de.toml +++ b/crates/ui-egui/locales/de.toml @@ -2258,6 +2258,16 @@ status = "draft — needs native review" "library.usage" = "Bibliotheksverwendung" "measure.distances" = "Abstände messen" "measure.padding" = "Innenabstand des Auto-Layouts messen" +"motion.clip" = "Animation hinzufügen" +"motion.clipDelete" = "Animationsclip löschen" +"motion.clipUpdate" = "Animationsclip bearbeiten" +"motion.keyframe" = "Keyframe" +"motion.keyframeDelete" = "Keyframe löschen" +"motion.keyframeEase" = "Keyframe-Easing" +"motion.keyframeMove" = "Keyframe verschieben" +"motion.replace" = "Animation verschieben" +"motion.timeline" = "Bewegungs-Zeitleiste" +"motion.track" = "Spur ein-/ausblenden" "node.create" = "Ebene erstellen" "node.find" = "Ebenen suchen" "node.get" = "Ebene abrufen" diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index fa853b62d..7ba0bf362 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -12,13 +12,16 @@ name = "English" "(no longer published)" = "(no longer published)" "({n} warnings: some entries were skipped)" = { one = "({n} warning: some entries were skipped)", other = "({n} warnings: some entries were skipped)" } "+ Create variable" = "+ Create variable" +"+{count} more" = "+{count} more" ", changed" = ", changed" ".fig (experimental)" = ".fig (experimental)" +"1 step" = "1 step" "1 year" = "1 year" "1…9, 0" = "1…9, 0" "30 days" = "30 days" "90 days" = "90 days" "@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{bin_added} / −{bin_deleted} binary assets, {first} – {last}" = "@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{bin_added} / −{bin_deleted} binary assets, {first} – {last}" +"A built-in skill. Make a copy to change it; your copy replaces it." = "A built-in skill. Make a copy to change it; your copy replaces it." "A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "A collection of this file with these modes and variables: override their values per mode and add variables of its own" "A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "A .figcraft file with this name already exists. Choose its full name to confirm replacement." "A later vote" = "A later vote" @@ -51,6 +54,7 @@ name = "English" "Add actions for when no condition holds" = "Add actions for when no condition holds" "Add an annotation for developers" = "Add an annotation for developers" "Add another condition" = "Add another condition" +"Add keyframe" = "Add keyframe" "Add auto layout" = "Add auto layout" "Add background behind overlay" = "Add background behind overlay" "Add column" = "Add column" @@ -59,6 +63,7 @@ name = "English" "Add effect" = "Add effect" "Add export setting" = "Add export setting" "Add fill" = "Add fill" +"Add hover, pressed and disabled variants" = "Add hover, pressed and disabled variants" "Add interaction" = "Add interaction" "Add layout grid" = "Add layout grid" "Add library" = "Add library" @@ -79,17 +84,139 @@ name = "English" "Add stroke" = "Add stroke" "Add variant" = "Add variant" "Add variant with a new value" = "Add variant with a new value" +"Agent quick actions" = "Agent quick actions" +"Allow" = "Allow" +"Always check with a screenshot" = "Always check with a screenshot" +"API key" = "API key" +"Ask" = "Ask" +"Ask agent…" = "Ask agent…" +"At most {count} images go with one request." = "At most {count} images go with one request." +"Attach" = "Attach" +"Attach an image or the selection. You can also drop an image on this panel." = "Attach an image or the selection. You can also drop an image on this panel." +"Attach the selection as an image" = "Attach the selection as an image" +"Attached image {name}" = "Attached image {name}" +"Bring this answer's changes back" = "Bring this answer's changes back" +"Built in" = "Built in" +"Can't attach {name}: {error}" = "Can't attach {name}: {error}" +"Can't delete {path}: {error}" = "Can't delete {path}: {error}" +"Can't reach the provider. Check the internet connection and try again." = "Can't reach the provider. Check the internet connection and try again." +"Can't read {name}: {error}" = "Can't read {name}: {error}" +"Can't render the selection: {error}" = "Can't render the selection: {error}" +"Changed 1 layer" = "Changed 1 layer" +"Changed the file" = "Changed the file" +"Changed {count} layers" = "Changed {count} layers" +"Changes undone" = "Changes undone" +"Chat history" = "Chat history" +"Check again" = "Check again" +"Check contrast and accessibility, then fix what fails" = "Check contrast and accessibility, then fix what fails" +"Check the connection" = "Check the connection" +"Check the selection for spacing and contrast problems" = "Check the selection for spacing and contrast problems" +"Checking…" = "Checking…" +"Choose a model first." = "Choose a model first." +"Choose how the agent reaches an AI model. It takes one step." = "Choose how the agent reaches an AI model. It takes one step." +"Connect" = "Connect" +"Connect a model" = "Connect a model" +"Connect a model first." = "Connect a model first." +"Connect a model to start" = "Connect a model to start" +"Connected, but the provider listed no chat model. Pick one under Advanced." = "Connected, but the provider listed no chat model. Pick one under Advanced." +"Connections" = "Connections" +"Copy this answer" = "Copy this answer" +"Copy this code" = "Copy this code" "Couldn't download {name}: {why}" = "Couldn't download {name}: {why}" "Couldn't open {name}." = "Couldn't open {name}." +"Default model" = "Default model" +"Delete this chat" = "Delete this chat" +"Deny" = "Deny" +"Describe what to design… @ names a layer, / adds a skill" = "Describe what to design… @ names a layer, / adds a skill" +"Design a sign-in screen for a mobile app" = "Design a sign-in screen for a mobile app" +"Dropped image" = "Dropped image" "Edit property" = "Edit property" +"Endpoint" = "Endpoint" +"Everything runs without asking" = "Everything runs without asking" +"Files and network ask first" = "Files and network ask first" +"Fill this with realistic content" = "Fill this with realistic content" +"Fix the type hierarchy" = "Fix the type hierarchy" "Frame {start} isn't in this file: presenting from the start." = "Frame {start} isn't in this file: presenting from the start." +"Get a key" = "Get a key" +"How many versions of the design to build" = "How many versions of the design to build" +"In $/1M" = "In $/1M" +"In use" = "In use" +"Installed, not signed in. Sign in with:" = "Installed, not signed in. Sign in with:" +"Instructions" = "Instructions" +"Instructions the agent follows for a kind of work. Type / in the box to add one to a request; the agent also loads one when it fits." = "Instructions the agent follows for a kind of work. Type / in the box to add one to a request; the agent also loads one when it fits." +"Layer" = "Layer" +"Layer {name}: select it" = "Layer {name}: select it" +"Leave {name} out of the request" = "Leave {name} out of the request" +"Look at the canvas after each change" = "Look at the canvas after each change" +"Make a copy to edit" = "Make a copy to edit" +"Make a pricing section with three plans" = "Make a pricing section with three plans" +"Make this responsive with auto layout" = "Make this responsive with auto layout" +"Make three variations of this" = "Make three variations of this" +"Manage connections…" = "Manage connections…" +"Match the colours to the file's styles" = "Match the colours to the file's styles" +"Model: {model}" = "Model: {model}" +"New chat" = "New chat" +"New skill" = "New skill" +"No earlier chats for this file" = "No earlier chats for this file" +"Not installed. Install it with:" = "Not installed. Install it with:" +"Nothing answered at this address. Is the local model server running?" = "Nothing answered at this address. Is the local model server running?" "Nothing to present." = "Nothing to present." "Nothing to present: {why}" = "Nothing to present: {why}" +"On: after every answer that changed the canvas, the agent takes a screenshot, compares it with the request and fixes what is off (one more request). Off: it takes one only when it decides to." = "On: after every answer that changed the canvas, the agent takes a screenshot, compares it with the request and fixes what is off (one more request). Off: it takes one only when it decides to." +"One line: the agent reads it to decide" = "One line: the agent reads it to decide" "Only a file on this site can be presented: {file}" = "Only a file on this site can be presented: {file}" "Lasso select" = "Lasso select" +"Only the last answer can be undone here, while nothing else changed since. Use Edit > Undo for single steps." = "Only the last answer can be undone here, while nothing else changed since. Use Edit > Undo for single steps." +"Out $/1M" = "Out $/1M" +"Paste a key and FigCraft picks a model for you. Keys stay in this app's settings, readable only by you." = "Paste a key and FigCraft picks a model for you. Keys stay in this app's settings, readable only by you." +"Paste image from clipboard" = "Paste image from clipboard" +"Paste your API key first." = "Paste your API key first." +"Pasted image {n}" = "Pasted image {n}" "Point eraser" = "Point eraser" "Preferred components" = "Preferred components" +"Price per million tokens (for the cost estimate)" = "Price per million tokens (for the cost estimate)" +"Put this request back in the box to change it" = "Put this request back in the box to change it" +"Queued" = "Queued" +"Reasoning" = "Reasoning" +"Rebuild as editable layers" = "Rebuild as editable layers" +"Rebuild this screenshot as editable layers" = "Rebuild this screenshot as editable layers" +"Recreate the attached screenshot as layers with auto layout" = "Recreate the attached screenshot as layers with auto layout" +"Redo" = "Redo" +"Refresh the model list" = "Refresh the model list" +"Remove image {name}" = "Remove image {name}" +"Remove queued request: {text}" = "Remove queued request: {text}" +"Remove {name}" = "Remove {name}" +"Rewrite the copy to be clearer and shorter" = "Rewrite the copy to be clearer and shorter" +"Run everything without asking" = "Run everything without asking" +"Running {tool}" = "Running {tool}" +"Select the changed layers and zoom to them" = "Select the changed layers and zoom to them" +"Select the layers this step changed and zoom to them" = "Select the layers this step changed and zoom to them" +"Select this layer on the canvas" = "Select this layer on the canvas" +"Send" = "Send" +"Show 1 layer" = "Show 1 layer" +"Show {count} layers" = "Show {count} layers" +"Sign in once in the program itself; FigCraft uses that sign-in and never sees it." = "Sign in once in the program itself; FigCraft uses that sign-in and never sees it." +"Skills" = "Skills" +"Skills can't be saved: the app has no settings folder." = "Skills can't be saved: the app has no settings folder." +"Something went wrong" = "Something went wrong" +"Stopped." = "Stopped." "Stroke eraser" = "Stroke eraser" +"The agent is working on the canvas" = "The agent is working on the canvas" +"The agent stopped unexpectedly." = "The agent stopped unexpectedly." +"The agent wants to: {reason}" = "The agent wants to: {reason}" +"The agent works on this canvas: describe a screen, or select layers and ask for a change." = "The agent works on this canvas: describe a screen, or select layers and ask for a change." +"The clipboard holds no image." = "The clipboard holds no image." +"The model reads images" = "The model reads images" +"The provider refused this key. Check that it is copied whole and still active." = "The provider refused this key. Check that it is copied whole and still active." +"Those layers are no longer in this file." = "Those layers are no longer in this file." +"Tidy up the spacing and alignment" = "Tidy up the spacing and alignment" +"Translate the text to English" = "Translate the text to English" +"Turn the selection into a component with variants" = "Turn the selection into a component with variants" +"Turn this into a component with variants" = "Turn this into a component with variants" +"Undo" = "Undo" +"Undo every change this answer made" = "Undo every change this answer made" +"Use a subscription" = "Use a subscription" +"Use an API key" = "Use an API key" "Values" = "Values" "Added" = "Added" "Added the library \"{name}\"" = "Added the library \"{name}\"" @@ -137,6 +264,7 @@ name = "English" "Anchor" = "Anchor" "Android" = "Android" "Android Vector Drawable" = "Android Vector Drawable" +"Angle" = "Angle" "Angular" = "Angular" "Animation" = "Animation" "Annotation" = "Annotation" @@ -274,6 +402,7 @@ name = "English" "Couldn't reach {server} for its team list." = "Couldn't reach {server} for its team list." "CSS custom properties…" = "CSS custom properties…" "Create from color" = "Create from color" +"Curve" = "Curve" "Dart constants for Flutter…" = "Dart constants for Flutter…" "Calculated from other variables; it follows them" = "Calculated from other variables; it follows them" "Can edit" = "Can edit" @@ -323,6 +452,7 @@ name = "English" "Code block" = "Code block" "Code syntax" = "Code syntax" "Collapse" = "Collapse" +"Collapse layers" = "Collapse layers" "Collection" = "Collection" "Collections" = "Collections" "Color" = "Color" @@ -374,6 +504,15 @@ name = "English" "Open preview in a new window" = "Open preview in a new window" "Return preview to the editor" = "Return preview to the editor" "The contrast can't be told when a gradient, image or blend mode is in this fill or behind the layer" = "The contrast can't be told when a gradient, image or blend mode is in this fill or behind the layer" +"Versions: {count}" = "Versions: {count}" +"What should we design?" = "What should we design?" +"When to use it" = "When to use it" +"Working…" = "Working…" +"Write a description for this component" = "Write a description for this component" +"{count} steps" = "{count} steps" +"{count} steps, {failed} failed" = "{count} steps, {failed} failed" +"{count} tokens" = "{count} tokens" +"{input} in · {output} out" = "{input} in · {output} out" "{level} needs {needed}:1 against {backdrop}" = "{level} needs {needed}:1 against {backdrop}" "Contributors" = "Contributors" "Contributors: {people} · Commits: {commits}" = "Contributors: {people} · Commits: {commits}" @@ -436,6 +575,10 @@ name = "English" "In code" = "In code" "Source file" = "Source file" "Variant value" = "Variant value" +"{m} min {s} s" = "{m} min {s} s" +"{name} is not an image this app reads: {error}" = "{name} is not an image this app reads: {error}" +"{n} s" = "{n} s" +"≈ ${cost} at API rates" = "≈ ${cost} at API rates" "⌘ click a padding field" = "⌘ click a padding field" "Ctrl+scroll" = "Ctrl+scroll" "Current name" = "Current name" @@ -545,6 +688,7 @@ name = "English" "Dispersion" = "Dispersion" "Display name" = "Display name" "Dissolve" = "Dissolve" +"Distance" = "Distance" "Distribute and tidy" = "Distribute and tidy" "Distribute horizontal spacing" = "Distribute horizontal spacing" "Distribute vertical spacing" = "Distribute vertical spacing" @@ -570,11 +714,13 @@ name = "English" "Drop to use this image" = "Drop to use this image" "Dual-licensed MIT OR Apache-2.0. Made by the ArtCraft team and community." = "Dual-licensed MIT OR Apache-2.0. Made by the ArtCraft team and community." "Duo" = "Duo" +"Duration" = "Duration" "Duplicate" = "Duplicate" "Duplicate by dragging" = "Duplicate by dragging" "Duplicate group" = "Duplicate group" "Duplicate mode" = "Duplicate mode" "Duplicate page" = "Duplicate page" +"Easing" = "Easing" "Edit" = "Edit" "Edit as an expression" = "Edit as an expression" "Edit colour" = "Edit colour" @@ -594,6 +740,7 @@ name = "English" "Effect styles" = "Effect styles" "Effects" = "Effects" "Curved" = "Curved" +"Elasticity" = "Elasticity" "Elbow" = "Elbow" "Ellipse" = "Ellipse" "Ellipses" = "Ellipses" @@ -614,6 +761,7 @@ name = "English" "Every conflict has a choice." = "Every conflict has a choice." "Every top-level frame already starts a flow" = "Every top-level frame already starts a flow" "Everyone who reaches this server can open these files while they are shared." = "Everyone who reaches this server can open these files while they are shared." +"Exact envelope" = "Exact envelope" "Exact only" = "Exact only" "Exact opacity (4 then 5: 45%)" = "Exact opacity (4 then 5: 45%)" "Exclude" = "Exclude" @@ -711,6 +859,7 @@ name = "English" "Frame tools" = "Frame tools" "Frames" = "Frames" "Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." = "Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." +"From" = "From" "From the library \"{name}\": read-only" = "From the library \"{name}\": read-only" "From {name}" = "From {name}" "From {server}" = "From {server}" @@ -926,6 +1075,7 @@ name = "English" "Local variables" = "Local variables" "Lock/Unlock" = "Lock/Unlock" "Locked" = "Locked" +"Loop" = "Loop" "Lowercase" = "Lowercase" "Luminance" = "Luminance" "Luminosity" = "Luminosity" @@ -943,9 +1093,12 @@ name = "English" "Pasted design layers" = "Pasted design layers" "Pasted design layers; the clipboard didn't carry the images of: {layers}" = "Pasted design layers; the clipboard didn't carry the images of: {layers}" "Remove these results from the file" = "Remove these results from the file" +"Mass" = "Mass" "Scroll wheel zoom" = "Scroll wheel zoom" "Invert zoom direction" = "Invert zoom direction" "Shared by your team on {server}" = "Shared by your team on {server}" +"Select a layer" = "Select a layer" +"Select a segment" = "Select a segment" "Slot name" = "Slot name" "Mar" = "Mar" "Margin" = "Margin" @@ -1174,6 +1327,7 @@ name = "English" "Pages" = "Pages" "Pages added to the document" = "Pages added to the document" "Pause" = "Pause" +"Play" = "Play" "Pink" = "Pink" "Placed on the current page" = "Placed on the current page" "Plain text" = "Plain text" @@ -1310,6 +1464,7 @@ name = "English" "Remove from server…" = "Remove from server…" "Remove guide" = "Remove guide" "Remove interaction" = "Remove interaction" +"Remove keyframe" = "Remove keyframe" "Remove library from this file" = "Remove library from this file" "Remove measurement" = "Remove measurement" "Remove min and max" = "Remove min and max" @@ -1443,6 +1598,8 @@ name = "English" "Someone who left" = "Someone who left" "Take the results off the board; they stay in the file" = "Take the results off the board; they stay in the file" "Upload from computer" = "Upload from computer" +"Spring" = "Spring" +"To" = "To" "Use fonts installed on this computer…" = "Use fonts installed on this computer…" "Search layers" = "Search layers" "Search pages" = "Search pages" @@ -1855,6 +2012,7 @@ name = "English" "Yellow" = "Yellow" "Yesterday" = "Yesterday" "You" = "You" +"You edited the file while the agent worked, so Undo answer is off for this turn; use Edit › Undo." = "You edited the file while the agent worked, so Undo answer is off for this turn; use Edit › Undo." "You'll get the shared file as a new tab and edit it together." = "You'll get the shared file as a new tab and edit it together." "You're spotlighting: everyone follows your view" = "You're spotlighting: everyone follows your view" "Your copy of the file stays open" = "Your copy of the file stays open" diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index 56d2f87b2..dfe14d875 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -2205,6 +2205,16 @@ status = "draft — needs native review" "library.usage" = "Uso de la biblioteca" "measure.distances" = "Medir distancias" "measure.padding" = "Medir margen interno del diseño automático" +"motion.clip" = "Añadir animación" +"motion.clipDelete" = "Eliminar clip de animación" +"motion.clipUpdate" = "Editar clip de animación" +"motion.keyframe" = "Fotograma clave" +"motion.keyframeDelete" = "Eliminar fotograma clave" +"motion.keyframeEase" = "Suavizar fotograma clave" +"motion.keyframeMove" = "Mover fotograma clave" +"motion.replace" = "Mover animación" +"motion.timeline" = "Línea de tiempo de movimiento" +"motion.track" = "Mostrar/ocultar pista" "node.create" = "Crear capa" "node.find" = "Buscar capas" "node.get" = "Obtener capa" diff --git a/crates/ui-egui/locales/fi.toml b/crates/ui-egui/locales/fi.toml index c28e3b349..0edd54b54 100644 --- a/crates/ui-egui/locales/fi.toml +++ b/crates/ui-egui/locales/fi.toml @@ -2339,6 +2339,16 @@ status = "draft — needs native review" "library.usage" = "Kirjaston käyttö" "measure.distances" = "Mittaa etäisyyksiä" "measure.padding" = "Mittaa automaattisen asettelun sisämarginaali" +"motion.clip" = "Lisää animaatio" +"motion.clipDelete" = "Poista animaatioklippi" +"motion.clipUpdate" = "Muokkaa animaatioklippiä" +"motion.keyframe" = "Avainkehys" +"motion.keyframeDelete" = "Poista avainkehys" +"motion.keyframeEase" = "Pehmennä avainkehys" +"motion.keyframeMove" = "Siirrä avainkehys" +"motion.replace" = "Siirrä animaatio" +"motion.timeline" = "Liikkeen aikajana" +"motion.track" = "Näytä/piilota raita" "node.create" = "Luo taso" "node.find" = "Etsi tasoja" "node.get" = "Hae taso" diff --git a/crates/ui-egui/locales/fr.toml b/crates/ui-egui/locales/fr.toml index 6365e2fbb..f96387e03 100644 --- a/crates/ui-egui/locales/fr.toml +++ b/crates/ui-egui/locales/fr.toml @@ -2141,6 +2141,16 @@ status = "draft — needs native review" "library.usage" = "Utilisation de la bibliothèque" "measure.distances" = "Mesurer les distances" "measure.padding" = "Mesurer la marge intérieure de la mise en page auto" +"motion.clip" = "Ajouter une animation" +"motion.clipDelete" = "Supprimer le clip d'animation" +"motion.clipUpdate" = "Modifier le clip d'animation" +"motion.keyframe" = "Image clé" +"motion.keyframeDelete" = "Supprimer l'image clé" +"motion.keyframeEase" = "Adoucir l'image clé" +"motion.keyframeMove" = "Déplacer l'image clé" +"motion.replace" = "Déplacer l'animation" +"motion.timeline" = "Chronologie du mouvement" +"motion.track" = "Afficher/masquer la piste" "node.create" = "Créer un calque" "node.find" = "Rechercher des calques" "node.get" = "Obtenir le calque" diff --git a/crates/ui-egui/locales/id.toml b/crates/ui-egui/locales/id.toml index 5563cec1d..51b087684 100644 --- a/crates/ui-egui/locales/id.toml +++ b/crates/ui-egui/locales/id.toml @@ -2100,6 +2100,16 @@ status = "draft — needs native review" "library.usage" = "Penggunaan pustaka" "measure.distances" = "Ukur jarak" "measure.padding" = "Ukur padding auto layout" +"motion.clip" = "Tambahkan animasi" +"motion.clipDelete" = "Hapus klip animasi" +"motion.clipUpdate" = "Edit klip animasi" +"motion.keyframe" = "Keyframe" +"motion.keyframeDelete" = "Hapus keyframe" +"motion.keyframeEase" = "Haluskan keyframe" +"motion.keyframeMove" = "Pindahkan keyframe" +"motion.replace" = "Pindahkan animasi" +"motion.timeline" = "Linimasa gerak" +"motion.track" = "Tampilkan/sembunyikan trek" "node.create" = "Buat layer" "node.find" = "Cari layer" "node.get" = "Ambil layer" diff --git a/crates/ui-egui/locales/it.toml b/crates/ui-egui/locales/it.toml index 441ea22a2..0bb81a15c 100644 --- a/crates/ui-egui/locales/it.toml +++ b/crates/ui-egui/locales/it.toml @@ -2424,6 +2424,16 @@ status = "draft — needs native review" "library.usage" = "Utilizzo della libreria" "measure.distances" = "Misura distanze" "measure.padding" = "Misura margini interni dell'auto layout" +"motion.clip" = "Aggiungi animazione" +"motion.clipDelete" = "Elimina clip di animazione" +"motion.clipUpdate" = "Modifica clip di animazione" +"motion.keyframe" = "Fotogramma chiave" +"motion.keyframeDelete" = "Elimina fotogramma chiave" +"motion.keyframeEase" = "Ammorbidisci fotogramma chiave" +"motion.keyframeMove" = "Sposta fotogramma chiave" +"motion.replace" = "Sposta animazione" +"motion.timeline" = "Sequenza temporale del movimento" +"motion.track" = "Mostra/nascondi traccia" "node.create" = "Crea livello" "node.find" = "Trova livelli" "node.get" = "Ottieni livello" diff --git a/crates/ui-egui/locales/ja.toml b/crates/ui-egui/locales/ja.toml index a0c6eb224..4ba99b47b 100644 --- a/crates/ui-egui/locales/ja.toml +++ b/crates/ui-egui/locales/ja.toml @@ -2121,6 +2121,16 @@ status = "draft — needs native review" "library.usage" = "ライブラリの使用状況" "measure.distances" = "距離を測定" "measure.padding" = "オートレイアウトのパディングを測定" +"motion.clip" = "アニメーションを追加" +"motion.clipDelete" = "アニメーションクリップを削除" +"motion.clipUpdate" = "アニメーションクリップを編集" +"motion.keyframe" = "キーフレーム" +"motion.keyframeDelete" = "キーフレームを削除" +"motion.keyframeEase" = "キーフレームのイージング" +"motion.keyframeMove" = "キーフレームを移動" +"motion.replace" = "アニメーションを移動" +"motion.timeline" = "モーションのタイムライン" +"motion.track" = "トラックの表示/非表示" "node.create" = "レイヤーを作成" "node.find" = "レイヤーを検索" "node.get" = "レイヤーを取得" diff --git a/crates/ui-egui/locales/ka.toml b/crates/ui-egui/locales/ka.toml index b73a24b34..401be9900 100644 --- a/crates/ui-egui/locales/ka.toml +++ b/crates/ui-egui/locales/ka.toml @@ -2339,6 +2339,16 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv "library.usage" = "ბიბლიოთეკის გამოყენება" "measure.distances" = "მანძილების გაზომვა" "measure.padding" = "ავტოგანლაგების შიდა დაშორების გაზომვა" +"motion.clip" = "ანიმაციის დამატება" +"motion.clipDelete" = "ანიმაციის კლიპის წაშლა" +"motion.clipUpdate" = "ანიმაციის კლიპის რედაქტირება" +"motion.keyframe" = "საკვანძო კადრი" +"motion.keyframeDelete" = "საკვანძო კადრის წაშლა" +"motion.keyframeEase" = "საკვანძო კადრის შერბილება" +"motion.keyframeMove" = "საკვანძო კადრის გადაადგილება" +"motion.replace" = "ანიმაციის გადაადგილება" +"motion.timeline" = "მოძრაობის დროის ხაზი" +"motion.track" = "ტრასის ჩვენება/დამალვა" "node.create" = "შრის შექმნა" "node.find" = "შრეების ძებნა" "node.get" = "შრის მიღება" diff --git a/crates/ui-egui/locales/ko.toml b/crates/ui-egui/locales/ko.toml index c19c14261..d0d6f77ee 100644 --- a/crates/ui-egui/locales/ko.toml +++ b/crates/ui-egui/locales/ko.toml @@ -2157,6 +2157,16 @@ status = "draft — needs native review" "library.usage" = "라이브러리 사용 현황" "measure.distances" = "거리 측정" "measure.padding" = "자동 레이아웃 패딩 측정" +"motion.clip" = "애니메이션 추가" +"motion.clipDelete" = "애니메이션 클립 삭제" +"motion.clipUpdate" = "애니메이션 클립 편집" +"motion.keyframe" = "키프레임" +"motion.keyframeDelete" = "키프레임 삭제" +"motion.keyframeEase" = "키프레임 이징" +"motion.keyframeMove" = "키프레임 이동" +"motion.replace" = "애니메이션 이동" +"motion.timeline" = "모션 타임라인" +"motion.track" = "트랙 표시/숨기기" "node.create" = "레이어 만들기" "node.find" = "레이어 찾기" "node.get" = "레이어 가져오기" diff --git a/crates/ui-egui/locales/nl.toml b/crates/ui-egui/locales/nl.toml index 712a31201..78aab60b3 100644 --- a/crates/ui-egui/locales/nl.toml +++ b/crates/ui-egui/locales/nl.toml @@ -2139,6 +2139,16 @@ status = "draft — needs native review" "library.usage" = "Bibliotheekgebruik" "measure.distances" = "Afstanden meten" "measure.padding" = "Padding van auto layout meten" +"motion.clip" = "Animatie toevoegen" +"motion.clipDelete" = "Animatieclip verwijderen" +"motion.clipUpdate" = "Animatieclip bewerken" +"motion.keyframe" = "Keyframe" +"motion.keyframeDelete" = "Keyframe verwijderen" +"motion.keyframeEase" = "Keyframe versoepelen" +"motion.keyframeMove" = "Keyframe verplaatsen" +"motion.replace" = "Animatie verplaatsen" +"motion.timeline" = "Bewegingstijdlijn" +"motion.track" = "Spoor tonen/verbergen" "node.create" = "Laag maken" "node.find" = "Lagen zoeken" "node.get" = "Laag ophalen" diff --git a/crates/ui-egui/locales/pl.toml b/crates/ui-egui/locales/pl.toml index be195ead4..fcf2e072c 100644 --- a/crates/ui-egui/locales/pl.toml +++ b/crates/ui-egui/locales/pl.toml @@ -2153,6 +2153,16 @@ name = "Polski" "library.usage" = "Użycie biblioteki" "measure.distances" = "Zmierz odległości" "measure.padding" = "Zmierz marginesy automatycznego układu" +"motion.clip" = "Dodaj animację" +"motion.clipDelete" = "Usuń klip animacji" +"motion.clipUpdate" = "Edytuj klip animacji" +"motion.keyframe" = "Klatka kluczowa" +"motion.keyframeDelete" = "Usuń klatkę kluczową" +"motion.keyframeEase" = "Wygładź klatkę kluczową" +"motion.keyframeMove" = "Przesuń klatkę kluczową" +"motion.replace" = "Przesuń animację" +"motion.timeline" = "Oś czasu ruchu" +"motion.track" = "Pokaż/ukryj ścieżkę" "node.create" = "Utwórz warstwę" "node.find" = "Znajdź warstwy" "node.get" = "Pobierz warstwę" diff --git a/crates/ui-egui/locales/pt-BR.toml b/crates/ui-egui/locales/pt-BR.toml index cc7ab5e0a..e7acc8586 100644 --- a/crates/ui-egui/locales/pt-BR.toml +++ b/crates/ui-egui/locales/pt-BR.toml @@ -2154,6 +2154,16 @@ status = "draft — needs native review" "library.usage" = "Uso da biblioteca" "measure.distances" = "Medir distâncias" "measure.padding" = "Medir espaçamento interno do layout automático" +"motion.clip" = "Adicionar animação" +"motion.clipDelete" = "Excluir clipe de animação" +"motion.clipUpdate" = "Editar clipe de animação" +"motion.keyframe" = "Quadro-chave" +"motion.keyframeDelete" = "Excluir quadro-chave" +"motion.keyframeEase" = "Suavizar quadro-chave" +"motion.keyframeMove" = "Mover quadro-chave" +"motion.replace" = "Mover animação" +"motion.timeline" = "Linha do tempo de movimento" +"motion.track" = "Mostrar/ocultar faixa" "node.create" = "Criar camada" "node.find" = "Localizar camadas" "node.get" = "Obter camada" diff --git a/crates/ui-egui/locales/ru.toml b/crates/ui-egui/locales/ru.toml index 0a523cd05..ced7ba677 100644 --- a/crates/ui-egui/locales/ru.toml +++ b/crates/ui-egui/locales/ru.toml @@ -2333,6 +2333,16 @@ name = "Русский" "library.usage" = "Использование библиотеки" "measure.distances" = "Измерить расстояния" "measure.padding" = "Измерить внутренние отступы автолейаута" +"motion.clip" = "Добавить анимацию" +"motion.clipDelete" = "Удалить клип анимации" +"motion.clipUpdate" = "Изменить клип анимации" +"motion.keyframe" = "Ключевой кадр" +"motion.keyframeDelete" = "Удалить ключевой кадр" +"motion.keyframeEase" = "Сгладить ключевой кадр" +"motion.keyframeMove" = "Переместить ключевой кадр" +"motion.replace" = "Переместить анимацию" +"motion.timeline" = "Шкала времени движения" +"motion.track" = "Показать/скрыть дорожку" "node.create" = "Создать слой" "node.find" = "Найти слои" "node.get" = "Получить слой" diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index a8b6f661c..a4980ba39 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -2395,6 +2395,16 @@ name = "Svenska" "library.usage" = "Biblioteksanvändning" "measure.distances" = "Mät avstånd" "measure.padding" = "Mät padding" +"motion.clip" = "Lägg till animering" +"motion.clipDelete" = "Radera animeringsklipp" +"motion.clipUpdate" = "Redigera animeringsklipp" +"motion.keyframe" = "Nyckelbild" +"motion.keyframeDelete" = "Radera nyckelbild" +"motion.keyframeEase" = "Mjuka upp nyckelbild" +"motion.keyframeMove" = "Flytta nyckelbild" +"motion.replace" = "Flytta animering" +"motion.timeline" = "Rörelsetidslinje" +"motion.track" = "Visa/dölj spår" "node.create" = "Skapa nod" "node.find" = "Sök lager" "node.get" = "Hämta nod" diff --git a/crates/ui-egui/locales/th.toml b/crates/ui-egui/locales/th.toml index 937e6e694..214f85866 100644 --- a/crates/ui-egui/locales/th.toml +++ b/crates/ui-egui/locales/th.toml @@ -2117,6 +2117,16 @@ status = "draft — needs native review" "library.usage" = "การใช้งานไลบรารี" "measure.distances" = "วัดระยะห่าง" "measure.padding" = "วัดระยะขอบในของออโต้เลย์เอาต์" +"motion.clip" = "เพิ่มแอนิเมชัน" +"motion.clipDelete" = "ลบคลิปแอนิเมชัน" +"motion.clipUpdate" = "แก้ไขคลิปแอนิเมชัน" +"motion.keyframe" = "คีย์เฟรม" +"motion.keyframeDelete" = "ลบคีย์เฟรม" +"motion.keyframeEase" = "ปรับความนุ่มคีย์เฟรม" +"motion.keyframeMove" = "ย้ายคีย์เฟรม" +"motion.replace" = "ย้ายแอนิเมชัน" +"motion.timeline" = "ไทม์ไลน์การเคลื่อนไหว" +"motion.track" = "แสดง/ซ่อนแทร็ก" "node.create" = "สร้างเลเยอร์" "node.find" = "ค้นหาเลเยอร์" "node.get" = "ดึงเลเยอร์" diff --git a/crates/ui-egui/locales/tr.toml b/crates/ui-egui/locales/tr.toml index cfcfda0df..29d48de69 100644 --- a/crates/ui-egui/locales/tr.toml +++ b/crates/ui-egui/locales/tr.toml @@ -2330,6 +2330,16 @@ name = "Türkçe" "library.usage" = "Kitaplık kullanımı" "measure.distances" = "Mesafeleri ölç" "measure.padding" = "Otomatik yerleşim iç boşluğunu ölç" +"motion.clip" = "Animasyon ekle" +"motion.clipDelete" = "Animasyon klibini sil" +"motion.clipUpdate" = "Animasyon klibini düzenle" +"motion.keyframe" = "Anahtar kare" +"motion.keyframeDelete" = "Anahtar kareyi sil" +"motion.keyframeEase" = "Anahtar kareyi yumuşat" +"motion.keyframeMove" = "Anahtar kareyi taşı" +"motion.replace" = "Animasyonu taşı" +"motion.timeline" = "Hareket zaman çizelgesi" +"motion.track" = "Parçayı göster/gizle" "node.create" = "Katman oluştur" "node.find" = "Katman bul" "node.get" = "Katmanı getir" diff --git a/crates/ui-egui/locales/vi.toml b/crates/ui-egui/locales/vi.toml index d9c8e88dc..a22da2531 100644 --- a/crates/ui-egui/locales/vi.toml +++ b/crates/ui-egui/locales/vi.toml @@ -2041,6 +2041,16 @@ status = "draft — needs native review" "library.usage" = "Mức sử dụng thư viện" "measure.distances" = "Đo khoảng cách" "measure.padding" = "Đo khoảng đệm bố cục tự động" +"motion.clip" = "Thêm hoạt ảnh" +"motion.clipDelete" = "Xóa đoạn hoạt ảnh" +"motion.clipUpdate" = "Chỉnh sửa đoạn hoạt ảnh" +"motion.keyframe" = "Khung hình chính" +"motion.keyframeDelete" = "Xóa khung hình chính" +"motion.keyframeEase" = "Làm mượt khung hình chính" +"motion.keyframeMove" = "Di chuyển khung hình chính" +"motion.replace" = "Di chuyển hoạt ảnh" +"motion.timeline" = "Dòng thời gian chuyển động" +"motion.track" = "Hiện/ẩn rãnh" "node.create" = "Tạo lớp" "node.find" = "Tìm lớp" "node.get" = "Lấy lớp" diff --git a/crates/ui-egui/locales/zh-Hans.toml b/crates/ui-egui/locales/zh-Hans.toml index 7d49b2ade..f1dbc4006 100644 --- a/crates/ui-egui/locales/zh-Hans.toml +++ b/crates/ui-egui/locales/zh-Hans.toml @@ -436,10 +436,12 @@ status = "draft — needs native review" "Drop shadow" = "投影" "Dual-licensed MIT OR Apache-2.0. Made by the ArtCraft team and community." = "采用 MIT 或 Apache-2.0 双重许可。由 ArtCraft 团队和社区打造。" "Duo" = "双色" +"Duration" = "时长" "Duplicate" = "创建副本" "Duplicate by dragging" = "拖动创建副本" "Duplicate mode" = "复制模式" "Duplicate page" = "复制页面" +"Easing" = "缓动" "Edit" = "编辑" "Edit as an expression" = "以表达式编辑" "Edit colour" = "编辑颜色" @@ -973,6 +975,8 @@ status = "draft — needs native review" "Pages" = "页面" "Pages added to the document" = "页面已添加到文档" "Pause" = "暂停" +"Play" = "播放" +"Loop" = "循环" "Pink" = "粉色" "Placed on the current page" = "已放置在当前页面" "Pages: {pages}" = "页面:{pages}" @@ -2054,6 +2058,16 @@ status = "draft — needs native review" "library.usage" = "库使用情况" "measure.distances" = "测量距离" "measure.padding" = "测量自动布局内边距" +"motion.clip" = "添加动画" +"motion.clipDelete" = "删除动画片段" +"motion.clipUpdate" = "编辑动画片段" +"motion.keyframe" = "关键帧" +"motion.keyframeDelete" = "删除关键帧" +"motion.keyframeEase" = "缓动关键帧" +"motion.keyframeMove" = "移动关键帧" +"motion.replace" = "移动动画" +"motion.timeline" = "动效时间线" +"motion.track" = "显示/隐藏轨道" "node.create" = "创建图层" "node.find" = "查找图层" "node.get" = "获取图层" diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index eef7e4426..5432fafb8 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -5,8 +5,8 @@ use super::state::{LEFT_PANEL, LeftTab, MOBILE_STRIP, MobilePanel, NARROW_WIDTH, use super::{ Arc, Done, FigApp, NodeId, OsStr, Path, PathBuf, PendingAck, PendingDialog, Poll, Session, TaskContext, UiState, Value, Waker, a11y, branch_ui, canvas, cjk, comments, cursors, dev_compare, dialogs, frame_stats, home, home_recents, i18n, icons, import_report, json, layers, live, menus, - missing_fonts, online, plugins_ui, present, render_worker, right, selection_spacing, shortcuts, style_picker, tabs, theme, toolbar, ui_scale, - updates_ui, variable_ui, versions, widgets, windows, + missing_fonts, motion, online, plugins_ui, present, render_worker, right, selection_spacing, shortcuts, style_picker, tabs, theme, toolbar, + ui_scale, updates_ui, variable_ui, versions, widgets, windows, }; mod clipboard; @@ -41,6 +41,8 @@ impl FigApp { field_focus: false, panels_unsaved: false, control_queue: Vec::new(), + #[cfg(not(target_arch = "wasm32"))] + chat: crate::chat::Chat::default(), control_waits: Default::default(), control_input: Vec::new(), frame_stats: frame_stats::FrameStats::default(), @@ -214,6 +216,19 @@ impl FigApp { // target/caret. Outgoing IME receipts run after mutation and cannot authorize it. let ime_input = shortcuts::ImeInputBaseline::capture(self); let t = theme::Tokens::get(&ctx); + // The agent's settings are read once, before the first frame lays out the panels: a + // window last left on the Agent tab opens on it. + #[cfg(not(target_arch = "wasm32"))] + if !self.chat.is_loaded() { + let path = self.services.agent_config_path(); + self.chat.ensure_loaded(path); + if self.chat.agents.panel { + self.ui.left_tab = LeftTab::Agent; + self.ui.left_collapsed = false; + } + } + #[cfg(not(target_arch = "wasm32"))] + crate::chat::shortcut(self, &ctx); // A field that had the keyboard when the frame began keeps its keys from the shortcuts // even if it lets go during the frame (Enter commits it), or as it began (egui drops the // focus on Escape before the frame, which cancels the field's edit and nothing else). @@ -314,6 +329,19 @@ impl FigApp { // right, the "right" (Design) panel on the left. Their ids and widths stay as they are. let mirrored = self.ui.mirrored; let side = |start: bool, id: &'static str| if start != mirrored { egui::Panel::left(id) } else { egui::Panel::right(id) }; + // The Motion timeline docks at the bottom of the window, full width, above both side panels. + if !hidden && !narrow && self.ui.motion_open { + // The panel takes an exact size and its own top edge drags it. A shrunken window keeps + // a strip of canvas rather than eating it whole. + let tallest = (ui.available_height() - 160.0).max(motion::timeline::MIN_H); + let h = motion::timeline::height(&self.ui.motion).min(tallest); + self.ui.motion.timeline_h = h; + egui::Panel::bottom("motion_timeline") + .exact_size(h) + .resizable(false) + .frame(egui::Frame::NONE.fill(t.panel)) + .show(ui, |ui| motion::timeline::panel(self, ui)); + } let rail_shown = !hidden && !minimized && (!narrow || mobile == Some(MobilePanel::Left)); if rail_shown && self.session.prefs.nav_bar_auto_hide { self.nav_bar_peek(&ctx, ui.available_rect_before_wrap(), mirrored); @@ -361,6 +389,7 @@ impl FigApp { LeftTab::File => i18n::tr("Layers"), LeftTab::Assets => i18n::tr("Assets"), LeftTab::Plugins => i18n::tr("Plugins"), + LeftTab::Agent => i18n::tr("Agent"), }; a11y::region(&mut self.ui.nav, ui, a11y::Region::Layers, egui::accesskit::Role::Pane, label); layers::left_panel(self, ui) @@ -480,3 +509,39 @@ pub(crate) fn right_tab_label(tab: RightTab) -> &'static str { RightTab::Inspect => i18n::tr("Developer Mode"), } } + +impl FigApp { + /// The page evaluated at the playhead while Motion is open, so the renderer previews the + /// animation. The result is cached per document revision, page and playhead: the renderer + /// recognises what it draws by the document's pointer, so an unchanged preview must hand back + /// the same one. + /// + /// The document in the session is never replaced: the canvas's input, hit tests, commands and + /// undo all see the real document, so a gesture that starts while the preview is on cannot + /// record evaluated values. Only the pixels are previewed. + pub(crate) fn preview_document(&mut self) -> Option> { + // The preview is a picture, not an edit: nothing it draws can reach the document. + if !self.ui.motion_open { + self.ui.motion.preview = None; + return None; + } + let (uid, revision, page) = { + let ds = self.session.ds().ok()?; + (ds.uid, ds.revision, ds.page) + }; + let key = motion::Preview { uid, revision, page, playhead: self.ui.motion.playhead_ms.to_bits() }; + if let Some((built, doc)) = &self.ui.motion.preview + && *built == key + { + return Some(doc.clone()); + } + let doc = self.session.doc().ok()?; + if figcraft_doc::anim::motion::animated_nodes(doc, page).is_empty() { + self.ui.motion.preview = None; + return None; + } + let evaluated = Arc::new(figcraft_doc::anim::motion::evaluate(doc, page, self.ui.motion.playhead_ms)); + self.ui.motion.preview = Some((key, evaluated.clone())); + Some(evaluated) + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 9f84c2ec4..dc990d66d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -520,7 +520,10 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { }) .unwrap_or(t.canvas); let dots = crate::board_bar::dots(app, bg, &t); - request_render(app, worker, &ctx, ppp, max_texture_side, dots); + // Motion previews the page at the playhead for the renderer alone: what the canvas hit-tests, + // edits and records in undo is the real document. + let preview = app.preview_document(); + request_render(app, worker, &ctx, ppp, max_texture_side, dots, preview); drag_sprite::drop_orphan(&mut app.canvas); // Every finished render is shown, even when a newer one is already on its way: renders finish // in order, and an edit every frame (a drag) would otherwise never show until it stopped. diff --git a/crates/ui-egui/src/canvas/render.rs b/crates/ui-egui/src/canvas/render.rs index d774ab0e0..493fcbd34 100644 --- a/crates/ui-egui/src/canvas/render.rs +++ b/crates/ui-egui/src/canvas/render.rs @@ -60,9 +60,16 @@ pub(super) fn request_render( ppp: f32, max_texture_side: u32, dots: Option, + preview: Option>, ) { // A dragged layer drawn as a sprite: the render is of the document the drag started from, without it. - let sprite = super::drag_sprite::sync(app, ctx, ppp, max_texture_side); + // Motion's preview draws every layer at the playhead, the dragged ones too, so it takes no sprite. + let sprite = if preview.is_some() { + app.canvas.sprite = None; + None + } else { + super::drag_sprite::sync(app, ctx, ppp, max_texture_side) + }; let Ok(ds) = app.session.ds() else { return }; let rect = app.canvas.rect; let (mut ox, mut oy) = ds.view.origin(); @@ -77,9 +84,16 @@ pub(super) fn request_render( }; // A drag's sprite renders the document the drag started from, without the dragged layers; // otherwise the edited text (an IME composition included) or a highlighter stroke is drawn live. - let (doc, skip, highlighter_generation) = match sprite { - Some((doc, skip)) => (doc, skip, None), - None => { + // Motion hands the page evaluated at the playhead here, for the pixels only. + let (doc, skip, highlighter_generation) = match (sprite, preview) { + (Some((doc, skip)), _) => (doc, skip, None), + // Text being composed with Motion open is evaluated too, or the letters follow the + // keyboard while the animation stands still until they are committed. + (None, Some(motion)) => match app.preedit_view() { + Some(text) => (Arc::new(figcraft_doc::anim::motion::evaluate(&text.doc, ds.page, app.ui.motion.playhead_ms)), vec![], None), + None => (motion, vec![], None), + }, + (None, None) => { let (doc, generation) = app.canvas_document(ds); (doc, vec![], generation) } diff --git a/crates/ui-egui/src/canvas/zoom_preview_tests.rs b/crates/ui-egui/src/canvas/zoom_preview_tests.rs index f79fdbda4..50b2de0b5 100644 --- a/crates/ui-egui/src/canvas/zoom_preview_tests.rs +++ b/crates/ui-egui/src/canvas/zoom_preview_tests.rs @@ -447,7 +447,7 @@ fn a_highlighter_render_delivered_after_escape_cannot_enter_the_page_cache() { } w.poll().expect("a finished render in the queue") }; - let submit = |app: &mut crate::FigApp, w: &mut Worker| super::request_render(app, w, &ctx, 1.0, 256, None); + let submit = |app: &mut crate::FigApp, w: &mut Worker| super::request_render(app, w, &ctx, 1.0, 256, None, None); submit(&mut app, &mut worker); let clean = queued(&mut worker); let clean_seq = clean.seq; diff --git a/crates/ui-egui/src/chat.rs b/crates/ui-egui/src/chat.rs new file mode 100644 index 000000000..7e4e9acb2 --- /dev/null +++ b/crates/ui-egui/src/chat.rs @@ -0,0 +1,3628 @@ +//! The Agent tab: the conversation with the agent, filling the left panel. +//! +//! The panel owns the worker thread ([`figcraft_agent::Worker`]); every tool call the model asks +//! for goes to the UI thread through the bridge ([`Chat::take_bridge_calls`]) and runs like a +//! control request, so the agent and an external MCP client behave the same. +//! +//! Connecting is one step: pick a subscription the person already signed in to in its own tool +//! (Claude Code, Codex, OpenCode), or paste an API key; the model list and a sensible model come +//! from the provider. Endpoints, limits and prices stay under Advanced. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; + +use egui::{Align, CornerRadius, Layout, Margin, RichText, Sense, Stroke, Ui, pos2, vec2}; +use figcraft_agent::bridge::{self, Bridge}; +use figcraft_agent::cli::Status as CliStatus; +use figcraft_agent::config::Reasoning; +use figcraft_agent::{AGENT_NAME, AgentsFile, ApiKind, ChatEvent, PRESETS, Provider, SUBSCRIPTIONS, Usage, Worker}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::control::{ControlReply, ControlRequest, RequestGate}; +use crate::i18n::{tr, trf}; +use crate::theme::{Tokens, regular, semibold}; +use crate::widgets::{self, PAD}; +use crate::{FigApp, a11y, icons}; + +/// One line of the conversation. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum Entry { + User(String), + Assistant(String), + Tool { + title: String, + summary: String, + state: ToolState, + /// The layers this step added or changed (its own changes, not the layers around them). + #[serde(default)] + layers: Vec, + }, + Note(String), + /// A turn that failed (network, provider, sign-in), shown with a way to fix the connection. + Error(String), + /// What the person attached to the request after it: layers (clickable, to select them again) + /// and the names of images. + Refs { + layers: Vec, + images: Vec, + /// Skills attached with `/`. + #[serde(default)] + skills: Vec, + }, + /// How long an answer took and the tokens it used. + Stats { + secs: u64, + tokens: u64, + }, + /// What an answer changed on the canvas, after it: the layers, and the undo steps it took. + Changes { + layers: Vec, + steps: usize, + /// The undo depth right after the answer; undoing it is offered only while nothing else + /// was done since. + depth: usize, + #[serde(default)] + undone: bool, + /// Made in this run of the app (undo history is not kept across launches). + #[serde(skip)] + live: bool, + }, +} + +/// A layer attached to a request. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LayerRef { + pub id: u64, + pub name: String, +} + +/// A skill open in the editor. `file`: the person's skill it replaces (none for a new one). +#[derive(Clone, Debug, Default)] +struct SkillDraft { + name: String, + description: String, + body: String, + file: Option, + /// A built-in skill, shown read-only until copied. + builtin: bool, +} + +/// A layer offered for the @ being typed. +#[derive(Clone, Debug)] +pub struct MentionHit { + pub layer: LayerRef, + pub icon: icons::Icon, + /// What it is ("Component", "Page"…), shown beside its name. + pub kind: &'static str, +} + +/// What the selection is, for the suggestions above the composer. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SelKind { + #[default] + None, + Text, + Component, + Instance, + Frame, + Other, +} + +/// An image attached to the next request. +pub struct Attachment { + pub name: String, + pub image: figcraft_agent::neutral::Image, + thumb: Option, +} + +/// Another conversation kept for this document. +pub struct PastChat { + pub key: String, + pub title: String, + pub current: bool, +} + +/// At most this many images go with one request. +const MAX_IMAGES: usize = 6; +/// The longest side an attached image is scaled down to (what vision models read at full detail). +const IMAGE_SIDE: u32 = 1568; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ToolState { + Running, + Ok, + Failed, +} + +/// Something the panel asks the app to do after drawing (it needs the whole `FigApp`). +pub enum Action { + Send, + /// Send this text (a suggestion) as the request. + SendText(String), + Stop, + /// Undo, or redo, the canvas changes of the answer at this entry. + UndoChanges(usize), + RedoChanges(usize), + /// Select these layers and bring them into view. + ShowLayers(Vec), + NewChat, + OpenSettings, + CloseSettings, + FetchModels, + ToggleAuto, + CycleVariants, + Allow(usize), + Deny(usize), + /// Connect a subscription (an installed command-line agent). + ConnectCli(ApiKind), + /// Check the installed programs again. + RefreshCli, + /// Connect the API-key preset with this index, using the key typed on its card. + ConnectKey(usize), + /// Make the provider with this index the one requests go to. + Use(usize), + /// Choose this model on the active provider. + UseModel(String), + Remove(usize), + /// Select this layer on the canvas (a chip was clicked). + SelectLayer(u64), + /// Leave this selected layer out of the next request. + Exclude(u64), + /// Take a layer named with @ off the next request. + Unmention(u64), + /// Put the layer offered for the @ being typed into the request. + Mention(usize), + /// Rebuild the attached screenshot as editable layers. + Rebuild, + /// Attach the skill offered at this index for the `/` being typed. + PickSkill(usize), + /// Take an attached skill off the next request. + Unskill(String), + OpenSkills, + /// Turn the screenshot check after every answer that changed the canvas on or off. + ToggleReview, + + RemoveImage(usize), + PasteImage, + AttachRender, + CopyText(String), + /// Put the last request back in the composer. + EditLast, + /// Send the last request again. + Retry, + Unqueue(usize), + OpenChat(String), + DeleteChat(String), +} + +struct Approval { + reason: String, + name: String, + args: Value, + reply: Sender, +} + +/// A tool call's answer on its way back to the agent thread. +type ReplyForward = (Receiver, Sender>); + +/// A model list being fetched: the provider it belongs to and the thread's answer. +/// A model list being fetched: the connection's row, what identified it then (a row removed +/// meanwhile moves the others up), and the answer on its way. +type ModelFetch = (usize, String, Receiver, String>>); + +/// What identifies a connection for a model list: its kind, address and name. +fn fetch_identity(p: &Provider) -> String { + format!("{:?}|{}|{}", p.kind, p.base_url, p.name) +} + +/// A request as it was sent, so Try again sends it the same way (its images and the instructions +/// the person did not type included). +#[derive(Clone)] +pub(crate) struct SentRequest { + text: String, + hidden: String, + skills: Vec, + image_names: Vec, + images: Vec, +} + +/// An API-key connection being tried: the preset, and the provider with its model list once the +/// endpoint answered. +type KeyTrial = (usize, Receiver>); + +/// The installed command-line agents, as last checked. +type CliCheck = Receiver>; + +/// The prompts offered on an empty conversation. +const SUGGESTIONS: &[&str] = &[ + crate::i18n::tr_noop("Design a sign-in screen for a mobile app"), + crate::i18n::tr_noop("Make a pricing section with three plans"), + crate::i18n::tr_noop("Turn the selection into a component with variants"), + crate::i18n::tr_noop("Check the selection for spacing and contrast problems"), +]; + +/// The chat panel's state, kept on the window. +#[derive(Default)] +pub struct Chat { + /// `agents.json`'s contents and where it lives. + pub agents: AgentsFile, + path: Option, + loaded: bool, + /// The Connections screen is showing instead of the conversation. + pub settings_open: bool, + pub error: Option, + pub draft: String, + pub entries: Vec, + pub running: bool, + pub auto: bool, + pub usage: Usage, + /// The undo depth the turn started at. + turn_mark: Option, + /// The document as the turn found it, and as the last finished step left it: comparing + /// them with the document now tells which layers an answer, or a step, changed. + turn_doc: Option>, + step_doc: Option>, + /// The tool card that just finished, waiting for its changed layers. + last_ended: Option, + /// The document on screen and its undo and redo depth, read each frame for the answers' + /// Undo and Redo buttons. + history_now: Option<(u64, (usize, usize))>, + /// The turn's document as it is now, read with `history_now`. + doc_now: Option>, + /// The answer entry whose Undo or Redo ran last (or that just finished), and the document it + /// left: its buttons work only while the document is still that one. The undo depth alone + /// can come back to the same number after the person undid a step and made one of their own. + answer_doc: Option<(usize, Arc)>, + /// When the turn started and the tokens used before it, for the line under the answer. + turn_started: Option, + usage_before: Usage, + /// Layers named with @ in the composer, going with the next request beside the selection. + pub(crate) mentioned: Vec<(LayerRef, icons::Icon)>, + /// The @ being typed (its character index in the draft, and what follows it), the layers it + /// matches, and the one the arrow keys are on. + mention: Option<(usize, String)>, + pub(crate) mention_hits: Vec, + mention_pick: usize, + /// An @ the person closed with Escape: not offered again until they type another. + mention_closed: Option, + /// What kind of layers are selected, for the suggestions above the composer. + sel_kind: SelKind, + /// The design system summary last sent in this conversation (its hash): sent again only + /// when it changed. + design_sent: Option, + /// Instructions for the model that go with the next request without showing in its bubble. + hidden: Option, + /// The skills: built in and the person's own (`agent-skills/` beside `agents.json`). + pub(crate) skills: Vec, + skills_dir: Option, + /// The Skills screen is showing, and the skill being edited there. + pub skills_open: bool, + skill_edit: Option, + /// Skills attached to the next request with `/`, by name. + pub(crate) picked_skills: Vec, + /// The `/` being typed and the skills it matches (indices into `skills`). + slash: Option<(usize, String)>, + slash_hits: Vec, + /// The skill list last told to this conversation (its hash). + catalog_sent: Option, + + /// The page list last told to this conversation (its hash). + pages_sent: Option, + + /// The composer's id, to move its cursor after an @ is picked. + composer_id: Option, + /// The window and document the conversation works in, pinned when a request is sent: a turn + /// must not follow the person to another tab or window halfway through. + window: Option, + pub(crate) document: Option, + /// The conversation on screen belongs to this file (a slug of its path or name). + pub(crate) doc_key: Option, + /// Where the per-document chats are kept (`agent-chats/` beside `agents.json`). + pub(crate) chats_dir: Option, + worker: Option, + pub(crate) bridge: Option, + /// Calls waiting for their answer, to hand it back to the agent thread. + pending: Vec, + approvals: Vec, + /// Model lists being fetched, and the provider they belong to. + fetching: Option, + /// The API-key card that is open, and what is typed in it. + key_card: Option, + key_draft: String, + trial: Option, + /// The installed command-line agents, and a check on its way. + cli: Vec<(ApiKind, CliStatus)>, + cli_check: Option, + /// The Advanced settings of the active connection are open. + advanced: bool, + /// Give the composer the keyboard on the next frame (the tab was just opened). + focus_composer: bool, + /// Whether the composer had the keyboard on the last frame (a paste there may be an image). + composer_focused: bool, + /// The canvas selection as the composer's chips, with each layer's icon. + selection: Vec<(LayerRef, icons::Icon)>, + /// Selected layers the person took off the next request; forgotten when the selection changes. + excluded: Vec, + /// Images going with the next request. + pub images: Vec, + /// Requests typed while the agent was working, sent in turn when it finishes. + pub queue: Vec, + /// Queued requests of other conversations (by conversation key), kept until that conversation + /// is on screen again, with whether its last turn failed. + parked: std::collections::HashMap, bool)>, + /// The last turn ended in an error: queued requests wait for the person. + pub(crate) turn_failed: bool, + /// New chat was asked for while a turn was running: it opens once that turn is over. + pending_new_chat: bool, + /// The last request sent, for Try again. + last_sent: Option, + /// Try again: the request `send` repeats instead of reading the composer. + retry: Option, + /// Undo steps the agent's own calls added this turn (minus the ones they undid); anything + /// else that changed the undo history was the person's. + agent_steps: i64, + /// The document as the agent's last call left it. Another one in its place means the person + /// changed it in between, even where the undo depth came out the same (undo, then a new edit). + agent_doc: Option>, + /// The person changed the document between the agent's calls this turn. + mixed: bool, + /// The conversation on screen, when it is not the document's first one (`-