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
ZBrush-style UI, workstream C: help, command palette, console, config, keys
islandmed365749899655
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 3a9eae53..00e7c37e 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -129,6 +129,9 @@ if(SCULPTFORGE_BUILD_APP)src/app/Ui.cppsrc/app/UiLayout.cppsrc/app/LightBoxStubs.cpp+ src/app/CommandPalette.cpp+ src/app/Console.cpp+ src/app/Config.cppsrc/app/PanelMasking.cppsrc/app/PanelPolygroups.cppsrc/app/PanelBrushes.cpp@@ -308,6 +311,11 @@ if(SCULPTFORGE_BUILD_TESTS)add_executable(sculptforge_tests ${SCULPTFORGE_TEST_SOURCES} src/cli/McpServer.cpp)target_include_directories(sculptforge_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests)target_link_libraries(sculptforge_tests PRIVATE sculptforge_core sculptforge_ai)+ if(SCULPTFORGE_BUILD_APP) # the action registry (key chords, shortcut overrides) needs SDL's key names+ target_sources(sculptforge_tests PRIVATE src/app/Actions.cpp)+ target_link_libraries(sculptforge_tests PRIVATE SDL3::SDL3)+ target_compile_definitions(sculptforge_tests PRIVATE SF_TEST_ACTIONS)+ endif()if(MSVC)target_compile_options(sculptforge_tests PRIVATE /utf-8)endif()diff --git a/src/app/Actions.cpp b/src/app/Actions.cppindex dd5b5f8b..12eb1755 100644--- a/src/app/Actions.cpp+++ b/src/app/Actions.cpp@@ -2,13 +2,154 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "app/Actions.h"+#include "core/Commands.h"+#include <algorithm>+#include <cctype>namespace sf {-// Phase 0: registry storage is real; key handling, overrides and MRU are filled in by the help/console workstream.+namespace {++std::string lower(std::string_view s) {+ std::string out(s);+ for (auto& c : out) c = char(std::tolower(static_cast<unsigned char>(c)));+ return out;+}++std::string trim(std::string_view s) {+ size_t a = 0, b = s.size();+ while (a < b && std::isspace(static_cast<unsigned char>(s[a]))) ++a;+ while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;+ return std::string(s.substr(a, b - a));+}++// "subtool_append" -> "Subtool append"+std::string humanize(const std::string& name) {+ std::string out = name;+ for (auto& c : out)+ if (c == '_') c = ' ';+ if (!out.empty()) out[0] = char(std::toupper(static_cast<unsigned char>(out[0])));+ return out;+}++} // namespace++bool isModifierKey(SDL_Keycode key) {+ switch (key) {+ case SDLK_LCTRL: case SDLK_RCTRL: case SDLK_LSHIFT: case SDLK_RSHIFT: case SDLK_LALT: case SDLK_RALT:+ case SDLK_LGUI: case SDLK_RGUI: case SDLK_MODE: case SDLK_CAPSLOCK:+ return true;+ default:+ return false;+ }+}++bool parseChord(std::string_view text, Chord& out) {+ out = Chord{};+ std::string t = trim(text);+ if (t.empty()) return false;+ // Split on '+', but a trailing "+" (or "Ctrl++") is the plus key itself.+ std::vector<std::string> parts;+ std::string cur;+ for (size_t i = 0; i < t.size(); ++i) {+ if (t[i] == '+' && !cur.empty()) {+ parts.push_back(trim(cur));+ cur.clear();+ } else {+ cur += t[i];+ }+ }+ parts.push_back(trim(cur));+ std::string key;+ for (size_t i = 0; i < parts.size(); ++i) {+ const std::string p = lower(parts[i]);+ if (i + 1 < parts.size()) {+ if (p == "ctrl" || p == "control" || p == "cmd" || p == "command") out.ctrl = true;+ else if (p == "shift") out.shift = true;+ else if (p == "alt" || p == "option" || p == "opt") out.alt = true;+ else return false;+ } else {+ key = parts[i];+ }+ }+ if (key.empty()) return false;+ if (key.size() == 1) {+ const unsigned char c = static_cast<unsigned char>(key[0]);+ if (!std::isprint(c) || c == ' ') return false;+ out.key = SDL_Keycode(std::tolower(c)); // SDL keycodes of printable keys are their (lower-case) characters+ return true;+ }+ const std::string k = lower(key);+ if (k == "enter") key = "Return";+ else if (k == "esc") key = "Escape";+ else if (k == "comma") key = ",";+ else if (k == "backtick" || k == "grave") key = "`";+ else if (k == "del") key = "Delete";+ out.key = SDL_GetKeyFromName(key.c_str());+ return out.key != SDLK_UNKNOWN;+}++std::vector<Chord> parseChords(std::string_view text) {+ std::vector<Chord> out;+ size_t start = 0;+ while (start <= text.size()) {+ size_t at = text.find(" / ", start);+ const std::string_view part = text.substr(start, at == std::string_view::npos ? std::string_view::npos : at - start);+ Chord c;+ if (parseChord(part, c)) out.push_back(c);+ if (at == std::string_view::npos) break;+ start = at + 3;+ }+ return out;+}++namespace {++std::string keyName(SDL_Keycode key) {+ if (key > 32 && key < 127) return std::string(1, char(std::toupper(int(key))));+ if (key == SDLK_RETURN) return "Enter";+ if (key == SDLK_ESCAPE) return "Esc";+ const char* name = SDL_GetKeyName(key);+ return name && *name ? name : "?";+}++} // namespace++std::string chordText(const Chord& c) {+ if (c.key == SDLK_UNKNOWN) return {};+ std::string s;+ if (c.ctrl) s += "Ctrl+";+ if (c.alt) s += "Alt+";+ if (c.shift) s += "Shift+";+ return s + keyName(c.key);+}++Chord chordFromEvent(SDL_Keycode key, SDL_Keymod mods) {+ Chord c;+ c.key = key;+ c.ctrl = (mods & (SDL_KMOD_CTRL | SDL_KMOD_GUI)) != 0;+ c.shift = (mods & SDL_KMOD_SHIFT) != 0;+ c.alt = (mods & SDL_KMOD_ALT) != 0;+ return c;+}++std::vector<std::string> chordKeys(std::string_view chord) {+ std::vector<std::string> keys;+ Chord c;+ if (!parseChord(chord, c)) {+ if (!chord.empty()) keys.emplace_back(chord);+ return keys;+ }+ if (c.ctrl) keys.emplace_back("Ctrl");+ if (c.alt) keys.emplace_back("Alt");+ if (c.shift) keys.emplace_back("Shift");+ keys.push_back(keyName(c.key));+ return keys;+}void ActionRegistry::add(Action a) {+ ++revision_;for (auto& existing : actions_)if (existing.id == a.id) {existing = std::move(a);@@ -23,7 +164,39 @@ const Action* ActionRegistry::find(std::string_view id) const {return nullptr;}-bool ActionRegistry::handleKey(SDL_Keycode, SDL_Keymod) { return false; }+const std::vector<Chord>& ActionRegistry::chordsOf(size_t index) const {+ if (chordsRevision_ != revision_ || chords_.size() != actions_.size()) {+ chords_.clear();+ for (const auto& a : actions_) chords_.push_back(parseChords(shortcutText(a.id)));+ chordsRevision_ = revision_;+ }+ return chords_[index];+}++const Action* ActionRegistry::actionForChord(const Chord& chord) const {+ for (size_t i = 0; i < actions_.size(); ++i)+ for (const Chord& c : chordsOf(i))+ if (c == chord) return &actions_[i];+ return nullptr;+}++bool ActionRegistry::handleKey(SDL_Keycode key, SDL_Keymod mods) {+ if (isModifierKey(key)) return false;+ Chord chord = chordFromEvent(key, mods);+ const Action* a = actionForChord(chord);+ if (!a && !chord.ctrl && (chord.shift || chord.alt)) {+ // Exact chords win; otherwise plain keys ignore Shift and Alt as they always have (Shift+[ while+ // smoothing still resizes the brush).+ chord.shift = chord.alt = false;+ a = actionForChord(chord);+ }+ if (!a || !a->run) return false;+ if (a->enabled && !a->enabled()) return true; // bound, just not available right now+ // Copy: running an action may register or replace actions.+ const std::function<void()> run = a->run;+ run();+ return true;+}std::string ActionRegistry::shortcutText(std::string_view id) const {for (const auto& [oid, chord] : overrides_)@@ -33,12 +206,48 @@ std::string ActionRegistry::shortcutText(std::string_view id) const {}void ActionRegistry::setShortcut(std::string_view id, std::string chord) {- for (auto& [oid, c] : overrides_)- if (oid == id) {- c = std::move(chord);+ ++revision_;+ const Action* a = find(id);+ const bool isDefault = a && a->shortcut == chord;+ for (auto it = overrides_.begin(); it != overrides_.end(); ++it)+ if (it->first == id) {+ if (isDefault) overrides_.erase(it);+ else it->second = std::move(chord);return;}- overrides_.emplace_back(std::string(id), std::move(chord));+ if (!isDefault) overrides_.emplace_back(std::string(id), std::move(chord));+}++std::string ActionRegistry::assignShortcut(std::string_view id, const std::string& chordString) {+ Chord chord;+ if (!parseChord(chordString, chord)) {+ setShortcut(id, "");+ return {};+ }+ std::string lost;+ for (const auto& other : actions_) {+ if (other.id == id) continue;+ const std::vector<Chord> theirs = parseChords(shortcutText(other.id));+ if (std::find(theirs.begin(), theirs.end(), chord) == theirs.end()) continue;+ std::string keep;+ for (const Chord& c : theirs)+ if (!(c == chord)) keep += (keep.empty() ? "" : " / ") + chordText(c);+ lost = other.label;+ setShortcut(other.id, keep);+ }+ setShortcut(id, chordText(chord));+ return lost;+}++bool ActionRegistry::hasOverride(std::string_view id) const {+ for (const auto& o : overrides_)+ if (o.first == id) return true;+ return false;+}++void ActionRegistry::clearOverrides() {+ overrides_.clear();+ ++revision_;}Json ActionRegistry::overridesToJson() const {@@ -47,7 +256,13 @@ Json ActionRegistry::overridesToJson() const {return j;}-void ActionRegistry::overridesFromJson(const Json&) {}+void ActionRegistry::overridesFromJson(const Json& j) {+ overrides_.clear();+ ++revision_;+ if (!j.isObject()) return;+ for (const auto& [id, chord] : j.members())+ if (chord.isString()) overrides_.emplace_back(id, chord.asString());+}void ActionRegistry::touch(std::string_view id) {recent_.erase(std::remove(recent_.begin(), recent_.end(), std::string(id)), recent_.end());@@ -55,4 +270,25 @@ void ActionRegistry::touch(std::string_view id) {if (recent_.size() > 20) recent_.resize(20);}+void ActionRegistry::registerCommands(const CommandRegistry& commands, std::function<void(const std::string&)> run,+ std::function<void(const std::string&)> prefill) {+ for (const Command& c : commands.all()) {+ const bool needsArgs = std::any_of(c.params.begin(), c.params.end(), [](const ParamSpec& p) { return p.required; });+ Action a;+ a.id = "cmd." + c.name;+ a.label = humanize(c.name) + (needsArgs ? "..." : "");+ a.description = c.description;+ a.palette = "Script";+ a.command = c.name;+ const std::string name = c.name;+ if (needsArgs) a.run = [prefill, name] { prefill(name); };+ else a.run = [run, name] { run(name); };+ if (const Action* existing = find(a.id)) { // keep a shortcut someone gave it+ a.shortcut = existing->shortcut;+ if (existing->icon) a.icon = existing->icon;+ }+ add(std::move(a));+ }+}+} // namespace sfdiff --git a/src/app/Actions.h b/src/app/Actions.hindex f5af51cc..d994c486 100644--- a/src/app/Actions.h+++ b/src/app/Actions.h@@ -18,6 +18,8 @@namespace sf {+class CommandRegistry;+struct Action {std::string id; // "geometry.subdivide", "ui.lightbox", "brush.clay", "view.wireframe"std::string label; // "Subdivide"@@ -31,6 +33,21 @@ struct Action {std::function<bool()> enabled; // null = always};+// A key chord: "Ctrl+Shift+Z", "Shift+F", ",", "F3". Ctrl also matches Cmd (macOS).+struct Chord {+ SDL_Keycode key = SDLK_UNKNOWN;+ bool ctrl = false, shift = false, alt = false;+ bool operator==(const Chord& o) const { return key == o.key && ctrl == o.ctrl && shift == o.shift && alt == o.alt; }+};+bool parseChord(std::string_view text, Chord& out);+// An action may have several chords, separated by " / " ("Ctrl+Shift+Z / Ctrl+Y").+std::vector<Chord> parseChords(std::string_view text);+std::string chordText(const Chord& chord); // canonical spelling, e.g. "Ctrl+Shift+Z"+Chord chordFromEvent(SDL_Keycode key, SDL_Keymod mods);+bool isModifierKey(SDL_Keycode key);+// The individual keys of a chord, for drawing keycaps: "Ctrl+Shift+Z" -> {"Ctrl", "Shift", "Z"}.+std::vector<std::string> chordKeys(std::string_view chord);+class ActionRegistry {public:void add(Action a); // replaces by id@@ -44,11 +61,31 @@ public:void overridesFromJson(const Json& j);void touch(std::string_view id); // most-recently-used, for the command paletteconst std::vector<std::string>& recent() const { return recent_; }+ void setRecent(std::vector<std::string> ids) { recent_ = std::move(ids); }++ // Like setShortcut, but takes CHORD away from any other action that has it (ZBrush reassigns+ // on conflict). Returns the label of the action that lost it, or "".+ std::string assignShortcut(std::string_view id, const std::string& chord);+ bool hasOverride(std::string_view id) const;+ void clearOverrides();+ // The action that CHORD runs (enabled or not), or nullptr.+ const Action* actionForChord(const Chord& chord) const;+ // Every command becomes "cmd.<name>". Commands with required parameters are listed too: `prefill`+ // is called for them (the console opens with the name typed), `run` for the others. Commands that+ // another action already runs (Action::command) are skipped by the command palette, not here.+ void registerCommands(const CommandRegistry& commands, std::function<void(const std::string&)> run,+ std::function<void(const std::string&)> prefill);+ // Bumped whenever actions or shortcuts change (lets views cache derived data).+ unsigned revision() const { return revision_; }private:+ const std::vector<Chord>& chordsOf(size_t index) const;std::vector<Action> actions_;std::vector<std::pair<std::string, std::string>> overrides_; // id -> chordstd::vector<std::string> recent_;+ unsigned revision_ = 0;+ mutable unsigned chordsRevision_ = ~0u;+ mutable std::vector<std::vector<Chord>> chords_; // parsed effective chords, per action};} // namespace sfdiff --git a/src/app/App.cpp b/src/app/App.cppindex 7617ab4c..4b7a8f77 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -180,6 +180,8 @@ bool App::init(const AppOptions& options) {float density = SDL_GetWindowPixelDensity(window_);float scale = SDL_GetWindowDisplayScale(window_) / (density > 0.0f ? density : 1.0f);if (scale <= 0.0f) scale = 1.0f;+ initUiConfig(headless || !options.demo.empty()); // ui.json (layout, shortcuts, UI scale); never for tests and videos+ if (!headless && uiPrefs_.uiScale > 0.0f) scale = uiPrefs_.uiScale;if (recording) scale = float(options.height) / 900.0f; // UI sized for the video, not this screenuiScale_ = scale;applyStyle();@@ -202,6 +204,7 @@ bool App::init(const AppOptions& options) {io.Fonts->AddFontFromMemoryTTF(const_cast<unsigned char*>(assets::fontLucide), int(assets::fontLucide_size),15.0f * scale, &icons, kIconRanges);}+ addHelpFonts(scale); // Ctrl-help titles (Inter SemiBold) and the console (ProggyClean)if (recording) {fontCaption_ = io.Fonts->AddFontFromMemoryTTF(const_cast<unsigned char*>(assets::fontSemiBold),int(assets::fontSemiBold_size), float(options.height) * 0.042f,@@ -218,6 +221,7 @@ bool App::init(const AppOptions& options) {for (int i = 0; i < int(FileAction::Count); ++i) dialogRequests_[i] = {this, FileAction(i)};initBrushLibrary(); // before a project can bring its own brushesinitProject(); // before opening anything, so it lands in the recent files+ initActions(); // the default shortcuts and every command, for keys, help and the command paletterunCommand("new_sphere");if (!options.openPath.empty()) openPath(options.openPath);if (!options.script.empty()) {@@ -606,46 +610,8 @@ void App::onMouseUp() {}void App::onKey(SDL_Keycode key, SDL_Keymod mod) {- const bool ctrl = ctrlDown(mod);- const bool shift = (mod & SDL_KMOD_SHIFT) != 0;- if (ctrl) {- switch (key) {- case SDLK_Z: runCommand(shift ? "redo" : "undo"); break;- case SDLK_Y: runCommand("redo"); break;- case SDLK_D: runCommand("subdivide"); break;- case SDLK_O: confirmDiscard([this] { openFileDialog(); }); break;- case SDLK_S: saveProjectAs(shift); break;- case SDLK_N: confirmDiscard([this] { runCommand("new_sphere"); }); break;- case SDLK_E: saveFileDialog(FileAction::ExportGlb); break;- case SDLK_U: sendToUnreal(); break;- case SDLK_V: pasteBrush(); break; // a brush code or .sfbrush text- default: break;- }- return;- }- switch (key) {- case SDLK_LEFTBRACKET: radiusPx_ = std::max(2.0f, radiusPx_ / 1.1f); break;- case SDLK_RIGHTBRACKET: radiusPx_ = std::min(800.0f, radiusPx_ * 1.1f); break;- case SDLK_X: symmetry_.x = !symmetry_.x; break;- case SDLK_W: renderSettings_.wireframe = !renderSettings_.wireframe; break;- case SDLK_F: camera_.frame(sceneBounds()); break;- case SDLK_F1: showHelp_ = !showHelp_; break;- case SDLK_P:- paintMode_ = !paintMode_;- if (paintMode_) showPolypaintPanel_ = true; // colour picker at hand- break;- case SDLK_C: pickColorUnderCursor(); break;- default:- // 1-9 pick the first nine brushes, 0 the tenth.- if (key >= SDLK_1 && key <= SDLK_9) {- brush_ = BrushType(key - SDLK_1);- paintMode_ = false;- } else if (key == SDLK_0) {- brush_ = BrushType(9);- paintMode_ = false;- }- break;- }+ if (captureShortcutKey(key, mod)) return; // Ctrl+Alt+click a button, then press its new key+ actions_.handleKey(key, mod); // the shortcut map: Config.cpp initActions()}// ---------------------------------------------------------------------------@@ -845,6 +811,7 @@ void App::runCommand(const std::string& name, const Args& args) {afterCommand(name, args, r);watchActiveBrush();updateTitle();+ consoleEcho(name, args, r); // the console shows every command as a script line}namespace {@@ -1094,40 +1061,7 @@ void App::drawUi() {}ImGui::End();}- if (showHelp_) {- ImGui::SetNextWindowSize(ImVec2(440, 0), ImGuiCond_FirstUseEver);- if (ImGui::Begin("Controls", &showHelp_)) {- ImGui::TextUnformatted(- "Sculpt Left drag on the model\n"- "Invert (subtract) Hold Alt while sculpting\n"- "Smooth Hold Shift while sculpting\n"- "Rotate Left drag on background / right drag\n"- "Pan Alt + left drag background / middle drag\n"- "Zoom Mouse wheel / Ctrl + middle drag\n"- " (Ctrl + left drag background when nothing is masked)\n"- "Paint mask Hold Ctrl while stroking (Ctrl+Alt erases)\n"- "Invert mask Ctrl + click background\n"- "Clear mask Ctrl + drag background\n"- "Isolate polygroup Ctrl+Shift+click (again: invert)\n"- "Hide polygroup Ctrl+Shift+Alt+click\n"- "Show all Ctrl+Shift+click background\n"- "Select SubTool Alt+click it\n"- "Hide outside rect Ctrl+Shift+drag (Alt: inside)\n"- "Brush size [ and ]\n"- "Brushes 1-9, 0\n"- "Paint brush P (colour only; Alt paints white)\n"- "Pick colour C over the model\n"- "Symmetry X X\n"- "Wireframe W\n"- "Frame model F\n"- "Subdivide Ctrl+D\n"- "Undo / Redo Ctrl+Z / Ctrl+Shift+Z\n"- "Open / Save Ctrl+O / Ctrl+S (project; Shift: Save As)\n"- "Tablet pressure is used automatically when a pen is detected.\n"- "Drop a model (.obj/.glb), brush (.sfbrush) or image onto the window.");- }- ImGui::End();- }+ drawHelpConsoleUi(); // console, command palette, Controls (F1), Ctrl-hover help: last, on top}void App::drawMenuBar() {diff --git a/src/app/App.h b/src/app/App.hindex 3191704c..341a93e7 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -4,6 +4,9 @@#include "ai/BrushAssistant.h"#include "app/Actions.h"+#include "app/CommandPalette.h"+#include "app/Config.h"+#include "app/Console.h"#include "app/LightBox.h"#include "app/Pickers.h"#include "app/Thumbnails.h"@@ -449,7 +452,60 @@ private:// ---- end LightBox (B) ----// ---- Help/Console/Config (C): actions, help, command palette, console, config ----+public:+ UiPrefs& uiPrefs() { return uiPrefs_; }+ const CommandRegistry& commands() const { return commands_; }+ ImFont* helpTitleFont() const { return fontHelpTitle_ ? fontHelpTitle_ : ImGui::GetFont(); }+ ImFont* consoleFont() const { return fontConsole_ ? fontConsole_ : ImGui::GetFont(); }+ // The next key press becomes ACTION's shortcut (Ctrl+Alt+click a button, or Preferences > Hotkeys).+ void beginShortcutCapture(const std::string& actionId);+ const std::string& capturingShortcut() const { return capturingShortcut_; }+ void openCommandPalette() { palette_.open(); }+ void setConsoleOpen(bool open);+ void consolePrefill(const std::string& text); // opens the console with TEXT typed+ // Store Config (Ctrl+Shift+I) / Restore Standard UI / Restore Custom UI / Save UI... / Load UI... (Ctrl+L)+ void storeConfig();+ void restoreStandardUi();+ void restoreCustomUi();+ void saveUiDialog();+ void loadUiDialog();+ void queueUiFile(int kind, std::string path); // file dialog callbacks (any thread)++private:+ friend class Console;+ friend class CommandPalette;+ friend void config::drawHotkeysSection(App&);+ friend void config::drawLightBoxSection(App&);+ void initUiConfig(bool deterministic); // reads ui.json before fonts are built (UI scale)+ void initActions(); // the default actions and shortcuts, then every command as cmd.*+ void addHelpFonts(float scale);+ void drawHelpConsoleUi(); // console, command palette, Controls, shortcut capture, Ctrl help+ void drawControlsWindow();+ bool captureShortcutKey(SDL_Keycode key, SDL_Keymod mod);+ void consoleEcho(const std::string& name, const Args& args, const CommandResult& r);+ std::string uiConfigPath() const;+ bool readUiConfig(const std::string& path, std::string& err);+ bool writeUiConfig(const std::string& path, std::string& err);+ std::string layoutKey() const; // the layout without per-session state, to notice edits+ void watchLayoutChanges();+ void saveRecentActions();+ CanvasRect consoleRect() const;+ CanvasRect paletteArea() const;ActionRegistry actions_;+ UiPrefs uiPrefs_;+ Console console_;+ CommandPalette palette_;+ std::string configDir_; // <prefs>/ (ui.json, console_history.txt, recent_actions.txt)+ std::string capturingShortcut_; // action id waiting for a key+ std::string layoutBaseline_; // layoutKey() as last stored / loaded / restored+ bool layoutHintShown_ = false;+ int layoutCheckFrame_ = 0;+ bool uiConfigDeterministic_ = false; // UI tests, renders, recordings: standard layout, nothing read+ ImFont* fontHelpTitle_ = nullptr;+ ImFont* fontConsole_ = nullptr;+ std::string commandSource_; // shown before echoed commands, e.g. "AI" while the agent drives the app+ std::mutex uiFileMutex_;+ std::vector<std::pair<int, std::string>> uiFiles_; // (kind, path) from file dialogs// ---- end Help/Console/Config (C) ----};diff --git a/src/app/CommandPalette.cpp b/src/app/CommandPalette.cppnew file mode 100644index 00000000..7cda07f1--- /dev/null+++ b/src/app/CommandPalette.cpp@@ -0,0 +1,305 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "app/CommandPalette.h"++#include "app/App.h"+#include "app/Ui.h"++#include <IconsLucide.h>+#include <imgui_internal.h>++#include <algorithm>+#include <cctype>+#include <cfloat>+#include <set>++namespace sf {++namespace {++constexpr int kMaxRows = 12;+constexpr int kRecentShown = 8;++std::string lower(std::string_view s) {+ std::string out(s);+ for (auto& c : out) c = char(std::tolower(static_cast<unsigned char>(c)));+ return out;+}++std::vector<std::string> words(const std::string& text) {+ std::vector<std::string> out;+ std::string cur;+ for (char c : text) {+ if (std::isspace(static_cast<unsigned char>(c))) {+ if (!cur.empty()) out.push_back(std::move(cur));+ cur.clear();+ } else {+ cur += char(std::tolower(static_cast<unsigned char>(c)));+ }+ }+ if (!cur.empty()) out.push_back(std::move(cur));+ return out;+}++bool wordStart(const std::string& hay, size_t pos) {+ return pos == 0 || !std::isalnum(static_cast<unsigned char>(hay[pos - 1]));+}++// How well WORD matches HAY (both lower case): 0 = not at all. Substrings beat scattered letters,+// and matches at the start of a word beat matches inside one.+int fuzzy(const std::string& hay, const std::string& word, bool allowScattered = true) {+ if (hay.empty() || word.empty()) return 0;+ if (const size_t pos = hay.find(word); pos != std::string::npos) {+ int s = 60;+ if (pos == 0) s += 40;+ else if (wordStart(hay, pos)) s += 25;+ if (word.size() == hay.size()) s += 20;+ return s;+ }+ if (!allowScattered || word.size() < 2) return 0;+ // Letters in order ("sbdv" -> "subdivide"); each jump costs, word starts are cheap.+ int s = 30;+ size_t at = 0;+ for (size_t i = 0; i < word.size(); ++i) {+ const size_t found = hay.find(word[i], at);+ if (found == std::string::npos) return 0;+ if (i > 0 && found != at && !wordStart(hay, found)) s -= 3;+ at = found + 1;+ }+ return std::max(s, 1);+}++} // namespace++int CommandPalette::score(const Action& a, const std::string& query) {+ const auto ws = words(query);+ if (ws.empty()) return 1;+ const std::string label = lower(a.label), palette = lower(a.palette), id = lower(a.id), command = lower(a.command),+ description = lower(a.description);+ int total = 0;+ for (const auto& w : ws) {+ const int s = 3 * fuzzy(label, w) + 2 * fuzzy(palette, w, false) + 2 * std::max(fuzzy(id, w), fuzzy(command, w)) ++ fuzzy(description, w, false);+ if (s == 0) return 0; // every word must match somewhere+ total += s;+ }+ return total;+}++void CommandPalette::search(App& app) {+ const ActionRegistry& reg = app.actions_;+ if (query_ == lastQuery_ && reg.revision() == lastRevision_) return;+ lastQuery_ = query_;+ lastRevision_ = reg.revision();+ results_.clear();+ selected_ = 0;+ scrollToSelected_ = true;+ const auto& all = reg.all();+ // A command another action already runs is listed once, under that action.+ std::set<std::string> covered;+ for (const auto& a : all)+ if (!a.command.empty() && a.id != "cmd." + a.command) covered.insert(a.command);+ auto listed = [&](const Action& a) {+ if (!a.run || a.label.empty()) return false;+ return a.id.rfind("cmd.", 0) != 0 || !covered.count(a.command);+ };+ auto withDescription = [&](const Action& a) {+ if (!a.description.empty() || a.command.empty()) return a;+ Action copy = a;+ if (const Command* c = app.commands_.find(a.command)) copy.description = c->description;+ return copy;+ };+ if (words(query_).empty()) {+ for (const auto& id : reg.recent()) {+ for (size_t i = 0; i < all.size(); ++i)+ if (all[i].id == id && listed(all[i])) results_.push_back(i);+ if (int(results_.size()) >= kRecentShown) break;+ }+ if (results_.empty()) {+ for (size_t i = 0; i < all.size(); ++i)+ if (listed(all[i])) results_.push_back(i);+ std::stable_sort(results_.begin(), results_.end(), [&](size_t a, size_t b) {+ return lower(all[a].label) < lower(all[b].label);+ });+ }+ return;+ }+ std::vector<std::pair<int, size_t>> scored;+ for (size_t i = 0; i < all.size(); ++i) {+ if (!listed(all[i])) continue;+ if (const int s = score(withDescription(all[i]), query_); s > 0) scored.emplace_back(s, i);+ }+ std::stable_sort(scored.begin(), scored.end(), [&](const auto& a, const auto& b) {+ if (a.first != b.first) return a.first > b.first;+ return lower(all[a.second].label) < lower(all[b.second].label);+ });+ for (const auto& [s, i] : scored) results_.push_back(i);+}++void CommandPalette::draw(App& app, const CanvasRect& area) {+ constexpr const char* kPopup = "##command_palette";+ const float s = app.uiScale_;+ bool focus = false;+ if (openRequested_) {+ openRequested_ = false;+ ImGui::OpenPopup(kPopup);+ query_[0] = 0;+ lastQuery_ = "\x01";+ focus = true;+ }+ const float width = std::min(560.0f * s, area.w - 24.0f * s);+ ImGui::SetNextWindowPos(ImVec2(area.x + (area.w - width) * 0.5f, area.y + 14.0f * s), ImGuiCond_Always);+ ImGui::SetNextWindowSize(ImVec2(width, 0.0f), ImGuiCond_Always);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8.0f * s, 8.0f * s));+ ImGui::PushStyleVar(ImGuiStyleVar_PopupRounding, 6.0f * s);+ ImGui::PushStyleVar(ImGuiStyleVar_PopupBorderSize, 1.0f);+ ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0x25 / 255.0f, 0x25 / 255.0f, 0x28 / 255.0f, 0.98f));+ ImGui::PushStyleColor(ImGuiCol_Border, ImGui::ColorConvertU32ToFloat4(IM_COL32(0xf0, 0x88, 0x2e, 0x70)));+ std::function<void()> pending;+ std::string prefill;+ if (ImGui::BeginPopup(kPopup, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings)) {+ open_ = true;+ ImDrawList* dl = ImGui::GetWindowDrawList();+ // Search field with a magnifier inside its frame.+ const float iconW = ImGui::CalcTextSize(ICON_LC_SEARCH).x + 10.0f * s;+ const ImVec2 fieldPos = ImGui::GetCursorScreenPos();+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(iconW, 6.0f * s));+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::ColorConvertU32ToFloat4(IM_COL32(0x1b, 0x1b, 0x1e, 0xff)));+ ImGui::SetNextItemWidth(-FLT_MIN);+ if (focus) ImGui::SetKeyboardFocusHere();+ ImGui::InputTextWithHint("##Command palette", "Search commands, brushes and settings", query_, sizeof query_);+ ImGui::PopStyleColor();+ ImGui::PopStyleVar();+ dl->AddText(ImVec2(fieldPos.x + 5.0f * s, fieldPos.y + 6.0f * s), ui::color::textDim, ICON_LC_SEARCH);+ search(app);++ const auto& all = app.actions_.all();+ const int n = int(results_.size());+ if (n > 0) {+ if (ImGui::IsKeyPressed(ImGuiKey_DownArrow, true)) selected_ = (selected_ + 1) % n, scrollToSelected_ = true;+ if (ImGui::IsKeyPressed(ImGuiKey_UpArrow, true)) selected_ = (selected_ + n - 1) % n, scrollToSelected_ = true;+ if (ImGui::IsKeyPressed(ImGuiKey_PageDown, true)) selected_ = std::min(n - 1, selected_ + kMaxRows), scrollToSelected_ = true;+ if (ImGui::IsKeyPressed(ImGuiKey_PageUp, true)) selected_ = std::max(0, selected_ - kMaxRows), scrollToSelected_ = true;+ selected_ = std::clamp(selected_, 0, n - 1);+ }+ int run = -1;+ bool toConsole = false;+ if (n > 0 && (ImGui::IsKeyPressed(ImGuiKey_Enter, false) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter, false))) {+ run = selected_;+ toConsole = ImGui::GetIO().KeyShift;+ }++ ImGui::Dummy(ImVec2(0, 2.0f * s));+ if (words(query_).empty() && n > 0 && !app.actions_.recent().empty())+ ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(ui::color::textDim), "Recently used");+ const float rowH = ImGui::GetTextLineHeight() + 10.0f * s;+ if (n == 0) {+ ImGui::Dummy(ImVec2(0, 4.0f * s));+ ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(ui::color::textDim), " No matching commands");+ ImGui::Dummy(ImVec2(0, 4.0f * s));+ } else {+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));+ ImGui::BeginChild("##palette_rows", ImVec2(0, rowH * float(std::min(n, kMaxRows))), ImGuiChildFlags_None,+ ImGuiWindowFlags_NoNav);+ ImDrawList* rows = ImGui::GetWindowDrawList();+ rows->ChannelsSplit(2);+ ImGuiListClipper clipper;+ clipper.Begin(n, rowH);+ if (scrollToSelected_) clipper.IncludeItemByIndex(selected_);+ while (clipper.Step()) {+ for (int r = clipper.DisplayStart; r < clipper.DisplayEnd; ++r) {+ const Action& a = all[results_[size_t(r)]];+ const bool enabled = !a.enabled || a.enabled();+ const ImVec2 p = ImGui::GetCursorScreenPos();+ const float w = ImGui::GetContentRegionAvail().x;+ rows->ChannelsSetCurrent(1);+ ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_HeaderActive, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0, 0, 0, 0));+ if (ImGui::Selectable((a.label + "##pal." + a.id).c_str(), false, ImGuiSelectableFlags_None, ImVec2(w, rowH)))+ run = r;+ ImGui::PopStyleColor(4);+ const bool hovered = ImGui::IsItemHovered();+ if (hovered && (ImGui::GetIO().MouseDelta.x != 0.0f || ImGui::GetIO().MouseDelta.y != 0.0f)) selected_ = r;+ ui::HelpAction(app, a.id.c_str());+ if (r == selected_ && scrollToSelected_) ImGui::SetScrollHereY(0.5f);+ // Row: icon, label, dim palette path, shortcut keycaps on the right.+ const ImU32 fg = enabled ? ui::color::text : ui::color::textDim;+ const float ty = p.y + (rowH - ImGui::GetTextLineHeight()) * 0.5f;+ float x = p.x + 8.0f * s;+ rows->AddText(ImVec2(x, ty), r == selected_ ? ui::color::accent : ui::color::textDim,+ a.icon ? a.icon : ICON_LC_CHEVRON_RIGHT);+ x += ImGui::GetFontSize() + 10.0f * s;+ rows->AddText(ImVec2(x, ty), fg, a.label.c_str());+ x += ImGui::CalcTextSize(a.label.c_str()).x + 10.0f * s;+ const std::string chord = app.actions_.shortcutText(a.id);+ const float keysW = chord.empty() ? 0.0f : ui::KeycapsWidth(chord);+ const float right = p.x + w - 8.0f * s - keysW;+ if (!a.palette.empty()) {+ const ImVec4 clip(x, p.y, right - 8.0f * s, p.y + rowH);+ rows->AddText(nullptr, 0.0f, ImVec2(x, ty), ui::color::textDim, a.palette.c_str(), nullptr, 0.0f, &clip);+ }+ if (!chord.empty()) ui::KeycapsAt(rows, ImVec2(right, ty - 1.0f * s), chord);+ if (ImGui::GetCurrentContext()->LogEnabled) ImGui::LogText("\n%s %s %s", a.label.c_str(), a.palette.c_str(), chord.c_str());+ rows->ChannelsSetCurrent(0);+ if (r == selected_)+ rows->AddRectFilled(p, ImVec2(p.x + w, p.y + rowH), IM_COL32(0xf0, 0x88, 0x2e, 0x30), 4.0f * s);+ else if (hovered)+ rows->AddRectFilled(p, ImVec2(p.x + w, p.y + rowH), IM_COL32(0xff, 0xff, 0xff, 0x0a), 4.0f * s);+ }+ }+ rows->ChannelsMerge();+ scrollToSelected_ = false;+ ImGui::EndChild();+ ImGui::PopStyleVar();+ }+ // Footer: keys.+ ImGui::Dummy(ImVec2(0, 2.0f * s));+ {+ const ImVec4 dim = ImGui::ColorConvertU32ToFloat4(ui::color::textDim);+ auto hint = [&](const char* keys, const char* what) {+ ui::Keycaps(keys);+ ImGui::SameLine(0, 4.0f * s);+ ImGui::TextColored(dim, "%s", what);+ ImGui::SameLine(0, 14.0f * s);+ };+ ImGui::SetWindowFontScale(0.86f);+ hint("Up / Down", "select");+ hint("Enter", "run");+ hint("Shift+Enter", "edit in console");+ hint("Esc", "close");+ const std::string count = std::to_string(n) + (n == 1 ? " result" : " results");+ ImGui::SameLine(ImGui::GetWindowContentRegionMax().x - ImGui::CalcTextSize(count.c_str()).x);+ ImGui::TextColored(dim, "%s", count.c_str());+ ImGui::SetWindowFontScale(1.0f);+ }++ if (ImGui::IsKeyPressed(ImGuiKey_Escape, false)) ImGui::CloseCurrentPopup();+ if (run >= 0 && run < n) {+ const Action& a = all[results_[size_t(run)]];+ ImGui::CloseCurrentPopup();+ app.actions_.touch(a.id);+ app.saveRecentActions();+ const Command* c = a.command.empty() ? nullptr : app.commands_.find(a.command);+ const bool required = c && std::any_of(c->params.begin(), c->params.end(), [](const ParamSpec& p) { return p.required; });+ if (a.enabled && !a.enabled()) {+ app.status_ = a.label + " isn't available right now";+ } else if (c && (required || (toConsole && !c->params.empty()))) {+ prefill = c->name + " ";+ } else {+ pending = a.run;+ }+ }+ ImGui::EndPopup();+ } else {+ open_ = false;+ }+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(3);+ // Run after the popup is closed: actions may open windows or popups of their own.+ if (!prefill.empty()) app.consolePrefill(prefill);+ if (pending) pending();+}++} // namespace sfdiff --git a/src/app/CommandPalette.h b/src/app/CommandPalette.hnew file mode 100644index 00000000..329b5b3e--- /dev/null+++ b/src/app/CommandPalette.h@@ -0,0 +1,39 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Command palette (F3 / Ctrl+Shift+P): fuzzy search over every action and+// command. Enter runs; commands that need parameters open in the console.+#pragma once++#include "app/UiLayout.h"++#include <string>+#include <vector>++namespace sf {++class App;+struct Action;++class CommandPalette {+public:+ void open() { openRequested_ = true; }+ bool isOpen() const { return open_; }+ void draw(App& app, const CanvasRect& area);++ // Ranks actions for QUERY (best first); exposed for tests.+ static int score(const Action& action, const std::string& query);++private:+ void search(App& app);+ bool openRequested_ = false;+ bool open_ = false;+ char query_[256] = "";+ std::string lastQuery_ = "\x01";+ unsigned lastRevision_ = ~0u;+ std::vector<size_t> results_; // indices into ActionRegistry::all()+ int selected_ = 0;+ bool scrollToSelected_ = false;+};++} // namespace sfdiff --git a/src/app/Config.cpp b/src/app/Config.cppnew file mode 100644index 00000000..ad728372--- /dev/null+++ b/src/app/Config.cpp@@ -0,0 +1,788 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Default actions and shortcuts, Store Config / Restore / Save / Load UI,+// the Preferences > Config / Interface / Hotkeys / LightBox sections, the F1+// Controls sheet (generated from the action registry) and ZBrush-style+// shortcut assignment.+#include "app/Config.h"++#include "app/App.h"+#include "app/Ui.h"+#include "core/Script.h"++#include <IconsLucide.h>+#include <imgui_internal.h>++#include <algorithm>+#include <cctype>+#include <cfloat>+#include <cmath>+#include <filesystem>+#include <fstream>+#include <map>++namespace sf {++namespace assets {+extern const unsigned char fontSemiBold[];+extern const unsigned long long fontSemiBold_size;+extern const unsigned char fontLucide[];+extern const unsigned long long fontLucide_size;+} // namespace assets++Json toJson(const UiPrefs& p) {+ Json j = Json::object();+ j.set("popupInfo", p.popupInfo);+ j.set("helpOpacity", double(p.helpOpacity));+ j.set("tooltipDelay", double(p.tooltipDelay));+ j.set("oneSubpalette", p.oneSubpalette);+ j.set("autoCollapseLeft", p.autoCollapseLeft);+ j.set("autoCollapseRight", p.autoCollapseRight);+ j.set("uiScale", double(p.uiScale));+ j.set("lightboxAtStartup", p.lightboxAtStartup);+ j.set("libraryFolder", p.libraryFolder);+ return j;+}++void fromJson(const Json& j, UiPrefs& p) {+ if (!j.isObject()) return;+ p.popupInfo = j["popupInfo"].asBool(p.popupInfo);+ p.helpOpacity = std::clamp(float(j["helpOpacity"].asNumber(p.helpOpacity)), 0.3f, 1.0f);+ p.tooltipDelay = std::clamp(float(j["tooltipDelay"].asNumber(p.tooltipDelay)), 0.0f, 3.0f);+ p.oneSubpalette = j["oneSubpalette"].asBool(p.oneSubpalette);+ p.autoCollapseLeft = j["autoCollapseLeft"].asBool(p.autoCollapseLeft);+ p.autoCollapseRight = j["autoCollapseRight"].asBool(p.autoCollapseRight);+ p.uiScale = std::clamp(float(j["uiScale"].asNumber(p.uiScale)), 0.0f, 3.0f);+ p.lightboxAtStartup = j["lightboxAtStartup"].asBool(p.lightboxAtStartup);+ if (j["libraryFolder"].isString()) p.libraryFolder = j["libraryFolder"].asString();+}++namespace {++enum UiFileKind { kSaveUi, kLoadUi, kRunScript, kLibraryFolder, kUiFileKinds };++struct UiFileRequest {+ App* app = nullptr;+ int kind = 0;+};+UiFileRequest g_requests[kUiFileKinds];++void SDLCALL onUiFileChosen(void* userdata, const char* const* files, int) {+ if (!files || !files[0]) return;+ auto* req = static_cast<UiFileRequest*>(userdata);+ req->app->queueUiFile(req->kind, files[0]);+}++const SDL_DialogFileFilter kUiFilters[] = {{"SculptForge UI layout", "json"}};+const SDL_DialogFileFilter kScriptFilters[] = {{"SculptForge script", "sfscript;txt"}, {"All files", "*"}};++std::filesystem::path fsPath(const std::string& utf8) { return std::filesystem::path(std::u8string(utf8.begin(), utf8.end())); }++bool fileExists(const std::string& path) {+ std::error_code ec;+ return !path.empty() && std::filesystem::is_regular_file(fsPath(path), ec);+}++std::string lower(std::string s) {+ for (auto& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));+ return s;+}++ImVec4 col(ImU32 c) { return ImGui::ColorConvertU32ToFloat4(c); }++// The mouse and pen gestures (not actions, so not in the registry).+struct Gesture {+ const char* what;+ const char* how;+};+constexpr Gesture kGestures[] = {+ {"Sculpt", "Left drag on the model"},+ {"Invert (subtract)", "Hold Alt while sculpting"},+ {"Smooth", "Hold Shift while sculpting"},+ {"Rotate", "Left drag on the background, or right drag"},+ {"Pan", "Alt + left drag on the background, or middle drag"},+ {"Zoom", "Mouse wheel, Ctrl + middle drag, or Ctrl + left drag on the background (nothing masked)"},+ {"Paint mask", "Hold Ctrl while stroking (Ctrl+Alt erases)"},+ {"Invert mask", "Ctrl + click the background"},+ {"Clear mask", "Ctrl + drag on the background"},+ {"Isolate polygroup", "Ctrl+Shift + click it (again: invert)"},+ {"Hide polygroup", "Ctrl+Shift+Alt + click it"},+ {"Show all", "Ctrl+Shift + click the background"},+ {"Hide outside a rectangle", "Ctrl+Shift + drag (add Alt: inside)"},+ {"Select a SubTool", "Alt + click it"},+ {"Help on any control", "Hold Ctrl and point at it (Ctrl+Alt: scripting parameters)"},+ {"Assign a shortcut", "Ctrl+Alt + click any button, then press the key"},+ {"Tablet pressure", "Used automatically when a pen is detected"},+ {"Open files", "Drop a model (.obj, .glb ...), brush (.sfbrush) or image onto the window"},+};++} // namespace++// ---------------------------------------------------------------------------+// Startup+// ---------------------------------------------------------------------------++void App::initUiConfig(bool deterministic) {+ uiConfigDeterministic_ = deterministic;+ if (char* pref = SDL_GetPrefPath("SculptForge", "SculptForge")) {+ configDir_ = pref;+ SDL_free(pref);+ }+ layout_ = standardLayout();+ if (deterministic) return; // tests, renders and recordings always use the standard layout+ std::string err;+ if (fileExists(uiConfigPath()) && !readUiConfig(uiConfigPath(), err)) SDL_Log("%s", err.c_str());+}++void App::addHelpFonts(float scale) {+ ImGuiIO& io = ImGui::GetIO();+ ImFontConfig cfg;+ cfg.FontDataOwnedByAtlas = false;+ cfg.OversampleH = 2;+ fontHelpTitle_ = io.Fonts->AddFontFromMemoryTTF(const_cast<unsigned char*>(assets::fontSemiBold),+ int(assets::fontSemiBold_size), 15.0f * scale, &cfg);+ static const ImWchar kIconRanges[] = {ICON_MIN_LC, ICON_MAX_LC, 0};+ ImFontConfig icons;+ icons.MergeMode = true;+ icons.PixelSnapH = true;+ icons.FontDataOwnedByAtlas = false;+ icons.GlyphMinAdvanceX = 15.0f * scale;+ icons.GlyphOffset = ImVec2(0, 2.0f * scale);+ io.Fonts->AddFontFromMemoryTTF(const_cast<unsigned char*>(assets::fontLucide), int(assets::fontLucide_size), 15.0f * scale,+ &icons, kIconRanges);+ // ProggyClean (ships inside Dear ImGui) is a pixel font: keep it at whole multiples of 13 px.+ ImFontConfig mono;+ mono.SizePixels = 13.0f * std::max(1.0f, std::floor(scale + 0.25f));+ fontConsole_ = io.Fonts->AddFontDefault(&mono);+}++void App::initActions() {+ for (int i = 0; i < kUiFileKinds; ++i) g_requests[i] = {this, i};+ auto add = [&](const char* id, const char* label, const char* palette, const char* shortcut, std::function<void()> run,+ const char* icon = nullptr, const char* command = nullptr, std::function<bool()> checked = nullptr,+ std::function<bool()> enabled = nullptr, const char* description = nullptr) {+ Action a;+ a.id = id;+ a.label = label;+ a.palette = palette;+ a.shortcut = shortcut ? shortcut : "";+ a.run = std::move(run);+ a.icon = icon;+ a.command = command ? command : "";+ a.checked = std::move(checked);+ a.enabled = std::move(enabled);+ if (description) a.description = description;+ else if (const Command* c = a.command.empty() ? nullptr : commands_.find(a.command)) a.description = c->description;+ actions_.add(std::move(a));+ };++ // --- The shortcuts SculptForge always had (unchanged meaning) ---+ add("edit.undo", "Undo", "Edit", "Ctrl+Z", [this] { runCommand("undo"); }, ICON_LC_UNDO_2, "undo", nullptr,+ [this] { return doc_.undo.canUndo(); });+ add("edit.redo", "Redo", "Edit", "Ctrl+Shift+Z / Ctrl+Y", [this] { runCommand("redo"); }, ICON_LC_REDO_2, "redo", nullptr,+ [this] { return doc_.undo.canRedo(); });+ add("geometry.subdivide", "Subdivide", "Tool > Geometry", "Ctrl+D", [this] { runCommand("subdivide"); }, nullptr, "subdivide");+ add("file.new_sphere", "New Sphere", "File", "Ctrl+N", [this] { confirmDiscard([this] { runCommand("new_sphere"); }); },+ ICON_LC_FILE_PLUS, "new_sphere");+ add("file.new_plane", "New Plane", "File", nullptr, [this] { confirmDiscard([this] { runCommand("new_plane"); }); }, nullptr,+ "new_plane");+ add("file.open", "Open...", "File", "Ctrl+O", [this] { confirmDiscard([this] { openFileDialog(); }); }, ICON_LC_FOLDER_OPEN,+ nullptr, nullptr, nullptr, "Open a project (.sfproj), a model (.obj, .glb, .fbx, .stl, .ply, .usd ...) or splats.");+ add("file.save", "Save", "File", "Ctrl+S", [this] { saveProjectAs(false); }, ICON_LC_SAVE, nullptr, nullptr, nullptr,+ "Save the project (.sfproj: every SubTool, layer, brush and setting). Asks for a name the first time.");+ add("file.save_as", "Save As...", "File", "Ctrl+Shift+S", [this] { saveProjectAs(true); }, nullptr, nullptr, nullptr, nullptr,+ "Save the project under a new name.");+ add("file.export_glb", "Export GLB...", "File > Export", "Ctrl+E", [this] { saveFileDialog(FileAction::ExportGlb); },+ ICON_LC_PACKAGE, nullptr, nullptr, nullptr,+ "Export the model as glTF binary, with sculpt layers as blend shapes (morph targets).");+ add("file.send_unreal", "Send to Unreal", "File > Export", "Ctrl+U", [this] { sendToUnreal(); }, ICON_LC_SEND, nullptr,+ nullptr, [this] { return !pendingUnreal_.valid(); },+ "Export a game-ready FBX and import it into the running Unreal Editor (Python remote execution).");+ add("brush.paste", "Paste brush", "Brush", "Ctrl+V", [this] { pasteBrush(); }, ICON_LC_CLIPBOARD_PASTE, nullptr, nullptr,+ nullptr, "Add the brush on the clipboard: a brush code someone shared, or the text of a .sfbrush file.");+ add("brush.size_down", "Smaller brush", "Draw", "[", [this] { radiusPx_ = std::max(2.0f, radiusPx_ / 1.1f); }, nullptr,+ nullptr, nullptr, nullptr, "Make the brush 10% smaller (hold to repeat).");+ add("brush.size_up", "Larger brush", "Draw", "]", [this] { radiusPx_ = std::min(800.0f, radiusPx_ * 1.1f); }, nullptr,+ nullptr, nullptr, nullptr, "Make the brush 10% larger (hold to repeat).");+ add("transform.symmetry_x", "Symmetry X", "Transform", "X", [this] { symmetry_.x = !symmetry_.x; }, ICON_LC_FLIP_HORIZONTAL_2,+ nullptr, [this] { return symmetry_.x; }, nullptr, "Mirror strokes across the X axis (left / right).");+ add("view.wireframe", "Wireframe", "Render", "W / Shift+F", [this] { renderSettings_.wireframe = !renderSettings_.wireframe; },+ ICON_LC_GRID_3X3, nullptr, [this] { return renderSettings_.wireframe; }, nullptr,+ "Show the mesh's triangles over the surface (ZBrush PolyFrame).");+ add("view.frame", "Frame model", "Transform", "F", [this] { camera_.frame(sceneBounds()); }, ICON_LC_SCAN, nullptr, nullptr,+ nullptr, "Fit the whole model in the view.");+ add("paint.toggle", "Paint mode", "Draw", "P",+ [this] {+ paintMode_ = !paintMode_;+ if (paintMode_) showPolypaintPanel_ = true; // colour picker at hand+ },+ ICON_LC_PAINTBRUSH, nullptr, [this] { return paintMode_; }, nullptr,+ "Switch between sculpting and polypainting (colour only; Alt paints white).");+ add("color.pick", "Pick colour", "Color", "C", [this] { pickColorUnderCursor(); }, ICON_LC_PIPETTE, nullptr, nullptr, nullptr,+ "Take the paint colour from the model under the cursor.");+ for (int i = 0; i < int(BrushType::Count); ++i) {+ const auto type = BrushType(i);+ std::string id = "brush.";+ for (const char* c = brushName(type); *c; ++c)+ if (*c != ' ') id += char(std::tolower(static_cast<unsigned char>(*c)));+ const std::string key = i < 9 ? std::to_string(i + 1) : i == 9 ? std::string("0") : std::string();+ add(id.c_str(), brushName(type), "Brush", key.c_str(),+ [this, type] {+ brush_ = type;+ doc_.activeBrush = -1;+ paintMode_ = false;+ },+ ICON_LC_BRUSH, nullptr, [this, type] { return brush_ == type && doc_.activeBrush < 0 && !paintMode_; }, nullptr,+ (std::string("Sculpt with the ") + brushName(type) + " brush.").c_str());+ }++ // --- Help ---+ add("help.controls", "Controls", "Help", "F1", [this] { showHelp_ = !showHelp_; }, ICON_LC_KEYBOARD, nullptr,+ [this] { return showHelp_; }, nullptr, "Every shortcut and mouse gesture, generated from the commands themselves.");+ add("help.about", "About SculptForge", "Help", nullptr, [this] { showAbout_ = true; }, ICON_LC_INFO, nullptr, nullptr, nullptr,+ "Version, licence and the open-source components SculptForge is built with.");+ add("help.website", "Website & documentation", "Help", nullptr, [] { SDL_OpenURL("https://islandmed.github.io/SculptForge/"); },+ ICON_LC_BOOK_OPEN, nullptr, nullptr, nullptr, "Open the SculptForge website and user guide in your browser.");+ add("help.report", "Report a problem", "Help", nullptr, [] { SDL_OpenURL("https://github.com/islandmed/SculptForge/issues"); },+ ICON_LC_CIRCLE_ALERT, nullptr, nullptr, nullptr, "Open the issue tracker in your browser.");++ // --- Command palette and console ---+ add("ui.command_palette", "Command palette", "Help", "F3 / Ctrl+Shift+P", [this] { palette_.open(); }, ICON_LC_SEARCH, nullptr,+ nullptr, nullptr,+ "Search every command, brush and setting by name and run it. Commands that need parameters open in the console.");+ add("ui.console", "Console", "Script", "`", [this] { setConsoleOpen(!layout_.consoleOpen); }, ICON_LC_SQUARE_TERMINAL, nullptr,+ [this] { return layout_.consoleOpen; }, nullptr,+ "The script console: every command you run appears as a script line, and you can type commands yourself.");+ add("script.run_file", "Run script file...", "Script", nullptr,+ [this] {+ SDL_ShowOpenFileDialog(onUiFileChosen, &g_requests[kRunScript], window_, kScriptFilters, 2, nullptr, false);+ },+ ICON_LC_FILE_CODE, nullptr, nullptr, nullptr, "Run a text file of script statements, one per line (# starts a comment).");+ add("script.copy_session", "Copy session as script", "Script", nullptr,+ [this] {+ const std::string script = console_.sessionScript();+ SDL_SetClipboardText(script.c_str());+ status_ = script.empty() ? "No commands run yet" : "Session copied as a script - paste it into a file to run it again";+ },+ ICON_LC_COPY, nullptr, nullptr, nullptr,+ "Put every command run this session on the clipboard as a script, ready to replay (a macro recorder).");+ add("script.clear_console", "Clear console", "Script", nullptr, [this] { console_.clear(); }, ICON_LC_TRASH_2, nullptr, nullptr,+ nullptr, "Empty the console log (the session script is kept).");++ // --- Config (ZBrush: Preferences > Config) ---+ add("config.store", "Store Config", "Preferences > Config", "Ctrl+Shift+I", [this] { storeConfig(); }, ICON_LC_SAVE, nullptr,+ nullptr, nullptr,+ "Keep the current layout, shortcuts and interface preferences for future sessions. Like ZBrush, SculptForge never "+ "saves them on its own.");+ add("config.restore_standard", "Restore Standard UI", "Preferences > Config", nullptr, [this] { restoreStandardUi(); },+ ICON_LC_ROTATE_CCW, nullptr, nullptr, nullptr,+ "Go back to the built-in layout and default shortcuts. Store Config afterwards to make it stick.");+ add("config.restore_custom", "Restore Custom UI", "Preferences > Config", nullptr, [this] { restoreCustomUi(); },+ ICON_LC_ARCHIVE_RESTORE, nullptr, nullptr, [this] { return fileExists(uiConfigPath()); },+ "Go back to the layout and shortcuts saved by the last Store Config.");+ add("config.load", "Load UI...", "Preferences > Config", "Ctrl+L", [this] { loadUiDialog(); }, ICON_LC_FOLDER_INPUT, nullptr,+ nullptr, nullptr, "Load a layout file someone shared (or you saved with Save UI).");+ add("config.save", "Save UI...", "Preferences > Config", nullptr, [this] { saveUiDialog(); }, ICON_LC_FOLDER_OUTPUT, nullptr,+ nullptr, nullptr, "Save the layout, shortcuts and interface preferences to a file you can share.");+ add("config.customize", "Enable Customize", "Preferences > Config", nullptr,+ [this] {+ layout_.customize = !layout_.customize;+ status_ = layout_.customize ? "Customize: Ctrl+Alt+drag to move or remove items" : "Customize off";+ },+ ICON_LC_LAYOUT_TEMPLATE, nullptr, [this] { return layout_.customize; }, nullptr,+ "Rearrange the shelves: Ctrl+Alt+drag any button onto a shelf to add or move it, or off the shelves to remove it.");++ // Every command, so the command palette finds anything scriptable.+ actions_.registerCommands(+ commands_, [this](const std::string& name) { runCommand(name); },+ [this](const std::string& name) { consolePrefill(name + " "); });++ if (!uiConfigDeterministic_ && !configDir_.empty()) {+ console_.loadHistory(configDir_ + "console_history.txt");+ std::ifstream f(fsPath(configDir_ + "recent_actions.txt"));+ std::vector<std::string> recent;+ for (std::string line; std::getline(f, line);)+ if (!line.empty()) recent.push_back(line);+ actions_.setRecent(std::move(recent));+ }+ layoutBaseline_ = layoutKey();+}++void App::saveRecentActions() {+ if (uiConfigDeterministic_ || configDir_.empty()) return;+ std::ofstream f(fsPath(configDir_ + "recent_actions.txt"), std::ios::binary | std::ios::trunc);+ for (const auto& id : actions_.recent()) f << id << "\n";+}++// ---------------------------------------------------------------------------+// Store / restore+// ---------------------------------------------------------------------------++std::string App::uiConfigPath() const { return configDir_.empty() ? std::string() : configDir_ + "ui.json"; }++bool App::writeUiConfig(const std::string& path, std::string& err) {+ Json j = Json::object();+ j.set("version", 1.0);+ j.set("layout", toJson(layout_));+ j.set("shortcuts", actions_.overridesToJson());+ j.set("prefs", toJson(uiPrefs_));+ std::ofstream f(fsPath(path), std::ios::binary | std::ios::trunc);+ f << j.dump(true) << "\n";+ if (!f) {+ err = "Could not write " + path;+ return false;+ }+ return true;+}++bool App::readUiConfig(const std::string& path, std::string& err) {+ std::ifstream f(fsPath(path), std::ios::binary);+ if (!f) {+ err = "Could not read " + path;+ return false;+ }+ Json j;+ if (!Json::parse(std::string(std::istreambuf_iterator<char>(f), {}), j, err)) {+ err = path + ": " + err;+ return false;+ }+ if (!j.isObject() || !j["layout"].isObject()) {+ err = path + " is not a SculptForge UI configuration";+ return false;+ }+ UiLayout layout;+ if (!fromJson(j["layout"], layout, err)) return false;+ const bool customize = layout_.customize;+ layout_ = std::move(layout);+ layout_.customize = customize;+ actions_.overridesFromJson(j["shortcuts"]);+ fromJson(j["prefs"], uiPrefs_);+ return true;+}++void App::storeConfig() {+ std::string err;+ if (uiConfigPath().empty()) {+ status_ = "Can't store the UI configuration: no settings folder";+ } else if (!writeUiConfig(uiConfigPath(), err)) {+ status_ = err;+ } else {+ status_ = "UI configuration stored";+ layoutBaseline_ = layoutKey();+ }+}++void App::restoreStandardUi() {+ const bool customize = layout_.customize;+ layout_ = standardLayout();+ layout_.customize = customize;+ actions_.clearOverrides();+ layoutBaseline_ = layoutKey();+ status_ = "Standard UI restored - Store Config (Ctrl+Shift+I) to keep it";+}++void App::restoreCustomUi() {+ std::string err;+ if (!fileExists(uiConfigPath())) {+ status_ = "No stored UI configuration yet - Store Config (Ctrl+Shift+I) first";+ } else if (!readUiConfig(uiConfigPath(), err)) {+ status_ = err;+ } else {+ layoutBaseline_ = layoutKey();+ status_ = "Custom UI restored";+ }+}++void App::saveUiDialog() {+ SDL_ShowSaveFileDialog(onUiFileChosen, &g_requests[kSaveUi], window_, kUiFilters, 1, nullptr);+}++void App::loadUiDialog() {+ SDL_ShowOpenFileDialog(onUiFileChosen, &g_requests[kLoadUi], window_, kUiFilters, 1, nullptr, false);+}++void App::queueUiFile(int kind, std::string path) {+ std::lock_guard<std::mutex> lock(uiFileMutex_);+ uiFiles_.emplace_back(kind, std::move(path));+}++std::string App::layoutKey() const {+ UiLayout l = layout_; // what a session changes on its own doesn't count as a layout edit+ l.consoleOpen = false;+ l.consoleHeight = 0;+ l.lightboxOpen = false;+ l.lightboxTab.clear();+ l.customize = false;+ return toJson(l).dump();+}++void App::watchLayoutChanges() {+ if (layoutHintShown_ || uiConfigDeterministic_ || ++layoutCheckFrame_ % 20 != 0) return;+ if (layoutKey() == layoutBaseline_) return;+ layoutHintShown_ = true; // once per session (ZBrush never saves the layout by itself)+ status_ = "Layout changed - Ctrl+Shift+I to keep it";+}++// ---------------------------------------------------------------------------+// Console and command palette glue+// ---------------------------------------------------------------------------++void App::setConsoleOpen(bool open) {+ layout_.consoleOpen = open;+ if (open) console_.focusInput();+}++void App::consolePrefill(const std::string& text) {+ layout_.consoleOpen = true;+ console_.prefill(text);+}++void App::consoleEcho(const std::string& name, const Args& args, const CommandResult& r) {+ console_.echo(formatStatement(name, args), r, commandSource_);+ console_.seenStatus(status_);+}++CanvasRect App::paletteArea() const {+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ return {vp->WorkPos.x, vp->WorkPos.y, vp->WorkSize.x, vp->WorkSize.y};+}++CanvasRect App::consoleRect() const {+ // The shell reserves this strip above the bottom shelf; on its own, the console spans the window bottom.+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ const float h = std::min(std::clamp(layout_.consoleHeight, 100.0f, 400.0f) * uiScale_, vp->WorkSize.y * 0.6f);+ return {vp->WorkPos.x, vp->WorkPos.y + vp->WorkSize.y - h, vp->WorkSize.x, h};+}++// ---------------------------------------------------------------------------+// Shortcut assignment (Ctrl+Alt+click a button, or Preferences > Hotkeys)+// ---------------------------------------------------------------------------++void App::beginShortcutCapture(const std::string& actionId) {+ const Action* a = actions_.find(actionId);+ if (!a) return;+ capturingShortcut_ = actionId;+ status_ = "Press a key for '" + a->label + "' (Esc cancels, Backspace clears)";+}++bool App::captureShortcutKey(SDL_Keycode key, SDL_Keymod mod) {+ if (capturingShortcut_.empty()) return false;+ if (isModifierKey(key)) return true;+ const Action* a = actions_.find(capturingShortcut_);+ const std::string label = a ? a->label : capturingShortcut_;+ if (key == SDLK_ESCAPE) {+ status_ = "Shortcut unchanged";+ } else if (key == SDLK_BACKSPACE || key == SDLK_DELETE) {+ actions_.setShortcut(capturingShortcut_, "");+ status_ = label + ": no shortcut - Store Config (Ctrl+Shift+I) to keep it";+ } else {+ const std::string chord = chordText(chordFromEvent(key, mod));+ const std::string lost = actions_.assignShortcut(capturingShortcut_, chord);+ status_ = label + ": " + chord + (lost.empty() ? "" : " (was " + lost + ")") + " - Store Config (Ctrl+Shift+I) to keep it";+ }+ capturingShortcut_.clear();+ return true;+}++// ---------------------------------------------------------------------------+// Per-frame UI+// ---------------------------------------------------------------------------++void App::drawHelpConsoleUi() {+ {+ std::vector<std::pair<int, std::string>> files;+ {+ std::lock_guard<std::mutex> lock(uiFileMutex_);+ files.swap(uiFiles_);+ }+ for (auto& [kind, path] : files) {+ std::string err;+ if (kind == kSaveUi) {+ if (fsPath(path).extension().empty()) path += ".json";+ status_ = writeUiConfig(path, err) ? "UI layout saved to " + path : err;+ } else if (kind == kLoadUi) {+ if (readUiConfig(path, err)) {+ status_ = "UI layout loaded - Store Config (Ctrl+Shift+I) to keep it";+ } else {+ status_ = err;+ }+ } else if (kind == kRunScript) {+ setConsoleOpen(true);+ console_.queueScriptFile(path);+ } else if (kind == kLibraryFolder) {+ uiPrefs_.libraryFolder = path;+ }+ }+ }+ console_.watchStatus(status_);+ if (layout_.consoleOpen) console_.draw(*this, consoleRect());+ palette_.draw(*this, paletteArea());+ if (showHelp_) drawControlsWindow();+ if (!capturingShortcut_.empty()) {+ const Action* a = actions_.find(capturingShortcut_);+ const CanvasRect area = paletteArea();+ const float s = uiScale_;+ ImGui::SetNextWindowPos(ImVec2(area.x + area.w * 0.5f, area.y + 60.0f * s), ImGuiCond_Always, ImVec2(0.5f, 0.0f));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(16.0f * s, 12.0f * s));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 6.0f * s);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleColor(ImGuiCol_WindowBg, col(IM_COL32(0x18, 0x18, 0x1a, 0xf8)));+ ImGui::PushStyleColor(ImGuiCol_Border, col(IM_COL32(0xf0, 0x88, 0x2e, 0xa0)));+ if (ImGui::Begin("##shortcut_capture", nullptr,+ ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings |+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoInputs)) {+ ImGui::PushFont(helpTitleFont());+ ImGui::Text(ICON_LC_KEYBOARD " Press a key for '%s'", a ? a->label.c_str() : capturingShortcut_.c_str());+ ImGui::PopFont();+ const std::string now = actions_.shortcutText(capturingShortcut_);+ ImGui::TextColored(col(ui::color::textDim), "Now:");+ ImGui::SameLine();+ if (now.empty()) ImGui::TextColored(col(ui::color::textDim), "none");+ else ui::Keycaps(now);+ ImGui::TextColored(col(ui::color::textDim), "Esc cancels, Backspace clears. A key that's taken moves here.");+ }+ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(3);+ }+ watchLayoutChanges();+ ui::DrawHelp(*this); // last: on top of everything+}++void App::drawControlsWindow() {+ const float s = uiScale_;+ ImGui::SetNextWindowSize(ImVec2(560.0f * s, 640.0f * s), ImGuiCond_FirstUseEver);+ ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));+ if (!ImGui::Begin("Controls", &showHelp_, ImGuiWindowFlags_NoCollapse)) {+ ImGui::End();+ return;+ }+ static char filter[96] = "";+ ImGui::SetNextItemWidth(-FLT_MIN);+ ImGui::InputTextWithHint("##controls_filter", ICON_LC_SEARCH " Filter shortcuts and gestures", filter, sizeof filter);+ const std::string f = lower(filter);+ auto matches = [&](const std::string& a, const std::string& b, const std::string& c) {+ return f.empty() || lower(a).find(f) != std::string::npos || lower(b).find(f) != std::string::npos ||+ lower(c).find(f) != std::string::npos;+ };+ ImGui::Spacing();+ if (ImGui::BeginTabBar("##controls_tabs")) {+ if (ImGui::BeginTabItem("Keyboard")) {+ ImGui::BeginChild("##controls_keys", ImVec2(0, -ImGui::GetTextLineHeightWithSpacing() * 1.6f));+ // Grouped by palette, alphabetically (as ZBrush lists its palettes).+ std::map<std::string, std::vector<const Action*>> groups;+ for (const auto& a : actions_.all()) {+ const std::string chord = actions_.shortcutText(a.id);+ if (chord.empty() || !matches(a.label, a.palette, chord)) continue;+ const std::string top = a.palette.substr(0, a.palette.find(" > "));+ groups[top.empty() ? "General" : top].push_back(&a);+ }+ if (groups.empty()) ImGui::TextColored(col(ui::color::textDim), "No shortcut matches \"%s\".", filter);+ for (auto& [group, list] : groups) {+ std::stable_sort(list.begin(), list.end(), [](const Action* x, const Action* y) { return x->label < y->label; });+ ImGui::SeparatorText(group.c_str());+ if (!ImGui::BeginTable(("##keys_" + group).c_str(), 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_PadOuterX)) continue;+ ImGui::TableSetupColumn("action", ImGuiTableColumnFlags_WidthStretch);+ ImGui::TableSetupColumn("keys", ImGuiTableColumnFlags_WidthFixed, 190.0f * s);+ for (const Action* a : list) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ const ImVec2 p = ImGui::GetCursorScreenPos();+ const float iconW = ImGui::GetFontSize() + 8.0f * s;+ if (a->icon) ImGui::GetWindowDrawList()->AddText(p, ui::color::textDim, a->icon);+ ImGui::SetCursorScreenPos(ImVec2(p.x + iconW, p.y));+ ImGui::Selectable((a->label + "##ctl." + a->id).c_str(), capturingShortcut_ == a->id,+ ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowDoubleClick);+ if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) beginShortcutCapture(a->id);+ ui::HelpAction(*this, a->id.c_str());+ ImGui::TableNextColumn();+ ui::Keycaps(actions_.shortcutText(a->id));+ }+ ImGui::EndTable();+ ImGui::Spacing();+ }+ ImGui::EndChild();+ ImGui::TextColored(col(ui::color::textDim), "Double-click a row, or Ctrl+Alt+click any button, to assign a key.");+ ImGui::EndTabItem();+ }+ if (ImGui::BeginTabItem("Mouse & pen")) {+ if (ImGui::BeginTable("##gestures", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_PadOuterX)) {+ ImGui::TableSetupColumn("what", ImGuiTableColumnFlags_WidthFixed, 180.0f * s);+ ImGui::TableSetupColumn("how", ImGuiTableColumnFlags_WidthStretch);+ for (const auto& g : kGestures) {+ if (!matches(g.what, g.how, "")) continue;+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::TextUnformatted(g.what);+ ImGui::TableNextColumn();+ ImGui::PushTextWrapPos(0.0f);+ ImGui::TextColored(col(IM_COL32(0xc8, 0xc8, 0xc8, 0xff)), "%s", g.how);+ ImGui::PopTextWrapPos();+ }+ ImGui::EndTable();+ }+ ImGui::EndTabItem();+ }+ ImGui::EndTabBar();+ }+ ImGui::End();+}++// ---------------------------------------------------------------------------+// Preferences sections (drawn inside the shell's Preferences palette)+// ---------------------------------------------------------------------------++namespace config {++void drawConfigSection(App& app) {+ const ImVec2 full(-FLT_MIN, 0);+ bool customize = app.layout().customize;+ if (ImGui::Checkbox("Enable Customize", &customize)) app.actions().find("config.customize")->run();+ ui::HelpAction(app, "config.customize");+ ui::ActionButton(app, "config.store", full, ui::Look::IconLabel);+ ui::ActionButton(app, "config.restore_custom", full, ui::Look::IconLabel);+ ui::ActionButton(app, "config.restore_standard", full, ui::Look::IconLabel);+ const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;+ ui::ActionButton(app, "config.save", ImVec2(half, 0), ui::Look::IconLabel);+ ImGui::SameLine();+ ui::ActionButton(app, "config.load", ImVec2(half, 0), ui::Look::IconLabel);+ ImGui::PushStyleColor(ImGuiCol_Text, col(ui::color::textDim));+ ImGui::PushTextWrapPos(0.0f);+ ImGui::TextUnformatted("Changes to the layout and shortcuts last until you quit. Store Config keeps them.");+ ImGui::PopTextWrapPos();+ ImGui::PopStyleColor();+}++void drawInterfaceSection(App& app) {+ UiPrefs& p = app.uiPrefs();+ ImGui::Checkbox("Popup Info (Ctrl+hover help)", &p.popupInfo);+ ui::HelpText("Popup Info", nullptr,+ "Hold Ctrl and point at any control to see what it does and its shortcut. Ctrl+Alt shows a command's "+ "scripting parameters.",+ "Preferences > Interface");+ ImGui::BeginDisabled(!p.popupInfo);+ ImGui::SetNextItemWidth(-FLT_MIN);+ ui::SliderInside("##help_opacity", &p.helpOpacity, 0.3f, 1.0f, "Popup Info opacity %.2f");+ ui::HelpText("Popup Info opacity", nullptr, "How solid the Ctrl-help box is (ZBrush: Quick Info Opacity).",+ "Preferences > Interface");+ ImGui::EndDisabled();+ ImGui::SetNextItemWidth(-FLT_MIN);+ ui::SliderInside("##tooltip_delay", &p.tooltipDelay, 0.0f, 2.0f, "Tooltip delay %.1f s");+ ui::HelpText("Tooltip delay", nullptr,+ "How long to point at an icon-only button (or a clipped label) before its name appears.",+ "Preferences > Interface");+ ImGui::Checkbox("One sub-palette open", &p.oneSubpalette);+ ui::HelpText("One sub-palette open", nullptr,+ "Opening a sub-palette closes the others in that palette. Shift+click opens more than one.",+ "Preferences > Interface");+ ImGui::Checkbox("Auto collapse left tray", &p.autoCollapseLeft);+ ui::HelpText("Auto collapse left tray", nullptr,+ "Opening a palette in the left tray collapses the others when they would not fit.", "Preferences > Interface");+ ImGui::Checkbox("Auto collapse right tray", &p.autoCollapseRight);+ ui::HelpText("Auto collapse right tray", nullptr,+ "Opening a palette in the right tray collapses the others when they would not fit.", "Preferences > Interface");+ ImGui::Checkbox("Left-handed layout", &app.layout().leftHanded);+ ui::HelpText("Left-handed layout", nullptr, "Mirror the shelves and trays: tools on the left, navigation on the right.",+ "Preferences > Interface");+ static const char* kScales[] = {"Automatic", "100%", "125%", "150%", "175%", "200%"};+ static const float kScaleValues[] = {0.0f, 1.0f, 1.25f, 1.5f, 1.75f, 2.0f};+ int current = 0;+ for (int i = 0; i < 6; ++i)+ if (std::abs(kScaleValues[i] - p.uiScale) < 0.01f) current = i;+ ImGui::SetNextItemWidth(-FLT_MIN);+ if (ImGui::BeginCombo("##ui_scale", (std::string("UI scale: ") + kScales[current]).c_str())) {+ for (int i = 0; i < 6; ++i)+ if (ImGui::Selectable(kScales[i], i == current)) p.uiScale = kScaleValues[i];+ ImGui::EndCombo();+ }+ ui::HelpText("UI scale", nullptr,+ "Size of text and controls. Automatic follows the display. Takes effect the next time SculptForge starts "+ "(Store Config to keep it).",+ "Preferences > Interface");+}++void drawHotkeysSection(App& app) {+ static char filter[64] = "";+ ImGui::SetNextItemWidth(-FLT_MIN);+ ImGui::InputTextWithHint("##hotkeys_filter", ICON_LC_SEARCH " Filter", filter, sizeof filter);+ const std::string f = lower(filter);+ ActionRegistry& reg = app.actions();+ const float s = ImGui::GetFontSize() / 15.0f;+ std::vector<const Action*> list;+ for (const auto& a : reg.all()) {+ if (!a.run || a.id.rfind("cmd.", 0) == 0) continue; // commands: through the command palette+ if (!f.empty() && lower(a.label).find(f) == std::string::npos && lower(a.palette).find(f) == std::string::npos) continue;+ list.push_back(&a);+ }+ std::stable_sort(list.begin(), list.end(), [](const Action* x, const Action* y) {+ return x->palette != y->palette ? x->palette < y->palette : x->label < y->label;+ });+ const float listH = std::min(320.0f * s, float(list.size()) * ImGui::GetFrameHeightWithSpacing() + 8.0f * s);+ if (ImGui::BeginTable("##hotkeys", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_PadOuterX,+ ImVec2(0, std::max(listH, 60.0f * s)))) {+ ImGui::TableSetupColumn("action", ImGuiTableColumnFlags_WidthStretch);+ ImGui::TableSetupColumn("key", ImGuiTableColumnFlags_WidthFixed, 110.0f * s);+ for (const Action* a : list) {+ ImGui::TableNextRow();+ ImGui::TableNextColumn();+ ImGui::AlignTextToFramePadding();+ ImGui::TextUnformatted(a->label.c_str());+ ui::HelpAction(app, a->id.c_str());+ ImGui::TableNextColumn();+ const std::string chord = reg.shortcutText(a->id);+ const bool capturing = app.capturingShortcut() == a->id;+ const std::string text = capturing ? "press a key..." : chord.empty() ? "-" : chord;+ if (reg.hasOverride(a->id)) ImGui::PushStyleColor(ImGuiCol_Text, col(ui::color::accent));+ if (ImGui::Button((text + "##hk." + a->id).c_str(), ImVec2(-FLT_MIN, 0))) app.beginShortcutCapture(a->id);+ if (reg.hasOverride(a->id)) ImGui::PopStyleColor();+ ui::HelpText(("Shortcut for " + a->label).c_str(), chord.c_str(),+ "Click, then press the new key. Esc cancels, Backspace clears. Orange: changed from the default.",+ "Preferences > Hotkeys");+ }+ ImGui::EndTable();+ }+ if (ImGui::Button(ICON_LC_ROTATE_CCW " Default shortcuts", ImVec2(-FLT_MIN, 0))) {+ reg.clearOverrides();+ app.status_ = "Default shortcuts restored - Store Config (Ctrl+Shift+I) to keep them";+ }+ ui::HelpText("Default shortcuts", nullptr, "Undo every shortcut change.", "Preferences > Hotkeys");+}++void drawLightBoxSection(App& app) {+ UiPrefs& p = app.uiPrefs();+ UiLayout& l = app.layout();+ ImGui::Checkbox("Show at startup", &p.lightboxAtStartup);+ ui::HelpText("Show LightBox at startup", nullptr, "Open LightBox on the Project tab when SculptForge starts (as ZBrush does).",+ "Preferences > LightBox");+ ImGui::AlignTextToFramePadding();+ ImGui::TextUnformatted("Rows");+ for (int r = 1; r <= 4; ++r) {+ ImGui::SameLine();+ const bool on = l.lightboxRows == r;+ if (on) ImGui::PushStyleColor(ImGuiCol_Button, col(ui::color::accent));+ if (ImGui::Button((std::to_string(r) + "##lbrows").c_str(), ImVec2(ImGui::GetFrameHeight() * 1.3f, 0))) l.lightboxRows = r;+ if (on) ImGui::PopStyleColor();+ ui::HelpText("LightBox rows", nullptr, "How many rows of thumbnails the LightBox strip shows.", "Preferences > LightBox");+ }+ ImGui::AlignTextToFramePadding();+ ImGui::TextUnformatted("Placement");+ ImGui::SameLine();+ if (ImGui::RadioButton("Top", !l.lightboxBottom)) l.lightboxBottom = false;+ ui::HelpText("LightBox at the top", nullptr, "LightBox opens along the top edge of the canvas.", "Preferences > LightBox");+ ImGui::SameLine();+ if (ImGui::RadioButton("Bottom", l.lightboxBottom)) l.lightboxBottom = true;+ ui::HelpText("LightBox at the bottom", nullptr, "LightBox opens above the bottom shelf.", "Preferences > LightBox");+ ImGui::TextColored(col(ui::color::textDim), "Library folder");+ const std::string shown = p.libraryFolder.empty() ? std::string("Documents/SculptForge (default)") : p.libraryFolder;+ if (ImGui::Button((std::string(ICON_LC_FOLDER_OPEN " ") + shown + "##libfolder").c_str(), ImVec2(-FLT_MIN, 0)))+ SDL_ShowOpenFolderDialog(onUiFileChosen, &g_requests[kLibraryFolder], app.window_, nullptr, false);+ ui::HelpText("Library folder", nullptr,+ "Where your projects, tools, brushes, alphas, images, splats and QuickSaves live. LightBox shows it as User.",+ "Preferences > LightBox");+ if (!p.libraryFolder.empty() && ImGui::SmallButton("Use the default folder")) p.libraryFolder.clear();+}++} // namespace config++} // namespace sfdiff --git a/src/app/Config.h b/src/app/Config.hnew file mode 100644index 00000000..26924acd--- /dev/null+++ b/src/app/Config.h@@ -0,0 +1,41 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// UI preferences and the ZBrush-style configuration workflow: Store Config+// (Ctrl+Shift+I) writes <prefs>/ui.json with the layout, shortcut overrides and+// these preferences; nothing is saved automatically. Restore Standard UI goes+// back to the built-in layout, Restore Custom UI to the stored one, and Save UI /+// Load UI (Ctrl+L) share a layout as a file.+#pragma once++#include "core/Json.h"++#include <string>++namespace sf {++class App;++struct UiPrefs {+ bool popupInfo = true; // Ctrl+hover shows an item's description (ZBrush "Popup Info")+ float helpOpacity = 0.97f; // Ctrl-help box opacity (ZBrush "Quick Info Opacity")+ float tooltipDelay = 0.5f; // plain hover tooltips on icon-only buttons and clipped labels+ bool oneSubpalette = true; // opening a sub-palette closes the others (Shift+click opens more)+ bool autoCollapseLeft = true, autoCollapseRight = false; // trays collapse palettes that would overflow+ float uiScale = 0.0f; // 0 = follow the display; otherwise applied at the next start+ bool lightboxAtStartup = true;+ std::string libraryFolder; // "" = Documents/SculptForge+};++Json toJson(const UiPrefs& prefs);+void fromJson(const Json& j, UiPrefs& prefs);++namespace config {+// Preferences palette sub-palettes (the shell's Preferences palette calls these).+void drawConfigSection(App& app); // Enable Customize, Store / Restore / Save / Load UI+void drawInterfaceSection(App& app); // UI scale, Popup Info, tooltips, sub-palettes, left-handed layout+void drawHotkeysSection(App& app); // every action's shortcut, click to reassign+void drawLightBoxSection(App& app); // show at startup, rows, placement, library folder+} // namespace config++} // namespace sfdiff --git a/src/app/Console.cpp b/src/app/Console.cppnew file mode 100644index 00000000..8dc92b31--- /dev/null+++ b/src/app/Console.cpp@@ -0,0 +1,498 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "app/Console.h"++#include "app/App.h"+#include "app/Ui.h"+#include "core/Script.h"++#include <IconsLucide.h>+#include <imgui_internal.h>++#include <algorithm>+#include <cctype>+#include <cfloat>+#include <cstring>+#include <filesystem>+#include <fstream>++namespace sf {++namespace {++constexpr size_t kMaxLines = 4000;+constexpr size_t kMaxHistory = 200;++std::filesystem::path fsPath(const std::string& utf8) { return std::filesystem::path(std::u8string(utf8.begin(), utf8.end())); }++std::string trim(const std::string& s) {+ size_t a = 0, b = s.size();+ while (a < b && std::isspace(static_cast<unsigned char>(s[a]))) ++a;+ while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;+ return s.substr(a, b - a);+}++std::string firstWord(const std::string& s) {+ const std::string t = trim(s);+ const size_t sp = t.find_first_of(" \t");+ return sp == std::string::npos ? t : t.substr(0, sp);+}++std::string commonPrefix(const std::vector<std::string>& v) {+ if (v.empty()) return {};+ std::string p = v[0];+ for (const auto& s : v) {+ size_t n = 0;+ while (n < p.size() && n < s.size() && p[n] == s[n]) ++n;+ p.resize(n);+ }+ return p;+}++const char* typeName(ParamSpec::Type t) {+ switch (t) {+ case ParamSpec::Type::Bool: return "true/false";+ case ParamSpec::Type::Number: return "number";+ case ParamSpec::Type::String: return "text";+ }+ return "";+}++// Names laid out in columns, like a shell listing.+std::vector<std::string> columns(std::vector<std::string> names, size_t width = 96) {+ std::sort(names.begin(), names.end());+ size_t col = 0;+ for (const auto& n : names) col = std::max(col, n.size() + 2);+ const size_t perLine = std::max<size_t>(1, width / std::max<size_t>(col, 1));+ std::vector<std::string> lines;+ std::string line;+ for (size_t i = 0; i < names.size(); ++i) {+ std::string cell = names[i];+ if ((i + 1) % perLine != 0 && i + 1 < names.size()) cell.resize(col, ' ');+ line += cell;+ if ((i + 1) % perLine == 0) {+ lines.push_back(" " + line);+ line.clear();+ }+ }+ if (!line.empty()) lines.push_back(" " + line);+ return lines;+}++} // namespace++void Console::print(Kind kind, const std::string& text) {+ // Multi-line messages become several lines (the log draws one line per entry).+ size_t start = 0;+ while (start <= text.size()) {+ const size_t nl = text.find('\n', start);+ lines_.push_back({kind, text.substr(start, nl == std::string::npos ? std::string::npos : nl - start), {}});+ if (nl == std::string::npos) break;+ start = nl + 1;+ }+ if (lines_.size() > kMaxLines) lines_.erase(lines_.begin(), lines_.begin() + std::ptrdiff_t(lines_.size() - kMaxLines));+ scrollToBottom_ = true;+}++void Console::echo(const std::string& statement, const CommandResult& result, const std::string& source) {+ const double now = ImGui::GetCurrentContext() ? ImGui::GetTime() : 0.0;+ // A slider runs its command every frame while dragged: keep one line for it, with the latest values.+ if (result.ok && firstWord(statement) == firstWord(lastEcho_) && now - lastEchoTime_ < 0.5 &&+ lastEchoLine_ + 2 == lines_.size() && lines_[lastEchoLine_].kind == Kind::Command) {+ lines_[lastEchoLine_].text = statement;+ lines_[lastEchoLine_ + 1].text = result.message;+ if (!session_.empty()) session_.back() = statement;+ lastEcho_ = statement;+ lastEchoTime_ = now;+ return;+ }+ if (result.ok) {+ lines_.push_back({Kind::Command, statement, source});+ lastEchoLine_ = lines_.size() - 1;+ lines_.push_back({Kind::Result, result.message, {}});+ session_.push_back(statement);+ } else {+ lines_.push_back({Kind::Error, statement + " -> " + result.message, source});+ lastEchoLine_ = 0;+ }+ lastEcho_ = statement;+ lastEchoTime_ = now;+ if (lines_.size() > kMaxLines) {+ const size_t drop = lines_.size() - kMaxLines;+ lines_.erase(lines_.begin(), lines_.begin() + std::ptrdiff_t(drop));+ lastEchoLine_ = lastEchoLine_ >= drop ? lastEchoLine_ - drop : 0;+ }+ scrollToBottom_ = true;+}++void Console::watchStatus(const std::string& status) {+ if (status == lastStatus_) return;+ lastStatus_ = status;+ if (!status.empty()) print(Kind::Status, status);+}++void Console::clear() {+ lines_.clear();+ lastEchoLine_ = 0;+ lastEcho_.clear();+}++std::string Console::sessionScript() const {+ std::string out;+ for (const auto& s : session_) out += s + "\n";+ return out;+}++void Console::focusInput() {+ focusInput_ = bringToFront_ = true;+ focusFrame_ = ImGui::GetCurrentContext() ? ImGui::GetFrameCount() : -100;+}++void Console::prefill(const std::string& text) {+ pendingText_ = text;+ hasPendingText_ = true;+ focusInput();+}++void Console::loadHistory(const std::string& path) {+ historyPath_ = path;+ history_.clear();+ std::ifstream f(fsPath(path));+ std::string line;+ while (std::getline(f, line)) {+ if (!line.empty() && line.back() == '\r') line.pop_back();+ if (!line.empty()) history_.push_back(line);+ }+ if (history_.size() > kMaxHistory) history_.erase(history_.begin(), history_.end() - kMaxHistory);+}++void Console::addHistory(const std::string& line) {+ historyPos_ = -1;+ if (line.empty()) return;+ history_.erase(std::remove(history_.begin(), history_.end(), line), history_.end());+ history_.push_back(line);+ if (history_.size() > kMaxHistory) history_.erase(history_.begin(), history_.end() - kMaxHistory);+ if (historyPath_.empty()) return;+ std::ofstream f(fsPath(historyPath_), std::ios::binary | std::ios::trunc);+ for (const auto& h : history_) f << h << "\n";+}++void Console::printHelp(App& app, const std::string& topic) {+ const std::string t = trim(topic);+ if (t.empty()) {+ print(Kind::Info, "Type a command and press Enter, e.g. remesh resolution=200 or subdivide; decimate ratio=0.5");+ print(Kind::Info, "Tab completes names and parameters, Up/Down walks the history, help <command> explains one.");+ std::vector<std::string> names;+ for (const auto& c : app.commands_.all()) names.push_back(c.name);+ for (const auto& l : columns(names)) print(Kind::Info, l);+ return;+ }+ const Command* c = app.commands_.find(t);+ if (!c) {+ print(Kind::Error, "help " + t + " -> No command named '" + t + "' (type help for the list)");+ return;+ }+ print(Kind::Info, c->name + " - " + c->description);+ if (c->params.empty()) print(Kind::Info, " (no parameters)");+ for (const auto& p : c->params)+ print(Kind::Info, " " + p.name + "=<" + typeName(p.type) + ">" + (p.required ? " (required)" : "") + " " + p.description);+}++void Console::runLine(App& app, const std::string& raw) {+ const std::string line = trim(raw);+ addHistory(line);+ if (line.empty()) return;+ const std::string word = firstWord(line);+ if (word == "help" || word == "?") {+ print(Kind::Command, line);+ printHelp(app, line.substr(word.size()));+ return;+ }+ if (line == "clear") {+ clear();+ return;+ }+ std::vector<ScriptStatement> statements;+ std::string err;+ if (!parseScript(line, statements, err)) {+ print(Kind::Error, line + " -> " + err);+ return;+ }+ for (const auto& st : statements) {+ if (!app.commands_.find(st.command)) {+ print(Kind::Error, formatStatement(st.command, st.args) + " -> Unknown command '" + st.command ++ "' (Tab completes, help lists them)");+ return;+ }+ app.runCommand(st.command, st.args); // echoes itself+ if (!app.lastCommandOk_) return; // later statements usually depend on this one+ }+}++void Console::runFile(App& app, const std::string& path) {+ std::ifstream f(fsPath(path), std::ios::binary);+ if (!f) {+ print(Kind::Error, "Run script -> Cannot read " + path);+ return;+ }+ const std::string text((std::istreambuf_iterator<char>(f)), {});+ std::vector<ScriptStatement> statements;+ std::string err;+ if (!parseScript(text, statements, err)) {+ print(Kind::Error, "Run script " + path + " -> " + err);+ return;+ }+ print(Kind::Info, "Running " + fsPath(path).filename().string() + " (" + std::to_string(statements.size()) + " statements)");+ for (const auto& st : statements) {+ if (!app.commands_.find(st.command)) {+ print(Kind::Error, "Line " + std::to_string(st.line) + ": unknown command '" + st.command + "' - stopped");+ return;+ }+ app.runCommand(st.command, st.args);+ if (!app.lastCommandOk_) {+ print(Kind::Error, "Line " + std::to_string(st.line) + " failed - stopped");+ return;+ }+ }+}++void Console::queueScriptFile(std::string path) {+ std::lock_guard<std::mutex> lock(pendingMutex_);+ pendingFiles_.push_back(std::move(path));+}++void Console::complete(App& app, ImGuiInputTextCallbackData* data) {+ const std::string text(data->Buf, size_t(data->CursorPos));+ const size_t stmtStart = text.find_last_of(';') == std::string::npos ? 0 : text.find_last_of(';') + 1;+ const std::string stmt = text.substr(stmtStart);+ const size_t tokStart = stmt.find_last_of(" \t") == std::string::npos ? 0 : stmt.find_last_of(" \t") + 1;+ const std::string prefix = stmt.substr(tokStart);+ const bool commandName = trim(stmt.substr(0, tokStart)).empty();+ std::vector<std::string> candidates;+ std::string suffix;+ if (commandName) {+ for (const auto& c : app.commands_.all())+ if (c.name.rfind(prefix, 0) == 0) candidates.push_back(c.name);+ if (std::string("help").rfind(prefix, 0) == 0) candidates.push_back("help");+ suffix = " ";+ } else {+ if (prefix.find('=') != std::string::npos) return; // a value: nothing to complete+ const Command* c = app.commands_.find(firstWord(stmt));+ if (!c) return;+ for (const auto& p : c->params)+ if (p.name.rfind(prefix, 0) == 0 && stmt.find(" " + p.name + "=") == std::string::npos) candidates.push_back(p.name);+ suffix = "=";+ }+ if (candidates.empty()) return;+ std::sort(candidates.begin(), candidates.end());+ const std::string common = candidates.size() == 1 ? candidates[0] + suffix : commonPrefix(candidates);+ if (common.size() > prefix.size()) {+ const int at = data->CursorPos - int(prefix.size());+ data->DeleteChars(at, int(prefix.size()));+ data->InsertChars(at, common.c_str());+ lastTab_.clear();+ return;+ }+ // Nothing more to add: a second Tab lists what could follow.+ const std::string now(data->Buf, size_t(data->BufTextLen));+ if (lastTab_ == now) {+ print(Kind::Info, commandName ? "Commands:" : "Parameters of " + firstWord(stmt) + ":");+ for (const auto& l : columns(candidates)) print(Kind::Info, l);+ lastTab_.clear();+ } else {+ lastTab_ = now;+ }+}++int Console::inputCallback(ImGuiInputTextCallbackData* data) {+ auto* self = static_cast<Console*>(data->UserData);+ switch (data->EventFlag) {+ case ImGuiInputTextFlags_CallbackCharFilter:+ if (data->EventChar == '`') { // the console key closes the console, even while typing+ if (ImGui::GetFrameCount() - self->focusFrame_ > 2) self->closeRequested_ = true;+ return 1;+ }+ return 0;+ case ImGuiInputTextFlags_CallbackCompletion:+ if (self->app_) self->complete(*self->app_, data);+ return 0;+ case ImGuiInputTextFlags_CallbackHistory: {+ const auto& h = self->history_;+ if (h.empty()) return 0;+ int& pos = self->historyPos_;+ if (data->EventKey == ImGuiKey_UpArrow) pos = pos < 0 ? int(h.size()) - 1 : std::max(0, pos - 1);+ else if (data->EventKey == ImGuiKey_DownArrow && pos >= 0) pos = pos + 1 >= int(h.size()) ? -1 : pos + 1;+ data->DeleteChars(0, data->BufTextLen);+ if (pos >= 0) data->InsertChars(0, h[size_t(pos)].c_str());+ return 0;+ }+ case ImGuiInputTextFlags_CallbackAlways:+ if (self->hasPendingText_) {+ data->DeleteChars(0, data->BufTextLen);+ data->InsertChars(0, self->pendingText_.c_str());+ self->hasPendingText_ = false;+ self->cursorToEnd_ = true;+ }+ if (self->cursorToEnd_) {+ data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen;+ self->cursorToEnd_ = false;+ }+ return 0;+ default:+ return 0;+ }+}++void Console::draw(App& app, const CanvasRect& rect) {+ app_ = &app;+ {+ std::vector<std::string> files;+ {+ std::lock_guard<std::mutex> lock(pendingMutex_);+ files.swap(pendingFiles_);+ }+ for (const auto& f : files) runFile(app, f);+ }+ const float s = app.uiScale_;+ ImGui::SetNextWindowPos(ImVec2(rect.x, rect.y), ImGuiCond_Always);+ ImGui::SetNextWindowSize(ImVec2(rect.w, rect.h), ImGuiCond_Always);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4.0f * s, 0.0f));+ ImGui::PushStyleColor(ImGuiCol_WindowBg, ImGui::ColorConvertU32ToFloat4(IM_COL32(0x16, 0x16, 0x18, 0xff)));+ const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize |+ ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoScrollWithMouse |+ ImGuiWindowFlags_NoFocusOnAppearing;+ if (bringToFront_) ImGui::SetNextWindowFocus();+ bringToFront_ = false;+ const bool visible = ImGui::Begin("Console", nullptr, flags);+ ImGui::PopStyleColor();+ ImGui::PopStyleVar(4);+ if (!visible) {+ ImGui::End();+ return;+ }+ ImDrawList* dl = ImGui::GetWindowDrawList();+ const ImVec2 origin = ImGui::GetWindowPos();+ const float w = rect.w;++ // Header bar (h 24) with a resize grip on its top edge.+ const float headerH = 24.0f * s;+ dl->AddRectFilled(origin, ImVec2(origin.x + w, origin.y + headerH), ui::color::header);+ dl->AddLine(origin, ImVec2(origin.x + w, origin.y), ui::color::border);+ ImGui::SetCursorScreenPos(origin);+ ImGui::InvisibleButton("##console_resize", ImVec2(w, 5.0f * s));+ if (ImGui::IsItemHovered() || ImGui::IsItemActive()) ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);+ if (ImGui::IsItemActive() && ImGui::GetIO().MouseDelta.y != 0.0f)+ app.layout_.consoleHeight = std::clamp(app.layout_.consoleHeight - ImGui::GetIO().MouseDelta.y / s, 100.0f, 400.0f);+ {+ const ImVec2 grip(origin.x + w * 0.5f, origin.y + 3.0f * s);+ dl->AddLine(ImVec2(grip.x - 14.0f * s, grip.y), ImVec2(grip.x + 14.0f * s, grip.y), IM_COL32(0x5a, 0x5a, 0x60, 0xff), 2.0f * s);+ }+ const float textY = origin.y + (headerH - ImGui::GetTextLineHeight()) * 0.5f;+ dl->AddText(ImVec2(origin.x + 10.0f * s, textY), ui::color::accent, ICON_LC_SQUARE_TERMINAL);+ dl->AddText(ImVec2(origin.x + 32.0f * s, textY), ui::color::text, "Console");+ dl->AddText(ImVec2(origin.x + 32.0f * s + ImGui::CalcTextSize("Console").x + 12.0f * s, textY), ui::color::textDim,+ "Every command you run appears here as a script line");+ {+ const float bs = 22.0f * s, gap = 2.0f * s;+ float x = origin.x + w - 8.0f * s - 4 * bs - 3 * gap;+ const float y = origin.y + (headerH - bs) * 0.5f;+ ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f * s);+ for (const char* id : {"script.run_file", "script.copy_session", "script.clear_console"}) {+ ImGui::SetCursorScreenPos(ImVec2(x, y));+ ui::ActionButton(app, id, ImVec2(bs, bs), ui::Look::Icon);+ x += bs + gap;+ }+ ImGui::SetCursorScreenPos(ImVec2(x, y));+ if (ImGui::Button(ICON_LC_X "###console_close", ImVec2(bs, bs))) closeRequested_ = true;+ const std::string key = app.actions_.shortcutText("ui.console");+ ui::HelpText("Close the console", key.c_str(), "Hide the console. The log and the session script are kept.", "Script");+ ui::DelayedTooltip(("Close " + key).c_str());+ ImGui::PopStyleVar();+ ImGui::PopStyleColor();+ }++ // Log.+ ImGui::PushFont(app.consoleFont());+ const float inputH = ImGui::GetFrameHeight() + 8.0f * s;+ ImGui::SetCursorScreenPos(ImVec2(origin.x, origin.y + headerH));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(10.0f * s, 4.0f * s));+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 1.0f * s));+ ImGui::BeginChild("##console_log", ImVec2(w, rect.h - headerH - inputH), ImGuiChildFlags_AlwaysUseWindowPadding,+ ImGuiWindowFlags_HorizontalScrollbar);+ const bool atBottom = ImGui::GetScrollY() >= ImGui::GetScrollMaxY() - 2.0f;+ ImGuiListClipper clipper;+ clipper.Begin(int(lines_.size()));+ while (clipper.Step()) {+ for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) {+ const Line& l = lines_[size_t(i)];+ const std::string src = l.source.empty() ? std::string() : "[" + l.source + "] ";+ switch (l.kind) {+ case Kind::Command:+ ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(IM_COL32(0xee, 0xee, 0xee, 0xff)), "%s> %s", src.c_str(), l.text.c_str());+ break;+ case Kind::Result:+ ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(IM_COL32(0xa4, 0xa4, 0xa8, 0xff)), " %s", l.text.c_str());+ break;+ case Kind::Error:+ ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(ui::color::danger), "%s! %s", src.c_str(), l.text.c_str());+ break;+ case Kind::Status:+ ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(IM_COL32(0x6c, 0x6c, 0x72, 0xff)), " %s", l.text.c_str());+ break;+ case Kind::Info:+ ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(IM_COL32(0xc8, 0xc8, 0xc8, 0xff)), "%s", l.text.c_str());+ break;+ }+ }+ }+ if (lines_.empty())+ ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(ui::color::textDim), "Type help and press Enter to list the commands.");+ if (scrollToBottom_ && (atBottom || focusInput_)) ImGui::SetScrollHereY(1.0f);+ scrollToBottom_ = false;+ ImGui::EndChild();+ ImGui::PopStyleVar(2);++ // Input line.+ const ImVec2 inputPos(origin.x, origin.y + rect.h - inputH);+ dl->AddLine(inputPos, ImVec2(inputPos.x + w, inputPos.y), IM_COL32(0x2a, 0x2a, 0x2e, 0xff));+ const float fy = inputPos.y + (inputH - ImGui::GetFrameHeight()) * 0.5f;+ dl->AddText(ImVec2(origin.x + 10.0f * s, fy + ImGui::GetStyle().FramePadding.y), ui::color::accent, ">");+ ImGui::SetCursorScreenPos(ImVec2(origin.x + 22.0f * s, fy));+ ImGui::SetNextItemWidth(w - 32.0f * s);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImVec4(1, 1, 1, 0.03f));+ ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImVec4(1, 1, 1, 0.04f));+ if (focusInput_) {+ ImGui::SetKeyboardFocusHere();+ focusInput_ = false;+ }+ const ImGuiInputTextFlags inputFlags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion |+ ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackCharFilter |+ ImGuiInputTextFlags_CallbackAlways;+ const bool entered = ImGui::InputTextWithHint("##console", "help, or a command such as remesh resolution=200", input_,+ sizeof input_, inputFlags, &Console::inputCallback, this);+ ImGui::PopStyleColor(3);+ ImGui::PopFont();+ ui::HelpText("Console", app.actions_.shortcutText("ui.console").c_str(),+ "Runs SculptForge script: one command per line or separated by ';', parameters as name=value "+ "(quote text with spaces). Tab completes, Up/Down recalls, help lists every command.",+ "Script");+ if (entered) {+ const std::string line = input_;+ input_[0] = 0;+ runLine(app, line);+ focusInput_ = true; // keep typing, like a terminal+ scrollToBottom_ = true;+ }+ ImGui::End();+ if (closeRequested_) {+ closeRequested_ = false;+ app.setConsoleOpen(false);+ }+}++} // namespace sfdiff --git a/src/app/Console.h b/src/app/Console.hnew file mode 100644index 00000000..8aa1cd11--- /dev/null+++ b/src/app/Console.h@@ -0,0 +1,80 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The script console (the ZBrush "ZScript window", backtick key): every command+// the app runs is echoed as a script line with its result, and the input line+// runs script statements (see core/Script.h) with Tab completion and history.+#pragma once++#include "app/UiLayout.h"+#include "core/Commands.h"++#include <imgui.h>++#include <mutex>+#include <string>+#include <vector>++namespace sf {++class App;++class Console {+public:+ enum class Kind { Command, Result, Error, Status, Info };++ // A command ran (from any source): "> name args" then its result.+ void echo(const std::string& statement, const CommandResult& result, const std::string& source = {});+ void print(Kind kind, const std::string& text);+ // Status messages that didn't come from a command appear dim.+ void watchStatus(const std::string& status);+ void seenStatus(const std::string& status) { lastStatus_ = status; } // already shown as a command result+ void clear();+ // The commands run this session, one per line, ready to paste back in (a macro recorder).+ std::string sessionScript() const;++ void focusInput();+ void prefill(const std::string& text);+ void runLine(App& app, const std::string& line);+ void runFile(App& app, const std::string& path);+ void queueScriptFile(std::string path); // from the file dialog thread++ void loadHistory(const std::string& path);+ void draw(App& app, const CanvasRect& rect);++private:+ struct Line {+ Kind kind;+ std::string text;+ std::string source;+ };+ void addHistory(const std::string& line);+ void complete(App& app, ImGuiInputTextCallbackData* data);+ void printHelp(App& app, const std::string& topic);+ static int inputCallback(ImGuiInputTextCallbackData* data);++ std::vector<Line> lines_;+ std::vector<std::string> session_;+ std::vector<std::string> history_;+ std::string historyPath_;+ int historyPos_ = -1; // -1: editing a new line+ std::string lastStatus_;+ std::string lastEcho_; // coalesces a slider that runs the same command every frame+ double lastEchoTime_ = -1.0;+ size_t lastEchoLine_ = 0;+ char input_[1024] = "";+ bool focusInput_ = false;+ bool bringToFront_ = false; // when opened: above any floating window that covers the strip+ int focusFrame_ = -100; // the backtick that opened the console arrives as text too: ignore it+ bool cursorToEnd_ = false;+ bool scrollToBottom_ = false;+ std::string lastTab_; // the input when Tab was last pressed (a second Tab lists candidates)+ std::string pendingText_; // replaces the input on the next frame (prefill)+ bool hasPendingText_ = false;+ App* app_ = nullptr; // for the input callback+ bool closeRequested_ = false; // backtick typed into the input+ std::mutex pendingMutex_;+ std::vector<std::string> pendingFiles_;+};++} // namespace sfdiff --git a/src/app/Ui.cpp b/src/app/Ui.cppindex 873dc931..09e560fd 100644--- a/src/app/Ui.cpp+++ b/src/app/Ui.cpp@@ -4,33 +4,437 @@#include "app/App.h"+#include <imgui_internal.h>++#include <algorithm>+#include <cfloat>+#include <cmath>#include <cstdio>+#include <cstring>namespace sf::ui {-// Phase 0 stubs: plain buttons and sliders. The help/console workstream adds Ctrl-hover help and-// customize-mode dragging; the shell workstream adds icon and tile looks.+namespace {++// The Ctrl-help request for this frame: the last hovered item that asked for help wins.+struct HelpRequest {+ bool active = false;+ std::string title, shortcut, description, path, command;+ const char* icon = nullptr;+ bool disabled = false;+ std::vector<ParamSpec> params;+ bool hasCommand = false;+};++HelpRequest g_help;+std::string g_shown;+bool g_popupInfo = true;+int g_nextShelf = ShelfNone, g_nextIndex = -1;++ImVec4 rgba(ImU32 c, float alpha = -1.0f) {+ ImVec4 v = ImGui::ColorConvertU32ToFloat4(c);+ if (alpha >= 0.0f) v.w = alpha;+ return v;+}++float uiScale() { return ImGui::GetFontSize() / 15.0f; }++bool itemHoveredForHelp() {+ return ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem);+}++bool wantHelp() { return g_popupInfo && CtrlHeld(); }++const char* typeName(ParamSpec::Type t) {+ switch (t) {+ case ParamSpec::Type::Bool: return "true/false";+ case ParamSpec::Type::Number: return "number";+ case ParamSpec::Type::String: return "text";+ }+ return "";+}++void takeOrigin(int& shelf, int& index) {+ shelf = g_nextShelf;+ index = g_nextIndex;+ g_nextShelf = ShelfNone;+ g_nextIndex = -1;+}++bool dragSource(App& app, const char* itemId, const char* label, int shelf, int index) {+ if (!app.layout().customize || !CtrlHeld() || !AltHeld()) return false;+ if (!ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceAllowNullID)) return false;+ UiItemPayload p;+ std::snprintf(p.id, sizeof p.id, "%s", itemId);+ p.fromShelf = shelf;+ p.fromIndex = index;+ ImGui::SetDragDropPayload(kUiItemPayload, &p, sizeof p);+ ImGui::TextUnformatted(label);+ ImGui::TextColored(rgba(color::textDim), shelf >= 0 ? "Drop on a shelf to move, elsewhere to remove" : "Drop on a shelf to add");+ ImGui::EndDragDropSource();+ return true;+}++} // namespace++bool CtrlHeld() {+ const ImGuiIO& io = ImGui::GetIO();+ return io.KeyCtrl || io.KeySuper || (SDL_GetModState() & (SDL_KMOD_CTRL | SDL_KMOD_GUI)) != 0;+}++bool AltHeld() { return ImGui::GetIO().KeyAlt || (SDL_GetModState() & SDL_KMOD_ALT) != 0; }++void SetNextItemOrigin(int shelf, int index) {+ g_nextShelf = shelf;+ g_nextIndex = index;+}++bool UiItemDragSource(App& app, const char* itemId, const char* label) {+ int shelf, index;+ takeOrigin(shelf, index);+ return dragSource(app, itemId, label, shelf, index);+}++void HelpText(const char* title, const char* shortcut, const char* description, const char* path) {+ if (!wantHelp() || !itemHoveredForHelp()) return;+ g_help = HelpRequest{};+ g_help.active = true;+ g_help.title = title ? title : "";+ g_help.shortcut = shortcut ? shortcut : "";+ g_help.description = description ? description : "";+ g_help.path = path ? path : "";+ g_help.disabled = (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled) != 0;+}++void HelpAction(App& app, const char* actionId) {+ if (!wantHelp() || !itemHoveredForHelp()) return;+ const Action* a = app.actions().find(actionId);+ if (!a) return;+ g_help = HelpRequest{};+ g_help.active = true;+ g_help.title = a->label;+ g_help.icon = a->icon;+ g_help.shortcut = app.actions().shortcutText(a->id);+ g_help.path = a->palette;+ g_help.command = a->command;+ g_help.disabled = a->enabled && !a->enabled();+ g_help.description = a->description;+ if (const Command* c = a->command.empty() ? nullptr : app.commands().find(a->command)) {+ if (g_help.description.empty()) g_help.description = c->description;+ g_help.params = c->params;+ g_help.hasCommand = true;+ }+}++float KeycapsWidth(const std::string& chord) {+ const float s = uiScale(), pad = 5.0f * s, gap = 3.0f * s;+ float w = 0.0f;+ size_t start = 0;+ bool firstChord = true;+ while (start <= chord.size()) {+ const size_t at = chord.find(" / ", start);+ const std::string part = chord.substr(start, at == std::string::npos ? std::string::npos : at - start);+ if (!firstChord) w += ImGui::CalcTextSize("/").x + 2 * gap;+ firstChord = false;+ const auto keys = chordKeys(part);+ for (size_t i = 0; i < keys.size(); ++i) {+ if (i) w += ImGui::CalcTextSize("+").x + 2 * gap;+ w += ImGui::CalcTextSize(keys[i].c_str()).x + 2 * pad;+ }+ if (at == std::string::npos) break;+ start = at + 3;+ }+ return w;+}++float KeycapsAt(ImDrawList* dl, ImVec2 p, const std::string& chord) {+ const float s = uiScale(), pad = 5.0f * s, gap = 3.0f * s;+ const float h = ImGui::GetTextLineHeight() + 2.0f * s;+ const float x0 = p.x;+ auto dimText = [&](const char* t) {+ p.x += gap;+ dl->AddText(ImVec2(p.x, p.y + 1.0f * s), color::textDim, t);+ p.x += ImGui::CalcTextSize(t).x + gap;+ };+ size_t start = 0;+ bool firstChord = true;+ while (start <= chord.size()) {+ const size_t at = chord.find(" / ", start);+ const std::string part = chord.substr(start, at == std::string::npos ? std::string::npos : at - start);+ if (!firstChord) dimText("/");+ firstChord = false;+ const auto keys = chordKeys(part);+ for (size_t i = 0; i < keys.size(); ++i) {+ if (i) dimText("+");+ const ImVec2 ts = ImGui::CalcTextSize(keys[i].c_str());+ const ImVec2 a = p, b(p.x + ts.x + 2 * pad, p.y + h);+ dl->AddRectFilled(a, b, IM_COL32(0x2c, 0x2c, 0x30, 0xff), 3.0f * s);+ dl->AddRect(a, b, IM_COL32(0x4a, 0x4a, 0x50, 0xff), 3.0f * s);+ dl->AddText(ImVec2(a.x + pad, a.y + 1.0f * s), color::accent, keys[i].c_str());+ p.x = b.x;+ }+ if (at == std::string::npos) break;+ start = at + 3;+ }+ return p.x - x0;+}++void Keycaps(const std::string& chord) {+ if (chord.empty()) return;+ const float w = KeycapsAt(ImGui::GetWindowDrawList(), ImGui::GetCursorScreenPos(), chord);+ ImGui::Dummy(ImVec2(w, ImGui::GetTextLineHeight() + 2.0f * uiScale()));+ if (ImGui::GetCurrentContext()->LogEnabled) ImGui::LogText(" %s", chord.c_str());+}-bool ActionButton(App& app, const char* actionId, ImVec2 size, Look) {+void DelayedTooltip(const char* text) {+ if (!text || !*text || CtrlHeld()) return;+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay)) ImGui::SetTooltip("%s", text);+}++bool ActionButton(App& app, const char* actionId, ImVec2 size, Look look) {+ int shelf, index;+ takeOrigin(shelf, index);const Action* a = app.actions().find(actionId);- if (!a) return false;+ if (!a) {+ ImGui::BeginDisabled();+ ImGui::Button((std::string("?") + actionId).c_str(), size);+ ImGui::EndDisabled();+ return false;+ }+ // Copy what we need: running the action may add or replace actions.+ const std::string id = a->id, label = a->label;+ const char* icon = a->icon;+ const std::function<void()> run = a->run;const bool enabled = !a->enabled || a->enabled();+ const bool checked = a->checked && a->checked();+ const float s = uiScale();+ if (look == Look::Icon && !icon) look = Look::Label;+ if (look == Look::IconLabel && !icon) look = Look::Label;+ if (look == Look::Icon && size.x <= 0.0f) size = ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight());+ if (look == Look::Tile && size.x <= 0.0f) size = ImVec2(44.0f * s, 40.0f * s);++ int colors = 0;+ if (checked) {+ ImGui::PushStyleColor(ImGuiCol_Button, rgba(color::accent));+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, rgba(color::accentHover));+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));+ colors = 3;+ }ImGui::BeginDisabled(!enabled);- const bool clicked = ImGui::Button((a->label + "##" + a->id).c_str(), size);+ bool clicked = false;+ const std::string itemLabel = label + "##" + id;+ bool clipped = false;+ if (look == Look::Label) {+ clicked = ImGui::Button(itemLabel.c_str(), size);+ const float textW = ImGui::CalcTextSize(itemLabel.c_str(), nullptr, true).x + 2.0f * ImGui::GetStyle().FramePadding.x;+ clipped = size.x > 0.0f && textW > size.x + 0.5f;+ } else if (look == Look::IconLabel) {+ // Drawn by hand so the item keeps the plain label as its name ("Store Config", not glyph + label).+ const std::string text = std::string(icon) + " " + label;+ const ImGuiStyle& st = ImGui::GetStyle();+ const ImVec2 ts = ImGui::CalcTextSize(text.c_str());+ const ImVec2 full = ImGui::CalcItemSize(size, ts.x + st.FramePadding.x * 2.0f, ts.y + st.FramePadding.y * 2.0f);+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0, 0, 0, 0));+ clicked = ImGui::Button(itemLabel.c_str(), full);+ ImGui::PopStyleColor();+ const ImRect r(ImGui::GetItemRectMin(), ImGui::GetItemRectMax());+ ImGui::RenderTextClipped(ImVec2(r.Min.x + st.FramePadding.x, r.Min.y + st.FramePadding.y),+ ImVec2(r.Max.x - st.FramePadding.x, r.Max.y - st.FramePadding.y), text.c_str(), nullptr, &ts,+ st.ButtonTextAlign, &r);+ clipped = ts.x + st.FramePadding.x * 2.0f > full.x + 0.5f;+ } else {+ // Icon / Tile: the label stays the item's name (for tests and screen readers) but is drawn by hand.+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0, 0, 0, 0));+ clicked = ImGui::Button(itemLabel.c_str(), size);+ ImGui::PopStyleColor();+ const ImRect r(ImGui::GetItemRectMin(), ImGui::GetItemRectMax());+ ImDrawList* dl = ImGui::GetWindowDrawList();+ const ImU32 fg = !enabled ? color::textDim : checked ? IM_COL32_WHITE : color::text;+ if (look == Look::Icon) {+ const ImVec2 is = ImGui::CalcTextSize(icon);+ dl->AddText(ImVec2(std::floor(r.GetCenter().x - is.x * 0.5f), std::floor(r.GetCenter().y - is.y * 0.5f)), fg, icon);+ } else {+ const ImVec2 is = ImGui::CalcTextSize(icon ? icon : "");+ const float small = 0.8f;+ ImFont* font = ImGui::GetFont();+ const float fs = ImGui::GetFontSize() * small;+ const ImVec2 ls = font->CalcTextSizeA(fs, FLT_MAX, 0.0f, label.c_str());+ const float total = (icon ? is.y : 0.0f) + ls.y;+ float y = r.GetCenter().y - total * 0.5f;+ if (icon) {+ dl->AddText(ImVec2(std::floor(r.GetCenter().x - is.x * 0.5f), std::floor(y)), fg, icon);+ y += is.y;+ }+ const float maxW = r.GetWidth() - 2.0f * s;+ clipped = ls.x > maxW;+ const float x = clipped ? r.Min.x + 1.0f * s : r.GetCenter().x - ls.x * 0.5f;+ const ImVec4 clip(r.Min.x + 1.0f * s, r.Min.y, r.Max.x - 1.0f * s, r.Max.y);+ dl->AddText(font, fs, ImVec2(std::floor(x), std::floor(y)), fg, label.c_str(), nullptr, 0.0f, &clip);+ }+ clipped = clipped || look == Look::Icon;+ }ImGui::EndDisabled();- if (clicked && a->run) {- app.actions().touch(a->id);- a->run();+ if (colors) ImGui::PopStyleColor(colors);++ const bool customize = app.layout().customize;+ dragSource(app, id.c_str(), label.c_str(), shelf, index);+ HelpAction(app, id.c_str());+ if (clipped) {+ const std::string chord = app.actions().shortcutText(id);+ DelayedTooltip((chord.empty() ? label : label + " " + chord).c_str());}- return clicked;+ if (!clicked) return false;+ if (CtrlHeld() && AltHeld()) {+ // Ctrl+Alt+click: customize mode drags instead; otherwise it assigns a shortcut (ZBrush).+ if (!customize) app.beginShortcutCapture(id);+ return false;+ }+ if (run) run();+ return true;}-void HelpText(const char*, const char*, const char*, const char*) {}+bool SliderInside(const char* id, float* v, float lo, float hi, const char* format, ImGuiSliderFlags flags) {+ const float s = uiScale();+ const float w = ImGui::CalcItemWidth(), h = ImGui::GetFrameHeight();+ const ImVec2 p = ImGui::GetCursorScreenPos();+ ImDrawList* dl = ImGui::GetWindowDrawList();+ // Frame and fill go underneath the slider (which draws a transparent frame and a thin grab on top).+ dl->ChannelsSplit(2);+ dl->ChannelsSetCurrent(1);+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0, 0, 0, 0));+ ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImVec4(1, 1, 1, 0.04f));+ ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImVec4(1, 1, 1, 0.06f));+ ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 3.0f * s);+ const bool changed = ImGui::SliderFloat(id, v, lo, hi, format, flags);+ ImGui::PopStyleVar();+ ImGui::PopStyleColor(3);+ dl->ChannelsSetCurrent(0);+ float t = 0.0f;+ if (hi > lo) {+ if ((flags & ImGuiSliderFlags_Logarithmic) && lo > 0.0f)+ t = std::log(std::max(*v, lo) / lo) / std::log(hi / lo);+ else+ t = (*v - lo) / (hi - lo);+ }+ t = std::clamp(t, 0.0f, 1.0f);+ const float rounding = ImGui::GetStyle().FrameRounding;+ dl->AddRectFilled(p, ImVec2(p.x + w, p.y + h), ImGui::GetColorU32(ImGuiCol_FrameBg), rounding);+ dl->AddRectFilled(p, ImVec2(p.x + w * t, p.y + h), IM_COL32(0xf0, 0x88, 0x2e, 0x38), rounding);+ dl->ChannelsMerge();+ return changed;+}-void HelpAction(App&, const char*) {}+void DrawHelp(App& app) {+ const UiPrefs& prefs = app.uiPrefs();+ g_popupInfo = prefs.popupInfo;+ ImGui::GetStyle().HoverDelayNormal = std::max(0.05f, prefs.tooltipDelay);+ g_shown.clear();+ if (!g_help.active) return;+ HelpRequest r = std::move(g_help);+ g_help = HelpRequest{};+ if (!wantHelp()) return;+ const bool alternate = AltHeld() && r.hasCommand; // Ctrl+Alt: the scripting reference-bool SliderInside(const char* id, float* v, float lo, float hi, const char* format, ImGuiSliderFlags flags) {- return ImGui::SliderFloat(id, v, lo, hi, format, flags);+ const float s = uiScale(), width = 340.0f * s;+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ const ImVec2 mouse = ImGui::GetIO().MousePos;+ ImVec2 size(width, 120.0f * s);+ if (ImGuiWindow* last = ImGui::FindWindowByName("##sf_help")) size.y = last->Size.y;+ ImVec2 pos(mouse.x + 18.0f * s, mouse.y + 18.0f * s);+ if (pos.x + size.x > vp->Pos.x + vp->Size.x - 4.0f * s) pos.x = mouse.x - 12.0f * s - size.x;+ if (pos.y + size.y > vp->Pos.y + vp->Size.y - 4.0f * s) pos.y = mouse.y - 12.0f * s - size.y;+ pos.x = std::max(pos.x, vp->Pos.x + 4.0f * s);+ pos.y = std::max(pos.y, vp->Pos.y + 4.0f * s);++ ImGui::SetNextWindowPos(pos, ImGuiCond_Always);+ ImGui::SetNextWindowSizeConstraints(ImVec2(width, 0), ImVec2(width, FLT_MAX));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(10.0f * s, 9.0f * s));+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 6.0f * s);+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4.0f * s, 4.0f * s));+ ImGui::PushStyleColor(ImGuiCol_WindowBg, rgba(IM_COL32(0x18, 0x18, 0x1a, 0xff), std::clamp(prefs.helpOpacity, 0.3f, 1.0f)));+ ImGui::PushStyleColor(ImGuiCol_Border, rgba(color::accent, 0.6f));+ const ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoInputs |+ ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoFocusOnAppearing |+ ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;+ if (ImGui::Begin("##sf_help", nullptr, flags)) {+ ImDrawList* dl = ImGui::GetWindowDrawList();+ // Title row: icon + title (SemiBold), keycaps on the right.+ const float keysW = r.shortcut.empty() ? 0.0f : KeycapsWidth(r.shortcut);+ ImGui::PushFont(app.helpTitleFont());+ const std::string title = (r.icon ? std::string(r.icon) + " " : std::string()) + r.title ++ (alternate ? " \xc2\xb7 script" : "");+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - keysW - 8.0f * s);+ ImGui::TextUnformatted(title.c_str());+ ImGui::PopTextWrapPos();+ ImGui::PopFont();+ if (!r.shortcut.empty()) {+ ImGui::SameLine(ImGui::GetWindowContentRegionMax().x - keysW);+ Keycaps(r.shortcut);+ }+ {+ const ImVec2 a = ImGui::GetCursorScreenPos();+ dl->AddLine(ImVec2(a.x, a.y + 1.0f * s), ImVec2(a.x + ImGui::GetContentRegionAvail().x, a.y + 1.0f * s),+ IM_COL32(0x34, 0x34, 0x38, 0xff));+ ImGui::Dummy(ImVec2(0, 3.0f * s));+ }+ ImGui::PushTextWrapPos(0.0f);+ if (!alternate) {+ ImGui::PushStyleColor(ImGuiCol_Text, rgba(IM_COL32(0xc8, 0xc8, 0xc8, 0xff)));+ ImGui::TextUnformatted(r.description.empty() ? "No description yet." : r.description.c_str());+ ImGui::PopStyleColor();+ if (r.hasCommand && !r.params.empty()) {+ ImGui::PushStyleColor(ImGuiCol_Text, rgba(color::textDim));+ ImGui::TextUnformatted("Hold Alt for the scripting parameters.");+ ImGui::PopStyleColor();+ }+ } else {+ ImGui::PushFont(app.consoleFont());+ std::string usage = r.command;+ for (const auto& p : r.params)+ usage += p.required ? " " + p.name + "=<" + typeName(p.type) + ">" : " [" + p.name + "=...]";+ ImGui::TextColored(rgba(color::accent), "%s", usage.c_str());+ ImGui::PopFont();+ if (r.params.empty()) ImGui::TextColored(rgba(color::textDim), "No parameters.");+ for (const auto& p : r.params) {+ ImGui::PushFont(app.consoleFont());+ ImGui::TextColored(rgba(color::text), "%s", p.name.c_str());+ ImGui::PopFont();+ ImGui::SameLine();+ ImGui::TextColored(rgba(color::textDim), "%s%s", typeName(p.type), p.required ? ", required" : "");+ ImGui::Indent(10.0f * s);+ ImGui::PushStyleColor(ImGuiCol_Text, rgba(IM_COL32(0xc8, 0xc8, 0xc8, 0xff)));+ ImGui::TextUnformatted(p.description.c_str());+ ImGui::PopStyleColor();+ ImGui::Unindent(10.0f * s);+ }+ }+ if (r.disabled) ImGui::TextColored(rgba(color::danger), "Not available right now.");+ ImGui::PopTextWrapPos();+ // Footer: where it lives (dim) and the script command (mono, right).+ if (!r.path.empty() || !r.command.empty()) {+ ImGui::Dummy(ImVec2(0, 2.0f * s));+ ImGui::SetWindowFontScale(0.82f);+ if (!r.path.empty()) ImGui::TextColored(rgba(color::textDim), "%s", r.path.c_str());+ ImGui::SetWindowFontScale(1.0f);+ if (!r.command.empty()) {+ ImGui::PushFont(app.consoleFont());+ const float cw = ImGui::CalcTextSize(r.command.c_str()).x;+ if (!r.path.empty()) ImGui::SameLine(ImGui::GetWindowContentRegionMax().x - cw);+ else ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - cw);+ ImGui::TextColored(rgba(color::textDim), "%s", r.command.c_str());+ ImGui::PopFont();+ }+ }+ }+ ImGui::End();+ ImGui::PopStyleColor(2);+ ImGui::PopStyleVar(4);++ g_shown = r.title + "\n" + r.shortcut + "\n" + r.description + "\n" + r.path + "\n" + r.command;+ for (const auto& p : r.params) g_shown += "\n" + p.name + ": " + p.description;}+const std::string& HelpShown() { return g_shown; }+} // namespace sf::uidiff --git a/src/app/Ui.h b/src/app/Ui.hindex dedf852e..902d81ac 100644--- a/src/app/Ui.h+++ b/src/app/Ui.h@@ -6,6 +6,8 @@#include <imgui.h>+#include <string>+namespace sf {class App;}@@ -15,12 +17,53 @@ namespace sf::ui {enum class Look { Label, Icon, IconLabel, Tile };// Runs the action on click; toggles draw with the accent when checked(); shows Ctrl-hover help;-// is a Ctrl+Alt drag source in customize mode. Returns true when clicked.+// is a Ctrl+Alt drag source in customize mode. Ctrl+Alt+click (outside customize mode) assigns+// a shortcut, as in ZBrush. Returns true when the action ran.bool ActionButton(App& app, const char* actionId, ImVec2 size = {}, Look look = Look::Label);// Ctrl-hover help for the last item.void HelpText(const char* title, const char* shortcut, const char* description, const char* path = nullptr);void HelpAction(App& app, const char* actionId);-// ZBrush-style slider with its label drawn inside the frame.+// ZBrush-style slider with its label drawn inside the frame ("Draw Size 60") and a thin accent grab.bool SliderInside(const char* id, float* v, float lo, float hi, const char* format, ImGuiSliderFlags flags = 0);+// Customize mode: shelves this payload ("SF_UIITEM") is dragged from and dropped on.+enum Shelf { ShelfNone = -1, ShelfTop, ShelfLeft, ShelfRight, ShelfBottom };+struct UiItemPayload {+ char id[96] = "";+ int fromShelf = ShelfNone;+ int fromIndex = -1;+};+inline constexpr const char* kUiItemPayload = "SF_UIITEM";+// Where the next ActionButton / UiItemDragSource sits (shelves call this before drawing an item).+void SetNextItemOrigin(int shelf, int index);+// Makes the last item a Ctrl+Alt drag source in customize mode (for widgets that aren't ActionButtons).+bool UiItemDragSource(App& app, const char* itemId, const char* label);++// Keyboard keycaps for a chord ("Ctrl+Shift+I", "F3 / Ctrl+Shift+P"), drawn inline as an item.+void Keycaps(const std::string& chord);+float KeycapsWidth(const std::string& chord);+float KeycapsAt(ImDrawList* drawList, ImVec2 pos, const std::string& chord); // no layout; returns the width+// A plain tooltip after the hover delay (icon-only buttons, clipped labels); suppressed while Ctrl is held.+void DelayedTooltip(const char* text);+bool CtrlHeld();+bool AltHeld();++// Draws this frame's Ctrl-help box; call once, after every other window.+void DrawHelp(App& app);+// What the Ctrl-help box showed in the last frame ("" if none), for UI tests.+const std::string& HelpShown();++// Theme tokens shared by the help, palette and console (ui-spec section 10).+namespace color {+inline constexpr ImU32 accent = IM_COL32(0xf0, 0x88, 0x2e, 0xff);+inline constexpr ImU32 accentHover = IM_COL32(0xff, 0x9a, 0x45, 0xff);+inline constexpr ImU32 text = IM_COL32(0xd8, 0xd8, 0xd8, 0xff);+inline constexpr ImU32 textDim = IM_COL32(0x8c, 0x8c, 0x90, 0xff);+inline constexpr ImU32 danger = IM_COL32(0xe5, 0x60, 0x4a, 0xff);+inline constexpr ImU32 panelBg = IM_COL32(0x25, 0x25, 0x28, 0xff);+inline constexpr ImU32 shellBg = IM_COL32(0x1e, 0x1e, 0x20, 0xff);+inline constexpr ImU32 header = IM_COL32(0x2e, 0x2e, 0x32, 0xff);+inline constexpr ImU32 border = IM_COL32(0x12, 0x12, 0x14, 0xff);+} // namespace color+} // namespace sf::uidiff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 8c2e8ecb..2b948a6b 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -8,7 +8,7 @@//// click LABEL / double_click LABEL / right_click LABEL / hover LABEL// type LABEL TEXT click a text field and type into it-// key COMBO e.g. enter, escape, ctrl+z, ctrl+shift+z, 3+// key COMBO e.g. enter, escape, ctrl+z, ctrl+shift+z, 3, comma, backtick, tab, f3// hold MODS ctrl / shift / alt / ctrl+shift ... or none (for strokes and drags)// stroke U0 V0 U1 V1 [S] brush stroke across the model (fractions of its on-screen bounds)// drag X0 Y0 X1 Y1 [S] left-drag in window fractions (rectangle hide, sliders...)@@ -20,6 +20,7 @@// expect LABEL / expect_not LABEL// expect_text TEXT / expect_no_text TEXT any text drawn this frame contains TEXT// expect_status TEXT the status bar message contains TEXT+// expect_help TEXT the Ctrl-hover help box shown this frame contains TEXT (hold ctrl, then hover)// clipboard TEXT put TEXT on the clipboard (to test pasting, e.g. a brush code)// expect_clipboard TEXT the clipboard contains TEXT (after a copy)// click_subtool NAME [U V] left-click SubTool NAME in the viewport (with the held modifiers, e.g.@@ -29,11 +30,14 @@// subtools (count), active_subtool (index, 0 = top), visible_subtools,// edited_subtools (SubTools with undo history), user_brushes (brushes in the// user library), library_files (.sfbrush files in it; UI tests get an empty-// one in --ui-out/brush-library); OP is == != < <= > >=+// one in --ui-out/brush-library), ui_config (1 once Store Config wrote ui.json),+// console_open, command_palette_open, customize, shelves_visible,+// right_tray_open, left_tray_open, lightbox_open; OP is == != < <= > >=// (mesh values are the active SubTool's)// shot NAME save a screenshot NAME.png (to --ui-out)#include "app/App.h"#include "app/Demo.h"+#include "app/Ui.h"#include "core/BrushLibrary.h"#include "core/Script.h"@@ -163,6 +167,18 @@ double Demo::query(const std::string& name, bool& known) const {if (name == "show_polygroups") return app_.renderSettings_.showPolygroups ? 1.0 : 0.0;if (name == "show_mask") return app_.renderSettings_.showMask ? 1.0 : 0.0;if (name == "wireframe") return app_.renderSettings_.wireframe ? 1.0 : 0.0;+ if (name == "ui_config") {+ std::error_code ec;+ const std::string p = app_.uiConfigPath();+ return !p.empty() && std::filesystem::is_regular_file(std::filesystem::path(std::u8string(p.begin(), p.end())), ec) ? 1.0 : 0.0;+ }+ if (name == "console_open") return app_.layout_.consoleOpen ? 1.0 : 0.0;+ if (name == "command_palette_open") return app_.palette_.isOpen() ? 1.0 : 0.0;+ if (name == "customize") return app_.layout_.customize ? 1.0 : 0.0;+ if (name == "shelves_visible") return app_.layout_.shelvesVisible ? 1.0 : 0.0;+ if (name == "right_tray_open") return app_.layout_.rightTrayOpen ? 1.0 : 0.0;+ if (name == "left_tray_open") return app_.layout_.leftTrayOpen ? 1.0 : 0.0;+ if (name == "lightbox_open") return app_.lightbox_.open() ? 1.0 : 0.0;const Document& doc = app_.doc_;if (name == "subtools") return double(doc.subtoolCount());if (name == "active_subtool") return double(doc.activeSubtool);@@ -266,6 +282,10 @@ void Demo::testKey(int line, const std::string& combo) {std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return char(std::tolower(c)); });if (lower == "enter") keyName = "Return"; // SDL's name for itelse if (lower == "esc") keyName = "Escape";+ else if (lower == "comma") keyName = ",";+ else if (lower == "backtick" || lower == "grave") keyName = "`";+ else if (lower == "tab") keyName = "Tab";+ else if (lower == "f3") keyName = "F3";const SDL_Keycode key = SDL_GetKeyFromName(keyName.c_str());if (key == SDLK_UNKNOWN) {run([this, line, keyName] { fail(line, "unknown key \"" + keyName + "\""); });@@ -514,6 +534,17 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& eif (app_.status_.find(text) == std::string::npos)fail(line, "status is \"" + app_.status_ + "\", expected it to contain \"" + text + "\"");});+ } else if (verb == "expect_help") {+ if (!need(1)) return false;+ const std::string text = restOf(lineText_, 1);+ steps_.push_back([this, line, text](float t) {+ if (t == 0.0f) return false; // the frame drawn after the previous step+ const std::string& shown = ui::HelpShown();+ if (shown.empty()) fail(line, "no Ctrl-help box is shown (hold ctrl, then hover an item)");+ else if (shown.find(text) == std::string::npos)+ fail(line, "the Ctrl-help box says \"" + shown.substr(0, 120) + "\", expected \"" + text + "\"");+ return true;+ });} else if (verb == "clipboard") {if (!need(1)) return false;const std::string text = restOf(lineText_, 1);diff --git a/src/core/Script.cpp b/src/core/Script.cppindex ef7fee80..93808576 100644--- a/src/core/Script.cpp+++ b/src/core/Script.cpp@@ -3,6 +3,7 @@#include "core/Script.h"#include <cctype>+#include <cstdio>#include <cstdlib>namespace sf {@@ -101,4 +102,31 @@ bool parseScript(const std::string& text, std::vector<ScriptStatement>& out, stdreturn flush();}+std::string formatValue(const ArgValue& value) {+ if (const bool* b = std::get_if<bool>(&value)) return *b ? "true" : "false";+ if (const double* d = std::get_if<double>(&value)) {+ char buf[40];+ std::snprintf(buf, sizeof buf, "%g", *d);+ if (std::strtod(buf, nullptr) != *d) std::snprintf(buf, sizeof buf, "%.17g", *d);+ return buf;+ }+ const std::string& s = std::get<std::string>(value);+ bool quote = s.empty() || parseValue(s, false).index() != 2; // "true" or "12" must stay strings+ for (char c : s)+ if (std::isspace(static_cast<unsigned char>(c)) || c == ';' || c == '#' || c == '"') quote = true;+ if (!quote) return s;+ std::string out = "\"";+ for (char c : s) {+ if (c == '"' || c == '\\') out += '\\';+ out += c;+ }+ return out + '"';+}++std::string formatStatement(const std::string& command, const Args& args) {+ std::string out = command;+ for (const auto& [key, value] : args) out += " " + key + "=" + formatValue(value);+ return out;+}+} // namespace sfdiff --git a/src/core/Script.h b/src/core/Script.hindex 5b5e7207..d3c147f1 100644--- a/src/core/Script.h+++ b/src/core/Script.h@@ -23,4 +23,10 @@ struct ScriptStatement {bool parseScript(const std::string& text, std::vector<ScriptStatement>& out, std::string& error);+// The inverse of parseScript: `remesh resolution=200`, `layer_add name="Big Smile"`. Strings are quoted+// when they contain spaces or would otherwise read back as a number or bool; numbers use the shortest+// form that reads back exactly.+std::string formatValue(const ArgValue& value);+std::string formatStatement(const std::string& command, const Args& args);+} // namespace sfdiff --git a/tests/test_actions.cpp b/tests/test_actions.cppnew file mode 100644index 00000000..cc3716f0--- /dev/null+++ b/tests/test_actions.cpp@@ -0,0 +1,84 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The action registry behind shortcuts, help and the command palette (src/app/Actions.cpp).+#include "TestHarness.h"++#ifdef SF_TEST_ACTIONS+#include "app/Actions.h"+#include "core/Commands.h"++using namespace sf;++TEST(action_chords) {+ Chord c;+ CHECK(parseChord("Ctrl+Shift+Z", c) && c.key == SDLK_Z && c.ctrl && c.shift && !c.alt);+ CHECK(chordText(c) == "Ctrl+Shift+Z");+ CHECK(parseChord("shift+f", c) && c.key == SDLK_F && c.shift && chordText(c) == "Shift+F");+ CHECK(parseChord(",", c) && c.key == SDLK_COMMA && !c.ctrl && chordText(c) == ",");+ CHECK(parseChord("`", c) && c.key == SDLK_GRAVE);+ CHECK(parseChord("F3", c) && c.key == SDLK_F3 && chordText(c) == "F3");+ CHECK(parseChord("Ctrl++", c) && c.key == SDLK_PLUS && c.ctrl);+ CHECK(parseChord("Cmd+D", c) && c.ctrl); // macOS spelling+ CHECK(!parseChord("", c) && !parseChord("Hyper+X", c) && !parseChord("Ctrl+", c));+ const auto two = parseChords("Ctrl+Shift+Z / Ctrl+Y");+ CHECK(two.size() == 2 && two[1].key == SDLK_Y && two[1].ctrl);+ CHECK(chordFromEvent(SDLK_D, SDL_KMOD_LGUI).ctrl); // Cmd counts as Ctrl+ CHECK((chordKeys("Ctrl+Shift+I") == std::vector<std::string>{"Ctrl", "Shift", "I"}));+ CHECK((chordKeys("Enter") == std::vector<std::string>{"Enter"}));+}++TEST(action_registry_keys_and_overrides) {+ ActionRegistry reg;+ int undo = 0, redo = 0, wire = 0;+ reg.add({"edit.undo", "Undo", nullptr, "", "Edit", "Ctrl+Z", "undo", [&] { ++undo; }, nullptr, nullptr});+ reg.add({"edit.redo", "Redo", nullptr, "", "Edit", "Ctrl+Shift+Z / Ctrl+Y", "redo", [&] { ++redo; }, nullptr, nullptr});+ reg.add({"view.wireframe", "Wireframe", nullptr, "", "Render", "W / Shift+F", "", [&] { ++wire; }, nullptr,+ [] { return true; }});+ CHECK(reg.handleKey(SDLK_Z, SDL_KMOD_LCTRL) && undo == 1);+ CHECK(reg.handleKey(SDLK_Z, SDL_Keymod(SDL_KMOD_LCTRL | SDL_KMOD_LSHIFT)) && redo == 1);+ CHECK(reg.handleKey(SDLK_Y, SDL_KMOD_RCTRL) && redo == 2);+ CHECK(reg.handleKey(SDLK_F, SDL_KMOD_LSHIFT) && wire == 1);+ CHECK(!reg.handleKey(SDLK_F, SDL_KMOD_NONE)); // plain F is not bound here+ CHECK(reg.handleKey(SDLK_W, SDL_KMOD_LALT) && wire == 2); // plain keys ignore Alt/Shift when nothing else matches+ CHECK(!reg.handleKey(SDLK_W, SDL_KMOD_LCTRL));+ --wire;+ CHECK(!reg.handleKey(SDLK_LCTRL, SDL_KMOD_LCTRL));++ // ZBrush-style assignment: taking Ctrl+Y from Redo leaves Redo its other chord.+ CHECK(reg.assignShortcut("view.wireframe", "Ctrl+Y") == "Redo");+ CHECK(reg.shortcutText("view.wireframe") == "Ctrl+Y");+ CHECK(reg.shortcutText("edit.redo") == "Ctrl+Shift+Z");+ CHECK(reg.handleKey(SDLK_Y, SDL_KMOD_LCTRL) && wire == 2 && redo == 2);+ CHECK(!reg.handleKey(SDLK_W, SDL_KMOD_NONE));++ // Overrides round-trip through JSON (Store Config) and clear (Restore Standard UI).+ const Json saved = reg.overridesToJson();+ reg.clearOverrides();+ CHECK(reg.shortcutText("view.wireframe") == "W / Shift+F" && !reg.hasOverride("edit.redo"));+ reg.overridesFromJson(saved);+ CHECK(reg.shortcutText("view.wireframe") == "Ctrl+Y" && reg.hasOverride("edit.redo"));+ reg.setShortcut("view.wireframe", "W / Shift+F"); // back to the default: no override left+ CHECK(!reg.hasOverride("view.wireframe"));++ reg.touch("edit.undo");+ reg.touch("edit.redo");+ reg.touch("edit.undo");+ CHECK(reg.recent().size() == 2 && reg.recent()[0] == "edit.undo");+}++TEST(action_registry_commands) {+ CommandRegistry commands;+ ActionRegistry reg;+ std::string ran, prefilled;+ reg.registerCommands(commands, [&](const std::string& n) { ran = n; }, [&](const std::string& n) { prefilled = n; });+ const Action* sub = reg.find("cmd.subdivide");+ CHECK(sub && sub->command == "subdivide" && sub->description.find("Loop subdivision") != std::string::npos);+ sub->run();+ CHECK(ran == "subdivide");+ const Action* open = reg.find("cmd.open"); // path is required: goes to the console instead+ CHECK(open && open->label.find("...") != std::string::npos);+ open->run();+ CHECK(prefilled == "open" && ran == "subdivide");+}+#endifdiff --git a/tests/test_core.cpp b/tests/test_core.cppindex 5dfdd0ae..4231d765 100644--- a/tests/test_core.cpp+++ b/tests/test_core.cpp@@ -324,6 +324,23 @@ TEST(script_windows_paths) {CHECK(parseScript(quoted, st, err) && std::get<std::string>(st[0].args["prompt"]) == "say \"hi\"");}+TEST(script_format_round_trip) {+ // formatStatement is parseScript's inverse: the console echoes every command this way.+ CHECK(formatStatement("subdivide", {}) == "subdivide");+ CHECK(formatStatement("remesh", {{"resolution", 200.0}}) == "remesh resolution=200");+ CHECK(formatStatement("layer_add", {{"name", std::string("Big Smile")}}) == "layer_add name=\"Big Smile\"");+ const Args args = {{"name", std::string("Big \"Smile\" C:\\x")}, {"ratio", 0.1}, {"third", 1.0 / 3.0},+ {"flag", true}, {"off", false}, {"count", -42.0}, {"word", std::string("plain")},+ {"numeric_text", std::string("12")}, {"bool_text", std::string("true")},+ {"empty", std::string()}, {"semi", std::string("a;b#c")}, {"big", 1.5e20}};+ std::vector<ScriptStatement> st;+ std::string err;+ const std::string text = formatStatement("brush_create", args) + "; " + formatStatement("subdivide", {{"levels", 2.0}});+ CHECK(parseScript(text, st, err));+ CHECK(st.size() == 2 && st[0].command == "brush_create" && st[0].args == args);+ CHECK(st.size() == 2 && st[1].command == "subdivide" && std::get<double>(st[1].args["levels"]) == 2.0);+}+TEST(script_parser_and_pipeline) {std::vector<ScriptStatement> st;std::string err;diff --git a/tests/ui/help_console.sfui b/tests/ui/help_console.sfuinew file mode 100644index 00000000..3af6ec7e--- /dev/null+++ b/tests/ui/help_console.sfui@@ -0,0 +1,107 @@+# Ctrl-hover help, the command palette, the script console and Store Config / Restore UI+# (ui-spec sections 7, 8 and 9.2).+run new_sphere subdivisions=3+expect_value triangles == 1280++# F1: the Controls sheet is generated from the action registry. Ctrl+hover explains any item,+# Ctrl+Alt+hover shows a command's scripting parameters.+key f1+type Controls/##controls_filter subdiv+expect Controls/Subdivide+hold ctrl+hover Controls/Subdivide+expect_help "Loop subdivision"+expect_help Ctrl+D+shot help_ctrl_hover+hold ctrl+alt+hover Controls/Subdivide+expect_help "Number of subdivision levels"+shot help_ctrl_alt_hover+hold none+wait 0.2+expect_no_text "Loop subdivision"++# ZBrush-style shortcut assignment: double-click a row (or Ctrl+Alt+click a button), press the key.+type Controls/##controls_filter wire+double_click Controls/Wireframe+expect_status "Press a key for 'Wireframe'"+key ctrl+k+expect_status "Wireframe: Ctrl+K"+key ctrl+k+expect_value wireframe == 1+key ctrl+k+expect_value wireframe == 0+key f1+expect_not Controls/Subdivide++# Command palette (F3): fuzzy search, Enter runs.+key f3+expect_value command_palette_open == 1+type "##Command palette" subdiv+expect_text "Tool > Geometry"+shot command_palette+key enter+expect_value triangles == 5120+expect_value command_palette_open == 0+key ctrl+z+expect_value triangles == 1280++# Commands that need parameters open in the console with their name typed.+key f3+type "##Command palette" "layer set weight"+key enter+expect_value console_open == 1++# The console (backtick): every command is echoed as a script line; the input runs statements.+type Console/##console "remesh resolution=64"+key enter+expect_text "> remesh resolution=64"+expect_value triangles > 30000+type Console/##console subd+key tab+key enter+expect_text "> subdivide"+expect_value triangles > 120000+type Console/##console "help remesh"+key enter+expect_text "Voxels across the longest side"+type Console/##console "nonsense_command x=1"+key enter+expect_text "Unknown command 'nonsense_command'"+shot console+hold ctrl+hover "Console/Copy session as script"+expect_help "macro recorder"+hold none+click "Console/Copy session as script"+expect_clipboard "remesh resolution=64"+expect_clipboard "subdivide"++# Store Config (Ctrl+Shift+I) writes ui.json; Restore Standard UI resets; Restore Custom UI brings it back.+click "Console/Clear console"+expect_no_text "> remesh"+key ctrl+shift+i+expect_status "UI configuration stored"+expect_value ui_config == 1+key f3+type "##Command palette" "restore standard"+key enter+expect_status "Standard UI restored"+expect_value console_open == 0+key w+expect_value wireframe == 1+key w+key f3+type "##Command palette" "restore custom"+key enter+expect_status "Custom UI restored"+expect_value console_open == 1+key ctrl+k+expect_value wireframe == 1++# The console's close button; then the console key opens it again.+click "Console/###console_close"+expect_value console_open == 0+key backtick+expect_value console_open == 1+shot console_reopened