OpenToonz - An open-source full-featured 2D animation creation software
C
Preset management panel, custom panel removal, dynamics icons/shortcuts (#6627)
Ahl763a7e106cda46
diff --git a/toonz/sources/include/tools/tooloptions.h b/toonz/sources/include/tools/tooloptions.hindex cc948543d..d75c1314c 100644--- a/toonz/sources/include/tools/tooloptions.h+++ b/toonz/sources/include/tools/tooloptions.h@@ -564,6 +564,12 @@ private:class PresetNamePopup;PresetNamePopup *m_presetNamePopup;void filterControls();+ // Guard: skip redundant setVisible() calls — and the Qt layout recalculation+ // they trigger — when the modifier-visibility state has not changed.+ // Each BrushToolOptionsBox is cached per TTool* by ToolOptions, so switching+ // back to a previously-seen level type is a no-op after the first visit.+ bool m_lastShowModifiers = false;+ bool m_filterInitialized = false;public:BrushToolOptionsBox(QWidget *parent, TTool *tool, TPaletteHandle *pltHandle,diff --git a/toonz/sources/include/toonzqt/brushpresetbridge.h b/toonz/sources/include/toonzqt/brushpresetbridge.hnew file mode 100644index 000000000..6d385b3a1--- /dev/null+++ b/toonz/sources/include/toonzqt/brushpresetbridge.h@@ -0,0 +1,56 @@+#pragma once++#ifndef BRUSHPRESETBRIDGE_H+#define BRUSHPRESETBRIDGE_H++#include <QString>+#include <QStringList>+#include "tcommon.h"++#undef DVAPI+#undef DVVAR+#ifdef TOONZQT_EXPORTS+#define DVAPI DV_EXPORT_API+#define DVVAR DV_EXPORT_VAR+#else+#define DVAPI DV_IMPORT_API+#define DVVAR DV_IMPORT_VAR+#endif++class TColorStyle;+class TPalette;+class TPaletteHandle;+class TUndo;++// Bridge to pass preset name and mode flags from BrushPresetPanel (toonz)+// to command handlers in tnztools. Avoids LNK2019 cross-DLL symbol issues.++namespace BrushPresetBridge {+DVAPI void setPendingPresetName(const QString &name);+DVAPI QString takePendingPresetName();++// Queue of preset names to be removed (for batch deletion from page delete)+DVAPI void addPendingRemoveName(const QString &name);+DVAPI QStringList takePendingRemoveNames();++// Toggle states shared between BrushPresetPanel (toonz) and brush tools (tnztools)+DVAPI void setNonDestructiveMode(bool enabled);+DVAPI bool isNonDestructiveMode();+DVAPI void setSelectivePresetMode(bool enabled);+DVAPI bool isSelectivePresetMode();++// Style matching for Non-Destructive mode: compare style parameters+// ignoring metadata (name, globalName, flags, pickedPosition)+DVAPI bool stylesMatchVisually(const TColorStyle *a, const TColorStyle *b);+DVAPI int findMatchingStyleInPalette(TPalette *palette,+ const TColorStyle *targetStyle);++// Creates a TUndo that records a style overwrite (for Ctrl+Z support).+// oldStyle and newStyle are cloned internally; caller retains ownership.+DVAPI TUndo *createStyleOverwriteUndo(TPalette *palette, int styleId,+ const TColorStyle *oldStyle,+ const TColorStyle *newStyle,+ TPaletteHandle *paletteHandle);+}++#endif // BRUSHPRESETBRIDGE_Hdiff --git a/toonz/sources/include/toonzqt/menubarcommand.h b/toonz/sources/include/toonzqt/menubarcommand.hindex 9e8ab69f8..d424fae90 100644--- a/toonz/sources/include/toonzqt/menubarcommand.h+++ b/toonz/sources/include/toonzqt/menubarcommand.h@@ -56,6 +56,7 @@ enum CommandType {MenuViewCommandType,MenuWindowsCommandType,CustomPanelCommandType,+ RoomCommandType, // Room switching shortcutsMenuHelpCommandType,PlaybackCommandType,RGBACommandType,diff --git a/toonz/sources/tnztools/fullcolorbrushtool.cpp b/toonz/sources/tnztools/fullcolorbrushtool.cppindex 4b30af4af..b3a2f5888 100644--- a/toonz/sources/tnztools/fullcolorbrushtool.cpp+++ b/toonz/sources/tnztools/fullcolorbrushtool.cpp@@ -14,6 +14,10 @@// TnzQt includes#include "toonzqt/dvdialog.h"+#include "toonzqt/brushpresetbridge.h"+#include "toonzqt/tselectionhandle.h"+#include "toonzqt/styleselection.h"+#include "tundo.h"// TnzLib includes#include "toonz/tpalettehandle.h"@@ -27,6 +31,7 @@#include "toonz/tstageobject.h"#include "toonz/palettecontroller.h"#include "toonz/mypaintbrushstyle.h"+#include "toonz/imagestyles.h"#include "toonz/preferences.h"#include "toonz/toonzfolders.h"@@ -767,39 +772,122 @@ void FullColorBrushTool::loadPreset() {m_modifierLockAlpha.setValue(preset.m_modifierLockAlpha);m_assistants.setValue(preset.m_assistants);- // CRITICAL: Restore MyPaint style from preset (strict state restoration)- // Only applies to NEW presets (version >= 1) that have style information- if (preset.m_styleInfoVersion >= 1) {+ // Style snapshot restoration.+ // When Selective Preset mode is ON, this entire block is skipped: only the+ // tool parameters above are injected. The user's current style acts as a+ // "base" that receives dynamic brush settings from any chosen preset.+ if (preset.m_styleInfoVersion >= 1 &&+ !BrushPresetBridge::isSelectivePresetMode()) {if (TTool::Application *app = getApplication()) {- if (TPaletteHandle *paletteHandle = app->getCurrentPalette()) {- TPalette *palette = paletteHandle->getPalette();- if (palette) {- int styleIndex = app->getCurrentLevelStyleIndex();+ TPaletteHandle *paletteHandle =+ app->getPaletteController()->getCurrentLevelPalette();+ TPalette *palette = paletteHandle ? paletteHandle->getPalette() : nullptr;+ int styleIndex = app ? app->getCurrentLevelStyleIndex() : 0;+ // Style 0 is the transparent/eraser style and must never be+ // overwritten, matching the Level Palette protection rules.+ if (palette && styleIndex >= 1) {TColorStyle *currentStyle = palette->getStyle(styleIndex);+ TPixel32 currentColor = TPixel32::Black;+ if (currentStyle) {+ if (dynamic_cast<TTextureStyle *>(currentStyle) &&+ currentStyle->getColorParamCount() > 0)+ currentColor = currentStyle->getColorParamValue(0);+ else+ currentColor = currentStyle->getMainColor();+ }- if (preset.m_hasMyPaint) {- // Preset was created WITH MyPaint: load the specific MyPaint brush- TFilePath myPaintPath(preset.m_myPaintPath);- TMyPaintBrushStyle *newStyle = new TMyPaintBrushStyle(myPaintPath);- if (currentStyle) {- newStyle->setMainColor(currentStyle->getMainColor());- }- palette->setStyle(styleIndex, newStyle);- paletteHandle->notifyColorStyleChanged(false);- } else {- // Preset was created WITHOUT MyPaint: replace any existing MyPaint with solid color- if (dynamic_cast<TMyPaintBrushStyle*>(currentStyle)) {- TSolidColorStyle *newStyle = new TSolidColorStyle(- currentStyle ? currentStyle->getMainColor() : TPixel32::Black);+ auto commitStyle = [&](TColorStyle *newStyle) {+ if (BrushPresetBridge::isNonDestructiveMode()) {+ if (TSelection *sel =+ app->getCurrentSelection()->getSelection())+ if (TStyleSelection *ss =+ dynamic_cast<TStyleSelection *>(sel))+ ss->selectNone();++ int matchIdx =+ BrushPresetBridge::findMatchingStyleInPalette(palette, newStyle);+ if (matchIdx >= 0) {+ delete newStyle;+ app->setCurrentLevelStyleIndex(matchIdx, true);+ } else {+ int newId = palette->addStyle(newStyle);+ if (newId >= 0) {+ for (int p = 0; p < palette->getPageCount(); ++p) {+ TPalette::Page *pg = palette->getPage(p);+ if (!pg) continue;+ for (int s = 0; s < pg->getStyleCount(); ++s) {+ if (pg->getStyleId(s) == styleIndex) {+ pg->addStyle(newId);+ p = palette->getPageCount();+ break;+ }+ }+ }+ palette->setDirtyFlag(true);+ app->setCurrentLevelStyleIndex(newId, true);+ paletteHandle->notifyPaletteChanged();+ }+ }+ } else {+ TColorStyle *oldStyle = palette->getStyle(styleIndex);+ TUndo *undo = BrushPresetBridge::createStyleOverwriteUndo(+ palette, styleIndex, oldStyle, newStyle, paletteHandle);palette->setStyle(styleIndex, newStyle);paletteHandle->notifyColorStyleChanged(false);+ TUndoManager::manager()->add(undo);+ }+ };++ if (preset.m_hasStyleSnapshot && preset.m_styleInfoVersion >= 3) {+ TColorStyle *newStyle = nullptr;++ if (preset.m_snapshotStyleTagId == 4001) {+ TFilePath mpPath(preset.m_snapshotFilePath);+ newStyle = new TMyPaintBrushStyle(mpPath);+ } else {+ newStyle = TColorStyle::create(preset.m_snapshotBrushIdName);+ }++ if (newStyle) {+ for (const auto ¶m : preset.m_snapshotParams) {+ int idx = param.first;+ double val = param.second;+ if (idx >= newStyle->getParamCount()) continue;+ TColorStyle::ParamType ptype = newStyle->getParamType(idx);+ switch (ptype) {+ case TColorStyle::BOOL:+ newStyle->setParamValue(idx, (bool)(val != 0));+ break;+ case TColorStyle::INT:+ case TColorStyle::ENUM:+ newStyle->setParamValue(idx, (int)val);+ break;+ case TColorStyle::DOUBLE:+ newStyle->setParamValue(idx, val);+ break;+ default:+ break;+ }+ }+ newStyle->setMainColor(currentColor);+ commitStyle(newStyle);+ }+ } else if (preset.m_hasMyPaint) {+ TFilePath myPaintPath(preset.m_myPaintPath);+ TMyPaintBrushStyle *newStyle = new TMyPaintBrushStyle(myPaintPath);+ newStyle->setMainColor(currentColor);+ commitStyle(newStyle);+ } else if (!preset.m_hasMyPaint && !preset.m_hasTexture && !preset.m_hasStyleSnapshot) {+ if (BrushPresetBridge::isNonDestructiveMode() ||+ dynamic_cast<TMyPaintBrushStyle*>(currentStyle) ||+ dynamic_cast<TTextureStyle*>(currentStyle)) {+ TSolidColorStyle *newStyle = new TSolidColorStyle(currentColor);+ commitStyle(newStyle);}}}}- }}- // OLD presets (version 0): do nothing - leave the current style unchanged} catch (...) {}}@@ -822,18 +910,53 @@ void FullColorBrushTool::addPreset(QString name) {preset.m_modifierLockAlpha = m_modifierLockAlpha.getValue();preset.m_assistants = m_assistants.getValue();- // Capture MyPaint style information (CRITICAL for strict preset restoration)- preset.m_styleInfoVersion = 1; // Mark as new preset with style information+ // Capture complete style snapshot using the GENERIC approach.+ // This captures ALL parameters (including MyPaint's 56 params) generically.+ preset.m_styleInfoVersion = 3;+ preset.m_hasMyPaint = false;+ preset.m_hasTexture = false;+ preset.m_hasStyleSnapshot = false;if (TTool::Application *app = getApplication()) {TColorStyle *style = app->getCurrentLevelStyle();- if (TMyPaintBrushStyle *mpStyle = dynamic_cast<TMyPaintBrushStyle*>(style)) {- preset.m_hasMyPaint = true;- std::wstring wpath = mpStyle->getPath().getWideString();- preset.m_myPaintPath = std::string(wpath.begin(), wpath.end());- } else {- preset.m_hasMyPaint = false;- preset.m_myPaintPath = "";++ if (style && !dynamic_cast<TSolidColorStyle*>(style)) {+ preset.m_hasStyleSnapshot = true;+ preset.m_snapshotStyleTagId = style->getTagId();+ preset.m_snapshotBrushIdName = style->getBrushIdName();++ // Extract primary file path+ if (TMyPaintBrushStyle *mpStyle = dynamic_cast<TMyPaintBrushStyle*>(style)) {+ std::wstring wpath = mpStyle->getPath().getWideString();+ preset.m_snapshotFilePath = std::string(wpath.begin(), wpath.end());+ // Legacy compatibility+ preset.m_hasMyPaint = true;+ preset.m_myPaintPath = preset.m_snapshotFilePath;+ }++ // GENERIC: Capture ALL numeric parameters of the style+ int paramCount = style->getParamCount();+ for (int i = 0; i < paramCount; ++i) {+ TColorStyle::ParamType ptype = style->getParamType(i);+ double numValue = 0.0;+ switch (ptype) {+ case TColorStyle::BOOL:+ numValue = style->getParamValue(TColorStyle::bool_tag(), i) ? 1.0 : 0.0;+ break;+ case TColorStyle::INT:+ case TColorStyle::ENUM:+ numValue = (double)style->getParamValue(TColorStyle::int_tag(), i);+ break;+ case TColorStyle::DOUBLE:+ numValue = style->getParamValue(TColorStyle::double_tag(), i);+ break;+ case TColorStyle::FILEPATH:+ continue; // Handled via m_snapshotFilePath+ default:+ continue;+ }+ preset.m_snapshotParams.push_back({i, numValue});+ }}}diff --git a/toonz/sources/tnztools/tooloptions.cpp b/toonz/sources/tnztools/tooloptions.cppindex 009d20c96..88d43226e 100644--- a/toonz/sources/tnztools/tooloptions.cpp+++ b/toonz/sources/tnztools/tooloptions.cpp@@ -27,6 +27,10 @@#include "toonzqt/dvscrollwidget.h"#include "toonzqt/lutcalibrator.h"#include "toonzqt/viewcommandids.h"+#include "toonzqt/brushpresetbridge.h"++// Tnz includes (for command ids)+#include "../toonz/menubarcommandids.h"// TnzLib includes#include "toonz/tobjecthandle.h"@@ -1925,6 +1929,13 @@ BrushToolOptionsBox::BrushToolOptionsBox(QWidget *parent, TTool *tool,m_pencilMode = dynamic_cast<ToolOptionCheckbox *>(m_controls.value("Pencil"));m_presetCombo = dynamic_cast<ToolOptionCombo *>(m_controls.value("Preset:"));+ // Connect the Preset combo to refresh when the preset list changes+ // (bi-directional sync: BrushPresetPanel add/remove <-> ToolOptionBar dropdown)+ if (m_presetCombo && toolHandle) {+ connect(toolHandle, SIGNAL(toolComboBoxListChanged(std::string)),+ m_presetCombo, SLOT(reloadComboBoxList(std::string)));+ }+// Preset +/- buttonsm_addPresetButton = new QPushButton(QString("+"));m_removePresetButton = new QPushButton(QString("-"));@@ -1991,6 +2002,14 @@ void BrushToolOptionsBox::filterControls() {return;}+ // Skip all setVisible() calls — and the Qt layout recalculation they+ // trigger — when the modifier-visibility state has not actually changed.+ // Each BrushToolOptionsBox instance is cached per TTool* by ToolOptions,+ // so repeated switches back to the same level+tool type are free.+ if (m_filterInitialized && showModifiers == m_lastShowModifiers) return;+ m_filterInitialized = true;+ m_lastShowModifiers = showModifiers;+for (QMap<std::string, QLabel *>::iterator it = m_labels.begin();it != m_labels.end(); it++) {bool isModifier = (it.key().substr(0, 8) == "Modifier");@@ -2068,6 +2087,12 @@ void BrushToolOptionsBox::onAddPreset() {}m_presetCombo->loadEntries();++ // Notify BrushPresetPanel that the preset list has changed+ // so it can assign the new preset to the currently visible page.+ TTool::Application *app = TTool::getApplication();+ if (app && app->getCurrentTool())+ app->getCurrentTool()->notifyToolComboBoxListChanged("Preset:");}//-----------------------------------------------------------------------------@@ -2090,6 +2115,12 @@ void BrushToolOptionsBox::onRemovePreset() {}m_presetCombo->loadEntries();++ // Notify BrushPresetPanel that the preset list has changed+ // so it can immediately refresh its view (removes deleted preset).+ TTool::Application *app = TTool::getApplication();+ if (app && app->getCurrentTool())+ app->getCurrentTool()->notifyToolComboBoxListChanged("Preset:");}//=============================================================================@@ -3151,3 +3182,144 @@ public:}}} rotateRightCHInstance("A_ToolOption_RotateRight");++//***********************************************************************************+// Brush Preset Panel commands (called from BrushPresetPanel to avoid LNK2019)+//***********************************************************************************++class AddBrushPresetCommandHandler final : public MenuItemHandler {+public:+ AddBrushPresetCommandHandler() : MenuItemHandler(MI_AddBrushPreset) {}+ void execute() override {+ QString name = BrushPresetBridge::takePendingPresetName();+ if (name.isEmpty()) return;+ TTool::Application *app = TTool::getApplication();+ if (!app) return;+ TTool *tool = app->getCurrentTool()->getTool();+ if (!tool || tool->getName() != T_Brush) return;+ switch (tool->getTargetType() & TTool::CommonImages) {+ case TTool::VectorImage: {+ ToonzVectorBrushTool *vt = dynamic_cast<ToonzVectorBrushTool *>(tool);+ if (vt) vt->addPreset(name);+ break;+ }+ case TTool::ToonzImage: {+ ToonzRasterBrushTool *rt = dynamic_cast<ToonzRasterBrushTool *>(tool);+ if (rt) rt->addPreset(name);+ break;+ }+ case TTool::RasterImage: {+ FullColorBrushTool *ft = dynamic_cast<FullColorBrushTool *>(tool);+ if (ft) ft->addPreset(name);+ break;+ }+ default:+ break;+ }+ // Notify panels that preset list changed (for BrushPresetPanel sync)+ if (app->getCurrentTool())+ app->getCurrentTool()->notifyToolComboBoxListChanged("Preset:");+ }+} addBrushPresetCHInstance;++class RemoveBrushPresetCommandHandler final : public MenuItemHandler {+public:+ RemoveBrushPresetCommandHandler() : MenuItemHandler(MI_RemoveBrushPreset) {}+ void execute() override {+ TTool::Application *app = TTool::getApplication();+ if (!app) return;+ TTool *tool = app->getCurrentTool()->getTool();+ if (!tool || tool->getName() != T_Brush) return;+ switch (tool->getTargetType() & TTool::CommonImages) {+ case TTool::VectorImage: {+ ToonzVectorBrushTool *vt = dynamic_cast<ToonzVectorBrushTool *>(tool);+ if (vt) vt->removePreset();+ break;+ }+ case TTool::ToonzImage: {+ ToonzRasterBrushTool *rt = dynamic_cast<ToonzRasterBrushTool *>(tool);+ if (rt) rt->removePreset();+ break;+ }+ case TTool::RasterImage: {+ FullColorBrushTool *ft = dynamic_cast<FullColorBrushTool *>(tool);+ if (ft) ft->removePreset();+ break;+ }+ default:+ break;+ }+ // Notify panels that preset list changed (for BrushPresetPanel sync)+ if (app->getCurrentTool())+ app->getCurrentTool()->notifyToolComboBoxListChanged("Preset:");+ }+} removeBrushPresetCHInstance;++// Batch remove presets by name (used by BrushPresetPanel page deletion).+// Uses public removePreset() after setting the internal preset property+// via the TProperty::setValue interface.+class RemoveBrushPresetByNameCommandHandler final : public MenuItemHandler {+public:+ RemoveBrushPresetByNameCommandHandler()+ : MenuItemHandler(MI_RemoveBrushPresetByName) {}+ void execute() override {+ QStringList names = BrushPresetBridge::takePendingRemoveNames();+ if (names.isEmpty()) return;+ TTool::Application *app = TTool::getApplication();+ if (!app) return;+ TTool *tool = app->getCurrentTool()->getTool();+ if (!tool || tool->getName() != T_Brush) return;++ // Find the Preset property to set the value before calling removePreset+ TPropertyGroup *props = tool->getProperties(0);+ TEnumProperty *presetProp = nullptr;+ if (props) {+ for (int i = 0; i < props->getPropertyCount(); ++i) {+ TProperty *prop = props->getProperty(i);+ if (prop->getName() == "Preset:") {+ presetProp = dynamic_cast<TEnumProperty *>(prop);+ break;+ }+ }+ }+ if (!presetProp) return;++ switch (tool->getTargetType() & TTool::CommonImages) {+ case TTool::VectorImage: {+ ToonzVectorBrushTool *vt = dynamic_cast<ToonzVectorBrushTool *>(tool);+ if (vt) {+ for (const QString &name : names) {+ presetProp->setValue(name.toStdWString());+ vt->removePreset();+ }+ }+ break;+ }+ case TTool::ToonzImage: {+ ToonzRasterBrushTool *rt = dynamic_cast<ToonzRasterBrushTool *>(tool);+ if (rt) {+ for (const QString &name : names) {+ presetProp->setValue(name.toStdWString());+ rt->removePreset();+ }+ }+ break;+ }+ case TTool::RasterImage: {+ FullColorBrushTool *ft = dynamic_cast<FullColorBrushTool *>(tool);+ if (ft) {+ for (const QString &name : names) {+ presetProp->setValue(name.toStdWString());+ ft->removePreset();+ }+ }+ break;+ }+ default:+ break;+ }+ // Notify panels that preset list changed (sync ToolOptionBar dropdown)+ if (app->getCurrentTool())+ app->getCurrentTool()->notifyToolComboBoxListChanged("Preset:");+ }+} removeBrushPresetByNameCHInstance;diff --git a/toonz/sources/tnztools/toonzrasterbrushtool.cpp b/toonz/sources/tnztools/toonzrasterbrushtool.cppindex 3a5ef9e04..2e76f380c 100644--- a/toonz/sources/tnztools/toonzrasterbrushtool.cpp+++ b/toonz/sources/tnztools/toonzrasterbrushtool.cpp@@ -15,6 +15,10 @@// TnzQt includes#include "toonzqt/dvdialog.h"#include "toonzqt/imageutils.h"+#include "toonzqt/brushpresetbridge.h"+#include "toonzqt/tselectionhandle.h"+#include "toonzqt/styleselection.h"+#include "tundo.h"// TnzLib includes#include "toonz/tobjecthandle.h"@@ -33,11 +37,13 @@#include "toonz/preferences.h"#include "toonz/tpalettehandle.h"#include "toonz/mypaintbrushstyle.h"+#include "toonz/imagestyles.h"#include "toonz/toonzfolders.h"// TnzCore includes#include "tstream.h"#include "tcolorstyles.h"+#include "timage_io.h"#include "tvectorimage.h"#include "tenv.h"#include "tregion.h"@@ -1770,38 +1776,165 @@ void ToonzRasterBrushTool::loadPreset() {m_brushPad = ToolUtils::getBrushPad(preset.m_max, preset.m_hardness * 0.01);- // CRITICAL: Restore MyPaint style from preset (strict state restoration)- // Only applies to NEW presets (version >= 1) that have style information- if (preset.m_styleInfoVersion >= 1) {+ // Style snapshot restoration.+ // When Selective Preset mode is ON, this entire block is skipped: only the+ // tool parameters above (size, hardness, pressure, etc.) are injected from+ // the preset. The user's current style in the palette remains untouched,+ // effectively acting as a "base" that receives dynamic brush settings from+ // any chosen preset. This is by design.+ if (preset.m_styleInfoVersion >= 1 &&+ !BrushPresetBridge::isSelectivePresetMode()) {TApplication *app = getApplication();if (app && app->getCurrentPalette()) {TPalette *palette = app->getCurrentPalette()->getPalette();- if (palette) {- int styleIndex = app->getCurrentLevelStyleIndex();+ int styleIndex = app->getCurrentLevelStyleIndex();+ // Style 0 is the transparent/eraser style and must never be+ // overwritten, matching the Level Palette protection rules.+ if (palette && styleIndex >= 1) {TColorStyle *currentStyle = palette->getStyle(styleIndex);+ TPixel32 currentColor = TPixel32::Black;+ if (currentStyle) {+ // TTextureStyle::getMainColor() returns the texture's average pixel+ // color, not the user-set color. Use getColorParamValue(0) which+ // maps to m_patternColor — the actual user-controlled color.+ if (dynamic_cast<TTextureStyle *>(currentStyle) &&+ currentStyle->getColorParamCount() > 0)+ currentColor = currentStyle->getColorParamValue(0);+ else+ currentColor = currentStyle->getMainColor();+ }- if (preset.m_hasMyPaint) {- // Preset was created WITH MyPaint: load the specific MyPaint brush- TFilePath myPaintPath(preset.m_myPaintPath);- TMyPaintBrushStyle *newStyle = new TMyPaintBrushStyle(myPaintPath);- if (currentStyle) {- newStyle->setMainColor(currentStyle->getMainColor());- }- palette->setStyle(styleIndex, newStyle);- app->getCurrentPalette()->notifyColorStyleChanged(false);- } else {- // Preset was created WITHOUT MyPaint: replace any existing MyPaint with solid color- if (dynamic_cast<TMyPaintBrushStyle*>(currentStyle)) {- TSolidColorStyle *newStyle = new TSolidColorStyle(- currentStyle ? currentStyle->getMainColor() : TPixel32::Black);+ // Non-Destructive helper: protect existing strokes by creating/reusing+ // a separate palette index instead of overwriting the current one.+ auto commitStyle = [&](TColorStyle *newStyle) {+ if (BrushPresetBridge::isNonDestructiveMode()) {+ if (TSelection *sel =+ app->getCurrentSelection()->getSelection())+ if (TStyleSelection *ss =+ dynamic_cast<TStyleSelection *>(sel))+ ss->selectNone();++ int matchIdx =+ BrushPresetBridge::findMatchingStyleInPalette(palette, newStyle);+ if (matchIdx >= 0) {+ delete newStyle;+ app->setCurrentLevelStyleIndex(matchIdx, true);+ } else {+ int newId = palette->addStyle(newStyle);+ if (newId >= 0) {+ for (int p = 0; p < palette->getPageCount(); ++p) {+ TPalette::Page *pg = palette->getPage(p);+ if (!pg) continue;+ for (int s = 0; s < pg->getStyleCount(); ++s) {+ if (pg->getStyleId(s) == styleIndex) {+ pg->addStyle(newId);+ p = palette->getPageCount();+ break;+ }+ }+ }+ palette->setDirtyFlag(true);+ app->setCurrentLevelStyleIndex(newId, true);+ app->getPaletteController()+ ->getCurrentLevelPalette()+ ->notifyPaletteChanged();+ }+ }+ } else {+ TColorStyle *oldStyle = palette->getStyle(styleIndex);+ TUndo *undo = BrushPresetBridge::createStyleOverwriteUndo(+ palette, styleIndex, oldStyle, newStyle,+ app->getPaletteController()->getCurrentLevelPalette());palette->setStyle(styleIndex, newStyle);app->getCurrentPalette()->notifyColorStyleChanged(false);+ TUndoManager::manager()->add(undo);+ }+ };++ if (preset.m_hasStyleSnapshot && preset.m_styleInfoVersion >= 3) {+ TColorStyle *newStyle = nullptr;++ if (preset.m_snapshotStyleTagId == 4001) {+ TFilePath mpPath(preset.m_snapshotFilePath);+ newStyle = new TMyPaintBrushStyle(mpPath);+ } else if (preset.m_snapshotStyleTagId == 2001) {+ TFilePath texRelPath(preset.m_snapshotFilePath);+ TFilePath fullTexPath = TEnv::getStuffDir() + "library" + "textures" + texRelPath;+ TRaster32P textureRas;+ try {+ TImageReaderP reader = TImageReaderP(fullTexPath);+ if (reader) {+ TImageP img = reader->load();+ if (TRasterImageP ri = img) textureRas = ri->getRaster();+ }+ } catch (...) {}+ if (!textureRas) textureRas = TRaster32P(1, 1);+ newStyle = new TTextureStyle(textureRas, texRelPath);+ } else {+ newStyle = TColorStyle::create(preset.m_snapshotBrushIdName);+ }++ if (newStyle) {+ for (const auto ¶m : preset.m_snapshotParams) {+ int idx = param.first;+ double val = param.second;+ if (idx >= newStyle->getParamCount()) continue;+ TColorStyle::ParamType ptype = newStyle->getParamType(idx);+ switch (ptype) {+ case TColorStyle::BOOL:+ newStyle->setParamValue(idx, (bool)(val != 0));+ break;+ case TColorStyle::INT:+ case TColorStyle::ENUM:+ newStyle->setParamValue(idx, (int)val);+ break;+ case TColorStyle::DOUBLE:+ newStyle->setParamValue(idx, val);+ break;+ default:+ break;+ }+ }+ newStyle->setMainColor(currentColor);+ commitStyle(newStyle);+ }+ } else if (preset.m_hasMyPaint) {+ TFilePath myPaintPath(preset.m_myPaintPath);+ TMyPaintBrushStyle *newStyle = new TMyPaintBrushStyle(myPaintPath);+ newStyle->setMainColor(currentColor);+ commitStyle(newStyle);+ } else if (preset.m_hasTexture && preset.m_styleInfoVersion >= 2) {+ TFilePath texRelPath(preset.m_texturePath);+ TFilePath fullTexPath = TEnv::getStuffDir() + "library" + "textures" + texRelPath;+ TRaster32P textureRas;+ try {+ TImageReaderP reader = TImageReaderP(fullTexPath);+ if (reader) {+ TImageP img = reader->load();+ if (TRasterImageP ri = img) textureRas = ri->getRaster();+ }+ } catch (...) {}+ if (!textureRas) textureRas = TRaster32P(1, 1);+ TTextureStyle *newStyle = new TTextureStyle(textureRas, texRelPath);+ newStyle->setParamValue(2, preset.m_textureScale);+ newStyle->setParamValue(3, preset.m_textureRotation);+ newStyle->setParamValue(4, preset.m_textureDispX);+ newStyle->setParamValue(5, preset.m_textureDispY);+ newStyle->setParamValue(6, preset.m_textureContrast);+ newStyle->setParamValue(1, preset.m_textureType);+ newStyle->setParamValue(0, preset.m_textureIsPattern);+ newStyle->setMainColor(currentColor);+ commitStyle(newStyle);+ } else if (!preset.m_hasMyPaint && !preset.m_hasTexture && !preset.m_hasStyleSnapshot) {+ if (dynamic_cast<TMyPaintBrushStyle*>(currentStyle) ||+ dynamic_cast<TTextureStyle*>(currentStyle)) {+ TSolidColorStyle *newStyle = new TSolidColorStyle(currentColor);+ commitStyle(newStyle);}}}}}- // OLD presets (version 0): do nothing - leave the current style unchanged} catch (...) {}}@@ -1824,19 +1957,69 @@ void ToonzRasterBrushTool::addPreset(QString name) {preset.m_modifierLockAlpha = m_modifierLockAlpha.getValue();preset.m_assistants = m_assistants.getValue();- // Capture MyPaint style information (CRITICAL for strict preset restoration)- preset.m_styleInfoVersion = 1; // Mark as new preset with style information+ // Capture complete style snapshot using the GENERIC approach.+ // This captures ALL parameters of ANY TColorStyle (MyPaint, Texture, etc.)+ // without hardcoding individual parameters.+ preset.m_styleInfoVersion = 3;+ preset.m_hasMyPaint = false;+ preset.m_hasTexture = false;+ preset.m_hasStyleSnapshot = false;TApplication *app = getApplication();if (app) {TColorStyle *style = app->getCurrentLevelStyle();- if (TMyPaintBrushStyle *mpStyle = dynamic_cast<TMyPaintBrushStyle*>(style)) {- preset.m_hasMyPaint = true;- std::wstring wpath = mpStyle->getPath().getWideString();- preset.m_myPaintPath = std::string(wpath.begin(), wpath.end());- } else {- preset.m_hasMyPaint = false;- preset.m_myPaintPath = "";++ if (style && !dynamic_cast<TSolidColorStyle*>(style)) {+ preset.m_hasStyleSnapshot = true;+ preset.m_snapshotStyleTagId = style->getTagId();+ preset.m_snapshotBrushIdName = style->getBrushIdName();++ // Extract primary file path based on style type+ if (TMyPaintBrushStyle *mpStyle = dynamic_cast<TMyPaintBrushStyle*>(style)) {+ std::wstring wpath = mpStyle->getPath().getWideString();+ preset.m_snapshotFilePath = std::string(wpath.begin(), wpath.end());+ // Legacy compatibility+ preset.m_hasMyPaint = true;+ preset.m_myPaintPath = preset.m_snapshotFilePath;+ } else if (TTextureStyle *texStyle = dynamic_cast<TTextureStyle*>(style)) {+ TFilePath texPath = texStyle->getParamValue(TColorStyle::TFilePath_tag(), 0);+ std::wstring wpath = texPath.getWideString();+ preset.m_snapshotFilePath = std::string(wpath.begin(), wpath.end());+ // Legacy compatibility+ preset.m_hasTexture = true;+ preset.m_texturePath = preset.m_snapshotFilePath;+ preset.m_textureScale = texStyle->getParamValue(TColorStyle::double_tag(), 2);+ preset.m_textureRotation = texStyle->getParamValue(TColorStyle::double_tag(), 3);+ preset.m_textureDispX = texStyle->getParamValue(TColorStyle::double_tag(), 4);+ preset.m_textureDispY = texStyle->getParamValue(TColorStyle::double_tag(), 5);+ preset.m_textureContrast = texStyle->getParamValue(TColorStyle::double_tag(), 6);+ preset.m_textureType = texStyle->getParamValue(TColorStyle::int_tag(), 1);+ preset.m_textureIsPattern = texStyle->getParamValue(TColorStyle::bool_tag(), 0);+ }++ // GENERIC: Capture ALL numeric parameters of the style+ int paramCount = style->getParamCount();+ for (int i = 0; i < paramCount; ++i) {+ TColorStyle::ParamType ptype = style->getParamType(i);+ double numValue = 0.0;+ switch (ptype) {+ case TColorStyle::BOOL:+ numValue = style->getParamValue(TColorStyle::bool_tag(), i) ? 1.0 : 0.0;+ break;+ case TColorStyle::INT:+ case TColorStyle::ENUM:+ numValue = (double)style->getParamValue(TColorStyle::int_tag(), i);+ break;+ case TColorStyle::DOUBLE:+ numValue = style->getParamValue(TColorStyle::double_tag(), i);+ break;+ case TColorStyle::FILEPATH:+ continue; // Skip filepath params (handled via m_snapshotFilePath)+ default:+ continue;+ }+ preset.m_snapshotParams.push_back({i, numValue});+ }}}@@ -1980,7 +2163,23 @@ BrushData::BrushData(), m_modifierOpacity(0.0), m_modifierEraser(0.0), m_modifierLockAlpha(0.0)- , m_assistants(false) {}+ , m_assistants(false)+ , m_styleInfoVersion(0)+ , m_hasMyPaint(false)+ , m_myPaintPath("")+ , m_hasTexture(false)+ , m_texturePath("")+ , m_textureScale(1.0)+ , m_textureRotation(0.0)+ , m_textureDispX(0.0)+ , m_textureDispY(0.0)+ , m_textureContrast(1.0)+ , m_textureType(1)+ , m_textureIsPattern(false)+ , m_hasStyleSnapshot(false)+ , m_snapshotStyleTagId(0)+ , m_snapshotBrushIdName("")+ , m_snapshotFilePath("") {}//----------------------------------------------------------------------------------------------------------@@ -2000,9 +2199,22 @@ BrushData::BrushData(const std::wstring &name), m_modifierEraser(0.0), m_modifierLockAlpha(0.0), m_assistants(false)+ , m_styleInfoVersion(0), m_hasMyPaint(false), m_myPaintPath("")- , m_styleInfoVersion(0) {}+ , m_hasTexture(false)+ , m_texturePath("")+ , m_textureScale(1.0)+ , m_textureRotation(0.0)+ , m_textureDispX(0.0)+ , m_textureDispY(0.0)+ , m_textureContrast(1.0)+ , m_textureType(1)+ , m_textureIsPattern(false)+ , m_hasStyleSnapshot(false)+ , m_snapshotStyleTagId(0)+ , m_snapshotBrushIdName("")+ , m_snapshotFilePath("") {}//----------------------------------------------------------------------------------------------------------@@ -2047,8 +2259,9 @@ void BrushData::saveData(TOStream &os) {os << (int)m_assistants;os.closeChild();os.openChild("StyleInfoVersion");- os << 1; // Version 1 = has style information+ os << 3; // Version 3 = generic style snapshot (all style types)os.closeChild();+ // Legacy fields (kept for backward compatibility with older OpenToonz versions)os.openChild("HasMyPaint");os << (int)m_hasMyPaint;os.closeChild();@@ -2057,6 +2270,59 @@ void BrushData::saveData(TOStream &os) {os << m_myPaintPath;os.closeChild();}+ os.openChild("HasTexture");+ os << (int)m_hasTexture;+ os.closeChild();+ if (m_hasTexture) {+ os.openChild("TexturePath");+ os << m_texturePath;+ os.closeChild();+ os.openChild("TextureScale");+ os << m_textureScale;+ os.closeChild();+ os.openChild("TextureRotation");+ os << m_textureRotation;+ os.closeChild();+ os.openChild("TextureDispX");+ os << m_textureDispX;+ os.closeChild();+ os.openChild("TextureDispY");+ os << m_textureDispY;+ os.closeChild();+ os.openChild("TextureContrast");+ os << m_textureContrast;+ os.closeChild();+ os.openChild("TextureType");+ os << m_textureType;+ os.closeChild();+ os.openChild("TextureIsPattern");+ os << (int)m_textureIsPattern;+ os.closeChild();+ }+ // Generic style snapshot (version >= 3)+ // Captures ALL parameters of any TColorStyle in a type-agnostic way.+ os.openChild("StyleSnapshot");+ os << (int)m_hasStyleSnapshot;+ os.closeChild();+ if (m_hasStyleSnapshot) {+ os.openChild("SnapshotTagId");+ os << m_snapshotStyleTagId;+ os.closeChild();+ os.openChild("SnapshotBrushId");+ os << m_snapshotBrushIdName;+ os.closeChild();+ os.openChild("SnapshotFile");+ os << m_snapshotFilePath;+ os.closeChild();+ os.openChild("SnapshotParamCount");+ os << (int)m_snapshotParams.size();+ os.closeChild();+ for (const auto ¶m : m_snapshotParams) {+ os.openChild("SNP");+ os << param.first << param.second;+ os.closeChild();+ }+ }}//----------------------------------------------------------------------------------------------------------@@ -2100,12 +2366,46 @@ void BrushData::loadData(TIStream &is) {is >> val, m_hasMyPaint = val, is.matchEndTag();else if (tagName == "MyPaintPath")is >> m_myPaintPath, is.matchEndTag();+ // Texture style snapshot (version >= 2)+ else if (tagName == "HasTexture")+ is >> val, m_hasTexture = val, is.matchEndTag();+ else if (tagName == "TexturePath")+ is >> m_texturePath, is.matchEndTag();+ else if (tagName == "TextureScale")+ is >> m_textureScale, is.matchEndTag();+ else if (tagName == "TextureRotation")+ is >> m_textureRotation, is.matchEndTag();+ else if (tagName == "TextureDispX")+ is >> m_textureDispX, is.matchEndTag();+ else if (tagName == "TextureDispY")+ is >> m_textureDispY, is.matchEndTag();+ else if (tagName == "TextureContrast")+ is >> m_textureContrast, is.matchEndTag();+ else if (tagName == "TextureType")+ is >> m_textureType, is.matchEndTag();+ else if (tagName == "TextureIsPattern")+ is >> val, m_textureIsPattern = val, is.matchEndTag();+ // Generic style snapshot (version >= 3)+ else if (tagName == "StyleSnapshot")+ is >> val, m_hasStyleSnapshot = val, is.matchEndTag();+ else if (tagName == "SnapshotTagId")+ is >> m_snapshotStyleTagId, is.matchEndTag();+ else if (tagName == "SnapshotBrushId")+ is >> m_snapshotBrushIdName, is.matchEndTag();+ else if (tagName == "SnapshotFile")+ is >> m_snapshotFilePath, is.matchEndTag();+ else if (tagName == "SnapshotParamCount")+ is >> val, is.matchEndTag(); // Count is informational; actual params follow+ else if (tagName == "SNP") {+ int idx;+ double dval;+ is >> idx >> dval;+ m_snapshotParams.push_back({idx, dval});+ is.matchEndTag();+ }elseis.skipCurrentTag();}-- // If StyleInfoVersion is missing, this is an old preset (version 0)- // Old presets don't have style information, so we leave m_styleInfoVersion at 0}//----------------------------------------------------------------------------------------------------------diff --git a/toonz/sources/tnztools/toonzrasterbrushtool.h b/toonz/sources/tnztools/toonzrasterbrushtool.hindex d928b7329..0f4efb0b0 100644--- a/toonz/sources/tnztools/toonzrasterbrushtool.h+++ b/toonz/sources/tnztools/toonzrasterbrushtool.h@@ -30,6 +30,8 @@#include <QCoreApplication>#include <QRadialGradient>#include <QElapsedTimer>+#include <vector>+#include <utility>//--------------------------------------------------------------@@ -61,10 +63,32 @@ struct BrushData final : public TPersist {bool m_modifierEraser, m_modifierLockAlpha;bool m_assistants;- // MyPaint style information (for strict preset restoration)+ // Style snapshot information (for strict preset restoration)+ int m_styleInfoVersion; // 0 = old, 1 = MyPaint only, 2 = full snapshot++ // MyPaint style info (version >= 1)bool m_hasMyPaint; // true if preset was created with MyPaint stylestd::string m_myPaintPath; // path to MyPaint brush if applicable- int m_styleInfoVersion; // 0 = old preset (no style info), 1 = new preset (has style info)++ // Texture style info (version >= 2, kept for backward compatibility)+ bool m_hasTexture; // true if preset was created with Texture style+ std::string m_texturePath; // path to the texture image+ double m_textureScale; // texture scale+ double m_textureRotation; // texture rotation+ double m_textureDispX; // texture displacement X+ double m_textureDispY; // texture displacement Y+ double m_textureContrast; // texture contrast+ int m_textureType; // 0=FIXED, 1=AUTOMATIC, 2=RANDOM+ bool m_textureIsPattern; // is pattern mode++ // Generic style snapshot (version >= 3)+ // Replaces individual texture/mypaint fields for new presets.+ // Captures ALL parameters of ANY TColorStyle generically.+ bool m_hasStyleSnapshot; // true if generic snapshot present+ int m_snapshotStyleTagId; // TColorStyle::getTagId() for recreation+ std::string m_snapshotBrushIdName; // TColorStyle::getBrushIdName()+ std::string m_snapshotFilePath; // Primary file (MyPaint brush, texture image)+ std::vector<std::pair<int, double>> m_snapshotParams; // (paramIndex, numericValue)BrushData();BrushData(const std::wstring &name);diff --git a/toonz/sources/tnztools/toonzvectorbrushtool.cpp b/toonz/sources/tnztools/toonzvectorbrushtool.cppindex a7c4e838e..30b27455d 100644--- a/toonz/sources/tnztools/toonzvectorbrushtool.cpp+++ b/toonz/sources/tnztools/toonzvectorbrushtool.cpp@@ -12,6 +12,10 @@// TnzQt includes#include "toonzqt/dvdialog.h"#include "toonzqt/imageutils.h"+#include "toonzqt/brushpresetbridge.h"+#include "toonzqt/tselectionhandle.h"+#include "toonzqt/styleselection.h"+#include "tundo.h"// TnzLib includes#include "toonz/tobjecthandle.h"@@ -33,10 +37,15 @@#include "toonz/tscenehandle.h"#include "toonz/toonzscene.h"#include "toonz/tcamera.h"+#include "toonz/tpalettehandle.h"+#include "toonz/imagestyles.h"// TnzCore includes#include "tstream.h"#include "tcolorstyles.h"+#include "timage_io.h"+#include "tvectorbrushstyle.h"+#include "tsimplecolorstyles.h"#include "tvectorimage.h"#include "tenv.h"#include "tregion.h"@@ -1765,6 +1774,172 @@ void ToonzVectorBrushTool::loadPreset() {// Recalculate based on updated presetsm_minThick = m_thickness.getValue().first;m_maxThick = m_thickness.getValue().second;++ // Style snapshot restoration.+ // When Selective Preset mode is ON, this entire block is skipped: only the+ // tool parameters above are injected. The user's current style acts as a+ // "base" that receives dynamic brush settings from any chosen preset.+ if (preset.m_styleInfoVersion >= 1 &&+ !BrushPresetBridge::isSelectivePresetMode()) {+ TApplication *app = getApplication();+ if (app && app->getCurrentPalette()) {+ TPalette *palette = app->getCurrentPalette()->getPalette();+ int styleIndex = app->getCurrentLevelStyleIndex();+ // Style 0 is the transparent/eraser style and must never be+ // overwritten, matching the Level Palette protection rules.+ if (palette && styleIndex >= 1) {+ TColorStyle *currentStyle = palette->getStyle(styleIndex);+ TPixel32 currentColor = TPixel32::Black;+ if (currentStyle) {+ if (dynamic_cast<TTextureStyle *>(currentStyle) &&+ currentStyle->getColorParamCount() > 0)+ currentColor = currentStyle->getColorParamValue(0);+ else+ currentColor = currentStyle->getMainColor();+ }++ auto commitStyle = [&](TColorStyle *newStyle) {+ if (BrushPresetBridge::isNonDestructiveMode()) {+ if (TSelection *sel =+ app->getCurrentSelection()->getSelection())+ if (TStyleSelection *ss =+ dynamic_cast<TStyleSelection *>(sel))+ ss->selectNone();++ int matchIdx =+ BrushPresetBridge::findMatchingStyleInPalette(palette, newStyle);+ if (matchIdx >= 0) {+ delete newStyle;+ app->setCurrentLevelStyleIndex(matchIdx, true);+ } else {+ int newId = palette->addStyle(newStyle);+ if (newId >= 0) {+ for (int p = 0; p < palette->getPageCount(); ++p) {+ TPalette::Page *pg = palette->getPage(p);+ if (!pg) continue;+ for (int s = 0; s < pg->getStyleCount(); ++s) {+ if (pg->getStyleId(s) == styleIndex) {+ pg->addStyle(newId);+ p = palette->getPageCount();+ break;+ }+ }+ }+ palette->setDirtyFlag(true);+ app->setCurrentLevelStyleIndex(newId, true);+ app->getPaletteController()+ ->getCurrentLevelPalette()+ ->notifyPaletteChanged();+ }+ }+ } else {+ TColorStyle *oldStyle = palette->getStyle(styleIndex);+ TUndo *undo = BrushPresetBridge::createStyleOverwriteUndo(+ palette, styleIndex, oldStyle, newStyle,+ app->getPaletteController()->getCurrentLevelPalette());+ palette->setStyle(styleIndex, newStyle);+ app->getCurrentPalette()->notifyColorStyleChanged(false);+ TUndoManager::manager()->add(undo);+ }+ };++ if (preset.m_hasStyleSnapshot && preset.m_styleInfoVersion >= 2) {+ TColorStyle *newStyle = nullptr;++ if (preset.m_snapshotStyleTagId == 3000) {+ std::string brushName = preset.m_snapshotBrushIdName;+ std::string prefix = "VectorBrushStyle:";+ if (brushName.find(prefix) == 0)+ brushName = brushName.substr(prefix.length());+ newStyle = new TVectorBrushStyle(brushName);+ } else if (preset.m_snapshotStyleTagId == 2001) {+ TFilePath texRelPath(preset.m_snapshotFilePath);+ TFilePath fullTexPath = TEnv::getStuffDir() + "library" + "textures" + texRelPath;+ TRaster32P textureRas;+ try {+ TImageReaderP reader = TImageReaderP(fullTexPath);+ if (reader) {+ TImageP img = reader->load();+ if (TRasterImageP ri = img) textureRas = ri->getRaster();+ }+ } catch (...) {}+ if (!textureRas) textureRas = TRaster32P(1, 1);+ newStyle = new TTextureStyle(textureRas, texRelPath);+ } else {+ newStyle = TColorStyle::create(preset.m_snapshotBrushIdName);+ }++ if (newStyle) {+ for (const auto ¶m : preset.m_snapshotParams) {+ int idx = param.first;+ double val = param.second;+ if (idx >= newStyle->getParamCount()) continue;+ TColorStyle::ParamType ptype = newStyle->getParamType(idx);+ switch (ptype) {+ case TColorStyle::BOOL:+ newStyle->setParamValue(idx, (bool)(val != 0));+ break;+ case TColorStyle::INT:+ case TColorStyle::ENUM:+ newStyle->setParamValue(idx, (int)val);+ break;+ case TColorStyle::DOUBLE:+ newStyle->setParamValue(idx, val);+ break;+ default:+ break;+ }+ }+ newStyle->setMainColor(currentColor);+ commitStyle(newStyle);+ }+ } else if (preset.m_hasVectorStyle) {+ if (preset.m_vectorStyleTagId == 3000) {+ std::string brushName = preset.m_vectorStyleName;+ std::string prefix = "VectorBrushStyle:";+ if (brushName.find(prefix) == 0)+ brushName = brushName.substr(prefix.length());+ TVectorBrushStyle *newStyle = new TVectorBrushStyle(brushName);+ newStyle->setMainColor(currentColor);+ commitStyle(newStyle);+ } else {+ TColorStyle *newStyle = TColorStyle::create(preset.m_vectorStyleName);+ if (newStyle) {+ newStyle->setMainColor(currentColor);+ commitStyle(newStyle);+ }+ }+ } else if (preset.m_hasTexture) {+ TFilePath texRelPath(preset.m_texturePath);+ TFilePath fullTexPath = TEnv::getStuffDir() + "library" + "textures" + texRelPath;+ TRaster32P textureRas;+ try {+ TImageReaderP reader = TImageReaderP(fullTexPath);+ if (reader) {+ TImageP img = reader->load();+ if (TRasterImageP ri = img) textureRas = ri->getRaster();+ }+ } catch (...) {}+ if (!textureRas) textureRas = TRaster32P(1, 1);+ TTextureStyle *newStyle = new TTextureStyle(textureRas, texRelPath);+ newStyle->setParamValue(2, preset.m_textureScale);+ newStyle->setParamValue(3, preset.m_textureRotation);+ newStyle->setParamValue(4, preset.m_textureDispX);+ newStyle->setParamValue(5, preset.m_textureDispY);+ newStyle->setParamValue(6, preset.m_textureContrast);+ newStyle->setParamValue(1, preset.m_textureType);+ newStyle->setParamValue(0, preset.m_textureIsPattern);+ newStyle->setMainColor(currentColor);+ commitStyle(newStyle);+ } else if (!preset.m_hasVectorStyle && !preset.m_hasTexture && !preset.m_hasStyleSnapshot) {+ if (!dynamic_cast<TSolidColorStyle*>(currentStyle)) {+ TSolidColorStyle *newStyle = new TSolidColorStyle(currentColor);+ commitStyle(newStyle);+ }+ }+ }+ }+ }} catch (...) {}}@@ -1786,6 +1961,77 @@ void ToonzVectorBrushTool::addPreset(QString name) {preset.m_cap = m_capStyle.getIndex();preset.m_join = m_joinStyle.getIndex();preset.m_miter = m_miterJoinLimit.getValue();++ // Capture complete style snapshot using the GENERIC approach+ preset.m_styleInfoVersion = 2;+ preset.m_hasVectorStyle = false;+ preset.m_hasTexture = false;+ preset.m_hasStyleSnapshot = false;++ TApplication *app = getApplication();+ if (app) {+ TColorStyle *style = app->getCurrentLevelStyle();++ if (style && !dynamic_cast<TSolidColorStyle*>(style)) {+ preset.m_hasStyleSnapshot = true;+ preset.m_snapshotStyleTagId = style->getTagId();+ preset.m_snapshotBrushIdName = style->getBrushIdName();++ // Extract primary file path and populate legacy fields+ if (TVectorBrushStyle *vbStyle = dynamic_cast<TVectorBrushStyle*>(style)) {+ preset.m_snapshotFilePath = "";+ // Legacy compatibility+ preset.m_hasVectorStyle = true;+ preset.m_vectorStyleTagId = vbStyle->getTagId();+ preset.m_vectorStyleName = vbStyle->getBrushIdName();+ } else if (TTextureStyle *texStyle = dynamic_cast<TTextureStyle*>(style)) {+ TFilePath texPath = texStyle->getParamValue(TColorStyle::TFilePath_tag(), 0);+ std::wstring wpath = texPath.getWideString();+ preset.m_snapshotFilePath = std::string(wpath.begin(), wpath.end());+ // Legacy compatibility+ preset.m_hasTexture = true;+ preset.m_texturePath = preset.m_snapshotFilePath;+ preset.m_textureScale = texStyle->getParamValue(TColorStyle::double_tag(), 2);+ preset.m_textureRotation = texStyle->getParamValue(TColorStyle::double_tag(), 3);+ preset.m_textureDispX = texStyle->getParamValue(TColorStyle::double_tag(), 4);+ preset.m_textureDispY = texStyle->getParamValue(TColorStyle::double_tag(), 5);+ preset.m_textureContrast = texStyle->getParamValue(TColorStyle::double_tag(), 6);+ preset.m_textureType = texStyle->getParamValue(TColorStyle::int_tag(), 1);+ preset.m_textureIsPattern = texStyle->getParamValue(TColorStyle::bool_tag(), 0);+ } else {+ // Generated or Trail styles+ preset.m_snapshotFilePath = "";+ // Legacy compatibility+ preset.m_hasVectorStyle = true;+ preset.m_vectorStyleTagId = style->getTagId();+ preset.m_vectorStyleName = style->getBrushIdName();+ }++ // GENERIC: Capture ALL numeric parameters of the style+ int paramCount = style->getParamCount();+ for (int i = 0; i < paramCount; ++i) {+ TColorStyle::ParamType ptype = style->getParamType(i);+ double numValue = 0.0;+ switch (ptype) {+ case TColorStyle::BOOL:+ numValue = style->getParamValue(TColorStyle::bool_tag(), i) ? 1.0 : 0.0;+ break;+ case TColorStyle::INT:+ case TColorStyle::ENUM:+ numValue = (double)style->getParamValue(TColorStyle::int_tag(), i);+ break;+ case TColorStyle::DOUBLE:+ numValue = style->getParamValue(TColorStyle::double_tag(), i);+ break;+ case TColorStyle::FILEPATH:+ continue; // Handled via m_snapshotFilePath+ default:+ continue;+ }+ preset.m_snapshotParams.push_back({i, numValue});+ }+ }+ }// Pass the preset to the managerm_presetsManager.addPreset(preset);@@ -1877,7 +2123,24 @@ VectorBrushData::VectorBrushData(), m_pressure(false), m_cap(0), m_join(0)- , m_miter(0) {}+ , m_miter(0)+ , m_styleInfoVersion(0)+ , m_hasVectorStyle(false)+ , m_vectorStyleTagId(0)+ , m_vectorStyleName("")+ , m_hasTexture(false)+ , m_texturePath("")+ , m_textureScale(1.0)+ , m_textureRotation(0.0)+ , m_textureDispX(0.0)+ , m_textureDispY(0.0)+ , m_textureContrast(1.0)+ , m_textureType(1)+ , m_textureIsPattern(false)+ , m_hasStyleSnapshot(false)+ , m_snapshotStyleTagId(0)+ , m_snapshotBrushIdName("")+ , m_snapshotFilePath("") {}//----------------------------------------------------------------------------------------------------------@@ -1892,7 +2155,24 @@ VectorBrushData::VectorBrushData(const std::wstring &name), m_pressure(false), m_cap(0), m_join(0)- , m_miter(0) {}+ , m_miter(0)+ , m_styleInfoVersion(0)+ , m_hasVectorStyle(false)+ , m_vectorStyleTagId(0)+ , m_vectorStyleName("")+ , m_hasTexture(false)+ , m_texturePath("")+ , m_textureScale(1.0)+ , m_textureRotation(0.0)+ , m_textureDispX(0.0)+ , m_textureDispY(0.0)+ , m_textureContrast(1.0)+ , m_textureType(1)+ , m_textureIsPattern(false)+ , m_hasStyleSnapshot(false)+ , m_snapshotStyleTagId(0)+ , m_snapshotBrushIdName("")+ , m_snapshotFilePath("") {}//----------------------------------------------------------------------------------------------------------@@ -1927,6 +2207,74 @@ void VectorBrushData::saveData(TOStream &os) {os.openChild("Miter");os << m_miter;os.closeChild();+ // Style snapshot (version 2 = generic)+ os.openChild("StyleInfoVersion");+ os << 2;+ os.closeChild();+ // Legacy fields (kept for backward compatibility)+ os.openChild("HasVectorStyle");+ os << (int)m_hasVectorStyle;+ os.closeChild();+ if (m_hasVectorStyle) {+ os.openChild("VectorStyleTagId");+ os << m_vectorStyleTagId;+ os.closeChild();+ os.openChild("VectorStyleName");+ os << m_vectorStyleName;+ os.closeChild();+ }+ os.openChild("HasTexture");+ os << (int)m_hasTexture;+ os.closeChild();+ if (m_hasTexture) {+ os.openChild("TexturePath");+ os << m_texturePath;+ os.closeChild();+ os.openChild("TextureScale");+ os << m_textureScale;+ os.closeChild();+ os.openChild("TextureRotation");+ os << m_textureRotation;+ os.closeChild();+ os.openChild("TextureDispX");+ os << m_textureDispX;+ os.closeChild();+ os.openChild("TextureDispY");+ os << m_textureDispY;+ os.closeChild();+ os.openChild("TextureContrast");+ os << m_textureContrast;+ os.closeChild();+ os.openChild("TextureType");+ os << m_textureType;+ os.closeChild();+ os.openChild("TextureIsPattern");+ os << (int)m_textureIsPattern;+ os.closeChild();+ }+ // Generic style snapshot (version >= 2)+ os.openChild("StyleSnapshot");+ os << (int)m_hasStyleSnapshot;+ os.closeChild();+ if (m_hasStyleSnapshot) {+ os.openChild("SnapshotTagId");+ os << m_snapshotStyleTagId;+ os.closeChild();+ os.openChild("SnapshotBrushId");+ os << m_snapshotBrushIdName;+ os.closeChild();+ os.openChild("SnapshotFile");+ os << m_snapshotFilePath;+ os.closeChild();+ os.openChild("SnapshotParamCount");+ os << (int)m_snapshotParams.size();+ os.closeChild();+ for (const auto ¶m : m_snapshotParams) {+ os.openChild("SNP");+ os << param.first << param.second;+ os.closeChild();+ }+ }}//----------------------------------------------------------------------------------------------------------@@ -1956,6 +2304,51 @@ void VectorBrushData::loadData(TIStream &is) {is >> m_join, is.matchEndTag();else if (tagName == "Miter")is >> m_miter, is.matchEndTag();+ // Style snapshot fields+ else if (tagName == "StyleInfoVersion")+ is >> m_styleInfoVersion, is.matchEndTag();+ else if (tagName == "HasVectorStyle")+ is >> val, m_hasVectorStyle = val, is.matchEndTag();+ else if (tagName == "VectorStyleTagId")+ is >> m_vectorStyleTagId, is.matchEndTag();+ else if (tagName == "VectorStyleName")+ is >> m_vectorStyleName, is.matchEndTag();+ else if (tagName == "HasTexture")+ is >> val, m_hasTexture = val, is.matchEndTag();+ else if (tagName == "TexturePath")+ is >> m_texturePath, is.matchEndTag();+ else if (tagName == "TextureScale")+ is >> m_textureScale, is.matchEndTag();+ else if (tagName == "TextureRotation")+ is >> m_textureRotation, is.matchEndTag();+ else if (tagName == "TextureDispX")+ is >> m_textureDispX, is.matchEndTag();+ else if (tagName == "TextureDispY")+ is >> m_textureDispY, is.matchEndTag();+ else if (tagName == "TextureContrast")+ is >> m_textureContrast, is.matchEndTag();+ else if (tagName == "TextureType")+ is >> m_textureType, is.matchEndTag();+ else if (tagName == "TextureIsPattern")+ is >> val, m_textureIsPattern = val, is.matchEndTag();+ // Generic style snapshot (version >= 2)+ else if (tagName == "StyleSnapshot")+ is >> val, m_hasStyleSnapshot = val, is.matchEndTag();+ else if (tagName == "SnapshotTagId")+ is >> m_snapshotStyleTagId, is.matchEndTag();+ else if (tagName == "SnapshotBrushId")+ is >> m_snapshotBrushIdName, is.matchEndTag();+ else if (tagName == "SnapshotFile")+ is >> m_snapshotFilePath, is.matchEndTag();+ else if (tagName == "SnapshotParamCount")+ is >> val, is.matchEndTag();+ else if (tagName == "SNP") {+ int idx;+ double dval;+ is >> idx >> dval;+ m_snapshotParams.push_back({idx, dval});+ is.matchEndTag();+ }elseis.skipCurrentTag();}diff --git a/toonz/sources/tnztools/toonzvectorbrushtool.h b/toonz/sources/tnztools/toonzvectorbrushtool.hindex b4bb8ea32..0c8006338 100644--- a/toonz/sources/tnztools/toonzvectorbrushtool.h+++ b/toonz/sources/tnztools/toonzvectorbrushtool.h@@ -26,6 +26,8 @@#include <QCoreApplication>#include <QRadialGradient>+#include <vector>+#include <utility>//--------------------------------------------------------------@@ -53,6 +55,34 @@ struct VectorBrushData final : public TPersist {int m_drawOrder;bool m_breakAngles, m_pressure;int m_cap, m_join, m_miter;++ // Style snapshot information (for strict preset restoration)+ int m_styleInfoVersion; // 0 = old, 1 = full snapshot++ // Vector style info: Generated, Trail, or VectorBrush+ bool m_hasVectorStyle; // true if non-solid style was active+ int m_vectorStyleTagId; // TagId of the style (e.g., 3000 for VectorBrush)+ std::string m_vectorStyleName; // brush/pattern name for VectorBrush/Trail styles++ // Texture style info (kept for backward compatibility)+ bool m_hasTexture; // true if Texture style was active+ std::string m_texturePath; // path to texture image+ double m_textureScale;+ double m_textureRotation;+ double m_textureDispX;+ double m_textureDispY;+ double m_textureContrast;+ int m_textureType; // 0=FIXED, 1=AUTOMATIC, 2=RANDOM+ bool m_textureIsPattern;++ // Generic style snapshot (version >= 2)+ // Replaces individual vector/texture fields for new presets.+ // Captures ALL parameters of ANY TColorStyle generically.+ bool m_hasStyleSnapshot; // true if generic snapshot present+ int m_snapshotStyleTagId; // TColorStyle::getTagId() for recreation+ std::string m_snapshotBrushIdName; // TColorStyle::getBrushIdName()+ std::string m_snapshotFilePath; // Primary file (texture image, VectorBrush)+ std::vector<std::pair<int, double>> m_snapshotParams; // (paramIndex, numericValue)VectorBrushData();VectorBrushData(const std::wstring &name);diff --git a/toonz/sources/toonz/brushpresetpanel.cpp b/toonz/sources/toonz/brushpresetpanel.cppindex d6cc2f804..189bdb6eb 100644--- a/toonz/sources/toonz/brushpresetpanel.cpp+++ b/toonz/sources/toonz/brushpresetpanel.cpp@@ -1,21 +1,37 @@#include "brushpresetpanel.h"+// Standard includes+#include <cmath>+// ToonzQt includes#include "tapp.h"#include "menubarcommandids.h"#include "toonzqt/gutil.h"#include "toonzqt/dvdialog.h"+#include "toonzqt/lineedit.h"#include "toolpresetcommandmanager.h"// ToonzLib includes#include "toonz/toonzfolders.h"#include "toonz/preferences.h"#include "toonz/mypaintbrushstyle.h"+#include "toonz/imagestyles.h"++// TnzCore includes for style detection+#include "tcolorstyles.h"+#include "tvectorbrushstyle.h"+#include "tundo.h"+#include "historytypes.h"+#include "tsimplecolorstyles.h"+#include "tpalette.h"+#include "toonz/palettecontroller.h"+#include "toonz/tpalettehandle.h"// ToonzCore includes#include "tenv.h"#include "tfilepath.h"#include "tsystem.h"+#include "tstream.h"// Tools includes#include "tools/tool.h"@@ -23,6 +39,10 @@#include "tools/toolcommandids.h"#include "tproperty.h"+// Command-based add/remove (avoids LNK2019 - handlers are in tnztools)+#include "toonzqt/brushpresetbridge.h"+#include "toonzqt/menubarcommand.h"+// Qt includes#include <QVBoxLayout>#include <QHBoxLayout>@@ -32,6 +52,7 @@#include <QLabel>#include <QMessageBox>#include <QPainter>+#include <QPainterPath>#include <QStyle>#include <QStyleOptionToolButton>#include <QLineEdit>@@ -52,6 +73,8 @@#include <QFile>#include <QTextStream>#include <QSet>+#include <QFrame>+#include <QTimer>//=============================================================================// PresetNamePopup - Popup to enter a preset name@@ -61,20 +84,21 @@ class PresetNamePopup : public QDialog {QLineEdit *m_nameFld;public:- PresetNamePopup(QWidget *parent = nullptr) : QDialog(parent) {+ PresetNamePopup(QWidget *parent = nullptr)+ : QDialog(parent) {setWindowTitle(tr("Enter Preset Name"));-+QVBoxLayout *mainLayout = new QVBoxLayout(this);- m_nameFld = new QLineEdit(this);+ m_nameFld = new QLineEdit(this);mainLayout->addWidget(m_nameFld);-+QHBoxLayout *buttonLayout = new QHBoxLayout();- QPushButton *okBtn = new QPushButton(tr("OK"), this);- QPushButton *cancelBtn = new QPushButton(tr("Cancel"), this);+ QPushButton *okBtn = new QPushButton(tr("OK"), this);+ QPushButton *cancelBtn = new QPushButton(tr("Cancel"), this);buttonLayout->addWidget(okBtn);buttonLayout->addWidget(cancelBtn);mainLayout->addLayout(buttonLayout);-+connect(okBtn, SIGNAL(clicked()), this, SLOT(accept()));connect(cancelBtn, SIGNAL(clicked()), this, SLOT(reject()));}@@ -85,21 +109,235 @@ public:namespace {-// Brush Preset Panel display prefs in user .env (TEnv), not the Windows-// registry.+// Brush Preset Panel UI state in user .env (TEnv), not the Windows registry.TEnv::IntVar BrushPresetPanelShowBorders("BrushPresetPanelShowBorders", 0);-TEnv::IntVar BrushPresetPanelShowBackgrounds("BrushPresetPanelShowBackgrounds",- 1);+TEnv::IntVar BrushPresetPanelShowBackgrounds("BrushPresetPanelShowBackgrounds", 1);+TEnv::IntVar BrushPresetPanelUseSampleStrokes("BrushPresetPanelUseSampleStrokes",+ 0);TEnv::IntVar BrushPresetPanelViewMode(- "BrushPresetPanelViewMode", static_cast<int>(BrushPresetPanel::GridLarge));+ "BrushPresetPanelViewMode",+ static_cast<int>(BrushPresetPanel::GridLarge));+TEnv::IntVar BrushPresetPanelNonDestructive("BrushPresetPanelNonDestructive", 0);+TEnv::IntVar BrushPresetPanelSelectivePreset("BrushPresetPanelSelectivePreset",+ 0);++TEnv::StringVar BrushPresetPagesVector("BrushPresetPages_vector", "");+TEnv::StringVar BrushPresetPagesToonzRaster("BrushPresetPages_toonzraster", "");+TEnv::StringVar BrushPresetPagesRaster("BrushPresetPages_raster", "");++const QChar kPageFieldSeparator(0x1e);+const QChar kPageEntrySeparator(0x1f);++TEnv::StringVar &brushPresetPagesEnvForToolType(const QString &toolType) {+ if (toolType == "vector") return BrushPresetPagesVector;+ if (toolType == "toonzraster") return BrushPresetPagesToonzRaster;+ return BrushPresetPagesRaster;+}++QString serializePageConfiguration(const QList<BrushPresetPage *> &pages,+ int currentPageIndex) {+ QStringList parts;+ parts << QString::number(pages.size());+ parts << QString::number(currentPageIndex);+ for (BrushPresetPage *page : pages) {+ if (!page) continue;+ QString entry = page->getName() + kPageFieldSeparator ++ page->getPresetNames().join("|||") + kPageFieldSeparator ++ page->getLastSelectedPreset();+ parts << entry;+ }+ return parts.join(kPageEntrySeparator);+}++bool deserializePageConfiguration(+ const QString &serialized, QList<BrushPresetPage *> &outPages,+ int &outCurrentPageIndex) {+ outPages.clear();+ if (serialized.isEmpty()) return false;++ const QStringList parts = serialized.split(kPageEntrySeparator);+ if (parts.size() < 2) return false;++ bool okCount = false, okCurrent = false;+ const int pageCount = parts[0].toInt(&okCount);+ outCurrentPageIndex = parts[1].toInt(&okCurrent);+ if (!okCount || !okCurrent || pageCount <= 0) return false;++ for (int i = 0; i < pageCount; ++i) {+ const int partIndex = i + 2;+ if (partIndex >= parts.size()) break;++ const QStringList fields = parts[partIndex].split(kPageFieldSeparator);+ const QString pageName = fields.value(0, QString("Page %1").arg(i + 1));+ BrushPresetPage *page = new BrushPresetPage(pageName, i);++ if (fields.size() > 1 && !fields[1].isEmpty()) {+ page->setPresetNames(fields[1].split("|||", Qt::SkipEmptyParts));+ }+ if (fields.size() > 2) page->setLastSelectedPreset(fields[2]);+ outPages.append(page);+ }++ return !outPages.isEmpty();+}++// Parse the preset file for toolType once and return a map of all presets.+// This is the efficient alternative to calling loadPresetRenderData() N times+// (which would open and linearly scan the file N times = O(N²) total work).+QHash<QString, PresetRenderData> loadAllPresetRenderData(const QString &toolType) {+ QHash<QString, PresetRenderData> result;++ TFilePath presetFilePath;+ if (toolType == "vector")+ presetFilePath = TEnv::getConfigDir() + "brush_vector.txt";+ else if (toolType == "toonzraster")+ presetFilePath = TEnv::getConfigDir() + "brush_toonzraster.txt";+ else if (toolType == "raster")+ presetFilePath = TEnv::getConfigDir() + "brush_raster.txt";+ else+ return result;++ try {+ TIStream is(presetFilePath);+ std::string tagName;+ while (is.matchTag(tagName)) {+ if (tagName == "version") {+ int major, minor;+ is >> major >> minor;+ is.matchEndTag();+ } else if (tagName == "brushes") {+ while (is.matchTag(tagName)) {+ if (tagName == "brush") {+ std::wstring name;+ double minT = 1.0, maxT = 5.0, h = 100.0, minO = 100.0, maxO = 100.0;+ int pencil = 0;+ while (is.matchTag(tagName)) {+ if (tagName == "Name") { is >> name; is.matchEndTag(); }+ else if (tagName == "Thickness") { is >> minT >> maxT; is.matchEndTag(); }+ else if (tagName == "Hardness") { is >> h; is.matchEndTag(); }+ else if (tagName == "Opacity") { is >> minO >> maxO; is.matchEndTag(); }+ else if (tagName == "Pencil") { is >> pencil; is.matchEndTag(); }+ else { is.skipCurrentTag(); }+ }+ if (!name.empty()) {+ PresetRenderData d;+ d.minThickness = minT;+ d.maxThickness = maxT;+ d.hardness = h;+ d.minOpacity = minO;+ d.maxOpacity = maxO;+ d.isPencil = (pencil != 0);+ d.hasData = true;+ result.insert(QString::fromStdWString(name), d);+ }+ is.matchEndTag();+ } else {+ is.skipCurrentTag();+ }+ }+ is.matchEndTag();+ } else {+ is.skipCurrentTag();+ }+ }+ } catch (...) {}++ return result;+}++PresetRenderData loadPresetRenderData(const QString &presetName, const QString &toolType) {+ PresetRenderData data;+ data.hasData = false;++ TFilePath presetFilePath;+ if (toolType == "vector") {+ presetFilePath = TEnv::getConfigDir() + "brush_vector.txt";+ } else if (toolType == "toonzraster") {+ presetFilePath = TEnv::getConfigDir() + "brush_toonzraster.txt";+ } else if (toolType == "raster") {+ presetFilePath = TEnv::getConfigDir() + "brush_raster.txt";+ } else {+ return data;+ }++ try {+ TIStream is(presetFilePath);+ std::string tagName;+ std::wstring wPresetName = presetName.toStdWString();++ while (is.matchTag(tagName)) {+ if (tagName == "version") {+ int major, minor;+ is >> major >> minor;+ is.matchEndTag();+ } else if (tagName == "brushes") {+ while (is.matchTag(tagName)) {+ if (tagName == "brush") {+ std::wstring name;+ double minThick = 1.0, maxThick = 5.0, hardness = 100.0;+ double minOp = 100.0, maxOp = 100.0;+ int pencil = 0;++ while (is.matchTag(tagName)) {+ if (tagName == "Name") {+ is >> name;+ is.matchEndTag();+ } else if (tagName == "Thickness") {+ is >> minThick >> maxThick;+ is.matchEndTag();+ } else if (tagName == "Hardness") {+ is >> hardness;+ is.matchEndTag();+ } else if (tagName == "Opacity") {+ is >> minOp >> maxOp;+ is.matchEndTag();+ } else if (tagName == "Pencil") {+ is >> pencil;+ is.matchEndTag();+ } else {+ is.skipCurrentTag();+ }+ }++ if (name == wPresetName) {+ data.minThickness = minThick;+ data.maxThickness = maxThick;+ data.hardness = hardness;+ data.minOpacity = minOp;+ data.maxOpacity = maxOp;+ data.isPencil = (pencil != 0);+ data.hasData = true;+ is.matchEndTag();+ return data;+ }++ is.matchEndTag();+ } else {+ is.skipCurrentTag();+ }+ }+ is.matchEndTag();+ } else {+ is.skipCurrentTag();+ }+ }+ } catch (...) {+ }+ return data;+}} // namespace+//=============================================================================// BrushPresetItem implementation//=============================================================================BrushPresetItem::BrushPresetItem(const QString &presetName,- const QString &toolType, bool isListMode,+ const QString &toolType,+ bool isListMode,+ bool useSampleStrokes,+ const QString &resolvedIconPath,+ const PresetRenderData &preloadedData,QWidget *parent): QToolButton(parent), m_presetName(presetName)@@ -109,30 +347,34 @@ BrushPresetItem::BrushPresetItem(const QString &presetName,, m_isListMode(isListMode), m_isSmallMode(false), m_showBorders(true)- , m_showBackgrounds(true) {+ , m_showBackgrounds(true)+ , m_checkboxVisible(false)+ , m_isMultiSelected(false)+ , m_useSampleStrokes(useSampleStrokes) {+setText(presetName);setCheckable(true);setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);- setMouseTracking(true); // To detect hover- setAcceptDrops(true); // Enable drag & drop-- // Load icon for this preset- QString customIconPath = findCustomPresetIcon(presetName);- if (!customIconPath.isEmpty()) {- setIconFromPath(customIconPath);- m_isCustomIcon = true; // Mark as custom icon+ setMouseTracking(true);+ setAcceptDrops(true);++ // Apply pre-resolved icon (no disk I/O here).+ if (!resolvedIconPath.isEmpty()) {+ setIconFromPath(resolvedIconPath);+ m_isCustomIcon = true;} else {setDefaultIcon(toolType);- m_isCustomIcon = false; // Generated icon+ m_isCustomIcon = false;}- // Create scaled version of icon (FIXED)- updateScaledIcon();+ // Use the pre-loaded render data (no file open here).+ m_renderData = preloadedData;- connect(this, &QPushButton::clicked,- [this]() { emit presetSelected(m_presetName, m_toolType); });+ updateScaledIcon();- // Force repaint when checked state changes+ connect(this, &QPushButton::clicked, [this]() {+ emit presetSelected(m_presetName, m_toolType);+ });connect(this, &QPushButton::toggled, [this](bool) { update(); });}@@ -140,33 +382,33 @@ void BrushPresetItem::setListMode(bool isListMode) {if (m_isListMode == isListMode) return;m_isListMode = isListMode;updateScaledIcon(); // Recalculate icon for new mode- update(); // Repaint+ update(); // Repaint}void BrushPresetItem::setSmallMode(bool isSmallMode) {if (m_isSmallMode == isSmallMode) return;m_isSmallMode = isSmallMode;updateScaledIcon(); // Recalculate icon for new mode- update(); // Repaint+ update(); // Repaint}QString BrushPresetItem::findCustomPresetIcon(const QString &presetName) {// Same logic as in ToolPresetCommandManagerTFilePath iconFolder = TEnv::getStuffDir() + "library" + "brushpreseticons";-+// Try .svg and .png extensionsQStringList extensions;extensions << ".svg" << ".png";-+for (const QString &ext : extensions) {QString iconFileName = presetName + ext;- TFilePath iconPath = iconFolder + TFilePath(iconFileName.toStdString());-+ TFilePath iconPath = iconFolder + TFilePath(iconFileName.toStdString());+if (TFileStatus(iconPath).doesExist()) {return iconPath.getQString();}}-+return QString();}@@ -175,14 +417,14 @@ void BrushPresetItem::setIconFromPath(const QString &iconPath) {m_hasIcon = false;return;}-+m_isCustomIcon = true;-+// Load icon directly (no theme adaptation)QPixmap pixmap(iconPath);if (!pixmap.isNull()) {m_iconPixmap = pixmap;- m_hasIcon = true;+ m_hasIcon = true;} else {m_hasIcon = false;}@@ -192,24 +434,20 @@ void BrushPresetItem::setDefaultIcon(const QString &toolType) {// Use default SVG icons according to tool typeQString iconName;if (toolType == "vector") {- iconName = "brush"; // Vector brush+ iconName = "brush"; // Vector brush} else if (toolType == "toonzraster") {- iconName = "palette"; // Toonz Raster brush (palette icon)- } else if (toolType == "mypaint") {- iconName = "paintbrush"; // MyPaint brush (raster)- } else if (toolType == "mypainttnz") {- iconName = "palette"; // MyPaint brush on Toonz Raster+ iconName = "palette"; // Toonz Raster brush} else if (toolType == "raster") {- iconName = "paintbrush"; // Raster brush+ iconName = "paintbrush"; // Raster brush}-+m_isCustomIcon = false;-+if (!iconName.isEmpty()) {QIcon icon = createQIcon(iconName.toStdString().c_str());if (!icon.isNull()) {m_iconPixmap = icon.pixmap(32, 32);- m_hasIcon = true;+ m_hasIcon = true;} else {m_hasIcon = false;}@@ -223,113 +461,380 @@ void BrushPresetItem::updateScaledIcon() {m_scaledIconCache = QPixmap();return;}-+// Calculate scaled icon size ONCE// based on MINIMUM widget heightconst int margin = 3; // Reduced margins for more space-+// Use minimumHeight() to have a fixed sizeint cellHeight = minimumHeight();if (cellHeight <= 0) cellHeight = 60; // Fallback-+// Available area for icon (depends on mode)int availableHeight, availableWidth;-+if (m_isListMode) {// In list mode: icon occupies full height (except reduced margins)availableHeight = cellHeight - (2 * margin);- availableWidth = availableHeight; // Square icon in list mode+ availableWidth = availableHeight; // Square icon in list mode} else {// In grid mode: leave space for text below (larger text)const int textHeightSmall = 16; // Larger text (was 14)- const int textMargin = 2;+ const int textMargin = 2;availableHeight = cellHeight - (2 * margin) - textHeightSmall - textMargin;- availableWidth = minimumWidth() - (2 * margin);+ availableWidth = minimumWidth() - (2 * margin);if (availableWidth <= 0) availableWidth = 120; // Fallback}-+// Calculate original icon ratioqreal iconRatio = (qreal)m_iconPixmap.width() / (qreal)m_iconPixmap.height();-+int scaledWidth, scaledHeight;-+if (availableHeight > 0 && availableWidth > 0) {qreal cellRatio = (qreal)availableWidth / (qreal)availableHeight;-+if (iconRatio > cellRatio) {// Icon is wider: limit by width- scaledWidth = availableWidth;+ scaledWidth = availableWidth;scaledHeight = (int)(availableWidth / iconRatio);} else {// Icon is taller: limit by heightscaledHeight = availableHeight;- scaledWidth = (int)(availableHeight * iconRatio);+ scaledWidth = (int)(availableHeight * iconRatio);}-+// Safety checkif (scaledHeight > availableHeight) {scaledHeight = availableHeight;- scaledWidth = (int)(availableHeight * iconRatio);+ scaledWidth = (int)(availableHeight * iconRatio);}if (scaledWidth > availableWidth) {- scaledWidth = availableWidth;+ scaledWidth = availableWidth;scaledHeight = (int)(availableWidth / iconRatio);}} else {- scaledWidth = availableWidth;+ scaledWidth = availableWidth;scaledHeight = availableHeight;}-+// For GENERATED icons (not custom) in GridSmall mode: reduce by 3pxif (!m_isCustomIcon && m_isSmallMode && !m_isListMode) {const int smallModeReduction = 3;- scaledWidth = qMax(1, scaledWidth - smallModeReduction);- scaledHeight = qMax(1, scaledHeight - smallModeReduction);+ scaledWidth = qMax(1, scaledWidth - smallModeReduction);+ scaledHeight = qMax(1, scaledHeight - smallModeReduction);}-+// For GENERATED icons (not custom) in ListView mode: reduce by 55%- // This optimization improves visual balance on screens < 4K (2.5K, 1080p,- // 1050p)+ // This optimization improves visual balance on screens < 4K (2.5K, 1080p, 1050p)if (!m_isCustomIcon && m_isListMode) {- scaledWidth = qMax(1, (int)(scaledWidth * 0.45));+ scaledWidth = qMax(1, (int)(scaledWidth * 0.45));scaledHeight = qMax(1, (int)(scaledHeight * 0.45));}-+// Create scaled icon and CACHE it- m_scaledIconCache = m_iconPixmap.scaled(- scaledWidth, scaledHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);+ m_scaledIconCache = m_iconPixmap.scaled(scaledWidth, scaledHeight,+ Qt::KeepAspectRatio,+ Qt::SmoothTransformation);+}++//-----------------------------------------------------------------------------++void BrushPresetItem::drawDynamicFallback(QPainter &painter, const QRect &iconRect) const {+ if (!m_renderData.hasData) return;++ painter.save();+ painter.setRenderHint(QPainter::Antialiasing, true);++ // Check if this is a size preset (pattern: [Size] NNN or [Size NNN])+ bool isSizePreset = m_presetName.startsWith("[Size] ") || m_presetName.startsWith("[Size ");++ if (isSizePreset) {+ // ==== SIZE PRESET: Progressive top-cropping circle + number ====+ // Small sizes: full circle (small).+ // As size grows, circle grows and gets progressively cropped from the TOP.+ // Around size 200+, only the bottom half remains (half-circle).+ QString sizeStr = m_presetName;+ sizeStr.remove("[Size] ").remove("[Size ").remove("]");+ double sizeVal = sizeStr.toDouble();++ // Font for the number+ QFont numFont = font();+ int fontSize = qMax(8, qMin(14, iconRect.height() / 4));+ numFont.setPixelSize(fontSize);+ numFont.setBold(true);+ QFontMetrics fm(numFont);+ int textH = fm.height();++ // Available space above text+ int availH = iconRect.height() - textH - 3;+ int maxDiam = qMin(iconRect.width() - 2, (int)(availH * 1.8));+ maxDiam = qMax(8, maxDiam);++ // Variable circle diameter (log scale from 0.5..1000)+ double minSz = 0.5, maxSz = 1000.0;+ double logMin = std::log(minSz + 1.0);+ double logMax = std::log(maxSz + 1.0);+ double logVal = std::log(qMax(sizeVal, minSz) + 1.0);+ double ratio = (logVal - logMin) / (logMax - logMin);+ ratio = qMax(0.0, qMin(1.0, ratio));++ int circleDiam = (int)(maxDiam * (0.15 + 0.85 * ratio));+ circleDiam = qMax(6, circleDiam);++ // Bottom of the circle sits at the text baseline+ int cx = iconRect.center().x();+ int circleBottom = iconRect.top() + availH;+ int circleTop = circleBottom - circleDiam;++ // Clip top: if circle extends above available area, crop from top+ int clipTop = iconRect.top();++ // Draw the circle. If it overflows the top, use a horizontal clip rect+ // so only the top is hidden — sides remain fully intact (like a horizontal mask).+ QRect circleRect(cx - circleDiam / 2, circleTop, circleDiam, circleDiam);++ if (circleTop < clipTop) {+ // Circle extends above the available area: clip horizontally from the top.+ // The clip rect spans the full width but starts at clipTop.+ painter.setClipRect(QRect(iconRect.left(), clipTop,+ iconRect.width(), circleBottom - clipTop));+ }++ painter.setPen(QPen(QColor(180, 180, 180), 1));+ painter.setBrush(QColor(255, 255, 255));+ painter.drawEllipse(circleRect);++ // Remove clip region so it does not affect subsequent drawing+ if (circleTop < clipTop) {+ painter.setClipping(false);+ }++ // Size number below the shape+ painter.setPen(palette().color(QPalette::Text));+ painter.setFont(numFont);+ QRect textRect(iconRect.left(), circleBottom + 1,+ iconRect.width(), textH + 2);+ painter.drawText(textRect, Qt::AlignHCenter | Qt::AlignTop, sizeStr);++ } else {+ // ==== BRUSH PRESET: Horizontal undulation sample stroke ====+ // Smooth double-wave: first half rises (hump), second half dips (valley).+ // Fills full iconRect width with tapered pointed tips.+ // Taper shape adapts to brush type (native vs overlay).+ // Texture varies: raster=grainy, toonzraster=light grain, vector=smooth.++ double minThick = m_renderData.minThickness;+ double maxThick = m_renderData.maxThickness;+ double avgThick = (minThick + maxThick) / 2.0;+ double avgOpacity = (m_renderData.minOpacity + m_renderData.maxOpacity) / 2.0;++ // Stroke max height: proportional to thickness, capped at 50% of icon height+ double maxH = iconRect.height() * 0.50;+ double strokeH = qMax(3.0, qMin(maxH, avgThick * iconRect.height() / 12.0));+ strokeH = qMax(strokeH, 5.0);++ // If opacity is 0 (tool doesn't support opacity, e.g. Toonz Raster),+ // treat as fully opaque since the brush always paints at full intensity.+ double alpha;+ if (avgOpacity < 0.01)+ alpha = 1.0;+ else+ alpha = qMax(0.3, qMin(1.0, avgOpacity / 100.0));++ // Hardness influences stroke brightness and crispness.+ // High hardness (100) -> pure white, crisp edges.+ // Low hardness (0) -> darker gray, soft/diffuse edges.+ double hardness = m_renderData.hardness; // 0..100+ double hardFrac = qMax(0.0, qMin(1.0, hardness / 100.0));++ // Stroke color: interpolate from a soft gray to pure white based on hardness.+ // Low hardness (0): gray ~140,140,140 (clearly visible as soft/diffuse)+ // High hardness (100): pure white 255,255,255 (crisp, bright)+ int lowVal = 140; // Gray value at hardness=0+ int highVal = 255; // White at hardness=100+ int val = lowVal + (int)((highVal - lowVal) * hardFrac);+ QColor strokeColor(val, val, val);+ strokeColor.setAlphaF(alpha);++ // Full width of iconRect with tiny margin for tips+ double x0 = iconRect.left() + 1.0;+ double x1 = iconRect.right() - 1.0;+ double totalW = x1 - x0;+ double cy = iconRect.center().y();++ // Wave amplitude: how much the centerline deviates up/down+ double waveAmp = iconRect.height() * 0.14;++ // Taper style depends on whether this is a native brush (no overlay).+ // Native brushes: taper driven by min/max thickness difference.+ // Other (MyPaint, texture, generated): default pointed taper.+ // Thickness ratio: how much thinner the tips are vs the body+ double thickRatio = (maxThick > 0.01) ? (minThick / maxThick) : 0.0;+ // Clamp to [0..1]: 0 = very tapered (big difference), 1 = uniform+ thickRatio = qMax(0.0, qMin(1.0, thickRatio));++ // Build the stroke outline as polygon (top edge + reversed bottom edge).+ // Centerline follows a sine wave (one full period = double undulation).+ const int N = 80;+ QPolygonF topEdge, botEdge;++ for (int i = 0; i <= N; ++i) {+ double t = (double)i / N; // 0..1 along the stroke+ double x = x0 + totalW * t;++ // Centerline: smooth sine wave (one full period).+ // First half: hump up. Second half: dip down.+ double angle = t * 2.0 * 3.14159265358979;+ double centerY = cy - std::sin(angle) * waveAmp;++ // Taper envelope: pointed tips at both ends, full thickness in middle.+ // For native brushes, the min/max ratio controls how pointed the tips are.+ // thickRatio=0 => very pointed; thickRatio=1 => blunt (uniform thickness).+ double taper;+ if (t < 0.5) {+ double u = t * 2.0; // 0 -> 1+ taper = u * u; // Quadratic ease-in+ } else {+ double u = (1.0 - t) * 2.0; // 1 -> 0+ taper = u * u; // Quadratic ease-out+ }++ // Blend taper with thickness ratio: native brushes use min/max difference+ // to set a floor on the taper (blunt tips when min ~ max).+ taper = thickRatio + (1.0 - thickRatio) * taper;++ // Hardness affects taper sharpness+ if (m_renderData.hardness < 50)+ taper = std::pow(taper, 0.7);+ if (m_renderData.hardness > 80)+ taper = std::pow(taper, 1.3);++ double halfH = strokeH * taper * 0.5;++ topEdge << QPointF(x, centerY - halfH);+ botEdge.prepend(QPointF(x, centerY + halfH));+ }++ // Build closed polygon path from the two edges+ QPolygonF outline = topEdge + botEdge;+ QPainterPath path;+ path.addPolygon(outline);+ path.closeSubpath();++ // === Texture rendering based on brush tool type ===+ // "raster" : grainy/pixelated look (stipple dots along the stroke)+ // "toonzraster" : lighter grain (fewer dots)+ // "vector" : perfectly smooth, no grain+ // Default : smooth with soft glow for soft brushes++ bool isRaster = (m_toolType == "raster");+ bool isToonzRaster = (m_toolType == "toonzraster");+ bool isVector = (m_toolType == "vector");++ // Main fill+ painter.setPen(Qt::NoPen);+ painter.setBrush(strokeColor);+ painter.drawPath(path);++ // Grain overlay for raster types (drawn on top of the fill).+ // Grain diminishes with higher hardness (hard brushes are clean/crisp).+ if ((isRaster || isToonzRaster) && hardFrac < 0.85) {+ // Draw scattered dots inside the stroke for a grainy effect.+ // Use a deterministic seed based on preset name for consistency.+ unsigned int seed = 0;+ for (int k = 0; k < m_presetName.length(); ++k)+ seed = seed * 31 + m_presetName.at(k).unicode();++ // Scale grain intensity down as hardness increases+ double grainScale = 1.0 - hardFrac; // 1.0 at hard=0, 0.0 at hard=100++ QColor grainColor = strokeColor;+ double grainAlpha = (isRaster ? 0.35 : 0.20) * grainScale;+ grainColor.setAlphaF(alpha * grainAlpha);+ painter.setPen(Qt::NoPen);++ // Number of grain dots: proportional to stroke area, scaled by hardness+ int dotCount = (int)((isRaster ? 60 : 30) * grainScale);+ double dotSize = isRaster ? 1.5 : 1.2;++ for (int d = 0; d < dotCount; ++d) {+ // Simple pseudo-random using seed (no external lib needed)+ seed = seed * 1103515245 + 12345;+ double rx = ((seed >> 16) & 0x7FFF) / 32768.0; // 0..1+ seed = seed * 1103515245 + 12345;+ double ry = ((seed >> 16) & 0x7FFF) / 32768.0; // 0..1++ double px = x0 + totalW * rx;+ double py = iconRect.top() + iconRect.height() * (0.2 + 0.6 * ry);++ // Only draw dot if it falls inside the stroke path+ if (path.contains(QPointF(px, py))) {+ // Alternate between dark and light grains+ if (d % 3 == 0) {+ QColor darkGrain = strokeColor.darker(140);+ darkGrain.setAlphaF(alpha * grainAlpha * 0.8);+ painter.setBrush(darkGrain);+ } else {+ painter.setBrush(grainColor);+ }+ painter.drawEllipse(QPointF(px, py), dotSize, dotSize);+ }+ }+ }++ // Soft glow for soft brushes (not pencil, not vector).+ // The softer the brush, the wider and more visible the diffuse glow.+ if (hardFrac < 0.5 && !m_renderData.isPencil && !isVector) {+ // Glow intensity increases as hardness decreases+ double glowIntensity = (0.5 - hardFrac) * 2.0; // 0..1 (0 at hard=50, 1 at hard=0)+ double glowWidth = 1.5 + glowIntensity * 2.5; // 1.5..4.0 px+ double glowAlpha = alpha * (0.08 + glowIntensity * 0.15);++ QColor glow = strokeColor;+ glow.setAlphaF(glowAlpha);+ painter.setBrush(Qt::NoBrush);+ painter.setPen(QPen(glow, glowWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ painter.drawPath(path);+ }+ }++ painter.restore();}+//-----------------------------------------------------------------------------+void BrushPresetItem::paintEvent(QPaintEvent *event) {QPainter painter(this);painter.setRenderHint(QPainter::Antialiasing);painter.setRenderHint(QPainter::SmoothPixmapTransform);-+// Draw background and border manually according to stateQRect r = rect();-+// Colors according to stateQColor bgColor;QColor borderColor = palette().color(QPalette::Mid);- int borderRadius = 4; // Always rounded for modern look-+ int borderRadius = 4; // Always rounded for modern look+// Get parent panel background color for seamless integrationQColor panelBgColor = palette().color(QPalette::Window);if (parentWidget()) {panelBgColor = parentWidget()->palette().color(QPalette::Window);}-+// Use QToolButton theme colors for hover/checked/pressed statesQStyleOptionToolButton opt;initStyleOption(&opt);- const bool useThemeState = opt.state.testFlag(QStyle::State_MouseOver) ||- opt.state.testFlag(QStyle::State_On) ||- opt.state.testFlag(QStyle::State_Sunken);-+ const bool useThemeState =+ opt.state.testFlag(QStyle::State_MouseOver) ||+ opt.state.testFlag(QStyle::State_On) ||+ opt.state.testFlag(QStyle::State_Sunken);+if (useThemeState) {QStyleOptionToolButton optBg = opt;- optBg.text = QString();- optBg.icon = QIcon();+ optBg.text = QString();+ optBg.icon = QIcon();style()->drawComplexControl(QStyle::CC_ToolButton, &optBg, &painter, this);} else {// Normal state background matches Brush Preset logic@@ -343,12 +848,12 @@ void BrushPresetItem::paintEvent(QPaintEvent *event) {} else {bgColor = panelBgColor;}-+painter.setPen(Qt::NoPen);painter.setBrush(bgColor);painter.drawRoundedRect(r, borderRadius, borderRadius);}-+// Draw border (if enabled AND not checked)if (m_showBorders && !isChecked()) {QPen borderPen(borderColor);@@ -358,104 +863,146 @@ void BrushPresetItem::paintEvent(QPaintEvent *event) {QRect borderRect = r.adjusted(0, 0, -1, -1);painter.drawRoundedRect(borderRect, borderRadius, borderRadius);}-+// Draw icon if availableif (m_hasIcon && !m_iconPixmap.isNull()) {// Margins and spacing (synchronized with updateScaledIcon)const int margin = 3;-+if (m_isListMode) {- // === LIST MODE: Icon on left (FIXED, positioned by type), text on right- // ===-+ // === LIST MODE: Icon on left (FIXED, positioned by type), text on right ===+// Use CACHED scaled icon (fixed size)if (!m_scaledIconCache.isNull()) {int iconX = margin;int iconY = (height() - m_scaledIconCache.height()) / 2;-+// Move custom icons up by 6px in list mode to avoid 4K clippingif (m_isCustomIcon) {iconY -= 6;}-- painter.drawPixmap(iconX, iconY, m_scaledIconCache);-- // Draw text to the right of icon- QRect textRect(- iconX + m_scaledIconCache.width() + margin, margin,- width() - iconX - m_scaledIconCache.width() - (2 * margin),- height() - (2 * margin));- painter.setPen(palette().color(QPalette::ButtonText));- painter.setFont(font());-- QString displayText = m_presetName;- QFontMetrics fm(font());- if (fm.horizontalAdvance(displayText) > textRect.width()) {- displayText =- fm.elidedText(displayText, Qt::ElideMiddle, textRect.width());++ // For dynamic fallback in list mode, use a wider rect:+ // Stroke can span the full icon area width (original icon height used as width basis)+ int dynIconW = m_scaledIconCache.width();+ int dynIconH = m_scaledIconCache.height();++ // Check if we should use dynamic fallback instead of generic icon+ if (m_useSampleStrokes && !m_isCustomIcon && m_renderData.hasData) {+ // Give the stroke more horizontal room in list mode (~2x wider)+ int wideW = qMin(width() / 2, dynIconW * 3);+ QRect iconRect(iconX, iconY, wideW, dynIconH);+ drawDynamicFallback(painter, iconRect);+ // Text goes after the wider rect+ QRect textRect(iconX + wideW + margin, margin,+ width() - iconX - wideW - (2 * margin),+ height() - (2 * margin));+ painter.setPen(palette().color(QPalette::ButtonText));+ painter.setFont(font());+ QString displayText = m_presetName;+ QFontMetrics fm(font());+ if (fm.horizontalAdvance(displayText) > textRect.width())+ displayText = fm.elidedText(displayText, Qt::ElideMiddle, textRect.width());+ painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, displayText);+ } else {+ painter.drawPixmap(iconX, iconY, m_scaledIconCache);+ // Draw text to the right of icon+ QRect textRect(iconX + m_scaledIconCache.width() + margin, margin,+ width() - iconX - m_scaledIconCache.width() - (2 * margin),+ height() - (2 * margin));+ painter.setPen(palette().color(QPalette::ButtonText));+ painter.setFont(font());+ QString displayText = m_presetName;+ QFontMetrics fm(font());+ if (fm.horizontalAdvance(displayText) > textRect.width())+ displayText = fm.elidedText(displayText, Qt::ElideMiddle, textRect.width());+ painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, displayText);}-- painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter,- displayText);}-+} else {// === GRID MODE: Icon on top (FIXED), Text below (larger) ===-- const int textHeightSmall =- 16; // Height reserved for text below (larger)- const int textMargin = 2; // Spacing between icon and text-++ const int textHeightSmall = 16; // Height reserved for text below (larger)+ const int textMargin = 2; // Spacing between icon and text+// Use CACHED scaled icon (fixed size)if (!m_scaledIconCache.isNull()) {// Available area to center iconint availableWidth = width() - (2 * margin);- int availableHeight =- height() - (2 * margin) - textHeightSmall - textMargin;-- // Center icon (which has a FIXED size) in available space- int iconX = margin + (availableWidth - m_scaledIconCache.width()) / 2;- int iconY = margin + (availableHeight - m_scaledIconCache.height()) / 2;-- painter.drawPixmap(iconX, iconY, m_scaledIconCache);+ int availableHeight = height() - (2 * margin) - textHeightSmall - textMargin;++ // Check if we should use dynamic fallback instead of generic icon+ if (m_useSampleStrokes && !m_isCustomIcon && m_renderData.hasData) {+ // Use the full available width for the stroke+ int iconY = margin + (availableHeight - m_scaledIconCache.height()) / 2;+ QRect iconRect(margin, iconY, availableWidth, m_scaledIconCache.height());+ drawDynamicFallback(painter, iconRect);+ } else {+ // Center icon (which has a FIXED size) in available space+ int iconX = margin + (availableWidth - m_scaledIconCache.width()) / 2;+ int iconY = margin + (availableHeight - m_scaledIconCache.height()) / 2;+ painter.drawPixmap(iconX, iconY, m_scaledIconCache);+ }}-+// Draw text at BOTTOM (below icon) - LARGERint textStartY = height() - margin - textHeightSmall;- QRect textRect(margin, textStartY, width() - (2 * margin),- textHeightSmall);-+ QRect textRect(margin, textStartY, width() - (2 * margin), textHeightSmall);+painter.setPen(palette().color(QPalette::ButtonText));QFont gridFont = font();// Use same font size as list mode (no reduction) for better readabilitygridFont.setPointSize(qMax(8, font().pointSize()));painter.setFont(gridFont);-+QString displayText = m_presetName;QFontMetrics fm(gridFont);if (fm.horizontalAdvance(displayText) > textRect.width()) {- displayText =- fm.elidedText(displayText, Qt::ElideMiddle, textRect.width());+ displayText = fm.elidedText(displayText, Qt::ElideMiddle, textRect.width());}-- painter.drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter,- displayText);++ painter.drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter, displayText);}} else {// No icon: just display centered textQRect textRect = rect().adjusted(4, 4, -4, -4);painter.setPen(palette().color(QPalette::ButtonText));painter.setFont(font());-+QString displayText = m_presetName;QFontMetrics fm(font());if (fm.horizontalAdvance(displayText) > textRect.width()) {- displayText =- fm.elidedText(displayText, Qt::ElideMiddle, textRect.width());+ displayText = fm.elidedText(displayText, Qt::ElideMiddle, textRect.width());}-+painter.drawText(textRect, Qt::AlignCenter, displayText);}++ // Draw checkbox overlay (top-right corner) when in checkbox mode+ if (m_checkboxVisible) {+ const int cbSize = 14;+ const int cbMargin = 4;+ QRect cbRect(width() - cbSize - cbMargin, cbMargin, cbSize, cbSize);++ // Draw checkbox background+ painter.setPen(QPen(palette().color(QPalette::Mid), 1));+ if (m_isMultiSelected) {+ painter.setBrush(palette().color(QPalette::Highlight));+ } else {+ painter.setBrush(palette().color(QPalette::Base));+ }+ painter.drawRoundedRect(cbRect, 2, 2);++ // Draw checkmark if selected+ if (m_isMultiSelected) {+ painter.setPen(QPen(palette().color(QPalette::HighlightedText), 2));+ painter.drawLine(cbRect.left() + 3, cbRect.center().y(),+ cbRect.center().x(), cbRect.bottom() - 3);+ painter.drawLine(cbRect.center().x(), cbRect.bottom() - 3,+ cbRect.right() - 3, cbRect.top() + 3);+ }+ }}QSize BrushPresetItem::sizeHint() const {@@ -475,6 +1022,21 @@ QSize BrushPresetItem::minimumSizeHint() const {void BrushPresetItem::mousePressEvent(QMouseEvent *event) {if (event->button() == Qt::LeftButton) {m_dragStartPosition = event->pos();+ } else if (event->button() == Qt::RightButton) {+ // Emit right-click signal for context menu+ // Find parent BrushPresetPanel and show context menu+ BrushPresetPanel *panel = nullptr;+ QWidget *p = parentWidget();+ while (p) {+ panel = qobject_cast<BrushPresetPanel*>(p);+ if (panel) break;+ p = p->parentWidget();+ }+ if (panel) {+ panel->showPresetContextMenu(event->globalPos(), m_presetName);+ event->accept();+ return;+ }}QToolButton::mousePressEvent(event);}@@ -484,38 +1046,37 @@ void BrushPresetItem::mouseMoveEvent(QMouseEvent *event) {QToolButton::mouseMoveEvent(event);return;}-- if ((event->pos() - m_dragStartPosition).manhattanLength() <- QApplication::startDragDistance()) {++ if ((event->pos() - m_dragStartPosition).manhattanLength() < QApplication::startDragDistance()) {QToolButton::mouseMoveEvent(event);return;}-+// Start drag operation- QDrag *drag = new QDrag(this);+ QDrag *drag = new QDrag(this);QMimeData *mimeData = new QMimeData;-+// Store preset name and tool type in MIME datamimeData->setText(m_presetName);mimeData->setData("application/x-brushpreset-tooltype", m_toolType.toUtf8());drag->setMimeData(mimeData);-+// Create drag pixmap (visual feedback)QPixmap dragPixmap = grab();drag->setPixmap(dragPixmap);drag->setHotSpot(event->pos());-+// Execute dragdrag->exec(Qt::MoveAction);}void BrushPresetItem::dragEnterEvent(QDragEnterEvent *event) {// Accept only if dragging a brush preset of the same tool type- if (event->mimeData()->hasText() &&+ if (event->mimeData()->hasText() &&event->mimeData()->hasFormat("application/x-brushpreset-tooltype")) {QString draggedToolType = QString::fromUtf8(event->mimeData()->data("application/x-brushpreset-tooltype"));-+if (draggedToolType == m_toolType) {event->acceptProposedAction();return;@@ -526,11 +1087,11 @@ void BrushPresetItem::dragEnterEvent(QDragEnterEvent *event) {void BrushPresetItem::dragMoveEvent(QDragMoveEvent *event) {// Same logic as dragEnterEvent- if (event->mimeData()->hasText() &&+ if (event->mimeData()->hasText() &&event->mimeData()->hasFormat("application/x-brushpreset-tooltype")) {QString draggedToolType = QString::fromUtf8(event->mimeData()->data("application/x-brushpreset-tooltype"));-+if (draggedToolType == m_toolType) {event->acceptProposedAction();return;@@ -544,34 +1105,169 @@ void BrushPresetItem::dropEvent(QDropEvent *event) {event->ignore();return;}-++ // Only accept drops if they have the correct MIME type+ if (!event->mimeData()->hasFormat("application/x-brushpreset-tooltype")) {+ event->ignore();+ return;+ }+QString fromPreset = event->mimeData()->text();- QString toPreset = m_presetName;-+ QString toPreset = m_presetName;+// Don't reorder if dropping on itselfif (fromPreset == toPreset) {event->ignore();return;}-++ // Only accept drops from the same tool type+ QString draggedToolType = QString::fromUtf8(+ event->mimeData()->data("application/x-brushpreset-tooltype"));++ if (draggedToolType != m_toolType) {+ event->ignore();+ return;+ }+// Emit signal to parent panel to handle reorderingemit presetReordered(fromPreset, toPreset);-+event->acceptProposedAction();}+//=============================================================================+// BrushPresetTabBar implementation (modeled after PaletteTabBar)+//=============================================================================++BrushPresetTabBar::BrushPresetTabBar(QWidget *parent)+ : QTabBar(parent)+ , m_renameTextField(new DVGui::LineEdit(this))+ , m_renameTabIndex(-1)+ , m_panel(nullptr) {+ setObjectName("BrushPresetTabBar");++ // Remove elevation effect - flat rendering like Level Palette+ setDrawBase(false);+ setDocumentMode(true); // CRITICAL: This removes the frame around tabs+ setMovable(false); // We handle movement ourselves via Ctrl+Drag+ setExpanding(false); // Don't expand tabs to fill width+ setIconSize(QSize(16, 16)); // Standard icon size for palette_tab icon+ setUsesScrollButtons(true); // Show scroll buttons when many tabs+ setElideMode(Qt::ElideNone); // Don't elide tab text++ m_renameTextField->hide();++ connect(m_renameTextField, SIGNAL(editingFinished()), this, SLOT(updateTabName()));+}++//-----------------------------------------------------------------------------+/*! Hide rename text field and handle tab selection+ */+void BrushPresetTabBar::mousePressEvent(QMouseEvent *event) {+ m_renameTextField->hide();+ QTabBar::mousePressEvent(event);+}++//-----------------------------------------------------------------------------+/*! If Ctrl+Left button is pressed, allow tab reordering by emitting movePage signal+ */+void BrushPresetTabBar::mouseMoveEvent(QMouseEvent *event) {+ if (event->buttons() == Qt::LeftButton &&+ event->modifiers() == Qt::ControlModifier) {+ int srcIndex = currentIndex();+ int dstIndex = tabAt(event->pos());+ if (dstIndex >= 0 && dstIndex < count() && dstIndex != srcIndex) {+ QRect rect = tabRect(srcIndex);+ int x = event->pos().x();+ if (x < rect.left() || x > rect.right()) {+ emit movePage(srcIndex, dstIndex);+ }+ }+ }+ QTabBar::mouseMoveEvent(event);+}++//-----------------------------------------------------------------------------+/*! Set a text field with focus in event position to edit tab name+ */+void BrushPresetTabBar::mouseDoubleClickEvent(QMouseEvent *event) {+ int index = tabAt(event->pos());+ if (index < 0) return;++ m_renameTabIndex = index;+ DVGui::LineEdit *fld = m_renameTextField;+ fld->setText(tabText(index));+ fld->setGeometry(tabRect(index));+ fld->setAlignment(Qt::AlignCenter);+ fld->show();+ fld->selectAll();+ fld->setFocus(Qt::OtherFocusReason);+}++//-----------------------------------------------------------------------------+/*! Update tab name from rename text field+ */+void BrushPresetTabBar::updateTabName() {+ int index = m_renameTabIndex;+ if (index < 0) return;++ m_renameTabIndex = -1;+ if (m_renameTextField->text() != "" && m_renameTextField->text() != tabText(index)) {+ setTabText(index, m_renameTextField->text());+ emit tabTextChanged(index);+ }+ m_renameTextField->hide();+}++//-----------------------------------------------------------------------------+/*! Show context menu for page operations (like Level Palette)+ */+void BrushPresetTabBar::contextMenuEvent(QContextMenuEvent *event) {+ if (!m_panel) {+ QTabBar::contextMenuEvent(event);+ return;+ }++ int tabIndex = tabAt(event->pos());++ QMenu menu(this);++ // Add New Page action (always available)+ QAction *addPageAction = menu.addAction(tr("New Page"));+ connect(addPageAction, &QAction::triggered, [this]() {+ if (m_panel) m_panel->addNewPage();+ });++ // Delete Page action (only if clicking on a tab and not the last page)+ if (tabIndex >= 0 && count() > 1) {+ menu.addSeparator();+ QAction *deletePageAction = menu.addAction(tr("Delete Page"));+ connect(deletePageAction, &QAction::triggered, [this, tabIndex]() {+ if (m_panel) m_panel->deletePage(tabIndex);+ });+ }++ menu.exec(event->globalPos());+}+//=============================================================================// BrushPresetPanel implementation//=============================================================================BrushPresetPanel::BrushPresetPanel(QWidget *parent): TPanel(parent)+ , m_tabBarContainer(nullptr)+ , m_tabBar(nullptr), m_scrollArea(nullptr), m_presetContainer(nullptr), m_presetLayout(nullptr), m_addPresetButton(nullptr), m_removePresetButton(nullptr), m_refreshButton(nullptr)+ , m_nonDestructiveToggle(nullptr)+ , m_selectivePresetToggle(nullptr)+ , m_plainColorButton(nullptr), m_toolLabel(nullptr), m_viewModeButton(nullptr), m_viewModeMenu(nullptr)@@ -582,20 +1278,25 @@ BrushPresetPanel::BrushPresetPanel(QWidget *parent), m_presetNamePopup(nullptr), m_viewMode(GridLarge), m_currentColumns(2)- , m_showBorders(false) // Borders disabled by default- , m_showBackgrounds(true) { // Backgrounds enabled by default-+ , m_showBorders(false)+ , m_showBackgrounds(true)+ , m_useSampleStrokes(false)+ , m_currentPageIndex(0)+ , m_checkboxMode(false)+ , m_clipboardIsCut(false)+ , m_suppressRefresh(false) {+// Load preferences from TEnv FIRST (before creating UI)- m_showBorders = BrushPresetPanelShowBorders != 0;+ m_showBorders = BrushPresetPanelShowBorders != 0;m_showBackgrounds = BrushPresetPanelShowBackgrounds != 0;-+ m_useSampleStrokes = BrushPresetPanelUseSampleStrokes != 0;// Load view mode (default: GridLarge)int savedViewMode = static_cast<int>(BrushPresetPanelViewMode);- m_viewMode = static_cast<ViewMode>(savedViewMode);-+ m_viewMode = static_cast<ViewMode>(savedViewMode);+// NOW initialize UI (menu will be created with correct m_viewMode)initializeUI();-+// Apply restored view mode (updates the layout)setViewMode(m_viewMode);}@@ -606,15 +1307,18 @@ BrushPresetPanel::~BrushPresetPanel() {delete m_presetNamePopup;m_presetNamePopup = nullptr;}++ // Clean up all pages+ clearPages();}void BrushPresetPanel::initializeUI() {// Main widget- QWidget *mainWidget = new QWidget(this);+ QWidget *mainWidget = new QWidget(this);QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget);mainLayout->setMargin(5);mainLayout->setSpacing(5);-+// Label for displaying active tool (theme-aware colors)m_toolLabel = new QLabel(tr("No brush tool selected"), mainWidget);m_toolLabel->setAlignment(Qt::AlignCenter);@@ -623,119 +1327,249 @@ void BrushPresetPanel::initializeUI() {// The label will follow the panel's theme automaticallym_toolLabel->setMinimumHeight(28);mainLayout->addWidget(m_toolLabel);-+// Vertical spacing between header and button barmainLayout->addSpacing(8);-- // Button bar at top++ // Button bar at top (matching Level Palette + Tool Options Bar logic)QHBoxLayout *buttonLayout = new QHBoxLayout();-- // Use native OpenToonz icons matching ToolOptionBar design++ // New Page button (like Level Palette - separate from presets)+ QPushButton *newPageButton = new QPushButton(mainWidget);+ newPageButton->setIcon(createQIcon("newpage"));+ newPageButton->setIconSize(QSize(20, 20));+ newPageButton->setFixedSize(24, 24);+ newPageButton->setToolTip(tr("New Page"));+ connect(newPageButton, SIGNAL(clicked()), this, SLOT(onAddPageClicked()));++ // Separator after page button+ QFrame *separator1 = new QFrame(mainWidget);+ separator1->setFrameShape(QFrame::VLine);+ separator1->setFrameShadow(QFrame::Sunken);++ // PRESET BUTTONS (mirror of Tool Options Bar)+ // Remove Preset button (minus icon like Tool Options Bar)m_removePresetButton = new QPushButton(mainWidget);m_removePresetButton->setIcon(createQIcon("minus"));m_removePresetButton->setIconSize(QSize(16, 16));m_removePresetButton->setFixedSize(24, 24);- m_removePresetButton->setToolTip(tr("Remove selected preset"));+ m_removePresetButton->setToolTip(tr("Remove Preset"));m_removePresetButton->setEnabled(false);-++ // Add Preset button (plus icon like Tool Options Bar)m_addPresetButton = new QPushButton(mainWidget);m_addPresetButton->setIcon(createQIcon("plus"));m_addPresetButton->setIconSize(QSize(16, 16));m_addPresetButton->setFixedSize(24, 24);- m_addPresetButton->setToolTip(tr("Add current settings as new preset"));+ m_addPresetButton->setToolTip(tr("Add Preset"));m_addPresetButton->setEnabled(false);-- // Refresh button with circular arrow icon (repeat)++ // Separator after preset buttons+ QFrame *separator2 = new QFrame(mainWidget);+ separator2->setFrameShape(QFrame::VLine);+ separator2->setFrameShadow(QFrame::Sunken);++ // Refresh buttonm_refreshButton = new QPushButton(mainWidget);m_refreshButton->setIcon(createQIcon("repeat"));m_refreshButton->setIconSize(QSize(16, 16));m_refreshButton->setFixedSize(24, 24);m_refreshButton->setToolTip(tr("Refresh preset list"));m_refreshButton->setEnabled(true);-- // Hamburger menu for display modes - use standard OpenToonz menu icon++ // Separator before smart preset toggles+ QFrame *separator3 = new QFrame(mainWidget);+ separator3->setFrameShape(QFrame::VLine);+ separator3->setFrameShadow(QFrame::Sunken);+ separator3->setStyleSheet("QFrame { color: rgba(128,128,128,80); }");++ // Non-Destructive toggle (protects existing strokes by not overwriting styles)+ m_nonDestructiveToggle = new QToolButton(mainWidget);+ m_nonDestructiveToggle->setIcon(createQIcon("lock"));+ m_nonDestructiveToggle->setIconSize(QSize(14, 14));+ m_nonDestructiveToggle->setFixedSize(20, 20);+ m_nonDestructiveToggle->setCheckable(true);+ m_nonDestructiveToggle->setToolTip(tr("Non-Destructive"));++ // Selective Preset toggle (applies only tool parameters, ignores style snapshot)+ m_selectivePresetToggle = new QToolButton(mainWidget);+ m_selectivePresetToggle->setIcon(createQIcon("preset"));+ m_selectivePresetToggle->setIconSize(QSize(14, 14));+ m_selectivePresetToggle->setFixedSize(20, 20);+ m_selectivePresetToggle->setCheckable(true);+ m_selectivePresetToggle->setToolTip(tr("Selective Preset"));++ // Plain Color button (removes style overlay, restores solid color)+ m_plainColorButton = new QToolButton(mainWidget);+ m_plainColorButton->setIcon(createQIcon("plaincolor"));+ m_plainColorButton->setIconSize(QSize(14, 14));+ m_plainColorButton->setFixedSize(20, 20);+ m_plainColorButton->setToolTip(tr("Plain Color"));++ // Restore toggle states from TEnv+ {+ bool nd = BrushPresetPanelNonDestructive != 0;+ bool sp = BrushPresetPanelSelectivePreset != 0;+ m_nonDestructiveToggle->setChecked(nd);+ m_selectivePresetToggle->setChecked(sp);+ BrushPresetBridge::setNonDestructiveMode(nd);+ BrushPresetBridge::setSelectivePresetMode(sp);+ }++ // Hamburger menu for display modesm_viewModeButton = new QPushButton(mainWidget);m_viewModeButton->setIcon(createQIcon("menu"));- m_viewModeButton->setFixedSize(24, 24); // Match Level Palette button size+ m_viewModeButton->setFixedSize(24, 24);m_viewModeButton->setToolTip(tr("View mode"));-++ // Layout: [NewPage] | [-] [+] | [Refresh] | [Lock] [Selective] [PlainColor] ... [Menu]+ buttonLayout->addWidget(newPageButton);+ buttonLayout->addWidget(separator1);buttonLayout->addWidget(m_removePresetButton);buttonLayout->addWidget(m_addPresetButton);+ buttonLayout->addWidget(separator2);buttonLayout->addWidget(m_refreshButton);+ buttonLayout->addWidget(separator3);+ buttonLayout->addWidget(m_nonDestructiveToggle);+ buttonLayout->addWidget(m_selectivePresetToggle);+ buttonLayout->addWidget(m_plainColorButton);buttonLayout->addStretch();buttonLayout->addWidget(m_viewModeButton);-+mainLayout->addLayout(buttonLayout);-++ // Tab bar container with top+bottom separator (like PaletteViewer).+ // TabBarContainter draws only the BOTTOM line via its paintEvent.+ // We wrap it in a container QFrame with a top border drawn via stylesheet+ // to ensure the top line is always visible regardless of theme.+ QFrame *tabContainerFrame = new QFrame(mainWidget);+ tabContainerFrame->setObjectName("BrushPresetTabContainerFrame");+ tabContainerFrame->setStyleSheet(+ "QFrame#BrushPresetTabContainerFrame {"+ " border-top: 1px solid palette(dark);"+ " border-left: none;"+ " border-right: none;"+ " border-bottom: none;"+ " padding: 0px;"+ " margin: 0px;"+ "}"+ );+ QVBoxLayout *tabContainerLayout = new QVBoxLayout(tabContainerFrame);+ tabContainerLayout->setContentsMargins(0, 0, 0, 0);+ tabContainerLayout->setSpacing(0);++ m_tabBarContainer = new TabBarContainter(tabContainerFrame);+ m_tabBar = new BrushPresetTabBar(m_tabBarContainer);+ m_tabBar->setBrushPresetPanel(this);++ // Layout for tab bar inside container (same as PaletteViewer::m_hLayout)+ QHBoxLayout *tabLayout = new QHBoxLayout;+ tabLayout->setContentsMargins(0, 0, 0, 0);+ tabLayout->setSpacing(0);+ tabLayout->addWidget(m_tabBar, 0);+ tabLayout->addStretch(1);+ m_tabBarContainer->setLayout(tabLayout);++ // Add TabBarContainter into the outer frame (which draws the top border)+ tabContainerLayout->addWidget(m_tabBarContainer);+ mainLayout->addWidget(tabContainerFrame, 0);+// Scrollable container for presetsm_scrollArea = new QScrollArea(mainWidget);m_scrollArea->setWidgetResizable(true);m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);-+m_presetContainer = new QWidget();- m_presetLayout = new QGridLayout(m_presetContainer);+ m_presetLayout = new QGridLayout(m_presetContainer);m_presetLayout->setMargin(5);m_presetLayout->setSpacing(8);m_presetLayout->setAlignment(Qt::AlignTop);-+m_presetContainer->setLayout(m_presetLayout);m_scrollArea->setWidget(m_presetContainer);-+mainLayout->addWidget(m_scrollArea, 1);-+setWidget(mainWidget);- setWindowTitle(tr("Brush Presets") +- tr(" [WIP]")); // Temporarily add WIP label-+ setWindowTitle(tr("Brush Presets"));+// Enable context menusetContextMenuPolicy(Qt::DefaultContextMenu);-+// Create display modes menucreateViewModeMenu();-+// Connect buttons- connect(m_addPresetButton, SIGNAL(clicked()), this,- SLOT(onAddPresetClicked()));- connect(m_removePresetButton, SIGNAL(clicked()), this,- SLOT(onRemovePresetClicked()));+ connect(m_addPresetButton, SIGNAL(clicked()), this, SLOT(onAddPresetClicked()));+ connect(m_removePresetButton, SIGNAL(clicked()), this, SLOT(onRemovePresetClicked()));connect(m_refreshButton, SIGNAL(clicked()), this, SLOT(onRefreshClicked()));+ connect(m_nonDestructiveToggle, SIGNAL(toggled(bool)),+ this, SLOT(onNonDestructiveToggled(bool)));+ connect(m_selectivePresetToggle, SIGNAL(toggled(bool)),+ this, SLOT(onSelectivePresetToggled(bool)));+ connect(m_plainColorButton, SIGNAL(clicked()), this, SLOT(onPlainColorClicked()));}void BrushPresetPanel::connectSignals() {if (!m_toolHandle) {TApplication *app = TApp::instance();- m_toolHandle = app->getCurrentTool();+ m_toolHandle = app->getCurrentTool();}-+if (m_toolHandle) {connect(m_toolHandle, SIGNAL(toolSwitched()), this, SLOT(onToolSwitched()));connect(m_toolHandle, SIGNAL(toolChanged()), this, SLOT(onToolChanged()));- connect(m_toolHandle, SIGNAL(toolComboBoxListChanged(std::string)), this,- SLOT(onToolComboBoxListChanged(std::string)));+ connect(m_toolHandle, SIGNAL(toolComboBoxListChanged(std::string)),+ this, SLOT(onToolComboBoxListChanged(std::string)));+ }++ // Tab bar signals+ if (m_tabBar) {+ connect(m_tabBar, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)));+ connect(m_tabBar, SIGNAL(tabTextChanged(int)), this, SLOT(onTabTextChanged(int)));+ connect(m_tabBar, SIGNAL(movePage(int, int)), this, SLOT(onTabMoved(int, int)));}}void BrushPresetPanel::disconnectSignals() {if (m_toolHandle) {- disconnect(m_toolHandle, SIGNAL(toolSwitched()), this,- SLOT(onToolSwitched()));- disconnect(m_toolHandle, SIGNAL(toolChanged()), this,- SLOT(onToolChanged()));- disconnect(m_toolHandle, SIGNAL(toolComboBoxListChanged(std::string)), this,- SLOT(onToolComboBoxListChanged(std::string)));+ disconnect(m_toolHandle, SIGNAL(toolSwitched()), this, SLOT(onToolSwitched()));+ disconnect(m_toolHandle, SIGNAL(toolChanged()), this, SLOT(onToolChanged()));+ disconnect(m_toolHandle, SIGNAL(toolComboBoxListChanged(std::string)),+ this, SLOT(onToolComboBoxListChanged(std::string)));+ }++ // Tab bar signals+ if (m_tabBar) {+ disconnect(m_tabBar, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)));+ disconnect(m_tabBar, SIGNAL(tabTextChanged(int)), this, SLOT(onTabTextChanged(int)));+ disconnect(m_tabBar, SIGNAL(movePage(int, int)), this, SLOT(onTabMoved(int, int)));}}void BrushPresetPanel::showEvent(QShowEvent *e) {TPanel::showEvent(e);- // Refresh brush preset commands to ensure they're up-to-date- // (same approach as ShortcutPopup and CustomPanelEditorPopup)+ // Reconnect signals immediately so the panel stays reactive.ToolPresetCommandManager::instance()->refreshPresetCommands();-connectSignals();- onToolSwitched(); // Initialize display++ // Detect the current tool type right now so that the label and tab+ // state are correct before the first paint, but defer the heavyweight+ // widget reconstruction (N file I/Os + N widget allocations) to the+ // next event-loop iteration. This keeps room switching instantaneous.+ QString newToolType = detectCurrentToolType();+ if (newToolType != m_currentToolType) {+ m_currentToolType = newToolType;+ initializeTabs();+ // Update the tool label immediately so the panel doesn't look stale.+ updateCheckedStates();+ }++ QTimer::singleShot(0, this, [this]() {+ if (isVisible()) refreshPresetList();+ });}void BrushPresetPanel::hideEvent(QHideEvent *e) {@@ -745,14 +1579,22 @@ void BrushPresetPanel::hideEvent(QHideEvent *e) {void BrushPresetPanel::enterEvent(QEvent *e) {TPanel::enterEvent(e);- // Refresh automatically when mouse enters panel- refreshPresetList();++ // Check if tool type changed (e.g., level switched while panel wasn't focused)+ QString currentType = detectCurrentToolType();+ if (!currentType.isEmpty() && currentType != m_currentToolType) {+ // Tool type changed externally - full refresh+ m_currentToolType = currentType;+ initializeTabs();+ refreshPresetList();+ }+ // No full refresh on every enter - avoids resetting page state}void BrushPresetPanel::reset() {clearPresetList();m_currentToolType = "";- m_currentPreset = "";+ m_currentPreset = "";m_toolLabel->setText(tr("No brush tool selected"));m_addPresetButton->setEnabled(false);m_removePresetButton->setEnabled(false);@@ -765,52 +1607,40 @@ void BrushPresetPanel::reset() {QString BrushPresetPanel::detectCurrentToolType() {TTool *tool = getCurrentBrushTool();if (!tool) return "";-+std::string toolName = tool->getName();- int targetType = tool->getTargetType();-- // Determine brush type based on name and target type+ int targetType = tool->getTargetType();++ // CRITICAL: Return ONLY the LEVEL type, NOT the style/engine type.+ // Pages are organized per level type (vector, toonzraster, raster).+ // The active style (MyPaint, Texture, Generated, etc.) only affects+ // the display label, NOT the page key. This ensures pages remain+ // stable when the user changes styles on the same level.if (toolName == T_Brush || toolName == T_PaintBrush || toolName == T_Eraser) {if (targetType & TTool::VectorImage) {return "vector";} else if (targetType & TTool::ToonzImage) {- // Check if it's a MyPaint brush on Toonz Raster- TApplication *app = TApp::instance();- if (app) {- TColorStyle *style = app->getCurrentLevelStyle();- if (dynamic_cast<TMyPaintBrushStyle *>(style)) {- return "mypainttnz";- }- }return "toonzraster";} else if (targetType & TTool::RasterImage) {- // Check if it's a MyPaint brush on Raster- TApplication *app = TApp::instance();- if (app) {- TColorStyle *style = app->getCurrentLevelStyle();- if (dynamic_cast<TMyPaintBrushStyle *>(style)) {- return "mypaint";- }- }return "raster";}}-+return "";}-TTool *BrushPresetPanel::getCurrentBrushTool() {+TTool* BrushPresetPanel::getCurrentBrushTool() {if (!m_toolHandle) return nullptr;-+TTool *tool = m_toolHandle->getTool();if (!tool) return nullptr;-+// Check if it's a brush toolstd::string toolName = tool->getName();if (toolName == T_Brush || toolName == T_PaintBrush || toolName == T_Eraser) {return tool;}-+return nullptr;}@@ -820,20 +1650,20 @@ TTool *BrushPresetPanel::getCurrentBrushTool() {QList<QString> BrushPresetPanel::loadPresetsForTool(const QString &toolType) {QList<QString> presets;-+// Get presets from tool's TEnumProperty// which has already loaded all presets from filesTTool *tool = getCurrentBrushTool();if (!tool) return presets;-+TPropertyGroup *props = tool->getProperties(0);if (!props) return presets;-+// Find "Preset:" propertyfor (int i = 0; i < props->getPropertyCount(); ++i) {TProperty *prop = props->getProperty(i);if (prop->getName() == "Preset:") {- TEnumProperty *presetProp = dynamic_cast<TEnumProperty *>(prop);+ TEnumProperty *presetProp = dynamic_cast<TEnumProperty*>(prop);if (presetProp) {// Get all enumeration values (unordered)const TEnumProperty::Range &range = presetProp->getRange();@@ -845,147 +1675,221 @@ QList<QString> BrushPresetPanel::loadPresetsForTool(const QString &toolType) {allPresets.append(presetName);}}-+// Try to load custom order from fileQString orderFileName;if (toolType == "vector") {orderFileName = "brush_vector_order.txt";} else if (toolType == "toonzraster") {orderFileName = "brush_toonzraster_order.txt";- } else if (toolType == "raster" || toolType == "mypaint" ||- toolType == "mypainttnz") {+ } else if (toolType == "raster") {orderFileName = "brush_raster_order.txt";}-+if (!orderFileName.isEmpty()) {- TFilePath orderFilePath =- TEnv::getConfigDir() + orderFileName.toStdString();+ TFilePath orderFilePath = TEnv::getConfigDir() + orderFileName.toStdString();QFile orderFile(orderFilePath.getQString());-- if (orderFile.exists() &&- orderFile.open(QIODevice::ReadOnly | QIODevice::Text)) {++ if (orderFile.exists() && orderFile.open(QIODevice::ReadOnly | QIODevice::Text)) {QTextStream in(&orderFile);QSet<QString> addedPresets; // Track already added presets-+while (!in.atEnd()) {QString presetName = in.readLine().trimmed();- if (!presetName.isEmpty() && allPresets.contains(presetName) &&- !addedPresets.contains(presetName)) {+ if (!presetName.isEmpty() && allPresets.contains(presetName) && !addedPresets.contains(presetName)) {presets.append(presetName);addedPresets.insert(presetName);}}orderFile.close();-+// Add any missing presets (new presets not in order file yet)for (const QString &preset : allPresets) {if (!addedPresets.contains(preset)) {presets.append(preset);}}-+return presets;}}-+// No order file found, return alphabetical orderpresets = allPresets;}break;}}-+return presets;}void BrushPresetPanel::refreshPresetList() {clearPresetList();-+// Delete old button group and create a new oneif (m_presetButtonGroup) {delete m_presetButtonGroup;}m_presetButtonGroup = new QButtonGroup(this);m_presetButtonGroup->setExclusive(true); // Only one button checked at a time-- QString toolType = detectCurrentToolType();-++ // Use m_currentToolType which is set by onToolSwitched/onToolChanged+ // before calling this method. Fall back to detection if not set yet.+ QString toolType = m_currentToolType;+ if (toolType.isEmpty()) {+ toolType = detectCurrentToolType();+ }+if (toolType.isEmpty()) {m_toolLabel->setText(tr("No brush tool selected"));m_addPresetButton->setEnabled(false);m_removePresetButton->setEnabled(false);return;}-+m_currentToolType = toolType;-- // Update label++ // Update label: detect the active STYLE sub-type for display only.+ // This does NOT affect page storage (pages are keyed by level type only).QString toolDisplayName;+ TApplication *labelApp = TApp::instance();+ TColorStyle *activeStyle = labelApp ? labelApp->getCurrentLevelStyle() : nullptr;+if (toolType == "vector") {- toolDisplayName = tr("Vector Brush");+ if (dynamic_cast<TVectorBrushStyle*>(activeStyle)) {+ toolDisplayName = tr("Custom Vector Brush");+ } else if (dynamic_cast<TTextureStyle*>(activeStyle)) {+ toolDisplayName = tr("Vector Texture");+ } else if (activeStyle && !dynamic_cast<TSolidColorStyle*>(activeStyle)) {+ std::string brushId = activeStyle->getBrushIdName();+ if (brushId.find("VectorImagePatternStrokeStyle:") == 0 ||+ brushId.find("RasterImagePatternStrokeStyle:") == 0) {+ toolDisplayName = tr("Vector Trail");+ } else {+ toolDisplayName = tr("Vector Generated");+ }+ } else {+ toolDisplayName = tr("Vector Brush");+ }} else if (toolType == "toonzraster") {- toolDisplayName = tr("Toonz Raster Brush");- } else if (toolType == "mypaint") {- toolDisplayName = tr("MyPaint Brush");- } else if (toolType == "mypainttnz") {- toolDisplayName = tr("MyPaint Brush Tnz");+ if (dynamic_cast<TMyPaintBrushStyle*>(activeStyle)) {+ toolDisplayName = tr("MyPaint Brush Tnz");+ } else if (dynamic_cast<TTextureStyle*>(activeStyle)) {+ toolDisplayName = tr("Toonz Raster Texture");+ } else {+ toolDisplayName = tr("Toonz Raster Brush");+ }} else if (toolType == "raster") {- toolDisplayName = tr("Raster Brush");+ if (dynamic_cast<TMyPaintBrushStyle*>(activeStyle)) {+ toolDisplayName = tr("MyPaint Brush");+ } else if (dynamic_cast<TTextureStyle*>(activeStyle)) {+ toolDisplayName = tr("Raster Texture");+ } else {+ toolDisplayName = tr("Raster Brush");+ }}m_toolLabel->setText(toolDisplayName);-- m_addPresetButton->setEnabled(true);-- // Load all presets for current tool- QList<QString> presets = loadPresetsForTool(toolType);- m_presetCache[toolType] = presets;-- // Calculate optimal number of columns based on panel width- int panelWidth = m_scrollArea->viewport()->width();- QSize itemSize = getItemSizeForViewMode();- int spacing = (m_viewMode == ListView) ? 3 : 8;-- // Calculate optimal number of columns- int optimalColumns =- qMax(1, (panelWidth + spacing) / (itemSize.width() + spacing));-- // Limit according to view mode- int maxColumns = 0;- switch (m_viewMode) {- case ListView:- maxColumns = 1;- break;- case GridSmall:- maxColumns = 6;- break;- case GridMedium:- maxColumns = 4;- break;- case GridLarge:- maxColumns = 3;- break;- default:- maxColumns = optimalColumns;- break;- }-- optimalColumns = qMin(optimalColumns, maxColumns);- m_currentColumns = optimalColumns;-++ // Only T_Brush tool has add/remove preset; T_PaintBrush and T_Eraser do not+ TTool *tool = getCurrentBrushTool();+ m_addPresetButton->setEnabled(tool && tool->getName() == T_Brush);++ // Get current page+ BrushPresetPage *currentPage = getCurrentPage();+ QList<QString> presets;++ if (!currentPage) {+ // No page available - shouldn't happen, but handle gracefully+ return;+ }++ // Load all physically existing presets+ QList<QString> allPresets = loadPresetsForTool(toolType);++ // Show presets that belong to the current page.+ // Take a COPY of the names list since removePreset() modifies the+ // underlying QStringList and would invalidate the range-based iterator.+ bool hasDeletedPresets = false;+ if (currentPage->getPresetCount() > 0) {+ QStringList pageNames = currentPage->getPresetNames();+ for (const QString &presetName : pageNames) {+ if (allPresets.contains(presetName)) {+ if (!presets.contains(presetName))+ presets.append(presetName);+ } else {+ currentPage->removePreset(presetName);+ hasDeletedPresets = true;+ }+ }+ }++ if (hasDeletedPresets) {+ savePageConfiguration();+ }++ // ALWAYS check for orphan presets (exist on disk but not in any page).+ // This handles two cases:+ // 1. First launch: Page 1 is empty, all presets are orphans+ // 2. Preset added from ToolOptionBar: new preset not in any page yet+ // Orphans are ALWAYS added to the CURRENT page (not just Page 1).+ QList<BrushPresetPage*> &allPages = m_pages[m_currentToolType];+ bool hasNewOrphans = false;+ for (const QString &presetName : allPresets) {+ bool foundInAnyPage = false;+ for (BrushPresetPage *page : allPages) {+ if (page->hasPreset(presetName)) {+ foundInAnyPage = true;+ break;+ }+ }++ if (!foundInAnyPage) {+ currentPage->addPreset(presetName);+ if (!presets.contains(presetName))+ presets.append(presetName);+ hasNewOrphans = true;+ }+ }++ if (hasNewOrphans) {+ savePageConfiguration();+ }++ // Calculate optimal number of columns based on panel width+ int panelWidth = m_scrollArea->viewport()->width();+ QSize itemSize = getItemSizeForViewMode();+ int spacing = (m_viewMode == ListView) ? 3 : 8;++ // Calculate optimal number of columns+ int optimalColumns = qMax(1, (panelWidth + spacing) / (itemSize.width() + spacing));++ // Limit according to view mode+ int maxColumns = 0;+ switch (m_viewMode) {+ case ListView: maxColumns = 1; break;+ case GridSmall: maxColumns = 6; break;+ case GridMedium: maxColumns = 4; break;+ case GridLarge: maxColumns = 3; break;+ default: maxColumns = optimalColumns; break;+ }++ optimalColumns = qMin(optimalColumns, maxColumns);+ m_currentColumns = optimalColumns;+// Create preset buttons in a gridint row = 0, col = 0;const int numColumns = m_currentColumns;-- // Get active preset- TTool *tool = getCurrentBrushTool();++ // Get active preset (tool already obtained above)TPropertyGroup *props = tool ? tool->getProperties(0) : nullptr;QString currentPresetName;-+if (props) {for (int i = 0; i < props->getPropertyCount(); ++i) {TProperty *prop = props->getProperty(i);if (prop->getName() == "Preset:") {- TEnumProperty *presetProp = dynamic_cast<TEnumProperty *>(prop);+ TEnumProperty *presetProp = dynamic_cast<TEnumProperty*>(prop);if (presetProp) {currentPresetName = QString::fromStdWString(presetProp->getValue());}@@ -993,59 +1897,98 @@ void BrushPresetPanel::refreshPresetList() {}}}++ bool isListMode = (m_viewMode == ListView);+ bool isSmallMode = (m_viewMode == GridSmall);- // Determine if we are in list mode- bool isListMode = (m_viewMode == ListView);+ // Pre-load all preset render data with a SINGLE file open (O(N) instead of+ // the previous O(N²) that opened and scanned the file for every preset).+ // Only do this when sample strokes are enabled — otherwise the data is unused.+ QHash<QString, PresetRenderData> allRenderData;+ if (m_useSampleStrokes)+ allRenderData = loadAllPresetRenderData(toolType);- // Determine if we are in GridSmall mode (for icon size adjustment)- bool isSmallMode = (m_viewMode == GridSmall);+ // Pre-resolve custom icons in one batch pass (2 stat() calls per preset,+ // done here outside the widget construction loop so it's amortised).+ QHash<QString, QString> resolvedIcons;+ for (const QString &presetName : presets)+ resolvedIcons.insert(presetName, BrushPresetItem::findCustomPresetIcon(presetName));for (const QString &presetName : presets) {- BrushPresetItem *item = new BrushPresetItem(presetName, toolType,- isListMode, m_presetContainer);+ // Retrieve pre-loaded data (no disk I/O inside the constructor).+ const QString &iconPath = resolvedIcons.value(presetName);+ PresetRenderData renderData;+ if (iconPath.isEmpty()) {+ // Size presets carry synthetic render data, not loaded from the file.+ if (presetName.startsWith("[Size] ") || presetName.startsWith("[Size ")) {+ QString sizeStr = presetName;+ sizeStr.remove("[Size] ").remove("[Size ").remove("]");+ bool ok;+ double size = sizeStr.toDouble(&ok);+ if (ok) {+ renderData.hasData = true;+ renderData.maxThickness = size;+ renderData.minThickness = size;+ renderData.hardness = 100.0;+ renderData.minOpacity = 100.0;+ renderData.maxOpacity = 100.0;+ renderData.isPencil = false;+ }+ } else {+ renderData = allRenderData.value(presetName);+ }+ }+ BrushPresetItem *item = new BrushPresetItem(+ presetName, toolType, isListMode, m_useSampleStrokes,+ iconPath, renderData, m_presetContainer);+// Apply size according to mode (fixed height, flexible width)item->setMinimumSize(itemSize);item->setMaximumSize(QWIDGETSIZE_MAX, itemSize.height());-- // Apply current border, background, and small mode states++ // Apply current border, background, small mode, and checkbox statesitem->setShowBorders(m_showBorders);item->setShowBackgrounds(m_showBackgrounds);item->setSmallMode(isSmallMode);-+ item->setCheckboxVisible(m_checkboxMode);+ item->setMultiSelected(m_selectedPresets.contains(presetName));+// Add to button group to manage exclusivitym_presetButtonGroup->addButton(item);-+// Mark the active presetif (presetName == currentPresetName) {item->setChecked(true);m_currentPreset = presetName;- m_removePresetButton->setEnabled(true);+ // Enable remove button for valid presets (not <custom>)+ if (presetName != QString::fromStdWString(L"<custom>")) {+ m_removePresetButton->setEnabled(true);+ }}-- connect(item, &BrushPresetItem::presetSelected, this,- &BrushPresetPanel::onPresetItemClicked);- connect(item, &BrushPresetItem::presetReordered, this,- &BrushPresetPanel::reorderPreset);-++ connect(item, &BrushPresetItem::presetSelected,+ this, &BrushPresetPanel::onPresetItemClicked);+ connect(item, &BrushPresetItem::presetReordered,+ this, &BrushPresetPanel::reorderPreset);+m_presetLayout->addWidget(item, row, col);-+col++;if (col >= numColumns) {col = 0;row++;}}-+// Adjust spacing according to view modem_presetLayout->setSpacing(spacing);-+// Apply borders stateupdateItemBorders();-+// If no preset is selected, disable remove button- if (currentPresetName.isEmpty() ||- currentPresetName == QString::fromStdWString(L"<custom>")) {+ if (currentPresetName.isEmpty() || currentPresetName == QString::fromStdWString(L"<custom>")) {m_removePresetButton->setEnabled(false);}}@@ -1067,167 +2010,174 @@ void BrushPresetPanel::clearPresetList() {void BrushPresetPanel::applyPreset(const QString &presetName) {TTool *tool = getCurrentBrushTool();if (!tool) return;-+// Get preset propertyTPropertyGroup *props = tool->getProperties(0);if (!props) return;-+for (int i = 0; i < props->getPropertyCount(); ++i) {TProperty *prop = props->getProperty(i);if (prop->getName() == "Preset:") {- TEnumProperty *presetProp = dynamic_cast<TEnumProperty *>(prop);+ TEnumProperty *presetProp = dynamic_cast<TEnumProperty*>(prop);if (presetProp) {// Change preset valuepresetProp->setValue(presetName.toStdWString());m_currentPreset = presetName;-+// CRUCIAL: Trigger onPropertyChanged to actually load the presettool->onPropertyChanged("Preset:");-+// Notify the system of the changeif (m_toolHandle) {m_toolHandle->notifyToolChanged();}-+// Update checked states of all Custom PanelsToolPresetCommandManager::instance()->updateCheckedStates();}break;}}-+// Update visual selection (QButtonGroup handles exclusivity automatically)for (int i = 0; i < m_presetLayout->count(); ++i) {QLayoutItem *item = m_presetLayout->itemAt(i);- if (BrushPresetItem *presetItem =- dynamic_cast<BrushPresetItem *>(item->widget())) {+ if (BrushPresetItem *presetItem = dynamic_cast<BrushPresetItem*>(item->widget())) {if (presetItem->getPresetName() == presetName) {- presetItem->setChecked(- true); // QButtonGroup will uncheck others automatically+ presetItem->setChecked(true); // QButtonGroup will uncheck others automaticallybreak;}}}-+// Enable remove button except for <custom>- m_removePresetButton->setEnabled(!presetName.isEmpty() &&- presetName !=- QString::fromStdWString(L"<custom>"));+ m_removePresetButton->setEnabled(!presetName.isEmpty() &&+ presetName != QString::fromStdWString(L"<custom>"));}void BrushPresetPanel::addNewPreset() {TTool *tool = getCurrentBrushTool();if (!tool) return;-+// Initialize the popupif (!m_presetNamePopup) {m_presetNamePopup = new PresetNamePopup();}-+if (!m_presetNamePopup->getName().isEmpty()) {m_presetNamePopup->removeName();}-+// Get the namebool ret = m_presetNamePopup->exec();if (!ret) return;-+QString name = m_presetNamePopup->getName();m_presetNamePopup->removeName();-+if (name.isEmpty()) {- QMessageBox::warning(this, tr("Invalid Name"),- tr("Please enter a valid preset name."));+ QMessageBox::warning(this, tr("Invalid Name"),+ tr("Please enter a valid preset name."));return;}-- // Note: Direct call to tool's addPreset method causes linking issues- // because the methods are not exported from tnztools library.- // For now, users can add presets via the Tool Options Bar.- QMessageBox::information(- this, tr("Add Preset"),- tr("Please use the [+] button in the Tool Options Bar to add new "- "presets.\n\n"- "The new preset will automatically appear in this panel."));- return;++ // Use command (handler in tnztools) to avoid LNK2019 when linking from toonz+ if (tool->getName() != T_Brush) return;+ BrushPresetBridge::setPendingPresetName(name);+ CommandManager::instance()->execute(MI_AddBrushPreset);++ // Add new preset to current page+ BrushPresetPage *currentPage = getCurrentPage();+ if (currentPage && !currentPage->hasPreset(name)) {+ currentPage->addPreset(name);+ savePageConfiguration();+ }++ refreshPresetList();+ ToolPresetCommandManager::instance()->markCommandsDirty();+ ToolPresetCommandManager::instance()->refreshPresetCommands();}void BrushPresetPanel::removeCurrentPreset() {if (m_currentPreset.isEmpty()) return;-+TTool *tool = getCurrentBrushTool();if (!tool) return;-++ // Don't remove <custom> preset+ if (m_currentPreset == QString::fromStdWString(L"<custom>")) return;+// Ask for confirmationint ret = QMessageBox::question(this, tr("Remove Preset"),- tr("Are you sure you want to remove the preset '%1'?")- .arg(m_currentPreset),+ tr("Are you sure you want to remove the preset '%1'?").arg(m_currentPreset),QMessageBox::Yes | QMessageBox::No, QMessageBox::No);-+if (ret != QMessageBox::Yes) return;-- // Note: Direct call to tool's removePreset method causes linking issues- // because the methods are not exported from tnztools library.- // For now, users can remove presets via the Tool Options Bar.- QMessageBox::information(- this, tr("Remove Preset"),- tr("Please use the [-] button in the Tool Options Bar to remove "- "presets.\n\n"- "The change will automatically be reflected in this panel."));- return;++ // Remove from current page first+ BrushPresetPage *currentPage = getCurrentPage();+ if (currentPage) {+ currentPage->removePreset(m_currentPreset);+ savePageConfiguration();+ }++ // Use command (handler in tnztools) to avoid LNK2019 when linking from toonz+ if (tool->getName() != T_Brush) return;+ CommandManager::instance()->execute(MI_RemoveBrushPreset);++ m_currentPreset = QString::fromStdWString(L"<custom>");+ m_removePresetButton->setEnabled(false);+ refreshPresetList();+ ToolPresetCommandManager::instance()->markCommandsDirty();+ ToolPresetCommandManager::instance()->refreshPresetCommands();}//-----------------------------------------------------------------------------// Drag & Drop reordering//------------------------------------------------------------------------------void BrushPresetPanel::reorderPreset(const QString &fromPreset,- const QString &toPreset) {+void BrushPresetPanel::reorderPreset(const QString &fromPreset, const QString &toPreset) {if (m_currentToolType.isEmpty()) return;-+// Get order file path based on tool typeQString orderFileName;if (m_currentToolType == "vector") {orderFileName = "brush_vector_order.txt";} else if (m_currentToolType == "toonzraster") {orderFileName = "brush_toonzraster_order.txt";- } else if (m_currentToolType == "raster" || m_currentToolType == "mypaint" ||- m_currentToolType == "mypainttnz") {+ } else if (m_currentToolType == "raster") {orderFileName = "brush_raster_order.txt";} else {return; // Unknown tool type}-+TFilePath orderFilePath = TEnv::getConfigDir() + orderFileName.toStdString();-- // Load current preset list- QList<QString> presets = m_presetCache.value(m_currentToolType);++ // Get current page+ BrushPresetPage *currentPage = getCurrentPage();+ if (!currentPage) return;++ // Get preset list from current page+ QStringList presets = currentPage->getPresetNames();if (presets.isEmpty()) return;-+// Find indicesint fromIndex = presets.indexOf(fromPreset);- int toIndex = presets.indexOf(toPreset);-+ int toIndex = presets.indexOf(toPreset);+if (fromIndex == -1 || toIndex == -1) return;if (fromIndex == toIndex) return;-+// Reorder listpresets.move(fromIndex, toIndex);-- // Save new order to file- QFile file(orderFilePath.getQString());- if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {- QTextStream out(&file);- for (const QString &preset : presets) {- out << preset << "\n";- }- file.close();- }-- // Update cache- m_presetCache[m_currentToolType] = presets;-++ // Update page+ currentPage->setPresetNames(presets);++ // Save configuration+ savePageConfiguration();+// Refresh UIrefreshPresetList();}@@ -1236,11 +2186,104 @@ void BrushPresetPanel::reorderPreset(const QString &fromPreset,// Slots//------------------------------------------------------------------------------void BrushPresetPanel::onToolSwitched() { refreshPresetList(); }+void BrushPresetPanel::onToolSwitched() {+ QString newToolType = detectCurrentToolType();++ // Save previous selection before switching tool type.+ if (!m_currentToolType.isEmpty() && !m_currentPreset.isEmpty()) {+ BrushPresetPage *prevPage = getCurrentPage();+ if (prevPage) {+ prevPage->setLastSelectedPreset(m_currentPreset);+ savePageConfiguration();+ }+ }++ m_currentToolType = newToolType;++ // Rebuild tabs synchronously (lightweight — no file I/O).+ initializeTabs();++ // Defer the heavy widget reconstruction so the level/tool switch feels instant.+ QTimer::singleShot(0, this, [this]() {+ if (isVisible()) refreshPresetList();+ });+}void BrushPresetPanel::onToolChanged() {- // Update checked states (called when tool changes)+ // onToolChanged() fires both when the tool switches and when the level type+ // changes (e.g., selecting a raster level while the brush tool stays active).+ QString newToolType = detectCurrentToolType();+ if (!newToolType.isEmpty() && newToolType != m_currentToolType) {+ // Save the previous selection.+ if (!m_currentToolType.isEmpty() && !m_currentPreset.isEmpty()) {+ BrushPresetPage *prevPage = getCurrentPage();+ if (prevPage) {+ prevPage->setLastSelectedPreset(m_currentPreset);+ savePageConfiguration();+ }+ }++ m_currentToolType = newToolType;++ // Rebuild tabs synchronously (lightweight).+ initializeTabs();++ // Defer the heavy widget reconstruction so level switching feels instant.+ QTimer::singleShot(0, this, [this]() {+ if (isVisible()) refreshPresetList();+ });+ return;+ }++ // Same tool type - update checked states and refresh display label+ // (the style sub-type may have changed, e.g., switched from solid to MyPaint)updateCheckedStates();++ // Update the display label to reflect the current style sub-type+ // without touching the pages or presets+ if (!m_currentToolType.isEmpty()) {+ TApplication *labelApp = TApp::instance();+ TColorStyle *activeStyle = labelApp ? labelApp->getCurrentLevelStyle() : nullptr;+ QString toolDisplayName;++ if (m_currentToolType == "vector") {+ if (dynamic_cast<TVectorBrushStyle*>(activeStyle)) {+ toolDisplayName = tr("Custom Vector Brush");+ } else if (dynamic_cast<TTextureStyle*>(activeStyle)) {+ toolDisplayName = tr("Vector Texture");+ } else if (activeStyle && !dynamic_cast<TSolidColorStyle*>(activeStyle)) {+ std::string brushId = activeStyle->getBrushIdName();+ if (brushId.find("VectorImagePatternStrokeStyle:") == 0 ||+ brushId.find("RasterImagePatternStrokeStyle:") == 0) {+ toolDisplayName = tr("Vector Trail");+ } else {+ toolDisplayName = tr("Vector Generated");+ }+ } else {+ toolDisplayName = tr("Vector Brush");+ }+ } else if (m_currentToolType == "toonzraster") {+ if (dynamic_cast<TMyPaintBrushStyle*>(activeStyle)) {+ toolDisplayName = tr("MyPaint Brush Tnz");+ } else if (dynamic_cast<TTextureStyle*>(activeStyle)) {+ toolDisplayName = tr("Toonz Raster Texture");+ } else {+ toolDisplayName = tr("Toonz Raster Brush");+ }+ } else if (m_currentToolType == "raster") {+ if (dynamic_cast<TMyPaintBrushStyle*>(activeStyle)) {+ toolDisplayName = tr("MyPaint Brush");+ } else if (dynamic_cast<TTextureStyle*>(activeStyle)) {+ toolDisplayName = tr("Raster Texture");+ } else {+ toolDisplayName = tr("Raster Brush");+ }+ }++ if (!toolDisplayName.isEmpty()) {+ m_toolLabel->setText(toolDisplayName);+ }+ }}void BrushPresetPanel::updateCheckedStates() {@@ -1249,36 +2292,40 @@ void BrushPresetPanel::updateCheckedStates() {if (toolType.isEmpty() || toolType != m_currentToolType) {return;}-+TTool *tool = getCurrentBrushTool();if (!tool) return;-+TPropertyGroup *props = tool->getProperties(0);if (!props) return;-+for (int i = 0; i < props->getPropertyCount(); ++i) {TProperty *prop = props->getProperty(i);if (prop->getName() == "Preset:") {- TEnumProperty *presetProp = dynamic_cast<TEnumProperty *>(prop);+ TEnumProperty *presetProp = dynamic_cast<TEnumProperty*>(prop);if (presetProp) {QString newPreset = QString::fromStdWString(presetProp->getValue());if (newPreset != m_currentPreset) {m_currentPreset = newPreset;+ // Update remove button state+ if (newPreset == QString::fromStdWString(L"<custom>")) {+ m_removePresetButton->setEnabled(false);+ } else {+ m_removePresetButton->setEnabled(true);+ }}-- // Always update visual selection (even if m_currentPreset hasn't- // changed) because another panel may have changed the preset++ // Always update visual selection (even if m_currentPreset hasn't changed)+ // because another panel may have changed the presetfor (int j = 0; j < m_presetLayout->count(); ++j) {QLayoutItem *item = m_presetLayout->itemAt(j);- if (BrushPresetItem *presetItem =- dynamic_cast<BrushPresetItem *>(item->widget())) {+ if (BrushPresetItem *presetItem = dynamic_cast<BrushPresetItem*>(item->widget())) {presetItem->setChecked(presetItem->getPresetName() == newPreset);}}-+// Enable/disable remove button- if (newPreset.isEmpty() ||- newPreset == QString::fromStdWString(L"<custom>")) {+ if (newPreset.isEmpty() || newPreset == QString::fromStdWString(L"<custom>")) {m_removePresetButton->setEnabled(false);} else {m_removePresetButton->setEnabled(true);@@ -1289,21 +2336,86 @@ void BrushPresetPanel::updateCheckedStates() {}}-void BrushPresetPanel::onPresetItemClicked(const QString &presetName,- const QString &toolType) {+void BrushPresetPanel::onPresetItemClicked(const QString &presetName, const QString &toolType) {+ // In checkbox mode: toggle multi-selection instead of applying+ if (m_checkboxMode) {+ togglePresetSelection(presetName);+ return;+ }+applyPreset(presetName);++ // Save this selection as the last selected preset for the current page+ BrushPresetPage *currentPage = getCurrentPage();+ if (currentPage) {+ currentPage->setLastSelectedPreset(presetName);+ savePageConfiguration();+ }+}++void BrushPresetPanel::onAddPresetClicked() {+ // Simple: just add new preset (no Shift modifier check)+ addNewPreset();+}++void BrushPresetPanel::onRemovePresetClicked() {+ // Mirror of Tool Options Bar - Remove current preset+ removeCurrentPreset();+}++void BrushPresetPanel::onRefreshClicked() {+ refreshPresetList();}-void BrushPresetPanel::onAddPresetClicked() { addNewPreset(); }+void BrushPresetPanel::onNonDestructiveToggled(bool checked) {+ BrushPresetBridge::setNonDestructiveMode(checked);+ BrushPresetPanelNonDestructive = checked ? 1 : 0;+}-void BrushPresetPanel::onRemovePresetClicked() { removeCurrentPreset(); }+void BrushPresetPanel::onSelectivePresetToggled(bool checked) {+ BrushPresetBridge::setSelectivePresetMode(checked);+ BrushPresetPanelSelectivePreset = checked ? 1 : 0;+}-void BrushPresetPanel::onRefreshClicked() { refreshPresetList(); }+void BrushPresetPanel::onPlainColorClicked() {+ TApplication *app = TApp::instance();+ if (!app) return;+ TPaletteHandle *ph =+ app->getPaletteController()->getCurrentLevelPalette();+ if (!ph) return;+ TPalette *palette = ph->getPalette();+ if (!palette) return;+ int styleIndex = app->getCurrentLevelStyleIndex();+ TColorStyle *currentStyle = palette->getStyle(styleIndex);+ if (!currentStyle) return;+ if (dynamic_cast<TSolidColorStyle *>(currentStyle)) return;++ // Read user-controlled color (TTextureStyle::getMainColor returns the+ // texture's average pixel color, not the user's drawing color).+ TPixel32 color = TPixel32::Black;+ if (dynamic_cast<TTextureStyle *>(currentStyle) &&+ currentStyle->getColorParamCount() > 0)+ color = currentStyle->getColorParamValue(0);+ else+ color = currentStyle->getMainColor();++ TSolidColorStyle *newStyle = new TSolidColorStyle(color);++ TUndo *undo = BrushPresetBridge::createStyleOverwriteUndo(+ palette, styleIndex, currentStyle, newStyle, ph);++ palette->setStyle(styleIndex, newStyle);+ palette->setDirtyFlag(true);+ ph->notifyColorStyleChanged(false);+ TUndoManager::manager()->add(undo);+}void BrushPresetPanel::onToolComboBoxListChanged(std::string id) {// Refresh list if preset combo has changed// This captures additions/deletions from the ToolOptionsBarif (id == "Preset:") {+ // Skip if a compound operation (paste/rename) is in progress+ if (m_suppressRefresh) return;// Force refresh even if we are on the same tool typerefreshPresetList();}@@ -1315,41 +2427,30 @@ void BrushPresetPanel::onToolComboBoxListChanged(std::string id) {void BrushPresetPanel::resizeEvent(QResizeEvent *event) {TPanel::resizeEvent(event);-+// Smart adjustment: adapt number of columns based on width// Only in grid mode (not in list mode)if (m_presetLayout->count() > 0) {int panelWidth = m_scrollArea->viewport()->width();QSize itemSize = getItemSizeForViewMode();- int spacing = m_presetLayout->spacing();-+ int spacing = m_presetLayout->spacing();+// Calculate optimal number of columns- int optimalColumns =- qMax(1, (panelWidth + spacing) / (itemSize.width() + spacing));-+ int optimalColumns = qMax(1, (panelWidth + spacing) / (itemSize.width() + spacing));+// Limit according to view modeint maxColumns = 0;switch (m_viewMode) {- case ListView:- maxColumns = 1;- break;- case GridSmall:- maxColumns = 6;- break;- case GridMedium:- maxColumns = 4;- break;- case GridLarge:- maxColumns = 3;- break;- default:- maxColumns = optimalColumns;- break;+ case ListView: maxColumns = 1; break;+ case GridSmall: maxColumns = 6; break;+ case GridMedium: maxColumns = 4; break;+ case GridLarge: maxColumns = 3; break;+ default: maxColumns = optimalColumns; break;}-+optimalColumns = qMin(optimalColumns, maxColumns);optimalColumns = qMax(1, optimalColumns); // Au moins 1 colonne-+// If number of columns has changed, reorganizeif (optimalColumns != m_currentColumns) {m_currentColumns = optimalColumns;@@ -1360,10 +2461,10 @@ void BrushPresetPanel::resizeEvent(QResizeEvent *event) {void BrushPresetPanel::createViewModeMenu() {m_viewModeMenu = new QMenu(this);-+QActionGroup *viewModeGroup = new QActionGroup(this);viewModeGroup->setExclusive(true);-+// Option List ViewQAction *listAction = new QAction(tr("List"), this);listAction->setCheckable(true);@@ -1371,7 +2472,7 @@ void BrushPresetPanel::createViewModeMenu() {listAction->setChecked(m_viewMode == ListView); // Check if current modeviewModeGroup->addAction(listAction);m_viewModeMenu->addAction(listAction);-+// Option SmallQAction *smallAction = new QAction(tr("Small"), this);smallAction->setCheckable(true);@@ -1379,7 +2480,7 @@ void BrushPresetPanel::createViewModeMenu() {smallAction->setChecked(m_viewMode == GridSmall); // Check if current modeviewModeGroup->addAction(smallAction);m_viewModeMenu->addAction(smallAction);-+// Option MediumQAction *mediumAction = new QAction(tr("Medium"), this);mediumAction->setCheckable(true);@@ -1387,7 +2488,7 @@ void BrushPresetPanel::createViewModeMenu() {mediumAction->setChecked(m_viewMode == GridMedium); // Check if current modeviewModeGroup->addAction(mediumAction);m_viewModeMenu->addAction(mediumAction);-+// Option Large (default)QAction *largeAction = new QAction(tr("Large"), this);largeAction->setCheckable(true);@@ -1395,18 +2496,54 @@ void BrushPresetPanel::createViewModeMenu() {largeAction->setData(static_cast<int>(GridLarge));viewModeGroup->addAction(largeAction);m_viewModeMenu->addAction(largeAction);-- // Connecter les actions++ // Connect view mode actionsconnect(viewModeGroup, &QActionGroup::triggered, [this](QAction *action) {ViewMode mode = static_cast<ViewMode>(action->data().toInt());onViewModeChanged(mode);});-++ // Separator before multi-select option+ m_viewModeMenu->addSeparator();++ // Show Checkboxes option for multi-selection+ QAction *checkboxAction = new QAction(tr("Show Checkboxes"), this);+ checkboxAction->setCheckable(true);+ checkboxAction->setChecked(m_checkboxMode);+ m_viewModeMenu->addAction(checkboxAction);+ connect(checkboxAction, &QAction::triggered, [this, checkboxAction]() {+ m_checkboxMode = checkboxAction->isChecked();+ if (!m_checkboxMode) {+ // Clear multi-selection when disabling checkbox mode+ clearMultiSelection();+ }+ updateCheckboxVisibility();+ });++ // Separator before dynamic rendering options+ m_viewModeMenu->addSeparator();++ // Use Sample Strokes option (for dynamic fallback graphics)+ QAction *sampleStrokesAction = new QAction(tr("Use Sample Strokes"), this);+ sampleStrokesAction->setCheckable(true);+ sampleStrokesAction->setChecked(m_useSampleStrokes);+ m_viewModeMenu->addAction(sampleStrokesAction);+ connect(sampleStrokesAction, &QAction::triggered, [this, sampleStrokesAction]() {+ m_useSampleStrokes = sampleStrokesAction->isChecked();+ // Save preference to TEnv+ BrushPresetPanelUseSampleStrokes = m_useSampleStrokes ? 1 : 0;+ // Refresh display in Brush Preset Panel+ refreshPresetList();+ // Refresh Universal Size icons in Custom Panels+ ToolPresetCommandManager::instance()->refreshSizeCommands();+ });++ // Add Show/Hide submenu+ addShowHideContextMenu(m_viewModeMenu);+// Connect button to show menu manually (no triangle indicator)connect(m_viewModeButton, &QPushButton::clicked, [this]() {- // Show menu below the button- QPoint pos =- m_viewModeButton->mapToGlobal(QPoint(0, m_viewModeButton->height()));+ QPoint pos = m_viewModeButton->mapToGlobal(QPoint(0, m_viewModeButton->height()));m_viewModeMenu->exec(pos);});}@@ -1414,10 +2551,10 @@ void BrushPresetPanel::createViewModeMenu() {void BrushPresetPanel::setViewMode(ViewMode mode) {if (m_viewMode == mode) return;m_viewMode = mode;-+// Update display with new modeupdatePresetItemsSizes();-+// Reorganize gridrefreshPresetList();}@@ -1425,52 +2562,43 @@ void BrushPresetPanel::setViewMode(ViewMode mode) {int BrushPresetPanel::getColumnsForViewMode() const {// For now, default mode: 2 columnsswitch (m_viewMode) {- case ListView:- return 1;- case GridSmall:- return 4;- case GridMedium:- return 3;- case GridLarge:- default:- return 2;+ case ListView: return 1;+ case GridSmall: return 4;+ case GridMedium: return 3;+ case GridLarge:+ default: return 2;}}QSize BrushPresetPanel::getItemSizeForViewMode() const {// Original cell sizes (icons adapt inside)switch (m_viewMode) {- case ListView:- return QSize(200, 40);- case GridSmall:- return QSize(80, 50);- case GridMedium:- return QSize(100, 55);- case GridLarge:- default:- return QSize(120, 60);+ case ListView: return QSize(200, 40);+ case GridSmall: return QSize(80, 50);+ case GridMedium: return QSize(100, 55);+ case GridLarge:+ default: return QSize(120, 60);}}void BrushPresetPanel::updatePresetItemsSizes() {- QSize itemSize = getItemSizeForViewMode();- bool isListMode = (m_viewMode == ListView);+ QSize itemSize = getItemSizeForViewMode();+ bool isListMode = (m_viewMode == ListView);bool isSmallMode = (m_viewMode == GridSmall);-+// Update size of all existing items (fixed height, flexible width)for (int i = 0; i < m_presetLayout->count(); ++i) {QLayoutItem *item = m_presetLayout->itemAt(i);- if (BrushPresetItem *presetItem =- dynamic_cast<BrushPresetItem *>(item->widget())) {+ if (BrushPresetItem *presetItem = dynamic_cast<BrushPresetItem*>(item->widget())) {presetItem->setMinimumSize(itemSize);presetItem->setMaximumSize(QWIDGETSIZE_MAX, itemSize.height());- presetItem->setListMode(isListMode); // Update mode+ presetItem->setListMode(isListMode); // Update modepresetItem->setSmallMode(isSmallMode); // Update small mode for icon size// Recalculate scaled icon with new sizepresetItem->updateScaledIcon();}}-+// Adjust spacing according to view modeint spacing = (m_viewMode == ListView) ? 3 : 8;m_presetLayout->setSpacing(spacing);@@ -1479,7 +2607,7 @@ void BrushPresetPanel::updatePresetItemsSizes() {void BrushPresetPanel::onViewModeChanged(ViewMode mode) {setViewMode(mode);refreshPresetList();-+// Save view preference in TEnvBrushPresetPanelViewMode = static_cast<int>(mode);}@@ -1490,6 +2618,33 @@ void BrushPresetPanel::onViewModeChanged(ViewMode mode) {void BrushPresetPanel::contextMenuEvent(QContextMenuEvent *event) {QMenu *menu = new QMenu(this);++ // Paste action (available when clipboard has content, even on empty page)+ if (!m_clipboardPresets.isEmpty()) {+ QAction *pasteAction = menu->addAction(+ tr("Paste (%1 preset(s))").arg(m_clipboardPresets.size()));+ connect(pasteAction, &QAction::triggered, [this]() {+ pastePresetsToCurrentPage();+ });+ menu->addSeparator();+ }++ // Smart Preset toggles+ QAction *ndAction = menu->addAction(tr("Non-Destructive"));+ ndAction->setCheckable(true);+ ndAction->setChecked(m_nonDestructiveToggle->isChecked());+ connect(ndAction, &QAction::toggled, m_nonDestructiveToggle, &QToolButton::setChecked);++ QAction *spAction = menu->addAction(tr("Selective Preset"));+ spAction->setCheckable(true);+ spAction->setChecked(m_selectivePresetToggle->isChecked());+ connect(spAction, &QAction::toggled, m_selectivePresetToggle, &QToolButton::setChecked);++ QAction *pcAction = menu->addAction(tr("Plain Color"));+ connect(pcAction, &QAction::triggered, this, &BrushPresetPanel::onPlainColorClicked);++ menu->addSeparator();+addShowHideContextMenu(menu);menu->exec(event->globalPos());delete menu;@@ -1497,28 +2652,26 @@ void BrushPresetPanel::contextMenuEvent(QContextMenuEvent *event) {void BrushPresetPanel::addShowHideContextMenu(QMenu *menu) {QMenu *showHideMenu = menu->addMenu(tr("GUI Show / Hide"));-+// Action to show/hide cell bordersQAction *bordersAction = showHideMenu->addAction(tr("Cell Borders"));bordersAction->setCheckable(true);bordersAction->setChecked(m_showBorders);bordersAction->setData("borders"); // Identifier for slot handler- connect(bordersAction, SIGNAL(triggered()), this,- SLOT(onShowHideActionTriggered()));-+ connect(bordersAction, SIGNAL(triggered()), this, SLOT(onShowHideActionTriggered()));+// Action to show/hide cell backgrounds (for total design control)QAction *backgroundsAction = showHideMenu->addAction(tr("Cell Backgrounds"));backgroundsAction->setCheckable(true);backgroundsAction->setChecked(m_showBackgrounds);backgroundsAction->setData("backgrounds"); // Identifier for slot handler- connect(backgroundsAction, SIGNAL(triggered()), this,- SLOT(onShowHideActionTriggered()));+ connect(backgroundsAction, SIGNAL(triggered()), this, SLOT(onShowHideActionTriggered()));}void BrushPresetPanel::onShowHideActionTriggered() {- QAction *action = qobject_cast<QAction *>(sender());+ QAction *action = qobject_cast<QAction*>(sender());if (!action) return;-+QString actionType = action->data().toString();if (actionType == "borders") {@@ -1538,8 +2691,7 @@ void BrushPresetPanel::updateItemBorders() {// Update borders state of all itemsfor (int i = 0; i < m_presetLayout->count(); ++i) {QLayoutItem *item = m_presetLayout->itemAt(i);- if (BrushPresetItem *presetItem =- dynamic_cast<BrushPresetItem *>(item->widget())) {+ if (BrushPresetItem *presetItem = dynamic_cast<BrushPresetItem*>(item->widget())) {presetItem->setShowBorders(m_showBorders); // Synchronize and redraw}}@@ -1549,19 +2701,17 @@ void BrushPresetPanel::updateItemBackgrounds() {// Update backgrounds state of all itemsfor (int i = 0; i < m_presetLayout->count(); ++i) {QLayoutItem *item = m_presetLayout->itemAt(i);- if (BrushPresetItem *presetItem =- dynamic_cast<BrushPresetItem *>(item->widget())) {- presetItem->setShowBackgrounds(- m_showBackgrounds); // Synchronize and redraw+ if (BrushPresetItem *presetItem = dynamic_cast<BrushPresetItem*>(item->widget())) {+ presetItem->setShowBackgrounds(m_showBackgrounds); // Synchronize and redraw}}}void BrushPresetPanel::reorganizeLayout(int newColumns) {if (newColumns < 1 || m_presetLayout->count() == 0) return;-+// Collect all existing widgets- QList<QWidget *> widgets;+ QList<QWidget*> widgets;while (m_presetLayout->count() > 0) {QLayoutItem *item = m_presetLayout->takeAt(0);if (QWidget *widget = item->widget()) {@@ -1569,7 +2719,7 @@ void BrushPresetPanel::reorganizeLayout(int newColumns) {}delete item;}-+// Reorganize in new gridint row = 0, col = 0;for (QWidget *widget : widgets) {@@ -1581,3 +2731,780 @@ void BrushPresetPanel::reorganizeLayout(int newColumns) {}}}++//-----------------------------------------------------------------------------+// Page access methods (modeled after TPalette)+//-----------------------------------------------------------------------------++BrushPresetPage* BrushPresetPanel::getCurrentPage() {+ return getPage(m_currentPageIndex);+}++BrushPresetPage* BrushPresetPanel::getPage(int pageIndex) {+ if (m_currentToolType.isEmpty()) return nullptr;++ QList<BrushPresetPage*> &pages = m_pages[m_currentToolType];+ if (pageIndex >= 0 && pageIndex < pages.size()) {+ return pages[pageIndex];+ }+ return nullptr;+}++int BrushPresetPanel::getPageCount() const {+ if (m_currentToolType.isEmpty()) return 0;+ return m_pages.value(m_currentToolType).size();+}++void BrushPresetPanel::clearPages() {+ // Delete all pages for all tool types+ for (auto it = m_pages.begin(); it != m_pages.end(); ++it) {+ qDeleteAll(it.value());+ it.value().clear();+ }+ m_pages.clear();+}++//-----------------------------------------------------------------------------+// Multi-selection management+//-----------------------------------------------------------------------------++void BrushPresetPanel::togglePresetSelection(const QString &presetName) {+ if (m_selectedPresets.contains(presetName)) {+ m_selectedPresets.remove(presetName);+ } else {+ m_selectedPresets.insert(presetName);+ }++ // Update checkbox state on the corresponding item widget+ for (int i = 0; i < m_presetLayout->count(); ++i) {+ QLayoutItem *item = m_presetLayout->itemAt(i);+ if (!item || !item->widget()) continue;+ BrushPresetItem *presetItem = qobject_cast<BrushPresetItem*>(item->widget());+ if (presetItem && presetItem->getPresetName() == presetName) {+ presetItem->setMultiSelected(m_selectedPresets.contains(presetName));+ break;+ }+ }+}++void BrushPresetPanel::clearMultiSelection() {+ m_selectedPresets.clear();++ // Clear all checkbox states+ for (int i = 0; i < m_presetLayout->count(); ++i) {+ QLayoutItem *item = m_presetLayout->itemAt(i);+ if (!item || !item->widget()) continue;+ BrushPresetItem *presetItem = qobject_cast<BrushPresetItem*>(item->widget());+ if (presetItem) {+ presetItem->setMultiSelected(false);+ }+ }+}++void BrushPresetPanel::updateCheckboxVisibility() {+ for (int i = 0; i < m_presetLayout->count(); ++i) {+ QLayoutItem *item = m_presetLayout->itemAt(i);+ if (!item || !item->widget()) continue;+ BrushPresetItem *presetItem = qobject_cast<BrushPresetItem*>(item->widget());+ if (presetItem) {+ presetItem->setCheckboxVisible(m_checkboxMode);+ }+ }+}++//-----------------------------------------------------------------------------+// Context menu for presets (copy/cut/paste/delete)+//-----------------------------------------------------------------------------++void BrushPresetPanel::showPresetContextMenu(const QPoint &globalPos, const QString &presetName) {+ QMenu menu(this);++ // Determine the effective selection (if multi-select or single)+ QStringList effectiveSelection;+ if (m_checkboxMode && !m_selectedPresets.isEmpty()) {+ // Use multi-selection+ effectiveSelection = m_selectedPresets.values();+ } else {+ // Use the right-clicked preset+ effectiveSelection.append(presetName);+ }++ int selCount = effectiveSelection.size();++ // Copy+ QAction *copyAction = menu.addAction(+ selCount > 1 ? tr("Copy %1 Presets").arg(selCount) : tr("Copy"));+ connect(copyAction, &QAction::triggered, [this, effectiveSelection]() {+ m_clipboardPresets = effectiveSelection;+ m_clipboardIsCut = false;+ });++ // Cut+ QAction *cutAction = menu.addAction(+ selCount > 1 ? tr("Cut %1 Presets").arg(selCount) : tr("Cut"));+ connect(cutAction, &QAction::triggered, [this, effectiveSelection]() {+ m_clipboardPresets = effectiveSelection;+ m_clipboardIsCut = true;+ });++ // Paste (only if clipboard has content)+ if (!m_clipboardPresets.isEmpty()) {+ QAction *pasteAction = menu.addAction(+ tr("Paste (%1)").arg(m_clipboardPresets.size()));+ connect(pasteAction, &QAction::triggered, [this]() {+ pastePresetsToCurrentPage();+ });+ }++ menu.addSeparator();++ // Delete+ QAction *deleteAction = menu.addAction(+ selCount > 1 ? tr("Delete %1 Presets").arg(selCount) : tr("Delete"));+ connect(deleteAction, &QAction::triggered, [this, effectiveSelection]() {+ // Confirm+ int ret = QMessageBox::question(+ this, tr("Delete Presets"),+ tr("Are you sure you want to permanently delete %1 preset(s)?")+ .arg(effectiveSelection.size()),+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);+ if (ret != QMessageBox::Yes) return;++ // Remove from current page+ BrushPresetPage *currentPage = getCurrentPage();+ if (currentPage) {+ for (const QString &name : effectiveSelection) {+ currentPage->removePreset(name);+ }+ savePageConfiguration();+ }++ // Remove from disk via batch command+ TTool *tool = getCurrentBrushTool();+ if (tool && tool->getName() == T_Brush) {+ for (const QString &name : effectiveSelection) {+ BrushPresetBridge::addPendingRemoveName(name);+ }+ CommandManager::instance()->execute(MI_RemoveBrushPresetByName);+ }++ m_currentPreset = QString::fromStdWString(L"<custom>");+ clearMultiSelection();+ refreshPresetList();+ ToolPresetCommandManager::instance()->markCommandsDirty();+ ToolPresetCommandManager::instance()->refreshPresetCommands();+ });++ // Rename (only for single selection)+ if (selCount == 1) {+ QAction *renameAction = menu.addAction(tr("Rename"));+ connect(renameAction, &QAction::triggered, [this, presetName]() {+ PresetNamePopup popup(this);+ popup.setWindowTitle(tr("Rename Preset"));+ if (popup.exec() == QDialog::Accepted) {+ QString newName = popup.getName().trimmed();+ if (!newName.isEmpty() && newName != presetName) {+ renamePreset(presetName, newName);+ }+ }+ });+ }++ // Separator before page-specific actions+ if (getPageCount() > 1) {+ menu.addSeparator();++ // Move to page submenu+ QMenu *moveToMenu = menu.addMenu(tr("Move to Page"));+ QList<BrushPresetPage*> &pages = m_pages[m_currentToolType];+ for (int i = 0; i < pages.size(); ++i) {+ if (i == m_currentPageIndex) continue; // Skip current page+ QAction *pageAction = moveToMenu->addAction(pages[i]->getName());+ connect(pageAction, &QAction::triggered, [this, effectiveSelection, i]() {+ BrushPresetPage *srcPage = getCurrentPage();+ BrushPresetPage *dstPage = getPage(i);+ if (!srcPage || !dstPage) return;++ for (const QString &name : effectiveSelection) {+ srcPage->removePreset(name);+ if (!dstPage->hasPreset(name)) {+ dstPage->addPreset(name);+ }+ }+ savePageConfiguration();+ clearMultiSelection();+ refreshPresetList();+ });+ }+ }++ // Smart Preset section+ menu.addSeparator();++ QAction *ndAction2 = menu.addAction(tr("Non-Destructive"));+ ndAction2->setCheckable(true);+ ndAction2->setChecked(m_nonDestructiveToggle->isChecked());+ connect(ndAction2, &QAction::toggled, m_nonDestructiveToggle, &QToolButton::setChecked);++ QAction *spAction2 = menu.addAction(tr("Selective Preset"));+ spAction2->setCheckable(true);+ spAction2->setChecked(m_selectivePresetToggle->isChecked());+ connect(spAction2, &QAction::toggled, m_selectivePresetToggle, &QToolButton::setChecked);++ QAction *pcAction2 = menu.addAction(tr("Plain Color"));+ connect(pcAction2, &QAction::triggered, this, &BrushPresetPanel::onPlainColorClicked);++ menu.exec(globalPos);+}++void BrushPresetPanel::copySelectedPresets() {+ if (m_checkboxMode && !m_selectedPresets.isEmpty()) {+ m_clipboardPresets = m_selectedPresets.values();+ } else if (!m_currentPreset.isEmpty()) {+ m_clipboardPresets.clear();+ m_clipboardPresets.append(m_currentPreset);+ }+ m_clipboardIsCut = false;+}++void BrushPresetPanel::cutSelectedPresets() {+ copySelectedPresets();+ m_clipboardIsCut = true;+}++void BrushPresetPanel::pastePresetsToCurrentPage() {+ if (m_clipboardPresets.isEmpty()) return;++ BrushPresetPage *currentPage = getCurrentPage();+ if (!currentPage) return;++ // Suppress intermediate refreshes triggered by MI_AddBrushPreset notifications+ m_suppressRefresh = true;++ if (m_clipboardIsCut) {+ // Cut mode: move presets (same name, remove from source pages)+ for (const QString &presetName : m_clipboardPresets) {+ if (!currentPage->hasPreset(presetName)) {+ currentPage->addPreset(presetName);+ }+ }+ // Remove from all other pages+ QList<BrushPresetPage*> &pages = m_pages[m_currentToolType];+ for (BrushPresetPage *page : pages) {+ if (page == currentPage) continue;+ for (const QString &presetName : m_clipboardPresets) {+ page->removePreset(presetName);+ }+ }+ m_clipboardIsCut = false;+ } else {+ // Copy mode: create true duplicates with unique names+ // This ensures each pasted preset is independent from the original+ for (const QString &presetName : m_clipboardPresets) {+ QString newName = generateUniqueCopyName(presetName);+ if (duplicatePresetInFile(presetName, newName)) {+ currentPage->addPreset(newName);+ }+ }+ }++ m_suppressRefresh = false;++ m_clipboardPresets.clear();+ savePageConfiguration();+ refreshPresetList();+ ToolPresetCommandManager::instance()->markCommandsDirty();+ ToolPresetCommandManager::instance()->refreshPresetCommands();+}++//-----------------------------------------------------------------------------+// Generate a unique copy name (e.g., "MyBrush (Copy)", "MyBrush (Copy 2)")+//-----------------------------------------------------------------------------++QString BrushPresetPanel::generateUniqueCopyName(const QString &baseName) {+ // Collect all known preset names from the tool's Preset: property+ QSet<QString> existingNames;+ TTool *tool = getCurrentBrushTool();+ if (tool) {+ TPropertyGroup *props = tool->getProperties(0);+ if (props) {+ for (int i = 0; i < props->getPropertyCount(); ++i) {+ TProperty *prop = props->getProperty(i);+ if (prop->getName() == "Preset:") {+ TEnumProperty *presetProp = dynamic_cast<TEnumProperty*>(prop);+ if (presetProp) {+ const std::vector<std::wstring> &range = presetProp->getRange();+ for (const std::wstring &w : range) {+ existingNames.insert(QString::fromStdWString(w));+ }+ }+ break;+ }+ }+ }+ }++ // Also check all page references (some presets may be in pages but not yet synced)+ QList<BrushPresetPage*> &pages = m_pages[m_currentToolType];+ for (BrushPresetPage *page : pages) {+ const QStringList &names = page->getPresetNames();+ for (const QString &n : names) {+ existingNames.insert(n);+ }+ }++ // Generate unique name+ QString candidate = baseName + " (Copy)";+ if (!existingNames.contains(candidate)) return candidate;++ for (int i = 2; i < 1000; ++i) {+ candidate = baseName + QString(" (Copy %1)").arg(i);+ if (!existingNames.contains(candidate)) return candidate;+ }++ return baseName + " (Copy)"; // Fallback+}++//-----------------------------------------------------------------------------+// Duplicate a preset: apply the source, then add as new with the given name+//-----------------------------------------------------------------------------++bool BrushPresetPanel::duplicatePresetInFile(const QString &srcName, const QString &newName) {+ TTool *tool = getCurrentBrushTool();+ if (!tool || tool->getName() != T_Brush) return false;++ // Save current preset selection to restore later+ QString previousPreset = m_currentPreset;++ // Step 1: Apply the source preset (loads all its settings into the tool)+ TPropertyGroup *props = tool->getProperties(0);+ if (!props) return false;++ TEnumProperty *presetProp = nullptr;+ for (int i = 0; i < props->getPropertyCount(); ++i) {+ TProperty *prop = props->getProperty(i);+ if (prop->getName() == "Preset:") {+ presetProp = dynamic_cast<TEnumProperty*>(prop);+ break;+ }+ }+ if (!presetProp) return false;++ // Load source preset into tool+ presetProp->setValue(srcName.toStdWString());+ tool->onPropertyChanged("Preset:");++ // Step 2: Add the preset with the new name (saves tool's current state)+ BrushPresetBridge::setPendingPresetName(newName);+ CommandManager::instance()->execute(MI_AddBrushPreset);++ // Step 3: Restore original preset+ if (!previousPreset.isEmpty() &&+ previousPreset != QString::fromStdWString(L"<custom>")) {+ presetProp->setValue(previousPreset.toStdWString());+ tool->onPropertyChanged("Preset:");+ }++ return true;+}++//-----------------------------------------------------------------------------+// Rename a preset: duplicate with new name, then delete the old one+//-----------------------------------------------------------------------------++void BrushPresetPanel::renamePreset(const QString &oldName, const QString &newName) {+ if (oldName.isEmpty() || newName.isEmpty() || oldName == newName) return;++ TTool *tool = getCurrentBrushTool();+ if (!tool || tool->getName() != T_Brush) return;++ // Suppress intermediate refreshes during the compound operation+ m_suppressRefresh = true;++ // Step 1: Duplicate the preset with the new name (old still exists on disk)+ if (!duplicatePresetInFile(oldName, newName)) {+ m_suppressRefresh = false;+ return;+ }++ // Step 2: Remove the old preset from disk+ BrushPresetBridge::addPendingRemoveName(oldName);+ CommandManager::instance()->execute(MI_RemoveBrushPresetByName);++ m_suppressRefresh = false;++ // Step 3: Update all page references in-place (preserves position)+ QList<BrushPresetPage*> &pages = m_pages[m_currentToolType];+ for (BrushPresetPage *page : pages) {+ if (page->hasPreset(oldName)) {+ page->replacePreset(oldName, newName);+ }+ if (page->getLastSelectedPreset() == oldName) {+ page->setLastSelectedPreset(newName);+ }+ }++ // Step 4: Save, refresh, and select the renamed preset+ m_currentPreset = newName;+ savePageConfiguration();+ refreshPresetList();+ ToolPresetCommandManager::instance()->markCommandsDirty();+ ToolPresetCommandManager::instance()->refreshPresetCommands();++ // Apply the renamed preset+ applyPreset(newName);+}++void BrushPresetPanel::deleteSelectedPresets() {+ QStringList toDelete;+ if (m_checkboxMode && !m_selectedPresets.isEmpty()) {+ toDelete = m_selectedPresets.values();+ } else if (!m_currentPreset.isEmpty() &&+ m_currentPreset != QString::fromStdWString(L"<custom>")) {+ toDelete.append(m_currentPreset);+ }++ if (toDelete.isEmpty()) return;++ int ret = QMessageBox::question(+ this, tr("Delete Presets"),+ tr("Are you sure you want to permanently delete %1 preset(s)?")+ .arg(toDelete.size()),+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);+ if (ret != QMessageBox::Yes) return;++ BrushPresetPage *currentPage = getCurrentPage();+ if (currentPage) {+ for (const QString &name : toDelete) {+ currentPage->removePreset(name);+ }+ savePageConfiguration();+ }++ TTool *tool = getCurrentBrushTool();+ if (tool && tool->getName() == T_Brush) {+ for (const QString &name : toDelete) {+ BrushPresetBridge::addPendingRemoveName(name);+ }+ CommandManager::instance()->execute(MI_RemoveBrushPresetByName);+ }++ m_currentPreset = QString::fromStdWString(L"<custom>");+ clearMultiSelection();+ refreshPresetList();+ ToolPresetCommandManager::instance()->markCommandsDirty();+ ToolPresetCommandManager::instance()->refreshPresetCommands();+}++//-----------------------------------------------------------------------------+// Page/Tab management (modeled after Level Palette Editor)+//-----------------------------------------------------------------------------++void BrushPresetPanel::initializeTabs() {+ if (!m_tabBar) return;+ if (m_currentToolType.isEmpty()) return;++ // Block signals to avoid triggering onTabChanged during rebuild+ m_tabBar->blockSignals(true);++ // Remove all existing tabs+ int tabCount = m_tabBar->count();+ for (int i = tabCount - 1; i >= 0; i--) {+ m_tabBar->removeTab(i);+ }++ // Load page configuration for current tool type from TEnv+ // This populates m_pages[m_currentToolType]+ loadPageConfiguration();++ // Get pages for current tool (create default page if none exist)+ QList<BrushPresetPage*> &pages = m_pages[m_currentToolType];+ if (pages.isEmpty()) {+ BrushPresetPage *defaultPage = new BrushPresetPage(tr("Page 1"), 0);+ pages.append(defaultPage);+ }++ // Create tabs with palette icon (same as PaletteViewer::updateTabBar)+ QIcon tabIcon = createQIcon("palette_tab");+ m_tabBar->setIconSize(QSize(16, 16));+ for (int i = 0; i < pages.size(); ++i) {+ m_tabBar->addTab(tabIcon, pages[i]->getName());+ }++ // Set current page (bounded to valid range)+ if (m_currentPageIndex < 0 || m_currentPageIndex >= m_tabBar->count()) {+ m_currentPageIndex = 0;+ }+ m_tabBar->setCurrentIndex(m_currentPageIndex);++ // Unblock signals+ m_tabBar->blockSignals(false);+}++void BrushPresetPanel::updateTabBar() {+ initializeTabs();+}++void BrushPresetPanel::switchToPage(int pageIndex) {+ if (pageIndex < 0 || pageIndex >= m_tabBar->count()) return;++ // Avoid re-entering when setCurrentIndex triggers currentChanged+ if (pageIndex == m_currentPageIndex && m_tabBar->currentIndex() == pageIndex) {+ return;+ }++ // Save last selected preset for previous page BEFORE changing index+ BrushPresetPage *prevPage = getCurrentPage();+ if (prevPage && !m_currentPreset.isEmpty()) {+ prevPage->setLastSelectedPreset(m_currentPreset);+ savePageConfiguration();+ }++ // Change to new page index+ m_currentPageIndex = pageIndex;++ // Block signals temporarily to avoid recursive calls via onTabChanged+ m_tabBar->blockSignals(true);+ m_tabBar->setCurrentIndex(pageIndex);+ m_tabBar->blockSignals(false);++ // Restore last selected preset for new page+ BrushPresetPage *newPage = getCurrentPage();+ QString restoredPreset;+ if (newPage) {+ restoredPreset = newPage->getLastSelectedPreset();+ if (restoredPreset.isEmpty() || !newPage->hasPreset(restoredPreset)) {+ restoredPreset = QString();+ }+ }++ // CRITICAL: Force refresh preset list for current page+ // This ensures we show only presets belonging to this page+ refreshPresetList();++ // After refreshing, restore the selection for this page+ // This applies the preset to the tool AND updates the visual selection+ if (!restoredPreset.isEmpty()) {+ applyPreset(restoredPreset);+ } else {+ // No saved selection for this page - deselect all+ m_currentPreset = QString::fromStdWString(L"<custom>");+ m_removePresetButton->setEnabled(false);+ }+}++void BrushPresetPanel::addNewPage() {+ if (m_currentToolType.isEmpty()) return;++ // Generate new page name+ int pageNum = m_tabBar->count() + 1;+ QString newPageName = tr("Page %1").arg(pageNum);++ // Create new page object+ QList<BrushPresetPage*> &pages = m_pages[m_currentToolType];+ BrushPresetPage *newPage = new BrushPresetPage(newPageName, pages.size());+ pages.append(newPage);++ // Add tab with palette icon+ QIcon tabIcon = createQIcon("palette_tab");+ int newIndex = m_tabBar->addTab(tabIcon, newPageName);++ // Save configuration+ savePageConfiguration();++ // Switch to new page+ switchToPage(newIndex);+}++void BrushPresetPanel::deletePage(int pageIndex) {+ if (pageIndex < 0 || pageIndex >= m_tabBar->count()) return;+ if (m_currentToolType.isEmpty()) return;++ // Don't allow deleting the last page+ if (m_tabBar->count() <= 1) {+ QMessageBox::information(this, tr("Cannot Delete Page"),+ tr("Cannot delete the last page. At least one page must exist."));+ return;+ }++ // Get the page and its presets+ BrushPresetPage *page = getPage(pageIndex);+ if (!page) return;++ QStringList pagePresets = page->getPresetNames();+ QString pageName = m_tabBar->tabText(pageIndex);++ // Confirm deletion with accurate information+ QString message;+ if (pagePresets.isEmpty()) {+ message = tr("Are you sure you want to delete the page '%1'?").arg(pageName);+ } else {+ message = tr("Are you sure you want to delete the page '%1'?\n"+ "This will permanently delete %2 preset(s) contained in this page.")+ .arg(pageName).arg(pagePresets.size());+ }++ int ret = QMessageBox::question(this, tr("Delete Page"), message,+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);+ if (ret != QMessageBox::Yes) return;++ // ACTUALLY delete the presets from disk via the batch remove command.+ // Queue all preset names and execute the batch remove command.+ TTool *tool = getCurrentBrushTool();+ if (tool && tool->getName() == T_Brush && !pagePresets.isEmpty()) {+ for (const QString &presetName : pagePresets) {+ BrushPresetBridge::addPendingRemoveName(presetName);+ }+ CommandManager::instance()->execute(MI_RemoveBrushPresetByName);+ }++ // Delete page object+ QList<BrushPresetPage*> &pages = m_pages[m_currentToolType];+ if (pageIndex < pages.size()) {+ delete pages[pageIndex];+ pages.removeAt(pageIndex);+ for (int i = 0; i < pages.size(); ++i) {+ pages[i]->setIndex(i);+ }+ }++ // Remove tab+ m_tabBar->removeTab(pageIndex);+ savePageConfiguration();++ // Switch to appropriate page+ if (m_currentPageIndex >= m_tabBar->count()) {+ m_currentPageIndex = m_tabBar->count() - 1;+ }+ switchToPage(m_currentPageIndex);++ ToolPresetCommandManager::instance()->markCommandsDirty();+ ToolPresetCommandManager::instance()->refreshPresetCommands();+}++void BrushPresetPanel::renamePage(int pageIndex, const QString &newName) {+ if (pageIndex < 0 || pageIndex >= m_tabBar->count()) return;+ if (m_currentToolType.isEmpty()) return;+ if (newName.isEmpty()) return;++ // Update page object+ BrushPresetPage *page = getPage(pageIndex);+ if (page) {+ page->setName(newName);+ }++ // Update tab text (already done by tab bar, but ensure consistency)+ m_tabBar->setTabText(pageIndex, newName);++ // Save configuration+ savePageConfiguration();+}++void BrushPresetPanel::movePageTab(int srcIndex, int dstIndex) {+ if (srcIndex < 0 || srcIndex >= m_tabBar->count()) return;+ if (dstIndex < 0 || dstIndex >= m_tabBar->count()) return;+ if (srcIndex == dstIndex) return;+ if (m_currentToolType.isEmpty()) return;++ // Update pages list+ QList<BrushPresetPage*> &pages = m_pages[m_currentToolType];+ if (srcIndex < pages.size() && dstIndex < pages.size()) {+ pages.move(srcIndex, dstIndex);++ // Update indices of all pages+ for (int i = 0; i < pages.size(); ++i) {+ pages[i]->setIndex(i);+ }+ }++ // Block signals during tab move to prevent stale refreshes from currentChanged+ m_tabBar->blockSignals(true);+ m_tabBar->moveTab(srcIndex, dstIndex);++ // Update current page index if it was moved+ if (m_currentPageIndex == srcIndex) {+ m_currentPageIndex = dstIndex;+ } else if (srcIndex < m_currentPageIndex && dstIndex >= m_currentPageIndex) {+ m_currentPageIndex--;+ } else if (srcIndex > m_currentPageIndex && dstIndex <= m_currentPageIndex) {+ m_currentPageIndex++;+ }++ // Sync tab bar to the updated current page index+ m_tabBar->setCurrentIndex(m_currentPageIndex);+ m_tabBar->blockSignals(false);++ // Save configuration+ savePageConfiguration();++ // Force refresh to show correct content for the current page after swap+ refreshPresetList();+}++void BrushPresetPanel::savePageConfiguration() {+ if (m_currentToolType.isEmpty()) return;++ const QList<BrushPresetPage *> pages = m_pages.value(m_currentToolType);+ for (int i = 0; i < pages.size(); ++i) {+ if (pages[i]) pages[i]->setIndex(i);+ }++ TEnv::StringVar &pagesEnv = brushPresetPagesEnvForToolType(m_currentToolType);+ pagesEnv =+ serializePageConfiguration(pages, m_currentPageIndex).toStdString();+}++void BrushPresetPanel::loadPageConfiguration() {+ if (m_currentToolType.isEmpty()) return;++ QList<BrushPresetPage *> &pages = m_pages[m_currentToolType];+ qDeleteAll(pages);+ pages.clear();++ const QString serialized =+ QString::fromStdString(+ (std::string)brushPresetPagesEnvForToolType(m_currentToolType));+ int loadedCurrentPage = 0;+ if (!deserializePageConfiguration(serialized, pages, loadedCurrentPage)) {+ BrushPresetPage *defaultPage = new BrushPresetPage(tr("Page 1"), 0);+ pages.append(defaultPage);+ loadedCurrentPage = 0;+ }++ m_currentPageIndex = loadedCurrentPage;+ if (m_currentPageIndex < 0 || m_currentPageIndex >= pages.size()) {+ m_currentPageIndex = 0;+ }+}+++//-----------------------------------------------------------------------------+// Tab/Page slots+//-----------------------------------------------------------------------------++void BrushPresetPanel::onTabChanged(int index) {+ // Only process if index actually changed (avoid recursion)+ if (index < 0 || index == m_currentPageIndex) return;+ switchToPage(index);+}++void BrushPresetPanel::onTabTextChanged(int index) {+ if (index < 0 || index >= m_tabBar->count()) return;+ QString newName = m_tabBar->tabText(index);+ renamePage(index, newName);+}++void BrushPresetPanel::onTabMoved(int srcIndex, int dstIndex) {+ movePageTab(srcIndex, dstIndex);+}++void BrushPresetPanel::onAddPageClicked() {+ addNewPage();+}++void BrushPresetPanel::onDeletePageClicked() {+ if (m_currentPageIndex >= 0 && m_currentPageIndex < m_tabBar->count()) {+ deletePage(m_currentPageIndex);+ }+}+diff --git a/toonz/sources/toonz/brushpresetpanel.h b/toonz/sources/toonz/brushpresetpanel.hindex d12784748..751838d01 100644--- a/toonz/sources/toonz/brushpresetpanel.h+++ b/toonz/sources/toonz/brushpresetpanel.h@@ -11,7 +11,10 @@#include <QToolButton>#include <QLabel>#include <QMap>+#include <QSet>#include <QString>+#include <QStringList>+#include <QTabBar>#include <set>// Forward declarations@@ -19,6 +22,31 @@ class TTool;class ToolHandle;class TApplication;class PresetNamePopup;+class BrushPresetPanel;+class TabBarContainter;++namespace DVGui {+class LineEdit;+}++//=============================================================================+// Preset Rendering Data (for dynamic fallback graphics)+//=============================================================================++// Stores essential visual properties of a preset for rendering+struct PresetRenderData {+ double minThickness;+ double maxThickness;+ double hardness;+ double minOpacity;+ double maxOpacity;+ bool isPencil;+ bool hasData; // true if data was successfully loaded++ PresetRenderData()+ : minThickness(1.0), maxThickness(5.0), hardness(100.0),+ minOpacity(100.0), maxOpacity(100.0), isPencil(false), hasData(false) {}+};//=============================================================================// BrushPresetItem - A widget representing an individual preset@@ -28,7 +56,8 @@ class BrushPresetItem : public QToolButton {Q_OBJECTQString m_presetName;- QString m_toolType; // "vector", "toonzraster", "mypaint", "mypainttnz", or "raster"+ QString m_toolType; // "vector", "toonzraster", or "raster"+ PresetRenderData m_renderData; // Preset visual properties for dynamic renderingQPixmap m_iconPixmap;QPixmap m_scaledIconCache; // Scaled icon (fixed)bool m_hasIcon;@@ -37,12 +66,21 @@ class BrushPresetItem : public QToolButton {bool m_isSmallMode; // true = GridSmall mode (reduce generated icon sizes by 3px)bool m_showBorders; // true = with borders, false = without borders (clean)bool m_showBackgrounds; // true = show backgrounds, false = transparent backgrounds+ bool m_checkboxVisible; // true = show checkbox for multi-select+ bool m_isMultiSelected; // true = checked in multi-select mode+ bool m_useSampleStrokes; // true = use sample strokes for fallback, false = use generic icons// Drag & Drop stateQPoint m_dragStartPosition;public:- BrushPresetItem(const QString &presetName, const QString &toolType, bool isListMode, QWidget *parent = nullptr);+ // Primary constructor: caller provides pre-resolved icon path and render data.+ // No disk I/O is performed — use this in loops via refreshPresetList().+ BrushPresetItem(const QString &presetName, const QString &toolType,+ bool isListMode, bool useSampleStrokes,+ const QString &resolvedIconPath,+ const PresetRenderData &preloadedData,+ QWidget *parent = nullptr);QString getPresetName() const { return m_presetName; }QString getToolType() const { return m_toolType; }@@ -53,10 +91,17 @@ public:void setSmallMode(bool isSmallMode);void setShowBorders(bool showBorders) { m_showBorders = showBorders; update(); }void setShowBackgrounds(bool showBackgrounds) { m_showBackgrounds = showBackgrounds; update(); }+ void setCheckboxVisible(bool visible) { m_checkboxVisible = visible; update(); }+ bool isCheckboxVisible() const { return m_checkboxVisible; }+ void setMultiSelected(bool selected) { m_isMultiSelected = selected; update(); }+ bool isMultiSelected() const { return m_isMultiSelected; }// Update scaled icon (cache) according to current sizevoid updateScaledIcon();-++ // Static so it can be called from refreshPresetList() without an instance.+ static QString findCustomPresetIcon(const QString &presetName);+protected:void paintEvent(QPaintEvent *event) override;QSize sizeHint() const override;@@ -68,15 +113,99 @@ protected:void dragEnterEvent(QDragEnterEvent *event) override;void dragMoveEvent(QDragMoveEvent *event) override;void dropEvent(QDropEvent *event) override;-+private:- QString findCustomPresetIcon(const QString &presetName);+ void drawDynamicFallback(QPainter &painter, const QRect &iconRect) const;signals:void presetSelected(const QString &presetName, const QString &toolType);void presetReordered(const QString &fromPreset, const QString &toPreset);};+//=============================================================================+// BrushPresetPage - Page structure for organizing presets (like TPalette::Page)+//=============================================================================++/*! \brief A preset page contains a list of preset names and remembers the last selected preset+ *+ * Modeled after TPalette::Page structure for consistency.+ */+class BrushPresetPage {+private:+ QString m_name; // Page name displayed in tab+ int m_index; // Page index+ QStringList m_presetNames; // List of preset names in this page+ QString m_lastSelectedPreset; // Last selected preset on this page++public:+ BrushPresetPage(const QString &name, int index = 0)+ : m_name(name), m_index(index) {}++ QString getName() const { return m_name; }+ void setName(const QString &name) { m_name = name; }++ int getIndex() const { return m_index; }+ void setIndex(int index) { m_index = index; }++ const QStringList& getPresetNames() const { return m_presetNames; }+ void setPresetNames(const QStringList &names) { m_presetNames = names; }+ void addPreset(const QString &presetName) {+ if (!m_presetNames.contains(presetName)) m_presetNames.append(presetName);+ }+ void removePreset(const QString &presetName) { m_presetNames.removeAll(presetName); }+ bool hasPreset(const QString &presetName) const { return m_presetNames.contains(presetName); }+ // Replace a preset name in-place (preserves position in the list)+ bool replacePreset(const QString &oldName, const QString &newName) {+ int idx = m_presetNames.indexOf(oldName);+ if (idx < 0) return false;+ m_presetNames[idx] = newName;+ return true;+ }+ int getPresetCount() const { return m_presetNames.size(); }++ QString getLastSelectedPreset() const { return m_lastSelectedPreset; }+ void setLastSelectedPreset(const QString &preset) { m_lastSelectedPreset = preset; }+};++//=============================================================================+// BrushPresetTabBar - Tab bar for organizing presets into pages+//=============================================================================++/*! \brief Custom tab bar with rename and drag & drop support (based on PaletteTabBar)+ *+ * This tab bar allows:+ * - Double-click to rename a tab+ * - Ctrl+Drag to reorder tabs+ * - Right-click context menu for page operations+ * Features are modeled after the Level Palette Editor's tab bar.+ */+class BrushPresetTabBar : public QTabBar {+ Q_OBJECT++public:+ BrushPresetTabBar(QWidget *parent = nullptr);++ void setBrushPresetPanel(BrushPresetPanel *panel) { m_panel = panel; }++public slots:+ void updateTabName();++signals:+ void tabTextChanged(int index);+ void movePage(int srcIndex, int dstIndex);++protected:+ void mousePressEvent(QMouseEvent *event) override;+ void mouseMoveEvent(QMouseEvent *event) override;+ void mouseDoubleClickEvent(QMouseEvent *event) override;+ void contextMenuEvent(QContextMenuEvent *event) override;++private:+ DVGui::LineEdit *m_renameTextField;+ int m_renameTabIndex;+ BrushPresetPanel *m_panel;+};+//=============================================================================// BrushPresetPanel - Dockable panel for brush preset management//=============================================================================@@ -94,12 +223,17 @@ public:private:// UI Components+ TabBarContainter *m_tabBarContainer;+ BrushPresetTabBar *m_tabBar;QScrollArea *m_scrollArea;QWidget *m_presetContainer;QGridLayout *m_presetLayout;QPushButton *m_addPresetButton;QPushButton *m_removePresetButton;QPushButton *m_refreshButton;+ QToolButton *m_nonDestructiveToggle;+ QToolButton *m_selectivePresetToggle;+ QToolButton *m_plainColorButton;QLabel *m_toolLabel;QPushButton *m_viewModeButton;QMenu *m_viewModeMenu;@@ -109,16 +243,30 @@ private:ToolHandle *m_toolHandle;// State- QString m_currentToolType; // "vector", "toonzraster", "raster", or ""+ QString m_currentToolType; // Level type only: "vector", "toonzraster", "raster", or ""QString m_currentPreset;PresetNamePopup *m_presetNamePopup;ViewMode m_viewMode;int m_currentColumns; // Current number of columns (dynamic based on width)bool m_showBorders; // Show or hide cell bordersbool m_showBackgrounds; // Show or hide cell backgrounds (for cleaner appearance)+ bool m_useSampleStrokes; // true = draw sample strokes for fallback, false = use generic icons+ int m_currentPageIndex; // Current selected page/tab index++ // Page/Tab management (modeled after TPalette::Page structure)+ // Key format: "toolType" -> List of BrushPresetPage pointers+ QMap<QString, QList<BrushPresetPage*>> m_pages;++ // Multi-selection state+ bool m_checkboxMode; // true = show checkboxes on each preset+ QSet<QString> m_selectedPresets; // Set of selected preset names (multi-select)++ // Clipboard for copy/cut/paste between pages+ QStringList m_clipboardPresets; // Preset names in clipboard+ bool m_clipboardIsCut; // true = cut (remove from source), false = copy- // Preset storage (to avoid multiple reads)- QMap<QString, QList<QString>> m_presetCache;+ // Guard flag to suppress intermediate refreshes during compound operations+ bool m_suppressRefresh;public:BrushPresetPanel(QWidget *parent = nullptr);@@ -126,6 +274,13 @@ public:void reset() override;+ // Page/Tab management (public for TabBar access)+ void addNewPage();+ void deletePage(int pageIndex);++ // Context menu for presets (public for BrushPresetItem access)+ void showPresetContextMenu(const QPoint &globalPos, const QString &presetName);+protected:void showEvent(QShowEvent *e) override;void hideEvent(QHideEvent *e) override;@@ -169,6 +324,37 @@ private:// Checked state synchronizationvoid updateCheckedStates();+ // Multi-selection+ void togglePresetSelection(const QString &presetName);+ void clearMultiSelection();+ void updateCheckboxVisibility();++ // Context menu actions (showPresetContextMenu is public, above)+ void copySelectedPresets();+ void cutSelectedPresets();+ void pastePresetsToCurrentPage();+ void deleteSelectedPresets();++ // Preset duplication and renaming+ QString generateUniqueCopyName(const QString &baseName);+ bool duplicatePresetInFile(const QString &srcName, const QString &newName);+ void renamePreset(const QString &oldName, const QString &newName);++ // Page/Tab management (internal methods)+ void initializeTabs();+ void updateTabBar();+ void switchToPage(int pageIndex);+ void renamePage(int pageIndex, const QString &newName);+ void movePageTab(int srcIndex, int dstIndex);+ void savePageConfiguration();+ void loadPageConfiguration();++ // Page access methods (like TPalette)+ BrushPresetPage* getCurrentPage();+ BrushPresetPage* getPage(int pageIndex);+ int getPageCount() const;+ void clearPages();+protected:void resizeEvent(QResizeEvent *event) override;@@ -185,6 +371,18 @@ private slots:void onToolComboBoxListChanged(std::string id);void onViewModeChanged(ViewMode mode);void onShowHideActionTriggered();++ // Smart preset mode slots+ void onNonDestructiveToggled(bool checked);+ void onSelectivePresetToggled(bool checked);+ void onPlainColorClicked();++ // Tab/Page management slots+ void onTabChanged(int index);+ void onTabTextChanged(int index);+ void onTabMoved(int srcIndex, int dstIndex);+ void onAddPageClicked();+ void onDeletePageClicked();};#endif // BRUSHPRESETPANEL_Hdiff --git a/toonz/sources/toonz/custompaneleditorpopup.cpp b/toonz/sources/toonz/custompaneleditorpopup.cppindex a38c153f1..f9bf180f5 100644--- a/toonz/sources/toonz/custompaneleditorpopup.cpp+++ b/toonz/sources/toonz/custompaneleditorpopup.cpp@@ -12,6 +12,7 @@// TnzQt includes#include "toonzqt/gutil.h"+#include "toonzqt/menubarcommand.h"// ToonzLib#include "toonz/toonzfolders.h"@@ -30,6 +31,7 @@#include <QLabel>#include <QScrollArea>#include <QComboBox>+#include <QCheckBox>#include <QPushButton>#include <QUiLoader>#include <QColor>@@ -38,6 +40,7 @@#include <QBuffer>#include <QToolButton>#include <QRegularExpression>+#include <QInputDialog>namespace {const TFilePath CustomPanelTemplateFolderName("custom panel templates");@@ -775,9 +778,245 @@ void CustomPanelEditorPopup::onRegister() {//-----------------------------------------------------------------------------+// Custom dialog for panel removal with collapsible multi-selection.+// Top section stays anchored; collapsible section expands downward only.+class RemoveCustomPanelDialog : public QDialog {+ QLineEdit* m_mainPanelField;+ QString m_mainPanelName;+ QWidget* m_collapsibleWidget;+ QList<QCheckBox*> m_checkboxes;+ QStringList m_allPanels;+ QPushButton* m_toggleButton;++public:+ RemoveCustomPanelDialog(const QStringList& panels, const QString& currentPanel, QWidget* parent)+ : QDialog(parent), m_allPanels(panels), m_mainPanelName(currentPanel) {+ setWindowTitle(tr("Remove Custom Panels"));+ setModal(true);+ setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);++ QVBoxLayout* mainLayout = new QVBoxLayout(this);+ mainLayout->setContentsMargins(12, 12, 12, 12);+ mainLayout->setSpacing(4);++ // --- Top section: anchored, never moves ---+ QLabel* mainLabel = new QLabel(tr("Selected Panel to Remove:"), this);+ mainLayout->addWidget(mainLabel);++ // Read-only field with dark background for visibility+ m_mainPanelField = new QLineEdit(currentPanel, this);+ m_mainPanelField->setReadOnly(true);+ m_mainPanelField->setFrame(true);+ m_mainPanelField->setStyleSheet(+ "QLineEdit { background-color: #2a2a2a; color: #e0e0e0; "+ "border: 1px solid #555; padding: 3px; }");+ mainLayout->addWidget(m_mainPanelField);++ // Collapsible toggle (immediately below, minimal gap)+ m_toggleButton = new QPushButton(this);+ m_toggleButton->setFlat(true);+ m_toggleButton->setText(QString::fromUtf8("\xe2\x96\xb6") + tr(" Other custom panels"));+ m_toggleButton->setStyleSheet("text-align: left; padding: 4px 0px;");+ m_toggleButton->setCursor(Qt::PointingHandCursor);+ mainLayout->addWidget(m_toggleButton);++ // Collapsible container (starts hidden, zero size policy when hidden)+ m_collapsibleWidget = new QWidget(this);+ m_collapsibleWidget->setVisible(false);+ m_collapsibleWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);+ QVBoxLayout* collapsibleLayout = new QVBoxLayout(m_collapsibleWidget);+ collapsibleLayout->setContentsMargins(16, 2, 0, 2);+ collapsibleLayout->setSpacing(2);++ // Scroll area for the list of other panels+ QScrollArea* scrollArea = new QScrollArea(m_collapsibleWidget);+ scrollArea->setFrameShape(QFrame::NoFrame);+ scrollArea->setWidgetResizable(true);+ scrollArea->setMaximumHeight(180);++ QWidget* scrollWidget = new QWidget();+ QVBoxLayout* scrollLayout = new QVBoxLayout(scrollWidget);+ scrollLayout->setContentsMargins(0, 0, 0, 0);+ scrollLayout->setSpacing(2);++ for (const QString& panel : panels) {+ if (panel != currentPanel) {+ QCheckBox* cb = new QCheckBox(panel, scrollWidget);+ scrollLayout->addWidget(cb);+ m_checkboxes.append(cb);+ }+ }+ scrollLayout->addStretch();+ scrollArea->setWidget(scrollWidget);+ collapsibleLayout->addWidget(scrollArea);+ mainLayout->addWidget(m_collapsibleWidget);++ // Stretch between content and buttons so buttons stay at bottom+ mainLayout->addStretch(1);++ // Bottom buttons+ QHBoxLayout* buttonLayout = new QHBoxLayout();+ buttonLayout->setSpacing(6);+ QPushButton* okBtn = new QPushButton(tr("Remove"), this);+ QPushButton* cancelBtn = new QPushButton(tr("Cancel"), this);+ buttonLayout->addStretch();+ buttonLayout->addWidget(okBtn);+ buttonLayout->addWidget(cancelBtn);+ mainLayout->addLayout(buttonLayout);++ connect(okBtn, &QPushButton::clicked, this, &QDialog::accept);+ connect(cancelBtn, &QPushButton::clicked, this, &QDialog::reject);++ // Toggle logic: show/hide collapsible widget, resize downward+ connect(m_toggleButton, &QPushButton::clicked, [this]() {+ bool wasVisible = m_collapsibleWidget->isVisible();+ m_collapsibleWidget->setVisible(!wasVisible);+ if (wasVisible) {+ m_toggleButton->setText(QString::fromUtf8("\xe2\x96\xb6") + tr(" Other custom panels"));+ } else {+ m_toggleButton->setText(QString::fromUtf8("\xe2\x96\xbc") + tr(" Other custom panels"));+ }+ // Resize dialog to fit content, expanding downward only+ QApplication::processEvents();+ resize(width(), sizeHint().height());+ });++ // Start compact+ resize(320, sizeHint().height());+ }++ QStringList getSelectedPanels() const {+ QStringList selected;+ // Always include main panel+ selected.append(m_mainPanelName);+ // Add checked panels from collapsible section+ for (QCheckBox* cb : m_checkboxes) {+ if (cb->isChecked() && !selected.contains(cb->text())) {+ selected.append(cb->text());+ }+ }+ return selected;+ }+};++void CustomPanelEditorPopup::onRemove() {+ // List all existing custom panels+ TFilePath customPanelsFolder = customPaneFolderPath();+ if (!TSystem::doesExistFileOrLevel(customPanelsFolder)) {+ DVGui::warning(tr("No custom panels found."));+ return;+ }++ TFilePathSet fileList =+ TSystem::readDirectory(customPanelsFolder, false, true, false);++ QStringList panelNames;+ for (auto file : fileList) {+ if (file.getType() != "ui") continue;+ panelNames.append(QString::fromStdString(file.getName()));+ }++ if (panelNames.isEmpty()) {+ DVGui::warning(tr("No custom panels found."));+ return;+ }++ // Determine current panel (use panel name edit field if it matches an existing panel)+ QString currentPanel = m_panelNameEdit->text();+ if (!panelNames.contains(currentPanel)) {+ currentPanel = panelNames.first(); // Fallback to first panel+ }++ // Show custom dialog+ RemoveCustomPanelDialog dialog(panelNames, currentPanel, this);+ if (dialog.exec() != QDialog::Accepted) {+ return; // User cancelled+ }++ QStringList selectedPanels = dialog.getSelectedPanels();+ if (selectedPanels.isEmpty()) {+ return;+ }++ // Confirmation dialog+ QString question;+ if (selectedPanels.size() == 1) {+ question = tr("Are you sure you want to permanently remove the custom panel '%1'?\n\n"+ "This will delete the panel file and unregister its command.")+ .arg(selectedPanels.first());+ } else {+ question = tr("Are you sure you want to permanently remove %1 custom panels?\n\n"+ "This will delete the panel files and unregister their commands.")+ .arg(selectedPanels.size());+ }++ int ret = DVGui::MsgBox(question, tr("Remove"), tr("Cancel"), 0);+ if (ret == 0 || ret == 2) {+ return; // User cancelled+ }++ // Delete the .ui files and mark commands as invisible+ int successCount = 0;+ QStringList deletedPanels;++ for (const QString& panelName : selectedPanels) {+ TFilePath panelPath = customPanelsFolder + TFilePath(panelName.toStdString() + ".ui");+ if (TSystem::doesExistFileOrLevel(panelPath)) {+ try {+ TSystem::deleteFile(panelPath);+ deletedPanels.append(panelName);+ successCount++;++ // IMMEDIATELY mark the command action as invisible+ // to hide it from Configure Shortcuts during current session+ QString commandId = "MI_CustomPanel_" + panelName;+ QAction* action = CommandManager::instance()->getAction(+ commandId.toStdString().c_str(), false);+ if (action) {+ action->setVisible(false);+ }+ } catch (...) {+ DVGui::warning(tr("Failed to delete panel: %1").arg(panelName));+ }+ }+ }++ if (successCount > 0) {+ // Reload custom panel entries+ // This rebuilds m_registeredPanelIds to exclude deleted panels+ // and updates the Custom Panels menu+ CustomPanelManager::instance()->loadCustomPanelEntries();++ // Refresh the template combo in this editor to reflect changes+ loadTemplateList();++ QString message = (successCount == 1)+ ? tr("Custom panel has been successfully removed.")+ : tr("%1 custom panels have been successfully removed.").arg(successCount);+ DVGui::info(message);+ }+}++//-----------------------------------------------------------------------------++// Static instance pointer for refreshCommandTreeIfOpen()+CustomPanelEditorPopup* CustomPanelEditorPopup::s_instance = nullptr;++CustomPanelEditorPopup::~CustomPanelEditorPopup() {+ if (s_instance == this) s_instance = nullptr;+}++void CustomPanelEditorPopup::refreshCommandTreeIfOpen() {+ if (s_instance && s_instance->m_commandListTree) {+ s_instance->m_commandListTree->refreshTree();+ s_instance->m_commandListTree->searchItems();+ }+}+CustomPanelEditorPopup::CustomPanelEditorPopup(): Dialog(TApp::instance()->getMainWindow(), true, false,"CustomPanelEditorPopup") {+ s_instance = this;setWindowTitle(tr("Custom Panel Editor"));m_commandListTree =@@ -795,6 +1034,7 @@ CustomPanelEditorPopup::CustomPanelEditorPopup()m_panelNameEdit = new QLineEdit("My Custom Panel", this);QPushButton* registerButton = new QPushButton(tr("Register"), this);+ QPushButton* removeButton = new QPushButton(tr("Remove"), this);QPushButton* cancelButton = new QPushButton(tr("Cancel"), this);m_previewArea->setStyleSheet("background-color: black;");@@ -847,6 +1087,7 @@ CustomPanelEditorPopup::CustomPanelEditorPopup()}m_buttonLayout->addLayout(nameLay, 0);m_buttonLayout->addWidget(registerButton, 0);+ m_buttonLayout->addWidget(removeButton, 0);m_buttonLayout->addSpacing(10);m_buttonLayout->addWidget(cancelButton, 0);@@ -856,6 +1097,8 @@ CustomPanelEditorPopup::CustomPanelEditorPopup()this, &CustomPanelEditorPopup::onTemplateSwitched);connect(registerButton, &QPushButton::clicked, this,&CustomPanelEditorPopup::onRegister);+ connect(removeButton, &QPushButton::clicked, this,+ &CustomPanelEditorPopup::onRemove);connect(searchEdit, &QLineEdit::textChanged, this,&CustomPanelEditorPopup::onSearchTextChanged);diff --git a/toonz/sources/toonz/custompaneleditorpopup.h b/toonz/sources/toonz/custompaneleditorpopup.hindex 1bbf853ca..d7832d4eb 100644--- a/toonz/sources/toonz/custompaneleditorpopup.h+++ b/toonz/sources/toonz/custompaneleditorpopup.h@@ -144,8 +144,15 @@ private:void updateControls(QWidget* customWidget); // Update widget using current entries+ static CustomPanelEditorPopup* s_instance;+public:CustomPanelEditorPopup();+ ~CustomPanelEditorPopup();++ // Refresh the command list tree if the popup is currently open.+ // Call this after preset commands are added/removed so the tree stays in sync.+ static void refreshCommandTreeIfOpen();protected:void showEvent(QShowEvent* event) override;@@ -157,6 +164,7 @@ protected slots:void onPreviewClicked(int id);void onPreviewDropped(int id, const QString& cmdId, bool fromTree);void onRegister();+ void onRemove();void onSearchTextChanged(const QString& text);};diff --git a/toonz/sources/toonz/icons/dark/actions/16x16/plaincolor.svg b/toonz/sources/toonz/icons/dark/actions/16x16/plaincolor.svgnew file mode 100644index 000000000..3766fcbbb--- /dev/null+++ b/toonz/sources/toonz/icons/dark/actions/16x16/plaincolor.svg@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="UTF-8"?>+<svg width="16" height="16" version="1.1" xmlns="http://www.w3.org/2000/svg" style="fill-rule:evenodd;clip-rule:evenodd;">+ <rect width="16" height="16" fill-opacity="0"/>+ <path d="M3.5 2 L12.5 2 C13.33 2 14 2.67 14 3.5 L14 12.5 C14 13.33 13.33 14 12.5 14 L3.5 14 C2.67 14 2 13.33 2 12.5 L2 3.5 C2 2.67 2.67 2 3.5 2 Z M4.25 3 C3.56 3 3 3.56 3 4.25 L3 11.75 C3 12.44 3.56 13 4.25 13 L11.75 13 C12.44 13 13 12.44 13 11.75 L13 4.25 C13 3.56 12.44 3 11.75 3 Z"/>+ <path d="M1.6 13.6 L2.4 14.4 L14.4 2.4 L13.6 1.6 Z"/>+</svg>diff --git a/toonz/sources/toonz/mainwindow.cpp b/toonz/sources/toonz/mainwindow.cppindex 7cffb8298..38f77e9e9 100644--- a/toonz/sources/toonz/mainwindow.cpp+++ b/toonz/sources/toonz/mainwindow.cpp@@ -17,6 +17,7 @@#include "custompanelmanager.h"#include "audiorecordingpopup.h"#include "pltgizmopopup.h"+#include "shortcutpopup.h"// TnzTools includes#include "tools/toolcommandids.h"@@ -742,6 +743,10 @@ void MainWindow::readSettings(const QString &argumentLayoutFileName) {}}+ // Register room shortcuts after all rooms are loaded+ // This allows users to assign keyboard shortcuts to switch between rooms+ registerRoomCommands();+RecentFiles::instance()->loadRecentFiles();// Note: loadCustomPanelEntries() now called BEFORE loading rooms// to ensure dynamic commands exist when Custom Panels initialize@@ -1374,6 +1379,198 @@ void MainWindow::updatePanelVisibility() {}}+//-----------------------------------------------------------------------------+// Register room shortcuts for all existing rooms+// This function creates shortcut commands with [Room] prefix for each room+// allowing users to switch between rooms using keyboard shortcuts++void MainWindow::registerRoomCommands() {+ // Build list of current room command IDs+ QList<QString> currentRoomIds;+ for (int i = 0; i < m_stackedWidget->count(); i++) {+ Room *room = getRoom(i);+ if (!room) continue;+ QString roomName = room->getName();+ QString commandId = "MI_Room_" + roomName;+ currentRoomIds.append(commandId);+ }++ // Disable old room commands that no longer exist+ // We can't actually remove them from CommandManager, but we can hide them+ // by removing them from m_registeredRoomIds and their actions from the main window+ for (const QString& oldId : m_registeredRoomIds) {+ if (!currentRoomIds.contains(oldId)) {+ QAction* oldAction = CommandManager::instance()->getAction(+ oldId.toStdString().c_str(), false);+ if (oldAction) {+ // Remove the action from this widget to prevent it from being triggered+ removeAction(oldAction);+ // Hide the action so it won't appear in menus+ oldAction->setVisible(false);+ }+ }+ }++ m_registeredRoomIds.clear();++ // Iterate through all existing rooms+ for (int i = 0; i < m_stackedWidget->count(); i++) {+ Room *room = getRoom(i);+ if (!room) continue;++ QString roomName = room->getName();+ QString commandId = "MI_Room_" + roomName;++ // Check if command already exists+ QAction* existingAction = CommandManager::instance()->getAction(+ commandId.toStdString().c_str(), false);+ if (existingAction) {+ // Make sure it's visible and added to this widget+ existingAction->setVisible(true);+ if (!actions().contains(existingAction)) {+ addAction(existingAction);+ }+ m_registeredRoomIds.append(commandId);+ continue;+ }++ // Clean up room name for better display+ // Replace underscores and hyphens with spaces for readability+ QString cleanName = roomName;+ cleanName.replace('_', ' ');+ cleanName.replace('-', ' ');++ // Create display name with [Room] prefix+ QString displayName = "[Room] " + cleanName;++ QAction* action = new DVAction(displayName, this);+ addAction(action);++ // Define command with RoomCommandType for proper categorization+ CommandManager::instance()->define(+ commandId.toStdString().c_str(),+ RoomCommandType,+ "",+ action,+ "");++ // Create handler that switches to this room when shortcut is triggered+ class RoomSwitchHandler : public CommandHandlerInterface {+ QString m_roomName;+ MainWindow* m_mainWindow;+ public:+ RoomSwitchHandler(const QString& name, MainWindow* mainWin)+ : m_roomName(name), m_mainWindow(mainWin) {}++ void execute() override {+ if (!m_mainWindow) return;++ // Find room by name and switch to it+ for (int i = 0; i < m_mainWindow->getRoomCount(); i++) {+ Room* room = m_mainWindow->getRoom(i);+ if (room && room->getName() == m_roomName) {+ m_mainWindow->m_topBar->getRoomTabWidget()->setCurrentIndex(i);+ return;+ }+ }+ }+ };++ CommandManager::instance()->setHandler(+ commandId.toStdString().c_str(),+ new RoomSwitchHandler(roomName, this));++ m_registeredRoomIds.append(commandId);+ }++ // Load saved shortcuts for room commands+ TFilePath shortcutsFile = ToonzFolder::getMyModuleDir() + TFilePath("shortcuts.ini");+ if (!TFileStatus(shortcutsFile).doesExist()) {+ // Refresh ShortcutPopup if it's open to show new room commands+ ShortcutPopup::refreshIfOpen();+ return;+ }++ QSettings settings(toQString(shortcutsFile), QSettings::IniFormat);+ settings.beginGroup("shortcuts");++ for (const QString& commandId : m_registeredRoomIds) {+ QString savedShortcut = settings.value(commandId, "").toString();+ if (!savedShortcut.isEmpty()) {+ QAction* action = CommandManager::instance()->getAction(+ commandId.toStdString().c_str(), false);+ if (action) {+ action->setShortcut(QKeySequence(savedShortcut));+ }+ }+ }++ settings.endGroup();++ // Refresh ShortcutPopup if it's open to show new room commands+ ShortcutPopup::refreshIfOpen();+}++//-----------------------------------------------------------------------------+// Unregister a room shortcut command when a room is deleted++void MainWindow::unregisterRoomCommand(const QString &roomName) {+ QString commandId = "MI_Room_" + roomName;++ // Remove from registered list+ m_registeredRoomIds.removeAll(commandId);++ // Note: We don't actually remove the command from CommandManager+ // as Qt doesn't provide a clean way to unregister QActions+ // The command will simply do nothing if triggered after room deletion++ // Clear the shortcut from settings file+ TFilePath shortcutsFile = ToonzFolder::getMyModuleDir() + TFilePath("shortcuts.ini");+ if (TFileStatus(shortcutsFile).doesExist()) {+ QSettings settings(toQString(shortcutsFile), QSettings::IniFormat);+ settings.beginGroup("shortcuts");+ settings.remove(commandId);+ settings.endGroup();+ }++ // Refresh ShortcutPopup if it's open+ ShortcutPopup::refreshIfOpen();+}++//-----------------------------------------------------------------------------+// Update a room shortcut command when a room is renamed++void MainWindow::updateRoomCommand(const QString &oldName, const QString &newName) {+ QString oldCommandId = "MI_Room_" + oldName;+ QString newCommandId = "MI_Room_" + newName;++ // Save and migrate the old shortcut if it exists+ TFilePath shortcutsFile = ToonzFolder::getMyModuleDir() + TFilePath("shortcuts.ini");+ QString oldShortcut;++ if (TFileStatus(shortcutsFile).doesExist()) {+ QSettings settings(toQString(shortcutsFile), QSettings::IniFormat);+ settings.beginGroup("shortcuts");+ oldShortcut = settings.value(oldCommandId, "").toString();++ // Migrate the shortcut to the new command ID+ if (oldCommandId != newCommandId) {+ settings.remove(oldCommandId);+ if (!oldShortcut.isEmpty()) {+ settings.setValue(newCommandId, oldShortcut);+ }+ }+ settings.endGroup();+ }++ // Re-register all room commands+ // This will clean up the old command and create the new one+ registerRoomCommands();++ // The shortcut was already saved in shortcuts.ini above,+ // so registerRoomCommands() will load it automatically+}+//-----------------------------------------------------------------------------void MainWindow::onIndexSwapped(int firstIndex, int secondIndex) {@@ -1393,12 +1590,18 @@ void MainWindow::insertNewRoom() {// Finally, old room index is increased by 1m_oldRoomIndex++;++ // Register shortcut for the newly created room+ registerRoomCommands();}//-----------------------------------------------------------------------------void MainWindow::deleteRoom(int index) {Room *room = getRoom(index);++ // Store room name before deletion for unregistering the shortcut+ QString roomName = room->getName();TFilePath fp = room->getPath();try {@@ -1420,6 +1623,9 @@ void MainWindow::deleteRoom(int index) {m_stackedWidget->removeWidget(room);delete room;++ // Unregister shortcut for the deleted room+ unregisterRoomCommand(roomName);}//-----------------------------------------------------------------------------@@ -1454,6 +1660,9 @@ void MainWindow::renameRoom(int index, const QString name) {// Update visibility immediately to reflect the changeupdatePanelVisibility();+ // Update room shortcut with new name+ updateRoomCommand(oldName, name);+if (m_saveSettingsOnQuit) room->save();}diff --git a/toonz/sources/toonz/mainwindow.h b/toonz/sources/toonz/mainwindow.hindex 1ca3be0f6..db2e4bd56 100644--- a/toonz/sources/toonz/mainwindow.h+++ b/toonz/sources/toonz/mainwindow.h@@ -85,6 +85,9 @@ class MainWindow final : public QMainWindow {/*-- show layout name in the title bar --*/QString m_layoutName;++ // List of registered room shortcut command IDs+ QList<QString> m_registeredRoomIds;public:MainWindow(const QString &argumentLayoutFileName, QWidget *parent = 0,@@ -128,6 +131,15 @@ public:// Update visibility of all room-bound panels (native and custom)void updatePanelVisibility();++ // Register room shortcuts for all existing rooms+ void registerRoomCommands();++ // Unregister a specific room shortcut+ void unregisterRoomCommand(const QString &roomName);++ // Update a room shortcut when renamed+ void updateRoomCommand(const QString &oldName, const QString &newName);protected:void showEvent(QShowEvent *) override;diff --git a/toonz/sources/toonz/menubarcommandids.h b/toonz/sources/toonz/menubarcommandids.hindex dbb6304d7..490dab8ad 100644--- a/toonz/sources/toonz/menubarcommandids.h+++ b/toonz/sources/toonz/menubarcommandids.h@@ -334,6 +334,9 @@#define MI_OpenComboViewer "MI_OpenComboViewer"#define MI_OpenHistoryPanel "MI_OpenHistoryPanel"#define MI_OpenBrushPresetPanel "MI_OpenBrushPresetPanel"+#define MI_AddBrushPreset "MI_AddBrushPreset"+#define MI_RemoveBrushPreset "MI_RemoveBrushPreset"+#define MI_RemoveBrushPresetByName "MI_RemoveBrushPresetByName"#define MI_OpenToolPropertiesPanel "MI_OpenToolPropertiesPanel"#define MI_ReplaceParentDirectory "MI_ReplaceParentDirectory"#define MI_Reframe1 "MI_Reframe1"diff --git a/toonz/sources/toonz/shortcutpopup.cpp b/toonz/sources/toonz/shortcutpopup.cppindex 9c92e91c5..dcccf8200 100644--- a/toonz/sources/toonz/shortcutpopup.cpp+++ b/toonz/sources/toonz/shortcutpopup.cpp@@ -292,6 +292,7 @@ ShortcutTree::ShortcutTree(QWidget *parent) : QTreeWidget(parent) {addFolder(tr("Windows"), MenuWindowsCommandType, menuCommandFolder);QTreeWidgetItem *windowsFolder = m_subFolders.back();addFolder(tr("Custom Panels"), CustomPanelCommandType, windowsFolder);+ addFolder(tr("Rooms"), RoomCommandType, windowsFolder);addFolder(tr("Help"), MenuHelpCommandType, menuCommandFolder);addFolder(tr("Right-click Menu Commands"), RightClickMenuCommandType);@@ -449,6 +450,7 @@ void ShortcutTree::refreshTree() {addFolder(tr("Windows"), MenuWindowsCommandType, menuCommandFolder);QTreeWidgetItem *windowsFolder = m_subFolders.back();addFolder(tr("Custom Panels"), CustomPanelCommandType, windowsFolder);+ addFolder(tr("Rooms"), RoomCommandType, windowsFolder);addFolder(tr("Help"), MenuHelpCommandType, menuCommandFolder);addFolder(tr("Right-click Menu Commands"), RightClickMenuCommandType);diff --git a/toonz/sources/toonz/toolpresetcommandmanager.cpp b/toonz/sources/toonz/toolpresetcommandmanager.cppindex 160cdadc7..53539d4f4 100644--- a/toonz/sources/toonz/toolpresetcommandmanager.cpp+++ b/toonz/sources/toonz/toolpresetcommandmanager.cpp@@ -3,6 +3,7 @@#include "menubarcommandids.h"#include "mainwindow.h"#include "shortcutpopup.h"+#include "custompaneleditorpopup.h"#include "tapp.h"// ToonzLib@@ -25,9 +26,16 @@#include "tools/toolcommandids.h"#include "tproperty.h"+#include "tstream.h"+#include <QSettings>+#include "tenv.h"+#include <QPainter>+#include <QPainterPath>+#include <QPixmap>+#include <QPolygonF>#include <algorithm> // For std::min, std::max-#include <cmath> // For log, exp+#include <cmath> // For sin, pow, log, expnamespace {@@ -139,6 +147,250 @@ QString findCustomPresetIcon(const QString& presetName) {return QString();}+// Helper to generate dynamic size icon for Custom Panels.+// Progressive top-cropping: small sizes show a full circle, larger sizes+// have the circle progressively cropped from the TOP until only the bottom+// half remains for the biggest values. Number always below the shape.+QPixmap generateDynamicSizeIcon(double size, int iconSize = 32) {+ QPixmap pixmap(iconSize, iconSize);+ pixmap.fill(Qt::transparent);++ QPainter painter(&pixmap);+ painter.setRenderHint(QPainter::Antialiasing);++ // Format the size string (show decimal for 0.5)+ QString sizeStr;+ if (size == (int)size)+ sizeStr = QString::number((int)size);+ else+ sizeStr = QString::number(size, 'g', 3);++ QFont numFont;+ int fontSize = qMax(7, iconSize / 4);+ numFont.setPixelSize(fontSize);+ numFont.setBold(true);+ QFontMetrics fm(numFont);+ int textH = fm.height();++ // Available height above text+ int availH = iconSize - textH - 2;+ // Allow circle diameter to exceed availH (it will be cropped from top)+ int maxDiam = qMin(iconSize - 2, (int)(availH * 1.8));+ maxDiam = qMax(6, maxDiam);++ // Variable diameter (log scale from 0.5..1000)+ double minSz = 0.5, maxSz = 1000.0;+ double logMin = std::log(minSz + 1.0);+ double logMax = std::log(maxSz + 1.0);+ double logVal = std::log(qMax(size, minSz) + 1.0);+ double ratio = (logVal - logMin) / (logMax - logMin);+ ratio = qMax(0.0, qMin(1.0, ratio));+ int circleDiam = (int)(maxDiam * (0.15 + 0.85 * ratio));+ circleDiam = qMax(4, circleDiam);++ int cx = iconSize / 2;+ // Circle bottom sits at the text baseline+ int circleBottom = availH;+ int circleTop = circleBottom - circleDiam;+ int clipTop = 0; // Top of the icon area++ // Draw the circle. If it overflows the top, apply a horizontal clip rect+ // so only the top is hidden — sides stay fully intact (horizontal mask effect).+ QRect circleRect(cx - circleDiam / 2, circleTop, circleDiam, circleDiam);++ if (circleTop < clipTop) {+ painter.setClipRect(QRect(0, clipTop, iconSize, circleBottom - clipTop));+ }++ painter.setPen(QPen(QColor(160, 160, 160), 1));+ painter.setBrush(QColor(255, 255, 255));+ painter.drawEllipse(circleRect);++ if (circleTop < clipTop) {+ painter.setClipping(false);+ }++ // Number below the shape+ painter.setPen(QColor(220, 220, 220));+ painter.setFont(numFont);+ QRect textRect(0, circleBottom + 1, iconSize, textH + 2);+ painter.drawText(textRect, Qt::AlignHCenter | Qt::AlignTop, sizeStr);++ return pixmap;+}++// Check if user preference is set to use sample strokes (TEnv, shared name+// with BrushPresetPanel).+bool useSampleStrokesEnabled() {+ static TEnv::IntVar BrushPresetPanelUseSampleStrokes(+ "BrushPresetPanelUseSampleStrokes", 0);+ return BrushPresetPanelUseSampleStrokes != 0;+}++// Helper structure to hold minimal render data for a brush preset+struct BrushRenderInfo {+ double minThickness = 1.0;+ double maxThickness = 5.0;+ double hardness = 100.0;+ double minOpacity = 100.0;+ double maxOpacity = 100.0;+ bool isPencil = false;+ bool found = false;+};++// Load render info from the preset .txt file for a given preset and tool type.+// toolType is one of: "vector", "toonzraster", "raster"+BrushRenderInfo loadBrushRenderInfo(const QString &presetName, const QString &toolType) {+ BrushRenderInfo info;+ TFilePath presetFilePath;+ if (toolType == "vector")+ presetFilePath = TEnv::getConfigDir() + "brush_vector.txt";+ else if (toolType == "toonzraster")+ presetFilePath = TEnv::getConfigDir() + "brush_toonzraster.txt";+ else if (toolType == "raster")+ presetFilePath = TEnv::getConfigDir() + "brush_raster.txt";+ else+ return info;++ try {+ TIStream is(presetFilePath);+ std::string tagName;+ std::wstring wPresetName = presetName.toStdWString();+ while (is.matchTag(tagName)) {+ if (tagName == "brushes") {+ while (is.matchTag(tagName)) {+ if (tagName == "brush") {+ std::wstring name;+ double minT = 1.0, maxT = 5.0, h = 100.0, minO = 100.0, maxO = 100.0;+ int pencil = 0;+ while (is.matchTag(tagName)) {+ if (tagName == "Name") { is >> name; is.matchEndTag(); }+ else if (tagName == "Thickness") { is >> minT >> maxT; is.matchEndTag(); }+ else if (tagName == "Hardness") { is >> h; is.matchEndTag(); }+ else if (tagName == "Opacity") { is >> minO >> maxO; is.matchEndTag(); }+ else if (tagName == "Pencil") { is >> pencil; is.matchEndTag(); }+ else is.skipCurrentTag();+ }+ if (name == wPresetName) {+ info.minThickness = minT;+ info.maxThickness = maxT;+ info.hardness = h;+ info.minOpacity = minO;+ info.maxOpacity = maxO;+ info.isPencil = (pencil != 0);+ info.found = true;+ is.matchEndTag();+ return info;+ }+ is.matchEndTag();+ } else {+ is.skipCurrentTag();+ }+ }+ is.matchEndTag();+ } else {+ is.skipCurrentTag();+ }+ }+ } catch (...) {}+ return info;+}++// Map a command prefix to the corresponding brush tool type string+// for loading preset render info from the correct .txt file.+QString toolTypeFromPrefix(const QString &prefix) {+ if (prefix.contains("TnzRasterBrush")) return "toonzraster";+ if (prefix.contains("TnzVectorBrush")) return "vector";+ if (prefix.contains("RasterBrush")) return "raster";+ return "";+}++// Generate a dynamic sample-stroke icon for a brush preset (Custom Panels).+// Smooth sine-wave double undulation with quadratic-tapered pointed tips.+// Taper adapts to min/max thickness ratio of the brush.+QPixmap generateDynamicBrushIcon(const BrushRenderInfo &info, int iconSize = 32) {+ QPixmap pixmap(iconSize, iconSize);+ pixmap.fill(Qt::transparent);++ QPainter painter(&pixmap);+ painter.setRenderHint(QPainter::Antialiasing, true);++ double avgThick = (info.minThickness + info.maxThickness) / 2.0;+ double avgOpacity = (info.minOpacity + info.maxOpacity) / 2.0;++ double maxH = iconSize * 0.50;+ double strokeH = qMax(3.0, qMin(maxH, avgThick * iconSize / 12.0));+ strokeH = qMax(strokeH, 4.0);++ // Thickness ratio controls tip bluntness (0 = very pointed, 1 = uniform)+ double thickRatio = (info.maxThickness > 0.01)+ ? (info.minThickness / info.maxThickness) : 0.0;+ thickRatio = qMax(0.0, qMin(1.0, thickRatio));++ // If opacity is 0 (tool doesn't support opacity, e.g. Toonz Raster),+ // treat as fully opaque since the brush always paints at full intensity.+ double alpha;+ if (avgOpacity < 0.01)+ alpha = 1.0;+ else+ alpha = qMax(0.35, qMin(1.0, avgOpacity / 100.0));+ // Hardness influences stroke color: low=gray, high=white (matching brushpresetpanel)+ double hardFrac = qMax(0.0, qMin(1.0, info.hardness / 100.0));+ int lowVal = 140;+ int highVal = 255;+ int val = lowVal + (int)((highVal - lowVal) * hardFrac);+ QColor strokeColor(val, val, val);+ strokeColor.setAlphaF(alpha);++ double x0 = 1.0, x1 = iconSize - 1.0;+ double totalW = x1 - x0;+ double cy = iconSize / 2.0;+ double waveAmp = iconSize * 0.12;++ const int N = 60;+ QPolygonF topEdge, botEdge;+ for (int i = 0; i <= N; ++i) {+ double t = (double)i / N;+ double x = x0 + totalW * t;++ // Sine wave centerline (one full period: hump up then dip down)+ double angle = t * 2.0 * 3.14159265358979;+ double centerY = cy - std::sin(angle) * waveAmp;++ // Quadratic taper blended with thickness ratio+ double taper;+ if (t < 0.5) { double u = t * 2.0; taper = u * u; }+ else { double u = (1.0 - t) * 2.0; taper = u * u; }+ taper = thickRatio + (1.0 - thickRatio) * taper;+ if (info.hardness < 50) taper = std::pow(taper, 0.7);+ if (info.hardness > 80) taper = std::pow(taper, 1.3);++ double halfH = strokeH * taper * 0.5;+ topEdge << QPointF(x, centerY - halfH);+ botEdge.prepend(QPointF(x, centerY + halfH));+ }++ QPolygonF outline = topEdge + botEdge;+ QPainterPath path;+ path.addPolygon(outline);+ path.closeSubpath();++ painter.setPen(Qt::NoPen);+ painter.setBrush(strokeColor);+ painter.drawPath(path);++ // Soft glow for soft brushes+ if (info.hardness < 50 && !info.isPencil) {+ QColor glow = strokeColor;+ glow.setAlphaF(alpha * 0.12);+ painter.setBrush(Qt::NoBrush);+ painter.setPen(QPen(glow, 1.5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ painter.drawPath(path);+ }++ return pixmap;+}+// Helper to get presets from a tool's propertiesQList<QString> getPresetsFromTool(const QString& toolId, TTool::ToolTargetType targetType) {QList<QString> presetNames;@@ -513,11 +765,14 @@ public://-----------------------------------------------------------------------------ToolPresetCommandManager::ToolPresetCommandManager()- : QObject(), m_initialized(false), m_presetActionGroup(nullptr), m_sizeActionGroup(nullptr) {- // Create action groups for mutual exclusivity+ : QObject()+ , m_initialized(false)+ , m_commandsDirty(true)+ , m_presetActionGroup(nullptr)+ , m_sizeActionGroup(nullptr) {m_presetActionGroup = new QActionGroup(this);m_presetActionGroup->setExclusive(true);-+m_sizeActionGroup = new QActionGroup(this);m_sizeActionGroup->setExclusive(true);}@@ -548,80 +803,85 @@ void ToolPresetCommandManager::initialize() {void ToolPresetCommandManager::registerToolPresetCommands() {MainWindow* mainWindow = dynamic_cast<MainWindow*>(TApp::instance()->getMainWindow());if (!mainWindow) return;-- // === Auto-create icons directory if it doesn't exist ===++ // Ensure the icons directory exists (one stat per full registration, not per preset).TFilePath iconFolder = TEnv::getStuffDir() + "library" + "brushpreseticons";if (!TFileStatus(iconFolder).doesExist()) {try {TSystem::mkDir(iconFolder);- } catch (...) {- // If directory creation fails, continue anyway (icons will use defaults)- }+ } catch (...) {}}-++ // Read the preference once — avoids opening QSettings N times inside the loop.+ const bool sampleStrokes = useSampleStrokesEnabled();+QSet<QString> currentPresets;-- // Process all supported brush tools+for (const BrushToolConfig& config : BRUSH_TOOLS) {QList<QString> presets = getPresetsFromTool(config.toolId, config.targetType);-- // Register new presets for this tool+for (const QString& presetName : presets) {QString commandId = config.commandPrefix + presetName;currentPresets.insert(commandId);-- // Check if already registered+QAction* existingAction = CommandManager::instance()->getAction(commandId.toStdString().c_str(), false);if (existingAction) {- // Update icon - check for custom icon first, then fallback to default+ // Refresh the icon in case the sample-strokes preference changed.+ // This runs only when the dirty flag was set, so it is not a hot path.QString customIconPath = findCustomPresetIcon(presetName);-if (!customIconPath.isEmpty()) {- // Custom icon found - update to use itexistingAction->setIcon(QIcon(customIconPath));+ } else if (sampleStrokes) {+ QString toolType = toolTypeFromPrefix(config.commandPrefix);+ BrushRenderInfo rInfo = loadBrushRenderInfo(presetName, toolType);+ if (rInfo.found)+ existingAction->setIcon(QIcon(generateDynamicBrushIcon(rInfo, 32)));+ else if (config.iconName && *config.iconName)+ existingAction->setIcon(createQIcon(config.iconName, true));} else if (config.iconName && *config.iconName) {- // No custom icon - use default type iconexistingAction->setIcon(createQIcon(config.iconName, true));}continue;}-++ // New preset — create and register the QAction.QString displayName = config.displayPrefix + presetName;QAction* action = new DVAction(displayName, mainWindow);-- // Make the action checkable for visual feedback in Custom Panelsaction->setCheckable(true);- action->setChecked(false); // Default unchecked-- // Priority 1: Try to find custom icon for this preset+ action->setChecked(false);++ // Priority 1: Custom icon -> 2: Dynamic stroke -> 3: Default iconQString customIconPath = findCustomPresetIcon(presetName);const char* iconNameToRegister = config.iconName;-+if (!customIconPath.isEmpty()) {- // Custom icon found - use itaction->setIcon(QIcon(customIconPath));- // Note: We can't register the full path in CommandManager,- // so we register the default iconName for metadata purposes+ } else if (sampleStrokes) {+ QString toolType = toolTypeFromPrefix(config.commandPrefix);+ BrushRenderInfo rInfo = loadBrushRenderInfo(presetName, toolType);+ if (rInfo.found) {+ action->setIcon(QIcon(generateDynamicBrushIcon(rInfo, 32)));+ } else if (config.iconName && *config.iconName) {+ action->setIcon(createQIcon(config.iconName));+ }} else if (config.iconName && *config.iconName) {- // Priority 2: Use default icon for this brush typeaction->setIcon(createQIcon(config.iconName));}-+mainWindow->addAction(action);-- // Add action to preset action group for mutual exclusivity+if (m_presetActionGroup) {m_presetActionGroup->addAction(action);}-+CommandManager::instance()->define(commandId.toStdString().c_str(),- BrushPresetCommandType, // Tool Modifiers/Brush Presets category+ BrushPresetCommandType,"",action,iconNameToRegister);-+CommandManager::instance()->setHandler(commandId.toStdString().c_str(),new BrushPresetHandler(config.toolId, presetName));@@ -637,6 +897,9 @@ void ToolPresetCommandManager::registerToolPresetCommands() {// Disable the command so it can't be triggeredCommandManager::instance()->enable(commandId.toStdString().c_str(), false);+ // Hide the action so it disappears from ShortcutPopup and CustomPanelEditor trees+ action->setVisible(false);+// Rename to indicate it's deletedQString oldText = action->iconText();if (!oldText.startsWith("(Deleted) ")) {@@ -651,8 +914,9 @@ void ToolPresetCommandManager::registerToolPresetCommands() {// Update the registered setm_registeredPresetIds = currentPresets;- // Notify ShortcutPopup to refresh if it's currently open+ // Notify open popups to refresh their command treesShortcutPopup::refreshIfOpen();+ CustomPanelEditorPopup::refreshCommandTreeIfOpen();// Load shortcuts if any were previously savedTFilePath shortcutsFile = ToonzFolder::getMyModuleDir() + TFilePath("shortcuts.ini");@@ -677,8 +941,17 @@ void ToolPresetCommandManager::registerToolPresetCommands() {//-----------------------------------------------------------------------------+void ToolPresetCommandManager::markCommandsDirty() {+ m_commandsDirty = true;+}++//-----------------------------------------------------------------------------+void ToolPresetCommandManager::refreshPresetCommands() {- // Simply re-register all commands (new ones will be added, existing ones skipped)+ // Only rebuild commands when the preset list has actually changed.+ // This prevents O(N*disk) I/O on every room switch when nothing changed.+ if (!m_commandsDirty) return;+ m_commandsDirty = false;registerToolPresetCommands();}@@ -687,93 +960,91 @@ void ToolPresetCommandManager::refreshPresetCommands() {void ToolPresetCommandManager::registerSizeCommands() {MainWindow* mainWindow = dynamic_cast<MainWindow*>(TApp::instance()->getMainWindow());if (!mainWindow) return;-- // === Auto-create icons directory if it doesn't exist ===+TFilePath iconFolder = TEnv::getStuffDir() + "library" + "brushpreseticons";if (!TFileStatus(iconFolder).doesExist()) {try {TSystem::mkDir(iconFolder);- } catch (...) {- // If directory creation fails, continue anyway (icons will use defaults)- }+ } catch (...) {}}-++ // Read the preference once — avoids opening QSettings N times inside the loop.+ const bool sampleStrokes = useSampleStrokesEnabled();+QSet<QString> currentSizes;-- // Register commands for each fixed size+const int numSizes = sizeof(FIXED_SIZES) / sizeof(FIXED_SIZES[0]);for (int i = 0; i < numSizes; ++i) {double size = FIXED_SIZES[i];-- // Create command ID and display name+QString sizeStr = QString::number(size);- if (sizeStr.contains('.')) {- sizeStr.replace('.', '_'); // Replace decimal point with underscore for ID- }+ if (sizeStr.contains('.')) sizeStr.replace('.', '_');QString commandId = "MI_ToolSize_" + sizeStr;currentSizes.insert(commandId);-- // Check if already registered+QAction* existingAction = CommandManager::instance()->getAction(commandId.toStdString().c_str(), false);if (existingAction) {- // Update icon if custom one is available+ // Refresh icon when sample-strokes preference changed (dirty-flag run only).QString iconName = "size_" + QString::number(size);QString customIconPath = findCustomPresetIcon(iconName);-- if (!customIconPath.isEmpty()) {+ if (!customIconPath.isEmpty())existingAction->setIcon(QIcon(customIconPath));- }+ else if (sampleStrokes)+ existingAction->setIcon(QIcon(generateDynamicSizeIcon(size, 32)));+ else+ existingAction->setIcon(createQIcon("thickness"));continue;}-- // Create display name+QString displayName = "[Size] " + QString::number(size);QAction* action = new DVAction(displayName, mainWindow);-- // Make the action checkable for visual feedback in Custom Panelsaction->setCheckable(true);- action->setChecked(false); // Default unchecked-- // Try to find custom icon (e.g., size_50.svg)+ action->setChecked(false);+QString iconName = "size_" + QString::number(size);QString customIconPath = findCustomPresetIcon(iconName);-+if (!customIconPath.isEmpty()) {- // Custom icon foundaction->setIcon(QIcon(customIconPath));+ } else if (sampleStrokes) {+ action->setIcon(QIcon(generateDynamicSizeIcon(size, 32)));} else {- // Use generic thickness iconaction->setIcon(createQIcon("thickness"));}-+mainWindow->addAction(action);-- // Add action to size action group for mutual exclusivity+if (m_sizeActionGroup) {m_sizeActionGroup->addAction(action);}-+CommandManager::instance()->define(commandId.toStdString().c_str(),- BrushSizeCommandType, // Tool Modifiers/Brush Sizes category+ BrushSizeCommandType,"",action,- "thickness"); // Default icon name-+ "thickness");+CommandManager::instance()->setHandler(commandId.toStdString().c_str(),new ToolSizeHandler(size));}-+m_registeredSizeIds = currentSizes;}//-----------------------------------------------------------------------------void ToolPresetCommandManager::refreshSizeCommands() {- // Simply re-register all size commands+ // Regenerate both size and preset command icons to reflect the current+ // sample-strokes preference. Force the dirty flag so registerToolPresetCommands+ // actually runs (it would be a no-op otherwise after a previous refresh).+ m_commandsDirty = true;registerSizeCommands();+ m_commandsDirty = true;+ registerToolPresetCommands();+ m_commandsDirty = false;}//-----------------------------------------------------------------------------diff --git a/toonz/sources/toonz/toolpresetcommandmanager.h b/toonz/sources/toonz/toolpresetcommandmanager.hindex bd2dac7ff..880b10e1d 100644--- a/toonz/sources/toonz/toolpresetcommandmanager.h+++ b/toonz/sources/toonz/toolpresetcommandmanager.h@@ -22,6 +22,9 @@ class ToolPresetCommandManager : public QObject { // singletonQSet<QString> m_registeredPresetIds;QSet<QString> m_registeredSizeIds;bool m_initialized;+ // True when presets were added/removed and commands need rebuilding.+ // Prevents redundant full re-registration on every room switch.+ bool m_commandsDirty;// Action groups for mutual exclusivityQActionGroup* m_presetActionGroup;@@ -39,7 +42,12 @@ public:// Registers universal size commandsvoid registerSizeCommands();- // Refreshes preset commands (called when presets are added/removed)+ // Marks commands as dirty so the next refreshPresetCommands() call+ // rebuilds them. Call this when presets are actually added or removed.+ void markCommandsDirty();++ // Refreshes preset commands only when the preset list has changed.+ // Safe to call frequently (e.g. on panel show) without performance cost.void refreshPresetCommands();// Refreshes size commands (called when shortcut popup is opened)diff --git a/toonz/sources/toonz/toonz.qrc b/toonz/sources/toonz/toonz.qrcindex db5c9fbab..606d6bd19 100644--- a/toonz/sources/toonz/toonz.qrc+++ b/toonz/sources/toonz/toonz.qrc@@ -483,6 +483,7 @@<!-- Palette --><file>icons/dark/actions/16x16/newstyle.svg</file>+ <file>icons/dark/actions/16x16/plaincolor.svg</file><file>icons/dark/actions/16x16/newpage.svg</file><file>icons/dark/actions/16x16/palette.svg</file><file>icons/dark/actions/16x16/palette_tab.svg</file>diff --git a/toonz/sources/toonzqt/CMakeLists.txt b/toonz/sources/toonzqt/CMakeLists.txtindex f4f7cfd5b..8fdd96e94 100644--- a/toonz/sources/toonzqt/CMakeLists.txt+++ b/toonz/sources/toonzqt/CMakeLists.txt@@ -134,6 +134,7 @@ set(SOURCESkeyframenavigator.cpplineedit.cppmenubarcommand.cpp+ brushpresetbridge.cpppalettesscanpopup.cpppaletteviewer.cpppaletteviewergui.cppdiff --git a/toonz/sources/toonzqt/brushpresetbridge.cpp b/toonz/sources/toonzqt/brushpresetbridge.cppnew file mode 100644index 000000000..cc904e802--- /dev/null+++ b/toonz/sources/toonzqt/brushpresetbridge.cpp@@ -0,0 +1,146 @@+#include "toonzqt/brushpresetbridge.h"+#include "tcolorstyles.h"+#include "tpalette.h"+#include "toonz/tpalettehandle.h"+#include "tundo.h"+#include "historytypes.h"+#include <QMutex>+#include <QMutexLocker>++namespace BrushPresetBridge {+static QString s_pendingPresetName;+static QStringList s_pendingRemoveNames;+static bool s_nonDestructiveMode = false;+static bool s_selectivePresetMode = false;+static QMutex s_mutex;++void setPendingPresetName(const QString &name) {+ QMutexLocker lock(&s_mutex);+ s_pendingPresetName = name;+}++QString takePendingPresetName() {+ QMutexLocker lock(&s_mutex);+ QString name = s_pendingPresetName;+ s_pendingPresetName.clear();+ return name;+}++void addPendingRemoveName(const QString &name) {+ QMutexLocker lock(&s_mutex);+ s_pendingRemoveNames.append(name);+}++QStringList takePendingRemoveNames() {+ QMutexLocker lock(&s_mutex);+ QStringList names = s_pendingRemoveNames;+ s_pendingRemoveNames.clear();+ return names;+}++void setNonDestructiveMode(bool enabled) { s_nonDestructiveMode = enabled; }+bool isNonDestructiveMode() { return s_nonDestructiveMode; }++void setSelectivePresetMode(bool enabled) { s_selectivePresetMode = enabled; }+bool isSelectivePresetMode() { return s_selectivePresetMode; }++//-----------------------------------------------------------------------------+// Visual style comparison (ignores name, globalName, flags, pickedPosition)+//-----------------------------------------------------------------------------++bool stylesMatchVisually(const TColorStyle *a, const TColorStyle *b) {+ if (!a || !b) return false;+ if (a->getTagId() != b->getTagId()) return false;++ // Intentionally skip mainColor and colorParamValues:+ // colors are user-controlled drawing data, not part of the brush identity.+ // Matching is based purely on structural/technical parameters.++ int paramCount = a->getParamCount();+ if (paramCount != b->getParamCount()) return false;++ for (int p = 0; p < paramCount; ++p) {+ TColorStyle::ParamType pt = a->getParamType(p);+ if (pt != b->getParamType(p)) return false;+ switch (pt) {+ case TColorStyle::BOOL:+ if (a->getParamValue(TColorStyle::bool_tag(), p) !=+ b->getParamValue(TColorStyle::bool_tag(), p))+ return false;+ break;+ case TColorStyle::INT:+ case TColorStyle::ENUM:+ if (a->getParamValue(TColorStyle::int_tag(), p) !=+ b->getParamValue(TColorStyle::int_tag(), p))+ return false;+ break;+ case TColorStyle::DOUBLE:+ if (a->getParamValue(TColorStyle::double_tag(), p) !=+ b->getParamValue(TColorStyle::double_tag(), p))+ return false;+ break;+ case TColorStyle::FILEPATH:+ if (a->getParamValue(TColorStyle::TFilePath_tag(), p) !=+ b->getParamValue(TColorStyle::TFilePath_tag(), p))+ return false;+ break;+ default:+ break;+ }+ }+ return true;+}++int findMatchingStyleInPalette(TPalette *palette,+ const TColorStyle *targetStyle) {+ if (!palette || !targetStyle) return -1;+ for (int i = 1; i < palette->getStyleCount(); ++i) {+ TColorStyle *existing = palette->getStyle(i);+ if (stylesMatchVisually(existing, targetStyle)) return i;+ }+ return -1;+}+//-----------------------------------------------------------------------------+// Undo for style overwrite (destructive preset application or Plain Color)+//-----------------------------------------------------------------------------++namespace {+class PresetStyleOverwriteUndo final : public TUndo {+ TPaletteP m_palette;+ int m_styleId;+ TColorStyleP m_oldStyle, m_newStyle;+ TPaletteHandle *m_ph;++public:+ PresetStyleOverwriteUndo(TPalette *pal, int id, const TColorStyle *oldS,+ const TColorStyle *newS, TPaletteHandle *ph)+ : m_palette(pal)+ , m_styleId(id)+ , m_oldStyle(oldS->clone())+ , m_newStyle(newS->clone())+ , m_ph(ph) {}+ void undo() const override {+ m_palette->setStyle(m_styleId, m_oldStyle->clone());+ if (m_ph) m_ph->notifyColorStyleChanged(false, false);+ }+ void redo() const override {+ m_palette->setStyle(m_styleId, m_newStyle->clone());+ if (m_ph) m_ph->notifyColorStyleChanged(false, false);+ }+ int getSize() const override { return sizeof(*this); }+ QString getHistoryString() override {+ return QObject::tr("Apply Brush Preset");+ }+ int getHistoryType() override { return HistoryType::Palette; }+};+} // namespace++TUndo *createStyleOverwriteUndo(TPalette *palette, int styleId,+ const TColorStyle *oldStyle,+ const TColorStyle *newStyle,+ TPaletteHandle *paletteHandle) {+ return new PresetStyleOverwriteUndo(palette, styleId, oldStyle, newStyle,+ paletteHandle);+}++} // namespace BrushPresetBridge