Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Packs and macros (#20): .sfpack files of brushes, alphas, Lit Spheres, Material Recipes, VDMs, keymaps, pie menus and macros, installed after a review; macros recorded, edited and run as one undo step
islandmed0e462d1e3f4a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a9c7210..29ef7a7c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,22 @@ All notable changes to SculptForge are listed here. The format follows## [Unreleased]### Added+- Packs and macros (#20): `.sfpack` files bring brushes, alphas, Lit Spheres, Material Recipes, VDMs, keymaps, pie+ menus and macros in one file (format: `docs/pack-format.md`). **File > Install Pack...**, a dropped file or+ **Library > Packs** shows a review first (counts by type, every item, the license text, the author; a Supporter+ Pack is marked by its `"channel": "insider"`, display only). Installed packs live in their own folders in the app+ data folder, can be switched off or removed, never replace built-in or user items (a clash gets the pack's name),+ and their items appear in the brush, alpha, Lit Sphere, Material Recipe, keymap, pie menu and macro lists tagged+ with the pack. **New Pack** exports your own items; `pack_install`, `pack_list`, `pack_remove`, `pack_enable`,+ `pack_disable` and `pack_create` work in `sculptforge-cli` and Python; `--no-packs` is a safe mode. Packs are data+ only and every one is treated as hostile: a strict zip reader refuses absolute paths, `..`, symbolic links,+ devices, encryption, ZIP64, overlapping entries and duplicate or Windows-reserved names, caps sizes, file counts+ and the unpacking ratio, accepts only the listed file types and parses every file (JSON strictly).+ Macros (`.sfmacro`): **Record Macro** keeps the commands you run, the **Macro Editor** checks the text as you type,+ and every macro is an action for F3, keys and pie menus; edits on one Part undo as one step. A macro+ shows its whole command list and asks before it first runs, only runs SculptForge's own commands (nothing that+ reaches the network or another program), and uses files only inside the project folder or picked when it runs+ (`macro_run`, `macro_list`, `macro_check`).- PBR viewport: **Material > Viewport Shading** switches between **Lit Sphere** (the default) and **PBR**, whichshows the texture's material channels as a game engine or renderer does: GGX reflections from a prefilteredenvironment, diffuse light from its spherical harmonics, multiple-scattering energy for rough metals, exposurediff --git a/CMakeLists.txt b/CMakeLists.txtindex eddf160a..a1722e3d 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -53,6 +53,8 @@ add_library(sculptforge_core STATICsrc/core/TransformCommands.cppsrc/core/Decimate.cppsrc/core/Script.cpp+ src/core/Macro.cpp+ src/core/Pack.cppsrc/core/Json.cppsrc/core/BrushRecipe.cppsrc/core/BrushLibrary.cpp@@ -291,6 +293,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/PanelBrushLibrary.cppsrc/app/PanelBrushGallery.cppsrc/app/PanelPolypaint.cpp+ src/app/PanelPacks.cppsrc/app/PanelPaintLayers.cppsrc/app/PanelTexture.cppsrc/app/PanelUvEditor.cppdiff --git a/docs/guide/index.md b/docs/guide/index.mdindex ddd4f188..ded3451a 100644--- a/docs/guide/index.md+++ b/docs/guide/index.md@@ -61,14 +61,15 @@ You can read it inside SculptForge (**Help > User Guide**, or <kbd>Shift</kbd>+<36. [Working with Maya](maya.md)37. [Projects, autosave and Snapshots](projects.md)38. [Scripting and automation](scripting.md)-39. [SculptForge for studios](studios.md)+39. [Packs and macros](packs-and-macros.md)+40. [SculptForge for studios](studios.md)## Reference-40. [Keyboard and mouse](shortcuts.md)-41. [Performance and big meshes](performance.md)-42. [Troubleshooting and FAQ](troubleshooting.md)-43. [Glossary](glossary.md)+41. [Keyboard and mouse](shortcuts.md)+42. [Performance and big meshes](performance.md)+43. [Troubleshooting and FAQ](troubleshooting.md)+44. [Glossary](glossary.md)## Getting helpdiff --git a/docs/guide/packs-and-macros.md b/docs/guide/packs-and-macros.mdnew file mode 100644index 00000000..7c8b829f--- /dev/null+++ b/docs/guide/packs-and-macros.md@@ -0,0 +1,141 @@+# Packs and macros++A **pack** is one file (`.sfpack`) that brings brushes, alphas, Lit Spheres, Material Recipes, VDM brushes,+keymaps, pie menus and macros at once. A **macro** is a list of SculptForge commands you can run with one click,+one key or one pie-menu slot. Both are plain data: SculptForge never runs code from a pack or a macro.++## Install a pack++Use **File > Install Pack...**, drop a `.sfpack` file on the window, or click **Install Pack...** in+**Library > Packs**. Nothing is installed yet: a review shows exactly what is inside first.++| The review shows | |+|---|---|+| **Name, version and author** | As the pack's maker wrote them. **Supporter Pack** marks the monthly pack for supporters. |+| **License** | The license name, and the license text from the pack on the right. |+| **Contains** | How many brushes, alphas, Lit Spheres, Material Recipes, VDMs, keymaps, pie menus and macros, with every item listed by name. |+| **Replaces the installed version** | When an older version of the same pack is installed. |++Click **Install** to add it, or **Cancel** to leave everything as it was. When a pack fails a check, the review+says which file and why (for example *"../evil.sfbrush" leaves its folder*), and nothing is installed.++Installed packs live in SculptForge's own data folder, each in its own folder. A pack never replaces a built-in+brush or one of your own: a pack brush called like an existing one shows the pack's name after its own, for+example **Clay (Supporter Pack)**.++## Where pack items show up++| Item | Where |+|---|---|+| Brushes and VDMs | The brush lists, the Brush picker and **Library > Brush**, tagged with the pack's name. |+| Alphas | The Alpha picker (a **Packs** section) and **Library > Alpha**, as **Name (Pack)**. |+| Lit Spheres | **Material** and **Library > Material**, as **Name (Pack)**. |+| Material Recipes | The **Material Recipe** list under **Tool > Paint Layers > Fill**, as **Name (Pack)**. |+| Keymaps | **Library > Packs > Details > Apply keymap**, and **Preferences > Input > Pack keymaps**. |+| Pie menus | **Library > Packs > Details > Add pie menu** (it becomes one of your radial menus). |+| Macros | <kbd>F3</kbd>, the key editor and the pie menus, as **Name (Pack)**. |++Keymaps and pie menus change how SculptForge responds, so they are only applied when you click **Apply keymap**+or **Add pie menu**. **Store Config** keeps the result.++## Library > Packs++Open the Library (<kbd>,</kbd>) and click **Packs**. Each installed pack has a row:++- The **check box** turns the pack off or on. Off, its items leave every list; nothing is deleted.+- **Details** shows its description, folder, keymaps, pie menus and macros.+- **Remove** deletes the pack and everything it brought. Your own files are never touched.++Start SculptForge with `--no-packs` to leave every pack out for one session (safe mode), for example to check+whether a problem comes from a pack. `sculptforge-cli --no-packs` does the same for scripts.++## Make a pack++**Library > Packs > New Pack...** lists what you made yourself: brushes in your library, images in your+Library's Alphas and MatCaps folders, the active Part's Fill layers as a Material Recipe, your VDMs, your pie+menus, your changed shortcuts (as a keymap) and your macros. Tick what goes in, fill in the name, author, license+and description, and click **Save Pack...**. The file is checked exactly as an install would check it before it+is written.++Tick **Supporter Pack (insider channel)** for a pack meant for supporters. It only changes the label shown in the+review and the pack list; anyone can install the file.++To build a pack from a folder in a script, lay the folder out like a pack (`brushes/`, `alphas/`, `matcaps/`,+`materials/`, `vdms/`, `keymaps/`, `piemenus/`, `macros/`, plus `LICENSE.txt` and `preview.png`) and run:++```+sculptforge-cli -c 'pack_create folder=MyPack path=MyPack.sfpack id=my-pack name="My Pack" author=Me license=CC-BY-4.0'+```++The file format is described in [the pack format](https://github.com/islandmed/SculptForge/blob/main/docs/pack-format.md).++## Record a macro++1. In **Library > Packs**, click **Record Macro**. A red **Recording macro** note shows at the top of the window.+2. Work as usual: every command you run from a menu, a button, the console or a script line is kept.+3. Click **Stop Recording**. The **Macro Editor** opens with the commands; give the macro a name and click **Save**.++Commands a macro may not run (see below) are left out, and the status line says how many. A file inside the+project folder is kept as a path relative to it; any other file becomes `?`, which asks for a file when the macro+runs.++## Write or change a macro++**Macro Editor** (in **Library > Packs**, or <kbd>F3</kbd>) is a plain text editor. A macro is the command+language of the console and `sculptforge-cli`, one command per line, `#` for comments:++```+# name: Clean Up Scan+# description: Remesh, smooth and export a GLB next to the project+remesh resolution=256+mask_clear+export_glb path=exports/clean.glb+```++The line under the text checks it as you type: every command must exist, be allowed in a macro and have the+values it needs. **Save** writes it to your macros folder; **Run** runs it.++## Run a macro++Every saved macro (yours and those of enabled packs) is an action:++- <kbd>F3</kbd>: type its name and press <kbd>Enter</kbd>.+- **Preferences > Hotkeys**: find it with the filter and give it a key, like any other action (see+ [Assign shortcuts](interface.md#assign-shortcuts)).+- **Preferences > Input > Radial Menus**: put it in a pie menu slot.+- **Library > Packs**: **Run** next to your macros, or in a pack's **Details**.++The first time a macro runs, SculptForge shows its whole command list and asks. Click **Run** to go on; you are+not asked again for that macro unless its text changes. A macro's edits on one Part are **one undo step**+(<kbd>Ctrl</kbd>+<kbd>Z</kbd> takes back the whole macro).++## What a macro can do++A macro only runs SculptForge's own commands, in order. It can't run programs or scripts, and it can't:++- reach the network (AI services, the brush gallery, Unreal, the phone link) or send to Blender, Maya or ZBrush;+- install, remove or switch packs, or run another macro;+- name a file outside the project folder. File values are either a path inside the folder of the saved project+ (`exports/clean.glb`) or `?`, which opens a file dialog when the macro runs. Absolute paths, `..`, `~` and drive+ letters are refused.++Save the project first when a macro uses relative paths: they are relative to the project's folder.++## Scripts and Python++The same rules apply outside the app:++| Command | What it does |+|---|---|+| `pack_install path=Pack.sfpack` | Checks and installs a pack (the app shows the review first). |+| `pack_list` | Lists the installed packs: id, name, version, author, license, contents, on or off. |+| `pack_remove id=my-pack` | Removes a pack. |+| `pack_enable id=...` / `pack_disable id=...` | Turns a pack on or off. |+| `pack_create folder=... path=...` | Makes a pack from a folder laid out like one. |+| `macro_run name=... ` or `path=...` | Runs a macro (`project=` sets the folder its relative paths use). |+| `macro_list` / `macro_check` | Lists the macros, or checks one without running it. |++In Python, `sculptforge.run(doc, "pack_install", path="Pack.sfpack")` and the other commands work the same way.+A command you type into `sculptforge-cli` or Python is your own explicit request, so it runs without the+confirmation the app shows. AI agents connected through `sculptforge-cli --mcp` can't install, remove or switch+packs.diff --git a/docs/guide/whats-new.md b/docs/guide/whats-new.mdindex 7e4c8b04..4ca51c92 100644--- a/docs/guide/whats-new.md+++ b/docs/guide/whats-new.md@@ -19,6 +19,12 @@ chapter opens by itself the first time you start a new version; you can always fchipped paint and dirt move with the form while you sculpt.- **Material Recipes**: Worn Metal, Painted Edges, Dirt and Dust and Rusted Iron in one click, and your own savedas small files.+- **Packs and macros** (**File > Install Pack...**, **Library > Packs**): install a `.sfpack` of brushes, alphas,+ Lit Spheres, Material Recipes, VDMs, keymaps, pie menus and macros after a review that shows exactly what's+ inside, its license and its author. Switch packs off, remove them, or make your own with **New Pack**. Record+ the commands you run as a **macro**, edit it as plain text, and run it from <kbd>F3</kbd>, a key or a pie menu as+ one undo step. Packs are data only and macros only run SculptForge's own commands; `--no-packs` starts without+ any pack. See [Packs and macros](packs-and-macros.md).- **More maps from Tool > Bake**: curvature, thickness, position and ID; bake a Part's top subdivision level (ormicro level) onto its lowest level without a second Part; UDIM tiles bake as one set of files per tile. See[Baking](baking.md).diff --git a/docs/pack-format.md b/docs/pack-format.mdnew file mode 100644index 00000000..56b95db8--- /dev/null+++ b/docs/pack-format.md@@ -0,0 +1,125 @@+# The SculptForge pack format (.sfpack)++A pack shares brushes, alphas, Lit Spheres, Material Recipes, VDM brushes, keymaps, pie menus and macros as one+file. It is **data only**: SculptForge never runs anything from a pack, nothing happens when it is installed or+when a project opens, and nothing in it reaches the network. Users install packs with **File > Install Pack...**+(a review shows what's inside first), `pack_install path=...` in `sculptforge-cli` or Python; see the user guide+chapter [Packs and macros](guide/packs-and-macros.md).++The reader is in `src/core/Pack.cpp`, the macro rules in `src/core/Macro.cpp`, and the tests that feed it+hostile archives in `tests/test_packs.cpp`.++## The archive++A `.sfpack` is a ZIP archive. Entries may be stored or deflated. The layout is fixed:++```+pack.json the manifest (required)+LICENSE.txt the license text (optional; LICENSE or LICENSE.md also work; at most one)+preview.png a preview image (optional; or preview.jpg; must be named in pack.json)+brushes/<name>.sfbrush brush recipes (core/BrushLibrary.h)+alphas/<name>.png|.jpg|.jpeg brush alphas+matcaps/<name>.png|.jpg|.jpeg Lit Sphere images+materials/<name>.sfmaterial Material Recipes (core/MaterialRecipe.h)+vdms/<name>.sfvdm vector displacement maps (core/Vdm.h)+keymaps/<name>.json keymaps (below)+piemenus/<name>.json pie menus, as Preferences > Input > Radial Menus exports them+macros/<name>.sfmacro macros (below)+```++Every file outside `pack.json`, the license and the preview must be listed in `pack.json`'s `contents`, directly+in its type's folder, with its type's extension. Anything else is refused.++## pack.json++```json+{+ "format": "sculptforge-pack",+ "formatVersion": 1,+ "id": "supporter-2026-11",+ "name": "Supporter Pack November 2026",+ "version": "1.0",+ "author": "The SculptForge developer",+ "license": "CC-BY-4.0",+ "description": "Twelve hard-surface brushes, four alphas and a clean-up macro.",+ "minAppVersion": "0.10.6",+ "preview": "preview.png",+ "channel": "insider",+ "contents": [+ {"type": "brush", "path": "brushes/Panel Line.sfbrush"},+ {"type": "alpha", "path": "alphas/Rivets.png"},+ {"type": "macro", "path": "macros/Clean Up.sfmacro"}+ ]+}+```++| Key | Required | Rules |+|---|---|---|+| `format` | yes | `"sculptforge-pack"` |+| `formatVersion` | yes | `1`. A newer number is refused (a newer SculptForge may read it). |+| `id` | yes | 1-64 characters: lower-case letters, digits, `.`, `_`, `-`; starts with a letter or digit; no `..`. The pack's folder name; a pack with the same id replaces the installed one. |+| `name` | yes | At most 64 bytes. Shown next to every item the pack brings. |+| `version` | yes | Starts with a digit; letters, digits, `.`, `-`, `+`; at most 32 bytes. |+| `author` | yes | At most 64 bytes. |+| `license` | yes | At most 64 bytes, for example `CC-BY-4.0` or `CC0-1.0`. |+| `description` | no | At most 1000 bytes; may hold line breaks. |+| `minAppVersion` | no | The oldest SculptForge that may install it; newer than the running app: refused. |+| `preview` | no | `preview.png` or `preview.jpg`, which must be in the archive. |+| `channel` | no | Lower-case letters, digits and `-`. `"insider"` marks a Supporter Pack. **Display only**: it changes a label, nothing else; there is no DRM and anyone can install the file. |+| `contents` | yes | A list of `{"type", "path"}`. Types: `brush`, `alpha`, `matcap`, `material`, `vdm`, `keymap`, `piemenu`, `macro`. |++Text values must be valid UTF-8 without control characters. The JSON is parsed strictly: a key given twice,+an unknown key, a number JSON doesn't allow or trailing text is an error.++## What every pack is checked for++Every pack is treated as hostile input. It is refused, with a message naming the file and the reason, when:++- **Paths**: a name is absolute, uses `\`, a drive letter or `:`, starts with `~`, has an empty, `.` or `..` part,+ a hidden part (`.x`), a part that starts or ends with a space or dot, a character Windows can't hold+ (`< > " | ? *`), a control character, invalid UTF-8, a NUL byte, a Windows device name (`CON`, `NUL`, `COM1`+ ...), more than one folder level, or more than 160 bytes.+- **Entries**: an entry is a symbolic link, a device or other special file, encrypted, compressed with anything+ but stored or deflate, spread over several disks or a ZIP64 entry; two entries share a name (ignoring case, as+ Windows and macOS do); two entries overlap in the file (a zip-bomb trick); the local header disagrees with the+ directory; the CRC doesn't match; or there is data after the archive's end.+- **Sizes**: the archive is over 128 MB, it holds over 1000 entries, one file unpacks to over 64 MB, all files+ together to over 256 MB, a file over 64 KB unpacks to more than 100 times its packed size (or the whole pack+ does), or a deflated stream unpacks to more than its stated size (it is decoded into a buffer of exactly that+ size).+- **Types**: a file isn't listed in `pack.json`, isn't in its type's folder or has the wrong extension, or a+ listed file is missing.+- **Contents**: each file is parsed as what it claims to be. Brushes, Material Recipes, keymaps and pie menus are+ strict JSON within their size caps; images are PNG or JPEG whose bytes match the extension, at most 4096 pixels+ a side (the preview 2048), and must decode; VDMs must have the `.sfvdm` header and exactly the size it states;+ the license is plain text up to 64 KB; macros pass the macro rules below.++Installing unpacks into a fresh staging folder inside `<app data>/packs/`, checks every destination again, then+swaps it in, so a failed install leaves the previous version as it was. Packs never write anywhere else and+never overwrite built-in or user files.++## Keymaps++```json+{"format": "sculptforge-keymap", "version": 1, "name": "Hard Surface Keys",+ "shortcuts": {"brush.clay": "C", "mask.invert": "Ctrl+Shift+K"}}+```++At most 512 shortcuts. Keys are action ids (as **Preferences > Hotkeys** lists them) and key chords. They are only+applied when the user clicks **Apply keymap**; unknown actions and chords are left out.++## Macros (.sfmacro)++Plain text in the command language of `sculptforge-cli` (`docs/guide/scripting.md`): one command per line, `#`+comments, optional `# name:` and `# description:` header lines. At most 64 KB and 500 commands.++- Only SculptForge's own commands, and not those that reach the network or another program (AI services, the+ brush gallery, Unreal, Blender, Maya and ZBrush exchange, splat training), install, list or remove packs, or run+ macros. Parameters naming URLs, endpoints, services or programs are refused.+- File values (`path=`, `folder=`, `file=`, `out=`, `exr=` ...) are either a path relative to the project folder,+ without `..`, `~`, `$`, `%`, drive letters or a leading slash (resolved, symbolic links followed, and checked to+ stay inside the folder), or `?`, which asks for a file in a dialog when the macro runs. `preset=` may only name a+ built-in preset.+- In the app, a macro shows its whole command list and asks before it first runs, and again after its text+ changes (confirmations are kept by SHA-256 of the text). `sculptforge-cli` and Python run what the user asked.+ AI agents on `sculptforge-cli --mcp` can't install, remove or switch packs.diff --git a/src/app/Actions.cpp b/src/app/Actions.cppindex dae90a0a..f96a1f15 100644--- a/src/app/Actions.cpp+++ b/src/app/Actions.cpp@@ -213,6 +213,11 @@ void ActionRegistry::add(Action a) {actions_.push_back(std::move(a));}+void ActionRegistry::removePrefix(std::string_view prefix) {+ ++revision_;+ std::erase_if(actions_, [&](const Action& a) { return std::string_view(a.id).substr(0, prefix.size()) == prefix; });+}+const Action* ActionRegistry::find(std::string_view id) const {for (const auto& a : actions_)if (a.id == id) return &a;diff --git a/src/app/Actions.h b/src/app/Actions.hindex a3bfd69a..26c59e97 100644--- a/src/app/Actions.h+++ b/src/app/Actions.h@@ -51,6 +51,7 @@ std::vector<std::string> chordKeys(std::string_view chord);class ActionRegistry {public:void add(Action a); // replaces by id+ void removePrefix(std::string_view prefix); // every action whose id starts with PREFIX (macros that went away)const Action* find(std::string_view id) const;const std::vector<Action>& all() const { return actions_; }// Runs the action bound to this chord; true if consumed. Callers skip it while ImGui wants the keyboard.diff --git a/src/app/App.cpp b/src/app/App.cppindex 7af9bb5b..7dbf76bd 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -1762,6 +1762,27 @@ void App::endStroke() {// ---------------------------------------------------------------------------void App::runCommand(const std::string& name, const Args& args) {+ // In the app a macro asks before it first runs and a pack is reviewed before it's installed (PanelPacks.cpp),+ // whether they come from a button, a key, the console or a script.+ if (name == "macro_run" && macros_.runDepth == 0) {+ Macro m;+ std::string err;+ const std::string path = argString(args, "path");+ if (!(path.empty() ? findMacro(argString(args, "name"), &commands_, m, err)+ : readMacroFile(path, &commands_, m, err))) {+ status_ = err;+ lastCommandOk_ = false;+ return;+ }+ lastCommandOk_ = true;+ requestMacroRun(m);+ return;+ }+ if (name == "pack_install") {+ reviewPackFile(argString(args, "path"));+ lastCommandOk_ = packs_.review != nullptr;+ return;+ }if (doc_.sculptor.strokeActive()) endStroke();if (name == "save_project") storeProjectSettings();flushBrushEdits(); // commands may replace brushes: save edits first, then watch what's there afterwards@@ -1797,6 +1818,10 @@ void App::runCommand(const std::string& name, const Args& args) {updateTitle();// The console shows every command as a script line (but not a live face feed, 30 times a second).if (name != "face_weights" || !r.ok) consoleEcho(name, args, r);+ if (r.ok && (name == "pack_remove" || name == "pack_enable" || name == "pack_disable")) refreshPacks();+ // Macro > Record keeps what the user runs (not what a running macro runs).+ if (r.ok && macros_.recorder.active() && macros_.runDepth == 0 && name != "face_weights")+ macros_.recorder.record(name, args, macroProjectDir());}namespace {@@ -1848,6 +1873,8 @@ void App::openPath(const std::string& path) {if (loadReferenceImage(path)) showImageTo3D_ = true;} else if (ext == ".sfbrush") {installBrushFile(path);+ } else if (ext == kPackExtension) { // a pack: the review screen first, nothing is installed yet+ reviewPackFile(path);} else if (ext == ".exr" || ext == ".sfvdm") { // a vector displacement map for the VDM brushrunCommand("vdm_set", {{"path", path}, {"swap_yz", vdmImport_.swapYZ}, {"flip_x", vdmImport_.flipX},{"flip_y", vdmImport_.flipY}, {"flip_z", vdmImport_.flipZ}, {"scale", double(vdmImport_.scale)}});@@ -1896,6 +1923,7 @@ AABB App::sceneBounds() const {}void App::processPendingFiles() {+ pollPackDialogs(); // Install Pack, New Pack's save and a macro's "?" files (PanelPacks.cpp)std::vector<PendingFile> files;{std::lock_guard lock(pendingMutex_);@@ -2118,6 +2146,7 @@ void App::drawUi() {}drawSupportUi(); // the first-run welcome, the one support reminder (PanelSupport.cpp)guide_.draw(*this); // Help > User Guide+ drawPacksUi(); // pack review, New Pack, macro confirmation and editor (PanelPacks.cpp)drawHelpConsoleUi(); // console, command palette, Controls (F1), Ctrl-hover help: last, on topdrawSupportCard(); // the support card at launch, over everything (PanelSupportCard.cpp)}diff --git a/src/app/App.h b/src/app/App.hindex 846ef205..2e032b51 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -21,6 +21,8 @@#include "ai/ImageTo3DService.h"#include "core/Commands.h"#include "core/Image.h"+#include "core/Macro.h"+#include "core/Pack.h"#include "core/Document.h"#include "core/Face.h"#include "core/MeshTransform.h"@@ -1478,6 +1480,89 @@ private:bool untilLeave = false; // Space let go over the menu: it closes when the pointer leaves itint openedFrame = -1;} quickMenu_;+ // ---- Packs and macros (PanelPacks.cpp, core/Pack.h, core/Macro.h, #20) ----+ // Library > Packs: install (a review screen first: what's inside, the license, the author), list, switch on and+ // off, remove, and New Pack. Pack items join the brush, alpha, Lit Sphere, Material Recipe, keymap, pie menu and+ // macro lists tagged with the pack's name. Macros: Record (the commands run between Start and Stop), the+ // editor (plain text, checked as you type), and one action per macro ("macro.<pack or user>.<name>") for F3, keys+ // and pie menus. A macro shows its whole command list and asks before it first runs (again after it changed).+public:+ void drawPacksTab(float height); // Library > Packs (LightBox.cpp)+ double packsTestValue(const std::string& name) const; // NaN: not a pack value (UiTest.cpp)+ void packDialogAnswered(std::string path); // thread-safe: a pack or macro file dialog's answer+ void reviewPackFile(const std::string& path); // File > Install Pack, a dropped .sfpack: the review screen+ const std::vector<PackContentItem>& packAlphas() const { return packs_.alphas; }+ const std::vector<PackContentItem>& packMaterials() const { return packs_.materials; }++private:+ void registerPackActions();+ void refreshPacks(); // after an install, removal or switch: brushes, VDMs, Lit Spheres, recipes, macros+ void refreshMacroActions(); // one action per macro+ void loadPackMatcaps();+ void drawPacksUi(); // the review screen, New Pack, the macro confirmation and the macro editor+ void drawPackReview();+ void drawNewPack();+ void drawMacroConfirm();+ void drawMacroEditor();+ void drawPackKeymapRows(); // Preferences > Input: the enabled packs' keymaps+ void pollPackDialogs();+ void openPackDialog(int kind, int pathKind = 0); // PackDialog, MacroPathKind+ void requestMacroRun(const Macro& m); // asks first unless this exact text was confirmed+ void startMacroRun(Macro m); // asks for "?" files, then runs+ void runMacroNow();+ void toggleMacroRecording();+ void openMacroEditor(const std::string& name, const std::string& text, const std::string& path);+ bool applyPackKeymap(const std::string& file);+ void openNewPack();+ void writeNewPack(const std::string& path);+ std::string macroProjectDir() const; // the saved project's folder ("" when the scene isn't a saved project)+ enum PackDialog { kPackDialogNone, kPackDialogInstall, kPackDialogSave, kPackDialogMacro };+ struct NewPackItem {+ PackItemType type = PackItemType::Brush;+ std::string label, file, name; // name: the file name in the pack+ std::vector<uint8_t> data; // made in memory (pie menus, the keymap, the current Fill layers)+ bool on = false;+ };+ struct PacksUi {+ std::vector<InstalledPack> installed;+ std::vector<PackContentItem> alphas, materials, keymaps, pieMenus;+ std::vector<int> matcaps; // Lit Sphere indices the packs added (removed again on a refresh)+ std::unique_ptr<PackReview> review;+ std::string reviewError, reviewPath;+ bool reviewOpen = false;+ std::string expanded; // the pack id whose details show+ bool newOpen = false;+ char id[65] = "", name[65] = "", version[33] = "1.0", author[65] = "", license[65] = "CC-BY-4.0";+ char description[1001] = "";+ bool insider = false;+ std::vector<NewPackItem> candidates;+ std::string newError;+ std::mutex mutex; // the dialog answer arrives on another thread+ std::string answer;+ bool answered = false, answerCancelled = false;+ int dialog = kPackDialogNone; // what the open dialog is for+ } packs_;+ struct MacrosUi {+ MacroRecorder recorder;+ int runDepth = 0; // > 0 while a macro runs: its commands aren't recorded or intercepted+ std::vector<Macro> list; // the user's and the packs' (refreshMacroActions)+ bool confirmOpen = false;+ Macro confirm;+ bool editorOpen = false;+ char name[97] = "";+ std::vector<char> text = std::vector<char>(kMaxMacroFileSize + 1, '\0');+ std::string path; // the file the editor saves to ("" = new)+ std::string check; // the editor's validation line+ bool checkOk = false;+ std::string checkedText = "\x01";+ Macro running; // waiting for its "?" files+ std::vector<MacroAsk> asks;+ std::vector<std::string> answers;+ bool waiting = false;+ int ran = -1; // commands the last run ran (UI tests)+ bool lastOk = false, lastOneStep = false;+ } macros_;+ // ---- end Packs and macros ----// ---- Radial menus (RadialMenu.cpp, core/RadialMenu.h, #45) ----// Up to eight pie menus of up to eight actions each. A menu's key (action radial.menuN, set in the keymap like// any other) or its mouse / pen button, held: the pie shows at the cursor, a flick toward a slot and letting godiff --git a/src/app/AssetLibrary.cpp b/src/app/AssetLibrary.cppindex 0472415b..75eba2df 100644--- a/src/app/AssetLibrary.cpp+++ b/src/app/AssetLibrary.cpp@@ -61,14 +61,14 @@ const char* primitiveName(Primitive p) {}const char* libraryTabName(LibraryTab tab) {- static const char* const names[] = {"Project", "Tool", "Brush", "Alpha", "Material",- "Image", "Splats", "Snapshots", "Recent"};+ static const char* const names[] = {"Project", "Tool", "Brush", "Alpha", "Material",+ "Image", "Splats", "Snapshots", "Recent", "Packs"};return tab < LibraryTab::Count ? names[int(tab)] : "";}const char* libraryTabId(LibraryTab tab) {- static const char* const ids[] = {"project", "tool", "brush", "alpha", "material",- "image", "splats", "quicksave", "recent"};+ static const char* const ids[] = {"project", "tool", "brush", "alpha", "material",+ "image", "splats", "quicksave", "recent", "packs"};return tab < LibraryTab::Count ? ids[int(tab)] : "project";}diff --git a/src/app/AssetLibrary.h b/src/app/AssetLibrary.hindex 514f489d..ee2e014a 100644--- a/src/app/AssetLibrary.h+++ b/src/app/AssetLibrary.h@@ -48,7 +48,7 @@ struct AssetEntry {};// The LightBox tabs, in the order they are shown.-enum class LibraryTab { Project, Tool, Brush, Alpha, Material, Image, Splats, QuickSave, Recent, Count };+enum class LibraryTab { Project, Tool, Brush, Alpha, Material, Image, Splats, QuickSave, Recent, Packs, Count };const char* libraryTabName(LibraryTab tab); // "Project"const char* libraryTabId(LibraryTab tab); // "project" (UiLayout::lightboxTab)LibraryTab libraryTabFromId(std::string_view id); // unknown -> Projectdiff --git a/src/app/Config.cpp b/src/app/Config.cppindex 4b85bce2..ad01bc19 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -548,6 +548,7 @@ void App::initActions() {actions_.registerCommands(commands_, [this](const std::string& name) { runCommand(name); },[this](const std::string& name) { consolePrefill(name + " "); });+ registerPackActions(); // Install Pack, New Pack, Record Macro, the editor, one action per macro (PanelPacks.cpp)registerRadialActions(); // last: a radial menu's items may be any of the above (RadialMenu.cpp)if (!uiConfigDeterministic_ && !configDir_.empty()) {diff --git a/src/app/Input.cpp b/src/app/Input.cppindex 3929ea0e..85e81d4d 100644--- a/src/app/Input.cpp+++ b/src/app/Input.cpp@@ -451,6 +451,7 @@ void App::drawInputSection() {uiPrefs_.cursorFollowsSurface = surfaceCursor;ui::HelpAction(*this, "input.surface_cursor");ui::ActionButton(*this, "input.import_blender", ImVec2(-FLT_MIN, 0), ui::Look::IconLabel);+ drawPackKeymapRows(); // keymaps from installed packs (PanelPacks.cpp)ImGui::TextDisabled("%s", tr("Rotation"));ImGui::SameLine();int rotation = uiPrefs_.turntable ? 1 : 0;diff --git a/src/app/LightBox.cpp b/src/app/LightBox.cppindex 49508e7d..34cf03b0 100644--- a/src/app/LightBox.cpp+++ b/src/app/LightBox.cpp@@ -249,6 +249,13 @@ void LightBox::rootEntries(App& app, std::vector<AssetEntry>& out) {}const auto files = scan(userDir, false);out.insert(out.end(), files.begin(), files.end());+ for (const PackContentItem& it : app.packAlphas()) { // the enabled packs' alphas, tagged with the pack+ AssetEntry e;+ e.kind = AssetKind::AlphaFile;+ e.name = it.label();+ e.path = it.file;+ out.push_back(std::move(e));+ }break;}case LibraryTab::Material:@@ -589,6 +596,7 @@ void LightBox::drawHeader(App& app, float width) {"Gaussian splat captures (.ply, .splat) to sculpt against.","Snapshots and the autosave, newest first.","Recently opened files of every kind.",+ "Installed packs (.sfpack): switch them on or off, remove them, make your own. Also macros: record, edit, run.",};ui::HelpText(libraryTabName(tab), nullptr, tips[i], "Library");ImGui::SameLine(0, 0);@@ -755,6 +763,11 @@ void LightBox::draw(App& app, const CanvasRect& canvas) {ImGui::SetCursorPosY(std::round((kHeader * scale - ImGui::GetFrameHeight()) * 0.5f));drawHeader(app, ws.x - 16.0f * scale);+ if (place_.tab == LibraryTab::Packs) { // a list, not tiles (PanelPacks.cpp)+ app.drawPacksTab(float(rows) * (kTile + kLabel + 4.0f) * scale + 8.0f * scale);+ ImGui::End();+ return;+ }const std::vector<AssetEntry> items = entries(app);const float tile = kTile * scale, rowH = (kTile + kLabel + 4.0f) * scale, gap = kGap * scale;diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 9ad74609..34c4e000 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -366,6 +366,7 @@ void App::drawPalette_File() {menuAction(*this, "file.export_fbx");menuAction(*this, "file.send_unreal");menuAction(*this, "file.save_splats");+ menuAction(*this, "pack.install"); // a review screen first (PanelPacks.cpp)ImGui::Separator();drawGozMenu();drawBlenderMenu(); // the Blender bridge (PanelBlender.cpp)diff --git a/src/app/PanelBrushLibrary.cpp b/src/app/PanelBrushLibrary.cppindex 5f953eae..e06bed7d 100644--- a/src/app/PanelBrushLibrary.cpp+++ b/src/app/PanelBrushLibrary.cpp@@ -35,6 +35,7 @@ std::string utf8(const fs::path& p) {const char* brushTag(const BrushRecipe& b) {switch (b.origin.source) {case BrushSource::Studio: return "studio";+ case BrushSource::Pack: return b.origin.pack.c_str(); // the pack's namecase BrushSource::Gallery: return "gallery";case BrushSource::Project: return "project";case BrushSource::Session: return "unsaved";@@ -82,6 +83,7 @@ std::string brushOriginText(const BrushRecipe& b) {: "In your brush library";case BrushSource::Gallery: return "From the community gallery, in your brush library";case BrushSource::Studio: return "Studio brush (shared folder, read-only)";+ case BrushSource::Pack: return "From the pack " + b.origin.pack + " (read-only; Library > Packs)";case BrushSource::Project: return "From the open project, not in your brush library";case BrushSource::Session: return "Not saved - refine it in Brush Lab to keep it";}@@ -93,12 +95,19 @@ void App::initBrushLibrary() {if (!options_.uiTest.empty()) {// UI tests get an empty library of their own, never the artist's.const fs::path base = options_.uiOutDir.empty() ? fs::temp_directory_path() / "sculptforge-ui-test" : fsPath(options_.uiOutDir);- paths = {utf8(base / "brush-library"), {}};+ paths = {utf8(base / "brush-library"), {}, {}};std::error_code ec;fs::remove_all(fsPath(paths.userDir), ec);+ // ... and no packs or macros but their own (core/Pack.h, core/Macro.h).+ setPacksRoot(utf8(base / "packs"));+ setUserMacroDir(utf8(base / "macros"));+ fs::remove_all(base / "packs", ec);+ fs::remove_all(base / "macros", ec);} else if (!options_.recordPath.empty() || !options_.renderPath.empty()) {paths = {}; // demo videos and renders: built-in brushes only, nothing saved+ setPacksSafeMode(true);}+ applyPacksToBrushLibrary(paths); // the enabled packs' brushes and VDMs (none in safe mode)const auto messages = loadBrushLibrary(doc_, paths);for (const auto& m : messages) SDL_Log("Brush library: %s", m.c_str());if (!messages.empty())diff --git a/src/app/PanelFill.cpp b/src/app/PanelFill.cppindex 06e178da..475c5fb5 100644--- a/src/app/PanelFill.cpp+++ b/src/app/PanelFill.cpp@@ -170,6 +170,9 @@ void App::drawFillLayerControls() {if (ImGui::Selectable((r.name + "##recipe").c_str())) runCommand("material_recipe", {{"name", r.id}});if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", r.description.c_str());}+ for (const PackContentItem& it : packMaterials()) // from installed packs, tagged with the pack's name+ if (ImGui::Selectable((it.label() + "##recipe" + it.file).c_str()))+ runCommand("material_recipe", {{"path", it.file}});ImGui::EndCombo();}ui::HelpText("Material Recipe", nullptr,diff --git a/src/app/PanelPacks.cpp b/src/app/PanelPacks.cppnew file mode 100644index 00000000..5f64cb02--- /dev/null+++ b/src/app/PanelPacks.cpp@@ -0,0 +1,931 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Library > Packs and macros (#20): installing a pack after a review screen, the installed packs (on / off,+// remove, their keymaps, pie menus and macros), New Pack, recording and editing macros, the confirmation a macro+// shows before it first runs, and its file dialogs. The checks themselves are in core/Pack.cpp and core/Macro.cpp.+#include "app/App.h"++#include "app/I18n.h"+#include "app/Ui.h"+#include "core/BrushLibrary.h"+#include "core/Matcap.h"+#include "core/MaterialRecipe.h"+#include "core/Project.h"+#include "core/Texture.h"+#include "core/Vdm.h"++#include <IconsLucide.h>++#include <algorithm>+#include <cctype>+#include <cmath>+#include <cstring>+#include <filesystem>+#include <fstream>++namespace sf {++namespace {++namespace fs = std::filesystem;++fs::path fsPath(const std::string& p) { return fs::path(std::u8string(p.begin(), p.end())); }+std::string utf8(const fs::path& p) {+ const std::u8string s = p.u8string();+ return std::string(s.begin(), s.end());+}+std::string lowerText(std::string s) {+ for (char& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));+ return s;+}+// "Clean Up Scan" -> "clean_up_scan": a stable piece of an action id.+std::string slug(const std::string& s) {+ std::string out;+ for (unsigned char c : s) {+ if (std::isalnum(c)) out += char(std::tolower(c));+ else if (!out.empty() && out.back() != '_') out += '_';+ }+ while (!out.empty() && out.back() == '_') out.pop_back();+ return out.empty() ? "macro" : out.substr(0, 48);+}++constexpr ImU32 kAccent = IM_COL32(240, 136, 46, 255);+constexpr ImU32 kInsider = IM_COL32(236, 190, 90, 255);++void SDLCALL onPackDialog(void* userdata, const char* const* files, int) {+ wakeMainLoop();+ auto* app = static_cast<App*>(userdata);+ if (!files) app->packDialogAnswered(""); // an error+ else app->packDialogAnswered(files[0] ? files[0] : "");+}++void centerNextWindow(float w, float h) {+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x + vp->WorkSize.x * 0.5f, vp->WorkPos.y + vp->WorkSize.y * 0.5f),+ ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));+ ImGui::SetNextWindowSize(ImVec2(std::min(w, vp->WorkSize.x - 40.0f), std::min(h, vp->WorkSize.y - 40.0f)),+ ImGuiCond_Appearing);+}++std::vector<std::string> filesIn(const std::string& dir, const std::function<bool(const std::string&)>& keep) {+ std::vector<std::string> out;+ if (dir.empty()) return out;+ std::error_code ec;+ for (fs::directory_iterator it(fsPath(dir), ec), end; !ec && it != end; it.increment(ec)) {+ std::error_code e2;+ if (!it->is_symlink(e2) && it->is_regular_file(e2) && keep(utf8(it->path().filename())))+ out.push_back(utf8(it->path()));+ }+ std::sort(out.begin(), out.end());+ return out;+}++} // namespace++// ---------------------------------------------------------------------------+// Actions and refreshing+// ---------------------------------------------------------------------------++void App::registerPackActions() {+ auto add = [this](const char* id, const char* label, const char* icon, const char* palette, const char* description,+ std::function<void()> run, std::function<bool()> checked = nullptr) {+ Action a;+ a.id = id;+ a.label = label;+ a.icon = icon;+ a.palette = palette;+ a.description = description;+ a.run = std::move(run);+ a.checked = std::move(checked);+ actions_.add(std::move(a));+ };+ add("pack.install", "Install Pack...", ICON_LC_PACKAGE_PLUS, "File",+ "Install a SculptForge pack (.sfpack): brushes, alphas, Lit Spheres, Material Recipes, VDMs, keymaps, pie "+ "menus and macros. A review shows exactly what's inside, its license and its author before anything is "+ "installed. Packs hold data only: nothing in one ever runs.",+ [this] { openPackDialog(kPackDialogInstall); });+ add("pack.new", "New Pack...", ICON_LC_PACKAGE, "Library > Packs",+ "Make a pack from your own brushes, alphas, Lit Spheres, Material Recipe, VDMs, pie menus, shortcuts and "+ "macros, to share as one .sfpack file.",+ [this] { openNewPack(); });+ add("pack.library", "Packs", ICON_LC_PACKAGE, "Library",+ "Library > Packs: the installed packs. Switch one off or remove it, apply its keymap, add its pie menus.",+ [this] { lightbox_.show(LibraryTab::Packs); });+ add("macro.record", "Record Macro", ICON_LC_CIRCLE_DOT, "Library > Packs",+ "Start recording: the commands you run (menus, buttons, the console) are kept as a macro until you press it "+ "again. Files inside the project folder are kept as relative paths, any other file is asked for when the "+ "macro runs.",+ [this] { toggleMacroRecording(); }, [this] { return macros_.recorder.active(); });+ add("macro.editor", "Macro Editor", ICON_LC_SQUARE_CODE, "Library > Packs",+ "Write or change a macro: SculptForge commands, one per line, checked as you type. Only SculptForge's own "+ "commands, nothing that reaches the network, and files only inside the project folder or picked when it runs.",+ [this] { openMacroEditor("My Macro", "", ""); });+ packs_.installed = listInstalledPacks();+ packs_.alphas = enabledPackItems(PackItemType::Alpha);+ packs_.materials = enabledPackItems(PackItemType::Material);+ packs_.keymaps = enabledPackItems(PackItemType::Keymap);+ packs_.pieMenus = enabledPackItems(PackItemType::PieMenu);+ loadPackMatcaps();+ refreshMacroActions();+}++void App::refreshMacroActions() {+ actions_.removePrefix("macro.run.");+ std::vector<std::string> messages;+ macros_.list = listMacros(&commands_, &messages);+ for (const std::string& m : messages) SDL_Log("Macros: %s", m.c_str());+ for (const Macro& m : macros_.list) {+ Action a;+ a.id = "macro.run." + (m.pack.empty() ? std::string("my") : slug(m.pack)) + "." + slug(m.name);+ a.label = m.pack.empty() ? m.name : m.name + " (" + m.pack + ")";+ a.icon = ICON_LC_LIST_VIDEO;+ a.palette = "Macros";+ std::string first;+ for (size_t i = 0; i < m.statements.size() && i < 3; ++i)+ first += (i ? "; " : "") + formatStatement(m.statements[i].command, m.statements[i].args);+ a.description = (m.description.empty() ? std::string("Macro") : m.description) + " - " ++ std::to_string(m.statements.size()) + " commands: " + first ++ (m.statements.size() > 3 ? "; ..." : "");+ a.run = [this, m] { requestMacroRun(m); };+ actions_.add(std::move(a));+ }+}++void App::loadPackMatcaps() {+ for (int i : packs_.matcaps) removeCustomMatcap(i);+ packs_.matcaps.clear();+ for (const PackContentItem& item : enabledPackItems(PackItemType::Matcap)) {+ CustomMatcap m;+ std::string err;+ if (!readMatcapImage(item.file, m, err)) {+ SDL_Log("Lit Spheres: %s (pack %s): %s", item.file.c_str(), item.packName.c_str(), err.c_str());+ continue;+ }+ m.name = item.label(); // "Chrome (Supporter Pack)": never mistaken for (or replacing) another+ packs_.matcaps.push_back(addCustomMatcap(std::move(m)));+ }+}++void App::refreshPacks() {+ packs_.installed = listInstalledPacks();+ applyPacksToBrushLibrary(brushLibraryPaths());+ for (const auto& m : loadBrushLibrary(doc_)) SDL_Log("Brush library: %s", m.c_str());+ watchActiveBrush();+ packs_.alphas = enabledPackItems(PackItemType::Alpha);+ packs_.materials = enabledPackItems(PackItemType::Material);+ packs_.keymaps = enabledPackItems(PackItemType::Keymap);+ packs_.pieMenus = enabledPackItems(PackItemType::PieMenu);+ loadPackMatcaps();+ refreshMacroActions();+}++std::string App::macroProjectDir() const {+ if (doc_.path.empty() || !isProjectPath(doc_.path)) return "";+ return utf8(fsPath(doc_.path).parent_path());+}++// ---------------------------------------------------------------------------+// File dialogs (answered on another thread; UI tests answer with answer_dialog)+// ---------------------------------------------------------------------------++void App::openPackDialog(int kind, int pathKind) {+ {+ std::lock_guard lock(packs_.mutex);+ packs_.dialog = kind;+ packs_.answered = false;+ }+ if (!options_.uiTest.empty()) return; // the script answers (answer_dialog)+ static const SDL_DialogFileFilter kPackFilters[] = {{"SculptForge packs", "sfpack"}, {"All files", "*"}};+ static const SDL_DialogFileFilter kAll[] = {{"All files", "*"}};+ const std::string project = macroProjectDir();+ const char* where = project.empty() ? nullptr : project.c_str();+ switch (kind) {+ case kPackDialogInstall: SDL_ShowOpenFileDialog(onPackDialog, this, window_, kPackFilters, 2, nullptr, false); break;+ case kPackDialogSave: {+ const std::string name = std::string(packs_.name[0] ? packs_.name : "My Pack") + kPackExtension;+ SDL_ShowSaveFileDialog(onPackDialog, this, window_, kPackFilters, 2, name.c_str());+ break;+ }+ case kPackDialogMacro:+ if (pathKind == int(MacroPathKind::Folder)) SDL_ShowOpenFolderDialog(onPackDialog, this, window_, where, false);+ else if (pathKind == int(MacroPathKind::Save)) SDL_ShowSaveFileDialog(onPackDialog, this, window_, kAll, 1, where);+ else SDL_ShowOpenFileDialog(onPackDialog, this, window_, kAll, 1, where, false);+ break;+ default: break;+ }+}++void App::packDialogAnswered(std::string path) {+ std::lock_guard lock(packs_.mutex);+ packs_.answer = std::move(path);+ packs_.answerCancelled = packs_.answer.empty();+ packs_.answered = true;+}++void App::pollPackDialogs() {+ std::string answer;+ int kind;+ {+ std::lock_guard lock(packs_.mutex);+ if (!packs_.answered) return;+ packs_.answered = false;+ answer = std::move(packs_.answer);+ kind = packs_.dialog;+ packs_.dialog = kPackDialogNone;+ }+ switch (kind) {+ case kPackDialogInstall:+ if (!answer.empty()) reviewPackFile(answer);+ break;+ case kPackDialogSave:+ if (!answer.empty()) {+ if (fsPath(answer).extension().empty()) answer += kPackExtension;+ writeNewPack(answer);+ }+ break;+ case kPackDialogMacro:+ if (!macros_.waiting) break;+ if (answer.empty()) {+ macros_.waiting = false;+ status_ = "Macro " + macros_.running.name + " stopped: no file picked";+ break;+ }+ macros_.answers.push_back(answer);+ if (macros_.answers.size() < macros_.asks.size())+ openPackDialog(kPackDialogMacro, int(macros_.asks[macros_.answers.size()].kind));+ else runMacroNow();+ break;+ default: break;+ }+}++// ---------------------------------------------------------------------------+// Install review+// ---------------------------------------------------------------------------++void App::reviewPackFile(const std::string& path) {+ packs_.review = std::make_unique<PackReview>();+ packs_.reviewPath = path;+ packs_.reviewError.clear();+ std::string err;+ if (!reviewPack(path, *packs_.review, err, &commands_)) {+ packs_.review.reset();+ packs_.reviewError = err;+ status_ = "Pack refused: " + err;+ SDL_Log("Pack %s refused: %s", path.c_str(), err.c_str());+ }+ packs_.reviewOpen = true;+}++void App::drawPackReview() {+ if (!packs_.reviewOpen) return;+ const float s = uiScale_;+ centerNextWindow(560 * s, 520 * s);+ bool open = true;+ if (!ImGui::Begin(tr("Install Pack"), &open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings)) {+ ImGui::End();+ packs_.reviewOpen = open;+ return;+ }+ PackReview* r = packs_.review.get();+ bool close = !open;+ if (!r) {+ ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(240, 110, 100, 255));+ ImGui::TextUnformatted(tr("This pack can't be installed"));+ ImGui::PopStyleColor();+ ImGui::TextDisabled("%s", utf8(fsPath(packs_.reviewPath).filename()).c_str());+ ImGui::Spacing();+ ImGui::TextWrapped("%s", packs_.reviewError.c_str());+ ImGui::Spacing();+ ImGui::TextWrapped("%s", tr("Nothing was installed. SculptForge only installs packs that pass every check: "+ "plain data files of the kinds a pack may hold, listed in its pack.json, within "+ "safe sizes, with nothing that could leave the pack's folder."));+ ImGui::Spacing();+ if (ImGui::Button(tr("Close##packreview"), ImVec2(120 * s, 0))) close = true;+ } else {+ const PackManifest& m = r->manifest;+ if (fontBold_) ImGui::PushFont(fontBold_);+ ImGui::TextUnformatted((m.name + " " + m.version).c_str());+ if (fontBold_) ImGui::PopFont();+ if (m.channel == "insider") {+ ImGui::SameLine();+ ImGui::TextColored(ImColor(kInsider), "%s", tr("Supporter Pack"));+ } else if (!m.channel.empty()) {+ ImGui::SameLine();+ ImGui::TextDisabled("[%s]", m.channel.c_str());+ }+ ImGui::Text("%s %s", tr("Author:"), m.author.c_str());+ ImGui::Text("%s %s", tr("License:"), m.license.c_str());+ ImGui::TextDisabled("%s - %s unpacked", utf8(fsPath(packs_.reviewPath).filename()).c_str(),+ r->bytes >= 1024 * 1024 ? (std::to_string(r->bytes / (1024 * 1024)) + " MB").c_str()+ : (std::to_string(std::max<uint64_t>(1, r->bytes / 1024)) + " KB").c_str());+ if (!m.description.empty()) ImGui::TextWrapped("%s", m.description.c_str());+ if (!r->installedVersion.empty())+ ImGui::TextColored(ImColor(kAccent), "%s %s", tr("Replaces the installed version"), r->installedVersion.c_str());+ ImGui::Separator();+ ImGui::TextWrapped("%s %s", tr("Contains:"), packCountsText(r->counts).c_str());+ const float listH = ImGui::GetContentRegionAvail().y - ImGui::GetFrameHeightWithSpacing() * 4.2f;+ ImGui::BeginChild("##packitems", ImVec2(ImGui::GetContentRegionAvail().x * 0.48f, std::max(60.0f, listH)),+ ImGuiChildFlags_Borders);+ for (const std::string& n : r->itemNames) ImGui::TextUnformatted(n.c_str());+ ImGui::EndChild();+ ImGui::SameLine();+ ImGui::BeginChild("##packlicense", ImVec2(0, std::max(60.0f, listH)), ImGuiChildFlags_Borders);+ if (r->licenseText.empty()) ImGui::TextDisabled("%s", tr("No license text in the pack (see License above)."));+ else ImGui::TextWrapped("%s", r->licenseText.c_str());+ ImGui::EndChild();+ ImGui::TextWrapped("%s", tr("Packs hold data only: nothing in this one runs on install or when a project "+ "opens. Its macros list their commands and ask before they first run."));+ if (r->counts[size_t(PackItemType::Keymap)] || r->counts[size_t(PackItemType::PieMenu)])+ ImGui::TextDisabled("%s", tr("Keymaps and pie menus are only applied when you choose to (Library > Packs)."));+ if (ImGui::Button(tr("Install##packreview"), ImVec2(120 * s, 0))) {+ std::string err;+ if (installPack(*r, err)) {+ refreshPacks();+ status_ = "Installed " + m.name + " " + m.version + ": " + packCountsText(r->counts) ++ (packsSafeMode() ? " (packs are off this session: --no-packs)" : "");+ lightbox_.show(LibraryTab::Packs);+ close = true;+ } else {+ status_ = "Could not install " + m.name + ": " + err;+ }+ }+ ui::HelpText("Install", nullptr, "Copy the pack into SculptForge's packs folder and add its items to the lists.",+ "Library > Packs");+ ImGui::SameLine();+ if (ImGui::Button(tr("Cancel##packreview"), ImVec2(120 * s, 0))) close = true;+ }+ ImGui::End();+ if (close) {+ packs_.reviewOpen = false;+ packs_.review.reset();+ }+}++// ---------------------------------------------------------------------------+// Library > Packs+// ---------------------------------------------------------------------------++void App::drawPacksTab(float height) {+ const float s = uiScale_;+ ImGui::BeginChild("##packs", ImVec2(0, height), ImGuiChildFlags_None, ImGuiWindowFlags_NoBackground);+ ui::ActionButton(*this, "pack.install", ImVec2(0, 0), ui::Look::IconLabel);+ ImGui::SameLine();+ ui::ActionButton(*this, "pack.new", ImVec2(0, 0), ui::Look::IconLabel);+ ImGui::SameLine(0, 18 * s);+ if (macros_.recorder.active()) {+ ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(240, 90, 80, 255));+ if (ImGui::Button((std::string(ICON_LC_SQUARE " ") + tr("Stop Recording") + " (" ++ std::to_string(macros_.recorder.lines().size()) + ")###macro.stop").c_str()))+ toggleMacroRecording();+ ImGui::PopStyleColor();+ } else {+ ui::ActionButton(*this, "macro.record", ImVec2(0, 0), ui::Look::IconLabel);+ }+ ImGui::SameLine();+ ui::ActionButton(*this, "macro.editor", ImVec2(0, 0), ui::Look::IconLabel);+ if (packsSafeMode()) {+ ImGui::SameLine(0, 18 * s);+ ImGui::TextColored(ImColor(kAccent), "%s", tr("Safe mode (--no-packs): no pack is loaded this session"));+ }++ if (packs_.installed.empty())+ ImGui::TextDisabled("%s", tr("No packs installed. Drop a .sfpack on the window or use Install Pack..."));+ std::string toggle, remove;+ bool toggleOn = false;+ for (const InstalledPack& p : packs_.installed) {+ const PackManifest& m = p.manifest;+ ImGui::PushID(m.id.c_str());+ bool on = p.enabled;+ if (ui::Checkbox(("##on" + m.id).c_str(), &on)) {+ toggle = m.id;+ toggleOn = on;+ }+ ui::HelpText("Pack on", nullptr, "Off: its items leave the lists until you switch it on again (nothing is deleted).",+ "Library > Packs");+ ImGui::SameLine();+ ImGui::TextUnformatted((m.name + " " + m.version).c_str());+ if (m.channel == "insider") {+ ImGui::SameLine();+ ImGui::TextColored(ImColor(kInsider), "%s", tr("Supporter Pack"));+ }+ std::array<int, kPackItemTypes> counts{};+ for (const PackItem& it : m.contents) ++counts[size_t(it.type)];+ ImGui::SameLine();+ ImGui::TextDisabled("by %s - %s - %s", m.author.c_str(), m.license.c_str(), packCountsText(counts).c_str());+ ImGui::SameLine();+ const bool expanded = packs_.expanded == m.id;+ if (ImGui::SmallButton((std::string(expanded ? tr("Hide") : tr("Details")) + "##" + m.id).c_str()))+ packs_.expanded = expanded ? "" : m.id;+ ImGui::SameLine();+ if (ImGui::SmallButton((std::string(tr("Remove")) + "##" + m.id).c_str())) remove = m.id;+ ui::HelpText("Remove", nullptr, "Delete the pack and everything it brought. Your own files are never touched.",+ "Library > Packs");+ if (expanded) {+ ImGui::Indent(24 * s);+ if (!m.description.empty()) ImGui::TextWrapped("%s", m.description.c_str());+ for (const PackContentItem& k : packs_.keymaps)+ if (k.packId == m.id) {+ if (ImGui::SmallButton((std::string(tr("Apply keymap")) + " " + k.name + "##km." + m.id + "." + k.name).c_str()))+ applyPackKeymap(k.file);+ ImGui::SameLine();+ }+ for (const PackContentItem& k : packs_.pieMenus)+ if (k.packId == m.id) {+ if (ImGui::SmallButton((std::string(tr("Add pie menu")) + " " + k.name + "##pie." + m.id + "." + k.name).c_str()))+ importRadialMenu(k.file);+ ImGui::SameLine();+ }+ for (const Macro& mac : macros_.list)+ if (mac.pack == m.name) {+ if (ImGui::SmallButton((std::string(tr("Run")) + " " + mac.name + "##mrun." + m.id + "." + mac.name).c_str()))+ requestMacroRun(mac);+ ImGui::SameLine();+ }+ ImGui::NewLine();+ ImGui::TextDisabled("%s", p.dir.c_str());+ ImGui::Unindent(24 * s);+ }+ ImGui::PopID();+ }++ // The user's own macros.+ bool any = false;+ std::string deleteMacro;+ for (const Macro& mac : macros_.list) {+ if (!mac.pack.empty()) continue;+ if (!any) {+ ImGui::Spacing();+ ImGui::TextDisabled("%s", tr("Your macros"));+ any = true;+ }+ ImGui::PushID(mac.path.c_str());+ ImGui::TextUnformatted(mac.name.c_str());+ ImGui::SameLine();+ ImGui::TextDisabled("%d commands", int(mac.statements.size()));+ ImGui::SameLine();+ if (ImGui::SmallButton((std::string(tr("Run")) + "##run" + mac.path).c_str())) requestMacroRun(mac);+ ImGui::SameLine();+ if (ImGui::SmallButton((std::string(tr("Edit")) + "##edit" + mac.path).c_str()))+ openMacroEditor(mac.name, mac.text, mac.path);+ ImGui::SameLine();+ if (ImGui::SmallButton((std::string(tr("Delete")) + "##del" + mac.path).c_str())) deleteMacro = mac.path;+ ImGui::PopID();+ }+ ImGui::EndChild();++ std::string err;+ if (!toggle.empty()) {+ if (setPackEnabled(toggle, toggleOn, err)) {+ refreshPacks();+ status_ = std::string(toggleOn ? "Turned on" : "Turned off") + " pack " + toggle;+ } else status_ = err;+ }+ if (!remove.empty()) {+ if (removePack(remove, err)) {+ if (packs_.expanded == remove) packs_.expanded.clear();+ refreshPacks();+ status_ = "Removed pack " + remove;+ } else status_ = err;+ }+ if (!deleteMacro.empty()) {+ std::error_code ec;+ fs::remove(fsPath(deleteMacro), ec);+ refreshMacroActions();+ status_ = ec ? "Could not delete " + deleteMacro : "Deleted macro " + utf8(fsPath(deleteMacro).stem());+ }+}++bool App::applyPackKeymap(const std::string& file) {+ std::ifstream f(fsPath(file), std::ios::binary);+ std::string text(128 * 1024 + 1, '\0');+ f.read(text.data(), std::streamsize(text.size()));+ text.resize(size_t(std::max<std::streamsize>(f.gcount(), 0)));+ KeymapFile k;+ std::string err;+ if (!f.is_open() && text.empty()) err = "Cannot read " + file;+ if (!err.empty() || !parseKeymapFile(text, k, err)) {+ status_ = "Keymap not applied: " + err;+ return false;+ }+ int applied = 0, skipped = 0;+ for (const auto& [id, chord] : k.shortcuts) {+ if (!actions_.find(id) || parseChords(chord).empty()) {+ ++skipped;+ continue;+ }+ actions_.assignShortcut(id, chord);+ ++applied;+ }+ status_ = "Keymap " + (k.name.empty() ? utf8(fsPath(file).stem()) : k.name) + ": " + std::to_string(applied) ++ " keys" + (skipped ? " (" + std::to_string(skipped) + " unknown left out)" : "") + " - Store Config keeps them";+ return applied > 0;+}++void App::drawPackKeymapRows() {+ if (packs_.keymaps.empty()) return;+ ImGui::TextDisabled("%s", tr("Pack keymaps"));+ for (const PackContentItem& k : packs_.keymaps) {+ ImGui::SameLine();+ if (ImGui::SmallButton((std::string(tr("Apply")) + " " + k.label() + "##" + k.file).c_str())) applyPackKeymap(k.file);+ ui::HelpText("Apply keymap", nullptr,+ "Take the keys of this keymap from an installed pack (only actions SculptForge knows; a key another "+ "action had moves here). Store Config keeps them.",+ "Preferences > Input");+ }+}++// ---------------------------------------------------------------------------+// New Pack+// ---------------------------------------------------------------------------++void App::openNewPack() {+ packs_.candidates.clear();+ packs_.newError.clear();+ auto add = [&](PackItemType t, std::string label, std::string file, std::string name = {}, std::string data = {}) {+ NewPackItem it;+ it.type = t;+ it.label = std::move(label);+ it.file = std::move(file);+ it.name = std::move(name);+ it.data.assign(data.begin(), data.end());+ packs_.candidates.push_back(std::move(it));+ };+ for (const BrushRecipe& b : doc_.brushes)+ if (isUserLibraryBrush(b) && !b.origin.path.empty()) add(PackItemType::Brush, b.name, b.origin.path);+ auto images = [](const std::string& n) { return packItemExtensionOk(PackItemType::Alpha, n); };+ if (!library_.user.empty())+ for (const std::string& f : filesIn(library_.user + "/Alphas", images))+ add(PackItemType::Alpha, utf8(fsPath(f).stem()), f);+ for (const std::string& f : filesIn(matcapFolder(), images)) add(PackItemType::Matcap, utf8(fsPath(f).stem()), f);+ if (hasTexture(doc_.mesh)) {+ const std::string name = doc_.activeSubtoolInfo().name + " Material";+ const std::string text = materialRecipeText(*doc_.mesh.texture, name);+ MaterialRecipe probe;+ std::string err;+ if (parseMaterialRecipe(text, probe, err) && probe.layers.size() > 0)+ add(PackItemType::Material, name + " (the Part's Fill layers)", "", name + kMaterialRecipeExtension, text);+ }+ for (const auto& v : doc_.vdms)+ if (v && !v->builtin && !v->path.empty() && packItemExtensionOk(PackItemType::Vdm, v->path))+ add(PackItemType::Vdm, v->name, v->path);+ for (const RadialMenu& menu : radialMenus_)+ if (!menu.slots.empty()) {+ const std::string label = menu.name.empty() ? "Pie menu" : menu.name;+ const std::string file = brushFileName(label); // safe on every OS, then .json instead of .sfbrush+ add(PackItemType::PieMenu, label, "", file.substr(0, file.size() - std::strlen(".sfbrush")) + ".json",+ radialMenuFileText(menu));+ }+ {+ KeymapFile k;+ k.name = "My shortcuts";+ const Json overrides = actions_.overridesToJson(); // (kept alive for the loop)+ for (const auto& [id, chord] : overrides.members())+ if (chord.isString() && !chord.asString().empty() && id.rfind("macro.run.", 0) != 0)+ k.shortcuts.emplace_back(id, chord.asString());+ if (!k.shortcuts.empty())+ add(PackItemType::Keymap, "My shortcuts (" + std::to_string(k.shortcuts.size()) + " keys)", "",+ "My shortcuts.json", keymapFileText(k));+ }+ for (const Macro& m : macros_.list)+ if (m.pack.empty() && !m.path.empty()) add(PackItemType::Macro, m.name, m.path);+ packs_.newOpen = true;+}++void App::writeNewPack(const std::string& path) {+ PackManifest m;+ m.id = packs_.id;+ m.name = packs_.name;+ m.version = packs_.version;+ m.author = packs_.author;+ m.license = packs_.license;+ m.description = packs_.description;+ m.channel = packs_.insider ? "insider" : "";+ std::vector<PackSource> items;+ for (const NewPackItem& it : packs_.candidates)+ if (it.on) items.push_back({it.type, it.file, it.name, it.data});+ const std::string license = m.name + " by " + m.author + " is shared under " + m.license + ".\n";+ std::string err;+ if (writePack(path, m, items, license, "", err, &commands_)) {+ packs_.newError.clear();+ packs_.newOpen = false;+ status_ = "Wrote " + path + " (" + std::to_string(items.size()) + " items)";+ } else {+ packs_.newError = err;+ status_ = "Pack not written: " + err;+ }+}++void App::drawNewPack() {+ if (!packs_.newOpen) return;+ const float s = uiScale_;+ centerNextWindow(560 * s, 560 * s);+ bool open = true;+ if (!ImGui::Begin(tr("New Pack"), &open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings)) {+ ImGui::End();+ packs_.newOpen = open;+ return;+ }+ auto field = [&](const char* label, char* buf, size_t size, const char* help) {+ ImGui::SetNextItemWidth(-110 * s);+ ImGui::InputText(label, buf, size);+ ui::HelpText(label, nullptr, help, "Library > Packs > New Pack");+ };+ field("Name##newpack", packs_.name, sizeof packs_.name, "The pack's name, shown next to every item it brings.");+ if (!packs_.id[0] && packs_.name[0]) {+ std::string id;+ for (unsigned char c : std::string(packs_.name))+ id += std::isalnum(c) ? char(std::tolower(c)) : (id.empty() || id.back() == '-' ? '\0' : '-');+ id.erase(std::remove(id.begin(), id.end(), '\0'), id.end());+ while (!id.empty() && id.back() == '-') id.pop_back();+ std::snprintf(packs_.id, sizeof packs_.id, "%s", id.substr(0, 64).c_str());+ }+ field("Id##newpack", packs_.id, sizeof packs_.id,+ "Its folder name: lower-case letters, digits, '.', '_' or '-'. A newer version keeps the same id.");+ field("Version##newpack", packs_.version, sizeof packs_.version, "1.0, 1.1, 2.0 ...");+ field("Author##newpack", packs_.author, sizeof packs_.author, "Who made it (shown when it's installed).");+ field("License##newpack", packs_.license, sizeof packs_.license, "For example CC-BY-4.0, CC0-1.0 or your own terms.");+ ImGui::SetNextItemWidth(-110 * s);+ ImGui::InputTextMultiline("Description##newpack", packs_.description, sizeof packs_.description,+ ImVec2(-110 * s, ImGui::GetTextLineHeight() * 3.0f));+ ui::Checkbox("Supporter Pack (insider channel)##newpack", &packs_.insider);+ ui::HelpText("Supporter Pack", nullptr, "Marks the pack as a Supporter Pack. Display only: anyone can install it.",+ "Library > Packs > New Pack");+ ImGui::Separator();+ const float listH = ImGui::GetContentRegionAvail().y - ImGui::GetFrameHeightWithSpacing() * 2.6f;+ ImGui::BeginChild("##newpackitems", ImVec2(0, std::max(80.0f, listH)), ImGuiChildFlags_Borders);+ if (packs_.candidates.empty())+ ImGui::TextDisabled("%s", tr("Nothing of your own yet: save brushes, put alphas and Lit Spheres in your "+ "Library folders, record a macro..."));+ int lastType = -1;+ for (size_t i = 0; i < packs_.candidates.size(); ++i) {+ NewPackItem& it = packs_.candidates[i];+ if (int(it.type) != lastType) {+ lastType = int(it.type);+ std::string group = packItemLabel(it.type, 2);+ group[0] = char(std::toupper(static_cast<unsigned char>(group[0])));+ ImGui::TextDisabled("%s", group.c_str());+ }+ ui::Checkbox((it.label + "##npi." + packItemTypeId(it.type) + "." + it.label).c_str(), &it.on);+ }+ ImGui::EndChild();+ int chosen = 0;+ for (const NewPackItem& it : packs_.candidates) chosen += it.on ? 1 : 0;+ if (!packs_.newError.empty()) ImGui::TextColored(ImColor(IM_COL32(240, 110, 100, 255)), "%s", packs_.newError.c_str());+ ImGui::BeginDisabled(chosen == 0 || !packs_.name[0] || !packs_.author[0]);+ if (ImGui::Button(tr("Save Pack...##newpack"), ImVec2(140 * s, 0))) openPackDialog(kPackDialogSave);+ ImGui::EndDisabled();+ ui::HelpText("Save Pack", nullptr, "Write the .sfpack, checked exactly as an install would check it.",+ "Library > Packs > New Pack");+ ImGui::SameLine();+ ImGui::TextDisabled("%d items", chosen);+ ImGui::SameLine();+ if (ImGui::Button(tr("Cancel##newpack"), ImVec2(100 * s, 0))) open = false;+ ImGui::End();+ if (!open) packs_.newOpen = false;+}++// ---------------------------------------------------------------------------+// Macros: confirm, run, record, edit+// ---------------------------------------------------------------------------++void App::requestMacroRun(const Macro& m) {+ if (macros_.waiting) {+ status_ = "A macro is waiting for a file: pick it or cancel first";+ return;+ }+ if (macroConfirmed(m.text)) {+ startMacroRun(m);+ return;+ }+ macros_.confirm = m;+ macros_.confirmOpen = true;+}++void App::startMacroRun(Macro m) {+ macros_.running = std::move(m);+ macros_.asks = macroAsks(macros_.running);+ macros_.answers.clear();+ if (macros_.asks.empty()) {+ runMacroNow();+ return;+ }+ macros_.waiting = true;+ status_ = macros_.running.name + ": pick a file for " + macros_.asks[0].command;+ openPackDialog(kPackDialogMacro, int(macros_.asks[0].kind));+}++void App::runMacroNow() {+ macros_.waiting = false;+ MacroRunContext ctx;+ ctx.projectDir = macroProjectDir();+ size_t next = 0;+ ctx.askPath = [&](const std::string&, const std::string&, MacroPathKind) {+ return next < macros_.answers.size() ? macros_.answers[next++] : std::string();+ };+ ctx.execute = [this](const std::string& command, const Args& args) {+ runCommand(command, args);+ return CommandResult{lastCommandOk_, status_};+ };+ ++macros_.runDepth;+ const MacroRunResult r = runMacro(doc_, commands_, macros_.running, ctx);+ --macros_.runDepth;+ macros_.ran = r.ran;+ macros_.lastOk = r.ok;+ macros_.lastOneStep = r.oneUndoStep;+ lastCommandOk_ = r.ok;+ status_ = r.message;+ if (!r.ok) SDL_Log("%s", r.message.c_str());+ if (r.oneUndoStep) clearLods();+ updateTitle();+}++void App::drawMacroConfirm() {+ if (!macros_.confirmOpen) return;+ const float s = uiScale_;+ centerNextWindow(560 * s, 460 * s);+ bool open = true;+ if (!ImGui::Begin(tr("Run Macro?"), &open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings)) {+ ImGui::End();+ macros_.confirmOpen = open;+ return;+ }+ const Macro& m = macros_.confirm;+ if (fontBold_) ImGui::PushFont(fontBold_);+ ImGui::TextUnformatted(m.name.c_str());+ if (fontBold_) ImGui::PopFont();+ ImGui::TextDisabled("%s", m.pack.empty() ? tr("Your macro") : ("From the pack " + m.pack).c_str());+ if (!m.description.empty()) ImGui::TextWrapped("%s", m.description.c_str());+ ImGui::TextWrapped("%s", ("It runs these " + std::to_string(m.statements.size()) ++ " SculptForge commands, in order (it can't do anything else):").c_str());+ ImGui::BeginChild("##macrolines", ImVec2(0, ImGui::GetContentRegionAvail().y - ImGui::GetFrameHeightWithSpacing() * 2.4f),+ ImGuiChildFlags_Borders);+ ImGui::PushFont(consoleFont());+ for (const ScriptStatement& st : m.statements)+ ImGui::Text("%3d %s", st.line, formatStatement(st.command, st.args).c_str());+ ImGui::PopFont();+ ImGui::EndChild();+ const size_t asks = macroAsks(m).size();+ ImGui::TextDisabled("%s", asks ? (std::to_string(asks) + " file(s) are asked for when it runs (\"?\"); other files "+ "stay inside the project folder.").c_str()+ : tr("Files it uses stay inside the project folder."));+ bool run = false;+ if (ImGui::Button(tr("Run##macroconfirm"), ImVec2(120 * s, 0))) run = true;+ ui::HelpText("Run", nullptr, "Run it now. You won't be asked again for this macro unless it changes.", "Macros");+ ImGui::SameLine();+ if (ImGui::Button(tr("Cancel##macroconfirm"), ImVec2(120 * s, 0))) open = false;+ ImGui::End();+ if (run) {+ setMacroConfirmed(m.text);+ macros_.confirmOpen = false;+ startMacroRun(m);+ } else if (!open) {+ macros_.confirmOpen = false;+ status_ = "Macro " + m.name + " not run";+ }+}++void App::toggleMacroRecording() {+ if (macros_.recorder.active()) {+ macros_.recorder.stop();+ const auto& lines = macros_.recorder.lines();+ const int skipped = macros_.recorder.skipped();+ status_ = "Recorded " + std::to_string(lines.size()) + " commands" ++ (skipped ? " (" + std::to_string(skipped) + " left out: macros can't run them)" : "") ++ " - name it and Save";+ openMacroEditor("Recorded Macro", macroFileText("Recorded Macro", "", lines), "");+ } else {+ macros_.recorder.start();+ status_ = "Recording a macro: the commands you run are kept until you press Stop";+ }+}++void App::openMacroEditor(const std::string& name, const std::string& text, const std::string& path) {+ std::snprintf(macros_.name, sizeof macros_.name, "%s", name.c_str());+ std::fill(macros_.text.begin(), macros_.text.end(), '\0');+ std::memcpy(macros_.text.data(), text.data(), std::min(text.size(), macros_.text.size() - 1));+ macros_.path = path;+ macros_.checkedText = "\x01";+ macros_.editorOpen = true;+}++void App::drawMacroEditor() {+ if (!macros_.editorOpen) return;+ const float s = uiScale_;+ centerNextWindow(600 * s, 480 * s);+ bool open = true;+ if (!ImGui::Begin(tr("Macro Editor"), &open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings)) {+ ImGui::End();+ macros_.editorOpen = open;+ return;+ }+ ImGui::SetNextItemWidth(-80 * s);+ ImGui::InputText("Name##macroname", macros_.name, sizeof macros_.name);+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));+ ImGui::TextWrapped("%s", tr("One command per line, as in the console (# starts a comment). Files: a path inside "+ "the project folder, or ? to pick one when it runs."));+ ImGui::PopStyleColor();+ ImGui::PushFont(consoleFont());+ ImGui::InputTextMultiline("##macrotext", macros_.text.data(), macros_.text.size(),+ ImVec2(-FLT_MIN, ImGui::GetContentRegionAvail().y - ImGui::GetFrameHeightWithSpacing() * 2.4f),+ ImGuiInputTextFlags_AllowTabInput);+ ImGui::PopFont();+ const std::string text(macros_.text.data());+ if (text != macros_.checkedText) {+ macros_.checkedText = text;+ Macro m;+ std::string err;+ macros_.checkOk = parseMacro(text, &commands_, m, err, macros_.name);+ macros_.check = macros_.checkOk ? std::to_string(m.statements.size()) + " commands, all allowed" : err;+ }+ ImGui::TextColored(macros_.checkOk ? ImColor(IM_COL32(120, 200, 120, 255)) : ImColor(IM_COL32(240, 110, 100, 255)),+ "%s", macros_.check.c_str());+ ImGui::BeginDisabled(!macros_.checkOk || !macros_.name[0]);+ if (ImGui::Button(tr("Save##macroeditor"), ImVec2(100 * s, 0))) {+ const std::string dir = userMacroDir();+ std::error_code ec;+ fs::create_directories(fsPath(dir), ec);+ // Keep the header's name in step with the Name field.+ std::string body = text;+ while (body.rfind("# name:", 0) == 0) body = body.substr(std::min(body.size(), body.find('\n') + 1));+ const std::string out = "# name: " + std::string(macros_.name) + "\n" + body;+ const std::string path = utf8(fsPath(dir) / fsPath(macroFileName(macros_.name)));+ std::ofstream f(fsPath(path), std::ios::binary | std::ios::trunc);+ f << out;+ f.close(); // (written out before the macro list reads it back)+ if (f) {+ if (!macros_.path.empty() && macros_.path != path) fs::remove(fsPath(macros_.path), ec); // renamed+ macros_.path = path;+ refreshMacroActions();+ status_ = "Saved macro " + std::string(macros_.name) + " (F3 finds it; keys and pie menus can run it)";+ } else status_ = "Could not write " + path;+ }+ ImGui::SameLine();+ if (ImGui::Button(tr("Run##macroeditor"), ImVec2(100 * s, 0))) {+ Macro m;+ std::string err;+ if (parseMacro(text, &commands_, m, err, macros_.name)) requestMacroRun(m);+ }+ ImGui::EndDisabled();+ ImGui::SameLine();+ if (ImGui::Button(tr("Close##macroeditor"), ImVec2(100 * s, 0))) open = false;+ ImGui::End();+ if (!open) macros_.editorOpen = false;+}++void App::drawPacksUi() {+ drawPackReview();+ drawNewPack();+ drawMacroConfirm();+ drawMacroEditor();+ if (macros_.recorder.active()) { // a small red reminder at the top of the canvas while recording+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ ImDrawList* dl = ImGui::GetForegroundDrawList();+ const std::string t = std::string(ICON_LC_CIRCLE_DOT " ") + tr("Recording macro") + " (" ++ std::to_string(macros_.recorder.lines().size()) + ")";+ const ImVec2 ts = ImGui::CalcTextSize(t.c_str());+ const ImVec2 p(vp->WorkPos.x + (vp->WorkSize.x - ts.x) * 0.5f, vp->WorkPos.y + 40.0f * uiScale_);+ dl->AddRectFilled(ImVec2(p.x - 8, p.y - 4), ImVec2(p.x + ts.x + 8, p.y + ts.y + 4), IM_COL32(40, 14, 14, 230), 4.0f);+ dl->AddText(p, IM_COL32(240, 90, 80, 255), t.c_str());+ }+}++double App::packsTestValue(const std::string& name) const {+ if (name == "packs_installed") return double(packs_.installed.size());+ if (name == "packs_enabled")+ return double(std::count_if(packs_.installed.begin(), packs_.installed.end(), [](const InstalledPack& p) { return p.enabled; }));+ if (name == "packs_safe_mode") return packsSafeMode() ? 1.0 : 0.0;+ if (name == "pack_review_open") return packs_.reviewOpen ? 1.0 : 0.0;+ if (name == "pack_review_ok") return packs_.review ? 1.0 : 0.0;+ if (name.rfind("pack_review_", 0) == 0) { // pack_review_brush, pack_review_macro ...: the review's counts+ PackItemType t;+ if (packItemTypeFromId(name.substr(12), t)) return packs_.review ? double(packs_.review->counts[size_t(t)]) : -1.0;+ }+ if (name == "pack_alphas") return double(packs_.alphas.size());+ if (name == "pack_materials") return double(packs_.materials.size());+ if (name == "pack_matcaps") return double(packs_.matcaps.size());+ if (name == "pack_keymaps") return double(packs_.keymaps.size());+ if (name == "pack_brushes")+ return double(std::count_if(doc_.brushes.begin(), doc_.brushes.end(),+ [](const BrushRecipe& b) { return b.origin.source == BrushSource::Pack; }));+ if (name == "new_pack_open") return packs_.newOpen ? 1.0 : 0.0;+ if (name == "new_pack_items") return double(packs_.candidates.size());+ if (name == "macro_recording") return macros_.recorder.active() ? 1.0 : 0.0;+ if (name == "macro_recorded") return double(macros_.recorder.lines().size());+ if (name == "macro_confirm_open") return macros_.confirmOpen ? 1.0 : 0.0;+ if (name == "macro_editor_open") return macros_.editorOpen ? 1.0 : 0.0;+ if (name == "macro_editor_ok") return macros_.checkOk ? 1.0 : 0.0;+ if (name == "macro_waiting") return macros_.waiting ? 1.0 : 0.0;+ if (name == "macros") return double(macros_.list.size());+ if (name == "macro_ran") return double(macros_.ran);+ if (name == "macro_ok") return macros_.lastOk ? 1.0 : 0.0;+ if (name == "macro_one_step") return macros_.lastOneStep ? 1.0 : 0.0;+ if (name == "macro_actions")+ return double(std::count_if(actions_.all().begin(), actions_.all().end(),+ [](const Action& a) { return a.id.rfind("macro.run.", 0) == 0; }));+ if (name == "undo_steps") return double(doc_.undo.undoCount());+ return std::nan("");+}++} // namespace sfdiff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cppindex 2c8ca6bc..2770ec94 100644--- a/src/app/PanelProject.cpp+++ b/src/app/PanelProject.cpp@@ -508,7 +508,8 @@ void App::openPathConfirmed(const std::string& path) {runCommand("splat_train", {{"source", path}});return;}- if (Image::isImagePath(path) || ext == ".sfbrush" || ext == ".exr" || ext == ".sfvdm") openPath(path);+ if (Image::isImagePath(path) || ext == ".sfbrush" || ext == ".exr" || ext == ".sfvdm" || ext == kPackExtension)+ openPath(path); // (a pack opens its review screen: the scene stays)else confirmDiscard([this, path] { openPath(path); });}diff --git a/src/app/Pickers.cpp b/src/app/Pickers.cppindex 22cfcf85..9315afd3 100644--- a/src/app/Pickers.cpp+++ b/src/app/Pickers.cpp@@ -444,6 +444,9 @@ std::vector<BrushItem> PickerUi::brushItems(App& app, bool libraryFiles) {case BrushSource::Studio:b.tag = "studio";break;+ case BrushSource::Pack:+ b.tag = r.origin.pack;+ break;case BrushSource::Gallery:b.tag = "gallery";break;@@ -878,6 +881,18 @@ void drawAlphaGrid(App& app, GridMode mode) {quickInfo(tex, ICON_LC_IMAGE, e.name, "Image in your library's Alphas folder.", e.path);}}+ if (!app.packAlphas().empty()) { // alphas from installed packs, tagged with the pack's name+ sectionHeader("Packs");+ column = 0;+ for (const PackContentItem& it : app.packAlphas()) {+ tileGrid(column, columns);+ const std::string label = it.label();+ const ImTextureID tex = app.thumbs_.file(it.file);+ if (AssetTile((label + "##alphapack" + it.file).c_str(), tex, ICON_LC_IMAGE, label, tile, false))+ app.runCommand("brush_set_alpha", {{"path", it.file}, {"invert", app.alphaInvert_}});+ quickInfo(tex, ICON_LC_IMAGE, label, ("From the pack " + it.packName + ".").c_str(), it.file);+ }+ }ImGui::Dummy(ImVec2(0, 2));if (ImGui::Button(ICON_LC_FOLDER_OPEN " Load image...", ImVec2(mode == GridMode::Popup ? 0.0f : -1.0f, 0)))SDL_ShowOpenFileDialog(App::onAlphaChosen, &app, app.window_, kAlphaFilters, 2, nullptr, false);diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex a8b0d679..712b9f38 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -150,6 +150,9 @@// shot NAME save a screenshot NAME.png (to --ui-out)// expect_guide FILE the User Guide shows FILE ("masking.md", "index.md")// dump_shortcuts NAME write every default shortcut as a Markdown table to --ui-out/NAME+// answer_dialog PATH|cancel what the open pack or macro file dialog answers (Install Pack, Save Pack, a+// macro's "?"); values: packs_installed, pack_review_open, pack_review_brush, macros,+// macro_recording, macro_recorded, macro_confirm_open, macro_ran, macro_one_step ...// A scripted phone for File > Capture from phone (link/PhoneLink.h), over real HTTP to the link on 127.0.0.1:// phone_upload KIND FILE... send files as the capture page does (KIND splat / photo / ply; FILE relative to the// script), in 64 KB chunks with one lost chunk resumed, then finish the capture@@ -444,6 +447,7 @@ double Demo::query(const std::string& name, bool& known) const {if (name == "radial_hover") return double(app_.radial_.hover);if (name == "radial_ran") return double(app_.radial_.ran); // the slot run last, -1: none yetif (name == "radial_menus") return double(app_.radialMenus_.size());+ if (const double v = app_.packsTestValue(name); !std::isnan(v)) return v; // packs_installed, macro_recording, ...if (name.rfind("radial_slots_", 0) == 0) { // radial_slots_N: menu N's items (1-based), -1: no such menuconst size_t i = size_t(std::max(0, std::atoi(name.c_str() + 13) - 1));return i < app_.radialMenus_.size() ? double(app_.radialMenus_[i].slots.size()) : -1.0;@@ -1247,6 +1251,26 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& eif (file.is_relative()) file = std::filesystem::path(std::u8string(scriptDir_.begin(), scriptDir_.end())) / file;const auto u8 = file.lexically_normal().u8string();run([this, action, path = std::string(u8.begin(), u8.end())] { app_.queueFile(action, path); });+ } else if (verb == "answer_dialog") {+ // answer_dialog PATH | cancel: what the open pack or macro file dialog (Install Pack, New Pack's Save Pack,+ // a macro's "?") answers. PATH is relative to the script; a file that doesn't exist beside it (a save) lands+ // in the shots folder.+ if (!need(1)) return false;+ std::string path;+ if (w[1] != "cancel") {+ const std::string name = restOf(lineText_, 1); // (names may have spaces)+ auto file = std::filesystem::path(std::u8string(name.begin(), name.end()));+ if (file.is_relative()) {+ const auto beside = std::filesystem::path(std::u8string(scriptDir_.begin(), scriptDir_.end())) / file;+ std::error_code ec;+ file = std::filesystem::exists(beside, ec)+ ? beside+ : std::filesystem::path(std::u8string(shotDir_.begin(), shotDir_.end())) / file;+ }+ const auto u8 = file.lexically_normal().u8string();+ path.assign(u8.begin(), u8.end());+ }+ run([this, path] { app_.packDialogAnswered(path); });} else if (verb == "radial_import" || verb == "radial_export") {// radial_import FILE (relative to the script) / radial_export N FILE (in the shots folder): what the file// dialogs of Preferences > Input > Radial Menus do with the path the user picked.@@ -1407,7 +1431,10 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& eif (!parseScript(text, statements, error)) return false;run([this, line, statements] {for (const auto& st : statements) {- app_.runCommand(st.command, st.args);+ Args args = st.args; // $LIBRARY: the test's own library folder (known once the app runs)+ for (auto& [key, value] : args)+ if (auto* sv = std::get_if<std::string>(&value)) *sv = expandLibrary(*sv);+ app_.runCommand(st.command, args);if (!app_.lastCommandOk_) {fail(line, st.command + " failed: " + app_.status_);return;diff --git a/src/app/UserGuide.cpp b/src/app/UserGuide.cppindex b5116153..60d38af8 100644--- a/src/app/UserGuide.cpp+++ b/src/app/UserGuide.cpp@@ -458,6 +458,7 @@ std::string UserGuide::chapterFor(const std::string& palette, const std::string&if (starts("Splats > Make sculptable")) return "scan-to-sculptable.md";if (starts("Splats")) return "splats.md";if (starts("Script")) return "scripting.md";+ if (starts("Library > Packs") || starts("Macros") || idStarts("pack.") || idStarts("macro.")) return "packs-and-macros.md";if (starts("Transform > Gizmo") || idStarts("gizmo.") || actionId == "tool.draw" || actionId == "tool.move" ||actionId == "tool.scale" || actionId == "tool.rotate")return "gizmo.md";diff --git a/src/app/main.cpp b/src/app/main.cppindex a64617e2..4d6d6314 100644--- a/src/app/main.cpp+++ b/src/app/main.cpp@@ -4,6 +4,7 @@#include "app/Bench.h"#include "app/Calibration.h"#include "app/CrashLog.h"+#include "core/Pack.h"#include <SDL3/SDL_main.h>@@ -44,6 +45,7 @@ void usage() {" --ui-test FILE.sfui Run a UI test script headless and exit (0 = pass); settings are isolated\n"" --ui-out DIR Where UI tests save screenshots\n"" --fullscreen Start filling the screen (F11 toggles)\n"+ " --no-packs Safe mode: start without any installed pack (Library > Packs)\n"" --blender Load what the Blender add-on sent (it starts SculptForge this way)\n"" --bench Run the performance benchmark (with GPU upload and orbit timings) and exit\n"" --bench-sizes 4,16,32 Benchmark sizes in millions of triangles\n"@@ -142,6 +144,7 @@ int main(int argc, char** argv) {else if (a == "--supersample") options.supersample = std::clamp(std::atoi(next().c_str()), 1, 4);else if (a == "--ui-test") options.uiTest = next();else if (a == "--fullscreen") options.fullscreen = true;+ else if (a == "--no-packs") sf::setPacksSafeMode(true); // safe mode: no installed pack is loadedelse if (a == "--blender") options.blender = true;else if (a == "--ui-out") options.uiOutDir = next();else if (a == "--log-dir") logDir = next();diff --git a/src/cli/McpServer.cpp b/src/cli/McpServer.cppindex bc4628a4..87b4d6a4 100644--- a/src/cli/McpServer.cpp+++ b/src/cli/McpServer.cpp@@ -17,9 +17,16 @@ namespace {constexpr const char* kLatestProtocol = "2025-06-18";+// Installing, removing or switching packs changes what every later session loads: that stays the user's own+// decision (the app's review screen, or sculptforge-cli run by hand), never an AI agent's.+bool hiddenFromAgents(const std::string& name) {+ return name == "pack_install" || name == "pack_remove" || name == "pack_enable" || name == "pack_disable";+}+Json toolList(const CommandRegistry& registry) {Json tools = Json::array();for (const auto& c : registry.all()) {+ if (hiddenFromAgents(c.name)) continue;Json props = Json::object(), required = Json::array();for (const auto& p : c.params) {Json prop = Json::object();@@ -97,7 +104,7 @@ std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, conif (method == "tools/list") return reply(id, toolList(registry)).dump();if (method == "tools/call") {const std::string name = msg["params"]["name"].asString();- if (!registry.find(name)) return errorReply(id, -32602, "Unknown tool: " + name).dump();+ if (!registry.find(name) || hiddenFromAgents(name)) return errorReply(id, -32602, "Unknown tool: " + name).dump();Args args;for (const auto& [key, value] : msg["params"]["arguments"].members()) {if (value.isBool()) args[key] = value.asBool();diff --git a/src/cli/main.cpp b/src/cli/main.cppindex d7de1cc4..edfc6855 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -9,6 +9,7 @@#include "core/Benchmark.h"#include "core/BrushLibrary.h"#include "core/Commands.h"+#include "core/Pack.h"#include "core/Script.h"#include <cstdio>@@ -32,6 +33,7 @@ void usage() {" --schema Print commands as LLM tool definitions (JSON)\n"" --mcp Run as an MCP server on stdio (Claude Code, Claude Desktop, any MCP client)\n"" -q, --quiet Only print errors\n"+ " --no-packs Safe mode: leave every installed pack out (pack_install still works)\n"" --bench Run the performance benchmark (CPU side; the app's --bench adds the GPU)\n"" --bench-sizes 4,16,32 Benchmark sizes in millions of triangles\n"" --bench-dabs N Dabs per benchmark stroke (default 40)\n"@@ -109,6 +111,8 @@ int main(int argc, char** argv) {return 0;} else if (sf::parseBenchArg(argc, argv, i, bench)) {// handled after the loop+ } else if (a == "--no-packs") {+ sf::setPacksSafeMode(true);} else if (a == "-q" || a == "--quiet") {quiet = true;} else if (a == "-h" || a == "--help") {diff --git a/src/core/BrushLibrary.cpp b/src/core/BrushLibrary.cppindex 0f5889f1..b2b8afa2 100644--- a/src/core/BrushLibrary.cpp+++ b/src/core/BrushLibrary.cpp@@ -4,6 +4,7 @@#include "core/Commands.h"#include "core/Document.h"+#include "core/Pack.h"#include "core/Vdm.h"#include <algorithm>@@ -203,6 +204,16 @@ bool findShadowed(const std::string& name, const BrushLibraryPaths& paths, Brushreturn true;}}+ for (const auto& pack : paths.packs) {+ if (pack.vdm) continue;+ for (const auto& file : brushFiles(pack.dir)) {+ std::string err;+ if (readBrushFile(file, out, err) && out.name == name) {+ out.origin = {BrushSource::Pack, file, BrushSource::Session, pack.pack};+ return true;+ }+ }+ }return false;}@@ -218,6 +229,7 @@ BrushLibraryPaths BrushLibraryPaths::fromEnvironment() {BrushLibraryPaths p;p.userDir = pathString(utf8Path(appDataDir()) / "brushes");p.studioDirs = splitSearchPath(env("SCULPTFORGE_BRUSH_PATH"));+ applyPacksToBrushLibrary(p); // the enabled packs' brushes and VDMs (none with --no-packs)return p;}@@ -386,6 +398,22 @@ std::vector<std::string> loadBrushLibrary(Document& doc, const BrushLibraryPaths}}+ for (const auto& pack : paths.packs) {+ if (pack.vdm || packsSafeMode()) continue;+ for (const auto& file : brushFiles(pack.dir)) {+ BrushRecipe r;+ std::string err;+ if (!readBrushFile(file, r, err)) {+ messages.push_back("Skipped " + file + " (pack " + pack.pack + "): " + err);+ continue;+ }+ r.origin = {BrushSource::Pack, file, BrushSource::Session, pack.pack};+ if (findBrush(doc, r.name) >= 0) r.name += " (" + pack.pack + ")"; // never replaces another brush+ if (findBrush(doc, r.name) >= 0) continue; // (the same pack twice)+ doc.brushes.push_back(std::move(r));+ }+ }+if (!paths.userDir.empty()) {for (const auto& file : brushFiles(paths.userDir)) {BrushRecipe r;@@ -404,6 +432,7 @@ std::vector<std::string> loadBrushLibrary(Document& doc, const BrushLibraryPaths" already has a brush called '" + r.name + "'");} else {r.origin.overrides = doc.brushes[size_t(i)].origin.source;+ r.origin.pack = doc.brushes[size_t(i)].origin.pack;doc.brushes[size_t(i)] = std::move(r);}}@@ -510,7 +539,7 @@ int renameBrush(Document& doc, int index, const std::string& newName, std::strinBrushRecipe& r = doc.brushes[size_t(index)];const BrushSource source = r.origin.source;- if (source == BrushSource::Builtin || source == BrushSource::Studio) {+ if (source == BrushSource::Builtin || source == BrushSource::Studio || source == BrushSource::Pack) {// Shared brushes stay as they are; the renamed one is the artist's copy.BrushRecipe copy = r;copy.name = name;@@ -635,7 +664,7 @@ void registerBrushLibraryCommands(CommandRegistry& registry) {if (j < 0) return {false, err};const std::string to = doc.brushes[size_t(j)].name;const std::string note = err.empty() ? "" : " (not saved: " + err + ")";- if (source == BrushSource::Builtin || source == BrushSource::Studio)+ if (source == BrushSource::Builtin || source == BrushSource::Studio || source == BrushSource::Pack)return {true, "Saved a copy of the " + std::string(brushSourceName(source)) + " brush '" + from +"' as '" + to + "'" + note};return {true, "Renamed '" + from + "' to '" + to + "'" + note};diff --git a/src/core/BrushLibrary.h b/src/core/BrushLibrary.hindex b7382479..a9ace6fc 100644--- a/src/core/BrushLibrary.h+++ b/src/core/BrushLibrary.h@@ -29,6 +29,13 @@ struct Document;struct BrushLibraryPaths {std::string userDir; // empty = nothing is saved (tests, demo recordings)std::vector<std::string> studioDirs; // read-only, in precedence order+ // Folders of enabled packs (core/Pack.h sets them): read-only, below the studio folders. A pack brush or VDM+ // never replaces a built-in, studio or other pack's of the same name: it gets " (<pack>)" after its name.+ struct PackDir {+ std::string dir, pack; // the pack's brushes/ or vdms/ folder, and the pack's name+ bool vdm = false;+ };+ std::vector<PackDir> packs;// <app data>/brushes plus the folders in SCULPTFORGE_BRUSH_PATH.static BrushLibraryPaths fromEnvironment();};diff --git a/src/core/BrushRecipe.cpp b/src/core/BrushRecipe.cppindex cbdb39bf..beae6aa1 100644--- a/src/core/BrushRecipe.cpp+++ b/src/core/BrushRecipe.cpp@@ -105,6 +105,7 @@ const char* brushSourceName(BrushSource source) {case BrushSource::Studio: return "studio";case BrushSource::Gallery: return "gallery";case BrushSource::Project: return "project";+ case BrushSource::Pack: return "pack";}return "session";}diff --git a/src/core/BrushRecipe.h b/src/core/BrushRecipe.hindex ddcfe37d..9de8e50c 100644--- a/src/core/BrushRecipe.h+++ b/src/core/BrushRecipe.h@@ -23,6 +23,7 @@ enum class BrushSource {Studio, // a read-only shared folder from SCULPTFORGE_BRUSH_PATHGallery, // installed from the community gallery (lives in the user library)Project, // came with an opened .sfproj and differs from (or is not in) the library+ Pack, // from an installed pack (core/Pack.h): read-only, like a studio brush};const char* brushSourceName(BrushSource source); // "session", "built-in", "user", "studio", "gallery", "project"@@ -31,6 +32,7 @@ struct BrushOrigin {std::string path; // the .sfbrush file it was loaded from or is saved to (user, gallery, studio)// A built-in or studio brush of the same name this user/gallery brush hides (Session = none).BrushSource overrides = BrushSource::Session;+ std::string pack; // Pack: the pack's name (the lists show it as the brush's tag)};struct BrushRecipe {diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 84b608df..c853f039 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -9,6 +9,8 @@#include "core/BrushLibrary.h"#include "core/Decimate.h"#include "core/KeepMasked.h"+#include "core/Macro.h"+#include "core/Pack.h"#include "core/Dyntopo.h"#include "core/EnginePresets.h"#include "core/ExtractMirror.h"@@ -809,6 +811,8 @@ CommandRegistry::CommandRegistry() {registerMayaCommands(*this); // maya_send/receive (io/MayaCommands.cpp)registerBakeCommands(*this); // bake (core/Bake.cpp)registerFaceCommands(*this); // face_shapes_generate, face_weights, ... (core/FaceCommands.cpp)+ registerPackCommands(*this); // pack_install, pack_list, pack_remove, ... (core/Pack.h)+ registerMacroCommands(*this); // macro_run, macro_list, macro_check (core/Macro.h)registerProjectCommands(*this); // keep last (core/Project.cpp)}diff --git a/src/core/Json.cpp b/src/core/Json.cppindex 1451cc16..f219d66b 100644--- a/src/core/Json.cpp+++ b/src/core/Json.cpp@@ -5,6 +5,7 @@#include <cmath>#include <cstdio>#include <cstdlib>+#include <cstring>namespace sf {@@ -19,6 +20,7 @@ struct Parser {size_t i = 0;std::string error;int depth = 0;+ bool strict = false; // parseStrict: duplicate keys and numbers outside JSON's grammar are errorsvoid ws() {while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) ++i;@@ -118,6 +120,7 @@ struct Parser {if (i >= s.size() || s[i] != '"') { ok = fail("Expected key"); break; }std::string key;if (!string(key)) { ok = false; break; }+ if (strict && out.has(key)) { ok = fail("Duplicate key \"" + key + "\""); break; }ws();if (i >= s.size() || s[i] != ':') { ok = fail("Expected ':'"); break; }++i;@@ -167,6 +170,12 @@ struct Parser {char* end = nullptr;double d = std::strtod(start, &end);if (end == start) ok = fail("Bad number");+ // strtod also takes hex, "inf", "nan" and a leading '+': not JSON.+ else if (strict) {+ for (const char* q = start; q < end; ++q)+ if (!std::strchr("0123456789+-.eE", *q)) { ok = fail("Bad number"); break; }+ if (ok && !std::isfinite(d)) ok = fail("Number out of range");+ }i += size_t(end - start);out = Json(d);} else {@@ -293,8 +302,12 @@ std::string Json::dump(bool pretty) const {return out;}-bool Json::parse(const std::string& text, Json& out, std::string& error) {+bool Json::parse(const std::string& text, Json& out, std::string& error) { return parseImpl(text, out, error, false); }+bool Json::parseStrict(const std::string& text, Json& out, std::string& error) { return parseImpl(text, out, error, true); }++bool Json::parseImpl(const std::string& text, Json& out, std::string& error, bool strict) {Parser p(text);+ p.strict = strict;Json v;if (!p.value(v)) {error = p.error;diff --git a/src/core/Json.h b/src/core/Json.hindex b9f36756..5b7f4e1a 100644--- a/src/core/Json.h+++ b/src/core/Json.h@@ -53,9 +53,13 @@ public:std::string dump(bool pretty = false) const;static bool parse(const std::string& text, Json& out, std::string& error);+ // Like parse, but a key given twice in one object, or a number JSON doesn't allow (hex, inf, nan), is an error+ // (files from outside: packs, macros' companions, keymaps).+ static bool parseStrict(const std::string& text, Json& out, std::string& error);private:void dumpTo(std::string& out, bool pretty, int indent) const;+ static bool parseImpl(const std::string& text, Json& out, std::string& error, bool strict);Type type_ = Type::Null;bool bool_ = false;diff --git a/src/core/Macro.cpp b/src/core/Macro.cppnew file mode 100644index 00000000..aa366b02--- /dev/null+++ b/src/core/Macro.cpp@@ -0,0 +1,562 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Macro.h"++#include "core/BrushLibrary.h"+#include "core/Pack.h"+#include "core/RadialMenu.h"+#include "core/Sha256.h"++#include <algorithm>+#include <cctype>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <set>++namespace sf {++namespace fs = std::filesystem;++namespace {++fs::path u8path(const std::string& p) { return fs::path(std::u8string(p.begin(), p.end())); }+std::string u8str(const fs::path& p) {+ const std::u8string s = p.u8string();+ return std::string(s.begin(), s.end());+}+std::string lowerAscii(std::string s) {+ for (char& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));+ return s;+}+std::string trim(const std::string& s) {+ const size_t a = s.find_first_not_of(" \t\r");+ if (a == std::string::npos) return "";+ return s.substr(a, s.find_last_not_of(" \t\r") - a + 1);+}++std::string g_macroDir;++// Commands a macro may never run: they reach the network, start or talk to another program, change what is+// installed, or run macros themselves.+const std::set<std::string>& deniedCommands() {+ static const std::set<std::string> kDenied = {+ "brush_ai", "brush_gallery_install", "brush_gallery_search", "comfyui_check", "image_to_3d",+ "text_to_3d", "splat_train", "splat_train_cancel", "blender_send", "blender_receive",+ "maya_send", "maya_receive", "goz_send", "goz_receive", "unreal_send",+ "unreal_editors", "blender_keymap_import", "macro_run", "macro_list", "macro_check",+ "pack_install", "pack_remove", "pack_enable", "pack_disable", "pack_list",+ "pack_create", "calibrate"};+ return kDenied;+}+// Parameters a macro may never set (network addresses, programs to start).+bool deniedParam(const std::string& p) {+ return p == "url" || p == "endpoint" || p == "gallery" || p == "zbrush" || p == "workflow" || p == "launch" ||+ p == "provider" || p == "service";+}++} // namespace++MacroPathKind macroPathKind(const std::string& command, const std::string& param) {+ const bool folder = param == "folder" || param == "out" || param == "dir" || param == "directory" ||+ (param.size() > 7 && param.compare(param.size() - 7, 7, "_folder") == 0);+ if (folder) return MacroPathKind::Folder;+ const bool file = param == "path" || param == "file" || param == "exr" || param == "output" ||+ (param.size() > 5 && param.compare(param.size() - 5, 5, "_path") == 0) ||+ (param.size() > 5 && param.compare(param.size() - 5, 5, "_file") == 0);+ if (!file) return MacroPathKind::None;+ const bool save = command.find("export") != std::string::npos || command.find("save") != std::string::npos ||+ command.rfind("capture_", 0) == 0 || command == "vdm_capture" || param == "exr" ||+ param == "output";+ return save ? MacroPathKind::Save : MacroPathKind::Open;+}++bool macroCommandAllowed(const std::string& command, std::string* why) {+ auto no = [&](const std::string& reason) {+ if (why) *why = reason;+ return false;+ };+ if (deniedCommands().count(command)) {+ if (command.rfind("macro_", 0) == 0) return no("a macro can't run macros");+ if (command.rfind("pack_", 0) == 0) return no("a macro can't install, list or remove packs");+ return no("it reaches the network or another program, which macros never do");+ }+ static const char* kPrefixes[] = {"ai_", "phone_", "link_", "unreal_", "comfyui", "gallery_", "mcp_"};+ for (const char* p : kPrefixes)+ if (command.rfind(p, 0) == 0) return no("it reaches the network or another program, which macros never do");+ return true;+}++bool macroPathValueOk(const std::string& v, std::string& error) {+ if (v == kMacroAsk) return true;+ if (v.empty()) {+ error = "an empty file name";+ return false;+ }+ if (v.size() > 260 || radialCleanText(v, v.size() + 1) != v) {+ error = "a file name with control characters or invalid text";+ return false;+ }+ if (v[0] == '/' || v[0] == '\\' || v.find(':') != std::string::npos || v[0] == '~' || v[0] == '$' || v[0] == '%') {+ error = "\"" + v + "\" is not inside the project folder: macros only use files relative to the project or \"?\" "+ "(asks when the macro runs)";+ return false;+ }+ for (size_t start = 0; start <= v.size();) {+ size_t end = v.find_first_of("/\\", start);+ if (end == std::string::npos) end = v.size();+ if (v.compare(start, end - start, "..") == 0) {+ error = "\"" + v + "\" leaves the project folder ('..')";+ return false;+ }+ start = end + 1;+ }+ return true;+}++bool resolveMacroPath(const std::string& projectDir, const std::string& relative, std::string& out, std::string& error) {+ if (!macroPathValueOk(relative, error)) return false;+ if (relative == kMacroAsk) {+ error = "\"?\" must be answered in a file dialog";+ return false;+ }+ if (projectDir.empty()) {+ error = "\"" + relative + "\" is relative to the project folder: save the project first";+ return false;+ }+ std::error_code ec;+ const fs::path root = fs::weakly_canonical(u8path(projectDir), ec);+ if (ec || !fs::is_directory(root, ec)) {+ error = "The project folder " + projectDir + " doesn't exist";+ return false;+ }+ const fs::path full = fs::weakly_canonical(root / u8path(relative), ec);+ if (ec) {+ error = "Cannot resolve " + relative;+ return false;+ }+ // Inside the project folder even after following symbolic links.+ const fs::path rel = full.lexically_relative(root);+ const std::string r = u8str(rel);+ if (rel.empty() || r == ".." || r.rfind("../", 0) == 0 || r.rfind("..\\", 0) == 0) {+ error = "\"" + relative + "\" leads outside the project folder";+ return false;+ }+ out = u8str(full);+ return true;+}++bool parseMacro(const std::string& text, const CommandRegistry* registry, Macro& out, std::string& error,+ const std::string& name) {+ out = {};+ out.name = name;+ out.text = text;+ if (text.size() > kMaxMacroFileSize) {+ error = "The macro is too long (at most 64 KB)";+ return false;+ }+ if (text.find('\0') != std::string::npos) {+ error = "The macro holds a NUL character: not a text file";+ return false;+ }+ // The header: the leading comment lines.+ size_t at = 0;+ while (at < text.size()) {+ size_t end = text.find('\n', at);+ if (end == std::string::npos) end = text.size();+ const std::string line = trim(text.substr(at, end - at));+ if (!line.empty() && line[0] != '#') break;+ auto key = [&](const char* k, std::string& to) {+ const std::string prefix = std::string("# ") + k + ":";+ if (line.compare(0, prefix.size(), prefix) == 0) to = radialCleanText(trim(line.substr(prefix.size())), 200);+ };+ key("name", out.name);+ key("description", out.description);+ at = end + 1;+ }+ if (trim(out.name).empty()) out.name = name;+ std::string err;+ if (!parseScript(text, out.statements, err)) {+ error = err;+ return false;+ }+ if (out.statements.size() > kMaxMacroStatements) {+ error = "The macro has too many commands (at most " + std::to_string(kMaxMacroStatements) + ")";+ return false;+ }+ if (out.statements.empty()) {+ error = "The macro has no commands";+ return false;+ }+ for (ScriptStatement& st : out.statements) {+ const std::string where = "Line " + std::to_string(st.line) + " (" + radialCleanText(st.command, 40) + "): ";+ std::string why;+ if (!macroCommandAllowed(st.command, &why)) {+ error = where + "not allowed in a macro: " + why;+ return false;+ }+ const Command* cmd = registry ? registry->find(st.command) : nullptr;+ if (registry && !cmd) {+ error = where + "unknown command";+ return false;+ }+ if (!registry) {+ bool idOk = !st.command.empty() && st.command.size() <= 64;+ for (unsigned char c : st.command) idOk = idOk && (std::islower(c) || std::isdigit(c) || c == '_');+ if (!idOk) {+ error = where + "not a command name";+ return false;+ }+ }+ for (auto& [key, value] : st.args) {+ if (deniedParam(key)) {+ error = where + key + "= is not allowed in a macro (network addresses and programs)";+ return false;+ }+ const ParamSpec* spec = nullptr;+ if (cmd)+ for (const ParamSpec& p : cmd->params)+ if (p.name == key) spec = &p;+ if (cmd && !spec) {+ error = where + "unknown parameter " + key + "=";+ return false;+ }+ if (spec) {+ using T = ParamSpec::Type;+ if (spec->type == T::String && !std::holds_alternative<std::string>(value))+ value = formatValue(value); // name=12: the text "12"+ else if (spec->type == T::Number && !std::holds_alternative<double>(value)) {+ error = where + key + "= must be a number";+ return false;+ } else if (spec->type == T::Bool && !std::holds_alternative<bool>(value)) {+ error = where + key + "= must be true or false";+ return false;+ }+ }+ const MacroPathKind kind = macroPathKind(st.command, key);+ if (kind != MacroPathKind::None) {+ if (!std::holds_alternative<std::string>(value)) value = formatValue(value);+ std::string perr;+ if (!macroPathValueOk(std::get<std::string>(value), perr)) {+ error = where + key + "=: " + perr;+ return false;+ }+ } else if (const auto* s = std::get_if<std::string>(&value);+ s && (key == "preset") && (s->find('/') != std::string::npos || s->find('\\') != std::string::npos ||+ lowerAscii(*s).find(".json") != std::string::npos)) {+ error = where + "preset= may only name a built-in preset in a macro";+ return false;+ }+ }+ if (cmd)+ for (const ParamSpec& p : cmd->params)+ if (p.required && !st.args.count(p.name)) {+ error = where + "needs " + p.name + "=";+ return false;+ }+ }+ return true;+}++bool readMacroFile(const std::string& path, const CommandRegistry* registry, Macro& out, std::string& error) {+ std::error_code ec;+ const fs::path p = u8path(path);+ if (!fs::is_regular_file(p, ec)) {+ error = "Cannot read " + path;+ return false;+ }+ if (fs::file_size(p, ec) > kMaxMacroFileSize) {+ error = path + " is too long for a macro (at most 64 KB)";+ return false;+ }+ std::ifstream f(p, std::ios::binary);+ std::string text(kMaxMacroFileSize + 1, '\0');+ f.read(text.data(), std::streamsize(text.size()));+ text.resize(size_t(std::max<std::streamsize>(f.gcount(), 0)));+ if (!parseMacro(text, registry, out, error, u8str(p.stem()))) return false;+ out.path = path;+ return true;+}++std::string macroFileText(const std::string& name, const std::string& description, const std::vector<std::string>& lines) {+ std::string out = "# name: " + radialCleanText(name, 200) + "\n";+ if (!description.empty()) out += "# description: " + radialCleanText(description, 200) + "\n";+ for (const std::string& l : lines) out += l + "\n";+ return out;+}++std::string macroFileName(const std::string& name) {+ std::string f = brushFileName(name); // the same rules: safe on every OS+ return f.substr(0, f.size() - std::strlen(".sfbrush")) + kMacroExtension;+}++// ---------------------------------------------------------------------------+// Undo as one step+// ---------------------------------------------------------------------------++MacroUndoGroup::MacroUndoGroup(const Document& doc)+ : subtoolId_(doc.activeSubtoolInfo().id), subtools_(doc.subtoolCount()), undoCount_(doc.undo.undoCount()),+ revision_(doc.undo.revision()) {}++bool MacroUndoGroup::end(Document& doc, const std::string& label) {+ if (!enabled_ || doc.subtoolCount() != subtools_ || doc.activeSubtoolInfo().id != subtoolId_) return false;+ const size_t now = doc.undo.undoCount();+ if (now < undoCount_ + 2) return false; // nothing to fold+ const size_t k = now - undoCount_;+ if (doc.undo.revision() - revision_ != k) return false; // steps were undone, redone or dropped meanwhile+ if (doc.mesh.multires || doc.mesh.micro) return false;+ for (size_t i = 0; i < k; ++i) {+ const UndoRecord* r = doc.undo.undoStep(i);+ if (!r || r->subtool || r->subdiv || r->micro || r->texture || r->textureTiles) return false;+ }+ Mesh after = doc.mesh;+ for (size_t i = 0; i < k; ++i)+ if (!doc.undo.undo(doc.mesh, doc.bvh)) return false;+ doc.replaceMeshUndoable(std::move(after), label);+ return true;+}++MacroRunResult runMacro(Document& doc, const CommandRegistry& registry, const Macro& macro, const MacroRunContext& ctx) {+ MacroRunResult result;+ std::string err;+ Macro checked;+ if (!parseMacro(macro.text, ®istry, checked, err, macro.name)) { // (again: the registry may know more now)+ result.ok = false;+ result.message = macro.name + ": " + err;+ return result;+ }+ MacroUndoGroup group(doc);+ for (const ScriptStatement& st : checked.statements) {+ Args args = st.args;+ for (auto& [key, value] : args) {+ const MacroPathKind kind = macroPathKind(st.command, key);+ if (kind == MacroPathKind::None) continue;+ const std::string v = std::get<std::string>(value);+ std::string resolved;+ if (v == kMacroAsk) {+ resolved = ctx.askPath ? ctx.askPath(st.command, key, kind) : std::string();+ if (resolved.empty()) {+ result.ok = false;+ result.message = macro.name + ", line " + std::to_string(st.line) + ": " ++ (ctx.askPath ? "no file picked; the macro stopped"+ : st.command + " asks for a file (\"?\"), which only the app can do");+ group.end(doc, "Macro: " + macro.name);+ return result;+ }+ } else if (!resolveMacroPath(ctx.projectDir, v, resolved, err)) {+ result.ok = false;+ result.message = macro.name + ", line " + std::to_string(st.line) + ": " + err;+ group.end(doc, "Macro: " + macro.name);+ return result;+ }+ value = resolved;+ }+ if (st.command == "undo" || st.command == "redo") group.disable();+ const CommandResult r = ctx.execute ? ctx.execute(st.command, args) : registry.execute(doc, st.command, args);+ if (!r.ok) {+ result.ok = false;+ result.message = macro.name + ", line " + std::to_string(st.line) + " (" + st.command + "): " + r.message;+ group.end(doc, "Macro: " + macro.name);+ return result;+ }+ ++result.ran;+ }+ result.oneUndoStep = group.end(doc, "Macro: " + macro.name);+ result.message = "Ran macro " + macro.name + " (" + std::to_string(result.ran) ++ (result.ran == 1 ? " command" : " commands") + (result.oneUndoStep ? ", one undo step)" : ")");+ return result;+}++std::vector<MacroAsk> macroAsks(const Macro& macro) {+ std::vector<MacroAsk> out;+ for (const ScriptStatement& st : macro.statements)+ for (const auto& [key, value] : st.args)+ if (const auto* s = std::get_if<std::string>(&value);+ s && *s == kMacroAsk && macroPathKind(st.command, key) != MacroPathKind::None)+ out.push_back({st.line, st.command, key, macroPathKind(st.command, key)});+ return out;+}++// ---------------------------------------------------------------------------+// Recording+// ---------------------------------------------------------------------------++void MacroRecorder::start() {+ active_ = true;+ lines_.clear();+ skipped_ = 0;+}++void MacroRecorder::record(const std::string& command, const Args& args, const std::string& projectDir) {+ if (!active_) return;+ if (!macroCommandAllowed(command)) {+ ++skipped_;+ return;+ }+ Args a;+ for (const auto& [key, value] : args) {+ if (deniedParam(key)) continue;+ if (macroPathKind(command, key) == MacroPathKind::None || !std::holds_alternative<std::string>(value)) {+ a[key] = value;+ continue;+ }+ // A file inside the project folder stays as a relative path; any other file is asked for when it runs.+ std::string v = kMacroAsk;+ const std::string& s = std::get<std::string>(value);+ std::error_code ec;+ if (!projectDir.empty() && !s.empty()) {+ const fs::path root = fs::weakly_canonical(u8path(projectDir), ec);+ const fs::path full = fs::weakly_canonical(u8path(s), ec);+ const fs::path rel = full.lexically_relative(root);+ const std::u8string g = rel.generic_u8string();+ const std::string r(g.begin(), g.end());+ std::string perr;+ if (!ec && !r.empty() && r != "." && r.rfind("..", 0) != 0 && macroPathValueOk(r, perr)) v = r;+ }+ a[key] = v;+ }+ lines_.push_back(formatStatement(command, a));+}++// ---------------------------------------------------------------------------+// Library+// ---------------------------------------------------------------------------++std::string userMacroDir() {+ if (!g_macroDir.empty()) return g_macroDir;+ const std::string data = appDataDir();+ return data.empty() ? std::string() : u8str(u8path(data) / "macros");+}+void setUserMacroDir(const std::string& dir) { g_macroDir = dir; }++std::vector<Macro> listMacros(const CommandRegistry* registry, std::vector<std::string>* messages) {+ std::vector<Macro> out;+ const std::string dir = userMacroDir();+ std::vector<std::string> files;+ std::error_code ec;+ if (!dir.empty())+ for (fs::directory_iterator it(u8path(dir), ec), end; !ec && it != end; it.increment(ec)) {+ std::error_code e2;+ if (it->is_regular_file(e2) && lowerAscii(u8str(it->path().extension())) == kMacroExtension)+ files.push_back(u8str(it->path()));+ }+ std::sort(files.begin(), files.end());+ for (const std::string& f : files) {+ Macro m;+ std::string err;+ if (readMacroFile(f, registry, m, err)) out.push_back(std::move(m));+ else if (messages) messages->push_back("Skipped macro " + f + ": " + err);+ }+ for (const PackContentItem& item : enabledPackItems(PackItemType::Macro)) {+ Macro m;+ std::string err;+ if (!readMacroFile(item.file, registry, m, err)) {+ if (messages) messages->push_back("Skipped macro " + item.file + " (pack " + item.packName + "): " + err);+ continue;+ }+ m.pack = item.packName;+ out.push_back(std::move(m));+ }+ std::stable_sort(out.begin(), out.end(), [](const Macro& a, const Macro& b) {+ return lowerAscii(a.name) < lowerAscii(b.name);+ });+ return out;+}++bool findMacro(const std::string& name, const CommandRegistry* registry, Macro& out, std::string& error) {+ std::vector<std::string> messages;+ const std::string want = lowerAscii(trim(name));+ for (Macro& m : listMacros(registry, &messages)) {+ const std::string label = lowerAscii(m.pack.empty() ? m.name : m.name + " (" + m.pack + ")");+ if (label == want || (m.pack.empty() && lowerAscii(m.name) == want)) {+ out = std::move(m);+ return true;+ }+ }+ for (Macro& m : listMacros(registry))+ if (lowerAscii(m.name) == want) {+ out = std::move(m);+ return true;+ }+ error = "No macro called \"" + radialCleanText(name, 64) + "\"";+ for (const std::string& m : messages) error += "; " + m;+ return false;+}++namespace {+fs::path confirmedPath() { return u8path(userMacroDir()) / "confirmed.txt"; }+} // namespace++bool macroConfirmed(const std::string& text) {+ if (userMacroDir().empty()) return false;+ std::ifstream f(confirmedPath(), std::ios::binary);+ const std::string want = sha256Hex(text);+ std::string line;+ int lines = 0;+ while (std::getline(f, line) && ++lines < 100000)+ if (trim(line) == want) return true;+ return false;+}++void setMacroConfirmed(const std::string& text) {+ if (userMacroDir().empty() || macroConfirmed(text)) return;+ std::error_code ec;+ fs::create_directories(u8path(userMacroDir()), ec);+ std::ofstream f(confirmedPath(), std::ios::binary | std::ios::app);+ f << sha256Hex(text) << "\n";+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++void registerMacroCommands(CommandRegistry& registry) {+ using T = ParamSpec::Type;+ const CommandRegistry* reg = ®istry;+ registry.add({"macro_run",+ "Run a macro (.sfmacro): a list of SculptForge commands. Its file values are relative to the project "+ "folder (the folder of `project`, else of the open project) or \"?\", which only the app can answer. "+ "Edits on one Part become one undo step. The app shows a macro's commands and asks before it first runs.",+ {{"path", T::String, "The .sfmacro file (or give name=).", false},+ {"name", T::String, "A macro in your macros folder or an enabled pack, by name.", false},+ {"project", T::String, "The project folder relative file values resolve in.", false}},+ [reg](Document& doc, const Args& a) -> CommandResult {+ Macro m;+ std::string err;+ const std::string path = argString(a, "path"), name = argString(a, "name");+ if (path.empty() && name.empty()) return {false, "Give path= (a .sfmacro file) or name="};+ if (!path.empty() ? !readMacroFile(path, reg, m, err) : !findMacro(name, reg, m, err))+ return {false, err};+ MacroRunContext ctx;+ ctx.projectDir = argString(a, "project");+ if (ctx.projectDir.empty() && !doc.path.empty())+ ctx.projectDir = u8str(u8path(doc.path).parent_path());+ const MacroRunResult r = runMacro(doc, *reg, m, ctx);+ return {r.ok, r.message};+ }});+ registry.add({"macro_list", "List the macros: your own (in the macros folder) and those of enabled packs.", {},+ [reg](Document&, const Args&) -> CommandResult {+ std::vector<std::string> messages;+ const auto macros = listMacros(reg, &messages);+ std::string out = macros.empty() ? "No macros"+ : std::to_string(macros.size()) + (macros.size() == 1 ? " macro" : " macros");+ for (const Macro& m : macros)+ out += "\n" + m.name + (m.pack.empty() ? "" : " (" + m.pack + ")") + ": " ++ std::to_string(m.statements.size()) + " commands" ++ (m.description.empty() ? "" : " - " + m.description);+ for (const std::string& msg : messages) out += "\n" + msg;+ return {true, out};+ }});+ registry.add({"macro_check", "Check a macro without running it: every command known and allowed, file values confined.",+ {{"path", T::String, "The .sfmacro file.", false}, {"text", T::String, "The macro's text instead.", false}},+ [reg](Document&, const Args& a) -> CommandResult {+ Macro m;+ std::string err;+ const bool ok = a.count("text") ? parseMacro(argString(a, "text"), reg, m, err)+ : readMacroFile(argString(a, "path"), reg, m, err);+ if (!ok) return {false, err};+ return {true, m.name + ": " + std::to_string(m.statements.size()) + " commands, all allowed"};+ }});+}++} // namespace sfdiff --git a/src/core/Macro.h b/src/core/Macro.hnew file mode 100644index 00000000..7a201792--- /dev/null+++ b/src/core/Macro.h@@ -0,0 +1,149 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Macros (.sfmacro): a list of SculptForge's own commands in the command language of core/Script.h, one per line,+// '#' comments. A macro is data, never code: it can only run commands from the registry, and not every command:+// nothing that reaches the network, starts another program, installs or removes packs, or runs another macro+// (macroCommandAllowed). Values of file parameters (path=, folder=, ...) must be either+// - a relative path, resolved inside the project folder (no absolute paths, drive letters, '~' or '..'), or+// - "?" : ask, in a file dialog when the macro runs.+// so a macro never names an arbitrary file baked into it. Optional header lines:+// # name: Clean Up Scan+// # description: Remesh, smooth and export a GLB next to the project+// The app shows a macro's full command list and asks before it first runs (and again after it changed; the+// confirmation is kept by the text's SHA-256). sculptforge-cli and the Python module run what the user asked.+#pragma once++#include "core/Commands.h"+#include "core/Script.h"++#include <functional>+#include <string>+#include <vector>++namespace sf {++constexpr const char* kMacroExtension = ".sfmacro";+constexpr size_t kMaxMacroFileSize = 64 * 1024;+constexpr size_t kMaxMacroStatements = 500;+constexpr const char* kMacroAsk = "?"; // a file value that asks when the macro runs++struct Macro {+ std::string name; // header "# name:", else the file name without its extension+ std::string description; // header "# description:"+ std::string text; // the whole file+ std::vector<ScriptStatement> statements;+ std::string path; // the file it came from (empty: typed or recorded)+ std::string pack; // the pack it came with (its name), "" for the user's own+};++// What kind of file a parameter names: None for parameters that aren't files.+enum class MacroPathKind { None, Open, Save, Folder };+MacroPathKind macroPathKind(const std::string& command, const std::string& param);++// Whether a macro may run COMMAND (WHY says why not).+bool macroCommandAllowed(const std::string& command, std::string* why = nullptr);++// A file value as a macro may hold it: "?" or a confined relative path. False with ERROR otherwise.+bool macroPathValueOk(const std::string& value, std::string& error);+// Resolves a confined relative path inside PROJECTDIR (which must exist). Symbolic links on the way are followed+// and the result must still lie inside the project folder.+bool resolveMacroPath(const std::string& projectDir, const std::string& relative, std::string& out, std::string& error);++// Parses TEXT: size and statement caps, the command language, the header, and for every statement: a command the+// REGISTRY knows (null: any name; packs are checked without the app's registry), allowed in macros, with its+// required parameters, no unknown parameters, values of the right type, and confined file values. ERROR names the+// line. NAME is the fallback name (the file stem).+bool parseMacro(const std::string& text, const CommandRegistry* registry, Macro& out, std::string& error,+ const std::string& name = "Macro");+// Reads and parses a .sfmacro file (size-capped).+bool readMacroFile(const std::string& path, const CommandRegistry* registry, Macro& out, std::string& error);+// The macro's file text with a fresh header: "# name: ...", "# description: ...", then the statements.+std::string macroFileText(const std::string& name, const std::string& description,+ const std::vector<std::string>& lines);+// "<name>.sfmacro" made safe on every OS.+std::string macroFileName(const std::string& name);++// --- Running ---++struct MacroRunContext {+ std::string projectDir; // folder of the saved project (relative file values resolve here); "" = none+ // Asks for a file for COMMAND's PARAM (a dialog in the app); returns "" when cancelled. Null: "?" values fail.+ std::function<std::string(const std::string& command, const std::string& param, MacroPathKind kind)> askPath;+ // Runs one command (the app's runCommand); null: registry.execute.+ std::function<CommandResult(const std::string& command, const Args& args)> execute;+};++struct MacroRunResult {+ bool ok = true;+ std::string message;+ int ran = 0; // statements that ran+ bool oneUndoStep = false; // the macro's edits were folded into one undo step+};++// Folds the undo steps a macro made on the active Part into one, when it can: the same Part is active before and+// after, the Parts weren't added or removed, and none of the steps is a level, micro, texture or Part step.+class MacroUndoGroup {+public:+ explicit MacroUndoGroup(const Document& doc);+ bool end(Document& doc, const std::string& label); // true when the steps became one+ void disable() { enabled_ = false; } // the macro ran undo / redo itself: leave its steps alone++private:+ uint32_t subtoolId_ = 0;+ int subtools_ = 0;+ size_t undoCount_ = 0;+ uint64_t revision_ = 0;+ bool enabled_ = true;+};++// The "?" values a macro will ask for, in the order runMacro asks (the app opens its dialogs first).+struct MacroAsk {+ int line = 0;+ std::string command, param;+ MacroPathKind kind = MacroPathKind::Open;+};+std::vector<MacroAsk> macroAsks(const Macro& macro);++// Runs every statement in order, stopping at the first failure; file values are resolved first ("?" asks).+MacroRunResult runMacro(Document& doc, const CommandRegistry& registry, const Macro& macro, const MacroRunContext& ctx);++// --- Recording ---++// Turns the commands the user runs into macro lines: commands macros may not run are left out, file values+// inside PROJECTDIR become relative paths and any other file becomes "?" (asked when the macro runs).+class MacroRecorder {+public:+ void start();+ void stop() { active_ = false; }+ bool active() const { return active_; }+ void record(const std::string& command, const Args& args, const std::string& projectDir);+ const std::vector<std::string>& lines() const { return lines_; }+ int skipped() const { return skipped_; }++private:+ bool active_ = false;+ std::vector<std::string> lines_;+ int skipped_ = 0;+};++// --- Library ---++// <app data>/macros: the user's own macros (empty when there is no app data folder).+std::string userMacroDir();+// Overrides userMacroDir() (UI tests, unit tests); "" = the default.+void setUserMacroDir(const std::string& dir);+// The user's macros, then every enabled pack's (core/Pack.h), sorted by name; files that can't be read are skipped+// with a message.+std::vector<Macro> listMacros(const CommandRegistry* registry, std::vector<std::string>* messages = nullptr);+// The macro called NAME (any case; "Name (Pack)" picks a pack's), or false.+bool findMacro(const std::string& name, const CommandRegistry* registry, Macro& out, std::string& error);++// Whether the user confirmed this exact macro text before (kept in <macros>/confirmed.txt by SHA-256).+bool macroConfirmed(const std::string& text);+void setMacroConfirmed(const std::string& text);++// macro_run, macro_list, macro_check.+void registerMacroCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/Pack.cpp b/src/core/Pack.cppnew file mode 100644index 00000000..63663e64--- /dev/null+++ b/src/core/Pack.cpp@@ -0,0 +1,1372 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Pack.h"++#include "core/BrushLibrary.h"+#include "core/BrushRecipe.h"+#include "core/Commands.h"+#include "core/Image.h"+#include "core/Macro.h"+#include "core/MaterialRecipe.h"+#include "core/RadialMenu.h"+#include "core/UpdateCheck.h"+#include "core/Vdm.h"+#include "io/Zip.h"++#include <stb_image.h>++#include <algorithm>+#include <cctype>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <map>+#include <set>++#ifndef SCULPTFORGE_VERSION+#define SCULPTFORGE_VERSION "0.0.0"+#endif++namespace sf {++namespace fs = std::filesystem;++namespace {++fs::path u8path(const std::string& p) { return fs::path(std::u8string(p.begin(), p.end())); }+std::string u8str(const fs::path& p) {+ const std::u8string s = p.u8string();+ return std::string(s.begin(), s.end());+}+std::string lowerAscii(std::string s) {+ for (char& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));+ return s;+}+std::string extensionOf(const std::string& name) {+ const size_t slash = name.find_last_of('/');+ const size_t dot = name.find_last_of('.');+ if (dot == std::string::npos || (slash != std::string::npos && dot < slash)) return "";+ return lowerAscii(name.substr(dot));+}+std::string stemOf(const std::string& name) {+ std::string file = name.substr(name.find_last_of('/') == std::string::npos ? 0 : name.find_last_of('/') + 1);+ const size_t dot = file.find_last_of('.');+ return dot == std::string::npos || dot == 0 ? file : file.substr(0, dot);+}+std::string text(const std::vector<uint8_t>& data) { return std::string(data.begin(), data.end()); }++std::string g_packsRoot;+bool g_safeMode = false;++uint16_t rd16(const uint8_t* p) { return uint16_t(p[0] | p[1] << 8); }+uint32_t rd32(const uint8_t* p) { return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; }++bool readWholeFile(const std::string& path, std::vector<uint8_t>& out, uint64_t cap, std::string& error) {+ std::error_code ec;+ const fs::path p = u8path(path);+ if (fs::is_symlink(fs::symlink_status(p, ec))) {+ error = path + " is a symbolic link";+ return false;+ }+ if (!fs::is_regular_file(p, ec)) {+ error = "Cannot read " + path;+ return false;+ }+ const uint64_t size = fs::file_size(p, ec);+ if (ec) {+ error = "Cannot read " + path;+ return false;+ }+ if (size > cap) {+ error = fs::path(p).filename().string() + " is too big (" + std::to_string(size >> 20) + " MB; at most " ++ std::to_string(cap >> 20) + " MB)";+ return false;+ }+ std::ifstream f(p, std::ios::binary);+ out.resize(size_t(size));+ if (!f || (size && !f.read(reinterpret_cast<char*>(out.data()), std::streamsize(size)))) {+ error = "Cannot read " + path;+ return false;+ }+ return true;+}++// Text a pack shows (names, author, license, description): valid UTF-8, no control characters (newlines and tabs+// allowed when MULTILINE), at most MAXBYTES.+bool cleanTextOk(const std::string& s, size_t maxBytes, bool multiline) {+ if (s.size() > maxBytes) return false;+ std::string flat = s;+ if (multiline)+ for (char& c : flat)+ if (c == '\n' || c == '\t' || c == '\r') c = ' ';+ return radialCleanText(flat, maxBytes + 1) == flat;+}++bool windowsReserved(const std::string& component) {+ std::string base = component.substr(0, component.find('.'));+ while (!base.empty() && base.back() == ' ') base.pop_back();+ for (char& c : base) c = char(std::toupper(static_cast<unsigned char>(c)));+ static const char* kReserved[] = {"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4",+ "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3",+ "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "CONIN$", "CONOUT$"};+ for (const char* r : kReserved)+ if (base == r) return true;+ return false;+}++bool packIdOk(const std::string& id) {+ if (id.empty() || id.size() > 64 || id.find("..") != std::string::npos) return false;+ if (!std::isalnum(static_cast<unsigned char>(id[0])) || id.back() == '.') return false;+ for (unsigned char c : id)+ if (!(std::islower(c) || std::isdigit(c) || c == '.' || c == '_' || c == '-')) return false;+ return !windowsReserved(id);+}++bool versionOk(const std::string& v) {+ if (v.empty() || v.size() > 32 || !std::isdigit(static_cast<unsigned char>(v[0]))) return false;+ for (unsigned char c : v)+ if (!(std::isalnum(c) || c == '.' || c == '-' || c == '+')) return false;+ return true;+}++} // namespace++// ---------------------------------------------------------------------------+// Item types+// ---------------------------------------------------------------------------++const char* packItemTypeId(PackItemType t) {+ switch (t) {+ case PackItemType::Brush: return "brush";+ case PackItemType::Alpha: return "alpha";+ case PackItemType::Matcap: return "matcap";+ case PackItemType::Material: return "material";+ case PackItemType::Vdm: return "vdm";+ case PackItemType::Keymap: return "keymap";+ case PackItemType::PieMenu: return "piemenu";+ case PackItemType::Macro: return "macro";+ case PackItemType::Count: break;+ }+ return "";+}++const char* packItemFolder(PackItemType t) {+ switch (t) {+ case PackItemType::Brush: return "brushes";+ case PackItemType::Alpha: return "alphas";+ case PackItemType::Matcap: return "matcaps";+ case PackItemType::Material: return "materials";+ case PackItemType::Vdm: return "vdms";+ case PackItemType::Keymap: return "keymaps";+ case PackItemType::PieMenu: return "piemenus";+ case PackItemType::Macro: return "macros";+ case PackItemType::Count: break;+ }+ return "";+}++const char* packItemLabel(PackItemType t, int count) {+ const bool one = count == 1;+ switch (t) {+ case PackItemType::Brush: return one ? "brush" : "brushes";+ case PackItemType::Alpha: return one ? "alpha" : "alphas";+ case PackItemType::Matcap: return one ? "Lit Sphere" : "Lit Spheres";+ case PackItemType::Material: return one ? "Material Recipe" : "Material Recipes";+ case PackItemType::Vdm: return one ? "VDM" : "VDMs";+ case PackItemType::Keymap: return one ? "keymap" : "keymaps";+ case PackItemType::PieMenu: return one ? "pie menu" : "pie menus";+ case PackItemType::Macro: return one ? "macro" : "macros";+ case PackItemType::Count: break;+ }+ return "";+}++bool packItemTypeFromId(const std::string& id, PackItemType& out) {+ for (int i = 0; i < kPackItemTypes; ++i)+ if (id == packItemTypeId(PackItemType(i))) {+ out = PackItemType(i);+ return true;+ }+ return false;+}++bool packItemExtensionOk(PackItemType t, const std::string& fileName) {+ const std::string ext = extensionOf(fileName);+ switch (t) {+ case PackItemType::Brush: return ext == ".sfbrush";+ case PackItemType::Alpha:+ case PackItemType::Matcap: return ext == ".png" || ext == ".jpg" || ext == ".jpeg";+ case PackItemType::Material: return ext == kMaterialRecipeExtension;+ case PackItemType::Vdm: return ext == ".sfvdm";+ case PackItemType::Keymap:+ case PackItemType::PieMenu: return ext == ".json";+ case PackItemType::Macro: return ext == kMacroExtension;+ case PackItemType::Count: break;+ }+ return false;+}++std::string packCountsText(const std::array<int, kPackItemTypes>& counts) {+ std::string out;+ for (int i = 0; i < kPackItemTypes; ++i) {+ if (!counts[size_t(i)]) continue;+ if (!out.empty()) out += ", ";+ out += std::to_string(counts[size_t(i)]) + " " + packItemLabel(PackItemType(i), counts[size_t(i)]);+ }+ return out.empty() ? "nothing" : out;+}++// ---------------------------------------------------------------------------+// Versions and the manifest+// ---------------------------------------------------------------------------++std::string appVersion() { return SCULPTFORGE_VERSION; }++bool parsePackManifest(const std::string& textIn, PackManifest& out, std::string& error) {+ out = {};+ if (textIn.size() > 64 * 1024) {+ error = "pack.json is too big (at most 64 KB)";+ return false;+ }+ Json j;+ std::string err;+ if (!Json::parseStrict(textIn, j, err)) {+ error = "pack.json is not valid JSON: " + err;+ return false;+ }+ if (!j.isObject()) {+ error = "pack.json must hold a JSON object";+ return false;+ }+ static const std::set<std::string> kKeys = {"format", "formatVersion", "id", "name", "version",+ "author", "license", "description", "minAppVersion",+ "preview", "channel", "contents"};+ for (const auto& [key, v] : j.members())+ if (!kKeys.count(key)) {+ error = "pack.json has an unknown key \"" + radialCleanText(key, 40) + "\"";+ return false;+ }+ auto str = [&](const char* key, bool required, size_t maxBytes, bool multiline, std::string& to) -> bool {+ const Json& v = j[key];+ if (v.isNull() && !j.has(key)) {+ if (required) error = std::string("pack.json is missing \"") + key + "\"";+ return !required;+ }+ if (!v.isString()) {+ error = std::string("pack.json: \"") + key + "\" must be a string";+ return false;+ }+ if (!cleanTextOk(v.asString(), maxBytes, multiline)) {+ error = std::string("pack.json: \"") + key + "\" is too long or holds control characters or invalid text";+ return false;+ }+ to = v.asString();+ if (required && to.empty()) {+ error = std::string("pack.json: \"") + key + "\" is empty";+ return false;+ }+ return true;+ };+ std::string format;+ if (!str("format", true, 32, false, format)) return false;+ if (format != "sculptforge-pack") {+ error = "pack.json: \"format\" must be \"sculptforge-pack\"";+ return false;+ }+ if (!j["formatVersion"].isNumber() || j["formatVersion"].asNumber() != double(kPackFormatVersion)) {+ error = "pack.json: \"formatVersion\" must be " + std::to_string(kPackFormatVersion) ++ " (a newer SculptForge may read this pack)";+ return false;+ }+ if (!str("id", true, 64, false, out.id) || !str("name", true, 64, false, out.name) ||+ !str("version", true, 32, false, out.version) || !str("author", true, 64, false, out.author) ||+ !str("license", true, 64, false, out.license) || !str("description", false, 1000, true, out.description) ||+ !str("minAppVersion", false, 32, false, out.minAppVersion) || !str("preview", false, 32, false, out.preview) ||+ !str("channel", false, 32, false, out.channel))+ return false;+ if (!packIdOk(out.id)) {+ error = "pack.json: \"id\" must be 1-64 lower-case letters, digits, '.', '_' or '-', starting with a letter or digit";+ return false;+ }+ if (!versionOk(out.version)) {+ error = "pack.json: \"version\" must look like 1.0 or 1.2.3";+ return false;+ }+ if (!out.minAppVersion.empty() && !versionOk(out.minAppVersion)) {+ error = "pack.json: \"minAppVersion\" must look like 0.10.6";+ return false;+ }+ if (!out.preview.empty() && out.preview != "preview.png" && out.preview != "preview.jpg") {+ error = "pack.json: \"preview\" must be preview.png or preview.jpg";+ return false;+ }+ for (unsigned char c : out.channel)+ if (!(std::islower(c) || std::isdigit(c) || c == '-')) {+ error = "pack.json: \"channel\" must be lower-case letters, digits or '-' (for example \"insider\")";+ return false;+ }+ const Json& contents = j["contents"];+ if (!contents.isArray()) {+ error = "pack.json: \"contents\" must be a list";+ return false;+ }+ if (contents.size() > PackLimits{}.entries) {+ error = "pack.json lists too many items";+ return false;+ }+ for (size_t i = 0; i < contents.size(); ++i) {+ const Json& it = contents[i];+ const std::string where = "pack.json: contents item " + std::to_string(i + 1);+ if (!it.isObject() || it.members().size() != 2 || !it["type"].isString() || !it["path"].isString()) {+ error = where + " must be {\"type\": ..., \"path\": ...}";+ return false;+ }+ PackItem item;+ if (!packItemTypeFromId(it["type"].asString(), item.type)) {+ error = where + " has an unknown type \"" + radialCleanText(it["type"].asString(), 40) + "\"";+ return false;+ }+ item.path = it["path"].asString();+ std::string nameErr;+ if (!packEntryNameOk(item.path, nameErr)) {+ error = where + ": " + nameErr;+ return false;+ }+ const std::string folder = std::string(packItemFolder(item.type)) + "/";+ if (item.path.compare(0, folder.size(), folder) != 0 || item.path.find('/', folder.size()) != std::string::npos ||+ item.path.size() == folder.size()) {+ error = where + ": a " + packItemTypeId(item.type) + " must be directly in " + folder;+ return false;+ }+ if (!packItemExtensionOk(item.type, item.path)) {+ error = where + ": " + radialCleanText(item.path, 80) + " is not a file type a " + packItemTypeId(item.type) ++ " may be";+ return false;+ }+ out.contents.push_back(std::move(item));+ }+ return true;+}++std::string packManifestText(const PackManifest& m) {+ Json j = Json::object();+ j.set("format", "sculptforge-pack");+ j.set("formatVersion", kPackFormatVersion);+ j.set("id", m.id);+ j.set("name", m.name);+ j.set("version", m.version);+ j.set("author", m.author);+ j.set("license", m.license);+ if (!m.description.empty()) j.set("description", m.description);+ if (!m.minAppVersion.empty()) j.set("minAppVersion", m.minAppVersion);+ if (!m.preview.empty()) j.set("preview", m.preview);+ if (!m.channel.empty()) j.set("channel", m.channel);+ Json contents = Json::array();+ for (const PackItem& it : m.contents) {+ Json e = Json::object();+ e.set("type", packItemTypeId(it.type));+ e.set("path", it.path);+ contents.push(std::move(e));+ }+ j.set("contents", std::move(contents));+ return j.dump(true) + "\n";+}++// ---------------------------------------------------------------------------+// The strict zip reader+// ---------------------------------------------------------------------------++bool packEntryNameOk(const std::string& name, std::string& error, size_t maxBytes) {+ const std::string shown = radialCleanText(name, 80);+ if (name.empty()) {+ error = "A file in the pack has no name";+ return false;+ }+ if (name.size() > maxBytes) {+ error = "\"" + shown + "...\" has too long a name";+ return false;+ }+ if (radialCleanText(name, name.size() + 1) != name) {+ error = "\"" + shown + "\" has control characters or invalid text in its name";+ return false;+ }+ if (name[0] == '/' || name.find('\\') != std::string::npos) {+ error = "\"" + shown + "\" is an absolute path or uses backslashes";+ return false;+ }+ if (name.find(':') != std::string::npos) {+ error = "\"" + shown + "\" names a drive or a stream (':')";+ return false;+ }+ if (name[0] == '~') {+ error = "\"" + shown + "\" points into a home folder";+ return false;+ }+ std::string body = name;+ if (body.back() == '/') body.pop_back(); // a folder entry+ size_t depth = 0;+ for (size_t start = 0; start <= body.size();) {+ const size_t end = std::min(body.find('/', start), body.size());+ const std::string part = body.substr(start, end - start);+ ++depth;+ if (part.empty()) {+ error = "\"" + shown + "\" has an empty path part";+ return false;+ }+ if (part == "." || part == "..") {+ error = "\"" + shown + "\" leaves its folder ('..')";+ return false;+ }+ if (part[0] == '.' || part[0] == ' ' || part.back() == '.' || part.back() == ' ') {+ error = "\"" + shown + "\" is a hidden name or starts or ends with a dot or space";+ return false;+ }+ for (char c : part)+ if (std::strchr("<>\"|?*", c)) {+ error = "\"" + shown + "\" has a character Windows can't hold in a file name";+ return false;+ }+ if (windowsReserved(part)) {+ error = "\"" + shown + "\" uses a name Windows reserves for devices";+ return false;+ }+ start = end + 1;+ }+ if (depth > 2) {+ error = "\"" + shown + "\" is nested too deep (packs hold folder/file at most)";+ return false;+ }+ return true;+}++bool readPackArchiveBytes(const std::vector<uint8_t>& b, std::vector<PackFile>& files, std::string& error,+ const PackLimits& limits) {+ files.clear();+ const size_t n = b.size();+ if (n > limits.archiveBytes) {+ error = "The pack is too big (at most " + std::to_string(limits.archiveBytes >> 20) + " MB)";+ return false;+ }+ // End of central directory: the last 22 bytes, or before a comment of up to 64 KB.+ if (n < 22) {+ error = "Not a pack: the file is not a zip archive";+ return false;+ }+ size_t eocd = std::string::npos;+ for (size_t back = 0; back <= std::min<size_t>(n - 22, 0xFFFF); ++back) {+ const size_t at = n - 22 - back;+ if (rd32(&b[at]) == 0x06054B50 && at + 22 + rd16(&b[at + 20]) == n) {+ eocd = at;+ break;+ }+ }+ if (eocd == std::string::npos) {+ error = "Not a pack: the file is not a zip archive (or has data after its end)";+ return false;+ }+ const uint8_t* e = &b[eocd];+ const uint16_t disk = rd16(e + 4), cdDisk = rd16(e + 6), here = rd16(e + 8), total = rd16(e + 10);+ const uint32_t cdSize = rd32(e + 12), cdOffset = rd32(e + 16);+ if (eocd >= 20 && rd32(&b[eocd - 20]) == 0x07064B50) {+ error = "The pack is a ZIP64 archive, which packs never need: refused";+ return false;+ }+ if (disk != 0 || cdDisk != 0 || here != total) {+ error = "The pack is split over several disks: refused";+ return false;+ }+ if (total == 0xFFFF || cdSize == 0xFFFFFFFFu || cdOffset == 0xFFFFFFFFu) {+ error = "The pack is a ZIP64 archive, which packs never need: refused";+ return false;+ }+ if (total > limits.entries) {+ error = "The pack holds too many files (" + std::to_string(total) + "; at most " + std::to_string(limits.entries) + ")";+ return false;+ }+ if (uint64_t(cdOffset) + cdSize != eocd) {+ error = "The pack's zip directory is damaged";+ return false;+ }++ struct Span {+ uint64_t begin, end;+ std::string name;+ };+ std::vector<Span> spans;+ std::set<std::string> seen; // lower-cased: names that differ only in case collide on Windows and macOS+ uint64_t totalUnpacked = 0, totalPacked = 0;+ size_t at = cdOffset;+ for (uint32_t k = 0; k < total; ++k) {+ if (at + 46 > eocd || rd32(&b[at]) != 0x02014B50) {+ error = "The pack's zip directory is damaged";+ return false;+ }+ const uint8_t* c = &b[at];+ const uint16_t madeBy = rd16(c + 4), flags = rd16(c + 8), method = rd16(c + 10);+ const uint32_t crc = rd32(c + 16), packed = rd32(c + 20), unpacked = rd32(c + 24);+ const uint16_t nameLen = rd16(c + 28), extraLen = rd16(c + 30), commentLen = rd16(c + 32), startDisk = rd16(c + 34);+ const uint32_t external = rd32(c + 38), local = rd32(c + 42);+ const size_t next = at + 46 + size_t(nameLen) + extraLen + commentLen;+ if (next > eocd) {+ error = "The pack's zip directory is damaged";+ return false;+ }+ std::string name(reinterpret_cast<const char*>(c + 46), nameLen);+ if (name.find('\0') != std::string::npos) {+ error = "A file name in the pack holds a NUL character: refused";+ return false;+ }+ std::string nameErr;+ if (!packEntryNameOk(name, nameErr, limits.nameBytes)) {+ error = nameErr;+ return false;+ }+ const std::string shown = radialCleanText(name, 80);+ const unsigned mode = external >> 16;+ const unsigned host = madeBy >> 8;+ if ((mode & 0170000) == 0120000) {+ error = "\"" + shown + "\" is a symbolic link: packs may hold plain files only";+ return false;+ }+ if (host == 3 && (mode & 0170000) != 0 && (mode & 0170000) != 0100000 && (mode & 0170000) != 0040000) {+ error = "\"" + shown + "\" is a device or other special file: refused";+ return false;+ }+ if (flags & 0x0041) {+ error = "\"" + shown + "\" is encrypted: packs are never encrypted";+ return false;+ }+ if (method != 0 && method != 8) {+ error = "\"" + shown + "\" uses a compression SculptForge doesn't read (only stored and deflate)";+ return false;+ }+ if (startDisk != 0 || packed == 0xFFFFFFFFu || unpacked == 0xFFFFFFFFu || local == 0xFFFFFFFFu) {+ error = "\"" + shown + "\" uses ZIP64 or several disks: refused";+ return false;+ }+ if (!seen.insert(lowerAscii(name.back() == '/' ? name.substr(0, name.size() - 1) : name)).second) {+ error = "\"" + shown + "\" is in the pack twice (names that differ only in case count as the same)";+ return false;+ }+ if (unpacked > limits.fileBytes) {+ error = "\"" + shown + "\" is too big unpacked (" + std::to_string(unpacked >> 20) + " MB; at most " ++ std::to_string(limits.fileBytes >> 20) + " MB)";+ return false;+ }+ totalUnpacked += unpacked;+ totalPacked += packed;+ if (totalUnpacked > limits.totalBytes) {+ error = "The pack is too big unpacked (at most " + std::to_string(limits.totalBytes >> 20) + " MB)";+ return false;+ }+ if (method == 0 && packed != unpacked) {+ error = "\"" + shown + "\" is damaged (its sizes disagree)";+ return false;+ }+ if (unpacked > 64 * 1024 && uint64_t(unpacked) > uint64_t(std::max<uint32_t>(packed, 1)) * limits.ratio) {+ error = "\"" + shown + "\" unpacks to more than " + std::to_string(limits.ratio) ++ " times its packed size (a zip bomb?): refused";+ return false;+ }+ // The local header must agree with the directory.+ if (uint64_t(local) + 30 > cdOffset || rd32(&b[local]) != 0x04034B50) {+ error = "\"" + shown + "\" is damaged (no local header)";+ return false;+ }+ const uint8_t* l = &b[local];+ const uint16_t localFlags = rd16(l + 6), localMethod = rd16(l + 8), localNameLen = rd16(l + 26),+ localExtra = rd16(l + 28);+ const uint64_t dataStart = uint64_t(local) + 30 + localNameLen + localExtra;+ const uint64_t dataEnd = dataStart + packed;+ if (dataEnd > cdOffset || localMethod != method || (localFlags & 0x0041) ||+ localNameLen != nameLen || std::memcmp(l + 30, name.data(), nameLen) != 0) {+ error = "\"" + shown + "\" is damaged (its local header disagrees with the directory)";+ return false;+ }+ spans.push_back({local, dataEnd + ((localFlags & 0x0008) ? 12 : 0), name}); // (a data descriptor: 12 bytes at least)+ if (name.back() == '/') {+ if (unpacked != 0) {+ error = "\"" + shown + "\" is a folder with data: refused";+ return false;+ }+ } else {+ PackFile f;+ f.name = name;+ f.data.resize(unpacked);+ const uint8_t* src = &b[size_t(dataStart)];+ if (method == 0) {+ if (unpacked) std::memcpy(f.data.data(), src, unpacked);+ } else if (unpacked) {+ // The output buffer is exactly the declared size: data that inflates to more fails here.+ const int got = stbi_zlib_decode_noheader_buffer(reinterpret_cast<char*>(f.data.data()), int(unpacked),+ reinterpret_cast<const char*>(src), int(packed));+ if (got != int(unpacked)) {+ error = "\"" + shown + "\" doesn't unpack to its stated size (damaged, or a zip bomb): refused";+ return false;+ }+ }+ if (crc32(f.data.data(), f.data.size()) != crc) {+ error = "\"" + shown + "\" is damaged (checksum mismatch)";+ return false;+ }+ files.push_back(std::move(f));+ }+ at = next;+ }+ if (at != eocd) {+ error = "The pack's zip directory is damaged";+ return false;+ }+ if (totalUnpacked > 1024 * 1024 && totalUnpacked > std::max<uint64_t>(totalPacked, 1) * limits.ratio) {+ error = "The pack unpacks to more than " + std::to_string(limits.ratio) + " times its size (a zip bomb?): refused";+ return false;+ }+ // No two entries may share bytes (overlapping entries are how some zip bombs multiply their data).+ std::sort(spans.begin(), spans.end(), [](const Span& x, const Span& y) { return x.begin < y.begin; });+ for (size_t i = 1; i < spans.size(); ++i)+ if (spans[i].begin < spans[i - 1].end) {+ error = "\"" + radialCleanText(spans[i].name, 80) + "\" overlaps another file in the archive: refused";+ return false;+ }+ return true;+}++bool readPackArchive(const std::string& path, std::vector<PackFile>& files, std::string& error, const PackLimits& limits) {+ std::vector<uint8_t> bytes;+ if (!readWholeFile(path, bytes, limits.archiveBytes, error)) return false;+ return readPackArchiveBytes(bytes, files, error, limits);+}++// ---------------------------------------------------------------------------+// Checking what a pack holds+// ---------------------------------------------------------------------------++namespace {++bool imageOk(const std::vector<uint8_t>& data, int maxSide, std::string& error, const std::string& shown) {+ int w = 0, h = 0, comp = 0;+ if (data.size() > size_t(INT32_MAX) ||+ !stbi_info_from_memory(data.data(), int(data.size()), &w, &h, &comp)) {+ error = "\"" + shown + "\" is not a readable PNG or JPEG image";+ return false;+ }+ if (w <= 0 || h <= 0 || w > maxSide || h > maxSide) {+ error = "\"" + shown + "\" is " + std::to_string(w) + " x " + std::to_string(h) + " pixels (at most " ++ std::to_string(maxSide) + " a side)";+ return false;+ }+ // The magic bytes must match the extension: no other format hides behind .png.+ const std::string ext = extensionOf(shown);+ const bool png = data.size() > 8 && std::memcmp(data.data(), "\x89PNG\r\n\x1a\n", 8) == 0;+ const bool jpg = data.size() > 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF;+ if ((ext == ".png" && !png) || ((ext == ".jpg" || ext == ".jpeg") && !jpg)) {+ error = "\"" + shown + "\" is not the image type its name says";+ return false;+ }+ Image img;+ std::string err;+ if (!Image::decode(data.data(), data.size(), img, err)) {+ error = "\"" + shown + "\" can't be decoded: " + err;+ return false;+ }+ return true;+}++bool vdmOk(const std::vector<uint8_t>& b, std::string& error, const std::string& shown) {+ auto u32 = [&](size_t at) { return rd32(&b[at]); };+ if (b.size() < 20 || std::memcmp(b.data(), "SFVDM1\n\0", 8) != 0) {+ error = "\"" + shown + "\" is not a SculptForge VDM (.sfvdm)";+ return false;+ }+ const uint32_t w = u32(8), h = u32(12), nameLen = u32(16);+ if (w == 0 || h == 0 || w > 2048 || h > 2048 || nameLen > 1024 || b.size() != 20 + size_t(nameLen) + size_t(w) * h * 12) {+ error = "\"" + shown + "\" is a damaged VDM (bad size)";+ return false;+ }+ const std::string name(reinterpret_cast<const char*>(b.data() + 20), nameLen);+ if (!cleanTextOk(name, 1024, false)) {+ error = "\"" + shown + "\" has an invalid VDM name";+ return false;+ }+ return true;+}++bool checkPackFile(PackItemType type, const PackFile& f, const CommandRegistry* registry, std::string& error) {+ const std::string shown = radialCleanText(f.name, 80);+ switch (type) {+ case PackItemType::Brush: {+ if (f.data.size() > kMaxBrushFileSize) {+ error = "\"" + shown + "\" is too big for a brush";+ return false;+ }+ BrushRecipe r;+ std::string err;+ Json j;+ if (!Json::parseStrict(text(f.data), j, err) || !parseBrushText(text(f.data), r, err)) {+ error = "\"" + shown + "\" is not a valid brush: " + err;+ return false;+ }+ return true;+ }+ case PackItemType::Alpha:+ case PackItemType::Matcap: return imageOk(f.data, 4096, error, f.name);+ case PackItemType::Material: {+ if (f.data.size() > 256 * 1024) {+ error = "\"" + shown + "\" is too big for a Material Recipe";+ return false;+ }+ MaterialRecipe m;+ Json j;+ std::string err;+ if (!Json::parseStrict(text(f.data), j, err) || !parseMaterialRecipe(text(f.data), m, err)) {+ error = "\"" + shown + "\" is not a valid Material Recipe: " + err;+ return false;+ }+ return true;+ }+ case PackItemType::Vdm: return vdmOk(f.data, error, f.name);+ case PackItemType::Keymap: {+ KeymapFile k;+ std::string err;+ if (!parseKeymapFile(text(f.data), k, err)) {+ error = "\"" + shown + "\" is not a valid keymap: " + err;+ return false;+ }+ return true;+ }+ case PackItemType::PieMenu: {+ if (f.data.size() > kRadialFileMax) {+ error = "\"" + shown + "\" is too big for a pie menu";+ return false;+ }+ // The app checks the actions against its own when the menu is added; here: well formed, ids that could be.+ RadialVocabulary any;+ auto idChars = [](std::string_view id) {+ if (id.empty() || id.size() > kRadialIdMax) return false;+ for (unsigned char c : id)+ if (!(std::isalnum(c) || c == '.' || c == '_' || c == '-')) return false;+ return true;+ };+ any.action = idChars;+ any.icon = idChars;+ RadialMenu menu;+ Json j;+ std::string err;+ if (!Json::parseStrict(text(f.data), j, err) || !parseRadialMenuFile(text(f.data), any, menu, err)) {+ error = "\"" + shown + "\" is not a valid pie menu: " + err;+ return false;+ }+ return true;+ }+ case PackItemType::Macro: {+ Macro m;+ std::string err;+ if (f.data.size() > kMaxMacroFileSize) {+ error = "\"" + shown + "\" is too big for a macro";+ return false;+ }+ if (!parseMacro(text(f.data), registry, m, err, stemOf(f.name))) {+ error = "\"" + shown + "\": " + err;+ return false;+ }+ return true;+ }+ case PackItemType::Count: break;+ }+ error = "\"" + shown + "\" has an unknown type";+ return false;+}++bool isLicenseName(const std::string& name) {+ return name == "LICENSE" || name == "LICENSE.txt" || name == "LICENSE.md";+}++} // namespace++bool reviewPackFiles(std::vector<PackFile> files, PackReview& out, std::string& error, const CommandRegistry* registry) {+ const std::string source = out.source;+ out = {};+ out.source = source;+ const PackFile* manifestFile = nullptr;+ for (const PackFile& f : files)+ if (f.name == "pack.json") manifestFile = &f;+ if (!manifestFile) {+ error = "Not a SculptForge pack: there is no pack.json";+ return false;+ }+ if (!parsePackManifest(text(manifestFile->data), out.manifest, error)) return false;+ const PackManifest& m = out.manifest;+ if (!m.minAppVersion.empty() && compareVersions(m.minAppVersion, appVersion()) > 0) {+ out.needsNewerApp = true;+ error = "\"" + m.name + "\" needs SculptForge " + m.minAppVersion + " or newer (this is " + appVersion() + ")";+ return false;+ }+ std::map<std::string, PackItemType> listed;+ for (const PackItem& it : m.contents)+ if (!listed.emplace(it.path, it.type).second) {+ error = "pack.json lists " + radialCleanText(it.path, 80) + " twice";+ return false;+ }+ std::set<std::string> present;+ bool haveLicense = false;+ for (const PackFile& f : files) {+ const std::string shown = radialCleanText(f.name, 80);+ out.bytes += f.data.size();+ present.insert(f.name);+ if (f.name == "pack.json") continue;+ if (f.name.find('/') == std::string::npos) {+ if (isLicenseName(f.name)) {+ if (haveLicense) {+ error = "The pack holds more than one license file";+ return false;+ }+ haveLicense = true;+ if (f.data.size() > 64 * 1024 || !cleanTextOk(text(f.data), 64 * 1024, true)) {+ error = "\"" + shown + "\" is not a plain text license (or is over 64 KB)";+ return false;+ }+ out.licenseText = text(f.data);+ continue;+ }+ if (f.name == "preview.png" || f.name == "preview.jpg") {+ if (f.name != m.preview) {+ error = "\"" + shown + "\" is in the pack but pack.json doesn't name it as the preview";+ return false;+ }+ if (!imageOk(f.data, 2048, error, f.name)) return false;+ continue;+ }+ error = "\"" + shown + "\" is not a file a pack may hold (allowed: pack.json, LICENSE, a preview image and "+ "the item folders)";+ return false;+ }+ const auto it = listed.find(f.name);+ if (it == listed.end()) {+ error = "\"" + shown + "\" is in the pack but not listed in pack.json";+ return false;+ }+ if (!checkPackFile(it->second, f, registry, error)) return false;+ ++out.counts[size_t(it->second)];+ out.itemNames.push_back(std::string(packItemTypeId(it->second)) + ": " + stemOf(f.name));+ }+ for (const PackItem& it : m.contents)+ if (!present.count(it.path)) {+ error = "pack.json lists " + radialCleanText(it.path, 80) + " but the pack doesn't hold it";+ return false;+ }+ if (!m.preview.empty() && !present.count(m.preview)) {+ error = "pack.json names " + m.preview + " as the preview but the pack doesn't hold it";+ return false;+ }+ for (const InstalledPack& p : listInstalledPacks())+ if (p.manifest.id == m.id) out.installedVersion = p.manifest.version;+ out.files = std::move(files);+ return true;+}++bool reviewPack(const std::string& path, PackReview& out, std::string& error, const CommandRegistry* registry,+ const PackLimits& limits) {+ std::vector<PackFile> files;+ if (!readPackArchive(path, files, error, limits)) return false;+ out.source = path;+ return reviewPackFiles(std::move(files), out, error, registry);+}++// ---------------------------------------------------------------------------+// Installed packs+// ---------------------------------------------------------------------------++std::string packsRoot() {+ if (!g_packsRoot.empty()) return g_packsRoot;+ const std::string data = appDataDir();+ return data.empty() ? std::string() : u8str(u8path(data) / "packs");+}+void setPacksRoot(const std::string& dir) { g_packsRoot = dir; }+bool packsSafeMode() { return g_safeMode; }+void setPacksSafeMode(bool on) { g_safeMode = on; }++namespace {++fs::path statePath() { return u8path(packsRoot()) / "packs.json"; }++std::set<std::string> disabledPacks() {+ std::set<std::string> out;+ std::vector<uint8_t> bytes;+ std::string err;+ if (!readWholeFile(u8str(statePath()), bytes, 256 * 1024, err)) return out;+ Json j;+ if (!Json::parseStrict(text(bytes), j, err) || !j.isObject() || !j["disabled"].isArray()) return out;+ for (const Json& id : j["disabled"].items())+ if (id.isString() && packIdOk(id.asString())) out.insert(id.asString());+ return out;+}++bool writeDisabledPacks(const std::set<std::string>& ids, std::string& error) {+ Json list = Json::array();+ for (const std::string& id : ids) list.push(id);+ Json j = Json::object();+ j.set("disabled", std::move(list));+ std::error_code ec;+ fs::create_directories(u8path(packsRoot()), ec);+ const fs::path tmp = u8path(packsRoot()) / "packs.json.tmp";+ {+ std::ofstream f(tmp, std::ios::binary | std::ios::trunc);+ f << j.dump(true) << "\n";+ if (!f) {+ error = "Cannot write " + u8str(tmp);+ return false;+ }+ }+ fs::rename(tmp, statePath(), ec);+ if (ec) {+ error = "Cannot write " + u8str(statePath()) + ": " + ec.message();+ return false;+ }+ return true;+}++// The installed pack folder for ID, checked to be a real folder directly in the packs root.+bool packDir(const std::string& id, fs::path& out, std::string& error) {+ if (!packIdOk(id)) {+ error = "\"" + radialCleanText(id, 64) + "\" is not a pack id";+ return false;+ }+ if (packsRoot().empty()) {+ error = "There is no folder for packs on this system";+ return false;+ }+ out = u8path(packsRoot()) / u8path(id);+ return true;+}++bool readInstalledManifest(const fs::path& dir, PackManifest& m, std::string& error) {+ std::vector<uint8_t> bytes;+ if (!readWholeFile(u8str(dir / "pack.json"), bytes, 64 * 1024, error)) return false;+ return parsePackManifest(text(bytes), m, error);+}++} // namespace++std::vector<InstalledPack> listInstalledPacks(std::vector<std::string>* messages) {+ std::vector<InstalledPack> out;+ const std::string root = packsRoot();+ if (root.empty()) return out;+ const std::set<std::string> disabled = disabledPacks();+ std::error_code ec;+ for (fs::directory_iterator it(u8path(root), ec), end; !ec && it != end; it.increment(ec)) {+ std::error_code e2;+ if (it->is_symlink(e2) || !it->is_directory(e2)) continue;+ const std::string id = u8str(it->path().filename());+ if (!packIdOk(id)) continue; // ".staging-..." and anything else that isn't a pack+ InstalledPack p;+ std::string err;+ if (!readInstalledManifest(it->path(), p.manifest, err) || p.manifest.id != id) {+ if (messages) messages->push_back("Skipped pack folder " + id + ": " + (err.empty() ? "its id doesn't match" : err));+ continue;+ }+ p.dir = u8str(it->path());+ p.enabled = !disabled.count(id);+ out.push_back(std::move(p));+ }+ std::sort(out.begin(), out.end(), [](const InstalledPack& a, const InstalledPack& b) {+ return lowerAscii(a.manifest.name) < lowerAscii(b.manifest.name) ||+ (lowerAscii(a.manifest.name) == lowerAscii(b.manifest.name) && a.manifest.id < b.manifest.id);+ });+ return out;+}++bool installPack(const PackReview& review, std::string& error) {+ fs::path dest;+ if (!packDir(review.manifest.id, dest, error)) return false;+ if (review.files.empty()) {+ error = "Nothing to install (review the pack first)";+ return false;+ }+ const fs::path root = u8path(packsRoot());+ std::error_code ec;+ fs::create_directories(root, ec);+ if (ec) {+ error = "Cannot create " + u8str(root) + ": " + ec.message();+ return false;+ }+ // Unpack into a fresh staging folder, then swap it in: a failed install leaves the old version as it was.+ const fs::path staging = root / u8path(".staging-" + review.manifest.id);+ fs::remove_all(staging, ec);+ if (!fs::create_directory(staging, ec) || ec) {+ error = "Cannot create " + u8str(staging);+ return false;+ }+ for (const PackFile& f : review.files) {+ std::string nameErr;+ if (!packEntryNameOk(f.name, nameErr)) { // (checked when read; checked again before anything is written)+ fs::remove_all(staging, ec);+ error = nameErr;+ return false;+ }+ const fs::path target = (staging / u8path(f.name)).lexically_normal();+ const std::string rel = u8str(target.lexically_relative(staging));+ if (rel.empty() || rel.rfind("..", 0) == 0 || target.is_absolute() != staging.is_absolute()) {+ fs::remove_all(staging, ec);+ error = "\"" + radialCleanText(f.name, 80) + "\" would land outside the pack's folder: refused";+ return false;+ }+ fs::create_directories(target.parent_path(), ec);+ if (fs::exists(fs::symlink_status(target, ec))) {+ fs::remove_all(staging, ec);+ error = "\"" + radialCleanText(f.name, 80) + "\" is in the pack twice";+ return false;+ }+ std::ofstream o(target, std::ios::binary | std::ios::trunc);+ if (!f.data.empty()) o.write(reinterpret_cast<const char*>(f.data.data()), std::streamsize(f.data.size()));+ if (!o) {+ fs::remove_all(staging, ec);+ error = "Cannot write " + u8str(target);+ return false;+ }+ }+ const fs::path old = root / u8path(".old-" + review.manifest.id);+ fs::remove_all(old, ec);+ if (fs::exists(fs::symlink_status(dest, ec))) {+ fs::rename(dest, old, ec);+ if (ec) {+ fs::remove_all(staging, ec);+ error = "Cannot replace the installed " + review.manifest.name + ": " + ec.message();+ return false;+ }+ }+ fs::rename(staging, dest, ec);+ if (ec) {+ std::error_code ignore;+ if (fs::exists(old, ignore)) fs::rename(old, dest, ignore);+ fs::remove_all(staging, ignore);+ error = "Cannot install " + review.manifest.name + ": " + ec.message();+ return false;+ }+ fs::remove_all(old, ec);+ std::set<std::string> disabled = disabledPacks();+ if (disabled.erase(review.manifest.id)) return writeDisabledPacks(disabled, error);+ return true;+}++bool removePack(const std::string& id, std::string& error) {+ fs::path dir;+ if (!packDir(id, dir, error)) return false;+ std::error_code ec;+ const auto st = fs::symlink_status(dir, ec);+ if (fs::is_symlink(st)) { // never follow a link out of the packs folder+ fs::remove(dir, ec);+ return true;+ }+ if (!fs::is_directory(st)) {+ error = "No pack \"" + id + "\" is installed";+ return false;+ }+ fs::remove_all(dir, ec);+ if (ec) {+ error = "Cannot remove " + u8str(dir) + ": " + ec.message();+ return false;+ }+ std::set<std::string> disabled = disabledPacks();+ if (disabled.erase(id)) return writeDisabledPacks(disabled, error);+ return true;+}++bool setPackEnabled(const std::string& id, bool enabled, std::string& error) {+ fs::path dir;+ if (!packDir(id, dir, error)) return false;+ std::error_code ec;+ if (!fs::is_directory(fs::symlink_status(dir, ec))) {+ error = "No pack \"" + id + "\" is installed";+ return false;+ }+ std::set<std::string> disabled = disabledPacks();+ if (enabled) disabled.erase(id);+ else disabled.insert(id);+ return writeDisabledPacks(disabled, error);+}++std::vector<PackContentItem> enabledPackItems(PackItemType type) {+ std::vector<PackContentItem> out;+ if (packsSafeMode()) return out;+ for (const InstalledPack& p : listInstalledPacks()) {+ if (!p.enabled) continue;+ for (const PackItem& it : p.manifest.contents) {+ if (it.type != type) continue;+ const fs::path file = u8path(p.dir) / u8path(it.path);+ std::error_code ec;+ if (!fs::is_regular_file(fs::symlink_status(file, ec))) continue; // (changed on disk since)+ PackContentItem c;+ c.type = type;+ c.file = u8str(file);+ c.name = stemOf(it.path);+ c.packId = p.manifest.id;+ c.packName = p.manifest.name;+ out.push_back(std::move(c));+ }+ }+ return out;+}++void applyPacksToBrushLibrary(BrushLibraryPaths& paths) {+ paths.packs.clear();+ if (packsSafeMode()) return;+ for (const InstalledPack& p : listInstalledPacks()) {+ if (!p.enabled) continue;+ bool brushes = false, vdms = false;+ for (const PackItem& it : p.manifest.contents) {+ brushes = brushes || it.type == PackItemType::Brush;+ vdms = vdms || it.type == PackItemType::Vdm;+ }+ if (brushes) paths.packs.push_back({u8str(u8path(p.dir) / "brushes"), p.manifest.name, false});+ if (vdms) paths.packs.push_back({u8str(u8path(p.dir) / "vdms"), p.manifest.name, true});+ }+}++// ---------------------------------------------------------------------------+// Keymaps+// ---------------------------------------------------------------------------++bool parseKeymapFile(const std::string& t, KeymapFile& out, std::string& error) {+ out = {};+ if (t.size() > 128 * 1024) {+ error = "too big (at most 128 KB)";+ return false;+ }+ Json j;+ std::string err;+ if (!Json::parseStrict(t, j, err)) {+ error = "not valid JSON: " + err;+ return false;+ }+ if (!j.isObject() || j["format"].asString() != "sculptforge-keymap" || !j["version"].isNumber() ||+ j["version"].asNumber() != 1.0) {+ error = "not a SculptForge keymap (format \"sculptforge-keymap\", version 1)";+ return false;+ }+ for (const auto& [key, v] : j.members())+ if (key != "format" && key != "version" && key != "name" && key != "shortcuts") {+ error = "unknown key \"" + radialCleanText(key, 40) + "\"";+ return false;+ }+ if (j.has("name")) {+ if (!j["name"].isString() || !cleanTextOk(j["name"].asString(), 64, false)) {+ error = "\"name\" must be a short string";+ return false;+ }+ out.name = j["name"].asString();+ }+ const Json& s = j["shortcuts"];+ if (!s.isObject()) {+ error = "\"shortcuts\" must be an object of action id to key";+ return false;+ }+ if (s.members().size() > kMaxKeymapShortcuts) {+ error = "too many shortcuts (at most " + std::to_string(kMaxKeymapShortcuts) + ")";+ return false;+ }+ for (const auto& [id, chord] : s.members()) {+ bool idOk = !id.empty() && id.size() <= kRadialIdMax;+ for (unsigned char c : id) idOk = idOk && (std::isalnum(c) || c == '.' || c == '_' || c == '-');+ if (!idOk) {+ error = "\"" + radialCleanText(id, 40) + "\" is not an action id";+ return false;+ }+ if (!chord.isString() || !cleanTextOk(chord.asString(), 48, false)) {+ error = "the key of " + id + " must be a short string such as \"Ctrl+Shift+K\"";+ return false;+ }+ out.shortcuts.emplace_back(id, chord.asString());+ }+ return true;+}++std::string keymapFileText(const KeymapFile& k) {+ Json j = Json::object();+ j.set("format", "sculptforge-keymap");+ j.set("version", 1);+ if (!k.name.empty()) j.set("name", k.name);+ Json s = Json::object();+ for (const auto& [id, chord] : k.shortcuts) s.set(id, chord);+ j.set("shortcuts", std::move(s));+ return j.dump(true) + "\n";+}++// ---------------------------------------------------------------------------+// Making a pack+// ---------------------------------------------------------------------------++bool writePack(const std::string& outPath, PackManifest manifest, const std::vector<PackSource>& items,+ const std::string& licenseText, const std::string& previewFile, std::string& error,+ const CommandRegistry* registry) {+ std::vector<ZipEntry> entries;+ manifest.contents.clear();+ std::set<std::string> names;+ for (const PackSource& s : items) {+ ZipEntry e;+ std::string file = s.name;+ if (file.empty()) file = u8str(u8path(s.file).filename());+ e.name = std::string(packItemFolder(s.type)) + "/" + file;+ if (!s.data.empty() || s.file.empty()) e.data = s.data;+ else if (!readWholeFile(s.file, e.data, PackLimits{}.fileBytes, error)) return false;+ if (!names.insert(lowerAscii(e.name)).second) {+ error = "Two items would both be " + e.name + " in the pack: rename one";+ return false;+ }+ manifest.contents.push_back({s.type, e.name});+ entries.push_back(std::move(e));+ }+ if (!licenseText.empty()) {+ ZipEntry e;+ e.name = "LICENSE.txt";+ e.data.assign(licenseText.begin(), licenseText.end());+ entries.push_back(std::move(e));+ }+ manifest.preview.clear();+ if (!previewFile.empty()) {+ ZipEntry e;+ const std::string ext = extensionOf(previewFile);+ e.name = ext == ".png" ? "preview.png" : "preview.jpg";+ if (!readWholeFile(previewFile, e.data, 16ull << 20, error)) return false;+ manifest.preview = e.name;+ entries.push_back(std::move(e));+ }+ if (manifest.minAppVersion.empty()) manifest.minAppVersion = appVersion();+ ZipEntry m;+ m.name = "pack.json";+ const std::string mt = packManifestText(manifest);+ m.data.assign(mt.begin(), mt.end());+ entries.insert(entries.begin(), std::move(m));++ // Check it exactly as an install would before writing anything.+ std::vector<PackFile> files;+ for (const ZipEntry& e : entries) files.push_back({e.name, e.data});+ PackReview review;+ if (!reviewPackFiles(std::move(files), review, error, registry)) return false;+ if (!writeStoredZip(outPath, entries, 1, error)) return false;+ // And read back what was written.+ PackReview again;+ if (!reviewPack(outPath, again, error, registry)) return false;+ return true;+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++void registerPackCommands(CommandRegistry& registry) {+ using T = ParamSpec::Type;+ const CommandRegistry* reg = ®istry;+ registry.add({"pack_install",+ "Install a SculptForge pack (.sfpack): brushes, alphas, Lit Spheres, Material Recipes, VDMs, keymaps, "+ "pie menus and macros. Packs hold data only and are checked completely first (in the app, a review "+ "shows what's inside before anything is installed).",+ {{"path", T::String, "The .sfpack file.", true}},+ [reg](Document& doc, const Args& a) -> CommandResult {+ PackReview review;+ std::string err;+ if (!reviewPack(argString(a, "path"), review, err, reg)) return {false, err};+ if (!installPack(review, err)) return {false, err};+ applyPacksToBrushLibrary(brushLibraryPaths());+ loadBrushLibrary(doc);+ return {true, "Installed " + review.manifest.name + " " + review.manifest.version + " by " ++ review.manifest.author + ": " + packCountsText(review.counts) ++ (packsSafeMode() ? " (not loaded: packs are off this session)" : "")};+ }});+ registry.add({"pack_list", "List the installed packs: id, name, version, author, license, what they hold and whether "+ "they are on.",+ {},+ [](Document&, const Args&) -> CommandResult {+ std::vector<std::string> messages;+ const auto packs = listInstalledPacks(&messages);+ std::string out = packs.empty() ? "No packs installed"+ : std::to_string(packs.size()) + (packs.size() == 1 ? " pack" : " packs");+ if (packsSafeMode()) out += " (packs are off this session: --no-packs)";+ for (const InstalledPack& p : packs) {+ std::array<int, kPackItemTypes> counts{};+ for (const PackItem& it : p.manifest.contents) ++counts[size_t(it.type)];+ out += "\n" + p.manifest.id + " " + p.manifest.name + " " + p.manifest.version + " by " ++ p.manifest.author + " (" + p.manifest.license + ")" ++ (p.manifest.channel.empty() ? "" : " [" + p.manifest.channel + "]") + ": " ++ packCountsText(counts) + (p.enabled ? "" : " - off");+ }+ for (const std::string& m : messages) out += "\n" + m;+ return {true, out};+ }});+ registry.add({"pack_remove", "Remove an installed pack and everything it brought (your own files are never touched).",+ {{"id", T::String, "The pack's id (pack_list shows it).", true}},+ [](Document& doc, const Args& a) -> CommandResult {+ std::string err;+ if (!removePack(argString(a, "id"), err)) return {false, err};+ applyPacksToBrushLibrary(brushLibraryPaths());+ loadBrushLibrary(doc);+ return {true, "Removed pack " + argString(a, "id")};+ }});+ registry.add({"pack_create",+ "Make a pack (.sfpack) from a folder laid out like one: brushes/, alphas/, matcaps/, materials/, vdms/, "+ "keymaps/, piemenus/ and macros/ (each with its own file types), plus LICENSE.txt and preview.png if "+ "there. Everything is checked exactly as an install would check it.",+ {{"folder", T::String, "The folder holding the items.", true},+ {"path", T::String, "The .sfpack to write.", true},+ {"id", T::String, "Pack id: lower-case letters, digits, '.', '_', '-'.", true},+ {"name", T::String, "Pack name.", true},+ {"version", T::String, "Version, e.g. 1.0.", false},+ {"author", T::String, "Who made it.", true},+ {"license", T::String, "License, e.g. CC-BY-4.0.", true},+ {"description", T::String, "What it holds.", false},+ {"channel", T::String, "insider marks a Supporter Pack (display only).", false}},+ [reg](Document&, const Args& a) -> CommandResult {+ PackManifest m;+ m.id = argString(a, "id");+ m.name = argString(a, "name");+ m.version = argString(a, "version", "1.0");+ m.author = argString(a, "author");+ m.license = argString(a, "license");+ m.description = argString(a, "description");+ m.channel = argString(a, "channel");+ const fs::path dir = u8path(argString(a, "folder"));+ std::vector<PackSource> items;+ for (int t = 0; t < kPackItemTypes; ++t) {+ std::vector<std::string> files;+ std::error_code ec;+ for (fs::directory_iterator it(dir / packItemFolder(PackItemType(t)), ec), end; !ec && it != end;+ it.increment(ec)) {+ std::error_code e2;+ if (!it->is_symlink(e2) && it->is_regular_file(e2) &&+ packItemExtensionOk(PackItemType(t), u8str(it->path().filename())))+ files.push_back(u8str(it->path()));+ }+ std::sort(files.begin(), files.end());+ for (const std::string& f : files) items.push_back({PackItemType(t), f, "", {}});+ }+ std::string license, preview, err;+ for (const char* n : {"LICENSE.txt", "LICENSE", "LICENSE.md"}) {+ std::vector<uint8_t> b;+ std::error_code ec;+ if (license.empty() && fs::is_regular_file(dir / n, ec) && readWholeFile(u8str(dir / n), b, 64 * 1024, err))+ license = text(b);+ }+ for (const char* n : {"preview.png", "preview.jpg"}) {+ std::error_code ec;+ if (preview.empty() && fs::is_regular_file(dir / n, ec)) preview = u8str(dir / n);+ }+ err.clear();+ if (!writePack(argString(a, "path"), m, items, license, preview, err, reg)) return {false, err};+ std::array<int, kPackItemTypes> counts{};+ for (const PackSource& s : items) ++counts[size_t(s.type)];+ return {true, "Wrote " + argString(a, "path") + ": " + packCountsText(counts)};+ }});+ for (const bool on : {true, false})+ registry.add({on ? "pack_enable" : "pack_disable",+ on ? "Turn an installed pack on: its items show in the lists again."+ : "Turn an installed pack off without removing it: its items leave the lists.",+ {{"id", T::String, "The pack's id (pack_list shows it).", true}},+ [on](Document& doc, const Args& a) -> CommandResult {+ std::string err;+ if (!setPackEnabled(argString(a, "id"), on, err)) return {false, err};+ applyPacksToBrushLibrary(brushLibraryPaths());+ loadBrushLibrary(doc);+ return {true, std::string(on ? "Turned on" : "Turned off") + " pack " + argString(a, "id")};+ }});+}++} // namespace sfdiff --git a/src/core/Pack.h b/src/core/Pack.hnew file mode 100644index 00000000..ca559e51--- /dev/null+++ b/src/core/Pack.h@@ -0,0 +1,163 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Packs (.sfpack): brushes, alphas, Lit Spheres, Material Recipes, VDMs, keymaps, pie menus and macros shared as+// one file (docs/pack-format.md). A pack is data only: no scripts, no programs, nothing runs when it is installed+// or a project opens, and nothing in it reaches the network. Every pack is treated as hostile input:+// - the zip is read by its own strict reader: absolute paths, '..', backslashes, drive letters, symbolic links,+// devices, encrypted entries, ZIP64, multi-disk archives, overlapping entries, duplicate names (in any case)+// and names Windows can't hold are refused; sizes, file counts and the decompression ratio are capped;+// - only the file types a pack may hold are accepted, each in its own folder, each listed in pack.json, and each+// is parsed (brushes, recipes, keymaps, pie menus and macros strictly; images decoded within size caps);+// - installing writes only inside <app data>/packs/<id>/, never over built-ins or the user's own files.+// Installed packs are listed, enabled, disabled and removed here; their items join the brush, alpha, Lit Sphere,+// Material Recipe, keymap, pie menu and macro lists tagged with the pack's name. --no-packs (safe mode) leaves+// every pack out for the session.+#pragma once++#include "core/Json.h"++#include <array>+#include <cstdint>+#include <string>+#include <vector>++namespace sf {++class CommandRegistry;+struct BrushLibraryPaths;++constexpr const char* kPackExtension = ".sfpack";+constexpr int kPackFormatVersion = 1;++struct PackLimits {+ uint64_t archiveBytes = 128ull << 20; // the .sfpack file+ size_t entries = 1000; // files (and folders) in it+ uint64_t fileBytes = 64ull << 20; // one file, unpacked+ uint64_t totalBytes = 256ull << 20; // every file, unpacked+ uint64_t ratio = 100; // unpacked / packed, per file over 64 KB and for the whole pack+ size_t nameBytes = 160; // one file name, with its folder+};++enum class PackItemType { Brush, Alpha, Matcap, Material, Vdm, Keymap, PieMenu, Macro, Count };+constexpr int kPackItemTypes = int(PackItemType::Count);+const char* packItemTypeId(PackItemType t); // "brush" (pack.json)+const char* packItemFolder(PackItemType t); // "brushes" (the folder inside the pack)+const char* packItemLabel(PackItemType t, int count); // "brush" / "brushes", "Lit Sphere" / "Lit Spheres", ...+bool packItemTypeFromId(const std::string& id, PackItemType& out);+bool packItemExtensionOk(PackItemType t, const std::string& fileName); // .sfbrush; .png/.jpg/.jpeg; ...++struct PackItem {+ PackItemType type = PackItemType::Brush;+ std::string path; // inside the pack: "brushes/Dragon Scales.sfbrush"+};++struct PackManifest {+ std::string id; // folder name: lower-case letters, digits, '.', '_', '-'+ std::string name, version, author, license, description;+ std::string minAppVersion; // "" = any+ std::string preview; // "preview.png" / "preview.jpg", or ""+ std::string channel; // "insider" marks a Supporter Pack (display only; no DRM), or ""+ std::vector<PackItem> contents;+};++bool parsePackManifest(const std::string& text, PackManifest& out, std::string& error);+std::string packManifestText(const PackManifest& m);+std::string appVersion(); // this build's version++// One file of a pack, unpacked.+struct PackFile {+ std::string name; // as in the archive+ std::vector<uint8_t> data;+};++// The checks every archive entry name must pass (see the file comment).+bool packEntryNameOk(const std::string& name, std::string& error, size_t maxBytes = PackLimits{}.nameBytes);++// Reads a zip with the strict checks above (stored and deflated entries, CRC checked). Folder entries are skipped.+bool readPackArchive(const std::string& path, std::vector<PackFile>& files, std::string& error, const PackLimits& limits = {});+bool readPackArchiveBytes(const std::vector<uint8_t>& bytes, std::vector<PackFile>& files, std::string& error,+ const PackLimits& limits = {});++// What the install review shows: the manifest, how many items of each type, the license text, the size, and+// whether it replaces an installed version.+struct PackReview {+ PackManifest manifest;+ std::array<int, kPackItemTypes> counts{};+ std::string licenseText;+ uint64_t bytes = 0; // unpacked+ std::string installedVersion; // "" = not installed+ bool needsNewerApp = false; // minAppVersion is newer than this build (refused)+ std::vector<std::string> itemNames; // "brush: Dragon Scales", for the review list+ std::vector<PackFile> files;+ std::string source; // the .sfpack it was read from+};+// Reads and checks a pack completely (archive, manifest, every file). Macros are checked against REGISTRY when given+// (the app's), otherwise against what a macro may hold at all.+bool reviewPack(const std::string& path, PackReview& out, std::string& error, const CommandRegistry* registry = nullptr,+ const PackLimits& limits = {});+bool reviewPackFiles(std::vector<PackFile> files, PackReview& out, std::string& error,+ const CommandRegistry* registry = nullptr);+// "12 brushes, 4 alphas, 1 macro"+std::string packCountsText(const std::array<int, kPackItemTypes>& counts);++// --- Installed packs (<app data>/packs/<id>/, state in <app data>/packs/packs.json) ---++struct InstalledPack {+ PackManifest manifest;+ std::string dir;+ bool enabled = true;+};++std::string packsRoot(); // <app data>/packs (or the override)+void setPacksRoot(const std::string& dir); // UI tests, unit tests; "" = the default+bool packsSafeMode(); // --no-packs: no pack is loaded this session+void setPacksSafeMode(bool on);++// Every installed pack (by name); folders that don't hold a readable pack are skipped with a message.+std::vector<InstalledPack> listInstalledPacks(std::vector<std::string>* messages = nullptr);+// Writes the reviewed pack into its folder (replacing an installed version of the same id) and enables it.+bool installPack(const PackReview& review, std::string& error);+bool removePack(const std::string& id, std::string& error);+bool setPackEnabled(const std::string& id, bool enabled, std::string& error);++// One item of an enabled pack.+struct PackContentItem {+ PackItemType type = PackItemType::Brush;+ std::string file; // absolute path of the installed file+ std::string name; // its file name without the extension+ std::string packId, packName;+ std::string label() const { return name + " (" + packName + ")"; } // as the lists show it+};+// The items of every enabled pack (none in safe mode), by pack name then file name.+std::vector<PackContentItem> enabledPackItems(PackItemType type);+// Points the brush library at the enabled packs' brushes and VDMs (core/BrushLibrary.h).+void applyPacksToBrushLibrary(BrushLibraryPaths& paths);++// --- Keymap files (keymaps/*.json in a pack) ---+// {"format": "sculptforge-keymap", "version": 1, "name": "...", "shortcuts": {"brush.clay": "C", ...}}+struct KeymapFile {+ std::string name;+ std::vector<std::pair<std::string, std::string>> shortcuts; // action id, chord text+};+constexpr size_t kMaxKeymapShortcuts = 512;+bool parseKeymapFile(const std::string& text, KeymapFile& out, std::string& error);+std::string keymapFileText(const KeymapFile& k);++// --- Making a pack ---++struct PackSource {+ PackItemType type = PackItemType::Brush;+ std::string file; // on disk+ std::string name; // file name inside the pack ("" = the file's own)+ std::vector<uint8_t> data; // instead of `file` (a recipe or keymap made in memory)+};+// Writes OUTPATH (a stored zip) from the items, checking the result exactly as an install would.+bool writePack(const std::string& outPath, PackManifest manifest, const std::vector<PackSource>& items,+ const std::string& licenseText, const std::string& previewFile, std::string& error,+ const CommandRegistry* registry = nullptr);++// pack_install, pack_list, pack_remove, pack_enable, pack_disable, pack_create.+void registerPackCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/Undo.h b/src/core/Undo.hindex 800b331b..216d4ab1 100644--- a/src/core/Undo.h+++ b/src/core/Undo.h@@ -224,6 +224,8 @@ public:// The step the next undo / redo applies (null if none): after undo() the undone step is lastRedo().UndoRecord* lastUndo() { return undo_.empty() ? nullptr : &undo_.back(); }UndoRecord* lastRedo() { return redo_.empty() ? nullptr : &redo_.back(); }+ // The undo step BACK places below the top (0 = the next undo), or null.+ const UndoRecord* undoStep(size_t back) const { return back < undo_.size() ? &undo_[undo_.size() - 1 - back] : nullptr; }// Both rebuild/refit the BVH as needed.bool undo(Mesh& mesh, BVH& bvh);diff --git a/src/core/Vdm.cpp b/src/core/Vdm.cppindex 8a6d995f..9b702f02 100644--- a/src/core/Vdm.cpp+++ b/src/core/Vdm.cpp@@ -4,6 +4,7 @@#include "core/Masking.h"#include "core/BrushLibrary.h"+#include "core/Pack.h"#include "core/Commands.h"#include "core/Document.h"#include "core/PathStroke.h"@@ -730,7 +731,7 @@ std::shared_ptr<const VectorDisplacement> addVdm(Document& doc, VectorDisplacemevoid loadVdmLibrary(Document& doc, const BrushLibraryPaths& paths, std::vector<std::string>& messages) {const std::string current = doc.brushVdm ? doc.brushVdm->name : std::string();doc.vdms = builtinVdms();- auto scan = [&](const std::string& dir, bool user) {+ auto scan = [&](const std::string& dir, bool user, const std::string& pack = {}) {std::vector<std::string> files;std::error_code ec;for (fs::directory_iterator it(utf8Path(dir), ec), end; !ec && it != end; it.increment(ec)) {@@ -746,6 +747,11 @@ void loadVdmLibrary(Document& doc, const BrushLibraryPaths& paths, std::vector<smessages.push_back("Skipped " + f + ": " + err);continue;}+ if (!pack.empty()) {+ // A pack's VDM never replaces another: it gets the pack's name after its own.+ if (findVdm(doc, v.name) >= 0) v.name += " (" + pack + ")";+ if (findVdm(doc, v.name) >= 0) continue;+ }const int i = findVdm(doc, v.name);auto shared = std::make_shared<const VectorDisplacement>(std::move(v));if (i < 0) doc.vdms.push_back(shared);@@ -753,6 +759,8 @@ void loadVdmLibrary(Document& doc, const BrushLibraryPaths& paths, std::vector<s}};for (const std::string& dir : paths.studioDirs) scan(dir, false);+ for (const auto& p : paths.packs)+ if (p.vdm && !packsSafeMode()) scan(p.dir, false, p.pack);if (!paths.userDir.empty()) scan(paths.userDir, true);const int i = findVdm(doc, current);doc.brushVdm = i >= 0 ? doc.vdms[size_t(i)] : doc.vdms.front();diff --git a/tests/test_core.cpp b/tests/test_core.cppindex 3ecd4d2f..d315e2e5 100644--- a/tests/test_core.cpp+++ b/tests/test_core.cpp@@ -1150,12 +1150,16 @@ TEST(mcp_server_protocol) {CHECK(init["result"]["serverInfo"]["name"].asString() == "sculptforge" && init["result"]["capabilities"]["tools"].isObject());CHECK(handleMcpMessage(reg, d, R"({"jsonrpc":"2.0","method":"notifications/initialized"})").empty());Json list = call(R"({"jsonrpc":"2.0","id":2,"method":"tools/list"})");- bool hasRemesh = false, schemasOk = true;+ bool hasRemesh = false, schemasOk = true, packTools = false;for (const auto& t : list["result"]["tools"].items()) {hasRemesh = hasRemesh || t["name"].asString() == "remesh";schemasOk = schemasOk && t["inputSchema"]["type"].asString() == "object";+ packTools = packTools || t["name"].asString() == "pack_install" || t["name"].asString() == "pack_remove";}- CHECK(hasRemesh && schemasOk && list["result"]["tools"].size() == reg.all().size());+ // Every command but installing, removing and switching packs (the user's decision, never an agent's).+ CHECK(hasRemesh && schemasOk && !packTools && list["result"]["tools"].size() == reg.all().size() - 4);+ Json refused = call(R"({"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"pack_install","arguments":{"path":"x.sfpack"}}})");+ CHECK(refused.has("error"));Json ok = call(R"({"jsonrpc":"2.0","id":"a","method":"tools/call","params":{"name":"new_sphere","arguments":{"subdivisions":2}}})");CHECK(ok["id"].asString() == "a" && !ok["result"]["isError"].asBool(true) && d.mesh.triangleCount() == 320);CHECK(ok["result"]["content"][0]["text"].asString().find("320") != std::string::npos);diff --git a/tests/test_packs.cpp b/tests/test_packs.cppnew file mode 100644index 00000000..68c894b2--- /dev/null+++ b/tests/test_packs.cpp@@ -0,0 +1,772 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Packs (.sfpack) and macros (.sfmacro): the strict zip reader and pack validator against hostile archives+// (traversal, symbolic links, zip bombs, bad JSON, wrong file types, duplicates, encryption), install / enable /+// disable / remove, the brush library tagging pack brushes, and macros: validation, path confinement, record and+// play back, one undo step.+#include "TestHarness.h"++#include "core/BrushLibrary.h"+#include "core/BrushRecipe.h"+#include "core/Commands.h"+#include "core/Image.h"+#include "core/Macro.h"+#include "core/Pack.h"+#include "core/Primitives.h"+#include "core/RadialMenu.h"+#include "core/Vdm.h"+#include "io/Zip.h"++#include <cstring>+#include <filesystem>+#include <fstream>++using namespace sf;+namespace fs = std::filesystem;++namespace {++// --- A zip writer that can write what a hostile tool would ---++struct RawEntry {+ std::string name;+ std::vector<uint8_t> data; // unpacked (for the CRC and, when stored, the bytes)+ std::vector<uint8_t> packed; // method 8: the deflate stream+ uint16_t method = 0;+ uint16_t madeBy = 20;+ uint16_t flags = 0;+ uint32_t external = 0;+ int64_t declaredSize = -1; // -1: data.size()+};++void put16(std::vector<uint8_t>& b, uint32_t v) {+ b.push_back(uint8_t(v));+ b.push_back(uint8_t(v >> 8));+}+void put32(std::vector<uint8_t>& b, uint32_t v) {+ put16(b, v & 0xFFFF);+ put16(b, v >> 16);+}++std::vector<uint8_t> buildZip(const std::vector<RawEntry>& entries) {+ std::vector<uint8_t> out, central;+ for (const RawEntry& e : entries) {+ const uint32_t offset = uint32_t(out.size());+ const std::vector<uint8_t>& body = e.method == 8 ? e.packed : e.data;+ const uint32_t usize = e.declaredSize >= 0 ? uint32_t(e.declaredSize) : uint32_t(e.data.size());+ const uint32_t crc = crc32(e.data.data(), e.data.size());+ put32(out, 0x04034B50);+ put16(out, 20);+ put16(out, e.flags);+ put16(out, e.method);+ put16(out, 0);+ put16(out, 0x21);+ put32(out, crc);+ put32(out, uint32_t(body.size()));+ put32(out, usize);+ put16(out, uint32_t(e.name.size()));+ put16(out, 0);+ out.insert(out.end(), e.name.begin(), e.name.end());+ out.insert(out.end(), body.begin(), body.end());+ put32(central, 0x02014B50);+ put16(central, e.madeBy);+ put16(central, 20);+ put16(central, e.flags);+ put16(central, e.method);+ put16(central, 0);+ put16(central, 0x21);+ put32(central, crc);+ put32(central, uint32_t(body.size()));+ put32(central, usize);+ put16(central, uint32_t(e.name.size()));+ put16(central, 0);+ put16(central, 0);+ put16(central, 0);+ put16(central, 0);+ put32(central, e.external);+ put32(central, offset);+ central.insert(central.end(), e.name.begin(), e.name.end());+ }+ const uint32_t cdOffset = uint32_t(out.size());+ out.insert(out.end(), central.begin(), central.end());+ put32(out, 0x06054B50);+ put16(out, 0);+ put16(out, 0);+ put16(out, uint32_t(entries.size()));+ put16(out, uint32_t(entries.size()));+ put32(out, uint32_t(central.size()));+ put32(out, cdOffset);+ put16(out, 0);+ return out;+}++// Deflate with fixed Huffman codes: one literal zero, then RUNS copies of 258 zeros (a zip bomb's shape).+std::vector<uint8_t> deflateZeros(int runs) {+ std::vector<uint8_t> out;+ uint32_t acc = 0;+ int bits = 0;+ auto put = [&](uint32_t v, int n) { // LSB first+ for (int i = 0; i < n; ++i) {+ acc |= ((v >> i) & 1u) << bits;+ if (++bits == 8) out.push_back(uint8_t(acc)), acc = 0, bits = 0;+ }+ };+ auto huff = [&](uint32_t code, int n) { // Huffman codes go MSB first+ for (int i = n - 1; i >= 0; --i) put((code >> i) & 1u, 1);+ };+ put(1, 1); // BFINAL+ put(1, 2); // fixed Huffman+ huff(0x30, 8); // literal 0+ for (int i = 0; i < runs; ++i) {+ huff(0xC5, 8); // length 258 (symbol 285)+ huff(0, 5); // distance 1+ }+ huff(0, 7); // end of block+ if (bits) out.push_back(uint8_t(acc));+ return out;+}++// Deflate's stored block: the same bytes, through the inflate path.+std::vector<uint8_t> deflateStored(const std::vector<uint8_t>& d) {+ std::vector<uint8_t> out = {1};+ put16(out, uint32_t(d.size()));+ put16(out, uint32_t(~d.size() & 0xFFFF));+ out.insert(out.end(), d.begin(), d.end());+ return out;+}++std::vector<uint8_t> bytes(const std::string& s) { return std::vector<uint8_t>(s.begin(), s.end()); }++std::string brushJson(const std::string& name) {+ BrushRecipe r;+ r.name = name;+ r.depth = 0.4f;+ return r.toJson().dump(true);+}++std::vector<uint8_t> pngBytes(int side) {+ Image img;+ img.width = img.height = side;+ img.rgba.assign(size_t(side) * side * 4, 200);+ std::vector<uint8_t> png;+ img.encodePng(png);+ return png;+}++std::string manifest(const std::string& contents, const std::string& extra = "") {+ return "{\"format\":\"sculptforge-pack\",\"formatVersion\":1,\"id\":\"test-pack\",\"name\":\"Test Pack\","+ "\"version\":\"1.0\",\"author\":\"Someone\",\"license\":\"CC0-1.0\"" + extra + ",\"contents\":[" + contents + "]}";+}++// A good pack's entries: a brush, an alpha and a macro.+std::vector<RawEntry> goodEntries() {+ std::vector<RawEntry> e;+ e.push_back({"pack.json", bytes(manifest("{\"type\":\"brush\",\"path\":\"brushes/Pack Clay.sfbrush\"},"+ "{\"type\":\"alpha\",\"path\":\"alphas/Dots.png\"},"+ "{\"type\":\"macro\",\"path\":\"macros/Prep.sfmacro\"}")), {}});+ e.push_back({"LICENSE.txt", bytes("CC0 1.0 Universal\n"), {}});+ e.push_back({"brushes/Pack Clay.sfbrush", bytes(brushJson("Pack Clay")), {}});+ e.push_back({"alphas/Dots.png", pngBytes(16), {}});+ e.push_back({"macros/Prep.sfmacro", bytes("# name: Prep\nmask_clear\nmask_all\n"), {}});+ return e;+}++bool review(const std::vector<RawEntry>& entries, std::string& error, PackReview* out = nullptr,+ const PackLimits& limits = {}) {+ std::vector<PackFile> files;+ if (!readPackArchiveBytes(buildZip(entries), files, error, limits)) return false;+ PackReview r;+ if (!reviewPackFiles(std::move(files), r, error)) return false;+ if (out) *out = std::move(r);+ return true;+}++bool contains(const std::string& s, const std::string& part) { return s.find(part) != std::string::npos; }++struct TempRoot {+ fs::path dir;+ explicit TempRoot(const char* name) : dir(fs::temp_directory_path() / name) {+ std::error_code ec;+ fs::remove_all(dir, ec);+ fs::create_directories(dir);+ setPacksRoot((dir / "packs").string());+ setUserMacroDir((dir / "macros").string());+ }+ ~TempRoot() {+ setPacksRoot("");+ setUserMacroDir("");+ setPacksSafeMode(false);+ std::error_code ec;+ fs::remove_all(dir, ec);+ }+};++} // namespace++TEST(pack_good_archive_reviews) {+ TempRoot root("sf_pack_good");+ std::string err;+ PackReview r;+ CHECK(review(goodEntries(), err, &r));+ CHECK(err.empty());+ CHECK(r.manifest.id == "test-pack");+ CHECK(r.counts[size_t(PackItemType::Brush)] == 1);+ CHECK(r.counts[size_t(PackItemType::Alpha)] == 1);+ CHECK(r.counts[size_t(PackItemType::Macro)] == 1);+ CHECK(r.licenseText == "CC0 1.0 Universal\n");+ CHECK(packCountsText(r.counts) == "1 brush, 1 alpha, 1 macro");+ CHECK(r.installedVersion.empty());+}++TEST(pack_deflated_entries_read) {+ TempRoot root("sf_pack_deflate");+ auto e = goodEntries();+ e[2].method = 8;+ e[2].packed = deflateStored(e[2].data);+ std::string err;+ CHECK(review(e, err));+ // Flipped byte: the checksum catches it.+ e[2].packed.back() ^= 1;+ CHECK(!review(e, err));+ CHECK(contains(err, "checksum"));+}++TEST(pack_rejects_traversal_and_odd_names) {+ TempRoot root("sf_pack_names");+ const char* bad[] = {"../evil.sfbrush", "brushes/../../evil.sfbrush", "/etc/passwd", "C:/evil.sfbrush",+ "brushes\\..\\evil.sfbrush", "~/evil.sfbrush", "brushes/./x.sfbrush", ".hidden",+ "brushes/CON.sfbrush", "brushes/a|b.sfbrush", "brushes/x.sfbrush ", "a/b/c/d.sfbrush",+ "brushes//x.sfbrush"};+ for (const char* name : bad) {+ auto e = goodEntries();+ e.push_back({name, bytes(brushJson("X")), {}});+ std::string err;+ CHECK(!review(e, err));+ CHECK(!err.empty());+ }+ std::string err;+ CHECK(!packEntryNameOk("../x", err));+ CHECK(contains(err, ".."));+ CHECK(!packEntryNameOk("/abs", err));+ CHECK(contains(err, "absolute"));+ CHECK(!packEntryNameOk("D:x", err));+ CHECK(contains(err, "drive"));+ CHECK(!packEntryNameOk(std::string("bad\x01name"), err));+ CHECK(contains(err, "control"));+ CHECK(packEntryNameOk("brushes/Dragon Scales (v2).sfbrush", err));+ // A NUL inside a name (some tools stop reading there).+ auto e = goodEntries();+ e.push_back({std::string("brushes/a.sfbrush\0.png", 23), bytes(brushJson("X")), {}});+ CHECK(!review(e, err));+ CHECK(contains(err, "NUL"));+}++TEST(pack_rejects_symlinks_and_devices) {+ TempRoot root("sf_pack_links");+ auto e = goodEntries();+ e[2].madeBy = 3 << 8; // Unix+ e[2].external = 0120777u << 16; // symbolic link+ e[2].data = bytes("/etc/passwd");+ std::string err;+ CHECK(!review(e, err));+ CHECK(contains(err, "symbolic link"));+ e = goodEntries();+ e[2].madeBy = 3 << 8;+ e[2].external = 0020644u << 16; // character device+ CHECK(!review(e, err));+ CHECK(contains(err, "special file"));+ e = goodEntries();+ e[2].madeBy = 3 << 8;+ e[2].external = 0100644u << 16; // a plain file is fine+ CHECK(review(e, err));+}++TEST(pack_rejects_zip_bombs) {+ TempRoot root("sf_pack_bomb");+ // Honest sizes, huge ratio: refused before anything is unpacked.+ auto e = goodEntries();+ RawEntry bomb{"alphas/Bomb.png", {}, deflateZeros(40000), 8};+ bomb.data.assign(1 + 258 * 40000, 0);+ e.push_back(bomb);+ std::string err;+ CHECK(!review(e, err));+ CHECK(contains(err, "zip bomb"));+ // Lying sizes: the stream inflates to more than it says; the bounded buffer stops it.+ e = goodEntries();+ RawEntry liar{"alphas/Liar.png", std::vector<uint8_t>(1000, 0), deflateZeros(40000), 8};+ e.push_back(liar);+ CHECK(!review(e, err));+ CHECK(contains(err, "stated size"));+ // Too big unpacked, too many files, too big a file.+ PackLimits small;+ small.totalBytes = 300;+ CHECK(!review(goodEntries(), err, nullptr, small));+ CHECK(contains(err, "too big unpacked"));+ small = {};+ small.entries = 3;+ CHECK(!review(goodEntries(), err, nullptr, small));+ CHECK(contains(err, "too many files"));+ small = {};+ small.fileBytes = 100;+ CHECK(!review(goodEntries(), err, nullptr, small));+ CHECK(contains(err, "too big"));+}++TEST(pack_rejects_overlapping_entries) {+ TempRoot root("sf_pack_overlap");+ // Two directory records pointing at the same local data (the "better zip bomb" trick).+ std::vector<uint8_t> z = buildZip(goodEntries());+ // Patch the second central record's local offset to the first's (0).+ size_t cd = 0;+ for (size_t i = z.size() - 22; i > 0; --i)+ if (z[i] == 0x50 && z[i + 1] == 0x4B && z[i + 2] == 0x05 && z[i + 3] == 0x06) {+ cd = size_t(z[i + 16] | z[i + 17] << 8 | z[i + 18] << 16 | uint32_t(z[i + 19]) << 24);+ break;+ }+ const size_t first = cd;+ const size_t second = first + 46 + size_t(z[first + 28] | z[first + 29] << 8);+ for (int k = 0; k < 4; ++k) z[second + 42 + size_t(k)] = 0;+ std::vector<PackFile> files;+ std::string err;+ CHECK(!readPackArchiveBytes(z, files, err));+ CHECK(!err.empty());+}++TEST(pack_rejects_bad_manifests) {+ TempRoot root("sf_pack_json");+ auto withManifest = [](const std::string& m) {+ auto e = goodEntries();+ e[0].data = bytes(m);+ return e;+ };+ std::string err;+ CHECK(!review(withManifest("{"), err));+ CHECK(contains(err, "not valid JSON"));+ CHECK(!review(withManifest("[1,2]"), err));+ CHECK(contains(err, "object"));+ CHECK(!review(withManifest(manifest("", ",\"id\":\"other\"")), err));+ CHECK(contains(err, "Duplicate key"));+ CHECK(!review(withManifest(manifest("", ",\"run\":\"install.sh\"")), err));+ CHECK(contains(err, "unknown key"));+ CHECK(!review(withManifest(manifest("{\"type\":\"script\",\"path\":\"brushes/x.sfbrush\"}")), err));+ CHECK(contains(err, "unknown type"));+ std::string m = manifest("");+ m.replace(m.find("\"formatVersion\":1"), 17, "\"formatVersion\":2");+ CHECK(!review(withManifest(m), err));+ CHECK(contains(err, "formatVersion"));+ m = manifest("");+ m.replace(m.find("test-pack"), 9, "../evil");+ CHECK(!review(withManifest(m), err));+ CHECK(contains(err, "\"id\""));+ CHECK(!review(withManifest(manifest("", ",\"minAppVersion\":\"99.0\"")), err));+ CHECK(contains(err, "needs SculptForge 99.0"));+ CHECK(!review(withManifest(manifest("", ",\"version\":2")), err)); // also a duplicate+ CHECK(!review(withManifest(manifest("", ",\"description\":\"a\\u0007b\"")), err));+ CHECK(contains(err, "control characters"));+ // No manifest at all.+ auto e = goodEntries();+ e.erase(e.begin());+ CHECK(!review(e, err));+ CHECK(contains(err, "no pack.json"));+ // The channel is display only, but must be well formed.+ PackReview r;+ CHECK(review(withManifest(manifest("{\"type\":\"brush\",\"path\":\"brushes/Pack Clay.sfbrush\"},"+ "{\"type\":\"alpha\",\"path\":\"alphas/Dots.png\"},"+ "{\"type\":\"macro\",\"path\":\"macros/Prep.sfmacro\"}",+ ",\"channel\":\"insider\"")),+ err, &r));+ CHECK(r.manifest.channel == "insider");+ CHECK(!review(withManifest(manifest("", ",\"channel\":\"Insider Only!\"")), err));+}++TEST(pack_rejects_wrong_file_types) {+ TempRoot root("sf_pack_types");+ std::string err;+ auto e = goodEntries();+ e.push_back({"install.sh", bytes("#!/bin/sh\nrm -rf ~\n"), {}});+ CHECK(!review(e, err));+ CHECK(contains(err, "not a file a pack may hold"));+ e = goodEntries();+ e.push_back({"brushes/plugin.so", bytes("\x7f" "ELF"), {}});+ CHECK(!review(e, err));+ CHECK(contains(err, "not listed"));+ // Listed under a wrong extension.+ e = goodEntries();+ e[0].data = bytes(manifest("{\"type\":\"brush\",\"path\":\"brushes/x.py\"}"));+ CHECK(!review(e, err));+ CHECK(contains(err, "not a file type"));+ // In the wrong folder.+ e = goodEntries();+ e[0].data = bytes(manifest("{\"type\":\"brush\",\"path\":\"alphas/x.sfbrush\"}"));+ CHECK(!review(e, err));+ CHECK(contains(err, "directly in brushes/"));+ // A "PNG" that is a script.+ e = goodEntries();+ e[3].data = bytes("#!/bin/sh\necho hi\n");+ CHECK(!review(e, err));+ CHECK(contains(err, "Dots.png"));+ // A JPEG behind a .png name is refused too (the bytes must match the name).+ // A brush that isn't one.+ e = goodEntries();+ e[2].data = bytes("{\"format\":\"something else\"}");+ CHECK(!review(e, err));+ CHECK(contains(err, "not a valid brush"));+ // A brush with a duplicated key.+ e = goodEntries();+ e[2].data = bytes("{\"name\":\"a\",\"name\":\"b\"}");+ CHECK(!review(e, err));+ // Listed but missing, and in the pack twice (case-insensitively).+ e = goodEntries();+ e.erase(e.begin() + 3);+ CHECK(!review(e, err));+ CHECK(contains(err, "doesn't hold it"));+ e = goodEntries();+ e.push_back({"BRUSHES/pack clay.sfbrush", bytes(brushJson("Y")), {}});+ CHECK(!review(e, err));+ CHECK(contains(err, "twice"));+ // Encrypted.+ e = goodEntries();+ e[2].flags = 1;+ CHECK(!review(e, err));+ CHECK(contains(err, "encrypted"));+ // A macro that reaches the network, or a file outside the project.+ e = goodEntries();+ e[4].data = bytes("brush_gallery_install name=x\n");+ CHECK(!review(e, err));+ CHECK(contains(err, "not allowed in a macro"));+ e = goodEntries();+ e[4].data = bytes("export_glb path=/home/someone/.bashrc\n");+ CHECK(!review(e, err));+ CHECK(contains(err, "not inside the project folder"));+ // Junk after the archive, and not a zip at all.+ std::vector<uint8_t> z = buildZip(goodEntries());+ z.push_back(0);+ std::vector<PackFile> files;+ CHECK(!readPackArchiveBytes(z, files, err));+ CHECK(!readPackArchiveBytes(bytes("hello"), files, err));+ CHECK(contains(err, "not a zip"));+}++TEST(pack_install_list_toggle_remove) {+ TempRoot root("sf_pack_install");+ PackReview r;+ std::string err;+ CHECK(review(goodEntries(), err, &r));+ CHECK(installPack(r, err));+ auto packs = listInstalledPacks();+ CHECK(packs.size() == 1);+ CHECK(packs.size() == 1 && packs[0].enabled && packs[0].manifest.name == "Test Pack");+ CHECK(fs::is_regular_file(root.dir / "packs" / "test-pack" / "brushes" / "Pack Clay.sfbrush"));++ // Its brush joins the library tagged with the pack; a pack brush named like a built-in gets the pack's name.+ BrushLibraryPaths paths;+ applyPacksToBrushLibrary(paths);+ CHECK(paths.packs.size() == 1);+ Document doc;+ loadBrushLibrary(doc, paths);+ int found = -1;+ for (size_t i = 0; i < doc.brushes.size(); ++i)+ if (doc.brushes[i].name == "Pack Clay") found = int(i);+ CHECK(found >= 0);+ CHECK(found >= 0 && doc.brushes[size_t(found)].origin.source == BrushSource::Pack);+ CHECK(found >= 0 && doc.brushes[size_t(found)].origin.pack == "Test Pack");+ CHECK(enabledPackItems(PackItemType::Alpha).size() == 1);+ CHECK(enabledPackItems(PackItemType::Alpha)[0].label() == "Dots (Test Pack)");++ // Reviewing it again names the installed version.+ PackReview again;+ CHECK(review(goodEntries(), err, &again));+ CHECK(again.installedVersion == "1.0");++ // Off: its items leave the lists; on again: back.+ CHECK(setPackEnabled("test-pack", false, err));+ CHECK(!listInstalledPacks()[0].enabled);+ CHECK(enabledPackItems(PackItemType::Alpha).empty());+ applyPacksToBrushLibrary(paths);+ CHECK(paths.packs.empty());+ CHECK(setPackEnabled("test-pack", true, err));+ CHECK(enabledPackItems(PackItemType::Alpha).size() == 1);+ // Safe mode: no pack at all, without changing what is enabled.+ setPacksSafeMode(true);+ CHECK(enabledPackItems(PackItemType::Alpha).empty());+ applyPacksToBrushLibrary(paths);+ CHECK(paths.packs.empty());+ setPacksSafeMode(false);++ // An update replaces the folder; a removed pack leaves nothing behind.+ CHECK(installPack(again, err));+ CHECK(listInstalledPacks().size() == 1);+ CHECK(!removePack("../packs", err));+ CHECK(removePack("test-pack", err));+ CHECK(listInstalledPacks().empty());+ CHECK(!fs::exists(root.dir / "packs" / "test-pack"));+ CHECK(!removePack("test-pack", err));+}++TEST(pack_never_replaces_builtin_brushes) {+ TempRoot root("sf_pack_builtin");+ const std::string builtin = builtinBrushRecipes().front().name;+ auto e = goodEntries();+ e[2].data = bytes(brushJson(builtin));+ PackReview r;+ std::string err;+ CHECK(review(e, err, &r));+ CHECK(installPack(r, err));+ BrushLibraryPaths paths;+ applyPacksToBrushLibrary(paths);+ Document doc;+ loadBrushLibrary(doc, paths);+ int builtinAt = -1, packAt = -1;+ for (size_t i = 0; i < doc.brushes.size(); ++i) {+ if (doc.brushes[i].name == builtin) builtinAt = int(i);+ if (doc.brushes[i].name == builtin + " (Test Pack)") packAt = int(i);+ }+ CHECK(builtinAt >= 0 && doc.brushes[size_t(builtinAt)].origin.source == BrushSource::Builtin);+ CHECK(packAt >= 0);+}++TEST(pack_write_round_trip) {+ TempRoot root("sf_pack_write");+ const fs::path src = root.dir / "src";+ fs::create_directories(src);+ {+ std::ofstream(src / "Ridge.sfbrush") << brushJson("Ridge");+ const auto png = pngBytes(8);+ std::ofstream(src / "Grain.png", std::ios::binary).write(reinterpret_cast<const char*>(png.data()), std::streamsize(png.size()));+ std::ofstream(src / "Prep.sfmacro") << "# name: Prep\nmask_all\nexport_glb path=out/prep.glb\n";+ }+ KeymapFile k;+ k.name = "Mine";+ k.shortcuts = {{"brush.clay", "Shift+C"}};+ const std::string keymap = keymapFileText(k);+ RadialMenu menu;+ menu.name = "Tools";+ menu.slots = {{"brush.clay", "", ""}};+ const std::string pie = radialMenuFileText(menu);+ std::vector<PackSource> items = {+ {PackItemType::Brush, (src / "Ridge.sfbrush").string(), "", {}},+ {PackItemType::Alpha, (src / "Grain.png").string(), "", {}},+ {PackItemType::Macro, (src / "Prep.sfmacro").string(), "", {}},+ {PackItemType::Keymap, "", "Mine.json", bytes(keymap)},+ {PackItemType::PieMenu, "", "Tools.json", bytes(pie)},+ };+ PackManifest m;+ m.id = "my-pack";+ m.name = "My Pack";+ m.version = "1.2";+ m.author = "Me";+ m.license = "CC-BY-4.0";+ m.channel = "insider";+ std::string err;+ const std::string out = (root.dir / "My Pack.sfpack").string();+ CHECK(writePack(out, m, items, "Attribution 4.0\n", "", err));+ CHECK(err.empty());+ PackReview r;+ CHECK(reviewPack(out, r, err));+ CHECK(r.manifest.channel == "insider");+ CHECK(r.manifest.minAppVersion == appVersion());+ CHECK(r.counts[size_t(PackItemType::Keymap)] == 1 && r.counts[size_t(PackItemType::PieMenu)] == 1);+ CHECK(r.licenseText == "Attribution 4.0\n");+ KeymapFile back;+ CHECK(parseKeymapFile(keymap, back, err) && back.shortcuts.size() == 1 && back.shortcuts[0].second == "Shift+C");+ // The same item twice is refused before anything is written.+ items.push_back(items[0]);+ CHECK(!writePack((root.dir / "twice.sfpack").string(), m, items, "", "", err));+ CHECK(contains(err, "Two items"));+ // A bad keymap.+ CHECK(!parseKeymapFile("{\"format\":\"sculptforge-keymap\",\"version\":1,\"shortcuts\":{\"a b\":\"C\"}}", back, err));+ CHECK(!parseKeymapFile("{\"format\":\"sculptforge-keymap\",\"version\":1,\"shortcuts\":{\"a\":3}}", back, err));+}++TEST(pack_commands) {+ TempRoot root("sf_pack_cmds");+ const fs::path src = root.dir / "layout";+ fs::create_directories(src / "brushes");+ std::ofstream(src / "brushes" / "Cmd Brush.sfbrush") << brushJson("Cmd Brush");+ std::ofstream(src / "LICENSE.txt") << "CC0\n";+ CommandRegistry reg;+ Document doc;+ const std::string out = (root.dir / "cmd.sfpack").string();+ CommandResult r = reg.execute(doc, "pack_create",+ {{"folder", src.string()}, {"path", out}, {"id", std::string("cmd-pack")},+ {"name", std::string("Cmd Pack")}, {"author", std::string("Me")},+ {"license", std::string("CC0-1.0")}});+ CHECK(r.ok);+ r = reg.execute(doc, "pack_install", {{"path", out}});+ CHECK(r.ok);+ CHECK(contains(r.message, "1 brush"));+ r = reg.execute(doc, "pack_list");+ CHECK(r.ok && contains(r.message, "cmd-pack") && contains(r.message, "Cmd Pack 1.0"));+ r = reg.execute(doc, "pack_disable", {{"id", std::string("cmd-pack")}});+ CHECK(r.ok);+ CHECK(contains(reg.execute(doc, "pack_list").message, "- off"));+ r = reg.execute(doc, "pack_remove", {{"id", std::string("cmd-pack")}});+ CHECK(r.ok);+ CHECK(contains(reg.execute(doc, "pack_list").message, "No packs"));+ CHECK(!reg.execute(doc, "pack_install", {{"path", (root.dir / "missing.sfpack").string()}}).ok);+}++// --- Macros ---++TEST(macro_validation) {+ CommandRegistry reg;+ Macro m;+ std::string err;+ CHECK(parseMacro("# name: Clean\n# description: tidy up\nmask_clear\nmask_all # all of it\n", ®, m, err));+ CHECK(m.name == "Clean" && m.description == "tidy up" && m.statements.size() == 2);+ CHECK(!parseMacro("no_such_command\n", ®, m, err));+ CHECK(contains(err, "unknown command"));+ CHECK(!parseMacro("mask_all bogus=1\n", ®, m, err));+ CHECK(contains(err, "unknown parameter"));+ CHECK(!parseMacro("image_to_3d path=?\n", ®, m, err));+ CHECK(contains(err, "not allowed in a macro"));+ CHECK(!parseMacro("macro_run name=x\n", ®, m, err));+ CHECK(!parseMacro("pack_install path=x.sfpack\n", ®, m, err));+ CHECK(!parseMacro("open\n", ®, m, err));+ CHECK(contains(err, "needs path="));+ CHECK(!parseMacro("new_sphere subdivisions=lots\n", ®, m, err));+ CHECK(contains(err, "must be a number"));+ CHECK(!parseMacro("", ®, m, err));+ CHECK(!parseMacro("open path=\"unterminated\n", ®, m, err));+ // File values: "?" or inside the project folder.+ CHECK(parseMacro("open path=?\nexport_glb path=out/head.glb\n", ®, m, err));+ CHECK(macroAsks(m).size() == 1 && macroAsks(m)[0].kind == MacroPathKind::Open);+ for (const char* bad : {"open path=/etc/passwd", "open path=../../secret.obj", "open path=C:\\Windows\\x.obj",+ "open path=~/x.obj", "export_glb path=out/../../x.glb", "open path=\"\\\\server\\share\\x.obj\"",+ "export_glb path=$HOME/x.glb", "export_maps preset=/tmp/evil.json"}) {+ CHECK(!parseMacro(bad, ®, m, err));+ CHECK(!err.empty());+ }+ std::string why;+ CHECK(!macroCommandAllowed("brush_ai", &why) && contains(why, "network"));+ CHECK(macroCommandAllowed("remesh"));+ // Too many commands.+ std::string many;+ for (int i = 0; i < 501; ++i) many += "mask_all\n";+ CHECK(!parseMacro(many, ®, m, err));+ CHECK(contains(err, "too many"));+}++TEST(macro_path_confinement) {+ const fs::path root = fs::temp_directory_path() / "sf_macro_paths";+ std::error_code ec;+ fs::remove_all(root, ec);+ fs::create_directories(root / "project" / "out");+ fs::create_directories(root / "outside");+ std::string out, err;+ CHECK(resolveMacroPath((root / "project").string(), "out/a.glb", out, err));+ CHECK(fs::path(out).parent_path().filename() == "out");+ CHECK(!resolveMacroPath((root / "project").string(), "../outside/a.glb", out, err));+ CHECK(!resolveMacroPath("", "out/a.glb", out, err));+ CHECK(contains(err, "save the project first"));+ CHECK(!resolveMacroPath((root / "project").string(), "?", out, err));+#if !defined(_WIN32)+ // A symbolic link in the project folder that points out of it.+ fs::create_directory_symlink(root / "outside", root / "project" / "escape", ec);+ if (!ec) {+ CHECK(!resolveMacroPath((root / "project").string(), "escape/a.glb", out, err));+ CHECK(contains(err, "outside the project folder"));+ }+#endif+ fs::remove_all(root, ec);+}++TEST(macro_record_play_round_trip) {+ TempRoot tmp("sf_macro_round");+ const fs::path project = tmp.dir / "proj";+ fs::create_directories(project / "out");+ CommandRegistry reg;++ // Record what the user runs.+ MacroRecorder rec;+ rec.start();+ const std::vector<std::pair<std::string, Args>> commands = {+ {"mask_all", {}},+ {"mask_invert", {}},+ {"transform", {{"translate", std::string("0.25,0,0")}, {"masked", false}}},+ {"export_obj_unused", {}}, // (not a command: recorded as typed, refused by validation below)+ {"brush_gallery_install", {{"name", std::string("x")}}}, // never recorded+ {"save_obj", {{"path", (project / "out" / "rec.obj").string()}}},+ {"open", {{"path", (tmp.dir / "elsewhere.obj").string()}}},+ };+ for (const auto& [c, a] : commands) rec.record(c, a, project.string());+ rec.stop();+ CHECK(rec.skipped() == 1);+ CHECK(rec.lines().size() == 6);+ CHECK(rec.lines()[4] == "save_obj path=out/rec.obj"); // inside the project: relative+ CHECK(rec.lines()[5] == "open path=?"); // anywhere else: asked when it runs+ std::vector<std::string> lines(rec.lines().begin(), rec.lines().begin() + 3);+ lines.push_back(rec.lines()[4]);+ const std::string text = macroFileText("Shift It", "moves the sculpt", lines);++ Macro m;+ std::string err;+ CHECK(parseMacro(text, ®, m, err));+ CHECK(m.name == "Shift It" && m.statements.size() == 4);++ // Played back: the same result as running the commands by hand.+ Document direct = makeDoc(makeIcosphere(2));+ reg.execute(direct, "mask_all");+ reg.execute(direct, "mask_invert");+ reg.execute(direct, "transform", {{"translate", std::string("0.25,0,0")}, {"masked", false}});+ Document played = makeDoc(makeIcosphere(2));+ const size_t before = played.undo.undoCount();+ MacroRunContext ctx;+ ctx.projectDir = project.string();+ const MacroRunResult r = runMacro(played, reg, m, ctx);+ CHECK(r.ok);+ CHECK(r.ran == 4);+ CHECK(played.mesh.positions == direct.mesh.positions);+ CHECK(fs::is_regular_file(project / "out" / "rec.obj"));+ // One undo step for the whole macro, and undo brings the sphere back.+ CHECK(r.oneUndoStep);+ CHECK(played.undo.undoCount() == before + 1);+ CHECK(played.undo.undoLabel() == "Macro: Shift It");+ const Document fresh = makeDoc(makeIcosphere(2));+ CHECK(reg.execute(played, "undo").ok);+ CHECK(played.mesh.positions == fresh.mesh.positions);++ // "?" without a way to ask fails; with an answer, it runs.+ Macro ask;+ CHECK(parseMacro("save_obj path=?\n", ®, ask, err));+ Document d = makeDoc(makeIcosphere(1));+ CHECK(!runMacro(d, reg, ask, MacroRunContext{}).ok);+ MacroRunContext answer;+ answer.askPath = [&](const std::string&, const std::string&, MacroPathKind kind) {+ CHECK(kind == MacroPathKind::Save);+ return (tmp.dir / "picked.obj").string();+ };+ CHECK(runMacro(d, reg, ask, answer).ok);+ CHECK(fs::is_regular_file(tmp.dir / "picked.obj"));+ // A relative path without a saved project fails.+ Macro rel;+ CHECK(parseMacro("save_obj path=out/x.obj\n", ®, rel, err));+ const MacroRunResult noProject = runMacro(d, reg, rel, MacroRunContext{});+ CHECK(!noProject.ok && contains(noProject.message, "save the project first"));+}++TEST(macro_library_and_confirmation) {+ TempRoot tmp("sf_macro_lib");+ fs::create_directories(tmp.dir / "macros");+ std::ofstream(tmp.dir / "macros" / "Tidy.sfmacro") << "# name: Tidy\nmask_clear\n";+ std::ofstream(tmp.dir / "macros" / "Broken.sfmacro") << "image_to_3d path=?\n";+ CommandRegistry reg;+ std::vector<std::string> messages;+ const auto macros = listMacros(®, &messages);+ CHECK(macros.size() == 1 && macros[0].name == "Tidy");+ CHECK(messages.size() == 1);+ Macro m;+ std::string err;+ CHECK(findMacro("tidy", ®, m, err));+ CHECK(!findMacro("nothing", ®, m, err));+ CHECK(!macroConfirmed(m.text));+ setMacroConfirmed(m.text);+ CHECK(macroConfirmed(m.text));+ CHECK(!macroConfirmed(m.text + "mask_all\n")); // changed: asked again+ Document doc = makeDoc(makeIcosphere(1));+ CHECK(reg.execute(doc, "macro_run", {{"name", std::string("Tidy")}}).ok);+ CHECK(reg.execute(doc, "macro_check", {{"text", std::string("mask_all")}}).ok);+ CHECK(!reg.execute(doc, "macro_check", {{"text", std::string("open path=/etc/passwd")}}).ok);+ CHECK(macroFileName("a/b:c") == "a_b_c.sfmacro");+}diff --git a/tests/test_python.py b/tests/test_python.pyindex 3abf01eb..2050eb74 100644--- a/tests/test_python.py+++ b/tests/test_python.py@@ -106,4 +106,31 @@ try:except ValueError:pass+# Packs and macros: data only, checked before install; a macro's files stay inside the project folder.+data_home = tempfile.mkdtemp()+os.environ["XDG_DATA_HOME"] = data_home # (packs and macros go to the app data folder; keep the user's untouched)+os.environ["APPDATA"] = data_home+os.environ["HOME"] = data_home+src = tempfile.mkdtemp()+os.makedirs(os.path.join(src, "macros"))+with open(os.path.join(src, "macros", "Prep.sfmacro"), "w") as f:+ f.write("# name: Prep\nmask_clear\nmask_all\n")+pack_path = os.path.join(tempfile.mkdtemp(), "py.sfpack")+sf.run(doc, "pack_create", folder=src, path=pack_path, id="py-pack", name="Py Pack", author="Tester", license="CC0-1.0")+assert "1 macro" in sf.run(doc, "pack_install", path=pack_path)+assert "py-pack" in sf.run(doc, "pack_list")+assert "Prep (Py Pack)" in sf.run(doc, "macro_list")+sf.run(doc, "new_sphere", subdivisions=2)+assert "Ran macro Prep" in sf.run(doc, "macro_run", name="Prep")+bad = os.path.join(src, "bad.sfmacro")+with open(bad, "w") as f:+ f.write("open path=/etc/passwd\n")+try:+ sf.run(doc, "macro_run", path=bad)+ raise AssertionError("expected CommandError")+except sf.CommandError as e:+ assert "not inside the project folder" in str(e)+sf.run(doc, "pack_remove", id="py-pack")+assert "No packs" in sf.run(doc, "pack_list")+print("python api ok:", sf.__version__)diff --git a/tests/ui/data/packs/demo/LICENSE.txt b/tests/ui/data/packs/demo/LICENSE.txtnew file mode 100644index 00000000..59203808--- /dev/null+++ b/tests/ui/data/packs/demo/LICENSE.txt@@ -0,0 +1 @@+CC0 1.0 Universal: no rights reserved. Test data for SculptForge's UI tests.diff --git a/tests/ui/data/packs/demo/alphas/Grit.png b/tests/ui/data/packs/demo/alphas/Grit.pngnew file mode 100644index 00000000..04212513Binary files /dev/null and b/tests/ui/data/packs/demo/alphas/Grit.png differdiff --git a/tests/ui/data/packs/demo/brushes/Pack Ridge.sfbrush b/tests/ui/data/packs/demo/brushes/Pack Ridge.sfbrushnew file mode 100644index 00000000..c8f03d13--- /dev/null+++ b/tests/ui/data/packs/demo/brushes/Pack Ridge.sfbrush@@ -0,0 +1,23 @@+{+ "name": "Pack Ridge",+ "description": "A sharp ridge from the demo pack",+ "direction": "normal",+ "depth": 0.6,+ "plane": "none",+ "planeAmount": 0.5,+ "pinch": 0.5,+ "drag": 0,+ "smooth": 0,+ "hardness": 0,+ "tipSharpness": 0,+ "pattern": "none",+ "patternScale": 0.3,+ "patternAmount": 0,+ "spacing": 0.15,+ "jitter": 0,+ "pressureCurve": 1,+ "frontFacesOnly": false,+ "cavityMask": 0,+ "format": "sfbrush",+ "version": 1+}diff --git a/tests/ui/data/packs/demo/keymaps/Demo Keys.json b/tests/ui/data/packs/demo/keymaps/Demo Keys.jsonnew file mode 100644index 00000000..ba612f74--- /dev/null+++ b/tests/ui/data/packs/demo/keymaps/Demo Keys.json@@ -0,0 +1,8 @@+{+ "format": "sculptforge-keymap",+ "version": 1,+ "name": "Demo Keys",+ "shortcuts": {+ "mask.invert": "Ctrl+Shift+K"+ }+}\ No newline at end of filediff --git a/tests/ui/data/packs/demo/macros/Prep.sfmacro b/tests/ui/data/packs/demo/macros/Prep.sfmacronew file mode 100644index 00000000..a56c1997--- /dev/null+++ b/tests/ui/data/packs/demo/macros/Prep.sfmacro@@ -0,0 +1,4 @@+# name: Prep+# description: Clear the mask, then mask everything+mask_clear+mask_alldiff --git a/tests/ui/data/packs/demo/matcaps/Chalk.png b/tests/ui/data/packs/demo/matcaps/Chalk.pngnew file mode 100644index 00000000..fd9bf5feBinary files /dev/null and b/tests/ui/data/packs/demo/matcaps/Chalk.png differdiff --git a/tests/ui/data/packs/demo/materials/Worn Steel.sfmaterial b/tests/ui/data/packs/demo/materials/Worn Steel.sfmaterialnew file mode 100644index 00000000..853f471e--- /dev/null+++ b/tests/ui/data/packs/demo/materials/Worn Steel.sfmaterial@@ -0,0 +1,38 @@+{+ "format": "sculptforge-material-recipe",+ "version": 1,+ "id": "worn_metal",+ "name": "Worn Metal",+ "description": "Dull steel with bright, polished edges where hands and tools rub it, and dark grime settled in the creases.",+ "layers": [+ {+ "name": "Steel",+ "fill": {+ "material": {"channels": ["base_color", "roughness", "metallic"], "color": [0.48, 0.49, 0.51], "roughness": 0.5, "metallic": 1.0},+ "mask": [{"kind": "fill", "value": 1.0}]+ }+ },+ {+ "name": "Steel Roughness Variation",+ "fill": {+ "material": {"channels": ["roughness"], "roughness": 0.3},+ "mask": [{"kind": "noise", "scale": 0.08, "octaves": 5, "seed": 11, "contrast": 1.2}, {"kind": "levels", "in_low": 0.35, "in_high": 0.85}]+ }+ },+ {+ "name": "Polished Edges",+ "fill": {+ "material": {"channels": ["base_color", "roughness", "metallic"], "color": [0.78, 0.79, 0.8], "roughness": 0.18, "metallic": 1.0},+ "mask": [{"kind": "generator", "generator": "edge_wear", "level": 0.45, "softness": 0.2, "breakup": 0.45, "scale": 0.03, "seed": 3}]+ }+ },+ {+ "name": "Grime",+ "fill": {+ "material": {"channels": ["base_color", "roughness", "metallic"], "color": [0.16, 0.13, 0.1], "roughness": 0.9, "metallic": 0.0},+ "mask": [{"kind": "generator", "generator": "dirt", "level": 0.45, "softness": 0.3, "breakup": 0.5, "scale": 0.05, "seed": 7},+ {"kind": "blur", "radius": 2, "opacity": 1.0}]+ }+ }+ ]+}diff --git a/tests/ui/data/packs/demo/piemenus/Demo Pie.json b/tests/ui/data/packs/demo/piemenus/Demo Pie.jsonnew file mode 100644index 00000000..bec93eeb--- /dev/null+++ b/tests/ui/data/packs/demo/piemenus/Demo Pie.json@@ -0,0 +1,15 @@+{+ "format": "sculptforge-radial-menu",+ "version": 1,+ "menu": {+ "name": "Demo Pie",+ "slots": [+ {+ "action": "mask.invert"+ },+ {+ "action": "mask.clear"+ }+ ]+ }+}\ No newline at end of filediff --git a/tests/ui/data/packs/traversal.sfpack b/tests/ui/data/packs/traversal.sfpacknew file mode 100644index 00000000..47e76a51Binary files /dev/null and b/tests/ui/data/packs/traversal.sfpack differdiff --git a/tests/ui/packs.sfui b/tests/ui/packs.sfuinew file mode 100644index 00000000..e4ce445d--- /dev/null+++ b/tests/ui/packs.sfui@@ -0,0 +1,157 @@+# Packs and macros (#20): a pack made from a folder laid out like one (as the monthly Supporter Pack is), the review+# screen before install (what's inside, the license, the author; nothing is installed until Install), Library >+# Packs (off, on, details), its items in the lists tagged with the pack's name, a hostile pack refused with a clear+# message, and a macro: recorded, saved, found with F3, confirmed before its first run, run as one undo step.+run new_sphere subdivisions=3+expect_value packs_installed == 0+expect_value macros == 0+run pack_create folder="$SCRIPT_DIR/data/packs/demo" path="$LIBRARY/Demo.sfpack" id=demo-pack name="Demo Pack" author="Test Author" license=CC0-1.0 channel=insider++# The review: everything about the pack, before anything is installed.+run pack_install path="$LIBRARY/Demo.sfpack"+expect_value pack_review_open == 1+expect_value pack_review_ok == 1+expect_value pack_review_brush == 1+expect_value pack_review_alpha == 1+expect_value pack_review_matcap == 1+expect_value pack_review_material == 1+expect_value pack_review_keymap == 1+expect_value pack_review_piemenu == 1+expect_value pack_review_macro == 1+expect_value packs_installed == 0+wait_idle 30+expect_text Demo Pack 1.0+expect_text Supporter Pack+expect_text Test Author+expect_text CC0-1.0+expect_text CC0 1.0 Universal+shot pack_review+click "Install##packreview"+expect_value pack_review_open == 0+expect_value packs_installed == 1+expect_value packs_enabled == 1+expect_status Installed Demo Pack 1.0+expect_value pack_brushes == 1+expect_value pack_alphas == 1+expect_value pack_matcaps == 1+expect_value pack_materials == 1+expect_value pack_keymaps == 1+expect_value macros == 1+expect_value macro_actions == 1+expect_value lightbox_open == 1+wait_idle 30+expect_text Demo Pack 1.0+shot packs_tab++# Its items show in the lists with the pack's name.+click "Library/Alpha"+type Library/##lbfilter grit+wait_idle 30+expect_text Grit (Demo Pack)+key backspace+key esc+click "Library/Packs"+click "Library/Details##demo-pack"+expect "Library/Apply keymap Demo Keys##km.demo-pack.Demo Keys"+click "Library/Apply keymap Demo Keys##km.demo-pack.Demo Keys"+expect_shortcut mask.invert Ctrl+Shift+K+expect_status Keymap Demo Keys: 1 keys+click "Library/Add pie menu Demo Pie##pie.demo-pack.Demo Pie"+expect_value radial_menus == 3+expect_value radial_slots_3 == 2++# Off: its items leave the lists; on again: back.+click "Library/##ondemo-pack"+expect_value packs_enabled == 0+expect_value pack_brushes == 0+expect_value pack_alphas == 0+expect_value pack_matcaps == 0+expect_value macro_actions == 0+click "Library/##ondemo-pack"+expect_value packs_enabled == 1+expect_value pack_brushes == 1+expect_value macro_actions == 1++# A hostile pack (a file that climbs out of its folder), dropped on the window, is refused with a clear message;+# nothing is installed.+drop data/packs/traversal.sfpack+expect_value pack_review_open == 1+expect_value pack_review_ok == 0+wait_idle 30+expect_text This pack can't be installed+expect_text leaves its folder+shot pack_refused+click "Close##packreview"+expect_value pack_review_open == 0+expect_value packs_installed == 1++# A macro: Record, run some commands, Stop; the editor opens with them, checked.+click "Library/Record Macro##macro.record"+expect_value macro_recording == 1+run mask_all+run mask_invert+run transform translate=0.2,0,0 masked=false+expect_value macro_recorded == 3+wait_idle 10+shot recording+click "Library/###macro.stop"+expect_value macro_recording == 0+expect_value macro_editor_open == 1+expect_value macro_editor_ok == 1+expect_text 3 commands, all allowed+shot macro_editor+click "Save##macroeditor"+expect_status Saved macro Recorded Macro+expect_value macros == 2+click "Close##macroeditor"+expect_value macro_editor_open == 0+run undo+run undo+run undo++# F3 finds it. Its first run shows every command and asks; Run runs them as one undo step.+snapshot+remember undo_steps before+key f3+type "##Command palette" "recorded macro"+key enter+expect_value macro_confirm_open == 1+wait_idle 10+expect_text transform masked=false translate=0.2,0,0+shot macro_confirm+click "Run##macroconfirm"+expect_value macro_confirm_open == 0+expect_value macro_ran == 3+expect_value macro_one_step == 1+expect_value moved > 0+expect_value undo_steps == $before+1+run undo+expect_value moved == 0++# The second run doesn't ask again (the text is the one confirmed).+key f3+type "##Command palette" "recorded macro"+key enter+expect_value macro_confirm_open == 0+expect_value moved > 0++# A macro may not reach outside the project folder: the console refuses it before anything runs.+run_fails macro_check text="open path=/etc/passwd"++# New Pack: the user's own items (here the recorded macro and the pie menus), written as a .sfpack that passes the+# same checks as an install.+# (Regression: with changed shortcuts - the keymap applied above - New Pack lists them as a keymap; it once read a+# destroyed temporary there and crashed.)+click "Library/New Pack...##pack.new"+expect_value new_pack_open == 1+expect "New Pack/My shortcuts (1 keys)##npi.keymap.My shortcuts (1 keys)"+type "New Pack/Name##newpack" My Test Pack+type "New Pack/Author##newpack" Tester+click "New Pack/Recorded Macro##npi.macro.Recorded Macro"+wait_idle 10+shot new_pack+click "New Pack/Save Pack...##newpack"+answer_dialog My Test Pack.sfpack+wait 0.2+expect_status Wrote+expect_value new_pack_open == 0