Skip to content

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

C

Add feature to rename image sequences with separator (#5768)

Abel_Youb2df327c86ef
diff --git a/toonz/sources/common/tsystem/tsystem.cpp b/toonz/sources/common/tsystem/tsystem.cpp
index 5199d101b..a1fcdcb62 100644
--- a/toonz/sources/common/tsystem/tsystem.cpp
+++ b/toonz/sources/common/tsystem/tsystem.cpp
@@ -22,6 +22,7 @@ using namespace std;
#include <QUrl>
#include <QCoreApplication>
#include <QUuid>
+#include <QRegularExpression>
#include <QDesktopServices>
#include <QHostInfo>
@@ -854,6 +855,31 @@ void TSystem::copyFileOrLevel_throw(const TFilePath &dst,
//--------------------------------------------------------------
+bool TSystem::renameImageSequence(const TFilePathSet &files,
+ const TFilePath &levelPath,
+ int prefixLength) {
+ std::string levelBaseName = levelPath.withoutParentDir().getName();
+
+ //TSystem::readDirectory(levelPath.getParentDir(), false);
+
+ std::wstring wstr;
+ TFilePath dst;
+
+ for (const TFilePath &file : files) {
+ wstr = file.getWideName();
+ if (wstr.size() > prefixLength)
+ wstr = wstr.substr(prefixLength);
+ else
+ wstr.clear();
+ dst = file.withName(levelBaseName).withFrame(TFrameId(TFrameId(wstr).expand()));
+ try {
+ TSystem::renameFile(dst, file);
+ } catch (...){
+ return false;
+ }
+ }
+}
+
void TSystem::renameFileOrLevel_throw(const TFilePath &dst,
const TFilePath &src,
bool renamePalette) {
diff --git a/toonz/sources/include/toonz/preferencesitemids.h b/toonz/sources/include/toonz/preferencesitemids.h
index 3ef40d1dd..8ff5ffaff 100644
--- a/toonz/sources/include/toonz/preferencesitemids.h
+++ b/toonz/sources/include/toonz/preferencesitemids.h
@@ -50,6 +50,7 @@ enum PreferencesItemId {
//----------
// Loading
importPolicy,
+ renamePolicy,
autoExposeEnabled,
subsceneFolderEnabled,
removeSceneNumberFromLoadedLevelName,
diff --git a/toonz/sources/include/toonz/tscenehandle.h b/toonz/sources/include/toonz/tscenehandle.h
index 57aa7bb39..b15f49218 100644
--- a/toonz/sources/include/toonz/tscenehandle.h
+++ b/toonz/sources/include/toonz/tscenehandle.h
@@ -60,6 +60,9 @@ public:
void notifyImportPolicyChanged(int policy) {
emit importPolicyChanged(policy);
}
+ void notifyRenamePolicyChanged(int policy) {
+ emit renamePolicyChanged(policy);
+ }
void setDirtyFlag(bool dirtyFlag) {
if (m_dirtyFlag == dirtyFlag) return;
@@ -84,6 +87,7 @@ signals:
void preferenceChanged(const QString &prefName);
void pixelUnitSelected(bool on);
void importPolicyChanged(int policy);
+ void renamePolicyChanged(int policy);
};
#endif // TSCENEHANDLE_H
diff --git a/toonz/sources/include/tsystem.h b/toonz/sources/include/tsystem.h
index bb93eb5c8..ee7da07d9 100644
--- a/toonz/sources/include/tsystem.h
+++ b/toonz/sources/include/tsystem.h
@@ -166,6 +166,9 @@ DVAPI void hideFile(const TFilePath &dst);
DVAPI void moveFileToRecycleBin(const TFilePath &fp);
DVAPI void copyFileOrLevel_throw(const TFilePath &dst, const TFilePath &src);
+DVAPI bool renameImageSequence(const TFilePathSet &files,
+ const TFilePath &levelName,
+ int prefixLength);
DVAPI void renameFileOrLevel_throw(const TFilePath &dst, const TFilePath &src,
bool renamePalette = false);
DVAPI void removeFileOrLevel_throw(const TFilePath &fp);
diff --git a/toonz/sources/toonz/iocommand.cpp b/toonz/sources/toonz/iocommand.cpp
index c50eb6dbb..fe5e193a6 100644
--- a/toonz/sources/toonz/iocommand.cpp
+++ b/toonz/sources/toonz/iocommand.cpp
@@ -1,4 +1,5 @@
#include <memory>
+#include <cwctype>
#include "iocommand.h"
@@ -82,6 +83,7 @@
#include <QLabel>
#include <QApplication>
#include <QClipboard>
+#include <QDirIterator>
// boost includes
#include <boost/optional.hpp>
@@ -153,6 +155,7 @@ public:
QString checkBoxLabel =
QObject::tr("Always do this action.")
.arg(QString::fromStdWString(path.getWideString()));
+ QString addSeparatorLabel = QObject::tr("Add separator for Frames");
QStringList buttons;
buttons << QObject::tr("Import") << QObject::tr("Load")
<< QObject::tr("Cancel");
@@ -2430,6 +2433,84 @@ int IoCmd::loadResources(LoadResourceArguments &args, bool updateRecentFile,
static bool isDir(const LoadResourceArguments::ResourceData &rd) {
return QFileInfo(rd.m_path.getQString()).isDir();
}
+
+ // call when loading levels
+ static bool matchSequencePattern(const TFilePath &path) {
+ QRegularExpression pattern(
+ R"(
+ ^ # Match the start of the string
+ .*? # Optional prefix
+ \d+ # allow aFilePrefix<number>.ext,ignore if less than 10 and no padding
+ \. # Match a dot (.)
+ (png|jpg|jpeg|bmp|tga|tiff) # Image extensions
+ $ # Match the end of the string
+)",
+ QRegularExpression::CaseInsensitiveOption |
+ QRegularExpression::ExtendedPatternSyntaxOption);
+ return pattern.match(QString::fromStdString(path.getLevelName()))
+ .hasMatch();
+ };
+
+ static bool checkRenamePolicy(const TFilePath &path) {
+ // TODO: Check the Preference Policy
+ switch (Preferences::instance()->getIntValue(renamePolicy)) {
+ case 0:
+ break;
+ case 1:
+ return true;
+ case 2:
+ return false;
+ }
+ QString label =
+ QObject::tr(
+ "OpenToonz uses an underscore (_) or dot (.) as a frame "
+ "separator.\n"
+ "Would you like to add a separator to the image sequence?\n"
+ "\n%1 (and similar files)")
+ .arg(path.getQString());
+ QString checkBoxLabel = QObject::tr("Always do this action.");
+ QStringList buttons;
+ buttons << QObject::tr("Yes")
+ << QObject::tr("No, treat as single frame.");
+ DVGui::MessageAndCheckboxDialog *renameDialog =
+ DVGui::createMsgandCheckbox(DVGui::QUESTION, label, checkBoxLabel,
+ buttons, 1, Qt::Unchecked);
+ int ret = renameDialog->exec();
+ int checked = renameDialog->getChecked();
+ if (checked) {
+ Preferences::instance()->setValue(renamePolicy, ret);
+ TApp::instance()->getCurrentScene()->notifyImportPolicyChanged(ret);
+ }
+ return ret == 1;
+ };
+
+ static bool isSharingSameParam(const TFilePath &path1,
+ const TFilePath &path2) {
+ std::wstring str1 = path1.getWideName(); // base name
+ std::wstring str2 = path2.getWideName();
+
+ str1.erase(std::remove_if(str1.begin(), str1.end(), ::iswdigit),
+ str1.end());
+ str2.erase(std::remove_if(str2.begin(), str2.end(), ::iswdigit),
+ str2.end());
+
+ return str1 == str2;
+ }
+
+ static TFilePath getLevelPath(TFilePath path) {
+ std::wstring levelBaseName = path.getWideName();
+
+ int i = levelBaseName.size();
+ while (i > 0 && std::iswdigit(levelBaseName[i - 1])) {
+ --i;
+ }
+ levelBaseName = levelBaseName.substr(0, i);
+
+ if (!levelBaseName.size())
+ levelBaseName = path.getParentDir().getWideName();
+ return path.withName(levelBaseName).withFrame();
+ }
+
}; // locals
if (args.resourceDatas.empty()) return 0;
@@ -2479,10 +2560,10 @@ int IoCmd::loadResources(LoadResourceArguments &args, bool updateRecentFile,
}
std::vector<TFilePath> paths;
- int all = 0;
+ int all = 0; // Turn on to allow all duplicate
// Loop for all the resources to load
- for (int r = 0; r != rCount; ++r) {
+ for (int r = 0; r < rCount; ++r) {
if (importDialog.aborted()) break;
QString origName =
@@ -2580,6 +2661,84 @@ int IoCmd::loadResources(LoadResourceArguments &args, bool updateRecentFile,
continue;
}
+ // for single level files
+ else if (path.getSepChar().isNull()) {
+ // for single frame
+ if (rCount == 1) {
+ try {
+ path = importDialog.process(scene, 0, path);
+ } catch (std::string msg) {
+ error(QString::fromStdString(msg));
+ continue;
+ }
+ }
+ // for sequence
+ else if (locals::matchSequencePattern(path) &&
+ locals::checkRenamePolicy(path)) {
+ TFilePathSet files;
+ TFilePath backup = scene->codeFilePath(path);
+ TFilePath levelPath = locals::getLevelPath(path);
+ progressDialog->setLabelText(
+ QString("Loading \"%1\"...")
+ .arg(levelPath.withFrame().getQString()));
+ // Check for Existing Level
+ if (TSystem::doesExistFileOrLevel(levelPath)) {
+ OverwriteDialog dialog;
+ levelPath.withName(dialog.execute(scene, levelPath, false));
+
+ switch (dialog.getChoice()) {
+ case OverwriteDialog::KEEP_OLD:
+ while (r < rCount) {
+ path = args.resourceDatas[r].m_path;
+ if (backup.getParentDir() != path.getParentDir()) break;
+ if (!locals::isSharingSameParam(backup, path)) break;
+ ++r;
+ }
+ --r;
+ continue;
+
+ case OverwriteDialog::OVERWRITE :
+ TSystem::removeFileOrLevel(levelPath);
+ default :
+ break;
+ }
+ }
+ // Load or Import the files
+ while (r < rCount) {
+ path = args.resourceDatas[r].m_path;
+ progressDialog->setValue(r);
+ try {
+ path = importDialog.process(scene, 0, path);
+ } catch (std::string msg) {
+ error(QString::fromStdString(msg));
+ continue;
+ }
+ if (importDialog.aborted()) break;
+ // and Same parent folder
+ if ((backup.getParentDir() != path.getParentDir()) ||
+ (!locals::isSharingSameParam(backup, path))) {
+ --r;
+ break;
+ }
+ files.push_back(path);
+ ++r;
+ }
+ if (importDialog.aborted()) break;
+ if(TSystem::renameImageSequence(
+ files, levelPath,
+ backup.getWideName().substr(0,
+ backup.getWideName().find_last_not_of(L"0123456789") + 1)
+ .size())) {
+ QCoreApplication::processEvents();
+ path = levelPath;
+ } else {
+ // Failed to rename Files
+ DVGui::warning(QString("Failed to rename files!"));
+ break;
+ }
+
+ }
+ }
// for other level files
else {
try {
@@ -2592,6 +2751,7 @@ int IoCmd::loadResources(LoadResourceArguments &args, bool updateRecentFile,
if (importDialog.aborted()) break;
}
+
if (path.getType() == "psd") {
static PsdSettingsPopup *popup = 0;
if (!popup) {
diff --git a/toonz/sources/toonz/preferencespopup.cpp b/toonz/sources/toonz/preferencespopup.cpp
index bd1986796..08cea4f72 100644
--- a/toonz/sources/toonz/preferencespopup.cpp
+++ b/toonz/sources/toonz/preferencespopup.cpp
@@ -953,6 +953,13 @@ void PreferencesPopup::onImportPolicyExternallyChanged(int policy) {
//-----------------------------------------------------------------------------
+void PreferencesPopup::onRenamePolicyExternallyChanged(int policy) {
+ QComboBox* renamePolicyCombo = getUI<QComboBox*>(renamePolicy);
+ // update preferences data accordingly
+ renamePolicyCombo->setCurrentIndex(policy);
+}
+//-----------------------------------------------------------------------------
+
QWidget* PreferencesPopup::createUI(PreferencesItemId id,
const QList<ComboBoxItem>& comboItems) {
PreferencesItem item = m_pref->getItem(id);
@@ -1239,6 +1246,7 @@ QString PreferencesPopup::getUIString(PreferencesItemId id) {
// Loading
{importPolicy, tr("Default File Import Behavior:")},
+ {renamePolicy, tr("Normalize Imported Image Sequences:")},
{autoExposeEnabled, tr("Expose Loaded Levels in Xsheet")},
{autoRemoveUnusedLevels,
tr("Automatically Remove Unused Levels From Scene Cast")},
@@ -1431,6 +1439,10 @@ QList<ComboBoxItem> PreferencesPopup::getComboItemList(
{{tr("Always ask before loading or importing"), 0},
{tr("Always import the file to the current project"), 1},
{tr("Always load the file from the current location"), 2}}},
+ {renamePolicy,
+ {{tr("Always ask before renaming"), 0},
+ {tr("Normalize sequence names automatically"), 1},
+ {tr("Keep original filenames"), 2}}},
{rasterLevelCachingBehavior,
{{tr("On Demand"), 0},
{tr("All Icons"), 1},
@@ -1807,6 +1819,7 @@ QWidget* PreferencesPopup::createLoadingPage() {
setupLayout(lay);
insertUI(importPolicy, lay, getComboItemList(importPolicy));
+ insertUI(renamePolicy, lay, getComboItemList(renamePolicy));
QGridLayout* autoExposeLay = insertGroupBoxUI(autoExposeEnabled, lay);
{ insertUI(autoRemoveUnusedLevels, autoExposeLay); }
insertUI(subsceneFolderEnabled, lay);
@@ -1846,6 +1859,9 @@ QWidget* PreferencesPopup::createLoadingPage() {
ret = ret && connect(TApp::instance()->getCurrentScene(),
SIGNAL(importPolicyChanged(int)), this,
SLOT(onImportPolicyExternallyChanged(int)));
+ ret = ret && connect(TApp::instance()->getCurrentScene(),
+ SIGNAL(renamePolicyChanged(int)), this,
+ SLOT(onRenamePolicyExternallyChanged(int)));
assert(ret);
return widget;
diff --git a/toonz/sources/toonz/preferencespopup.h b/toonz/sources/toonz/preferencespopup.h
index b798ce944..350a8aed1 100644
--- a/toonz/sources/toonz/preferencespopup.h
+++ b/toonz/sources/toonz/preferencespopup.h
@@ -179,6 +179,7 @@ private slots:
void onEditLevelFormat();
void onLevelFormatEdited();
void onImportPolicyExternallyChanged(int policy);
+ void onRenamePolicyExternallyChanged(int policy);
};
//**********************************************************************************
diff --git a/toonz/sources/toonzlib/preferences.cpp b/toonz/sources/toonzlib/preferences.cpp
index 961cd933e..c2f153c0e 100644
--- a/toonz/sources/toonzlib/preferences.cpp
+++ b/toonz/sources/toonzlib/preferences.cpp
@@ -456,6 +456,7 @@ void Preferences::definePreferenceItems() {
// Loading
define(importPolicy, "importPolicy", QMetaType::Int, 0); // Always ask
+ define(renamePolicy, "renamePolicy", QMetaType::Int, 0); // Always ask
define(autoExposeEnabled, "autoExposeEnabled", QMetaType::Bool, true);
define(subsceneFolderEnabled, "subsceneFolderEnabled", QMetaType::Bool, true);
define(removeSceneNumberFromLoadedLevelName,