Skip to content

OpenToonz - An open-source full-featured 2D animation creation software

C

Add Save as Custom Vector Brush command

Rodneyba1b9a23856a
diff --git a/toonz/sources/include/tools/strokeselection.h b/toonz/sources/include/tools/strokeselection.h
index d5d355fc5..97b969c9a 100644
--- a/toonz/sources/include/tools/strokeselection.h
+++ b/toonz/sources/include/tools/strokeselection.h
@@ -86,6 +86,8 @@ public:
void copy();
void cut();
void paste();
+ void saveAsCustomVectorBrush();
+ void saveVectorSelectionAs();
void removeEndpoints();
void sortWithPaletteOrder();
@@ -95,6 +97,8 @@ public:
void selectAll();
private:
+ void saveSelectedVectors(bool chooseDestination);
+
TVectorImageP m_vi; //!< Selected vector image.
IndexesContainer m_indexes; //!< Selected stroke indexes in m_vi.
diff --git a/toonz/sources/include/toonz/customvectorbrushexporter.h b/toonz/sources/include/toonz/customvectorbrushexporter.h
new file mode 100644
index 000000000..993a0c5c5
--- /dev/null
+++ b/toonz/sources/include/toonz/customvectorbrushexporter.h
@@ -0,0 +1,61 @@
+#pragma once
+
+#ifndef CUSTOM_VECTOR_BRUSH_EXPORTER_H
+#define CUSTOM_VECTOR_BRUSH_EXPORTER_H
+
+#include "tfilepath.h"
+#include "tvectorimage.h"
+
+#include <vector>
+
+#undef DVAPI
+#undef DVVAR
+#ifdef TOONZLIB_EXPORTS
+#define DVAPI DV_EXPORT_API
+#define DVVAR DV_EXPORT_VAR
+#else
+#define DVAPI DV_IMPORT_API
+#define DVVAR DV_IMPORT_VAR
+#endif
+
+class QString;
+
+namespace CustomVectorBrushExporter {
+
+struct DVAPI SourceFrame {
+ TFrameId sourceFrameId;
+ TVectorImageP image;
+
+ SourceFrame(const TFrameId &sourceFrameId = TFrameId(),
+ const TVectorImageP &image = TVectorImageP())
+ : sourceFrameId(sourceFrameId), image(image) {}
+};
+
+struct DVAPI Source {
+ std::vector<SourceFrame> frames;
+ TFrameId preferredFirstFrame;
+};
+
+struct DVAPI PreparedFile {
+ TFilePath temporaryPath;
+ TINT64 serializedBytes = 0;
+ int frameCount = 0;
+};
+
+// Writes a validated temporary PLI, placing the preferred source frame first.
+DVAPI bool prepare(const Source &source, const TFilePath &destinationFolder,
+ PreparedFile &prepared, QString &errorMessage);
+
+// Appends source frames without changing existing frame IDs.
+DVAPI bool prepareAppend(const Source &source, const TFilePath &destinationPath,
+ PreparedFile &prepared, QString &errorMessage);
+
+// Replaces destinationPath with a prepared file.
+DVAPI bool commit(PreparedFile &prepared, const TFilePath &destinationPath,
+ QString &errorMessage);
+
+DVAPI void discard(PreparedFile &prepared);
+
+} // namespace CustomVectorBrushExporter
+
+#endif // CUSTOM_VECTOR_BRUSH_EXPORTER_H
diff --git a/toonz/sources/include/toonz/stylemanager.h b/toonz/sources/include/toonz/stylemanager.h
index bc8a27edf..10d0528b2 100644
--- a/toonz/sources/include/toonz/stylemanager.h
+++ b/toonz/sources/include/toonz/stylemanager.h
@@ -8,6 +8,7 @@
#include "traster.h"
#include "toonz/mypaintbrushstyle.h"
+#include "toonz/toonzfolders.h"
#include <QSize>
#include <QVector>
@@ -144,7 +145,8 @@ public:
// CustomStyleManager declaration
//********************************************************************************
-class DVAPI CustomStyleManager final : public BaseStyleManager {
+class DVAPI CustomStyleManager final : public BaseStyleManager,
+ public FolderListenerManager::Listener {
Q_OBJECT
TThread::Executor m_executor;
@@ -152,13 +154,16 @@ class DVAPI CustomStyleManager final : public BaseStyleManager {
std::string m_rasterIdName;
std::string m_vectorIdName;
+ int m_loadGeneration;
public:
CustomStyleManager(std::string rasterIdName, std::string vectorIdName,
const TFilePath &stylesFolder, QString filters = QString(),
QSize chipSize = QSize(25, 25));
+ ~CustomStyleManager() override;
void loadItems() override;
+ void onFolderChanged(const TFilePath &path) override;
class StyleLoaderTask;
friend class CustomStyleManager::StyleLoaderTask;
diff --git a/toonz/sources/include/toonzqt/selectioncommandids.h b/toonz/sources/include/toonzqt/selectioncommandids.h
index ce45dc353..7871fd955 100644
--- a/toonz/sources/include/toonzqt/selectioncommandids.h
+++ b/toonz/sources/include/toonzqt/selectioncommandids.h
@@ -34,6 +34,7 @@
#define MI_ExitGroup "MI_ExitGroup"
#define MI_RemoveEndpoints "MI_RemoveEndpoints"
#define MI_SortWithPaletteOrder "MI_SortWithPaletteOrder"
+#define MI_SaveAsCustomVectorBrush "MI_SaveAsCustomVectorBrush"
#define MI_OpenChild "MI_OpenChild"
#define MI_CloseChild "MI_CloseChild"
diff --git a/toonz/sources/tnztools/strokeselection.cpp b/toonz/sources/tnztools/strokeselection.cpp
index 3f57bb0a4..189890594 100644
--- a/toonz/sources/tnztools/strokeselection.cpp
+++ b/toonz/sources/tnztools/strokeselection.cpp
@@ -30,11 +30,15 @@
#include "toonz/toonzscene.h"
#include "toonz/sceneproperties.h"
#include "toonz/tframehandle.h"
+#include "toonz/customvectorbrushexporter.h"
+#include "toonz/toonzfolders.h"
+#include "toonz/txshlevel.h"
// TnzCore includes
#include "tthreadmessage.h"
#include "tundo.h"
#include "tstroke.h"
+#include "tsystem.h"
#include "tvectorimage.h"
#include "tcolorstyles.h"
#include "tpalette.h"
@@ -42,10 +46,74 @@
// Qt includes
#include <QApplication>
#include <QClipboard>
+#include <QFileDialog>
+#include <QInputDialog>
+#include <QLineEdit>
+#include <QMutexLocker>
//=============================================================================
namespace {
+// Warn about unusually large brushes without preventing their use.
+constexpr TINT64 RecommendedCustomVectorBrushBytes = 32 * 1024;
+
+QString normalizeBrushName(QString name) {
+ name = name.trimmed();
+ if (name.endsWith(".pli", Qt::CaseInsensitive)) {
+ name.chop(4);
+ name = name.trimmed();
+ }
+ return name;
+}
+
+QString validateBrushName(const QString &name) {
+ if (name.isEmpty()) return QObject::tr("Please enter a brush name.");
+ if (name == "." || name == "..")
+ return QObject::tr("Please enter a valid brush name.");
+ if (name.endsWith('.') || name.endsWith(' '))
+ return QObject::tr("A brush name cannot end with a dot or a space.");
+
+ const QString invalidCharacters = "\\/:*?\"<>|";
+ for (const QChar character : name) {
+ if (character.unicode() < 32 || invalidCharacters.contains(character))
+ return QObject::tr(
+ "A brush name cannot contain \\ / : * ? \" < > | or control "
+ "characters.");
+ }
+
+ const QString deviceName = name.section('.', 0, 0).toUpper();
+ if (deviceName == "CON" || deviceName == "PRN" || deviceName == "AUX" ||
+ deviceName == "NUL" ||
+ ((deviceName.startsWith("COM") || deviceName.startsWith("LPT")) &&
+ deviceName.size() == 4 && deviceName.at(3) >= '1' &&
+ deviceName.at(3) <= '9'))
+ return QObject::tr("That brush name is reserved by the operating system.");
+
+ if (!TFilePath(name + ".pli").getFrame().isNoFrame())
+ return QObject::tr("A brush name cannot end with a numbered frame suffix.");
+
+ return QString();
+}
+
+QString suggestedBrushName() {
+ TXshLevel *level = TTool::getApplication()->getCurrentLevel()->getLevel();
+ QString name = level ? QString::fromStdWString(level->getName()) : QString();
+
+ QString sanitized;
+ const QString invalidCharacters = "\\/:*?\"<>|";
+ sanitized.reserve(name.size());
+ for (const QChar character : name) {
+ sanitized.append(character.unicode() < 32 ||
+ invalidCharacters.contains(character)
+ ? QChar('_')
+ : character);
+ }
+ sanitized = sanitized.trimmed();
+ while (sanitized.endsWith('.')) sanitized.chop(1);
+ if (sanitized.isEmpty()) sanitized = QStringLiteral("custom");
+ return sanitized + QStringLiteral("_brush");
+}
+
void vectorizeToonzImageData(const TVectorImageP &image,
const ToonzImageData *tiData,
std::set<int> &indexes, TPalette *palette,
@@ -680,6 +748,156 @@ void StrokeSelection::copy() {
// TUndoManager::manager()->add(new CopyStrokesUndo(oldData, newData));
}
+//=============================================================================
+//
+// StrokeSelection::saveAsCustomVectorBrush()
+//
+//-----------------------------------------------------------------------------
+
+void StrokeSelection::saveAsCustomVectorBrush() {
+ saveSelectedVectors(QApplication::keyboardModifiers() & Qt::ShiftModifier);
+}
+
+//-----------------------------------------------------------------------------
+
+void StrokeSelection::saveVectorSelectionAs() { saveSelectedVectors(true); }
+
+//-----------------------------------------------------------------------------
+
+void StrokeSelection::saveSelectedVectors(bool chooseDestination) {
+ if (!m_vi || m_indexes.empty()) return;
+
+ std::vector<int> indexes(m_indexes.begin(), m_indexes.end());
+ for (int index : indexes) {
+ if (index < 0 || index >= static_cast<int>(m_vi->getStrokeCount())) {
+ DVGui::error(QObject::tr(
+ "The vector selection is no longer valid. Please select it again."));
+ return;
+ }
+ }
+
+ TVectorImageP selectedImage;
+ {
+ QMutexLocker lock(m_vi->getMutex());
+ selectedImage = m_vi->splitImage(indexes, false);
+ }
+ if (!selectedImage || selectedImage->getStrokeCount() == 0) return;
+
+ QWidget *parent = QApplication::activeWindow();
+ const TFilePath brushFolder =
+ ToonzFolder::getLibraryFolder() + "vector brushes";
+ TFilePath destination;
+
+ if (chooseDestination) {
+ TFilePath initialFolder = brushFolder;
+ TXshLevel *level = TTool::getApplication()->getCurrentLevel()->getLevel();
+ if (level && !level->getPath().isEmpty()) {
+ TFilePath levelPath = level->getPath();
+ if (m_sceneHandle && m_sceneHandle->getScene())
+ levelPath = m_sceneHandle->getScene()->decodeFilePath(levelPath);
+ if (!levelPath.isEmpty()) initialFolder = levelPath.getParentDir();
+ }
+
+ const TFilePath initialPath =
+ initialFolder + TFilePath(suggestedBrushName() + ".pli");
+ QString fileName = QFileDialog::getSaveFileName(
+ parent, QObject::tr("Save Vector Selection As"),
+ initialPath.getQString(), QObject::tr("OpenToonz Vector Level (*.pli)"),
+ nullptr, QFileDialog::DontConfirmOverwrite);
+ if (fileName.isEmpty()) return;
+
+ destination = TFilePath(fileName);
+ if (QString::fromStdString(destination.getType())
+ .compare("pli", Qt::CaseInsensitive) != 0)
+ destination = TFilePath(destination.getWideString() + L".pli");
+ } else {
+ QString proposedName = suggestedBrushName();
+ QString brushName;
+ while (brushName.isEmpty()) {
+ bool accepted = false;
+ QString input = QInputDialog::getText(
+ parent, QObject::tr("Save as Custom Vector Brush"),
+ QObject::tr("Brush name:"), QLineEdit::Normal, proposedName,
+ &accepted);
+ if (!accepted) return;
+
+ input = normalizeBrushName(input);
+ const QString error = validateBrushName(input);
+ if (!error.isEmpty()) {
+ DVGui::warning(error);
+ proposedName = input;
+ continue;
+ }
+ brushName = input;
+ }
+ destination = brushFolder + TFilePath(brushName + ".pli");
+ }
+
+ bool appendToDestination = false;
+ if (TFileStatus(destination).doesExist()) {
+ const QString question =
+ chooseDestination
+ ? QObject::tr("The file '%1' already exists.")
+ .arg(destination.getQString())
+ : QObject::tr("The custom vector brush '%1' already exists.")
+ .arg(QString::fromStdWString(destination.getWideName()));
+ const int choice =
+ DVGui::MsgBox(question, QObject::tr("Overwrite"), QObject::tr("Append"),
+ QObject::tr("Cancel"), 2, parent);
+ if (choice != 1 && choice != 2) return;
+ appendToDestination = choice == 2;
+ }
+
+ const TFilePath destinationFolder = destination.getParentDir();
+ const bool installsCustomBrush = destinationFolder == brushFolder;
+
+ TTool *tool = TTool::getApplication()->getCurrentTool()->getTool();
+ const TFrameId sourceFrameId = tool ? tool->getCurrentFid() : TFrameId(1);
+
+ CustomVectorBrushExporter::Source source;
+ source.preferredFirstFrame = sourceFrameId;
+ source.frames.emplace_back(sourceFrameId, selectedImage);
+
+ CustomVectorBrushExporter::PreparedFile prepared;
+ QString errorMessage;
+ if (!CustomVectorBrushExporter::prepare(source, destinationFolder, prepared,
+ errorMessage)) {
+ DVGui::error(errorMessage);
+ return;
+ }
+
+ if (installsCustomBrush &&
+ prepared.serializedBytes > RecommendedCustomVectorBrushBytes) {
+ const TINT64 sizeInKilobytes = (prepared.serializedBytes + 1023) / 1024;
+ const QString question =
+ QObject::tr(
+ "This custom vector brush is %1 KB, above the recommended size "
+ "of 32 KB. Large vector brushes may reduce drawing and rendering "
+ "performance. Continue?")
+ .arg(sizeInKilobytes);
+ if (DVGui::MsgBox(question, QObject::tr("Continue"), QObject::tr("Cancel"),
+ 1, parent) != 1) {
+ CustomVectorBrushExporter::discard(prepared);
+ return;
+ }
+ }
+
+ if (appendToDestination && !CustomVectorBrushExporter::prepareAppend(
+ source, destination, prepared, errorMessage)) {
+ CustomVectorBrushExporter::discard(prepared);
+ DVGui::error(errorMessage);
+ return;
+ }
+
+ if (!CustomVectorBrushExporter::commit(prepared, destination, errorMessage)) {
+ CustomVectorBrushExporter::discard(prepared);
+ DVGui::error(errorMessage);
+ return;
+ }
+
+ FolderListenerManager::instance()->notifyFolderChanged(destinationFolder);
+}
+
//=============================================================================
//
// StrokeSelection::paste()
@@ -788,6 +1006,8 @@ void StrokeSelection::enableCommands() {
enableCommand(this, MI_Cut, &StrokeSelection::cut);
enableCommand(this, MI_Copy, &StrokeSelection::copy);
enableCommand(this, MI_Paste, &StrokeSelection::paste);
+ enableCommand(this, MI_SaveAsCustomVectorBrush,
+ &StrokeSelection::saveAsCustomVectorBrush);
enableCommand(m_groupCommand.get(), MI_Group, &TGroupCommand::group);
enableCommand(m_groupCommand.get(), MI_Ungroup, &TGroupCommand::ungroup);
diff --git a/toonz/sources/tnztools/vectorselectiontool.cpp b/toonz/sources/tnztools/vectorselectiontool.cpp
index 670560a2d..8d8acac9a 100644
--- a/toonz/sources/tnztools/vectorselectiontool.cpp
+++ b/toonz/sources/tnztools/vectorselectiontool.cpp
@@ -24,6 +24,9 @@
// TnzCore includes
#include "drawutil.h"
+// Qt includes
+#include <QApplication>
+
using namespace ToolUtils;
using namespace DragSelectionTool;
@@ -1799,6 +1802,19 @@ void VectorSelectionTool::addContextMenuItems(QMenu *menu) {
menu->addSeparator();
m_strokeSelection.getGroupCommand()->addMenuItems(menu);
+
+ if (!m_strokeSelection.isEmpty()) {
+ menu->addSeparator();
+ if (QApplication::keyboardModifiers() & Qt::ShiftModifier) {
+ QAction *saveSelectionAction =
+ menu->addAction(tr("Save Vector Selection As..."));
+ QObject::connect(saveSelectionAction, &QAction::triggered, menu,
+ [this]() { m_strokeSelection.saveVectorSelectionAs(); });
+ } else {
+ menu->addAction(
+ CommandManager::instance()->getAction(MI_SaveAsCustomVectorBrush));
+ }
+ }
}
//-----------------------------------------------------------------------------
diff --git a/toonz/sources/toonz/mainwindow.cpp b/toonz/sources/toonz/mainwindow.cpp
index 4e91252b5..0d03c41ed 100644
--- a/toonz/sources/toonz/mainwindow.cpp
+++ b/toonz/sources/toonz/mainwindow.cpp
@@ -2826,6 +2826,8 @@ void MainWindow::defineActions() {
CommandManager::instance()->setToggleTexts(
MI_FreezePreview, tr("Freeze Preview"), tr("Unfreeze Preview"));
createRightClickMenuAction(MI_SavePreset, QT_TR_NOOP("&Save As Preset"), "");
+ createRightClickMenuAction(MI_SaveAsCustomVectorBrush,
+ QT_TR_NOOP("Save as Custom Vector Brush..."), "");
createRightClickMenuAction(MI_PreviewFx, QT_TR_NOOP("Preview Fx"), "");
createRightClickMenuAction(MI_PasteValues, QT_TR_NOOP("&Paste Color && Name"),
"", "paste_color_and_name");
diff --git a/toonz/sources/toonzlib/CMakeLists.txt b/toonz/sources/toonzlib/CMakeLists.txt
index 4f809c31b..b70cfa8c8 100644
--- a/toonz/sources/toonzlib/CMakeLists.txt
+++ b/toonz/sources/toonzlib/CMakeLists.txt
@@ -76,6 +76,7 @@ set(HEADERS
../include/toonz/cleanupparameters.h
../include/toonz/columnfan.h
../include/toonz/controlpointobserver.h
+ ../include/toonz/customvectorbrushexporter.h
../include/toonz/currentimage.h
../include/toonz/doubleparamcmd.h
../include/toonz/dpiscale.h
@@ -178,6 +179,7 @@ set(SOURCES
cleanupparameters.cpp
columnfan.cpp
convert2tlv.cpp
+ customvectorbrushexporter.cpp
dpiscale.cpp
fill.cpp
fillutil.cpp
diff --git a/toonz/sources/toonzlib/customvectorbrushexporter.cpp b/toonz/sources/toonzlib/customvectorbrushexporter.cpp
new file mode 100644
index 000000000..473c489dc
--- /dev/null
+++ b/toonz/sources/toonzlib/customvectorbrushexporter.cpp
@@ -0,0 +1,397 @@
+#include "toonz/customvectorbrushexporter.h"
+
+#include "tcolorstyles.h"
+#include "tcontenthistory.h"
+#include "tlevel.h"
+#include "tlevel_io.h"
+#include "tpalette.h"
+#include "tsystem.h"
+
+#include <QDir>
+#include <QObject>
+#include <QTemporaryFile>
+
+#include <algorithm>
+#include <limits>
+#include <set>
+
+namespace CustomVectorBrushExporter {
+namespace {
+
+constexpr int VectorImagePatternStyleTag = 2800;
+constexpr int VectorBrushStyleTag = 3000;
+
+using FrameIds = std::set<TFrameId>;
+
+QString exceptionMessage(const TException &exception) {
+ return QString::fromStdWString(exception.getMessage());
+}
+
+bool hasUnsupportedStyles(const TVectorImageP &image) {
+ TPalette *palette = image ? image->getPalette() : nullptr;
+ if (!palette) return false;
+
+ std::set<int> usedStyles;
+ image->getUsedStyles(usedStyles);
+ for (int styleId : usedStyles) {
+ TColorStyle *style = palette->getStyle(styleId);
+ if (!style) continue;
+ const int tagId = style->getTagId();
+ if (tagId == VectorImagePatternStyleTag || tagId == VectorBrushStyleTag)
+ return true;
+ }
+ return false;
+}
+
+void removeTemporaryFile(const TFilePath &path) {
+ if (path.isEmpty()) return;
+ try {
+ if (TFileStatus(path).doesExist()) TSystem::deleteFile(path);
+ } catch (...) {
+ }
+}
+
+bool validateSource(const Source &source,
+ std::vector<const SourceFrame *> &orderedFrames,
+ QString &errorMessage) {
+ if (source.frames.empty()) {
+ errorMessage = QObject::tr("No vector brush frames were supplied.");
+ return false;
+ }
+
+ std::set<TFrameId> frameIds;
+ auto preferred = source.frames.end();
+ for (auto it = source.frames.begin(); it != source.frames.end(); ++it) {
+ if (!it->image || it->image->getStrokeCount() == 0) {
+ errorMessage = QObject::tr("A vector brush frame is empty.");
+ return false;
+ }
+ if (!frameIds.insert(it->sourceFrameId).second) {
+ errorMessage = QObject::tr("A vector brush source frame is duplicated.");
+ return false;
+ }
+ if (it->sourceFrameId == source.preferredFirstFrame) preferred = it;
+ if (hasUnsupportedStyles(it->image)) {
+ errorMessage = QObject::tr(
+ "The selection uses a Vector Brush or Vector Image Pattern style. "
+ "Nested vector brush dependencies cannot be saved as a custom "
+ "vector brush.");
+ return false;
+ }
+ }
+
+ if (preferred == source.frames.end()) {
+ errorMessage =
+ QObject::tr("The preferred first frame is not in the brush source.");
+ return false;
+ }
+
+ orderedFrames.reserve(source.frames.size());
+ orderedFrames.push_back(&*preferred);
+ for (const SourceFrame &frame : source.frames)
+ if (frame.sourceFrameId != source.preferredFirstFrame)
+ orderedFrames.push_back(&frame);
+
+ return true;
+}
+
+TVectorImageP prepareFrame(const TVectorImageP &source,
+ const TPaletteP &sharedPalette,
+ QString &errorMessage) {
+ TVectorImageP sourceCopy = source->clone();
+ TVectorImageP output = new TVectorImage();
+ output->setPalette(sharedPalette.getPointer());
+ output->setAutocloseTolerance(source->getAutocloseTolerance());
+ output->mergeImage(sourceCopy, TAffine());
+ output->findRegions();
+
+ const TRectD bounds = output->getBBox();
+ if (bounds.isEmpty() || bounds.x0 >= bounds.x1 || bounds.y0 >= bounds.y1) {
+ errorMessage = QObject::tr(
+ "The selection has no usable width or height for a vector brush.");
+ return TVectorImageP();
+ }
+
+ return output;
+}
+
+bool validateWrittenLevel(const TFilePath &path,
+ const FrameIds &expectedFrameIds,
+ QString &errorMessage) {
+ try {
+ TLevelReaderP reader(path);
+ TLevelP level = reader->loadInfo();
+ if (!level ||
+ level->getFrameCount() != static_cast<int>(expectedFrameIds.size())) {
+ errorMessage = QObject::tr(
+ "The custom vector brush file could not be validated after writing.");
+ return false;
+ }
+
+ FrameIds writtenFrameIds;
+ for (TLevel::Iterator it = level->begin(); it != level->end(); ++it)
+ writtenFrameIds.insert(it->first);
+ if (writtenFrameIds != expectedFrameIds) {
+ errorMessage = QObject::tr(
+ "The custom vector brush file contains unexpected frame IDs after "
+ "writing.");
+ return false;
+ }
+
+ for (const TFrameId &frameId : expectedFrameIds) {
+ TImageReaderP frameReader = reader->getFrameReader(frameId);
+ TVectorImageP frame;
+ if (frameReader) frame = frameReader->load();
+ if (!frame) {
+ errorMessage =
+ QObject::tr(
+ "The custom vector brush file does not contain a valid frame "
+ "%1.")
+ .arg(QString::fromStdString(frameId.expand(TFrameId::NO_PAD)));
+ return false;
+ }
+ }
+ } catch (const TException &exception) {
+ errorMessage = QObject::tr("Could not validate the custom vector brush: %1")
+ .arg(exceptionMessage(exception));
+ return false;
+ } catch (...) {
+ errorMessage = QObject::tr(
+ "An unexpected error occurred while validating the custom vector "
+ "brush.");
+ return false;
+ }
+ return true;
+}
+
+bool prepareLevel(const TLevelP &level, const FrameIds &expectedFrameIds,
+ const TFilePath &destinationFolder, const QString &creator,
+ const TContentHistory *contentHistory, PreparedFile &prepared,
+ QString &errorMessage) {
+ removeTemporaryFile(prepared.temporaryPath);
+ prepared = PreparedFile();
+
+ try {
+ if (!TFileStatus(destinationFolder).doesExist())
+ TSystem::mkDir(destinationFolder);
+ if (!TFileStatus(destinationFolder).isWritableDir()) {
+ errorMessage = QObject::tr("The destination folder is not writable: %1")
+ .arg(destinationFolder.getQString());
+ return false;
+ }
+
+ QDir folder(destinationFolder.getQString());
+ {
+ // The Windows PLI stream requires the temporary-file reservation to be
+ // released before it can open the path.
+ QTemporaryFile temporaryFile(
+ folder.filePath(".custom-vector-brush-XXXXXX.pli"));
+ temporaryFile.setAutoRemove(true);
+ if (!temporaryFile.open()) {
+ errorMessage = QObject::tr(
+ "Could not reserve a temporary PLI file in the destination "
+ "folder.");
+ return false;
+ }
+ prepared.temporaryPath = TFilePath(temporaryFile.fileName());
+ }
+
+ if (TFileStatus(prepared.temporaryPath).doesExist()) {
+ errorMessage = QObject::tr("Could not release the temporary PLI file.");
+ removeTemporaryFile(prepared.temporaryPath);
+ prepared = PreparedFile();
+ return false;
+ }
+
+ TLevelWriterP writer(prepared.temporaryPath);
+ if (!creator.isEmpty()) writer->setCreator(creator);
+ if (contentHistory) writer->setContentHistory(contentHistory->clone());
+ writer->save(level);
+ writer = TLevelWriterP(); // PLI serialization finishes in the destructor.
+
+ TFileStatus fileStatus(prepared.temporaryPath);
+ if (!fileStatus.doesExist()) {
+ errorMessage =
+ QObject::tr("The PLI writer could not create a temporary file in: %1")
+ .arg(destinationFolder.getQString());
+ removeTemporaryFile(prepared.temporaryPath);
+ prepared = PreparedFile();
+ return false;
+ }
+ if (fileStatus.getSize() <= 0) {
+ errorMessage = QObject::tr("The PLI writer created an empty file.");
+ removeTemporaryFile(prepared.temporaryPath);
+ prepared = PreparedFile();
+ return false;
+ }
+
+ prepared.serializedBytes = fileStatus.getSize();
+ prepared.frameCount = static_cast<int>(expectedFrameIds.size());
+ if (!validateWrittenLevel(prepared.temporaryPath, expectedFrameIds,
+ errorMessage)) {
+ removeTemporaryFile(prepared.temporaryPath);
+ prepared = PreparedFile();
+ return false;
+ }
+ } catch (const TException &exception) {
+ errorMessage = QObject::tr("Could not save the PLI file: %1")
+ .arg(exceptionMessage(exception));
+ removeTemporaryFile(prepared.temporaryPath);
+ prepared = PreparedFile();
+ return false;
+ } catch (...) {
+ errorMessage =
+ QObject::tr("An unexpected error occurred while saving the PLI file.");
+ removeTemporaryFile(prepared.temporaryPath);
+ prepared = PreparedFile();
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace
+
+void discard(PreparedFile &prepared) {
+ removeTemporaryFile(prepared.temporaryPath);
+ prepared = PreparedFile();
+}
+
+bool prepare(const Source &source, const TFilePath &destinationFolder,
+ PreparedFile &prepared, QString &errorMessage) {
+ discard(prepared);
+ errorMessage.clear();
+
+ std::vector<const SourceFrame *> orderedFrames;
+ if (!validateSource(source, orderedFrames, errorMessage)) return false;
+
+ TPaletteP sharedPalette = new TPalette();
+ TLevelP level = new TLevel();
+ level->setPalette(sharedPalette.getPointer());
+
+ FrameIds expectedFrameIds;
+ int outputFrameNumber = 1;
+ for (const SourceFrame *sourceFrame : orderedFrames) {
+ TVectorImageP output =
+ prepareFrame(sourceFrame->image, sharedPalette, errorMessage);
+ if (!output) return false;
+
+ TFrameId outputFrameId(outputFrameNumber++);
+ level->setFrame(outputFrameId, output);
+ expectedFrameIds.insert(outputFrameId);
+ }
+
+ return prepareLevel(level, expectedFrameIds, destinationFolder, QString(),
+ nullptr, prepared, errorMessage);
+}
+
+bool prepareAppend(const Source &source, const TFilePath &destinationPath,
+ PreparedFile &prepared, QString &errorMessage) {
+ discard(prepared);
+ errorMessage.clear();
+
+ std::vector<const SourceFrame *> orderedFrames;
+ if (!validateSource(source, orderedFrames, errorMessage)) return false;
+
+ try {
+ TLevelReaderP reader(destinationPath);
+ TLevelP existingLevel = reader->loadInfo();
+ if (!existingLevel || existingLevel->getFrameCount() == 0) {
+ errorMessage =
+ QObject::tr("The existing PLI file does not contain any frames.");
+ return false;
+ }
+
+ TPalette *existingPalette = existingLevel->getPalette();
+ if (!existingPalette) {
+ errorMessage =
+ QObject::tr("The existing PLI file does not contain a palette.");
+ return false;
+ }
+
+ TPaletteP sharedPalette = existingPalette->clone();
+ TLevelP outputLevel = new TLevel();
+ outputLevel->setPalette(sharedPalette.getPointer());
+
+ FrameIds expectedFrameIds;
+ int highestFrameNumber = 0;
+ for (TLevel::Iterator it = existingLevel->begin();
+ it != existingLevel->end(); ++it) {
+ const TFrameId frameId = it->first;
+ highestFrameNumber = (std::max)(highestFrameNumber, frameId.getNumber());
+
+ TImageReaderP frameReader = reader->getFrameReader(frameId);
+ TVectorImageP frame;
+ if (frameReader) frame = frameReader->load();
+ if (!frame) {
+ errorMessage =
+ QObject::tr("Could not load frame %1 from the existing PLI file.")
+ .arg(QString::fromStdString(frameId.expand(TFrameId::NO_PAD)));
+ return false;
+ }
+
+ frame->setPalette(sharedPalette.getPointer());
+ outputLevel->setFrame(frameId, frame);
+ expectedFrameIds.insert(frameId);
+ }
+
+ const int maximumFrameNumber = (std::numeric_limits<int>::max)();
+ if (highestFrameNumber >
+ maximumFrameNumber - static_cast<int>(orderedFrames.size())) {
+ errorMessage =
+ QObject::tr("The existing PLI file has no available frame numbers.");
+ return false;
+ }
+
+ int nextFrameNumber = highestFrameNumber + 1;
+ for (const SourceFrame *sourceFrame : orderedFrames) {
+ TVectorImageP output =
+ prepareFrame(sourceFrame->image, sharedPalette, errorMessage);
+ if (!output) return false;
+
+ TFrameId outputFrameId(nextFrameNumber++);
+ outputLevel->setFrame(outputFrameId, output);
+ expectedFrameIds.insert(outputFrameId);
+ }
+
+ return prepareLevel(outputLevel, expectedFrameIds,
+ destinationPath.getParentDir(), reader->getCreator(),
+ reader->getContentHistory(), prepared, errorMessage);
+ } catch (const TException &exception) {
+ errorMessage = QObject::tr("Could not append to the PLI file: %1")
+ .arg(exceptionMessage(exception));
+ return false;
+ } catch (...) {
+ errorMessage = QObject::tr(
+ "An unexpected error occurred while appending to the PLI "
+ "file.");
+ return false;
+ }
+}
+
+bool commit(PreparedFile &prepared, const TFilePath &destinationPath,
+ QString &errorMessage) {
+ errorMessage.clear();
+ if (prepared.temporaryPath.isEmpty() ||
+ !TFileStatus(prepared.temporaryPath).doesExist()) {
+ errorMessage = QObject::tr("No prepared custom vector brush file exists.");
+ return false;
+ }
+
+ try {
+ TSystem::replaceFile(destinationPath, prepared.temporaryPath);
+ prepared = PreparedFile();
+ } catch (const TException &exception) {
+ errorMessage = QObject::tr("Could not install the custom vector brush: %1")
+ .arg(exceptionMessage(exception));
+ return false;
+ } catch (...) {
+ errorMessage = QObject::tr(
+ "An unexpected error occurred while installing the custom vector "
+ "brush.");
+ return false;
+ }
+ return true;
+}
+
+} // namespace CustomVectorBrushExporter
diff --git a/toonz/sources/toonzlib/stylemanager.cpp b/toonz/sources/toonzlib/stylemanager.cpp
index dada685d4..c0520c8fb 100644
--- a/toonz/sources/toonzlib/stylemanager.cpp
+++ b/toonz/sources/toonzlib/stylemanager.cpp
@@ -243,6 +243,7 @@ class CustomStyleManager::StyleLoaderTask final : public TThread::Runnable {
TFilePath m_fp;
ChipData m_data;
std::shared_ptr<QOffscreenSurface> m_offScreenSurface;
+ int m_loadGeneration;
public:
StyleLoaderTask(CustomStyleManager *manager, const TFilePath &fp);
@@ -256,7 +257,9 @@ public:
CustomStyleManager::StyleLoaderTask::StyleLoaderTask(
CustomStyleManager *manager, const TFilePath &fp)
- : m_manager(manager), m_fp(fp) {
+ : m_manager(manager)
+ , m_fp(fp)
+ , m_loadGeneration(manager->m_loadGeneration) {
connect(this, SIGNAL(finished(TThread::RunnableP)), this,
SLOT(onFinished(TThread::RunnableP)));
@@ -278,7 +281,8 @@ void CustomStyleManager::StyleLoaderTask::run() {
void CustomStyleManager::StyleLoaderTask::onFinished(
TThread::RunnableP sender) {
// On the main thread...
- if (!m_data.image.isNull()) // Everything went ok
+ if (m_loadGeneration == m_manager->m_loadGeneration &&
+ !m_data.image.isNull()) // Everything went ok
{
m_manager->m_chips.append(m_data);
emit m_manager->patternAdded();
@@ -296,8 +300,30 @@ CustomStyleManager::CustomStyleManager(std::string rasterIdName,
: BaseStyleManager(stylesFolder, filters, chipSize)
, m_started(false)
, m_rasterIdName(rasterIdName)
- , m_vectorIdName(vectorIdName) {
+ , m_vectorIdName(vectorIdName)
+ , m_loadGeneration(0) {
m_executor.setMaxActiveTasks(1);
+ FolderListenerManager::instance()->addListener(this);
+}
+
+//-----------------------------------------------------------------------------
+
+CustomStyleManager::~CustomStyleManager() {
+ FolderListenerManager::instance()->removeListener(this);
+ m_executor.cancelAll();
+}
+
+//-----------------------------------------------------------------------------
+
+void CustomStyleManager::onFolderChanged(const TFilePath &path) {
+ if (path != getRootPath() + m_stylesFolder) return;
+
+ ++m_loadGeneration;
+ m_executor.cancelAll();
+ m_chips.clear();
+ m_indexes.clear();
+ emit patternAdded();
+ loadItems();
}
//-----------------------------------------------------------------------------