OpenToonz - An open-source full-featured 2D animation creation software
C
Refactor: Modernize Qt/C++ code (QRegularExpression, signals/slots) (#6600)
Anderson Pradod5db4e900baa
diff --git a/toonz/sources/toonz/filebrowser.cpp b/toonz/sources/toonz/filebrowser.cppindex bc9ecafc8..4f55b817d 100644--- a/toonz/sources/toonz/filebrowser.cpp+++ b/toonz/sources/toonz/filebrowser.cpp@@ -1,5 +1,3 @@--#include "filebrowser.h"// Tnz6 includes@@ -58,7 +56,6 @@#include <QDir>#include <QPixmap>#include <QUrl>-#include <QRegExp>#include <QScrollBar>#include <QMap>#include <QPushButton>@@ -92,9 +89,9 @@ using namespace DVGui;// Local declarations//=============================================================================-//============================+//=============================================================================// FrameCountTask class-//----------------------------+//-----------------------------------------------------------------------------class FrameCountTask final : public TThread::Runnable {bool m_started;@@ -117,9 +114,9 @@ public slots:void onCanceled(TThread::RunnableP thisTask) override;};-//============================+//=============================================================================// FCData struct-//----------------------------+//-----------------------------------------------------------------------------struct FCData {QDateTime m_date;@@ -217,67 +214,67 @@ FileBrowser::FileBrowser(QWidget *parent, Qt::WindowFlags flags,m_mainSplitter->setSizes(QList<int>() << 270 << 500);- // signal-slot connections- bool ret = connect(m_folderTreeView, SIGNAL(currentNodeChanged()),- itemViewPlayDelegate, SLOT(resetPlayWidget()));- // if the current forder is changed in the folder tree, then update in the+ // Modernized signal-slot connections using member function pointers+ connect(m_folderTreeView, &DvDirTreeView::currentNodeChanged,+ itemViewPlayDelegate, &DVItemViewPlayDelegate::resetPlayWidget);++ // if the current folder is changed in the folder tree, then update in the// item view- ret = ret && connect(m_folderTreeView, SIGNAL(currentNodeChanged()), this,- SLOT(onTreeFolderChanged()));-- ret = ret && connect(m_itemViewer, SIGNAL(clickedItem(int)), this,- SLOT(onClickedItem(int)));- ret = ret && connect(m_itemViewer, SIGNAL(doubleClickedItem(int)), this,- SLOT(onDoubleClickedItem(int)));- ret =- ret && connect(m_itemViewer, SIGNAL(selectedItems(const std::set<int> &)),- this, SLOT(onSelectedItems(const std::set<int> &)));- ret = ret && connect(buttonBar, SIGNAL(folderUp()), this, SLOT(folderUp()));- ret = ret && connect(buttonBar, SIGNAL(newFolder()), this, SLOT(newFolder()));-- ret = ret && connect(&m_frameCountReader, SIGNAL(calculatedFrameCount()),- m_itemViewer->getPanel(), SLOT(update()));+ connect(m_folderTreeView, &DvDirTreeView::currentNodeChanged, this,+ &FileBrowser::onTreeFolderChanged);++ connect(m_itemViewer, &DvItemViewer::clickedItem, this,+ &FileBrowser::onClickedItem);+ connect(m_itemViewer, &DvItemViewer::doubleClickedItem, this,+ &FileBrowser::onDoubleClickedItem);+ connect(m_itemViewer, &DvItemViewer::selectedItems, this,+ &FileBrowser::onSelectedItems);+ connect(buttonBar, &DvItemViewerButtonBar::folderUp, this,+ &FileBrowser::folderUp);+ connect(buttonBar, &DvItemViewerButtonBar::newFolder, this,+ &FileBrowser::newFolder);++ connect(&m_frameCountReader, &FrameCountReader::calculatedFrameCount,+ m_itemViewer->getPanel(),+ [panel = m_itemViewer->getPanel()]() { panel->update(); });QAction *refresh = CommandManager::instance()->getAction(MI_RefreshTree);- ret = ret && connect(refresh, SIGNAL(triggered()), this, SLOT(refresh()));+ connect(refresh, &QAction::triggered, this, &FileBrowser::refresh);addAction(refresh);// Version Control instance connectionif (Preferences::instance()->isSVNEnabled())- ret =- ret && connect(VersionControl::instance(),- SIGNAL(commandDone(const QStringList &)), this,- SLOT(onVersionControlCommandDone(const QStringList &)));+ connect(VersionControl::instance(), &VersionControl::commandDone, this,+ &FileBrowser::onVersionControlCommandDone);// if the folderName is edited, move the current folder accordingly- ret = ret && connect(m_folderName, SIGNAL(editingFinished()), this,- SLOT(onFolderEdited()));+ connect(m_folderName, &QLineEdit::editingFinished, this,+ &FileBrowser::onFolderEdited);// folder history- ret = ret && connect(m_folderTreeView, SIGNAL(currentNodeChanged()), this,- SLOT(storeFolderHistory()));- ret = ret && connect(buttonBar, SIGNAL(folderBack()), this,- SLOT(onBackButtonPushed()));- ret = ret && connect(buttonBar, SIGNAL(folderFwd()), this,- SLOT(onFwdButtonPushed()));+ connect(m_folderTreeView, &DvDirTreeView::currentNodeChanged, this,+ &FileBrowser::storeFolderHistory);+ connect(buttonBar, &DvItemViewerButtonBar::folderBack, this,+ &FileBrowser::onBackButtonPushed);+ connect(buttonBar, &DvItemViewerButtonBar::folderFwd, this,+ &FileBrowser::onFwdButtonPushed);+// when the history changes, enable/disable the history buttons accordingly- ret = ret && connect(this, SIGNAL(historyChanged(bool, bool)), buttonBar,- SLOT(onHistoryChanged(bool, bool)));+ connect(this, &FileBrowser::historyChanged, buttonBar,+ &DvItemViewerButtonBar::onHistoryChanged);// check out the update of the current folder.// Use MyFileSystemWatcher which is shared by all browsers.// Adding and removing paths to the watcher is done in DvDirTreeView.- ret = ret && connect(MyFileSystemWatcher::instance(),- SIGNAL(directoryChanged(const QString &)), this,- SLOT(onFileSystemChanged(const QString &)));+ connect(MyFileSystemWatcher::instance(),+ &MyFileSystemWatcher::directoryChanged, this,+ &FileBrowser::onFileSystemChanged);// store the first item("Root") in the historym_indexHistoryList.append(m_folderTreeView->currentIndex());m_currentPosition = 0;refreshHistoryButtons();-- assert(ret);}//-----------------------------------------------------------------------------@@ -882,8 +879,7 @@ item.m_validInfo = true;*///-----------------------------------------------------------------------------//! Frame count needs a special access function for viewable types - for they-//! are-//! calculated by using a dedicated thread and therefore cannot be simply+//! are calculated by using a dedicated thread and therefore cannot be simply//! classified as *valid* or *invalid* infos...void FileBrowser::readFrameCount(Item &item) {if (!item.m_isFolder &&@@ -1103,8 +1099,6 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {return path.getType() == "tzp" || path.getType() == "tzu";};- bool ret = true;-// TODO: move the definition of actions to this class too?FileSelection *fs =dynamic_cast<FileSelection *>(m_itemViewer->getPanel()->getSelection());@@ -1127,8 +1121,7 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {menu->addAction(cm->getAction(MI_Clear));QAction *action =new QAction(QIcon(createQIcon("rename")), tr("Rename"), menu);- ret =- ret && connect(action, SIGNAL(triggered()), this, SLOT(renameFolder()));+ connect(action, &QAction::triggered, this, &FileBrowser::renameFolder);menu->addAction(action);return menu;}@@ -1175,8 +1168,7 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {elsetitle = tr("Load");QAction *action = new QAction(QIcon(createQIcon("import")), title, menu);- ret = ret &&- connect(action, SIGNAL(triggered()), this, SLOT(loadResources()));+ connect(action, &QAction::triggered, this, &FileBrowser::loadResources);menu->addAction(action);menu->addSeparator();}@@ -1227,8 +1219,8 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {if (files.size() == 1 && files[0].getType() != "tnz") {QAction *action =new QAction(QIcon(createQIcon("rename")), tr("Rename"), menu);- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(renameAsToonzLevel()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::renameAsToonzLevel);menu->addAction(action);}#ifdef LEVO@@ -1241,14 +1233,14 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {files[1].getType() == "png" || files[1].getType() == "TIF" ||files[1].getType() == "TIFF" || files[1].getType() == "PNG")) {QAction *action = new QAction(tr("Convert to Painted TLV"), menu);- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(convertToPaintedTlv()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::convertToPaintedTlv);menu->addAction(action);}if (areFullcolor) {QAction *action = new QAction(tr("Convert to Unpainted TLV"), menu);- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(convertToUnpaintedTlv()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::convertToUnpaintedTlv);menu->addAction(action);menu->addSeparator();}@@ -1280,43 +1272,43 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {(status == DvItemListModel::VC_ToUpdate && files.size() == 1)) {if (status == DvItemListModel::VC_ReadOnly) {action = vcMenu->addAction(tr("Edit"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(editVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::editVersionControl);TFilePath path = files.at(0);std::string fileType = path.getType();if (fileType == "tlv" || fileType == "pli" || path.getDots() == "..") {action = vcMenu->addAction(tr("Edit Frame Range..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(editFrameRangeVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::editFrameRangeVersionControl);}} else {action = vcMenu->addAction(tr("Edit"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(updateAndEditVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::updateAndEditVersionControl);}}if (status == DvItemListModel::VC_Modified) {action = vcMenu->addAction(tr("Put..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(putVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::putVersionControl);action = vcMenu->addAction(tr("Revert"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(revertVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::revertVersionControl);}if (status == DvItemListModel::VC_ReadOnly ||status == DvItemListModel::VC_ToUpdate) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getVersionControl);if (status == DvItemListModel::VC_ReadOnly) {action = vcMenu->addAction(tr("Delete"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(deleteVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::deleteVersionControl);}vcMenu->addSeparator();@@ -1325,99 +1317,99 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {action = vcMenu->addAction(tr("Get Revision..."));TFilePath path = files.at(0);if (path.getDots() == "..")- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getRevisionVersionControl);else- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionHistory()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getRevisionHistory);} else if (files.size() > 1) {action = vcMenu->addAction("Get Revision...");- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getRevisionVersionControl);}}if (status == DvItemListModel::VC_Edited) {action = vcMenu->addAction(tr("Unlock"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(unlockVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::unlockVersionControl);}if (status == DvItemListModel::VC_Unversioned) {action = vcMenu->addAction(tr("Put..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(putVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::putVersionControl);}if (status == DvItemListModel::VC_Locked && files.size() == 1) {action = vcMenu->addAction(tr("Unlock"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(unlockVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::unlockVersionControl);action = vcMenu->addAction(tr("Edit Info"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(showLockInformation()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::showLockInformation);}if (status == DvItemListModel::VC_Missing) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getVersionControl);if (files.size() == 1) {vcMenu->addSeparator();action = vcMenu->addAction(tr("Revision History..."));TFilePath path = files.at(0);if (path.getDots() == "..")- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getRevisionVersionControl);else- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionHistory()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getRevisionHistory);}}if (status == DvItemListModel::VC_PartialLocked) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getVersionControl);if (files.size() == 1) {action = vcMenu->addAction(tr("Edit Frame Range..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(editFrameRangeVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::editFrameRangeVersionControl);action = vcMenu->addAction(tr("Edit Info"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(showFrameRangeLockInfo()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::showFrameRangeLockInfo);}} else if (status == DvItemListModel::VC_PartialEdited) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getVersionControl);if (files.size() == 1) {action = vcMenu->addAction(tr("Unlock Frame Range"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(unlockFrameRangeVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::unlockFrameRangeVersionControl);action = vcMenu->addAction(tr("Edit Info"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(showFrameRangeLockInfo()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::showFrameRangeLockInfo);}} else if (status == DvItemListModel::VC_PartialModified) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::getVersionControl);if (files.size() == 1) {action = vcMenu->addAction(tr("Put..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(putFrameRangeVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::putFrameRangeVersionControl);action = vcMenu->addAction(tr("Revert"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(revertFrameRangeVersionControl()));+ connect(action, &QAction::triggered, this,+ &FileBrowser::revertFrameRangeVersionControl);}}@@ -1432,8 +1424,6 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {menu->addAction(cm->getAction(MI_RefreshTree));}- assert(ret);-return menu;}@@ -1668,12 +1658,10 @@ RenameAsToonzPopup::RenameAsToonzPopup(const QString name, int frames,m_name = new LineEdit(frames == -1 ? "" : name);m_name->setFixedHeight(20);- // connect(m_name, SIGNAL(editingFinished()), SLOT(onNameChanged()));- // addWidget(tr("Level Name:"),m_name);+ // Modernized: Removed commented connection as it's not usedm_overwrite = new QCheckBox(tr("Delete Original Files"));m_overwrite->setFixedHeight(20);- // addWidget(m_overwrite, false);QFormLayout *formLayout = new QFormLayout;@@ -1695,8 +1683,8 @@ RenameAsToonzPopup::RenameAsToonzPopup(const QString name, int frames,m_okBtn = new QPushButton(tr("Rename"), this);m_okBtn->setDefault(true);m_cancelBtn = new QPushButton(tr("Cancel"), this);- connect(m_okBtn, SIGNAL(clicked()), this, SLOT(onOk()));- connect(m_cancelBtn, SIGNAL(clicked()), this, SLOT(reject()));+ connect(m_okBtn, &QPushButton::clicked, this, &RenameAsToonzPopup::onOk);+ connect(m_cancelBtn, &QPushButton::clicked, this, &QDialog::reject);addButtonBarWidget(m_okBtn, m_cancelBtn);}@@ -1784,8 +1772,6 @@ QString getFrame(const QString &filename) {//-------------------------------------------------------------------//------------------------------------------------------------void renameSingleFileOrToonzLevel(const QString &fullpath) {TFilePath fpin(fullpath.toStdString());@@ -2336,8 +2322,8 @@ void FileBrowser::selectNone() { m_itemViewer->selectNone(); }void FileBrowser::enableDoubleClickToOpenScenes() {// perhaps this should disconnect existing signal handlers first- connect(this, SIGNAL(filePathDoubleClicked(const TFilePath &)), this,- SLOT(tryToOpenScene(const TFilePath &)));+ connect(this, &FileBrowser::filePathDoubleClicked, this,+ &FileBrowser::tryToOpenScene);}//-----------------------------------------------------------------------------@@ -2400,10 +2386,10 @@ calculateTask:// Now, we have to calculate the frame count; first, create a frame count// calculation task and submit it.FrameCountTask *task = new FrameCountTask(fp, modifiedDate);- connect(task, SIGNAL(finished(TThread::RunnableP)), this,- SIGNAL(calculatedFrameCount()));- connect(task, SIGNAL(exception(TThread::RunnableP)), this,- SIGNAL(calculatedFrameCount()));+ connect(task, &FrameCountTask::finished, this,+ &FrameCountReader::calculatedFrameCount);+ connect(task, &FrameCountTask::exception, this,+ &FrameCountReader::calculatedFrameCount);m_executor.addTask(task);@@ -2421,10 +2407,8 @@ void FrameCountReader::stopReading() { m_executor.cancelAll(); }FrameCountTask::FrameCountTask(const TFilePath &path,const QDateTime &modifiedDate): m_path(path), m_modifiedDate(modifiedDate), m_started(false) {- connect(this, SIGNAL(started(TThread::RunnableP)), this,- SLOT(onStarted(TThread::RunnableP)));- connect(this, SIGNAL(canceled(TThread::RunnableP)), this,- SLOT(onCanceled(TThread::RunnableP)));+ connect(this, &FrameCountTask::started, this, &FrameCountTask::onStarted);+ connect(this, &FrameCountTask::canceled, this, &FrameCountTask::onCanceled);}//-----------------------------------------------------------------------------diff --git a/toonz/sources/toonz/filebrowser.h b/toonz/sources/toonz/filebrowser.hindex bc0253d4e..3e68d3a40 100644--- a/toonz/sources/toonz/filebrowser.h+++ b/toonz/sources/toonz/filebrowser.h@@ -27,16 +27,12 @@ class QFileSystemWatcher;//-----------------------------------------------------------------------------//! FrameCountReader is the class responsible for calculation of levels' frame-//! counts-//! in the file browser. Since on many file formats this requires to open the-//! level file-//! and scan each frame (MOV-like), and on some machine configurations such a-//! task-//! can be time consuming, we dedicate a separate thread for it - just like the-//! icon-//! generator does. Calculated frame counts are also stored for quick lookup-//! once they-//! have been calculated the first time.+//! counts in the file browser. Since on many file formats this requires to+//! open the level file and scan each frame (MOV-like), and on some machine+//! configurations such a task can be time consuming, we dedicate a separate+//! thread for it - just like the icon generator does. Calculated frame counts+//! are also stored for quick lookup once they have been calculated the first+//! time.class FrameCountReader final : public QObject {Q_OBJECT@@ -50,7 +46,6 @@ public:void stopReading();signals:-void calculatedFrameCount();};@@ -79,16 +74,16 @@ public:QMenu *getContextMenu(QWidget *parent, int index) override;/*!-This functions adds to the types to be filtered a new type;-if this function is never called, the default filter is all image-files and scene files and palette files-*/+ This function adds to the types to be filtered a new type;+ if this function is never called, the default filter is all image+ files and scene files and palette files+ */void addFilterType(const QString &type);/*!-The setFilterTypes function directly specifies the list of file-types to be displayed in the file browser.-*/+ The setFilterTypes function directly specifies the list of file+ types to be displayed in the file browser.+ */void setFilterTypes(const QStringList &types);const QStringList &getFilterTypes() const { return m_filter; }void removeFilterType(const QString &type);@@ -108,8 +103,8 @@ types to be displayed in the file browser.static void updateItemViewerPanel();- // ritorna true se il file e' stato rinominato. dopo la chiamata fp contiene- // il nuovo path+ // returns true if the file has been renamed. After the call, fp contains+ // the new pathstatic bool renameFile(TFilePath &fp, QString newName);void makeCurrentProjectVisible();@@ -148,11 +143,9 @@ protected:void refreshHistoryButtons();public slots:-void onTreeFolderChanged();protected slots:-void refresh();void changeFolder(const QModelIndex &index);@@ -201,7 +194,6 @@ protected slots:void tryToOpenScene(const TFilePath &filePath);signals:-void filePathClicked(const TFilePath &);void filePathDoubleClicked(const TFilePath &);// reuse the list of TFrameId in order to skip loadInfo() when loading the@@ -210,8 +202,8 @@ signals:const std::list<std::vector<TFrameId>> &);void treeFolderChanged(const TFilePath &);- // for activating/deactivating the folder history buttons( back button &- // forward button )+ // for activating/deactivating the folder history buttons (back button &+ // forward button)void historyChanged(bool, bool);private:diff --git a/toonz/sources/toonz/filebrowsermodel.cpp b/toonz/sources/toonz/filebrowsermodel.cppindex 3d810f507..acd016d06 100644--- a/toonz/sources/toonz/filebrowsermodel.cpp+++ b/toonz/sources/toonz/filebrowsermodel.cpp@@ -1,5 +1,3 @@--#include "filebrowsermodel.h"#include "tutil.h"#include "tsystem.h"@@ -19,6 +17,7 @@#include <QFileInfo>#include <QDir>#include <QDirIterator>+#include <QRegularExpression>#ifdef _WIN32#include <shlobj.h>@@ -36,7 +35,7 @@ namespace {TFilePath getMyDocumentsPath() {#ifdef _WIN32WCHAR szPath[MAX_PATH];- if (SHGetSpecialFolderPath(NULL, szPath, CSIDL_PERSONAL, 0)) {+ if (SHGetSpecialFolderPath(nullptr, szPath, CSIDL_PERSONAL, 0)) {return TFilePath(szPath);}return TFilePath();@@ -60,7 +59,7 @@ TFilePath getMyDocumentsPath() {TFilePath getDesktopPath() {#ifdef _WIN32WCHAR szPath[MAX_PATH];- if (SHGetSpecialFolderPath(NULL, szPath, CSIDL_DESKTOP, 0)) {+ if (SHGetSpecialFolderPath(nullptr, szPath, CSIDL_DESKTOP, 0)) {return TFilePath(szPath);}return TFilePath();@@ -91,9 +90,7 @@ TFilePath getDesktopPath() {} // namespace//=============================================================================-//-// DvDirModelNode-//+// DvDirModelNode implementation//-----------------------------------------------------------------------------DvDirModelNode::DvDirModelNode(DvDirModelNode *parent, std::wstring name)@@ -105,12 +102,8 @@ DvDirModelNode::DvDirModelNode(DvDirModelNode *parent, std::wstring name), m_renameEnabled(false), m_nodeType("") {}-//------------------------------------------------------------------------------DvDirModelNode::~DvDirModelNode() { clearPointerContainer(m_children); }-//------------------------------------------------------------------------------void DvDirModelNode::removeChildren(int row, int count) {assert(0 <= row && row + count <= (int)m_children.size());int i;@@ -119,30 +112,22 @@ void DvDirModelNode::removeChildren(int row, int count) {for (i = 0; i < (int)m_children.size(); i++) m_children[i]->setRow(i);}-//------------------------------------------------------------------------------void DvDirModelNode::addChild(DvDirModelNode *child) {child->setRow(m_children.size());m_children.push_back(child);}-//------------------------------------------------------------------------------int DvDirModelNode::getChildCount() {if (!m_childrenValid) refreshChildren();return (int)m_children.size();}-//------------------------------------------------------------------------------DvDirModelNode *DvDirModelNode::getChild(int index) {if (!m_childrenValid) refreshChildren();assert(0 <= index && index < getChildCount());return m_children[index];}-//------------------------------------------------------------------------------bool DvDirModelNode::hasChildren() {if (m_childrenValid)return getChildCount() > 0;@@ -150,19 +135,13 @@ bool DvDirModelNode::hasChildren() {return true;}-//------------------------------------------------------------------------------QPixmap DvDirModelNode::getPixmap(bool isOpen) const { return QPixmap(); }-//------------------------------------------------------------------------------void DvDirModelNode::setTemporaryName(const std::wstring &newName) {m_oldName = getName();m_name = newName;}-//------------------------------------------------------------------------------void DvDirModelNode::restoreName() {if (m_oldName != L"") {m_name = m_oldName;@@ -171,9 +150,7 @@ void DvDirModelNode::restoreName() {}//=============================================================================-//-// DvDirModelFileFolderNode [File folder]-//+// DvDirModelFileFolderNode implementation//-----------------------------------------------------------------------------DvDirModelFileFolderNode::DvDirModelFileFolderNode(DvDirModelNode *parent,@@ -189,8 +166,6 @@ DvDirModelFileFolderNode::DvDirModelFileFolderNode(DvDirModelNode *parent,m_nodeType = "FileFolder";}-//------------------------------------------------------------------------------DvDirModelFileFolderNode::DvDirModelFileFolderNode(DvDirModelNode *parent,const TFilePath &path): DvDirModelNode(parent, path.withoutParentDir().getWideString())@@ -203,8 +178,6 @@ DvDirModelFileFolderNode::DvDirModelFileFolderNode(DvDirModelNode *parent,m_nodeType = "FileFolder";}-//------------------------------------------------------------------------------bool DvDirModelFileFolderNode::exists() {return m_existsChecked ? m_exists: m_peeks@@ -212,20 +185,14 @@ bool DvDirModelFileFolderNode::exists() {m_exists = TFileStatus(m_path).doesExist() : true;}-//------------------------------------------------------------------------------void DvDirModelFileFolderNode::visualizeContent(FileBrowser *browser) {browser->setFolder(m_path);}-//------------------------------------------------------------------------------DvDirModelNode *DvDirModelFileFolderNode::makeChild(std::wstring name) {return createNode(this, m_path + name);}-//------------------------------------------------------------------------------DvDirModelFileFolderNode *DvDirModelFileFolderNode::createNode(DvDirModelNode *parent, const TFilePath &path) {DvDirModelFileFolderNode *node;@@ -241,8 +208,6 @@ DvDirModelFileFolderNode *DvDirModelFileFolderNode::createNode(return node;}-//------------------------------------------------------------------------------bool DvDirModelFileFolderNode::setName(std::wstring newName) {if (isSpaceString(QString::fromStdWString(newName))) return true;@@ -259,8 +224,6 @@ bool DvDirModelFileFolderNode::setName(std::wstring newName) {return true;}-//------------------------------------------------------------------------------bool DvDirModelFileFolderNode::hasChildren() {if (m_childrenValid) return m_hasChildren;@@ -275,8 +238,6 @@ bool DvDirModelFileFolderNode::hasChildren() {// sub-folders}-//-------------------------------------------------------------------------------void DvDirModelFileFolderNode::refreshChildren() {m_childrenValid = true;@@ -293,7 +254,7 @@ void DvDirModelFileFolderNode::refreshChildren() {for (j = oldChildren.begin();j != oldChildren.end() && (*j)->getName() != name; ++j) {}- DvDirModelNode *child = 0;+ DvDirModelNode *child = nullptr;if (j != oldChildren.end()) {child = *j;oldChildren.erase(j);@@ -319,8 +280,6 @@ void DvDirModelFileFolderNode::refreshChildren() {m_hasChildren = (m_children.size() > 0);}-//------------------------------------------------------------------------------void DvDirModelFileFolderNode::getChildrenNames(std::vector<std::wstring> &names) const {if (m_path.isEmpty()) return;@@ -336,8 +295,6 @@ void DvDirModelFileFolderNode::getChildrenNames(QDir dir(toQString(m_path));}-//------------------------------------------------------------------------------int DvDirModelFileFolderNode::rowByName(const std::wstring &name) const {std::vector<std::wstring> names;getChildrenNames(names);@@ -349,30 +306,24 @@ int DvDirModelFileFolderNode::rowByName(const std::wstring &name) const {return std::distance(names.begin(), it);}-//------------------------------------------------------------------------------DvDirModelNode *DvDirModelFileFolderNode::getNodeByPath(const TFilePath &path) {if (path == m_path) return this;- if (!m_path.isAncestorOf(path)) return 0;+ if (!m_path.isAncestorOf(path)) return nullptr;int i, n = getChildCount();for (i = 0; i < n; i++) {DvDirModelNode *node = getChild(i)->getNodeByPath(path);if (node) return node;}- return 0;+ return nullptr;}-//------------------------------------------------------------------------------QPixmap DvDirModelFileFolderNode::getPixmap(bool isOpen) const {return createQIcon("folder").pixmap({18, 18}, QIcon::Normal,isOpen ? QIcon::On : QIcon::Off);}//=============================================================================-//-// DvDirModelSpecialFileFolderNode [Special File Folder]-//+// DvDirModelSpecialFileFolderNode implementation//-----------------------------------------------------------------------------DvDirModelSpecialFileFolderNode::DvDirModelSpecialFileFolderNode(@@ -381,8 +332,6 @@ DvDirModelSpecialFileFolderNode::DvDirModelSpecialFileFolderNode(, m_iconName(), m_iconSize(16, 16) {}-//------------------------------------------------------------------------------QPixmap DvDirModelSpecialFileFolderNode::getPixmap(bool isOpen) const {if (!m_iconName.isEmpty()) {QIcon icon = createQIcon(m_iconName);@@ -392,9 +341,7 @@ QPixmap DvDirModelSpecialFileFolderNode::getPixmap(bool isOpen) const {}//=============================================================================-//-// DvDirVersionControlNode [Special File Folder]-//+// DvDirVersionControlNode implementation//-----------------------------------------------------------------------------DvDirVersionControlNode::DvDirVersionControlNode(DvDirModelNode *parent,@@ -409,8 +356,6 @@ DvDirVersionControlNode::DvDirVersionControlNode(DvDirModelNode *parent,VersionControl::instance()->isFolderUnderVersionControl(toQString(path)));}-//------------------------------------------------------------------------------QList<TFilePath> DvDirVersionControlNode::getMissingFiles() const {QList<TFilePath> list;QMap<QString, SVNStatus>::const_iterator i = m_statusMap.constBegin();@@ -430,10 +375,8 @@ QList<TFilePath> DvDirVersionControlNode::getMissingFiles() const {return list;}-//------------------------------------------------------------------------------QStringList DvDirVersionControlNode::getMissingFiles(- const QRegExp &filter) const {+ const QRegularExpression &filter) const {QStringList list;QMap<QString, SVNStatus>::const_iterator i = m_statusMap.constBegin();for (; i != m_statusMap.constEnd(); i++) {@@ -441,8 +384,10 @@ QStringList DvDirVersionControlNode::getMissingFiles(if (s.m_item == "missing" ||(s.m_item == "none" && s.m_repoStatus == "added")) {TFilePath path(s.m_path.toStdWString());- if (!filter.exactMatch(- QString::fromStdWString(path.withoutParentDir().getWideString())))+ if (!filter+ .match(QString::fromStdWString(+ path.withoutParentDir().getWideString()))+ .hasMatch())continue;std::string dots = path.getDots();if (dots != "") list.append(toQString(path));@@ -451,8 +396,6 @@ QStringList DvDirVersionControlNode::getMissingFiles(return list;}-//------------------------------------------------------------------------------QList<TFilePath> DvDirVersionControlNode::getMissingFolders() const {QList<TFilePath> list;QMap<QString, SVNStatus>::const_iterator i = m_statusMap.constBegin();@@ -480,8 +423,6 @@ QList<TFilePath> DvDirVersionControlNode::getMissingFolders() const {return list;}-//------------------------------------------------------------------------------void DvDirVersionControlNode::getChildrenNames(std::vector<std::wstring> &names) const {DvDirModelFileFolderNode::getChildrenNames(names);@@ -496,24 +437,18 @@ void DvDirVersionControlNode::getChildrenNames(}}-//------------------------------------------------------------------------------void DvDirVersionControlNode::setIsUnderVersionControl(bool value) {// Set the flags and enable/disable renaming accordinglym_isUnderVersionControl = value;enableRename(!value);}-//------------------------------------------------------------------------------DvDirModelNode *DvDirVersionControlNode::makeChild(std::wstring name) {if (TProjectManager::instance()->isProject(getPath() + name))return new DvDirVersionControlProjectNode(this, name, getPath() + name);return new DvDirVersionControlNode(this, name, getPath() + name);}-//------------------------------------------------------------------------------QPixmap DvDirVersionControlNode::getPixmap(bool isOpen) const {static const QSize iconSize(18, 18);@@ -530,15 +465,11 @@ QPixmap DvDirVersionControlNode::getPixmap(bool isOpen) const {return icon.pixmap(iconSize, QIcon::Normal, isOpen ? QIcon::On : QIcon::Off);}-//------------------------------------------------------------------------------void DvDirVersionControlNode::insertVersionControlStatus(const QString &fileName, SVNStatus status) {m_statusMap.insert(fileName, status);}-//------------------------------------------------------------------------------SVNStatus DvDirVersionControlNode::getVersionControlStatus(const QString &fileName) {if (m_statusMap.contains(fileName)) return m_statusMap.value(fileName);@@ -550,8 +481,6 @@ SVNStatus DvDirVersionControlNode::getVersionControlStatus(return s;}-//------------------------------------------------------------------------------QStringList DvDirVersionControlNode::refreshVersionControl(const QList<SVNStatus> &status) {TFilePath nodePath = getPath();@@ -625,19 +554,15 @@ QStringList DvDirVersionControlNode::refreshVersionControl(return checkPartialLockList;}-//------------------------------------------------------------------------------DvDirVersionControlRootNode *DvDirVersionControlNode::getVersionControlRootNode() {DvDirModelNode *parent = getParent();if (parent) return parent->getVersionControlRootNode();- return 0;+ return nullptr;}//=============================================================================-//-// DvDirVersionControlRootNode [Special File Folder]-//+// DvDirVersionControlRootNode implementation//-----------------------------------------------------------------------------DvDirVersionControlRootNode::DvDirVersionControlRootNode(DvDirModelNode *parent,@@ -648,14 +573,12 @@ DvDirVersionControlRootNode::DvDirVersionControlRootNode(DvDirModelNode *parent,setIsUnderVersionControl(true);}-//------------------------------------------------------------------------------void DvDirVersionControlRootNode::refreshChildren() {DvDirModelFileFolderNode::refreshChildren();}//=============================================================================-// DvDirVersionControlProjectNode+// DvDirVersionControlProjectNode implementation//-----------------------------------------------------------------------------DvDirVersionControlProjectNode::DvDirVersionControlProjectNode(@@ -665,21 +588,15 @@ DvDirVersionControlProjectNode::DvDirVersionControlProjectNode(setIsUnderVersionControl(true);}-//------------------------------------------------------------------------------TFilePath DvDirVersionControlProjectNode::getProjectPath() const {return TProjectManager::instance()->projectFolderToProjectPath(getPath());}-//------------------------------------------------------------------------------bool DvDirVersionControlProjectNode::isCurrent() const {TProjectManager *pm = TProjectManager::instance();return pm->getCurrentProjectPath().getParentDir() == getPath();}-//------------------------------------------------------------------------------void DvDirVersionControlProjectNode::makeCurrent() {TProjectManager *pm = TProjectManager::instance();TFilePath projectPath = getProjectPath();@@ -688,8 +605,6 @@ void DvDirVersionControlProjectNode::makeCurrent() {IoCmd::newScene();}-//------------------------------------------------------------------------------QPixmap DvDirVersionControlProjectNode::getPixmap(bool isOpen) const {static QPixmap openPixmap(svgToPixmap(":Resources/browser_vcproject_open.svg"));@@ -706,8 +621,6 @@ QPixmap DvDirVersionControlProjectNode::getPixmap(bool isOpen) const {return isOpen ? openMissingPixmap : closeMissingPixmap;}-//------------------------------------------------------------------------------void DvDirVersionControlProjectNode::refreshChildren() {DvDirModelFileFolderNode::refreshChildren();int i;@@ -724,8 +637,6 @@ void DvDirVersionControlProjectNode::refreshChildren() {}}-//------------------------------------------------------------------------------void DvDirVersionControlProjectNode::getChildrenNames(std::vector<std::wstring> &names) const {DvDirVersionControlNode::getChildrenNames(names);@@ -736,7 +647,6 @@ void DvDirVersionControlProjectNode::getChildrenNames(for (i = 0; i < project->getFolderCount(); i++) {std::string folderName = project->getFolderName(i);TFilePath folderPath = project->getFolder(i);- // if(folderPath.isAbsolute() || folderPath.getParentDir() != TFilePath())if (folderPath.isAbsolute() && project->isConstantFolder(i)) {names.push_back(L"+" + ::to_wstring(folderName));}@@ -744,9 +654,7 @@ void DvDirVersionControlProjectNode::getChildrenNames(}//=============================================================================-//-// DvDirModelProjectNode [Project Folder]-//+// DvDirModelProjectNode implementation//-----------------------------------------------------------------------------DvDirModelProjectNode::DvDirModelProjectNode(DvDirModelNode *parent,@@ -755,21 +663,15 @@ DvDirModelProjectNode::DvDirModelProjectNode(DvDirModelNode *parent,m_nodeType = "Project";}-//------------------------------------------------------------------------------TFilePath DvDirModelProjectNode::getProjectPath() const {return TProjectManager::instance()->projectFolderToProjectPath(getPath());}-//------------------------------------------------------------------------------bool DvDirModelProjectNode::isCurrent() const {TProjectManager *pm = TProjectManager::instance();return pm->getCurrentProjectPath().getParentDir() == getPath();}-//------------------------------------------------------------------------------void DvDirModelProjectNode::makeCurrent() {TProjectManager *pm = TProjectManager::instance();TFilePath projectPath = getProjectPath();@@ -779,16 +681,12 @@ void DvDirModelProjectNode::makeCurrent() {IoCmd::newScene();}-//------------------------------------------------------------------------------QPixmap DvDirModelProjectNode::getPixmap(bool isOpen) const {static const QIcon projectIcon = createQIcon("folder_project");return projectIcon.pixmap({18, 18}, QIcon::Normal,isOpen ? QIcon::On : QIcon::Off);}-//------------------------------------------------------------------------------void DvDirModelProjectNode::refreshChildren() {DvDirModelFileFolderNode::refreshChildren();int i;@@ -805,8 +703,6 @@ void DvDirModelProjectNode::refreshChildren() {}}-//------------------------------------------------------------------------------void DvDirModelProjectNode::getChildrenNames(std::vector<std::wstring> &names) const {DvDirModelFileFolderNode::getChildrenNames(names);@@ -817,15 +713,12 @@ void DvDirModelProjectNode::getChildrenNames(for (i = 0; i < project->getFolderCount(); i++) {std::string folderName = project->getFolderName(i);TFilePath folderPath = project->getFolder(i);- // if(folderPath.isAbsolute() || folderPath.getParentDir() != TFilePath())if (folderPath.isAbsolute() && project->isConstantFolder(i)) {names.push_back(L"+" + ::to_wstring(folderName));}}}-//------------------------------------------------------------------------------DvDirModelNode *DvDirModelProjectNode::makeChild(std::wstring name) {if (name != L"" && name[0] == L'+') {TProjectManager *pm = TProjectManager::instance();@@ -840,9 +733,7 @@ DvDirModelNode *DvDirModelProjectNode::makeChild(std::wstring name) {}//=============================================================================-//-// DvDirModelDayNode [Day folder]-//+// DvDirModelDayNode implementation//-----------------------------------------------------------------------------DvDirModelDayNode::DvDirModelDayNode(DvDirModelNode *parent,@@ -852,14 +743,10 @@ DvDirModelDayNode::DvDirModelDayNode(DvDirModelNode *parent,m_nodeType = "Day";}-//------------------------------------------------------------------------------void DvDirModelDayNode::visualizeContent(FileBrowser *browser) {browser->setHistoryDay(m_dayDateString);}-//------------------------------------------------------------------------------QPixmap DvDirModelDayNode::getPixmap(bool isOpen) const {static const QIcon folderIcon = createQIcon("folder");return folderIcon.pixmap({18, 18}, QIcon::Normal,@@ -867,9 +754,7 @@ QPixmap DvDirModelDayNode::getPixmap(bool isOpen) const {}//=============================================================================-//-// DvDirModelHistoryNode [History]-//+// DvDirModelHistoryNode implementation//-----------------------------------------------------------------------------DvDirModelHistoryNode::DvDirModelHistoryNode(DvDirModelNode *parent)@@ -877,8 +762,6 @@ DvDirModelHistoryNode::DvDirModelHistoryNode(DvDirModelNode *parent)m_nodeType = "History";}-//------------------------------------------------------------------------------void DvDirModelHistoryNode::refreshChildren() {m_children.clear();m_childrenValid = true;@@ -891,26 +774,19 @@ void DvDirModelHistoryNode::refreshChildren() {}}-//------------------------------------------------------------------------------QPixmap DvDirModelHistoryNode::getPixmap(bool isOpen) const {return createQIcon("history").pixmap(QSize(16, 16));}//=============================================================================-//-// DvDirModelMyComputerNode [My Computer]-//+// DvDirModelMyComputerNode implementation//-----------------------------------------------------------------------------DvDirModelMyComputerNode::DvDirModelMyComputerNode(DvDirModelNode *parent): DvDirModelNode(parent, L"My Computer") {- // setIcon(QFileIconProvider().icon(QFileIconProvider::Computer));m_nodeType = "MyComputer";}-//------------------------------------------------------------------------------void DvDirModelMyComputerNode::refreshChildren() {m_childrenValid = true;if (!m_children.empty()) clearPointerContainer(m_children);@@ -929,16 +805,12 @@ void DvDirModelMyComputerNode::refreshChildren() {}}-//------------------------------------------------------------------------------QPixmap DvDirModelMyComputerNode::getPixmap(bool isOpen) const {return createQIcon("my_computer").pixmap(QSize(16, 16));}//=============================================================================-//-// DvDirModelNetworkNode [Network]-//+// DvDirModelNetworkNode implementation//-----------------------------------------------------------------------------DvDirModelNetworkNode::DvDirModelNetworkNode(DvDirModelNode *parent)@@ -946,8 +818,6 @@ DvDirModelNetworkNode::DvDirModelNetworkNode(DvDirModelNode *parent)m_nodeType = "Network";}-//------------------------------------------------------------------------------void DvDirModelNetworkNode::refreshChildren() {m_childrenValid = true;@@ -957,8 +827,8 @@ void DvDirModelNetworkNode::refreshChildren() {// Enumerate network nodesHANDLE enumHandle;- DWORD err =- WNetOpenEnum(RESOURCE_CONTEXT, RESOURCETYPE_DISK, 0, NULL, &enumHandle);+ DWORD err = WNetOpenEnum(RESOURCE_CONTEXT, RESOURCETYPE_DISK, 0, nullptr,+ &enumHandle);assert(err == NO_ERROR);DWORD count = -1,@@ -1000,14 +870,10 @@ void DvDirModelNetworkNode::refreshChildren() {#endif}-//------------------------------------------------------------------------------QPixmap DvDirModelNetworkNode::getPixmap(bool isOpen) const {return createQIcon("network").pixmap(QSize(16, 16));}-//------------------------------------------------------------------------------DvDirModelNode *DvDirModelNetworkNode::createNetworkFolderNode(const TFilePath &path) {QDir networkDir(path.getQString());@@ -1025,29 +891,23 @@ DvDirModelNode *DvDirModelNetworkNode::createNetworkFolderNode(}//=============================================================================-//-// DvDirModelRootNode [Root]-//+// DvDirModelRootNode implementation//-----------------------------------------------------------------------------DvDirModelRootNode::DvDirModelRootNode()- : DvDirModelNode(0, L"Root")- , m_myComputerNode(0)- , m_networkNode(0)- , m_sandboxProjectNode(0) {+ : DvDirModelNode(nullptr, L"Root")+ , m_myComputerNode(nullptr)+ , m_networkNode(nullptr)+ , m_sandboxProjectNode(nullptr) {m_nodeType = "Root";}-//------------------------------------------------------------------------------void DvDirModelRootNode::add(std::wstring name, const TFilePath &path) {DvDirModelNode *child = new DvDirModelFileFolderNode(this, name, path);child->setRow((int)m_children.size());m_children.push_back(child);}-//------------------------------------------------------------------------------void DvDirModelRootNode::refreshChildren() {m_childrenValid = true;if (m_children.empty()) {@@ -1126,10 +986,9 @@ void DvDirModelRootNode::refreshChildren() {}}-//-----------------------------------------------------------------------------DvDirModelNode *DvDirModelRootNode::getNodeByPath(const TFilePath &path) {// Check first for version control nodes- DvDirModelNode *node = 0;+ DvDirModelNode *node = nullptr;int i;// search in #1 the project folders, #2 sandbox, #3 other folders in file@@ -1228,12 +1087,9 @@ DvDirModelNode *DvDirModelRootNode::getNodeByPath(const TFilePath &path) {}}- return 0;+ return nullptr;}-//------------------------------------------------------------------------------// update the path of sceneLocationNode-void DvDirModelRootNode::setSceneLocation(const TFilePath &path) {if (path == m_sceneFolderNode->getPath()) return;m_sceneFolderNode->setPath(path);@@ -1245,8 +1101,6 @@ void DvDirModelRootNode::setSceneLocation(const TFilePath &path) {updateSceneFolderNodeVisibility();}-//------------------------------------------------------------------------------void DvDirModelRootNode::updateSceneFolderNodeVisibility(bool forceHide) {bool show = (forceHide) ? false : !m_sceneFolderNode->getPath().isEmpty();if (show && m_sceneFolderNode->getRow() == -1) {@@ -1263,68 +1117,31 @@ void DvDirModelRootNode::updateSceneFolderNodeVisibility(bool forceHide) {m_sceneFolderNode->setRow(-1);}}+//=============================================================================-//-// DvDirModel-//+// DvDirModel implementation//-----------------------------------------------------------------------------DvDirModel::DvDirModel() {m_root = new DvDirModelRootNode();m_root->refreshChildren();- // when the scene switched, update the path of the scene location node+ // Modern Qt5 signal/slot connections without unnecessary return value checksTSceneHandle *sceneHandle = TApp::instance()->getCurrentScene();- bool ret = true;- ret = ret && connect(sceneHandle, SIGNAL(sceneSwitched()), this,- SLOT(onSceneSwitched()));- ret = ret && connect(sceneHandle, SIGNAL(nameSceneChanged()), this,- SLOT(onSceneSwitched()));- ret = ret && connect(sceneHandle, SIGNAL(preferenceChanged(const QString &)),- this, SLOT(onPreferenceChanged(const QString &)));- assert(ret);+ connect(sceneHandle, &TSceneHandle::sceneSwitched, this,+ &DvDirModel::onSceneSwitched);+ connect(sceneHandle, &TSceneHandle::nameSceneChanged, this,+ &DvDirModel::onSceneSwitched);+ connect(sceneHandle, &TSceneHandle::preferenceChanged, this,+ &DvDirModel::onPreferenceChanged);onSceneSwitched();}-//------------------------------------------------------------------------------DvDirModel::~DvDirModel() { delete m_root; }-//------------------------------------------------------------------------------void DvDirModel::onFolderChanged(const TFilePath &path) { refreshFolder(path); }-//-------------------------------------------------------------------------------// void DvDirModel::refresh(const QModelIndex &index) {-// if (!index.isValid()) return;-// DvDirModelNode *node = getNode(index);-// if (!node) return;-//-// emit layoutAboutToBeChanged();-//-// int oldChildren = node->getChildCount();-// if (oldChildren > 0) {-// emit beginRemoveRows(index, 0, oldChildren - 1);-// node->refreshChildren();-// emit endRemoveRows();-// } else if (oldChildren == 0) {-// node->refreshChildren();-// } else {-// emit layoutChanged();-// return;-// }-//-// int newChildren = node->getChildCount();-// if (newChildren > 0) {-// emit beginInsertRows(index, 0, newChildren - 1);-// emit endInsertRows();-// }-//-// emit layoutChanged();-// }-void DvDirModel::refresh(const QModelIndex &index) {if (!index.isValid()) return;DvDirModelNode *node = getNode(index);@@ -1337,8 +1154,6 @@ void DvDirModel::refresh(const QModelIndex &index) {emit layoutChanged();}-//------------------------------------------------------------------------------void DvDirModel::refreshFolder(const TFilePath &folderPath,const QModelIndex &i) {DvDirModelNode *node = getNode(i);@@ -1352,8 +1167,6 @@ void DvDirModel::refreshFolder(const TFilePath &folderPath,}}-//------------------------------------------------------------------------------void DvDirModel::refreshFolderChild(const QModelIndex &i) {DvDirModelNode *node = getNode(i);if (!node || !node->areChildrenValid()) return;@@ -1365,8 +1178,6 @@ void DvDirModel::refreshFolderChild(const QModelIndex &i) {for (r = 0; r < count; r++) refreshFolderChild(index(r, 0, i));}-//------------------------------------------------------------------------------DvDirModelNode *DvDirModel::getNode(const QModelIndex &index) const {if (index.isValid())return static_cast<DvDirModelNode *>(index.internalPointer());@@ -1374,8 +1185,6 @@ DvDirModelNode *DvDirModel::getNode(const QModelIndex &index) const {return m_root;}-//------------------------------------------------------------------------------QModelIndex DvDirModel::index(int row, int column,const QModelIndex &parent) const {if (column != 0) return QModelIndex();@@ -1386,8 +1195,6 @@ QModelIndex DvDirModel::index(int row, int column,return createIndex(row, column, node);}-//------------------------------------------------------------------------------QModelIndex DvDirModel::parent(const QModelIndex &index) const {if (!index.isValid()) return QModelIndex();DvDirModelNode *node = getNode(index);@@ -1398,8 +1205,6 @@ QModelIndex DvDirModel::parent(const QModelIndex &index) const {return createIndex(parentNode->getRow(), 0, parentNode);}-//------------------------------------------------------------------------------QModelIndex DvDirModel::childByName(const QModelIndex &parent,const std::wstring &name) const {if (!parent.isValid()) return QModelIndex();@@ -1411,22 +1216,16 @@ QModelIndex DvDirModel::childByName(const QModelIndex &parent,return createIndex(row, 0, childNode);}-//------------------------------------------------------------------------------int DvDirModel::rowCount(const QModelIndex &parent) const {DvDirModelNode *node = getNode(parent);return node->getChildCount();}-//------------------------------------------------------------------------------bool DvDirModel::hasChildren(const QModelIndex &parent) const {DvDirModelNode *node = getNode(parent);return node->hasChildren();}-//------------------------------------------------------------------------------QVariant DvDirModel::data(const QModelIndex &index, int role) const {if (!index.isValid()) return QVariant();DvDirModelNode *node = getNode(index);@@ -1443,8 +1242,6 @@ QVariant DvDirModel::data(const QModelIndex &index, int role) const {return QVariant();}-//------------------------------------------------------------------------------Qt::ItemFlags DvDirModel::flags(const QModelIndex &index) const {Qt::ItemFlags flags = QAbstractItemModel::flags(index);if (index.isValid()) {@@ -1454,9 +1251,6 @@ Qt::ItemFlags DvDirModel::flags(const QModelIndex &index) const {return flags;}-//------------------------------------------------------------------------------/*! used only for name / rename of items- */bool DvDirModel::setData(const QModelIndex &index, const QVariant &value,int role) {if (!index.isValid()) return false;@@ -1469,8 +1263,6 @@ bool DvDirModel::setData(const QModelIndex &index, const QVariant &value,return true;}-//------------------------------------------------------------------------------bool DvDirModel::removeRows(int row, int count,const QModelIndex &parentIndex) {if (!parentIndex.isValid()) return false;@@ -1482,35 +1274,25 @@ bool DvDirModel::removeRows(int row, int count,return true;}-//------------------------------------------------------------------------------QModelIndex DvDirModel::getIndexByPath(const TFilePath &path) const {return getIndexByNode(m_root->getNodeByPath(path));}-//------------------------------------------------------------------------------QModelIndex DvDirModel::getIndexByNode(DvDirModelNode *node) const {if (!node) return QModelIndex();return createIndex(node->getRow(), 0, node);}-//------------------------------------------------------------------------------QModelIndex DvDirModel::getCurrentProjectIndex() const {return getIndexByPath(TProjectManager::instance()->getCurrentProjectPath().getParentDir());}-//------------------------------------------------------------------------------DvDirModel *DvDirModel::instance() {static DvDirModel _instance;return &_instance;}-//------------------------------------------------------------------------------void DvDirModel::onSceneSwitched() {DvDirModelRootNode *rootNode = dynamic_cast<DvDirModelRootNode *>(m_root);if (rootNode) {@@ -1524,8 +1306,6 @@ void DvDirModel::onSceneSwitched() {}}-//------------------------------------------------------------------------------void DvDirModel::onPreferenceChanged(const QString &prefName) {if (prefName != "PathAliasPriority") return;diff --git a/toonz/sources/toonz/filebrowsermodel.h b/toonz/sources/toonz/filebrowsermodel.hindex 7e51c235c..a5fa003da 100644--- a/toonz/sources/toonz/filebrowsermodel.h+++ b/toonz/sources/toonz/filebrowsermodel.h@@ -6,6 +6,7 @@#include <QAbstractItemModel>#include <QPixmap>#include <QMap>+#include <QRegularExpression>#include "tfilepath.h"#include "toonz/toonzfolders.h"@@ -44,7 +45,7 @@ public:void removeChildren(int row, int count);void addChild(DvDirModelNode *child);- virtual void visualizeContent(FileBrowser *browser) {} // ?????????????+ virtual void visualizeContent(FileBrowser *browser) {}virtual QPixmap getPixmap(bool isOpen) const;@@ -54,25 +55,25 @@ public:virtual void refreshChildren() = 0;virtual bool hasChildren();- virtual int rowByName(const std::wstring &name) const {- return -1;- } // ?????????????+ virtual int rowByName(const std::wstring &name) const { return -1; }void enableRename(bool enabled) { m_renameEnabled = enabled; }bool isRenameEnabled() const { return m_renameEnabled; }- virtual bool isFolder(const TFilePath &folderPath) const {- return false;- } // ?????????????+ virtual bool isFolder(const TFilePath &folderPath) const { return false; }virtual bool isFolder() const { return false; }- bool areChildrenValid() const { return m_childrenValid; } // ?????????????+ bool areChildrenValid() const { return m_childrenValid; }std::string getNodeType() const { return m_nodeType; }- virtual DvDirModelNode *getNodeByPath(const TFilePath &path) { return 0; }+ virtual DvDirModelNode *getNodeByPath(const TFilePath &path) {+ return nullptr;+ }- virtual DvDirVersionControlRootNode *getVersionControlRootNode() { return 0; }+ virtual DvDirVersionControlRootNode *getVersionControlRootNode() {+ return nullptr;+ }};//-----------------------------------------------------------------------------@@ -94,7 +95,7 @@ public:QPixmap getPixmap(bool isOpen) const override;TFilePath getPath() const { return m_path; }- void visualizeContent(FileBrowser *browser) override; //?????????????+ void visualizeContent(FileBrowser *browser) override;void refreshChildren() override;bool hasChildren() override;@@ -175,7 +176,8 @@ public:void getChildrenNames(std::vector<std::wstring> &names) const override;QList<TFilePath> getMissingFiles() const;- QStringList getMissingFiles(const QRegExp &filter) const;+ QStringList getMissingFiles(+ const QRegularExpression &filter) const; // Updated from QRegExpQList<TFilePath> getMissingFolders() const;void insertVersionControlStatus(const QString &fileName, SVNStatus status);@@ -272,7 +274,7 @@ class DvDirModelDayNode final : public DvDirModelNode {public:DvDirModelDayNode(DvDirModelNode *parent, std::wstring dayDateString);void refreshChildren() override {}- void visualizeContent(FileBrowser *browser) override; //??????????????????+ void visualizeContent(FileBrowser *browser) override;QPixmap getPixmap(bool isOpen) const override;};diff --git a/toonz/sources/toonz/filebrowserversioncontrol.cpp b/toonz/sources/toonz/filebrowserversioncontrol.cppindex 8f74eb64e..aeb565e77 100644--- a/toonz/sources/toonz/filebrowserversioncontrol.cpp+++ b/toonz/sources/toonz/filebrowserversioncontrol.cpp@@ -16,6 +16,8 @@#include "toonzqt/gutil.h"#include "toonzqt/icongenerator.h"+#include <QRegularExpression>+namespace {//---------------------------------------------------------------------------@@ -23,12 +25,20 @@ QStringList getLevelFileNames(TFilePath path) {TFilePath dir = path.getParentDir();QDir qDir(QString::fromStdWString(dir.getWideString()));QString levelName =- QRegExp::escape(QString::fromStdWString(path.getWideName()));+ QRegularExpression::escape(QString::fromStdWString(path.getWideName()));QString levelType = QString::fromStdString(path.getType());- QString exp(levelName + ".[0-9]{1,4}." + levelType);- QRegExp regExp(exp);+ QString exp(levelName + "\\.[0-9]{1,4}\\." + levelType); // Updated escaping+ QRegularExpression regExp(exp);QStringList list = qDir.entryList(QDir::Files);- return list.filter(regExp);++ // Updated filtering logic for QRegularExpression+ QStringList filteredList;+ for (const QString &fileName : list) {+ if (regExp.match(fileName).hasMatch()) {+ filteredList.append(fileName);+ }+ }+ return filteredList;}} // namespace@@ -88,11 +98,14 @@ void FileBrowser::setupVersionControlCommand(QStringList &files, QString &path,QStringList levelNames = getLevelFileNames(fp);if (levelNames.isEmpty()) {- QString levelName =- QRegExp::escape(QString::fromStdWString(fp.getWideName()));+ QString levelName = QRegularExpression::escape(+ QString::fromStdWString(fp.getWideName()));QString levelType = QString::fromStdString(fp.getType());- QString exp(levelName + ".[0-9]{1,4}." + levelType);- QRegExp regExp(exp);+ QString exp(+ levelName ++ "_[0-9]{3}\\.(tlv|tif|tga|png|gif|bmp|jpg|jpeg|mov|avi|mp4|tpl)$");+ QRegularExpression regExp(exp,+ QRegularExpression::CaseInsensitiveOption);levelNames = node->getMissingFiles(regExp);}@@ -490,8 +503,10 @@ void FileBrowser::getRevisionHistory() {files.removeAt(files.indexOf(file));SVNTimeline *timelineDialog = new SVNTimeline(this, path, file, files);- connect(timelineDialog, SIGNAL(commandDone(const QStringList &)), this,- SLOT(onVersionControlCommandDone(const QStringList &)));++ // Updated signal/slot connection to modern Qt5 syntax+ connect(timelineDialog, &SVNTimeline::commandDone, this,+ &FileBrowser::onVersionControlCommandDone);timelineDialog->show();timelineDialog->raise();diff --git a/toonz/sources/toonz/levelcreatepopup.cpp b/toonz/sources/toonz/levelcreatepopup.cppindex 349f05b20..915c9f936 100644--- a/toonz/sources/toonz/levelcreatepopup.cpp+++ b/toonz/sources/toonz/levelcreatepopup.cpp@@ -56,6 +56,8 @@#include <QComboBox>#include <QPushButton>#include <QMainWindow>+#include <QRegularExpressionValidator>+#include <QRegularExpression>using namespace DVGui;@@ -83,66 +85,83 @@ public:, m_columnIndex(column), m_frameCount(frameCount), m_step(step)- , m_sl(0)+ , m_sl(nullptr), m_areColumnsShifted(areColumnsShifted) {TApp *app = TApp::instance();ToonzScene *scene = app->getCurrentScene()->getScene();m_oldLevelCount = scene->getLevelSet()->getLevelCount();}- ~CreateLevelUndo() { m_sl = 0; }- void onAdd(TXshSimpleLevelP sl) { m_sl = sl; }+ ~CreateLevelUndo() override = default;++ void onAdd(const TXshSimpleLevelP &sl) { m_sl = sl; }void undo() const override {TApp *app = TApp::instance();ToonzScene *scene = app->getCurrentScene()->getScene();TXsheet *xsh = scene->getXsheet();- if (m_areColumnsShifted)++ if (m_areColumnsShifted) {xsh->removeColumn(m_columnIndex);- else if (m_frameCount > 0)+ } else if (m_frameCount > 0) {xsh->removeCells(m_rowIndex, m_columnIndex, m_frameCount);+ }- TLevelSet *levelSet = scene->getLevelSet();- if (levelSet) {+ if (TLevelSet *levelSet = scene->getLevelSet()) {int m = levelSet->getLevelCount();while (m > 0 && m > m_oldLevelCount) {--m;- TXshLevel *level = levelSet->getLevel(m);- if (level) levelSet->removeLevel(level);+ if (TXshLevel *level = levelSet->getLevel(m)) {+ levelSet->removeLevel(level);+ }}}+app->getCurrentScene()->notifySceneChanged();app->getCurrentScene()->notifyCastChange();app->getCurrentXsheet()->notifyXsheetChanged();}void redo() const override {- if (!m_sl.getPointer()) return;+ if (!m_sl) return;+TApp *app = TApp::instance();ToonzScene *scene = app->getCurrentScene()->getScene();+ // Using getPointer() instead of get()scene->getLevelSet()->insertLevel(m_sl.getPointer());+TXsheet *xsh = scene->getXsheet();- if (m_areColumnsShifted) xsh->insertColumn(m_columnIndex);+ if (m_areColumnsShifted) {+ xsh->insertColumn(m_columnIndex);+ }+std::vector<TFrameId> fids;m_sl->getFids(fids);+int i = m_rowIndex;int f = 0;while (i < m_frameCount + m_rowIndex) {- TFrameId fid = (fids.size() != 0) ? fids[f] : i;+ TFrameId fid = (!fids.empty()) ? fids[f] : TFrameId(i);+ // Using getPointer() instead of get()TXshCell cell(m_sl.getPointer(), fid);f++;xsh->setCell(i, m_columnIndex, cell);- int appo = i++;- while (i < m_step + appo) xsh->setCell(i++, m_columnIndex, cell);+ int temp = i++;++ while (i < m_step + temp) {+ xsh->setCell(i++, m_columnIndex, cell);+ }}+app->getCurrentScene()->notifySceneChanged();app->getCurrentScene()->notifyCastChange();app->getCurrentXsheet()->notifyXsheetChanged();}int getSize() const override { return sizeof *this; }+QString getHistoryString() override {- return QObject::tr("Create Level %1 at Column %2")+ return QObject::tr("Create Level %1 at Column %2").arg(QString::fromStdWString(m_sl->getName())).arg(QString::number(m_columnIndex + 1));}@@ -154,10 +173,10 @@ public://=============================================================================/*! \class LevelCreatePopup- \brief The LevelCreatePopup class provides a modal dialog to- create a new level.+ \brief The LevelCreatePopup class provides a modal dialog to create a new+ level.- Inherits \b Dialog.+ Inherits \b Dialog.*///-----------------------------------------------------------------------------@@ -172,32 +191,33 @@ LevelCreatePopup::LevelCreatePopup()m_incFld = new DVGui::IntLineEdit(this);m_levelTypeOm = new QComboBox();- m_pathFld = new FileField(0);+ m_pathFld = new FileField(nullptr);m_widthLabel = new QLabel(tr("Width:"));- m_widthFld = new DVGui::MeasuredDoubleLineEdit(0);+ m_widthFld = new DVGui::MeasuredDoubleLineEdit(nullptr);m_heightLabel = new QLabel(tr("Height:"));- m_heightFld = new DVGui::MeasuredDoubleLineEdit(0);+ m_heightFld = new DVGui::MeasuredDoubleLineEdit(nullptr);m_dpiLabel = new QLabel(tr("DPI:"));- m_dpiFld = new DoubleLineEdit(0, 66.76);+ m_dpiFld = new DoubleLineEdit(nullptr, 66.76);m_rasterFormatLabel = new QLabel(tr("Format:"));m_rasterFormatOm = new QComboBox();m_frameFormatBtn = new QPushButton(tr("Frame Format"));- QPushButton *okBtn = new QPushButton(tr("OK"), this);- QPushButton *cancelBtn = new QPushButton(tr("Cancel"), this);- QPushButton *applyBtn = new QPushButton(tr("Apply"), this);+ auto *okBtn = new QPushButton(tr("OK"), this);+ auto *cancelBtn = new QPushButton(tr("Cancel"), this);+ auto *applyBtn = new QPushButton(tr("Apply"), this);- // Exclude all character which cannot fit in a filepath (Win).+ // Replace QRegExp with QRegularExpression+ // Exclude all characters which cannot fit in a filepath (Windows).// Dots are also prohibited since they are internally managed by Toonz.- QRegExp rx("[^\\\\/:?*.\"<>|]+");- m_nameFld->setValidator(new QRegExpValidator(rx, this));+ QRegularExpression rx(R"([^\\/:?*."<>|]+)");+ m_nameFld->setValidator(new QRegularExpressionValidator(rx, this));- m_levelTypeOm->addItem(tr("Toonz Vector Level"), (int)PLI_XSHLEVEL);- m_levelTypeOm->addItem(tr("Toonz Raster Level"), (int)TZP_XSHLEVEL);- m_levelTypeOm->addItem(tr("Raster Level"), (int)OVL_XSHLEVEL);- m_levelTypeOm->addItem(tr("Scan Level"), (int)TZI_XSHLEVEL);- m_levelTypeOm->addItem(tr("Assistants Level"), (int)META_XSHLEVEL);+ m_levelTypeOm->addItem(tr("Toonz Vector Level"), PLI_XSHLEVEL);+ m_levelTypeOm->addItem(tr("Toonz Raster Level"), TZP_XSHLEVEL);+ m_levelTypeOm->addItem(tr("Raster Level"), OVL_XSHLEVEL);+ m_levelTypeOm->addItem(tr("Scan Level"), TZI_XSHLEVEL);+ m_levelTypeOm->addItem(tr("Assistants Level"), META_XSHLEVEL);if (Preferences::instance()->getUnits() == "pixel") {m_widthFld->setMeasure("camera.lx");@@ -207,9 +227,9 @@ LevelCreatePopup::LevelCreatePopup()m_heightFld->setMeasure("level.ly");}- m_widthFld->setRange(0.1, (std::numeric_limits<double>::max)());- m_heightFld->setRange(0.1, (std::numeric_limits<double>::max)());- m_dpiFld->setRange(0.1, (std::numeric_limits<double>::max)());+ m_widthFld->setRange(0.1, std::numeric_limits<double>::max());+ m_heightFld->setRange(0.1, std::numeric_limits<double>::max());+ m_dpiFld->setRange(0.1, std::numeric_limits<double>::max());m_rasterFormatOm->addItem("tif", "tif");m_rasterFormatOm->addItem("png", "png");@@ -218,70 +238,69 @@ LevelCreatePopup::LevelCreatePopup()okBtn->setDefault(true);- //--- layout+ // Layoutm_topLayout->setContentsMargins(0, 0, 0, 0);m_topLayout->setSpacing(0);- {- QGridLayout *guiLay = new QGridLayout();- guiLay->setContentsMargins(10, 10, 10, 10);- guiLay->setVerticalSpacing(10);- guiLay->setHorizontalSpacing(5);- {- // Name- guiLay->addWidget(new QLabel(tr("Name:")), 0, 0,- Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_nameFld, 0, 1, 1, 4);-- // From-To- guiLay->addWidget(new QLabel(tr("From:")), 1, 0,- Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_fromFld, 1, 1);- guiLay->addWidget(new QLabel(tr("To:")), 1, 2,- Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_toFld, 1, 3);-- // Step-Inc- guiLay->addWidget(new QLabel(tr("Step:")), 2, 0,- Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_stepFld, 2, 1);- guiLay->addWidget(new QLabel(tr("Increment:")), 2, 2,- Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_incFld, 2, 3);-- // Type- guiLay->addWidget(new QLabel(tr("Type:")), 3, 0,- Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_levelTypeOm, 3, 1, 1, 3);-- // Save In- guiLay->addWidget(new QLabel(tr("Save In:")), 4, 0,- Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_pathFld, 4, 1, 1, 4);-- // Format options (for Raster/Scan levels)- guiLay->addWidget(m_rasterFormatLabel, 5, 0,- Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_rasterFormatOm, 5, 1, Qt::AlignLeft);- guiLay->addWidget(m_frameFormatBtn, 5, 2, 1, 2, Qt::AlignLeft);-- // Width - Height- guiLay->addWidget(m_widthLabel, 6, 0, Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_widthFld, 6, 1);- guiLay->addWidget(m_heightLabel, 6, 2, Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_heightFld, 6, 3);-- // DPI- guiLay->addWidget(m_dpiLabel, 7, 0, Qt::AlignRight | Qt::AlignVCenter);- guiLay->addWidget(m_dpiFld, 7, 1);- }- guiLay->setColumnStretch(0, 0);- guiLay->setColumnStretch(1, 0);- guiLay->setColumnStretch(2, 0);- guiLay->setColumnStretch(3, 0);- guiLay->setColumnStretch(4, 1);- m_topLayout->addLayout(guiLay, 1);- }+ auto *guiLay = new QGridLayout();+ guiLay->setContentsMargins(10, 10, 10, 10);+ guiLay->setVerticalSpacing(10);+ guiLay->setHorizontalSpacing(5);++ // Name+ guiLay->addWidget(new QLabel(tr("Name:")), 0, 0,+ Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_nameFld, 0, 1, 1, 4);++ // From-To+ guiLay->addWidget(new QLabel(tr("From:")), 1, 0,+ Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_fromFld, 1, 1);+ guiLay->addWidget(new QLabel(tr("To:")), 1, 2,+ Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_toFld, 1, 3);++ // Step-Increment+ guiLay->addWidget(new QLabel(tr("Step:")), 2, 0,+ Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_stepFld, 2, 1);+ guiLay->addWidget(new QLabel(tr("Increment:")), 2, 2,+ Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_incFld, 2, 3);++ // Type+ guiLay->addWidget(new QLabel(tr("Type:")), 3, 0,+ Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_levelTypeOm, 3, 1, 1, 3);++ // Save In+ guiLay->addWidget(new QLabel(tr("Save In:")), 4, 0,+ Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_pathFld, 4, 1, 1, 4);++ // Format options (for Raster/Scan levels)+ guiLay->addWidget(m_rasterFormatLabel, 5, 0,+ Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_rasterFormatOm, 5, 1, Qt::AlignLeft);+ guiLay->addWidget(m_frameFormatBtn, 5, 2, 1, 2, Qt::AlignLeft);++ // Width - Height+ guiLay->addWidget(m_widthLabel, 6, 0, Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_widthFld, 6, 1);+ guiLay->addWidget(m_heightLabel, 6, 2, Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_heightFld, 6, 3);++ // DPI+ guiLay->addWidget(m_dpiLabel, 7, 0, Qt::AlignRight | Qt::AlignVCenter);+ guiLay->addWidget(m_dpiFld, 7, 1);++ guiLay->setColumnStretch(0, 0);+ guiLay->setColumnStretch(1, 0);+ guiLay->setColumnStretch(2, 0);+ guiLay->setColumnStretch(3, 0);+ guiLay->setColumnStretch(4, 1);++ m_topLayout->addLayout(guiLay, 1);m_buttonLayout->setContentsMargins(0, 0, 0, 0);m_buttonLayout->setSpacing(30);@@ -293,16 +312,15 @@ LevelCreatePopup::LevelCreatePopup()m_buttonLayout->addStretch(1);}- //---- signal-slot connections- bool ret = true;- ret = ret && connect(m_levelTypeOm, SIGNAL(currentIndexChanged(int)),- SLOT(onLevelTypeChanged(int)));- ret = ret && connect(m_frameFormatBtn, SIGNAL(clicked()), this,- SLOT(onFrameFormatButton()));- ret = ret && connect(okBtn, SIGNAL(clicked()), this, SLOT(onOkBtn()));- ret = ret && connect(cancelBtn, SIGNAL(clicked()), this, SLOT(reject()));- ret =- ret && connect(applyBtn, SIGNAL(clicked()), this, SLOT(onApplyButton()));+ // Modern signal-slot connections using function pointers+ connect(m_levelTypeOm, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &LevelCreatePopup::onLevelTypeChanged);+ connect(m_frameFormatBtn, &QPushButton::clicked, this,+ &LevelCreatePopup::onFrameFormatButton);+ connect(okBtn, &QPushButton::clicked, this, &LevelCreatePopup::onOkBtn);+ connect(cancelBtn, &QPushButton::clicked, this, &QDialog::reject);+ connect(applyBtn, &QPushButton::clicked, this,+ &LevelCreatePopup::onApplyButton);setSizeWidgetEnable(false);setRasterWidgetVisible(false);@@ -312,27 +330,26 @@ LevelCreatePopup::LevelCreatePopup()void LevelCreatePopup::updatePath() {ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();- TFilePath defaultPath;- defaultPath = scene->getDefaultLevelPath(getLevelType()).getParentDir();+ TFilePath defaultPath =+ scene->getDefaultLevelPath(getLevelType()).getParentDir();m_pathFld->setPath(toQString(defaultPath));}//-----------------------------------------------------------------------------void LevelCreatePopup::nextName() {- const std::unique_ptr<NameBuilder> nameBuilder(NameBuilder::getBuilder(L""));+ const auto nameBuilder =+ std::unique_ptr<NameBuilder>(NameBuilder::getBuilder(L""));- std::wstring levelName = L"";+ std::wstring levelName;// Select a different unique level name in case it already exists (either in// scene or on disk)-- for (;;) {+ while (true) {levelName = nameBuilder->getNext();-- if (levelExists(levelName)) continue;-- break;+ if (!levelExists(levelName)) {+ break;+ }}m_nameFld->setText(QString::fromStdWString(levelName));@@ -340,37 +357,39 @@ void LevelCreatePopup::nextName() {//------------------------------------------------------------------------------bool LevelCreatePopup::levelExists(std::wstring levelName) {- TFilePath fp;- TFilePath actualFp;- ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();- TLevelSet *levelSet =- TApp::instance()->getCurrentScene()->getScene()->getLevelSet();+bool LevelCreatePopup::levelExists(const std::wstring &levelName) {+ ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();+ TLevelSet *levelSet = scene->getLevelSet();TFilePath parentDir(m_pathFld->getPath().toStdWString());- fp = scene->getDefaultLevelPath(getLevelType(), levelName)- .withParentDir(parentDir);- actualFp = scene->decodeFilePath(fp);+ TFilePath fp = scene->getDefaultLevelPath(getLevelType(), levelName)+ .withParentDir(parentDir);+ TFilePath actualFp = scene->decodeFilePath(fp);- if (TSystem::doesExistFileOrLevel(actualFp))+ if (TSystem::doesExistFileOrLevel(actualFp)) {return true;- else if (TXshLevel *level = levelSet->getLevel(levelName)) {- // even if the level exists in the scene cast, it can be replaced if it is+ }++ if (TXshLevel *level = levelSet->getLevel(levelName)) {+ // Even if the level exists in the scene cast, it can be replaced if it is// unusedif (Preferences::instance()->isAutoRemoveUnusedLevelsEnabled() &&- !scene->getChildStack()->getTopXsheet()->isLevelUsed(level))+ !scene->getChildStack()->getTopXsheet()->isLevelUsed(level)) {return false;- else- return true;- } else- return false;+ }+ return true;+ }++ return false;}//------------------------------------------------------------------------------void LevelCreatePopup::showEvent(QShowEvent *) {+void LevelCreatePopup::showEvent(QShowEvent *event) {+ Dialog::showEvent(event);update();nextName();m_nameFld->setFocus();+if (Preferences::instance()->getUnits() == "pixel") {m_dpiFld->hide();m_dpiLabel->hide();@@ -414,20 +433,16 @@ int LevelCreatePopup::getLevelType() const {void LevelCreatePopup::onLevelTypeChanged(int index) {int type = m_levelTypeOm->itemData(index).toInt();- if (type == OVL_XSHLEVEL || type == TZP_XSHLEVEL)- setSizeWidgetEnable(true);- else- setSizeWidgetEnable(false);+ setSizeWidgetEnable(type == OVL_XSHLEVEL || type == TZP_XSHLEVEL);setRasterWidgetVisible(type == OVL_XSHLEVEL || type == TZI_XSHLEVEL);updatePath();std::wstring levelName = m_nameFld->text().toStdWString();- // check if the name already exists or if it is a 1 letter name- // one letter names are most likely created automatically so- // this makes sure that automatically created names- // don't skip a letter.+ // Check if the name already exists or if it is a 1-letter name+ // One-letter names are most likely created automatically so+ // this ensures that automatically created names don't skip a letter.if (levelExists(levelName) || levelName.length() == 1) {nextName();}@@ -437,10 +452,11 @@ void LevelCreatePopup::onLevelTypeChanged(int index) {//-----------------------------------------------------------------------------void LevelCreatePopup::onOkBtn() {- if (apply())+ if (apply()) {close();- else+ } else {m_nameFld->setFocus();+ }}//-----------------------------------------------------------------------------@@ -458,6 +474,7 @@ void LevelCreatePopup::onFrameFormatButton() {// Tentatively use the preview output settingsToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();if (!scene) return;+std::string ext = m_rasterFormatOm->currentData().toString().toStdString();openFormatSettingsPopup(this, ext, nullptr,&scene->getProperties()->formatTemplateFIdForInput());@@ -469,20 +486,19 @@ bool LevelCreatePopup::apply() {TApp *app = TApp::instance();int row = app->getCurrentFrame()->getFrame();int col = app->getCurrentColumn()->getColumnIndex();- int i, j;ToonzScene *scene = app->getCurrentScene()->getScene();TXsheet *xsh = scene->getXsheet();bool validColumn = true;- if (xsh->getColumn(col))- validColumn =- xsh->getColumn(col)->getColumnType() == TXshColumn::eLevelType;-- int from = (int)m_fromFld->getValue();- int to = (int)m_toFld->getValue();- int inc = (int)m_incFld->getValue();- int step = (int)m_stepFld->getValue();+ if (TXshColumn *column = xsh->getColumn(col)) {+ validColumn = (column->getColumnType() == TXshColumn::eLevelType);+ }++ int from = static_cast<int>(m_fromFld->getValue());+ int to = static_cast<int>(m_toFld->getValue());+ int inc = static_cast<int>(m_incFld->getValue());+ int step = static_cast<int>(m_stepFld->getValue());double w = m_widthFld->getValue();double h = m_heightFld->getValue();double dpi = m_dpiFld->getValue();@@ -491,23 +507,23 @@ bool LevelCreatePopup::apply() {int lType = getLevelType();std::wstring levelName = m_nameFld->text().toStdWString();- // tolgo i blanks prima e dopo-- i = levelName.find_first_not_of(L' ');- if (i == (int)std::wstring::npos)- levelName = L"";- else {- int j = levelName.find_last_not_of(L' ');- assert(j != (int)std::wstring::npos);- levelName = levelName.substr(i, j - i + 1);+ // Remove leading and trailing whitespace+ auto start = levelName.find_first_not_of(L' ');+ if (start == std::wstring::npos) {+ levelName.clear();+ } else {+ auto end = levelName.find_last_not_of(L' ');+ levelName = levelName.substr(start, end - start + 1);}+if (levelName.empty()) {error(tr("No level name specified: please choose a valid level name"));return false;}- if (isReservedFileName_message(QString::fromStdWString(levelName)))+ if (isReservedFileName_message(QString::fromStdWString(levelName))) {return false;+ }if (from > to) {error(tr("Invalid frame range"));@@ -526,7 +542,7 @@ bool LevelCreatePopup::apply() {TXshLevel *existingLevel = scene->getLevelSet()->getLevel(levelName);if (existingLevel) {- // check if the existing level can be removed+ // Check if the existing level can be removedif (!Preferences::instance()->isAutoRemoveUnusedLevelsEnabled() ||scene->getChildStack()->getTopXsheet()->isLevelUsed(existingLevel)) {error(@@ -535,15 +551,16 @@ bool LevelCreatePopup::apply() {m_nameFld->selectAll();return false;}- // if the exitingLevel is not null, it will be removed afterwards+ // If existingLevel is not null, it will be removed afterwards}TFilePath parentDir(m_pathFld->getPath().toStdWString());TFilePath fp =scene->getDefaultLevelPath(lType, levelName).withParentDir(parentDir);- if (lType == OVL_XSHLEVEL || lType == TZI_XSHLEVEL)+ if (lType == OVL_XSHLEVEL || lType == TZI_XSHLEVEL) {fp = fp.withType(m_rasterFormatOm->currentData().toString().toStdString());+ }TFilePath actualFp = scene->decodeFilePath(fp);if (TSystem::doesExistFileOrLevel(actualFp)) {@@ -553,21 +570,19 @@ bool LevelCreatePopup::apply() {m_nameFld->selectAll();return false;}+parentDir = scene->decodeFilePath(parentDir);if (!TFileStatus(parentDir).doesExist()) {- QString question;- /*question = "Folder " +toQString(parentDir) +- " doesn't exist.\nDo you- want to create it?";*/- question = tr("Folder %1 doesn't exist.\nDo you want to create it?")- .arg(toQString(parentDir));+ QString question = tr("Folder %1 doesn't exist.\nDo you want to create it?")+ .arg(toQString(parentDir));int ret = DVGui::MsgBox(question, QObject::tr("Yes"), QObject::tr("No"));if (ret == 0 || ret == 2) return false;+try {TSystem::mkDir(parentDir);DvDirModel::instance()->refreshFolder(parentDir.getParentDir());} catch (...) {- error(tr("Unable to create") + toQString(parentDir));+ error(tr("Unable to create %1").arg(toQString(parentDir)));return false;}}@@ -578,33 +593,33 @@ bool LevelCreatePopup::apply() {// the preference option AutoRemoveUnusedLevels is ONif (existingLevel) {bool ok = LevelCmd::removeLevelFromCast(existingLevel, scene, false);- assert(ok);+ Q_ASSERT(ok);DVGui::info(QObject::tr("Removed unused level %1 from the scene cast. ""(This behavior can be disabled in Preferences.)").arg(QString::fromStdWString(levelName)));}- /*-- これからLevelを配置しようとしているセルが空いているかどうかのチェック- * --*/+ // Check if the cells where we want to place the level are emptybool areColumnsShifted = false;- TXshCell cell = xsh->getCell(row, col);bool isInRange = true;- if (col < 0)++ if (col < 0) {isInRange = false;- else {- for (i = row; i < row + numFrames; i++) {- if (!cell.isEmpty()) {+ } else {+ for (int i = row; i < row + numFrames; ++i) {+ if (!xsh->getCell(i, col).isEmpty()) {isInRange = false;break;}- cell = xsh->getCell(i, col);}}+if (!validColumn) {isInRange = false;}- /*-- 別のLevelに占有されていた場合、Columnを1つ右に移動 --*/+ // If the range is occupied by another level, shift the column one to the+ // rightif (!isInRange) {col += 1;TApp::instance()->getCurrentColumn()->setColumnIndex(col);@@ -612,7 +627,7 @@ bool LevelCreatePopup::apply() {xsh->insertColumn(col);}- CreateLevelUndo *undo =+ auto *undo =new CreateLevelUndo(row, col, numFrames, step, areColumnsShifted);TUndoManager::manager()->add(undo);@@ -620,8 +635,9 @@ bool LevelCreatePopup::apply() {scene->createNewLevel(lType, levelName, TDimension(), 0, fp);TXshSimpleLevel *sl = dynamic_cast<TXshSimpleLevel *>(level);- assert(sl);+ Q_ASSERT(sl);sl->setPath(fp, true);+if (lType == TZP_XSHLEVEL || lType == OVL_XSHLEVEL) {sl->getProperties()->setDpiPolicy(LevelProperties::DP_ImageDpi);sl->getProperties()->setDpi(dpi);@@ -629,13 +645,14 @@ bool LevelCreatePopup::apply() {sl->getProperties()->setImageRes(TDimension(xres, yres));}- for (i = from; i <= to; i += inc) {+ for (int i = from; i <= to; i += inc) {TFrameId fid(i);- if (lType == PLI_XSHLEVEL)++ if (lType == PLI_XSHLEVEL) {sl->setFrame(fid, new TVectorImage());- else if (lType == META_XSHLEVEL)+ } else if (lType == META_XSHLEVEL) {sl->setFrame(fid, new TMetaImage());- else if (lType == TZP_XSHLEVEL) {+ } else if (lType == TZP_XSHLEVEL) {TRasterCM32P raster(xres, yres);raster->fill(TPixelCM32());TToonzImageP ti(raster, TRect());@@ -645,21 +662,24 @@ bool LevelCreatePopup::apply() {// This update should be called at least once, or it won't be rendered// Almost every level tool will call ToolUtils::updateSavebox() to update- // But since fill tool tend to not update the savebox, we call it here- TImageInfo* info = sl->getFrameInfo(fid, true);+ // But since fill tool tends to not update the savebox, we call it here+ TImageInfo *info = sl->getFrameInfo(fid, true);ImageBuilder::setImageInfo(*info, ti.getPointer());} else if (lType == OVL_XSHLEVEL) {TRaster32P raster(xres, yres);raster->clear();TRasterImageP ri(raster);ri->setDpi(dpi, dpi);- // modify frameId to be with the same frame format as existing frames+ // Modify frameId to have the same frame format as existing framesTFrameId tmplFId = scene->getProperties()->formatTemplateFIdForInput();sl->formatFId(fid, tmplFId);sl->setFrame(fid, ri);}+TXshCell cell(sl, fid);- for (j = 0; j < step; j++) xsh->setCell(row++, col, cell);+ for (int j = 0; j < step; ++j) {+ xsh->setCell(row++, col, cell);+ }}if (lType == TZP_XSHLEVEL || lType == OVL_XSHLEVEL) {@@ -668,19 +688,18 @@ bool LevelCreatePopup::apply() {}undo->onAdd(sl);-TUndoManager::manager()->endBlock();app->getCurrentScene()->notifySceneChanged();app->getCurrentScene()->notifyCastChange();app->getCurrentXsheet()->notifyXsheetChanged();- // Cambia l'immagine corrente ma non cambiano ne' il frame ne' la colonna- // corrente- // (entrambi notificano il cambiamento dell'immagine al tool).- // devo verfificare che sia settato il tool giusto.+ // Change the current image but don't change the current frame or column+ // (both notify the image change to the tool).+ // Need to verify that the correct tool is set.app->getCurrentTool()->onImageChanged(- (TImage::Type)app->getCurrentImageType());+ static_cast<TImage::Type>(app->getCurrentImageType()));+return true;}@@ -688,6 +707,7 @@ bool LevelCreatePopup::apply() {void LevelCreatePopup::update() {updatePath();+Preferences *pref = Preferences::instance();if (pref->getUnits() == "pixel") {m_widthFld->setMeasure("camera.lx");@@ -696,6 +716,7 @@ void LevelCreatePopup::update() {m_widthFld->setMeasure("level.lx");m_heightFld->setMeasure("level.ly");}+if (pref->isNewLevelSizeToCameraSizeEnabled()) {TCamera *currCamera =TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera();@@ -711,19 +732,9 @@ void LevelCreatePopup::update() {int levelType = pref->getDefLevelType();int index = m_levelTypeOm->findData(levelType);- if (index >= 0) m_levelTypeOm->setCurrentIndex(index);-- /*-(old behaviour)-TCamera* camera = scene->getCurrentCamera();- TDimensionD cameraSize = camera->getSize();- m_widthFld->setValue(cameraSize.lx);- m_heightFld->setValue(cameraSize.ly);-if(camera->isXPrevalence())-m_dpiFld->setValue(camera->getDpi().x);-else-m_dpiFld->setValue(camera->getDpi().y);-*/+ if (index >= 0) {+ m_levelTypeOm->setCurrentIndex(index);+ }}//-----------------------------------------------------------------------------diff --git a/toonz/sources/toonz/levelcreatepopup.h b/toonz/sources/toonz/levelcreatepopup.hindex b47f54bbf..5815ad138 100644--- a/toonz/sources/toonz/levelcreatepopup.h+++ b/toonz/sources/toonz/levelcreatepopup.h@@ -8,10 +8,19 @@#include "toonzqt/intfield.h"#include "toonzqt/filefield.h"-// forward declaration+// Qt forward declarations+#include <QObject>+#include <QString>+class QLabel;class QComboBox;-// class DVGui::MeasuredDoubleLineEdit;+class QPushButton;+class QShowEvent;++namespace DVGui {+class LineEdit;+class MeasuredDoubleLineEdit;+} // namespace DVGui//=============================================================================// LevelCreatePopup@@ -20,13 +29,16 @@ class QComboBox;class LevelCreatePopup final : public DVGui::Dialog {Q_OBJECT+ // UI WidgetsDVGui::LineEdit *m_nameFld;DVGui::IntLineEdit *m_fromFld;DVGui::IntLineEdit *m_toFld;- QComboBox *m_levelTypeOm;DVGui::IntLineEdit *m_stepFld;DVGui::IntLineEdit *m_incFld;++ QComboBox *m_levelTypeOm;DVGui::FileField *m_pathFld;+QLabel *m_widthLabel;QLabel *m_heightLabel;QLabel *m_dpiLabel;@@ -39,27 +51,37 @@ class LevelCreatePopup final : public DVGui::Dialog {QPushButton *m_frameFormatBtn;public:- LevelCreatePopup();+ explicit LevelCreatePopup();++ // Disable copying+ LevelCreatePopup(const LevelCreatePopup &) = delete;+ LevelCreatePopup &operator=(const LevelCreatePopup &) = delete;+ // Widget state controlvoid setSizeWidgetEnable(bool isEnable);void setRasterWidgetVisible(bool isVisible);+ // Gettersint getLevelType() const;+ // Operationsvoid update();bool apply();protected:- // set m_pathFld to the default path+ // Set m_pathFld to the default pathvoid updatePath();void nextName();- void showEvent(QShowEvent *) override;- bool levelExists(std::wstring levelName);-public slots:+ // Event handlers+ void showEvent(QShowEvent *event) override;++ // Validation+ bool levelExists(const std::wstring &levelName);++public Q_SLOTS:void onLevelTypeChanged(int index);void onOkBtn();-void onApplyButton();void onFrameFormatButton();};diff --git a/toonz/sources/toonz/loadfoldercommand.cpp b/toonz/sources/toonz/loadfoldercommand.cppindex 05d9301b5..941f186a2 100644--- a/toonz/sources/toonz/loadfoldercommand.cpp+++ b/toonz/sources/toonz/loadfoldercommand.cpp@@ -26,28 +26,27 @@#include <QCoreApplication>#include <QDir>#include <QFileInfo>-#include <QRegExp>+#include <QMainWindow>+#include <QRegularExpression> // Changed from QRegExp#include <QButtonGroup>#include <QRadioButton>-// boost includes+// Boost includes#include <boost/optional.hpp>#include <boost/operators.hpp>#include <boost/range.hpp>-#include <boost/iterator/transform_iterator.hpp>-#include <boost/range/algorithm/for_each.hpp>#include <boost/range/algorithm/copy.hpp>#include <boost/range/adaptor/filtered.hpp>#include <boost/range/adaptor/adjacent_filtered.hpp>#include <boost/range/adaptor/transformed.hpp>-#include <boost/utility/in_place_factory.hpp>// STD includes#include <set>#include <algorithm>+#include <memory> // Added for std::unique_ptr//************************************************************************// Local namespace structures@@ -56,13 +55,12 @@namespace {typedef IoCmd::LoadResourceArguments LRArgs;-typedef TFilePath (*PathFunc)(const TFilePath &);//--------------------------------------------------------------struct FormatData {- QRegExp m_regExp;+ QRegularExpression m_regExp; // Changed from QRegExpPathFunc m_resourcePathFunc, m_componentPathFunc;};@@ -70,14 +68,15 @@ struct FormatData {// ResourceData definition//************************************************************************-struct Resource //! A single resource to be loaded.+struct Resource //! A single resource to be loaded.{- struct Path : private boost::less_than_comparable<Path> //! Path locating a- //! resource.+ struct Path+ : private boost::less_than_comparable<Path> //! Path locating a resource.{- TFilePath m_rootFp, //!< Selected root folder hosting the resource.- m_relFp; //!< Path representing the resource, \a relative- //! to \p m_rootFolder.+ TFilePath m_rootFp; //!< Selected root folder hosting the resource.+ TFilePath m_relFp; //!< Path representing the resource, \a relative to \p+ //!< m_rootFolder.+public:Path(const TFilePath &rootPath, const TFilePath &relativeFilePath): m_rootFp(rootPath), m_relFp(relativeFilePath) {@@ -94,9 +93,10 @@ struct Resource //! A single resource to be loaded.};struct Component {- TFilePath m_srcFp; //!< Source path, <I>relative to parent folder</I>.- PathFunc m_pathFunc; //!< Possible callback function transforming source- //! paths into their imported counterparts.+ TFilePath m_srcFp; //!< Source path, <I>relative to parent folder</I>.+ PathFunc+ m_pathFunc; //!< Possible callback function transforming source paths.+public:Component(const TFilePath &srcPath, PathFunc pathFunc): m_srcFp(srcPath), m_pathFunc(pathFunc) {@@ -108,10 +108,9 @@ struct Resource //! A single resource to be loaded.public:Path m_path; //!< The level path.- CompSeq m_components; //!< File Paths for level components. The first path- //! is intended as the resource's file representant.+ CompSeq m_components; //!< File Paths for level components.boost::optional<LevelOptions>- m_levelOptions; //!< Level Options to be loaded for a level resource.+ m_levelOptions; //!< Level Options to be loaded.public:Resource(const Path &path) : m_path(path) {}@@ -157,7 +156,6 @@ TFilePath relativePath(const TFilePath &from, const TFilePath &to) {bool isLoadable(const TFilePath &resourcePath) {TFileType::Type type = TFileType::getInfo(resourcePath);-return (type & TFileType::IMAGE || type & TFileType::LEVEL);}@@ -165,7 +163,8 @@ bool isLoadable(const TFilePath &resourcePath) {template <typename RegStruct>bool exactMatch(const RegStruct ®Struct, const TFilePath &fp) {- return regStruct.m_regExp.exactMatch(fp.getQString());+ QRegularExpressionMatch match = regStruct.m_regExp.match(fp.getQString());+ return match.hasMatch(); // Changed from exactMatch()}//==============================================================@@ -195,9 +194,12 @@ TFilePath retasResourcePath(const TFilePath &fp) {//--------------------------------------------------------------static const FormatData l_formatDatas[] = {- {QRegExp(".+\\.[0-9]{4,4}.*\\..*"), &multiframeResourcePath, 0},- {QRegExp(".+[0-9]{4,4}\\.tga", Qt::CaseInsensitive), &retasResourcePath,- &retasComponentPath}};+ // Changed QRegExp patterns to QRegularExpression+ {QRegularExpression(R"(.+\.[0-9]{4,4}.*\..*)"), &multiframeResourcePath,+ nullptr},+ {QRegularExpression(R"(.+[0-9]{4,4}\.tga)",+ QRegularExpression::CaseInsensitiveOption),+ &retasResourcePath, &retasComponentPath}};//==============================================================@@ -219,25 +221,26 @@ struct buildResources_locals {}struct MergeData {- QRegExp m_regExp; //!< Path regexp for file pattern recognition.- int m_componentIdx; //!< Starting index for components merging.+ QRegularExpression m_regExp; // Changed from QRegExp+ int m_componentIdx; //!< Starting index for components merging.};static void mergeInto(RsrcMap::iterator &rt, RsrcMap &rsrcMap) {- // NOTE: This algorithm works for 1-level-deep inclusions. I guess this is- // sufficient,- // for now.+ // This algorithm works for 1-level-deep inclusions.static const std::string componentsTable[] = {"cln", "tpl", "hst"};-- static const MergeData mergeTable[] = {- {QRegExp(".*\\.\\..*"), 0}, {QRegExp(".*\\.tlv"), 1}, {QRegExp(), 3}};+ static const MergeData mergeTable[] = {+ {QRegularExpression(R"(.*\..\..*)"), 0},+ {QRegularExpression(R"(.*\.tlv)"), 1},+ {QRegularExpression(), 3}};// Lookup rd's path in the mergeTableconst MergeData *mdt,*mdEnd = mergeTable + boost::size(mergeTable) - 1; // Last item is fake- mdt = std::find_if(mergeTable, mdEnd, [&rt](const MergeData& mergeData){ return exactMatch(mergeData, rt->first.first.m_relFp); });+ mdt = std::find_if(mergeTable, mdEnd, [&rt](const MergeData &mergeData) {+ return exactMatch(mergeData, rt->first.first.m_relFp);+ });if (mdt != mdEnd) {// Lookup every possible resource component to merge@@ -286,8 +289,7 @@ void buildResources(std::vector<Resource> &resources, const TFilePath &rootPath,// Extract loadable levels in the folderQDir folderDir(folderPath.getQString());{- const QStringList &files =- folderDir.entryList(QDir::Files); // Files only first+ const QStringList &files = folderDir.entryList(QDir::Files);// Store every possible resource pathRsrcMap rsrcMap;@@ -295,14 +297,16 @@ void buildResources(std::vector<Resource> &resources, const TFilePath &rootPath,QStringList::const_iterator ft, fEnd = files.end();for (ft = files.begin(); ft != fEnd; ++ft) {const TFilePath &compPath = TFilePath(*ft); // Relative to folderPath- PathFunc componentFunc = 0;+ PathFunc componentFunc = nullptr; // Changed from 0 to nullptrTFilePath relPath = relativePath(rootPath, folderPath + compPath);const FormatData *fdt,*fdEnd = l_formatDatas + boost::size(l_formatDatas);- fdt = std::find_if(- l_formatDatas, fdEnd, [&relPath](const FormatData &formatData){ return exactMatch(formatData, relPath); });+ fdt = std::find_if(l_formatDatas, fdEnd,+ [&relPath](const FormatData &formatData) {+ return exactMatch(formatData, relPath);+ });if (fdt != fdEnd) {relPath = fdt->m_resourcePathFunc(relPath);@@ -352,14 +356,15 @@ TFilePath dstPath(const TFilePath &dstDir, const Resource::Component &comp) {struct import_Locals {const ToonzScene &m_scene;- std::unique_ptr<OverwriteDialog> m_overwriteDialog;+ std::unique_ptr<OverwriteDialog>+ m_overwriteDialog; // Changed to std::unique_ptrvoid switchToDst(Resource::Path &path) {path.m_rootFp = m_scene.decodeFilePath(m_scene.getImportedLevelPath(path.absoluteResourcePath()).getParentDir() // E.g. +drawings/+ path.m_rootFp.getWideName() // Root dir name- );+ );}static void copy(const TFilePath &srcDir, const TFilePath &dstDir,@@ -382,8 +387,7 @@ struct import_Locals {// Make sure destination folder existsTSystem::mkDir(dstDir);- // Find out whether a destination component file- // already exists+ // Find out whether a destination component file already existsbool overwrite = false;OverwriteDialog::Obj obj = {dstDir, rsrc};@@ -396,11 +400,15 @@ struct import_Locals {}// Perform resource copy- std::for_each(rsrc.m_components.begin(), rsrc.m_components.end(),- [&srcDir, &dstDir, &overwrite](const Resource::Component &comp){ copy(srcDir, dstDir, comp, overwrite); });+ std::for_each(+ rsrc.m_components.begin(), rsrc.m_components.end(),+ [&srcDir, &dstDir, &overwrite](const Resource::Component &comp) {+ copy(srcDir, dstDir, comp, overwrite);+ });} catch (const TException &e) {DVGui::error(QString::fromStdWString(e.getMessage()));} catch (...) {+ // Handle unknown exceptions}}@@ -408,12 +416,12 @@ struct import_Locals {void import(const ToonzScene &scene, std::vector<Resource> &resources,IoCmd::LoadResourceArguments::ScopedBlock &sb) {- import_Locals locals = {scene, std::unique_ptr<OverwriteDialog>()};+ import_Locals locals = {scene, nullptr};// Setup import GUI- int r, rCount = resources.size();+ int r, rCount = static_cast<int>(resources.size());- DVGui::ProgressDialog *progressDialog = 0;+ DVGui::ProgressDialog *progressDialog = nullptr; // Changed from 0 to nullptrif (rCount > 1) {progressDialog = &sb.progressDialog();@@ -425,8 +433,9 @@ void import(const ToonzScene &scene, std::vector<Resource> &resources,// Perform importlocals.m_overwriteDialog.reset(new OverwriteDialog(- progressDialog ? (QWidget *)progressDialog- : (QWidget *)TApp::instance()->getMainWindow()));+ progressDialog+ ? static_cast<QWidget *>(progressDialog)+ : static_cast<QWidget *>(TApp::instance()->getMainWindow())));for (r = 0; r != rCount; ++r) {Resource &rsrc = resources[r];@@ -486,7 +495,9 @@ QString OverwriteDialog::acceptResolution(void *obj_, int resolution,static bool existsResource(const TFilePath &dstDir, const Resource &rsrc) {return std::any_of(rsrc.m_components.begin(), rsrc.m_components.end(),- [&dstDir](const Resource::Component &comp){ return existsComponent(dstDir, comp); });+ [&dstDir](const Resource::Component &comp) {+ return existsComponent(dstDir, comp);+ });}}; // locals@@ -539,9 +550,10 @@ int IoCmd::loadResourceFolders(LoadResourceArguments &args,// Deal with import decisionbool import = false;{- if (std::any_of(- args.resourceDatas.begin(), args.resourceDatas.end(),- [scene](const LRArgs::ResourceData &rd){ return locals::isExternPath(*scene, rd); })) {+ if (std::any_of(args.resourceDatas.begin(), args.resourceDatas.end(),+ [scene](const LRArgs::ResourceData &rd) {+ return locals::isExternPath(*scene, rd);+ })) {// Ask for data import in this caseint resolutionButton = DVGui::MsgBox(QObject::tr("Selected folders don't belong to the current project.\n"@@ -565,7 +577,9 @@ int IoCmd::loadResourceFolders(LoadResourceArguments &args,std::vector<Resource> resources;boost::for_each(args.resourceDatas,- [&resources](const LRArgs::ResourceData &resourceData){ buildResources(resources, resourceData.m_path, TFilePath()); });+ [&resources](const LRArgs::ResourceData &resourceData) {+ buildResources(resources, resourceData.m_path, TFilePath());+ });// Import them if requiredif (import) ::import(*scene, resources, *sb);diff --git a/toonz/sources/toonz/penciltestpopup.cpp b/toonz/sources/toonz/penciltestpopup.cppindex e1c6fbff5..bccd294e7 100644--- a/toonz/sources/toonz/penciltestpopup.cpp+++ b/toonz/sources/toonz/penciltestpopup.cpp@@ -1,3 +1,5 @@++#include "penciltestpopup.h"#ifdef WIN32@@ -84,7 +86,7 @@#include <QCommonStyle>#include <QTimer>#include <QIntValidator>-#include <QRegExpValidator>+#include <QRegularExpressionValidator>#include <QVideoSurfaceFormat>#include <QThreadPool>@@ -147,15 +149,14 @@ void convertImageToRaster(TRaster32P dstRas, const QImage& srcImg) {}void bgReduction(cv::Mat& srcImg, cv::Mat& bgImg, int reduction) {- // void bgReduction(QImage& srcImg, QImage& bgImg, int reduction) {if (srcImg.cols != bgImg.cols || srcImg.rows != bgImg.rows) return;float reductionRatio = (float)reduction / 100.0f;- // first, make the reduction table+ // First, make the reduction tablestd::vector<int> reductionAmount(256);for (int i = 0; i < reductionAmount.size(); i++) {reductionAmount[i] = (int)(std::floor((float)(255 - i) * reductionRatio));}- // then, compute for all pixels+ // Then, compute for all pixelsint lx = srcImg.cols;int ly = srcImg.rows;for (int j = 0; j < srcImg.rows; j++) {@@ -255,32 +256,32 @@ void openCaptureFilterSettings(const QWidget* parent,ISpecifyPropertyPages* specifyPropertyPages;CAUUID cauuid;- // set parent's window handle in order to make the dialog modal+ // Set parent's window handle in order to make the dialog modalHWND ghwndApp = (HWND)(parent->winId());- // initialize COM+ // Initialize COMCoInitialize(NULL);- // get device list+ // Get device listCoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,IID_ICreateDevEnum, (PVOID*)&createDevEnum);- // create EnumMoniker+ // Create EnumMonikercreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,&enumMoniker, 0);if (enumMoniker == NULL) {- // if no connected devices found+ // If no connected devices foundreturn;}- // reset EnumMoniker+ // Reset EnumMonikerenumMoniker->Reset();- // find target camera+ // Find target cameraULONG fetched = 0;bool isCameraFound = false;while (hr = enumMoniker->Next(1, &moniker, &fetched), hr == S_OK) {- // get friendly name (= device name) of the camera+ // Get friendly name (= device name) of the cameraIPropertyBag* pPropertyBag;moniker->BindToStorage(0, 0, IID_IPropertyBag, (void**)&pPropertyBag);VARIANT var;@@ -294,10 +295,10 @@ void openCaptureFilterSettings(const QWidget* parent,VariantClear(&var);if (deviceName == cameraName) {- // bind monkier to the filter+ // Bind monkier to the filtermoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&deviceFilter);- // release moniker etc.+ // Release moniker etc.moniker->Release();enumMoniker->Release();createDevEnum->Release();@@ -307,10 +308,10 @@ void openCaptureFilterSettings(const QWidget* parent,}}- // if no matching camera found+ // If no matching camera foundif (!isCameraFound) return;- // open capture filter popup+ // Open capture filter popuphr = deviceFilter->QueryInterface(IID_ISpecifyPropertyPages,(void**)&specifyPropertyPages);if (hr == S_OK) {@@ -329,7 +330,7 @@ void openCaptureFilterSettings(const QWidget* parent,QString convertToFrameWithLetter(int value, int length = -1) {QString str;str.setNum((int)(value / 10));- while (str.length() < length) str.push_front("0");+ while (str.length() < length) str.push_front(QLatin1Char('0'));QChar letter = numToLetter(value % 10);if (!letter.isNull()) str.append(letter);return str;@@ -498,10 +499,10 @@ void MyVideoWidget::paintEvent(QPaintEvent* event) {p.setOpacity(1.0);}- // draw subcamera+ // Draw subcameraif (m_subCameraRect.isValid()) drawSubCamera(p);- // draw countdown text+ // Draw countdown textif (m_countDownTime > 0) {QString str =QTime::fromMSecsSinceStartOfDay(m_countDownTime).toString("s.zzz");@@ -542,7 +543,7 @@ void MyVideoWidget::setSubCameraRect(QRect rect) {assert(frameSize == rect.size().expandedTo(frameSize));m_subCameraRect = rect;- // make sure the sub camera is inside of the frame+ // Make sure the sub camera is inside of the frameif (rect.isValid() &&!QRect(QPoint(0, 0), frameSize).contains(m_subCameraRect)) {m_subCameraRect.moveCenter(QRect(QPoint(0, 0), frameSize).center());@@ -574,13 +575,13 @@ void MyVideoWidget::drawSubCamera(QPainter& p) {drawSubFrameLine(HandleBottom, vidSubRect.bottomLeft(),vidSubRect.bottomRight());- // draw handles+ // Draw handlesdrawHandle(HandleTopLeft, vidSubRect.topLeft());drawHandle(HandleTopRight, vidSubRect.topRight());drawHandle(HandleBottomLeft, vidSubRect.bottomLeft());drawHandle(HandleBottomRight, vidSubRect.bottomRight());- // draw cross mark at subcamera center when the cursor is in the frame+ // Draw cross mark at subcamera center when the cursor is in the frameif (m_activeSubHandle != HandleNone) {p.setPen(QPen(Qt::magenta, 1, Qt::DashLine));QPoint crossP(vidSubRect.width() / 40, vidSubRect.height() / 40);@@ -601,10 +602,10 @@ void MyVideoWidget::mouseMoveEvent(QMouseEvent* event) {return std::abs(handlePos - mousePos) <= d;};- // if the sub camera is not active, do nothing and return+ // If the sub camera is not active, do nothing and returnif (m_image.isNull() || m_subCameraRect.isNull()) return;- // with no mouse button, update the active handles+ // With no mouse button, update the active handlesif (event->buttons() == Qt::NoButton) {QRect vidSubRect = m_S2V_Transform.mapRect(m_subCameraRect);SUBHANDLE preHandle = m_activeSubHandle;@@ -653,7 +654,7 @@ void MyVideoWidget::mouseMoveEvent(QMouseEvent* event) {update();}}- // if left button is pressed and some handle is active, transform the+ // If left button is pressed and some handle is active, transform the// subcameraelse if (event->buttons() & Qt::LeftButton &&m_activeSubHandle != HandleNone && m_preSubCameraRect.isValid()) {@@ -721,7 +722,7 @@ void MyVideoWidget::mouseMoveEvent(QMouseEvent* event) {m_subCameraRect.setBottom(m_preSubCameraRect.bottom() + offset.y());}}- // if the sub camera size is changed, notify the parent for updating the+ // If the sub camera size is changed, notify the parent for updating the// fieldsemit subCameraChanged(true);update();@@ -729,23 +730,23 @@ void MyVideoWidget::mouseMoveEvent(QMouseEvent* event) {}void MyVideoWidget::mousePressEvent(QMouseEvent* event) {- // if the sub camera is not active, do nothing and return- // use left button only and some handle must be active+ // If the sub camera is not active, do nothing and return+ // Use left button only and some handle must be activeif (m_image.isNull() || m_subCameraRect.isNull() ||event->button() != Qt::LeftButton || m_activeSubHandle == HandleNone)return;- // record the original sub camera size+ // Record the original sub camera sizem_preSubCameraRect = m_subCameraRect;m_dragStartPos = m_S2V_Transform.inverted().map(event->pos());- // temporary stop the camera+ // Temporary stop the cameraemit stopCamera();}void MyVideoWidget::mouseReleaseEvent(QMouseEvent* event) {- // if the sub camera is not active, do nothing and return- // use left button only and some handle must be active+ // If the sub camera is not active, do nothing and return+ // Use left button only and some handle must be activeif (m_image.isNull() || m_subCameraRect.isNull() ||event->button() != Qt::LeftButton || m_activeSubHandle == HandleNone)return;@@ -754,7 +755,7 @@ void MyVideoWidget::mouseReleaseEvent(QMouseEvent* event) {emit subCameraChanged(false);- // restart the camera+ // Restart the cameraemit startCamera();}@@ -762,21 +763,36 @@ void MyVideoWidget::mouseReleaseEvent(QMouseEvent* event) {FrameNumberLineEdit::FrameNumberLineEdit(QWidget* parent, TFrameId fId,bool acceptLetter)- : LineEdit(parent) {+ : LineEdit(parent)+ , m_regexpValidator(nullptr)+ , m_regexpValidator_alt(nullptr) {if (acceptLetter) {- QString regExpStr = QString("^%1$").arg(TFilePath::fidRegExpStr());- m_regexpValidator = new QRegExpValidator(QRegExp(regExpStr), this);- TProjectManager* pm = TProjectManager::instance();- pm->addListener(this);- } else- m_regexpValidator = new QRegExpValidator(QRegExp("^\\d{1,4}$"), this);+ const QString fid = TFilePath::fidRegExpStr();+ QRegularExpression regExp(QString("^%1$").arg(fid));++ if (regExp.isValid() && !fid.isEmpty()) {+ // Use frame-id regular expression from TFilePath+ m_regexpValidator = new QRegularExpressionValidator(regExp, this);+ } else {+ // Fallback: allow digits only if the regular expression is invalid+ m_regexpValidator = new QRegularExpressionValidator(+ QRegularExpression("^\\d{1,4}$"), this);+ }- m_regexpValidator_alt =- new QRegExpValidator(QRegExp("^\\d{1,3}[A-Ia-i]?$"), this);+ // Listen for project changes to update the validator dynamically+ TProjectManager::instance()->addListener(this);+ } else {+ // Digits only (no letter suffix allowed)+ m_regexpValidator =+ new QRegularExpressionValidator(QRegularExpression("^\\d{1,4}$"), this);+ }++ // Alternative validator allowing optional A–I suffix+ m_regexpValidator_alt = new QRegularExpressionValidator(+ QRegularExpression("^\\d{1,3}[A-Ia-i]?$"), this);updateValidator();updateSize();-setValue(fId);}@@ -811,7 +827,7 @@ void FrameNumberLineEdit::setValue(TFrameId fId) {QString str;if (Preferences::instance()->isShowFrameNumberWithLettersEnabled()) {if (!fId.getLetter().isEmpty()) {- // need some warning?+ // Need some warning?}str = convertToFrameWithLetter(fId.getNumber(), 3);} else {@@ -827,7 +843,7 @@ TFrameId FrameNumberLineEdit::getValue() {if (Preferences::instance()->isShowFrameNumberWithLettersEnabled()) {QString str = text();int f;- // if no letters added+ // If no letters addedif (str.at(str.size() - 1).isDigit())f = str.toInt() * 10;else {@@ -837,22 +853,26 @@ TFrameId FrameNumberLineEdit::getValue() {return TFrameId(f);} else {QString regExpStr = QString("^%1$").arg(TFilePath::fidRegExpStr());- QRegExp rx(regExpStr);- int pos = rx.indexIn(text());- if (pos < 0) return TFrameId();- if (rx.cap(2).isEmpty())- return TFrameId(rx.cap(1).toInt());+ QRegularExpression rx(regExpStr);+ QRegularExpressionMatch match = rx.match(text());+ if (!match.hasMatch()) return TFrameId();+ QString cap1 = match.captured(1);+ QString cap2 = match.captured(2);+ if (cap2.isEmpty())+ return TFrameId(cap1.toInt());else- return TFrameId(rx.cap(1).toInt(), rx.cap(2));+ return TFrameId(cap1.toInt(), cap2);}}//-----------------------------------------------------------------------------void FrameNumberLineEdit::onProjectSwitched() {- QRegExpValidator* oldValidator = m_regexpValidator;+ QRegularExpressionValidator* oldValidator = m_regexpValidator;QString regExpStr = QString("^%1$").arg(TFilePath::fidRegExpStr());- m_regexpValidator = new QRegExpValidator(QRegExp(regExpStr), this);+ // Migration to QRegularExpressionValidator+ m_regexpValidator =+ new QRegularExpressionValidator(QRegularExpression(regExpStr), this);updateValidator();if (oldValidator) delete oldValidator;updateSize();@@ -867,7 +887,7 @@ void FrameNumberLineEdit::focusInEvent(QFocusEvent* e) {}void FrameNumberLineEdit::focusOutEvent(QFocusEvent* e) {- // if the field is empty, then revert the last input+ // If the field is empty, then revert the last inputif (text().isEmpty()) setText(m_textOnFocusIn);LineEdit::focusOutEvent(e);@@ -879,11 +899,13 @@ LevelNameLineEdit::LevelNameLineEdit(QWidget* parent): QLineEdit(parent), m_textOnFocusIn("") {// Exclude all character which cannot fit in a filepath (Win).// Dots are also prohibited since they are internally managed by Toonz.- QRegExp rx("[^\\\\/:?*.\"<>|]+");- setValidator(new QRegExpValidator(rx, this));+ // Migration to QRegularExpressionValidator+ QRegularExpression rx("[^\\\\/:?*.\"<>|]+");+ setValidator(new QRegularExpressionValidator(rx, this));setObjectName("LargeSizedText");- connect(this, SIGNAL(editingFinished()), this, SLOT(onEditingFinished()));+ connect(this, &QLineEdit::editingFinished, this,+ &LevelNameLineEdit::onEditingFinished);}void LevelNameLineEdit::focusInEvent(QFocusEvent* e) {@@ -891,7 +913,7 @@ void LevelNameLineEdit::focusInEvent(QFocusEvent* e) {}void LevelNameLineEdit::onEditingFinished() {- // if the content is not changed, do nothing.+ // If the content is not changed, do nothing.if (text() == m_textOnFocusIn) return;emit levelNameEdited();@@ -977,7 +999,7 @@ PencilTestSaveInFolderPopup::PencilTestSaveInFolderPopup(QWidget* parent)m_subFolderCB->setChecked(CamCapSaveInPopupSubFolder != 0);subFolderFrame->setEnabled(CamCapSaveInPopupSubFolder != 0);- // project name+ // Project nameQString prjName = QString::fromStdString(CamCapSaveInPopupProject.getValue());if (prjName.isEmpty()) {prjName = TProjectManager::instance()@@ -1087,33 +1109,42 @@ PencilTestSaveInFolderPopup::PencilTestSaveInFolderPopup(QWidget* parent)resize(300, 440);//---- signal-slot connection- bool ret = true;+ connect(m_subFolderCB, &QCheckBox::clicked, subFolderFrame,+ &QFrame::setEnabled);- ret = ret && connect(m_subFolderCB, SIGNAL(clicked(bool)), subFolderFrame,- SLOT(setEnabled(bool)));- ret = ret && connect(m_projectField, SIGNAL(textEdited(const QString&)), this,- SLOT(updateSubFolderName()));- ret = ret && connect(m_episodeField, SIGNAL(textEdited(const QString&)), this,- SLOT(updateSubFolderName()));- ret = ret && connect(m_sequenceField, SIGNAL(textEdited(const QString&)),- this, SLOT(updateSubFolderName()));- ret = ret && connect(m_sceneField, SIGNAL(textEdited(const QString&)), this,- SLOT(updateSubFolderName()));- ret = ret && connect(m_autoSubNameCB, SIGNAL(clicked(bool)), this,- SLOT(onAutoSubNameCBClicked(bool)));- ret = ret && connect(m_subNameFormatCombo, SIGNAL(currentIndexChanged(int)),- this, SLOT(updateSubFolderName()));-- ret = ret && connect(showPopupOnLaunchCB, SIGNAL(clicked(bool)), this,- SLOT(onShowPopupOnLaunchCBClicked(bool)));- ret = ret && connect(m_createSceneInFolderCB, SIGNAL(clicked(bool)), this,- SLOT(onCreateSceneInFolderCBClicked(bool)));- ret = ret && connect(setAsDefaultBtn, SIGNAL(pressed()), this,- SLOT(onSetAsDefaultBtnPressed()));-- ret = ret && connect(okBtn, SIGNAL(clicked(bool)), this, SLOT(onOkPressed()));- ret = ret && connect(cancelBtn, SIGNAL(clicked(bool)), this, SLOT(reject()));- assert(ret);+ connect(m_projectField, &QLineEdit::textEdited, this,+ &PencilTestSaveInFolderPopup::updateSubFolderName);++ connect(m_episodeField, &QLineEdit::textEdited, this,+ &PencilTestSaveInFolderPopup::updateSubFolderName);++ connect(m_sequenceField, &QLineEdit::textEdited, this,+ &PencilTestSaveInFolderPopup::updateSubFolderName);++ connect(m_sceneField, &QLineEdit::textEdited, this,+ &PencilTestSaveInFolderPopup::updateSubFolderName);++ connect(m_autoSubNameCB, &QCheckBox::clicked, this,+ &PencilTestSaveInFolderPopup::onAutoSubNameCBClicked);++ connect(m_subNameFormatCombo,+ QOverload<int>::of(&QComboBox::currentIndexChanged), this,+ &PencilTestSaveInFolderPopup::updateSubFolderName);++ connect(showPopupOnLaunchCB, &QCheckBox::clicked, this,+ &PencilTestSaveInFolderPopup::onShowPopupOnLaunchCBClicked);++ connect(m_createSceneInFolderCB, &QCheckBox::clicked, this,+ &PencilTestSaveInFolderPopup::onCreateSceneInFolderCBClicked);++ connect(setAsDefaultBtn, &QPushButton::pressed, this,+ &PencilTestSaveInFolderPopup::onSetAsDefaultBtnPressed);++ connect(okBtn, &QPushButton::clicked, this,+ &PencilTestSaveInFolderPopup::onOkPressed);++ connect(cancelBtn, &QPushButton::clicked, this,+ &PencilTestSaveInFolderPopup::reject);updateSubFolderName();}@@ -1123,7 +1154,7 @@ PencilTestSaveInFolderPopup::PencilTestSaveInFolderPopup(QWidget* parent)QString PencilTestSaveInFolderPopup::getPath() {if (!m_subFolderCB->isChecked()) return m_parentFolderField->getPath();- // re-code filepath+ // Re-code filepathTFilePath path(m_parentFolderField->getPath() + "\\" +m_subFolderNameField->text());ToonzScene* scene = TApp::instance()->getCurrentScene()->getScene();@@ -1155,14 +1186,17 @@ QString formatString(QString inStr, int charNum) {if (inStr.isEmpty()) return QString("0").rightJustified(charNum, '0');QString numStr, postStr;- // find the first non-digit character- int index = inStr.indexOf(QRegExp("[^0-9]"), 0);+ // Find the first non-digit character+ // Migration to QRegularExpression+ QRegularExpression nonDigitRegex("[^0-9]");+ QRegularExpressionMatch match = nonDigitRegex.match(inStr);+ int index = match.hasMatch() ? match.capturedStart() : -1;- if (index == -1) // only digits+ if (index == -1) // Only digitsnumStr = inStr;- else if (index == 0) // only post strings+ else if (index == 0) // Only post stringsreturn inStr;- else { // contains both+ else { // Contains bothnumStr = inStr.left(index);postStr = inStr.right(inStr.length() - index);}@@ -1235,15 +1269,17 @@ void PencilTestSaveInFolderPopup::onOkPressed() {return;}- // check the subFolder value+ // Check the subFolder valueQString subFolderName = m_subFolderNameField->text();if (subFolderName.isEmpty()) {DVGui::MsgBox(WARNING, tr("Subfolder name should not be empty."));return;}- int index = subFolderName.indexOf(QRegExp("[\\]:;|=,\\[\\*\\.\"/\\\\]"), 0);- if (index >= 0) {+ // Migration to QRegularExpression+ QRegularExpression invalidCharsRegex("[\\]:;|=,\\[\\*\\.\"/\\\\]");+ QRegularExpressionMatch match = invalidCharsRegex.match(subFolderName);+ if (match.hasMatch()) {DVGui::MsgBox(WARNING, tr("Subfolder name should not contain following ""characters: * . \" / \\ [ ] : ; | = , "));return;@@ -1260,7 +1296,7 @@ void PencilTestSaveInFolderPopup::onOkPressed() {return;}- // save the current properties to env data+ // Save the current properties to env dataCamCapSaveInPopupSubFolder = (m_subFolderCB->isChecked()) ? 1 : 0;CamCapSaveInPopupProject = m_projectField->text().toStdString();CamCapSaveInPopupEpisode = m_episodeField->text().toStdString();@@ -1270,7 +1306,7 @@ void PencilTestSaveInFolderPopup::onOkPressed() {? 0: m_subNameFormatCombo->currentIndex() + 1;- // create folder+ // Create foldertry {TSystem::mkDir(actualFp);} catch (...) {@@ -1286,21 +1322,21 @@ void PencilTestSaveInFolderPopup::onOkPressed() {//-----------------------------------------------------------------------------void PencilTestSaveInFolderPopup::createSceneInFolder() {- // make sure that the check box is displayed (= the scene is untitled) and is+ // Make sure that the check box is displayed (= the scene is untitled) and is// checked.if (m_createSceneInFolderCB->isHidden() ||!m_createSceneInFolderCB->isChecked())return;- // just in case+ // Just in caseif (!m_subFolderCB->isChecked()) return;- // set the output folder+ // Set the output folderToonzScene* scene = TApp::instance()->getCurrentScene()->getScene();if (!scene) return;TFilePath fp(getPath().toStdWString());- // for the scene folder mode, output destination must be already set to+ // For the scene folder mode, output destination must be already set to// $scenefolder or its subfolder. See TSceneProperties::onInitialize()if (Preferences::instance()->getPathAliasPriority() !=Preferences::SceneFolderAlias) {@@ -1308,7 +1344,7 @@ void PencilTestSaveInFolderPopup::createSceneInFolder() {prop->setPath(prop->getPath().withParentDir(fp));}- // save the scene+ // Save the sceneTFilePath sceneFp =scene->decodeFilePath(fp) +TFilePath(m_subFolderNameField->text().toStdWString()).withType("tnz");@@ -1323,9 +1359,9 @@ void PencilTestSaveInFolderPopup::updateParentFolder() {QString parentFolder =scene->getProperties()->cameraCaptureSaveInPath().getQString();if (parentFolder.isEmpty()) {- // else then, if the user-env stores the parent folder value, use it+ // Else then, if the user-env stores the parent folder value, use itparentFolder = QString::fromStdString(CamCapSaveInParentFolder);- // else, use "+extras" project folder+ // Else, use "+extras" project folderif (parentFolder.isEmpty())parentFolder =QString("+%1").arg(QString::fromStdString(TProject::Extras));@@ -1338,7 +1374,6 @@ void PencilTestSaveInFolderPopup::updateParentFolder() {namespace {bool strToSubCamera(const QString& str, QRect& subCamera, double& dpi) {-QStringList values = str.split(',', Qt::SkipEmptyParts);if (values.count() != 4 && values.count() != 5) return false;@@ -1366,7 +1401,7 @@ SubCameraButton::SubCameraButton(const QString& text, QWidget* parent)setIcon(createQIcon("subcamera"));setCheckable(true);- // load preference file+ // Load preference fileTFilePath layoutDir = ToonzFolder::getMyModuleDir();TFilePath prefPath = layoutDir + TFilePath("camera_capture_subcamera.ini");// In case the personal settings is not exist (for new users)@@ -1382,9 +1417,9 @@ SubCameraButton::SubCameraButton(const QString& text, QWidget* parent)}void SubCameraButton::contextMenuEvent(QContextMenuEvent* event) {- // return if the current camera is not valid+ // Return if the current camera is not validif (!m_curResolution.isValid()) return;- // load presets for the current resolution+ // Load presets for the current resolutionQString groupName = QString("%1x%2").arg(m_curResolution.width()).arg(m_curResolution.height());@@ -1418,25 +1453,28 @@ void SubCameraButton::contextMenuEvent(QContextMenuEvent* event) {.arg(rect.y());if (dpi > 0.) toolTip += QString(", %1DPI").arg(dpi);scAct->setToolTip(toolTip);- connect(scAct, SIGNAL(triggered()), this, SLOT(onSubCameraAct()));+ connect(scAct, &QAction::triggered, this,+ &SubCameraButton::onSubCameraAct);}}if (hasPresets) menu.addSeparator();- // save preset (visible if the subcamera is active)+ // Save preset (visible if the subcamera is active)if (m_curSubCamera.isValid()) {QAction* saveAct = menu.addAction(tr("Save Current Subcamera"));- connect(saveAct, SIGNAL(triggered()), this, SLOT(onSaveSubCamera()));+ connect(saveAct, &QAction::triggered, this,+ &SubCameraButton::onSaveSubCamera);}- // delete preset (visible if there is any)+ // Delete preset (visible if there is any)if (hasPresets) {QMenu* delMenu = menu.addMenu(tr("Delete Preset"));for (auto key : m_settings->childKeys()) {QAction* delAct = delMenu->addAction(tr("Delete %1").arg(key));delAct->setData(key);- connect(delAct, SIGNAL(triggered()), this, SLOT(onDeletePreset()));+ connect(delAct, &QAction::triggered, this,+ &SubCameraButton::onDeletePreset);}}@@ -1474,7 +1512,7 @@ void SubCameraButton::onSaveSubCamera() {static QLineEdit* lineEdit = nullptr;if (!nameDialog) nameDialog = initDialog(&lineEdit);- // ask name+ // Ask nameQString oldName;QString groupName = QString("%1x%2").arg(m_curResolution.width())@@ -1503,7 +1541,7 @@ void SubCameraButton::onSaveSubCamera() {return;}- // ask if there are the same name / data in the existing entries+ // Ask if there are the same name / data in the existing entriesif (m_settings->contains(newName) || !oldName.isEmpty()) {QString txt =tr("Overwriting the existing subcamera preset. Are you sure?");@@ -1512,7 +1550,7 @@ void SubCameraButton::onSaveSubCamera() {if (!oldName.isEmpty()) m_settings->remove(oldName);}- // register+ // Registerm_settings->setValue(newName, subCameraToStr(m_curSubCamera, m_currentDpi));m_settings->endGroup();}@@ -1541,7 +1579,7 @@ void SubCameraButton::onDeletePreset() {//=============================================================================PencilTestPopup::PencilTestPopup()- // set the parent 0 in order to enable the popup behind the main window+ // Set the parent 0 in order to enable the popup behind the main window: Dialog(0, false, false, "PencilTest"), m_currentCamera(NULL), m_captureWhiteBGCue(false)@@ -1554,7 +1592,7 @@ PencilTestPopup::PencilTestPopup(), m_customDpi(CamCapCustomDpi) {setWindowTitle(tr("Camera Capture"));- // add maximize button to the dialog+ // Add maximize button to the dialogsetWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint);layout()->setSizeConstraint(QLayout::SetNoConstraint);@@ -1569,7 +1607,7 @@ PencilTestPopup::PencilTestPopup()QGroupBox* fileFrame = new QGroupBox(tr("File"), this);m_levelNameEdit = new LevelNameLineEdit(this);- // set the start frame 10 if the option in preferences+ // Set the start frame 10 if the option in preferences// "Show ABC Appendix to the Frame Number in Xsheet Cell" is active.// (frame 10 is displayed as "1" with this option)int startFrame =@@ -1618,7 +1656,7 @@ PencilTestPopup::PencilTestPopup()QPushButton* subfolderButton = new QPushButton(tr("Subfolder"), this);- // subcamera+ // Subcameram_subcameraButton = new SubCameraButton(tr("Subcamera"), this);m_subWidthFld = new IntLineEdit(this);m_subHeightFld = new IntLineEdit(this);@@ -1635,12 +1673,13 @@ PencilTestPopup::PencilTestPopup()m_calibration.exportBtn = new QPushButton(tr("Export"), this);m_calibration.label = new QLabel(this);- // dpi settings+ // DPI settingsm_dpiBtn = new QPushButton(tr("DPI:Auto"), this);m_dpiMenuWidget = createDpiMenuWidget();//----- m_resolutionCombo->setMaximumWidth(fontMetrics().horizontalAdvance("0000 x 0000") + 25);+ m_resolutionCombo->setMaximumWidth(+ fontMetrics().horizontalAdvance("0000 x 0000") + 25);m_fileTypeCombo->addItems({"jpg", "png", "tga", "tif"});m_fileTypeCombo->setCurrentText(QString::fromStdString(CamCapFileType));@@ -1940,116 +1979,144 @@ PencilTestPopup::PencilTestPopup()}//---- signal-slot connections ----- bool ret = true;- ret = ret && connect(refreshCamListButton, SIGNAL(pressed()), this,- SLOT(refreshCameraList()));- ret = ret && connect(m_cameraListCombo, SIGNAL(activated(int)), this,- SLOT(onCameraListComboActivated(int)));- ret = ret && connect(m_resolutionCombo, SIGNAL(activated(int)), this,- SLOT(onResolutionComboActivated()));- ret = ret && connect(m_fileFormatOptionButton, SIGNAL(pressed()), this,- SLOT(onFileFormatOptionButtonPressed()));- ret = ret && connect(m_levelNameEdit, SIGNAL(levelNameEdited()), this,- SLOT(onLevelNameEdited()));- ret = ret &&- connect(nextLevelButton, SIGNAL(pressed()), this, SLOT(onNextName()));- ret = ret && connect(m_previousLevelButton, SIGNAL(pressed()), this,- SLOT(onPreviousName()));- ret = ret && connect(m_colorTypeCombo, SIGNAL(currentIndexChanged(int)), this,- SLOT(onColorTypeComboChanged(int)));- ret = ret && connect(m_saveImgAdjustDefaultButton, SIGNAL(pressed()), this,- SLOT(saveImageAdjustDefault()));- ret = ret && connect(m_captureWhiteBGButton, SIGNAL(pressed()), this,- SLOT(onCaptureWhiteBGButtonPressed()));- ret = ret && connect(m_onionSkinGBox, SIGNAL(toggled(bool)), this,- SLOT(onOnionCBToggled(bool)));- ret = ret && connect(m_loadImageButton, SIGNAL(pressed()), this,- SLOT(onLoadImageButtonPressed()));- ret = ret && connect(m_onionOpacityFld, SIGNAL(valueEditedByHand()), this,- SLOT(onOnionOpacityFldEdited()));- ret = ret && connect(m_upsideDownCB, SIGNAL(toggled(bool)), m_videoWidget,- SLOT(onUpsideDownChecked(bool)));- ret = ret && connect(m_timerGBox, SIGNAL(toggled(bool)), this,- SLOT(onTimerCBToggled(bool)));- ret = ret && connect(m_captureTimer, SIGNAL(timeout()), this,- SLOT(onCaptureTimerTimeout()));- ret = ret &&- connect(m_countdownTimer, SIGNAL(timeout()), this, SLOT(onCountDown()));-- ret = ret && connect(closeButton, SIGNAL(clicked()), this, SLOT(reject()));- ret = ret && connect(m_captureButton, SIGNAL(clicked(bool)), this,- SLOT(onCaptureButtonClicked(bool)));- ret = ret && connect(subfolderButton, SIGNAL(clicked(bool)), this,- SLOT(openSaveInFolderPopup()));- ret = ret && connect(m_saveInFileFld, SIGNAL(pathChanged()), this,- SLOT(onSaveInPathEdited()));- ret = ret &&- connect(m_fileTypeCombo, QOverload<int>::of(&QComboBox::activated),- [&](int index) {- CamCapFileType = m_fileTypeCombo->currentText().toStdString();- refreshFrameInfo();- });- ret = ret && connect(m_frameNumberEdit, SIGNAL(editingFinished()), this,- SLOT(refreshFrameInfo()));-- // sub camera- ret = ret && connect(m_subcameraButton, SIGNAL(toggled(bool)), this,- SLOT(onSubCameraToggled(bool)));- ret = ret && connect(m_subcameraButton, SIGNAL(toggled(bool)), subCamWidget,- SLOT(setVisible(bool)));- ret =- ret &&- connect(m_subcameraButton,- SIGNAL(subCameraPresetSelected(const QRect&, const double)), this,- SLOT(onSubCameraPresetSelected(const QRect&, const double)));- ret = ret && connect(m_subWidthFld, SIGNAL(editingFinished()), this,- SLOT(onSubCameraRectEdited()));- ret = ret && connect(m_subHeightFld, SIGNAL(editingFinished()), this,- SLOT(onSubCameraRectEdited()));- ret = ret && connect(m_subXPosFld, SIGNAL(editingFinished()), this,- SLOT(onSubCameraRectEdited()));- ret = ret && connect(m_subYPosFld, SIGNAL(editingFinished()), this,- SLOT(onSubCameraRectEdited()));- ret = ret && connect(m_videoWidget, SIGNAL(subCameraChanged(bool)), this,- SLOT(onSubCameraChanged(bool)));-- ret = ret && connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimeout()));- // Calibration- ret = ret &&- connect(m_calibration.groupBox, &QGroupBox::toggled, [&](bool checked) {- CamCapDoCalibration = checked;- resetCalibSettingsFromFile();- });- // ret = ret && connect(m_calibration.groupBox, SIGNAL(toggled(bool)), this,- // SLOT(resetCalibSettingsFromFile()));- ret = ret && connect(m_calibration.capBtn, SIGNAL(clicked()), this,- SLOT(onCalibCapBtnClicked()));- ret = ret && connect(m_calibration.newBtn, SIGNAL(clicked()), this,- SLOT(onCalibNewBtnClicked()));- ret = ret && connect(m_calibration.cancelBtn, SIGNAL(clicked()), this,- SLOT(resetCalibSettingsFromFile()));- ret = ret && connect(m_calibration.loadBtn, SIGNAL(clicked()), this,- SLOT(onCalibLoadBtnClicked()));- ret = ret && connect(m_calibration.exportBtn, SIGNAL(clicked()), this,- SLOT(onCalibExportBtnClicked()));- ret = ret && connect(calibrationHelp, SIGNAL(triggered()), this,- SLOT(onCalibReadme()));-- ret =- ret && connect(m_dpiBtn, &QPushButton::clicked, [&](bool) {- m_dpiMenuWidget->move(m_dpiBtn->mapToGlobal(m_dpiBtn->rect().center()));- m_dpiMenuWidget->show();- m_dpiMenuWidget->updateGeometry();- });+ connect(refreshCamListButton, &QPushButton::pressed, this,+ &PencilTestPopup::refreshCameraList);- assert(ret);+ connect(m_cameraListCombo, QOverload<int>::of(&QComboBox::activated), this,+ &PencilTestPopup::onCameraListComboActivated);++ connect(m_resolutionCombo, QOverload<int>::of(&QComboBox::activated), this,+ &PencilTestPopup::onResolutionComboActivated);++ connect(m_fileFormatOptionButton, &QPushButton::pressed, this,+ &PencilTestPopup::onFileFormatOptionButtonPressed);++ connect(m_levelNameEdit, &LevelNameLineEdit::levelNameEdited, this,+ &PencilTestPopup::onLevelNameEdited);++ connect(nextLevelButton, &QToolButton::pressed, this,+ &PencilTestPopup::onNextName);++ connect(m_previousLevelButton, &QToolButton::pressed, this,+ &PencilTestPopup::onPreviousName);++ connect(m_colorTypeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &PencilTestPopup::onColorTypeComboChanged);++ connect(m_saveImgAdjustDefaultButton, &QPushButton::pressed, this,+ &PencilTestPopup::saveImageAdjustDefault);++ connect(m_captureWhiteBGButton, &QPushButton::pressed, this,+ &PencilTestPopup::onCaptureWhiteBGButtonPressed);++ connect(m_onionSkinGBox, &QGroupBox::toggled, this,+ &PencilTestPopup::onOnionCBToggled);++ connect(m_loadImageButton, &QPushButton::pressed, this,+ &PencilTestPopup::onLoadImageButtonPressed);++ connect(m_onionOpacityFld, &DVGui::IntField::valueEditedByHand, this,+ &PencilTestPopup::onOnionOpacityFldEdited);++ connect(m_upsideDownCB, &QCheckBox::toggled, m_videoWidget,+ &MyVideoWidget::onUpsideDownChecked);++ connect(m_timerGBox, &QGroupBox::toggled, this,+ &PencilTestPopup::onTimerCBToggled);++ connect(m_captureTimer, &QTimer::timeout, this,+ &PencilTestPopup::onCaptureTimerTimeout);++ connect(m_countdownTimer, &QTimer::timeout, this,+ &PencilTestPopup::onCountDown);++ connect(closeButton, &QPushButton::clicked, this, &PencilTestPopup::reject);++ connect(m_captureButton, &QPushButton::clicked, this,+ &PencilTestPopup::onCaptureButtonClicked);++ connect(subfolderButton, &QPushButton::clicked, this,+ &PencilTestPopup::openSaveInFolderPopup);++ connect(m_saveInFileFld, &DVGui::FileField::pathChanged, this,+ &PencilTestPopup::onSaveInPathEdited);++ // File type changed (usando lambda porque atualiza variável global + chama+ // função)+ connect(m_fileTypeCombo, QOverload<int>::of(&QComboBox::activated), this,+ [this](int) {+ CamCapFileType = m_fileTypeCombo->currentText().toStdString();+ refreshFrameInfo();+ });++ connect(m_frameNumberEdit, &QLineEdit::editingFinished, this,+ &PencilTestPopup::refreshFrameInfo);++ // Subcamera+ connect(m_subcameraButton, &QPushButton::toggled, this,+ &PencilTestPopup::onSubCameraToggled);++ connect(m_subcameraButton, &QPushButton::toggled, subCamWidget,+ &QWidget::setVisible);++ connect(m_subcameraButton, &SubCameraButton::subCameraPresetSelected, this,+ &PencilTestPopup::onSubCameraPresetSelected);++ connect(m_subWidthFld, &DVGui::IntLineEdit::editingFinished, this,+ &PencilTestPopup::onSubCameraRectEdited);++ connect(m_subHeightFld, &DVGui::IntLineEdit::editingFinished, this,+ &PencilTestPopup::onSubCameraRectEdited);++ connect(m_subXPosFld, &DVGui::IntLineEdit::editingFinished, this,+ &PencilTestPopup::onSubCameraRectEdited);++ connect(m_subYPosFld, &DVGui::IntLineEdit::editingFinished, this,+ &PencilTestPopup::onSubCameraRectEdited);++ connect(m_videoWidget, &MyVideoWidget::subCameraChanged, this,+ &PencilTestPopup::onSubCameraChanged);++ connect(m_timer, &QTimer::timeout, this, &PencilTestPopup::onTimeout);++ // Calibration group box (lambda porque altera variável global + chama função)+ connect(m_calibration.groupBox, &QGroupBox::toggled, this,+ [this](bool checked) {+ CamCapDoCalibration = checked;+ resetCalibSettingsFromFile();+ });++ connect(m_calibration.capBtn, &QPushButton::clicked, this,+ &PencilTestPopup::onCalibCapBtnClicked);++ connect(m_calibration.newBtn, &QPushButton::clicked, this,+ &PencilTestPopup::onCalibNewBtnClicked);++ connect(m_calibration.cancelBtn, &QPushButton::clicked, this,+ &PencilTestPopup::resetCalibSettingsFromFile);++ connect(m_calibration.loadBtn, &QPushButton::clicked, this,+ &PencilTestPopup::onCalibLoadBtnClicked);++ connect(m_calibration.exportBtn, &QPushButton::clicked, this,+ &PencilTestPopup::onCalibExportBtnClicked);++ connect(calibrationHelp, &QAction::triggered, this,+ &PencilTestPopup::onCalibReadme);++ // DPI button menu+ connect(m_dpiBtn, &QPushButton::clicked, this, [this](bool) {+ m_dpiMenuWidget->move(m_dpiBtn->mapToGlobal(m_dpiBtn->rect().center()));+ m_dpiMenuWidget->show();+ m_dpiMenuWidget->updateGeometry();+ });refreshCameraList();int startupCamIndex = m_cameraListCombo->findText(QString::fromStdString(CamCapCameraName.getValue()));- // if previous camera is not found, then try to activate the connected default+ // If previous camera is not found, then try to activate the connected default// cameraif (startupCamIndex <= 0 && !QCameraInfo::defaultCamera().isNull()) {startupCamIndex =@@ -2059,7 +2126,7 @@ PencilTestPopup::PencilTestPopup()m_cameraListCombo->setCurrentIndex(startupCamIndex);onCameraListComboActivated(startupCamIndex);}- // just in case, try to activate any connected camera+ // Just in case, try to activate any connected cameraelse if (m_cameraListCombo->count() >= 2) {m_cameraListCombo->setCurrentIndex(1);onCameraListComboActivated(1);@@ -2072,21 +2139,21 @@ PencilTestPopup::PencilTestPopup()m_resolutionCombo->setCurrentIndex(startupResolutionIndex);onResolutionComboActivated();- // if the saved resolution was reproduced, then reproduce the subcamera+ // If the saved resolution was reproduced, then reproduce the subcameraTRect subCamRect = CamCapSubCameraRect;if (!subCamRect.isEmpty()) {m_subWidthFld->setValue(subCamRect.getLx());m_subHeightFld->setValue(subCamRect.getLy());m_subXPosFld->setValue(subCamRect.x0);m_subYPosFld->setValue(subCamRect.y0);- // need to store the dummy image before starting the camera+ // Need to store the dummy image before starting the cameraQImage dummyImg(m_resolution, QImage::Format_RGB32);dummyImg.fill(Qt::transparent);m_videoWidget->setImage(dummyImg);m_subcameraButton->setChecked(true);}- // try loading the default parameter+ // Try loading the default parameterloadImageAdjustDefault();}}@@ -2104,12 +2171,10 @@ QMenu* PencilTestPopup::createOptionsMenu() {QMenu* menu = new QMenu();bool ret = true;#ifdef _WIN32- QAction* settingsAct =- menu->addAction(tr("Video Capture Filter Settings..."));- ret = ret && connect(settingsAct, SIGNAL(triggered()), this,- SLOT(onCaptureFilterSettingsBtnPressed()));+ auto* settingsAct = menu->addAction(tr("Video Capture Filter Settings..."));+ connect(settingsAct, &QAction::triggered, this,+ &PencilTestPopup::onCaptureFilterSettingsBtnPressed);settingsAct->setIcon(QIcon(":Resources/preferences.svg"));-menu->addSeparator();QAction* useDShowAct = menu->addAction(tr("Use Direct Show Webcam Drivers"));@@ -2126,13 +2191,16 @@ QMenu* PencilTestPopup::createOptionsMenu() {QAction* useMjpgAct = menu->addAction(tr("Use MJPG with Webcam"));useMjpgAct->setCheckable(true);useMjpgAct->setChecked(m_useMjpg);- ret = ret && connect(useMjpgAct, &QAction::toggled, [&](bool checked) {- m_cvWebcam.release();- if (m_timer->isActive()) m_timer->stop();- m_useMjpg = checked;- CamCapUseMjpg = checked;- m_timer->start(40);- });++ connect(useMjpgAct, &QAction::toggled, this, [this](bool checked) {+ m_cvWebcam.release();+ if (m_timer->isActive()) {+ m_timer->stop();+ }+ m_useMjpg = checked;+ CamCapUseMjpg = checked;+ m_timer->start(40);+ });return menu;}@@ -2150,12 +2218,13 @@ void PencilTestPopup::refreshCameraList() {}int maxTextLength = 0;- // add non-connected state as default+ // Add non-connected state as defaultm_cameraListCombo->addItem(tr("- Select camera -"));for (int c = 0; c < cameras.size(); c++) {QString camDesc = cameras.at(c).description();m_cameraListCombo->addItem(camDesc);- maxTextLength = std::max(maxTextLength, fontMetrics().horizontalAdvance(camDesc));+ maxTextLength =+ std::max(maxTextLength, fontMetrics().horizontalAdvance(camDesc));}m_cameraListCombo->setMaximumWidth(maxTextLength + 25);m_cameraListCombo->setEnabled(true);@@ -2171,30 +2240,30 @@ void PencilTestPopup::onCameraListComboActivated(int comboIndex) {m_cvWebcam.release();if (m_timer->isActive()) m_timer->stop();- // if selected the non-connected state, then disconnect the current camera+ // If selected the non-connected state, then disconnect the current cameraif (comboIndex == 0) {m_deviceName = QString();m_videoWidget->setImage(QImage());- // update env+ // Update envCamCapCameraName = "";m_subcameraButton->setEnabled(false);return;}int index = comboIndex - 1;- // in case the camera is not changed (just click the combobox)+ // In case the camera is not changed (just click the combobox)if (cameras.at(index).deviceName() == m_deviceName) return;m_currentCamera = new QCamera(cameras.at(index), this);m_deviceName = cameras.at(index).deviceName();- // loading new camera+ // Loading new cameram_currentCamera->load();- // refresh resolution+ // Refresh resolutionm_resolutionCombo->clear();QList<QSize> sizes = m_currentCamera->supportedViewfinderResolutions();- // simple workaround because Qt fails to auto-detect the camera resolutions+ // Simple workaround because Qt fails to auto-detect the camera resolutions// https://forum.qt.io/topic/68904/how-to-get-the-supported-resolution-of-a-qcamera/5if (sizes.size() == 0) {sizes.push_back(QSize(640, 360));@@ -2219,13 +2288,13 @@ void PencilTestPopup::onCameraListComboActivated(int comboIndex) {QString("%1 x %2").arg(size.width()).arg(size.height()), size);}if (!sizes.isEmpty()) {- // select the largest available resolution+ // Select the largest available resolutionm_resolutionCombo->setCurrentIndex(m_resolutionCombo->count() - 1);}m_videoWidget->setImage(QImage());m_timer->start(40);- // update env+ // Update envCamCapCameraName = m_cameraListCombo->itemText(comboIndex).toStdString();m_subcameraButton->setEnabled(true);}@@ -2246,27 +2315,27 @@ void PencilTestPopup::onResolutionComboActivated() {m_resolution = newResolution;- // reset white bg+ // Reset white bgm_whiteBGImg = cv::Mat();m_bgReductionFld->setDisabled(true);m_videoWidget->setImage(QImage());m_videoWidget->computeTransform(m_resolution);- // update env+ // Update envCamCapCameraResolution = m_resolutionCombo->currentText().toStdString();refreshFrameInfo();- // reset subcamera info- m_subcameraButton->setChecked(false); // this will hide the size fields+ // Reset subcamera info+ m_subcameraButton->setChecked(false); // This will hide the size fieldsm_subcameraButton->setCurResolution(m_resolution);m_subWidthFld->setRange(10, newResolution.width());m_subHeightFld->setRange(10, newResolution.height());- // if there is no existing level or its size is larger than the current camera+ // If there is no existing level or its size is larger than the current cameraif (!m_allowedCameraSize.isValid() ||m_allowedCameraSize.width() > newResolution.width() ||m_allowedCameraSize.height() > newResolution.height()) {- // make the initial subcamera size to be with the same aspect ratio as the+ // Make the initial subcamera size to be with the same aspect ratio as the// current cameraTCamera* camera =TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera();@@ -2330,7 +2399,7 @@ void PencilTestPopup::onPreviousName() {std::wstring levelName;- // if the current level name is non-sequential, then try to switch the last+ // If the current level name is non-sequential, then try to switch the last// sequential level in the scene.if (!nameCreator->setCurrent(m_levelNameEdit->text().toStdWString())) {TLevelSet* levelSet =@@ -2391,7 +2460,7 @@ void PencilTestPopup::updateLevelNameAndFrame(std::wstring levelName) {m_levelNameEdit->setText(QString::fromStdWString(levelName));m_previousLevelButton->setDisabled(levelName == L"A");- // set the start frame 10 if the option in preferences+ // Set the start frame 10 if the option in preferences// "Show ABC Appendix to the Frame Number in Xsheet Cell" is active.// (frame 10 is displayed as "1" with this option)bool withLetter =@@ -2459,7 +2528,7 @@ int PencilTestPopup::translateIndex(int camIndex) {HRESULT hr = S_OK;- // this is important!!+ // This is important!!hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);UINT32 count = 0;@@ -2482,13 +2551,13 @@ int PencilTestPopup::translateIndex(int camIndex) {if (FAILED(hr)) {CLEAN_ATTRIBUTES()}- // Enummerate the video capture devices+ // Enumerate the video capture deviceshr = MFEnumDeviceSources(attributes, &devices, &count);if (FAILED(hr)) {CLEAN_ATTRIBUTES()}- // if there are any available devices+ // If there are any available devicesif (count > 0) {WCHAR* nameString = NULL;// Get the human-friendly name of the device@@ -2505,7 +2574,7 @@ int PencilTestPopup::translateIndex(int camIndex) {CoTaskMemFree(nameString);}- // clean+ // CleanCLEAN_ATTRIBUTES()#endif // WIN32return camIndex;@@ -2523,7 +2592,7 @@ void PencilTestPopup::getWebcamImage() {int camIndex = m_cameraListCombo->currentIndex() - 1;#ifdef WIN32if (!m_useDirectShow) {- // the webcam order obtained from Qt isn't always the same order as+ // The webcam order obtained from Qt isn't always the same order as// the one obtained from OpenCV without DirectShowm_cvWebcam.open(translateIndex(camIndex));} else {@@ -2532,8 +2601,8 @@ void PencilTestPopup::getWebcamImage() {#elsem_cvWebcam.open(translateIndex(camIndex));#endif- // mjpg is used by many webcams- // opencv runs very slow on some webcams without it.+ // Mjpg is used by many webcams+ // OpenCV runs very slow on some webcams without it.if (m_useMjpg) {m_cvWebcam.set(cv::CAP_PROP_FOURCC,cv::VideoWriter::fourcc('m', 'j', 'p', 'g'));@@ -2546,12 +2615,12 @@ void PencilTestPopup::getWebcamImage() {}bool blnFrameReadSuccessfully =- m_cvWebcam.read(imgOriginal); // get next frame+ m_cvWebcam.read(imgOriginal); // Get next frameif (!blnFrameReadSuccessfully ||- imgOriginal.empty()) { // if frame not read successfully+ imgOriginal.empty()) { // If frame not read successfullystd::cout << "error: frame not read from webcam\n";- error = true; // print error message to std out+ error = true; // Print error message to std out}if (!error) {@@ -2564,7 +2633,7 @@ void PencilTestPopup::getWebcamImage() {void PencilTestPopup::onFrameCaptured(cv::Mat& image) {if (!m_videoWidget) return;- // capture the white BG+ // Capture the white BGif (m_captureWhiteBGCue) {;m_whiteBGImg = image.clone();@@ -2572,7 +2641,7 @@ void PencilTestPopup::onFrameCaptured(cv::Mat& image) {m_bgReductionFld->setEnabled(true);}- // capture calibration reference+ // Capture calibration referenceif (m_calibration.captureCue) {m_calibration.captureCue = false;captureCalibrationRefImage(image);@@ -2595,39 +2664,39 @@ void PencilTestPopup::onFrameCaptured(cv::Mat& image) {if (Preferences::instance()->isShowFrameNumberWithLettersEnabled()) {TFrameId fId = m_frameNumberEdit->getValue();int f = fId.getNumber();- if (f % 10 == 0) // next number+ if (f % 10 == 0) // Next numberm_frameNumberEdit->setValue(TFrameId(((int)(f / 10) + 1) * 10));- else // next alphabet+ else // Next alphabetm_frameNumberEdit->setValue(TFrameId(f + 1));} else {TFrameId fId = m_frameNumberEdit->getValue();if (fId.getLetter().isEmpty() || fId.getLetter() == "Z" ||- fId.getLetter() == "z") // next number+ fId.getLetter() == "z") // Next numberm_frameNumberEdit->setValue(TFrameId(fId.getNumber() + 1));- else { // next alphabet+ else { // Next alphabetQByteArray byteArray = fId.getLetter().toUtf8();- // return incrementing the last letter+ // Return incrementing the last letterbyteArray.data()[byteArray.size() - 1]++;m_frameNumberEdit->setValue(TFrameId(fId.getNumber(), QString::fromUtf8(byteArray)));}}- /* notify */+ /* Notify */TApp::instance()->getCurrentScene()->notifySceneChanged();TApp::instance()->getCurrentScene()->notifyCastChange();TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();- // restart interval timer for capturing next frame (it is single shot)+ // Restart interval timer for capturing next frame (it is single shot)if (m_timerGBox->isChecked() && m_captureButton->isChecked()) {m_captureTimer->start(m_timerIntervalFld->getValue() * 1000);- // restart the count down as well (for aligning the timing. It is not+ // Restart the count down as well (for aligning the timing. It is not// single shot)if (m_timerIntervalFld->getValue() != 0) m_countdownTimer->start(100);}}- // if capture was failed, stop interval capturing+ // If capture was failed, stop interval capturingelse if (m_timerGBox->isChecked()) {m_captureButton->setChecked(false);onCaptureButtonClicked(false);@@ -2644,16 +2713,16 @@ void PencilTestPopup::captureCalibrationRefImage(cv::Mat& image) {image, m_calibration.boardSize, corners,cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_FILTER_QUADS);if (found) {- // compute corners in detail+ // Compute corners in detailcv::cornerSubPix(image, corners, cv::Size(11, 11), cv::Size(-1, -1),cv::TermCriteria(cv::TermCriteria::EPS | cv::TermCriteria::MAX_ITER, 30,0.1));- // count up+ // Count upm_calibration.refCaptured++;- // register corners+ // Register cornersm_calibration.image_points.push_back(corners);- // register 3d points in real world space+ // Register 3d points in real world spacestd::vector<cv::Point3f> obj;for (int i = 0;i < m_calibration.boardSize.width * m_calibration.boardSize.height;@@ -2662,13 +2731,13 @@ void PencilTestPopup::captureCalibrationRefImage(cv::Mat& image) {i % m_calibration.boardSize.width, 0.0f));m_calibration.obj_points.push_back(obj);- // needs 10 references+ // Needs 10 referencesif (m_calibration.refCaptured < 10) {- // update label+ // Update labelm_calibration.label->setText(QString("%1/%2").arg(m_calibration.refCaptured).arg(10));} else {- // swap UIs+ // Swap UIsm_calibration.label->hide();m_calibration.capBtn->hide();m_calibration.cancelBtn->hide();@@ -2688,21 +2757,20 @@ void PencilTestPopup::captureCalibrationRefImage(cv::Mat& image) {cv::Mat mapR = cv::Mat::eye(3, 3, CV_64F);cv::Mat new_intrinsic = cv::getOptimalNewCameraMatrix(intrinsic, distCoeffs, image.size(),- 0.0); // setting the last argument to 1.0 will include all source+ 0.0); // Setting the last argument to 1.0 will include all source// pixels in the framecv::initUndistortRectifyMap(intrinsic, distCoeffs, mapR, new_intrinsic,image.size(), CV_32FC1, m_calibration.mapX,m_calibration.mapY);- // save calibration settings+ // Save calibration settingsQString calibFp = getCurrentCalibFilePath();cv::FileStorage fs(calibFp.toStdString(), cv::FileStorage::WRITE);if (!fs.isOpened()) {DVGui::warning(tr("Failed to save calibration settings."));return;}- fs << "identifier"- << "OpenToonzCameraCalibrationSettings";+ fs << "identifier" << "OpenToonzCameraCalibrationSettings";fs << "resolution"<< cv::Size(m_resolution.width(), m_resolution.height());fs << "instrinsic" << intrinsic;@@ -2719,17 +2787,19 @@ void PencilTestPopup::captureCalibrationRefImage(cv::Mat& image) {//-----------------------------------------------------------------------------void PencilTestPopup::showEvent(QShowEvent* event) {- // if there is another action of which "return" key is assigned as short cut+ // If there is another action of which "return" key is assigned as short cut// key,// then release the shortcut key temporary while the popup opensQAction* action = CommandManager::instance()->getActionFromShortcut("Return");if (action) action->setShortcut(QKeySequence(""));TSceneHandle* sceneHandle = TApp::instance()->getCurrentScene();- connect(sceneHandle, SIGNAL(sceneSwitched()), this, SLOT(onSceneSwitched()));- connect(sceneHandle, SIGNAL(castChanged()), this, SLOT(refreshFrameInfo()));- connect(sceneHandle, SIGNAL(preferenceChanged(const QString&)), this,- SLOT(onPreferenceChanged(const QString&)));+ connect(sceneHandle, &TSceneHandle::sceneSwitched, this,+ &PencilTestPopup::onSceneSwitched);+ connect(sceneHandle, &TSceneHandle::castChanged, this,+ &PencilTestPopup::refreshFrameInfo);+ connect(sceneHandle, &TSceneHandle::preferenceChanged, this,+ &PencilTestPopup::onPreferenceChanged);bool tmp_alwaysOverwrite = m_alwaysOverwrite;onSceneSwitched();@@ -2744,11 +2814,11 @@ void PencilTestPopup::showEvent(QShowEvent* event) {//-----------------------------------------------------------------------------void PencilTestPopup::hideEvent(QHideEvent* event) {- // set back the "return" short cut key+ // Set back the "return" short cut keyQAction* action = CommandManager::instance()->getActionFromShortcut("Return");if (action) action->setShortcut(QKeySequence("Return"));- // stop interval timer if it is active+ // Stop interval timer if it is activeif (m_timerGBox->isChecked() && m_captureButton->isChecked()) {m_captureButton->setChecked(false);onCaptureButtonClicked(false);@@ -2760,14 +2830,14 @@ void PencilTestPopup::hideEvent(QHideEvent* event) {Dialog::hideEvent(event);TSceneHandle* sceneHandle = TApp::instance()->getCurrentScene();- disconnect(sceneHandle, SIGNAL(sceneSwitched()), this,- SLOT(refreshFrameInfo()));- disconnect(sceneHandle, SIGNAL(castChanged()), this,- SLOT(refreshFrameInfo()));- disconnect(sceneHandle, SIGNAL(preferenceChanged(const QString&)), this,- SLOT(onPreferenceChanged(const QString&)));-- // save the current subcamera to env+ disconnect(sceneHandle, &TSceneHandle::sceneSwitched, this,+ &PencilTestPopup::refreshFrameInfo);+ disconnect(sceneHandle, &TSceneHandle::castChanged, this,+ &PencilTestPopup::refreshFrameInfo);+ disconnect(sceneHandle, &TSceneHandle::preferenceChanged, this,+ &PencilTestPopup::onPreferenceChanged);++ // Save the current subcamera to envif (m_subcameraButton->isChecked()) {CamCapSubCameraRect = TRect(TPoint(m_subXPosFld->getValue(), m_subYPosFld->getValue()),@@ -2779,10 +2849,10 @@ void PencilTestPopup::hideEvent(QHideEvent* event) {//-----------------------------------------------------------------------------void PencilTestPopup::keyPressEvent(QKeyEvent* event) {- // override return (or enter) key as shortcut key for capturing+ // Override return (or enter) key as shortcut key for capturingint key = event->key();if (key == Qt::Key_Return || key == Qt::Key_Enter) {- // show button-clicking animation followed by calling+ // Show button-clicking animation followed by calling// onCaptureButtonClicked()m_captureButton->animateClick();event->accept();@@ -2810,27 +2880,27 @@ bool PencilTestPopup::event(QEvent* event) {//-----------------------------------------------------------------------------void PencilTestPopup::processImage(cv::Mat& image) {- // perform calibration+ // Perform calibrationif (m_calibration.groupBox->isChecked() && m_calibration.isValid) {cv::remap(image, image, m_calibration.mapX, m_calibration.mapY,cv::INTER_LINEAR);}- // white bg reduction+ // White bg reductionif (!m_whiteBGImg.empty() && m_bgReductionFld->getValue() != 0)bgReduction(image, m_whiteBGImg, m_bgReductionFld->getValue());// void PencilTestPopup::processImage(QImage& image) {if (m_upsideDownCB->isChecked())- cv::flip(image, image, -1); // flip in both directions+ cv::flip(image, image, -1); // Flip in both directions- // obtain histogram AFTER bg reduction+ // Obtain histogram AFTER bg reductionm_camCapLevelControl->updateHistogram(image);- // change channel+ // Change channelif (m_colorTypeCombo->currentIndex() != 0)cv::cvtColor(image, image, cv::COLOR_RGB2GRAY);- // color and grayscale mode+ // Color and grayscale modeif (m_colorTypeCombo->currentIndex() != 2)m_camCapLevelControl->adjustLevel(image);else@@ -2894,7 +2964,7 @@ void PencilTestPopup::onLoadImageButtonPressed() {int totalBytes = m_lx * m_ly * m_bpp;image->getRaster()->yMirror();- // lock raster to get data+ // Lock raster to get dataimage->getRaster()->lock();void* buffin = image->getRaster()->getRawData();assert(buffin);@@ -2937,22 +3007,22 @@ void PencilTestPopup::onCaptureButtonClicked(bool on) {if (m_timerGBox->isChecked()) {m_timerGBox->setDisabled(on);m_timerIntervalFld->setDisabled(on);- // start interval capturing+ // Start interval capturingif (on) {m_captureButton->setText(tr("Stop Capturing\n[Return key]"));m_captureTimer->start(m_timerIntervalFld->getValue() * 1000);if (m_timerIntervalFld->getValue() != 0) m_countdownTimer->start(100);}- // stop interval capturing+ // Stop interval capturingelse {m_captureButton->setText(tr("Start Capturing\n[Return key]"));m_captureTimer->stop();m_countdownTimer->stop();- // hide the count down text+ // Hide the count down textm_videoWidget->showCountDownTime(0);}}- // capture immediately+ // Capture immediatelyelsem_captureCue = true;}@@ -2969,7 +3039,7 @@ void PencilTestPopup::onCountDown() {}//------------------------------------------------------------------------------/*! referenced from LevelCreatePopup::apply()+/*! Referenced from LevelCreatePopup::apply()*/bool PencilTestPopup::importImage(QImage image) {TApp* app = TApp::instance();@@ -2984,7 +3054,7 @@ bool PencilTestPopup::importImage(QImage image) {TFrameId fId = m_frameNumberEdit->getValue();- /* create parent directory if it does not exist */+ /* Create parent directory if it does not exist */TFilePath parentDir =scene->decodeFilePath(TFilePath(m_saveInFileFld->getPath()));if (!TFileStatus(parentDir).doesExist()) {@@ -3015,21 +3085,21 @@ bool PencilTestPopup::importImage(QImage image) {TXshLevel* level = scene->getLevelSet()->getLevel(levelName);enum State { NEWLEVEL = 0, ADDFRAME, OVERWRITE } state;- // retrieve subcamera image+ // Retrieve subcamera imageif (m_subcameraButton->isChecked() &&m_videoWidget->subCameraRect().isValid())image = image.copy(m_videoWidget->subCameraRect());- /* if the level already exists in the scene cast */+ /* If the level already exists in the scene cast */if (level) {- /* if the existing level is not a raster level, then return */+ /* If the existing level is not a raster level, then return */if (level->getType() != OVL_XSHLEVEL) {error(tr("The level name specified is already used: please choose a ""different level name."));return false;}- /* if the existing level does not match file path and pixel size, then+ /* If the existing level does not match file path and pixel size, then* return */sl = level->getSimpleLevel();if (scene->decodeFilePath(sl->getPath()) != actualLevelFp) {@@ -3045,11 +3115,11 @@ bool PencilTestPopup::importImage(QImage image) {return false;}- // if the level already has a frame, use the same zero padding regardless of+ // If the level already has a frame, use the same zero padding regardless of// the frame format settingsl->formatFId(fId, tmplFId);- /* if the level already have the same frame, then ask if overwrite it */+ /* If the level already have the same frame, then ask if overwrite it */TFilePath frameFp(actualLevelFp.withFrame(fId));if (TFileStatus(frameFp).doesExist()) {if (!m_alwaysOverwrite) {@@ -3066,9 +3136,9 @@ bool PencilTestPopup::importImage(QImage image) {} elsestate = ADDFRAME;}- /* if the level does not exist in the scene cast */+ /* If the level does not exist in the scene cast */else {- /* if the file does exist, load it first */+ /* If the file does exist, load it first */if (TSystem::doesExistFileOrLevel(actualLevelFp)) {level = scene->loadLevel(actualLevelFp);if (!level) {@@ -3076,7 +3146,7 @@ bool PencilTestPopup::importImage(QImage image) {return false;}- /* if the loaded level does not match in pixel size, then return */+ /* If the loaded level does not match in pixel size, then return */sl = level->getSimpleLevel();if (!sl || sl->getProperties()->getImageRes() !=TDimension(image.width(), image.height())) {@@ -3084,11 +3154,11 @@ bool PencilTestPopup::importImage(QImage image) {"The captured image size does not match with the existing level."));return false;}- // if the level already has a frame, use the same zero padding regardless+ // If the level already has a frame, use the same zero padding regardless// of the frame format settingsl->formatFId(fId, tmplFId);- /* confirm overwrite */+ /* Confirm overwrite */TFilePath frameFp(actualLevelFp.withFrame(fId));if (TFileStatus(frameFp).doesExist()) {if (!m_alwaysOverwrite) {@@ -3103,7 +3173,7 @@ bool PencilTestPopup::importImage(QImage image) {}}}- /* if the file does not exist, then create a new level */+ /* If the file does not exist, then create a new level */else {TXshLevel* level = scene->createNewLevel(OVL_XSHLEVEL, levelName,TDimension(), 0, levelFp);@@ -3112,15 +3182,15 @@ bool PencilTestPopup::importImage(QImage image) {sl->getProperties()->setDpiPolicy(LevelProperties::DP_CustomDpi);TPointD dpi;- // if the pixel unit is used, always apply the current camera dpi+ // If the pixel unit is used, always apply the current camera dpiif (Preferences::instance()->getPixelsOnly()) {dpi = getCurrentCameraDpi();} else if (m_doAutoDpi) {- // if the subcamera is not active, apply the current camera dpi+ // If the subcamera is not active, apply the current camera dpiif (!m_subcameraButton->isChecked() ||!m_videoWidget->subCameraRect().isValid())dpi = getCurrentCameraDpi();- // if the subcamera is active, compute the dpi so that the image will+ // If the subcamera is active, compute the dpi so that the image will// fit to the camera frameelse {TCamera* camera = TApp::instance()@@ -3132,7 +3202,7 @@ bool PencilTestPopup::importImage(QImage image) {std::min(image.width() / size.lx, image.height() / size.ly);dpi = TPointD(minimumDpi, minimumDpi);}- } else { // apply the custom dpi value+ } else { // Apply the custom dpi valuedpi = TPointD(m_customDpi, m_customDpi);}sl->getProperties()->setDpi(dpi.x);@@ -3146,26 +3216,26 @@ bool PencilTestPopup::importImage(QImage image) {}TPointD levelDpi = sl->getDpi();- /* create the raster */+ /* Create the raster */TRaster32P raster(image.width(), image.height());convertImageToRaster(raster, image.mirrored(true, true));TRasterImageP ri(raster);ri->setDpi(levelDpi.x, levelDpi.y);- /* setting the frame */+ /* Setting the frame */sl->setFrame(fId, ri);- /* set dirty flag */+ /* Set dirty flag */sl->getProperties()->setDirtyFlag(true);if (m_saveOnCaptureCB->isChecked()) sl->save();- /* placement in xsheet */+ /* Placement in xsheet */int row = app->getCurrentFrame()->getFrame();int col = app->getCurrentColumn()->getColumnIndex();- // if the level is newly created or imported, then insert a new column+ // If the level is newly created or imported, then insert a new columnif (state == NEWLEVEL) {if (col < 0 || !xsh->isColumnEmpty(col)) {col += 1;@@ -3178,17 +3248,17 @@ bool PencilTestPopup::importImage(QImage image) {// state == OVERWRITE, ADDFRAME- // if the same cell is already in the column, then just replace the content+ // If the same cell is already in the column, then just replace the content// and do not set a new cellint foundCol, foundRow = -1;- // most possibly, it's in the current column+ // Most possibly, it's in the current columnint rowCheck;if (findCell(xsh, col, TXshCell(sl, fId), rowCheck)) return true;if (rowCheck >= 0) {foundRow = rowCheck;foundCol = col;}- // search entire xsheet+ // Search entire xsheetfor (int c = 0; c < xsh->getColumnCount(); c++) {if (c == col) continue;if (findCell(xsh, c, TXshCell(sl, fId), rowCheck)) return true;@@ -3197,9 +3267,9 @@ bool PencilTestPopup::importImage(QImage image) {foundCol = c;}}- // if there is a column containing the same level+ // If there is a column containing the same levelif (foundRow >= 0) {- // put the cell at the bottom+ // Put the cell at the bottomint tmpRow = foundRow + 1;while (1) {if (xsh->getCell(tmpRow, foundCol).isEmpty()) {@@ -3210,7 +3280,7 @@ bool PencilTestPopup::importImage(QImage image) {tmpRow++;}}- // if the level is registered in the scene, but is not placed in the xsheet,+ // If the level is registered in the scene, but is not placed in the xsheet,// then insert a new columnelse {if (!xsh->isColumnEmpty(col)) {@@ -3287,7 +3357,7 @@ void PencilTestPopup::refreshFrameInfo() {bool letterOptionEnabled =Preferences::instance()->isShowFrameNumberWithLettersEnabled();- // level with the same name+ // Level with the same nameTXshLevel* level_sameName = levelSet->getLevel(levelName);TFrameId tmplFId = currentScene->getProperties()->formatTemplateFIdForInput();@@ -3297,20 +3367,20 @@ void PencilTestPopup::refreshFrameInfo() {m_fileTypeCombo->currentText().toStdWString()).withFrame(tmplFId);- // level with the same path+ // Level with the same pathTXshLevel* level_samePath = levelSet->getLevel(*(currentScene), levelFp);TFilePath actualLevelFp = currentScene->decodeFilePath(levelFp);- // level existence+ // Level existencebool levelExist = TSystem::doesExistFileOrLevel(actualLevelFp);- // frame existence+ // Frame existenceTFilePath frameFp(actualLevelFp.withFrame(fId));bool frameExist = false;if (levelExist) frameExist = TFileStatus(frameFp).doesExist();- // reset acceptable camera size+ // Reset acceptable camera sizem_allowedCameraSize = QSize();// ### CASE 1 ###@@ -3349,7 +3419,7 @@ void PencilTestPopup::refreshFrameInfo() {std::vector<TFrameId> fids;for (int i = 0; it != level_p->end(); ++it, ++i) {fids.push_back(it->first);- // in case fId with different format+ // In case fId with different formatif (!frameExist && fId == it->first) frameExist = true;}@@ -3357,7 +3427,7 @@ void PencilTestPopup::refreshFrameInfo() {tr("The level is not registered in the scene, but exists in the file ""system.");- // check resolution+ // Check resolutionconst TImageInfo* ii;try {ii = lr->getImageInfo(fids[0]);@@ -3367,7 +3437,7 @@ void PencilTestPopup::refreshFrameInfo() {return;}TDimension dim(ii->m_lx, ii->m_ly);- // if the saved images has not the same resolution as the current camera+ // If the saved images has not the same resolution as the current camera// resolutionif (camRes != dim) {tooltipStr += tr("\nWARNING : Image size mismatch. The saved image "@@ -3377,7 +3447,7 @@ void PencilTestPopup::refreshFrameInfo() {labelStr += tr("WARNING");infoType = WARNING;}- // if the resolutions are matched+ // If the resolutions are matchedelse {if (frameCount == 1)tooltipStr += tr("\nFrame %1 exists.")@@ -3385,7 +3455,7 @@ void PencilTestPopup::refreshFrameInfo() {elsetooltipStr += tr("\nFrames %1 exist.").arg(fidsToString(fids, letterOptionEnabled));- // if the frame exists, then it will be overwritten+ // If the frame exists, then it will be overwrittenif (frameExist) {labelStr += tr("OVERWRITE 1 of");infoType = OVERWRITE;@@ -3417,7 +3487,7 @@ void PencilTestPopup::refreshFrameInfo() {std::vector<TFrameId> fids;level_sameName->getFids(fids);- // check resolution+ // Check resolutionTDimension dim;bool ret = getRasterLevelSize(level_sameName, dim);if (!ret) {@@ -3427,7 +3497,7 @@ void PencilTestPopup::refreshFrameInfo() {labelStr += tr("WARNING");infoType = WARNING;}- // if the saved images has not the same resolution as the current camera+ // If the saved images has not the same resolution as the current camera// resolutionelse if (camRes != dim) {tooltipStr += tr("\nWARNING : Image size mismatch. The existing level "@@ -3437,7 +3507,7 @@ void PencilTestPopup::refreshFrameInfo() {labelStr += tr("WARNING");infoType = WARNING;}- // if the resolutions are matched+ // If the resolutions are matchedelse {int frameCount = fids.size();if (fids.size() == 1)@@ -3481,7 +3551,7 @@ void PencilTestPopup::refreshFrameInfo() {\n %2.").arg(QString::fromStdWString(levelName)).arg(toQString(anotherPath));- // check resolution+ // Check resolutionTDimension dim;bool ret = getRasterLevelSize(level_sameName, dim);if (ret && camRes != dim)@@ -3499,7 +3569,7 @@ void PencilTestPopup::refreshFrameInfo() {\n in the scene with the name %2.").arg(toQString(levelFp)).arg(QString::fromStdWString(anotherName));- // check resolution+ // Check resolutionTDimension dim;bool ret = getRasterLevelSize(level_samePath, dim);if (ret && camRes != dim)@@ -3594,7 +3664,7 @@ void PencilTestPopup::onSubCameraPresetSelected(const QRect& subCameraRect,m_subYPosFld->setValue(subCameraRect.y());if (!m_subcameraButton->isChecked())- // calling onSubCameraToggled() accordingly+ // Calling onSubCameraToggled() accordinglym_subcameraButton->setChecked(true);elseonSubCameraToggled(true);@@ -3626,17 +3696,17 @@ void PencilTestPopup::onCalibNewBtnClicked() {DVGui::MsgBox(question, QObject::tr("Restart"), QObject::tr("Cancel"));if (ret == 0 || ret == 2) return;}- // initialize calibration parameter+ // Initialize calibration parameterm_calibration.captureCue = false;m_calibration.refCaptured = 0;m_calibration.obj_points.clear();m_calibration.image_points.clear();m_calibration.isValid = false;- // initialize label+ // Initialize labelm_calibration.label->setText(QString("%1/%2").arg(m_calibration.refCaptured).arg(10));- // swap UIs+ // Swap UIsm_calibration.newBtn->hide();m_calibration.loadBtn->hide();m_calibration.exportBtn->hide();@@ -3649,7 +3719,7 @@ void PencilTestPopup::onCalibNewBtnClicked() {void PencilTestPopup::resetCalibSettingsFromFile() {if (m_calibration.capBtn->isVisible()) {- // swap UIs+ // Swap UIsm_calibration.label->hide();m_calibration.capBtn->hide();m_calibration.cancelBtn->hide();@@ -3760,7 +3830,7 @@ void PencilTestPopup::onCalibLoadBtnClicked() {//-----------------------------------------------------------------------------void PencilTestPopup::onCalibExportBtnClicked() {- // just in case+ // Just in caseif (!m_calibration.isValid) return;if (!QFileInfo(getCurrentCalibFilePath()).exists()) return;@@ -3814,7 +3884,7 @@ QWidget* PencilTestPopup::createDpiMenuWidget() {m_autoDpiRadioBtn = new QRadioButton(tr("Auto"), this);m_customDpiRadioBtn = new QRadioButton(tr("Custom"), this);- // check the opposite option so that the slot will be called when setting the+ // Check the opposite option so that the slot will be called when setting the// initial stateif (m_doAutoDpi)m_customDpiRadioBtn->setChecked(true);@@ -3874,16 +3944,16 @@ QWidget* PencilTestPopup::createDpiMenuWidget() {//-----------------------------------------------------------------------------void PencilTestPopup::onPreferenceChanged(const QString& prefName) {- // react only when the related preference is changed+ // React only when the related preference is changedif (prefName != "pixelsOnly") return;m_dpiBtn->setHidden(Preferences::instance()->getPixelsOnly());}//------------------------------------------------------------------------------// called in ctor+// Called in ctorvoid PencilTestPopup::loadImageAdjustDefault() {- // find the configuration file+ // Find the configuration fileQString settingsPath = getImageAdjustSettingsPath();if (!TFileStatus(TFilePath(settingsPath)).doesExist()) return;@@ -3958,7 +4028,7 @@ void PencilTestPopup::saveImageAdjustDefault() {OpenPopupCommandHandler<PencilTestPopup> openPencilTestPopup(MI_PencilTest);-// specialized in order to call openSaveInFolderPopup()+// Specialized in order to call openSaveInFolderPopup()template <>void OpenPopupCommandHandler<PencilTestPopup>::execute() {if (!m_popup) m_popup = new PencilTestPopup();@@ -3998,4 +4068,4 @@ LoadCalibrationFilePopup::LoadCalibrationFilePopup(QWidget* parent)void LoadCalibrationFilePopup::showEvent(QShowEvent* e) {FileBrowserPopup::showEvent(e);setFolder(ToonzFolder::getLibraryFolder() + "camera calibration");-}\ No newline at end of file+}diff --git a/toonz/sources/toonz/penciltestpopup.h b/toonz/sources/toonz/penciltestpopup.hindex 397cb97a4..ca042a0b2 100644--- a/toonz/sources/toonz/penciltestpopup.h+++ b/toonz/sources/toonz/penciltestpopup.h@@ -15,18 +15,17 @@#include <QRunnable>#include <QLineEdit>#include <QPushButton>+#include <QRegularExpressionValidator>// forward decl.class QCamera;class QCameraImageCapture;-class QComboBox;class QSlider;class QCheckBox;class QVideoFrame;class QTimer;class QIntValidator;-class QRegExpValidator;class QLabel;class QGroupBox;class QRadioButton;@@ -77,7 +76,7 @@ class MyVideoWidget : public QWidget {void drawSubCamera(QPainter&);public:- MyVideoWidget(QWidget* parent = 0);+ MyVideoWidget(QWidget* parent = nullptr);void setImage(const QImage& image) {m_image = image;@@ -106,7 +105,7 @@ protected:void mousePressEvent(QMouseEvent* event) override;void mouseReleaseEvent(QMouseEvent* event) override;-protected slots:+public slots:void onUpsideDownChecked(bool on) { m_upsideDown = on; }signals:@@ -117,23 +116,22 @@ signals://=============================================================================// FrameNumberLineEdit-// a special Line Edit which accepts imputting alphabets if the preference-// option-// "Show ABC Appendix to the Frame Number in Xsheet Cell" is active.+// Special Line Edit which accepts alphabets input if the preference option+// "Show ABC Appendix to the Frame Number in Xsheet Cell" is active//-----------------------------------------------------------------------------class FrameNumberLineEdit : public DVGui::LineEdit,public TProjectManager::Listener {Q_OBJECT- /* having two validators and switch them according to the preferences*/- QRegExpValidator *m_regexpValidator, *m_regexpValidator_alt;++ QRegularExpressionValidator *m_regexpValidator, *m_regexpValidator_alt;void updateValidator();void updateSize();QString m_textOnFocusIn;public:- FrameNumberLineEdit(QWidget* parent = 0, TFrameId fId = TFrameId(1),+ FrameNumberLineEdit(QWidget* parent = nullptr, TFrameId fId = TFrameId(1),bool acceptLetter = true);~FrameNumberLineEdit() {}@@ -148,7 +146,7 @@ public:protected:/*! If focus is lost and current text value is out of range emit signal- \b editingFinished.*/+ * \b editingFinished.*/void focusInEvent(QFocusEvent*) override;void focusOutEvent(QFocusEvent*) override;void showEvent(QShowEvent* event) override { updateValidator(); }@@ -161,7 +159,7 @@ class LevelNameLineEdit : public QLineEdit {QString m_textOnFocusIn;public:- LevelNameLineEdit(QWidget* parent = 0);+ LevelNameLineEdit(QWidget* parent = nullptr);protected:void focusInEvent(QFocusEvent* e);@@ -202,7 +200,7 @@ class PencilTestSaveInFolderPopup : public DVGui::Dialog {void createSceneInFolder();public:- PencilTestSaveInFolderPopup(QWidget* parent = 0);+ PencilTestSaveInFolderPopup(QWidget* parent = nullptr);QString getPath();QString getParentPath();void updateParentFolder();@@ -233,19 +231,21 @@ class SubCameraButton : public QPushButton {double m_currentDpi;public:- SubCameraButton(const QString& text, QWidget* parent = 0);+ SubCameraButton(const QString& text, QWidget* parent = nullptr);void setCurResolution(const QSize& size) { m_curResolution = size; }void setCurSubCamera(const QRect& rect) { m_curSubCamera = rect; }void setCurDpi(const double& dpi) { m_currentDpi = dpi; }protected:void contextMenuEvent(QContextMenuEvent* event) override;+protected slots:void onSubCameraAct();void onSaveSubCamera();void onDeletePreset();+signals:- void subCameraPresetSelected(const QRect&, const double dpi);+ void subCameraPresetSelected(const QRect&, double dpi);};//=============================================================================@@ -329,17 +329,12 @@ class PencilTestPopup : public DVGui::Dialog {QLineEdit* m_customDpiField;void captureCalibrationRefImage(cv::Mat& procImage);-void processImage(cv::Mat& procImage);bool importImage(QImage image);-void setToNextNewLevel();void updateLevelNameAndFrame(std::wstring levelName);-void getWebcamImage();-QMenu* createOptionsMenu();-int translateIndex(int camIndex);void loadImageAdjustDefault();@@ -359,7 +354,6 @@ protected:void showEvent(QShowEvent* event) override;void hideEvent(QHideEvent* event) override;void keyPressEvent(QKeyEvent* event) override;-bool event(QEvent* e) override;protected slots:@@ -379,23 +373,17 @@ protected slots:void onTimerCBToggled(bool);void onCaptureTimerTimeout();void onCountDown();-void onCaptureButtonClicked(bool);void onCaptureFilterSettingsBtnPressed();-void refreshFrameInfo();-void onSaveInPathEdited();void onFileTypeChanged();void onSceneSwitched();-void onSubCameraToggled(bool);void onSubCameraChanged(bool isDragging);void onSubCameraRectEdited();- void onSubCameraPresetSelected(const QRect&, const double);-+ void onSubCameraPresetSelected(const QRect&, double);void onTimeout();-void onCalibCapBtnClicked();void onCalibNewBtnClicked();void resetCalibSettingsFromFile();@@ -403,7 +391,6 @@ protected slots:void onCalibExportBtnClicked();void onCalibReadme();void onPreferenceChanged(const QString&);-void saveImageAdjustDefault();public slots:@@ -432,4 +419,4 @@ protected:void showEvent(QShowEvent*) override;};-#endif+#endif // PENCILTESTPOPUP_Hdiff --git a/toonz/sources/toonz/rendercommand.cpp b/toonz/sources/toonz/rendercommand.cppindex 6d425d4eb..13d901c6a 100644--- a/toonz/sources/toonz/rendercommand.cpp+++ b/toonz/sources/toonz/rendercommand.cpp@@ -53,6 +53,7 @@#include <QObject>#include <QDesktopServices>#include <QUrl>+#include <QRegularExpression> // Added to replace QRegExp//---------------------------------------------------------@@ -131,8 +132,7 @@ public:m_fp.getType() == "gif" || m_fp.getType() == "webm")) {QString name = QString::fromStdString(m_fp.getName());int index;- if ((index = name.indexOf("#RENDERID")) != -1) //! quite ugly I- //! know....+ if ((index = name.indexOf("#RENDERID")) != -1)m_fp = m_fp.withName(name.left(index).toStdWString());if (!TSystem::showDocument(m_fp)) {@@ -153,7 +153,7 @@ public:isPreview ? *scene->getProperties()->getPreviewProperties(): *scene->getProperties()->getOutputProperties();outputSettings.getRange(r0, r1, step);- const TRenderSettings rs = outputSettings.getRenderSettings();+ const TRenderSettings rs = outputSettings.getRenderSettings();if (r0 == 0 && r1 == -1) r0 = 0, r1 = scene->getFrameCount() - 1;double timeStretchFactor =@@ -234,16 +234,16 @@ RenderCommand renderCommand;bool RenderCommand::init(bool isPreview) {ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();TSceneProperties *sprop = scene->getProperties();- /*-- Preview/Renderに応じてそれぞれのSettingを取得 --*/+ /*-- Get settings for Preview/Render respectively --*/TOutputProperties &outputSettings = isPreview ? *sprop->getPreviewProperties(): *sprop->getOutputProperties();outputSettings.getRange(m_r0, m_r1, m_step);- /*-- シーン全体のレンダリングの場合、m_r1をScene長に設定 --*/+ /*-- For whole scene rendering, set m_r1 to scene length --*/if (m_r0 == 0 && m_r1 == -1) {m_r0 = 0;m_r1 = scene->getFrameCount() - 1;}- if (m_r0 < 0) m_r0 = 0;+ if (m_r0 < 0) m_r0 = 0;if (m_r1 >= scene->getFrameCount()) m_r1 = scene->getFrameCount() - 1;if (m_r1 < m_r0) {DVGui::warning(QObject::tr(@@ -267,7 +267,8 @@ sprop->getOutputProperties()->setRenderSettings(rso);*/if (isPreview) {/*--- * PreviewではTimeStretchを考慮しないので、そのままフレーム値を格納してゆく+ * In Preview, time stretch is not considered, so store frame values as they+ * are* --*/m_numFrames = (int)(m_r1 - m_r0 + 1);m_r = m_r0;@@ -289,16 +290,17 @@ sprop->getOutputProperties()->setRenderSettings(rso);*/return false;}- /*-- ファイル名が指定されていない場合は、シーン名を出力ファイル名にする --*/+ /*-- If the filename is not specified, use the scene name as the output+ * filename --*/if (fp.getWideName() == L"")fp = fp.withName(scene->getScenePath().getName());- /*-- ラスタ画像の場合、ファイル名にフレーム番号を追加 --*/+ /*-- For raster images, add frame numbers to the filename --*/if (TFileType::getInfo(fp) == TFileType::RASTER_IMAGE ||fp.getType() == "pct" || fp.getType() == "pic" ||- fp.getType() == "pict") // pct e' un formato"livello" (ha i settings di- // quicktime) ma fatto di diversi frames+ fp.getType() == "pict") // pct is a "level" format (has quicktime+ // settings) but consists of multiple framesfp = fp.withFrame(TFrameId::EMPTY_FRAME);- fp = scene->decodeFilePath(fp);+ fp = scene->decodeFilePath(fp);if (!TFileStatus(fp.getParentDir()).doesExist()) {try {TFilePath parent = fp.getParentDir();@@ -388,8 +390,9 @@ public:bool isPreview): DVGui::ProgressDialog(QObject::tr("Precomputing %1 Frames", "RenderListener").arg(steps) +- ((isPreview) ? "" : QObject::tr(" of %1", "RenderListener")- .arg(toQString(path))),+ ((isPreview) ? ""+ : QObject::tr(" of %1", "RenderListener")+ .arg(toQString(path))),QObject::tr("Cancel"), 0, steps, TApp::instance()->getMainWindow()), m_renderer(renderer), m_frameCounter(0)@@ -412,7 +415,8 @@ public:show();}- /*-- 以下3つの関数はMovieRenderer::Listenerの純粋仮想関数の実装 --*/+ /*-- The following three functions are implementations of pure virtual+ * functions of MovieRenderer::Listener --*/bool onFrameCompleted(int frame) override {bool ret = wasCanceled();if (m_frameCounter + 1 < m_totalFrames)@@ -496,7 +500,7 @@ void RenderCommand::rasterRender(bool isPreview) {: scene->getProperties()->getOutputProperties();// Build thread count- /*-- Dedicated CPUs のコンボボックス (Single, Half, All) --*/+ /*-- Dedicated CPUs combo box (Single, Half, All) --*/int index = prop->getThreadIndex();const int procCount = TSystem::getProcessorCount();@@ -504,7 +508,7 @@ void RenderCommand::rasterRender(bool isPreview) {int threadCount = threadCounts[index];- /*-- MovieRendererを作る。Previewの場合はファイルパスは空 --*/+ /*-- Create MovieRenderer. For Preview, the file path is empty --*/MovieRenderer movieRenderer(scene, isPreview ? TFilePath() : m_fp,threadCount, isPreview);@@ -520,9 +524,9 @@ void RenderCommand::rasterRender(bool isPreview) {// Build- /*-- RenderSettingsをセット --*/+ /*-- Set RenderSettings --*/movieRenderer.setRenderSettings(rs);- /*-- カメラDPIの取得、セット --*/+ /*-- Get and set camera DPI --*/TPointD cameraDpi = isPreview ? scene->getCurrentPreviewCamera()->getDpi(): scene->getCurrentCamera()->getDpi();movieRenderer.setDpi(cameraDpi.x, cameraDpi.y);@@ -532,17 +536,18 @@ void RenderCommand::rasterRender(bool isPreview) {elsemovieRenderer.enablePrecomputing(true);- /*-- プログレス ダイアログの作成 --*/+ /*-- Create progress dialog --*/RenderListener *listener =new RenderListener(movieRenderer.getTRenderer(), m_fp,((m_numFrames - 1) / m_step) + 1, isPreview);- QObject::connect(listener, SIGNAL(canceled()), &movieRenderer,- SLOT(onCanceled()));+ // Use modern syntax for connection+ QObject::connect(listener, &RenderListener::canceled, &movieRenderer,+ &MovieRenderer::onCanceled);movieRenderer.addListener(listener);bool fieldRendering = rs.m_fieldPrevalence != TRenderSettings::NoField;- /*-- buildSceneFxの進行状況を表示するプログレスバー --*/+ /*-- Progress bar showing buildSceneFx progress --*/QProgressBar *buildSceneProgressBar =new QProgressBar(TApp::instance()->getMainWindow());buildSceneProgressBar->setAttribute(Qt::WA_DeleteOnClose);@@ -572,10 +577,10 @@ void RenderCommand::rasterRender(bool isPreview) {scene->shiftCameraX(-rs.m_stereoscopicShift / 2);} elsefx.m_frameB = TRasterFxP();- /*-- movieRendererにフレーム毎のFxを登録 --*/+ /*-- Register Fx for each frame to movieRenderer --*/movieRenderer.addFrame(m_r, fx);}- /*-- プログレスバーを閉じる --*/+ /*-- Close progress bar --*/buildSceneProgressBar->close();// resetViewer(); //TODO cancella le immagini dell'eventuale render precedente@@ -772,8 +777,9 @@ void RenderCommand::multimediaRender() {MultimediaProgressBar *listener =new MultimediaProgressBar(&multimediaRenderer);- QObject::connect(listener, SIGNAL(canceled()), &multimediaRenderer,- SLOT(onCanceled()));+ // Use modern syntax for connection+ QObject::connect(listener, &MultimediaProgressBar::canceled,+ &multimediaRenderer, &MultimediaRenderer::onCanceled);multimediaRenderer.addListener(listener);multimediaRenderer.start();@@ -822,9 +828,8 @@ void RenderCommand::onPreview() { doRender(true); }void RenderCommand::doRender(bool isPreview) {bool isWritable = true;bool isMultiFrame;- /*--- * 初期化処理。フレーム範囲の計算や、Renderの場合はOutputSettingsから保存先パスも作る- * --*/+ /*-- Initialization. Calculate frame range and, for Render, also create output+ * path from OutputSettings --*/if (!init(isPreview)) return;if (m_fp.getDots() == ".") {isMultiFrame = false;@@ -834,13 +839,23 @@ void RenderCommand::doRender(bool isPreview) {isMultiFrame = true;TFilePath dir = m_fp.getParentDir();QDir qDir(QString::fromStdWString(dir.getWideString()));- QString levelName =- QRegExp::escape(QString::fromStdWString(m_fp.getWideName()));+ QString levelName = QString::fromStdWString(m_fp.getWideName());QString levelType = QString::fromStdString(m_fp.getType());- QString exp(levelName + ".[0-9]{1,4}." + levelType);- QRegExp regExp(exp);- QStringList list = qDir.entryList(QDir::Files);- QStringList livelFrames = list.filter(regExp);++ // Replace QRegExp with QRegularExpression+ QString exp = QRegularExpression::escape(levelName) + "\\.[0-9]{1,4}\\." ++ QRegularExpression::escape(levelType);+ QRegularExpression regExp(exp);++ QStringList list = qDir.entryList(QDir::Files);+ QStringList livelFrames;++ // Filter with QRegularExpression+ for (const QString &file : list) {+ if (regExp.match(file).hasMatch()) {+ livelFrames.append(file);+ }+ }int i;for (i = 0; i < livelFrames.size() && isWritable; i++) {@@ -863,15 +878,15 @@ void RenderCommand::doRender(bool isPreview) {TCamera *camera = 0;try {- /*-- Xsheetノードに繋がっている各ラインごとに計算するモード。- MultipleRender で Schematic Flows または Fx Schematic Terminal Nodes- が選択されている場合+ /*-- Mode that calculates for each line connected to the Xsheet node.+ When MultipleRender and Schematic Flows or Fx Schematic Terminal+ Nodes are selected--*/if (m_multimediaRender)multimediaRender();else- /*-- 通常のRendering --*/+ /*-- Normal rendering --*/rasterRender(isPreview);} catch (TException &e) {DVGui::warning(QString::fromStdString(::to_string(e.getMessage())));diff --git a/toonz/sources/toonz/scenebrowser.cpp b/toonz/sources/toonz/scenebrowser.cppindex 79f3796ce..2b7ea951b 100644--- a/toonz/sources/toonz/scenebrowser.cpp+++ b/toonz/sources/toonz/scenebrowser.cpp@@ -59,7 +59,7 @@#include <QDir>#include <QPixmap>#include <QUrl>-#include <QRegExp>+#include <QRegularExpression> // Updated from QRegExp#include <QScrollBar>#include <QMap>#include <QPushButton>@@ -95,8 +95,6 @@ using namespace DVGui;namespace {std::set<SceneBrowser *> activePreproductionBoards;-// std::map<TFilePath, FCData> frameCountMap;-// QMutex frameCountMapMutex;QMutex levelFileMutex;} // namespace@@ -113,15 +111,15 @@ SceneBrowserButtonBar::SceneBrowserButtonBar(DvItemViewer *itemViewer,setToolButtonStyle(Qt::ToolButtonTextBesideIcon);setIconSize(QSize(17, 17));setObjectName("buttonBar");- // buttonBar->setIconSize(QSize(10,10));QIcon newFolderIcon = createQIcon("newfolder");QAction *newScene = new QAction(newFolderIcon, tr("Create new scene"), this);newScene->setIconText(tr("Create scene"));addAction(newScene);- // addSeparator();- connect(newScene, SIGNAL(triggered()), SIGNAL(newScene()));+ // Modern signal/slot connection+ connect(newScene, &QAction::triggered, this,+ &SceneBrowserButtonBar::newScene);}//=============================================================================@@ -130,12 +128,11 @@ SceneBrowserButtonBar::SceneBrowserButtonBar(DvItemViewer *itemViewer,SceneBrowser::SceneBrowser(QWidget *parent, Qt::WindowFlags flags,bool noContextMenu, bool multiSelectionEnabled)- : QFrame(parent), m_folderName(0), m_itemViewer(0) {+ : QFrame(parent), m_folderName(nullptr), m_itemViewer(nullptr) {// style sheetsetObjectName("SceneBrowser");setFrameStyle(QFrame::StyledPanel);- // m_mainSplitter = new QSplitter(this);m_folderTreeView = new DvDirTreeView(this);QFrame *box = new QFrame(this);QLabel *folderLabel = new QLabel(tr("Folder: "), this);@@ -161,7 +158,6 @@ SceneBrowser::SceneBrowser(QWidget *parent, Qt::WindowFlags flags,new DVItemViewPlayDelegate(viewerPanel);viewerPanel->setItemViewPlayDelegate(itemViewPlayDelegate);- // m_mainSplitter->setObjectName("SceneBrowserSplitter");m_folderTreeView->hide();m_folderTreeView->setObjectName("DirTreeView");box->setObjectName("castFrame");@@ -185,7 +181,6 @@ SceneBrowser::SceneBrowser(QWidget *parent, Qt::WindowFlags flags,}mainLayout->addLayout(folderLay, 0);- // m_mainSplitter->addWidget(m_folderTreeView);QVBoxLayout *boxLayout = new QVBoxLayout(box);boxLayout->setContentsMargins(0, 0, 0, 0);boxLayout->setSpacing(0);@@ -193,75 +188,53 @@ SceneBrowser::SceneBrowser(QWidget *parent, Qt::WindowFlags flags,boxLayout->addWidget(titleBar, 0);boxLayout->addWidget(m_itemViewer, 1);}- // m_mainSplitter->addWidget(box);mainLayout->addWidget(box, 1);}setLayout(mainLayout);- // m_mainSplitter->setSizes(QList<int>() << 270 << 500);-- // signal-slot connections- bool ret = connect(m_folderTreeView, SIGNAL(currentNodeChanged()),- itemViewPlayDelegate, SLOT(resetPlayWidget()));- // if the current forder is changed in the folder tree, then update in the- // item view- ret = ret && connect(m_folderTreeView, SIGNAL(currentNodeChanged()), this,- SLOT(onTreeFolderChanged()));-- ret = ret && connect(m_itemViewer, SIGNAL(clickedItem(int)), this,- SLOT(onClickedItem(int)));- ret = ret && connect(m_itemViewer, SIGNAL(doubleClickedItem(int)), this,- SLOT(onDoubleClickedItem(int)));- ret =- ret && connect(m_itemViewer, SIGNAL(selectedItems(const std::set<int> &)),- this, SLOT(onSelectedItems(const std::set<int> &)));- ret = ret && connect(buttonBar, SIGNAL(newScene()), this, SLOT(newScene()));-- ret = ret && connect(&m_frameCountReader, SIGNAL(calculatedFrameCount()),- m_itemViewer->getPanel(), SLOT(update()));+ // Modern Qt5 signal/slot connections+ connect(m_folderTreeView, &DvDirTreeView::currentNodeChanged,+ itemViewPlayDelegate, &DVItemViewPlayDelegate::resetPlayWidget);+ connect(m_folderTreeView, &DvDirTreeView::currentNodeChanged, this,+ &SceneBrowser::onTreeFolderChanged);+ connect(m_itemViewer, &DvItemViewer::clickedItem, this,+ &SceneBrowser::onClickedItem);+ connect(m_itemViewer, &DvItemViewer::doubleClickedItem, this,+ &SceneBrowser::onDoubleClickedItem);+ connect(m_itemViewer, &DvItemViewer::selectedItems, this,+ &SceneBrowser::onSelectedItems);+ connect(buttonBar, &SceneBrowserButtonBar::newScene, this,+ &SceneBrowser::newScene);+ connect(&m_frameCountReader, &FrameCountReader::calculatedFrameCount, this,+ [panel = m_itemViewer->getPanel()]() { panel->update(); });QAction *refresh = CommandManager::instance()->getAction(MI_RefreshTree);- ret = ret && connect(refresh, SIGNAL(triggered()), this, SLOT(refresh()));+ connect(refresh, &QAction::triggered, this, &SceneBrowser::refresh);addAction(refresh);// Version Control instance connection- if (Preferences::instance()->isSVNEnabled())- ret =- ret && connect(VersionControl::instance(),- SIGNAL(commandDone(const QStringList &)), this,- SLOT(onVersionControlCommandDone(const QStringList &)));-- // if the folderName is edited, move the current folder accordingly- ret = ret && connect(m_folderName, SIGNAL(editingFinished()), this,- SLOT(onFolderEdited()));-- // folder history- ret = ret && connect(m_folderTreeView, SIGNAL(currentNodeChanged()), this,- SLOT(storeFolderHistory()));-- // check out the update of the current folder.- // Use MyFileSystemWatcher which is shared by all browsers.- // Adding and removing paths to the watcher is done in DvDirTreeView.- ret = ret && connect(MyFileSystemWatcher::instance(),- SIGNAL(directoryChanged(const QString &)), this,- SLOT(onFileSystemChanged(const QString &)));-- // when the scene switched, update the path of the scene location node- TSceneHandle *sceneHandle = TApp::instance()->getCurrentScene();- // ret = ret && connect(sceneHandle, SIGNAL(sceneSwitched()), this,- // SLOT(onSceneSwitched()));- ret = ret && connect(sceneHandle, SIGNAL(nameSceneChanged()), this,- SLOT(onSceneSwitched()));+ if (Preferences::instance()->isSVNEnabled()) {+ connect(VersionControl::instance(), &VersionControl::commandDone, this,+ &SceneBrowser::onVersionControlCommandDone);+ }++ connect(m_folderName, &QLineEdit::editingFinished, this,+ &SceneBrowser::onFolderEdited);+ connect(m_folderTreeView, &DvDirTreeView::currentNodeChanged, this,+ &SceneBrowser::storeFolderHistory);+ connect(MyFileSystemWatcher::instance(),+ &MyFileSystemWatcher::directoryChanged, this,+ &SceneBrowser::onFileSystemChanged);- // onSceneSwitched();+ TSceneHandle *sceneHandle = TApp::instance()->getCurrentScene();+ connect(sceneHandle, &TSceneHandle::nameSceneChanged, this,+ &SceneBrowser::onSceneSwitched);// store the first item("Root") in the historym_indexHistoryList.append(m_folderTreeView->currentIndex());m_currentPosition = 0;refreshHistoryButtons();-- assert(ret);}//-----------------------------------------------------------------------------@@ -416,9 +389,10 @@ void SceneBrowser::sortByDataModel(DataType dataType, bool isDiscendent) {boost::make_counting_iterator(0),boost::make_counting_iterator(int(m_items.size())));- std::stable_sort(- new2OldIdx.begin(), new2OldIdx.end(),- [this, dataType](int x, int y){ return locals::itemLess(x, y, *this, dataType); });+ std::stable_sort(new2OldIdx.begin(), new2OldIdx.end(),+ [this, dataType](int x, int y) {+ return locals::itemLess(x, y, *this, dataType);+ });// Use the renumbering table to permutate elementsstd::vector<Item>(@@ -436,13 +410,17 @@ void SceneBrowser::sortByDataModel(DataType dataType, bool isDiscendent) {boost::make_counting_iterator(int(m_items.size())));std::sort(old2NewIdx.begin(), old2NewIdx.end(),- [&new2OldIdx](int x, int y){ return locals::indexLess(x, y, new2OldIdx); });+ [&new2OldIdx](int x, int y) {+ return locals::indexLess(x, y, new2OldIdx);+ });std::vector<int> newSelectedIndices;- tcg::substitute(- newSelectedIndices,- tcg::permuted_range(old2NewIdx, fs->getSelectedIndices() |- ba::filtered([&old2NewIdx](int x){ return x < old2NewIdx.size(); })));+ tcg::substitute(newSelectedIndices,+ tcg::permuted_range(+ old2NewIdx, fs->getSelectedIndices() |+ ba::filtered([&old2NewIdx](int x) {+ return x < old2NewIdx.size();+ })));fs->select(!newSelectedIndices.empty() ? &newSelectedIndices.front() : 0,int(newSelectedIndices.size()));@@ -464,11 +442,12 @@ void SceneBrowser::sortByDataModel(DataType dataType, bool isDiscendent) {int iCount = int(m_items.size()), lastIdx = iCount - 1;std::vector<int> newSelectedIndices;- tcg::substitute(- newSelectedIndices,- fs->getSelectedIndices() |- ba::filtered([iCount](int x){ return x < iCount; }) |- ba::transformed([lastIdx](int x){ return locals::complement(x, lastIdx); }));+ tcg::substitute(newSelectedIndices,+ fs->getSelectedIndices() | ba::filtered([iCount](int x) {+ return x < iCount;+ }) | ba::transformed([lastIdx](int x) {+ return locals::complement(x, lastIdx);+ }));fs->select(!newSelectedIndices.empty() ? &newSelectedIndices.front() : 0,int(newSelectedIndices.size()));@@ -503,11 +482,6 @@ void SceneBrowser::removeFilterType(const QString &type) {void SceneBrowser::refreshCurrentFolderItems() {m_items.clear();- // put the parent directory item- // TFilePath parentFp = m_folder.getParentDir();- // if (parentFp != TFilePath("") && parentFp != m_folder)- // m_items.push_back(Item(parentFp, true, false));-// register the file itemsif (m_folder != TFilePath()) {TFilePathSet files;@@ -556,20 +530,19 @@ void SceneBrowser::refreshCurrentFolderItems() {if (levelName.isLevelName()) {Item &levelItem = m_multiFileItemMap[levelName];- // TODO:- // とりあえず残すが、FileInfoの取得に時間がかかるようならオプション化も検討- // 2015/12/28 shun_iwasawaQFileInfo fileInfo(QString::fromStdWString(it->getWideString()));// Get creation time safely across platformsQDateTime creationTime = fileInfo.birthTime();if (!creationTime.isValid())- creationTime = fileInfo.metadataChangeTime(); // or fileInfo.lastModified()+ creationTime = fileInfo.metadataChangeTime();// Update level infos- if (levelItem.m_creationDate.isNull() || creationTime < levelItem.m_creationDate)+ if (levelItem.m_creationDate.isNull() ||+ creationTime < levelItem.m_creationDate)levelItem.m_creationDate = creationTime;- if (levelItem.m_modifiedDate.isNull() || fileInfo.lastModified() > levelItem.m_modifiedDate)+ if (levelItem.m_modifiedDate.isNull() ||+ fileInfo.lastModified() > levelItem.m_modifiedDate)levelItem.m_modifiedDate = fileInfo.lastModified();levelItem.m_fileSize += fileInfo.size();@@ -725,7 +698,7 @@ void SceneBrowser::setHistoryDay(std::string dayDateString) {m_dayDateString = dayDateString;const History::Day *day = History::instance()->getDay(dayDateString);m_items.clear();- if (day == 0) {+ if (day == nullptr) {m_folderName->setText("");} else {m_folderName->setText(QString::fromStdString(dayDateString));@@ -763,9 +736,9 @@ void SceneBrowser::readInfo(Item &item) {// Use birthTime(), fall back to metadataChangeTime() if unavailableitem.m_creationDate = info.birthTime();if (!item.m_creationDate.isValid()) {- item.m_creationDate = info.metadataChangeTime();+ item.m_creationDate = info.metadataChangeTime();}- item.m_modifiedDate = info.lastModified();+ item.m_modifiedDate = info.lastModified();item.m_fileType = info.suffix();item.m_fileSize = info.size();if (fp.getType() == "tnz") {@@ -795,14 +768,6 @@ void SceneBrowser::readInfo(Item &item) {// keep the list of frameIds at the first time and try to reuse it.item.m_frameIds = it->second.m_frameIds;-- // The old way- /*TLevelReaderP lr(fp);-item.m_frameCount = lr->loadInfo()->getFrameCount();-item.m_creationDate = QDateTime();-item.m_modifiedDate = QDateTime();-item.m_fileSize = -1;-item.m_validInfo = true;*/} catch (...) {item.m_frameCount = 0;}@@ -814,8 +779,7 @@ item.m_validInfo = true;*///-----------------------------------------------------------------------------//! Frame count needs a special access function for viewable types - for they-//! are-//! calculated by using a dedicated thread and therefore cannot be simply+//! are calculated by using a dedicated thread and therefore cannot be simply//! classified as *valid* or *invalid* infos...void SceneBrowser::readFrameCount(Item &item) {if (TFileType::isViewable(TFileType::getInfo(item.m_path))) {@@ -914,7 +878,7 @@ bool SceneBrowser::isSceneItem(int index) const {//-----------------------------------------------------------------------------bool SceneBrowser::canRenameItem(int index) const {- // se sto guardando la history non posso rinominare nulla+ // if I'm looking at history, I can't rename anythingif (getFolder() == TFilePath()) return false;if (index < 0 || index >= (int)m_items.size()) return false;// for now, disable rename for folders@@ -944,7 +908,7 @@ void SceneBrowser::renameItem(int index, const QString &newName) {m_items[index].m_name = QString::fromStdWString(newFp.getLevelNameW());m_items[index].m_path = newFp;- // ho rinominato anche la palette devo aggiornarla.+ // if I also renamed the palette, I need to update it.if (newFp.getType() == "tlv" || newFp.getType() == "tzp" ||newFp.getType() == "tzu") {const char *type = (newFp.getType() == "tlv") ? "tpl" : "plt";@@ -959,12 +923,11 @@ void SceneBrowser::renameItem(int index, const QString &newName) {m_itemViewer->update();if (fp.getType() == "tnz") {- // ho cambiato il folder _files. Devo aggiornare il folder che lo contiene- // nel tree view+ // I changed the _files folder. I need to update the containing folder in+ // the tree viewQModelIndex index = m_folderTreeView->currentIndex();if (index.isValid()) {DvDirModel::instance()->refresh(index);- // m_folderTreeView->getDvDirModel()->refresh(index);m_folderTreeView->update();}}@@ -995,7 +958,7 @@ bool SceneBrowser::renameFile(TFilePath &fp, QString newName) {}newFp = newFp.withParentDir(fp.getParentDir());- // se sono uguali non devo rinominare nulla+ // if they are the same, I don't need to rename anythingif (newFp == fp) return false;if (TSystem::doesExistFileOrLevel(newFp)) {@@ -1007,10 +970,6 @@ bool SceneBrowser::renameFile(TFilePath &fp, QString newName) {TSystem::renameFileOrLevel_throw(newFp, fp, true);IconGenerator::instance()->remove(fp);if (fp.getType() == "tnz") {- /* TFilePath folder = fp.getParentDir() + (fp.getName() + "_files");-TFilePath newFolder = newFp.getParentDir() + (newFp.getName() + "_files");-TSystem::renameFile(newFolder, folder);-*/TFilePath sceneIconFp = ToonzScene::getIconPath(fp);TFilePath sceneIconNewFp = ToonzScene::getIconPath(newFp);if (TFileStatus(sceneIconFp).doesExist()) {@@ -1037,12 +996,10 @@ QMenu *SceneBrowser::getContextMenu(QWidget *parent, int index) {return path.getType() == "tzp" || path.getType() == "tzu";};- bool ret = true;-- // TODO: spostare in questa classe anche la definizione delle azioni?+ // TODO: move action definitions to this class as well?FileSelection *fs =dynamic_cast<FileSelection *>(m_itemViewer->getPanel()->getSelection());- if (!fs) return 0;+ if (!fs) return nullptr;std::vector<TFilePath> files;fs->getSelectedFiles(files);@@ -1091,8 +1048,7 @@ QMenu *SceneBrowser::getContextMenu(QWidget *parent, int index) {elsetitle = tr("Load");QAction *action = new QAction(title, menu);- ret = ret &&- connect(action, SIGNAL(triggered()), this, SLOT(loadResources()));+ connect(action, &QAction::triggered, this, &SceneBrowser::loadResources);menu->addAction(action);menu->addSeparator();}@@ -1131,8 +1087,6 @@ QMenu *SceneBrowser::getContextMenu(QWidget *parent, int index) {}if (j == files.size()) {menu->addAction(cm->getAction(MI_ConvertFiles));- // iwsw commented out temporarily- // menu->addAction(cm->getAction(MI_ToonShadedImageToTLV));}if (areFullcolor) menu->addAction(cm->getAction(MI_SeparateColors));@@ -1140,32 +1094,10 @@ QMenu *SceneBrowser::getContextMenu(QWidget *parent, int index) {}if (files.size() == 1 && files[0].getType() != "tnz") {QAction *action = new QAction(tr("Rename"), menu);- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(renameAsToonzLevel()));- menu->addAction(action);- }-#ifdef LEVO-- if (files.size() == 2 &&- (files[0].getType() == "tif" || files[0].getType() == "tiff" ||- files[0].getType() == "png" || files[0].getType() == "TIF" ||- files[0].getType() == "TIFF" || files[0].getType() == "PNG") &&- (files[1].getType() == "tif" || files[1].getType() == "tiff" ||- files[1].getType() == "png" || files[1].getType() == "TIF" ||- files[1].getType() == "TIFF" || files[1].getType() == "PNG")) {- QAction *action = new QAction(tr("Convert to Painted TLV"), menu);- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(convertToPaintedTlv()));- menu->addAction(action);- }- if (areFullcolor) {- QAction *action = new QAction(tr("Convert to Unpainted TLV"), menu);- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(convertToUnpaintedTlv()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::renameAsToonzLevel);menu->addAction(action);- menu->addSeparator();}-#endifif (!clickedFile.isEmpty() && (clickedFile.getType() == "tnz")) {menu->addSeparator();@@ -1193,43 +1125,35 @@ QMenu *SceneBrowser::getContextMenu(QWidget *parent, int index) {(status == DvItemListModel::VC_ToUpdate && files.size() == 1)) {if (status == DvItemListModel::VC_ReadOnly) {action = vcMenu->addAction(tr("Edit"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(editVersionControl()));-- TFilePath path = files.at(0);- std::string fileType = path.getType();- if (fileType == "tlv" || fileType == "pli" || path.getDots() == "..") {- action = vcMenu->addAction(tr("Edit Frame Range..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(editFrameRangeVersionControl()));- }+ connect(action, &QAction::triggered, this,+ &SceneBrowser::editVersionControl);} else {action = vcMenu->addAction(tr("Edit"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(updateAndEditVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::updateAndEditVersionControl);}}if (status == DvItemListModel::VC_Modified) {action = vcMenu->addAction(tr("Put..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(putVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::putVersionControl);action = vcMenu->addAction(tr("Revert"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(revertVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::revertVersionControl);}if (status == DvItemListModel::VC_ReadOnly ||status == DvItemListModel::VC_ToUpdate) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getVersionControl);if (status == DvItemListModel::VC_ReadOnly) {action = vcMenu->addAction(tr("Delete"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(deleteVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::deleteVersionControl);}vcMenu->addSeparator();@@ -1238,99 +1162,99 @@ QMenu *SceneBrowser::getContextMenu(QWidget *parent, int index) {action = vcMenu->addAction(tr("Get Revision..."));TFilePath path = files.at(0);if (path.getDots() == "..")- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getRevisionVersionControl);else- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionHistory()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getRevisionHistory);} else if (files.size() > 1) {action = vcMenu->addAction("Get Revision...");- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getRevisionVersionControl);}}if (status == DvItemListModel::VC_Edited) {action = vcMenu->addAction(tr("Unlock"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(unlockVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::unlockVersionControl);}if (status == DvItemListModel::VC_Unversioned) {action = vcMenu->addAction(tr("Put..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(putVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::putVersionControl);}if (status == DvItemListModel::VC_Locked && files.size() == 1) {action = vcMenu->addAction(tr("Unlock"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(unlockVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::unlockVersionControl);action = vcMenu->addAction(tr("Edit Info"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(showLockInformation()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::showLockInformation);}if (status == DvItemListModel::VC_Missing) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getVersionControl);if (files.size() == 1) {vcMenu->addSeparator();action = vcMenu->addAction(tr("Revision History..."));TFilePath path = files.at(0);if (path.getDots() == "..")- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getRevisionVersionControl);else- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getRevisionHistory()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getRevisionHistory);}}if (status == DvItemListModel::VC_PartialLocked) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getVersionControl);if (files.size() == 1) {action = vcMenu->addAction(tr("Edit Frame Range..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(editFrameRangeVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::editFrameRangeVersionControl);action = vcMenu->addAction(tr("Edit Info"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(showFrameRangeLockInfo()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::showFrameRangeLockInfo);}} else if (status == DvItemListModel::VC_PartialEdited) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getVersionControl);if (files.size() == 1) {action = vcMenu->addAction(tr("Unlock Frame Range"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(unlockFrameRangeVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::unlockFrameRangeVersionControl);action = vcMenu->addAction(tr("Edit Info"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(showFrameRangeLockInfo()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::showFrameRangeLockInfo);}} else if (status == DvItemListModel::VC_PartialModified) {action = vcMenu->addAction(tr("Get"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(getVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::getVersionControl);if (files.size() == 1) {action = vcMenu->addAction(tr("Put..."));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(putFrameRangeVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::putFrameRangeVersionControl);action = vcMenu->addAction(tr("Revert"));- ret = ret && connect(action, SIGNAL(triggered()), this,- SLOT(revertFrameRangeVersionControl()));+ connect(action, &QAction::triggered, this,+ &SceneBrowser::revertFrameRangeVersionControl);}}@@ -1345,8 +1269,6 @@ QMenu *SceneBrowser::getContextMenu(QWidget *parent, int index) {menu->addAction(cm->getAction(MI_RefreshTree));}- assert(ret);-return menu;}@@ -1393,12 +1315,7 @@ bool SceneBrowser::dropMimeData(QTreeWidgetItem *parent, int index,//-----------------------------------------------------------------------------void SceneBrowser::onTreeFolderChanged() {- // Commented by KDDvDirModelNode *node = m_folderTreeView->getCurrentNode();- // if (node)- // node->visualizeContent(this);- // else- // setFolder(TFilePath());m_itemViewer->resetVerticalScrollBar();m_itemViewer->updateContentSize();m_itemViewer->getPanel()->update();@@ -1427,8 +1344,8 @@ void SceneBrowser::onDataChanged(const QModelIndex &topLeft,//-----------------------------------------------------------------------------bool SceneBrowser::acceptDrop(const QMimeData *data) const {- // se il browser non sta visualizzando un folder standard non posso accettare- // nessun drop+ // if the browser is not displaying a standard folder, I cannot accept any+ // dropif (getFolder() == TFilePath()) return false;if (data->hasFormat("application/vnd.toonz.levels") ||@@ -1443,8 +1360,8 @@ bool SceneBrowser::acceptDrop(const QMimeData *data) const {//-----------------------------------------------------------------------------bool SceneBrowser::drop(const QMimeData *mimeData) {- // se il browser non sta visualizzando un folder standard non posso accettare- // nessun drop+ // if the browser is not displaying a standard folder, I cannot accept any+ // dropTFilePath folderPath = getFolder();if (folderPath == TFilePath()) return false;@@ -1740,191 +1657,14 @@ void SceneBrowser::renameAsToonzLevel() {QApplication::restoreOverrideCursor();- FileBrowser::refreshFolder(filePaths[0].getParentDir());-}--#ifdef LEVO--void SceneBrowser::convertToUnpaintedTlv() {- std::vector<TFilePath> filePaths;- FileSelection *fs =- dynamic_cast<FileSelection *>(m_itemViewer->getPanel()->getSelection());- if (!fs) return;- fs->getSelectedFiles(filePaths);-- QStringList sl;- sl << "Apply Autoclose "- << "Don't Apply Autoclose ";- bool ok;- QString autoclose = QInputDialog::getItem(- this, tr("Convert To Unpainted Tlv"), "", sl, 0, false, &ok);- if (!ok) return;-- QApplication::setOverrideCursor(Qt::WaitCursor);-- int i, totFrames = 0;- std::vector<Convert2Tlv *> converters;- for (i = 0; i < filePaths.size(); i++) {- Convert2Tlv *converter =- new Convert2Tlv(filePaths[i], TFilePath(), TFilePath(), -1, -1,- autoclose == sl.at(0), TFilePath(), 0, 0, 0);-- if (TSystem::doesExistFileOrLevel(converter->m_levelOut)) {- QApplication::restoreOverrideCursor();- int ret = DVGui::MsgBox(tr("Warning: level %1 already exists; overwrite?")- .arg(toQString(converter->m_levelOut)),- tr("Yes"), tr("No"), 1);- QApplication::setOverrideCursor(Qt::WaitCursor);- if (ret == 2 || ret == 0) {- delete converter;- continue;- }- TSystem::removeFileOrLevel(converter->m_levelOut);- }-- totFrames += converter->getFramesToConvertCount();- converters.push_back(converter);- }-- if (converters.empty()) {- QApplication::restoreOverrideCursor();- return;- }-- ProgressDialog pb("", "Cancel", 0, totFrames);- int j, l, k = 0;- for (i = 0; i < converters.size(); i++) {- std::string errorMessage;- if (!converters[i]->init(errorMessage)) {- converters[i]->abort();- DVGui::error(QString::fromStdString(errorMessage));- delete converters[i];- converters[i] = 0;- continue;- }-- int count = converters[i]->getFramesToConvertCount();-- pb.setLabelText("Generating level " + toQString(converters[i]->m_levelOut));- pb.show();-- for (j = 0; j < count; j++) {- std::string errorMessage = "";- if (!converters[i]->convertNext(errorMessage) || pb.wasCanceled()) {- for (l = i; l < converters.size(); l++) {- converters[l]->abort();- delete converters[i];- converters[i] = 0;- }- if (errorMessage != "")- DVGui::error(QString::fromStdString(errorMessage));- QApplication::restoreOverrideCursor();- SceneBrowser::refreshFolder(filePaths[0].getParentDir());- return;- }- pb.setValue(++k);- }- TFilePath levelOut(converters[i]->m_levelOut);- delete converters[i];- IconGenerator::instance()->invalidate(levelOut);-- converters[i] = 0;- }-- QApplication::restoreOverrideCursor();- pb.hide();- DVGui::info(tr("Done: All Levels converted to TLV Format"));-- SceneBrowser::refreshFolder(filePaths[0].getParentDir());-}--//-------------------------------------------------------------------------------void SceneBrowser::convertToPaintedTlv() {- std::vector<TFilePath> filePaths;- FileSelection *fs =- dynamic_cast<FileSelection *>(m_itemViewer->getPanel()->getSelection());- if (!fs) return;- fs->getSelectedFiles(filePaths);-- if (filePaths.size() != 2) return;-- QStringList sl;- sl << "Apply Autoclose "- << "Don't Apply Autoclose ";- bool ok;- QString autoclose = QInputDialog::getItem(this, tr("Convert To Painted Tlv"),- "", sl, 0, false, &ok);- if (!ok) return;-- QApplication::setOverrideCursor(Qt::WaitCursor);-- Convert2Tlv *converter =- new Convert2Tlv(filePaths[0], filePaths[1], TFilePath(), -1, -1,- autoclose == sl.at(0), TFilePath(), 0, 0, 0);-- if (TSystem::doesExistFileOrLevel(converter->m_levelOut)) {- QApplication::restoreOverrideCursor();- int ret = DVGui::MsgBox(tr("Warning: level %1 already exists; overwrite?")- .arg(toQString(converter->m_levelOut)),- tr("Yes"), tr("No"), 1);- QApplication::setOverrideCursor(Qt::WaitCursor);- if (ret == 2 || ret == 0) {- QApplication::restoreOverrideCursor();- return;- }- TSystem::removeFileOrLevel(converter->m_levelOut);- }-- std::string errorMessage;- if (!converter->init(errorMessage)) {- converter->abort();- delete converter;- DVGui::error(QString::fromStdString(errorMessage));- QApplication::restoreOverrideCursor();- return;- }- int count = converter->getFramesToConvertCount();-- ProgressDialog pb("Generating level " + toQString(converter->m_levelOut),- "Cancel", 0, count);- pb.show();-- for (int i = 0; i < count; i++) {- errorMessage = "";- if (!converter->convertNext(errorMessage) || pb.wasCanceled()) {- converter->abort();- delete converter;- if (errorMessage != "")- DVGui::error(QString::fromStdString(errorMessage));- QApplication::restoreOverrideCursor();- SceneBrowser::refreshFolder(filePaths[0].getParentDir());- return;- }-- pb.setValue(i + 1);- }-- TFilePath levelOut(converter->m_levelOut);- delete converter;- IconGenerator::instance()->invalidate(levelOut);-- QApplication::restoreOverrideCursor();- pb.hide();- DVGui::info(tr("Done: 2 Levels converted to TLV Format"));-- fs->selectNone();SceneBrowser::refreshFolder(filePaths[0].getParentDir());}-#endif//-----------------------------------------------------------------------------void SceneBrowser::onSceneSwitched() {ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();TFilePath scenesFolder = scene->getScenePath().getParentDir();- // TFilePath scenesFolder =- // TProjectManager::instance()->getCurrentProject()->getScenesPath();setFolder(scenesFolder, true);}@@ -2087,7 +1827,6 @@ void SceneBrowser::newScene() {}}if (number.length() == 0) {- // prefix+="-";number = "000";}int i = number.toInt();@@ -2108,7 +1847,6 @@ void SceneBrowser::newScene() {QString tempName(tr("New Folder"));std::wstring folderName = tempName.toStdWString();TFilePath folderPath = parentFolder + folderName;- // int i = 1;while (TFileStatus(folderPath).doesExist())folderPath = parentFolder + (folderName + L" " + std::to_wstring(++i));@@ -2179,15 +1917,15 @@ void SceneBrowser::selectNone() { m_itemViewer->selectNone(); }//-----------------------------------------------------------------------------void SceneBrowser::enableDoubleClickToOpenScenes() {- // perhaps this should disconnect existing signal handlers first- connect(this, SIGNAL(filePathDoubleClicked(const TFilePath &)), this,- SLOT(tryToOpenScene(const TFilePath &)));+ // Modern Qt5 signal/slot connection+ connect(this, &SceneBrowser::filePathDoubleClicked, this,+ &SceneBrowser::tryToOpenScene);}void SceneBrowser::enableSingleClickToOpenScenes() {- // perhaps this should disconnect existing signal handlers first- connect(this, SIGNAL(filePathClicked(const TFilePath &)), this,- SLOT(tryToOpenScene(const TFilePath &)));+ // Modern Qt5 signal/slot connection+ connect(this, &SceneBrowser::filePathClicked, this,+ &SceneBrowser::tryToOpenScene);}//-----------------------------------------------------------------------------diff --git a/toonz/sources/toonz/scenebrowser.h b/toonz/sources/toonz/scenebrowser.hindex 52702fca4..6613f3628 100644--- a/toonz/sources/toonz/scenebrowser.h+++ b/toonz/sources/toonz/scenebrowser.h@@ -47,7 +47,7 @@ public:bool noContextMenu = false, bool multiSelectionEnabled = false);~SceneBrowser();- void sortByDataModel(DataType dataType, bool isDiscendent) override;+ void sortByDataModel(DataType dataType, bool isDescendant) override;void refreshData() override;int getItemCount() const override;@@ -62,24 +62,24 @@ public:QMenu *getContextMenu(QWidget *parent, int index) override;/*!-This functions adds to the types to be filtered a new type;-if this function is never called, the default filter is all image-files and scene files and palette files-*/+ This function adds a new type to the filter list;+ if this function is never called, the default filter includes all image+ files, scene files, and palette files.+ */void addFilterType(const QString &type);/*!-The setFilterTypes function directly specifies the list of file-types to be displayed in the file browser.-*/+ The setFilterTypes function directly specifies the list of file types+ to be displayed in the file browser.+ */void setFilterTypes(const QStringList &types);const QStringList &getFilterTypes() const { return m_filter; }void removeFilterType(const QString &type);void setFolder(const TFilePath &fp, bool expandNode = false,bool forceUpdate = false);- // process when inputting the folder which is not regitered in the folder tree- // (e.g. UNC path in Windows)+ // Process when inputting a folder that is not registered in the folder tree+ // (e.g., a UNC path in Windows)void setUnregisteredFolder(const TFilePath &fp);void setHistoryDay(std::string dayDateString);@@ -91,8 +91,8 @@ types to be displayed in the file browser.static void updateItemViewerPanel();- // ritorna true se il file e' stato rinominato. dopo la chiamata fp contiene- // il nuovo path+ // Returns true if the file has been renamed. After the call, fp contains+ // the new path.static bool renameFile(TFilePath &fp, QString newName);void makeCurrentProjectVisible();@@ -103,8 +103,8 @@ types to be displayed in the file browser.QSplitter *getMainSplitter() const { return m_mainSplitter; }// Enable double-click to open a scene.- // This is not always desirable (e.g. if a user double-clicks on a file in- // a "Save As" dialog, they expect the file will be saved to, not opened).+ // This is not always desirable (e.g., if a user double-clicks on a file in+ // a "Save As" dialog, they expect the file to be saved, not opened).// So it is disabled by default.void enableDoubleClickToOpenScenes();@@ -125,7 +125,7 @@ protected:// Fill the QStringList with files selected in the browser, auxiliary files// (palette for tlv, hooks, sceneIcons)- // retrieve also the path, and return also the sceneIconsCount+ // Also retrieve the path and return the sceneIconsCount.void setupVersionControlCommand(QStringList &files, QString &path,int &sceneIconsCount);void setupVersionControlCommand(QString &file, QString &path);@@ -188,14 +188,14 @@ signals:void filePathClicked(const TFilePath &);void filePathDoubleClicked(const TFilePath &);- // reuse the list of TFrameId in order to skip loadInfo() when loading the- // level with sequencial frames.+ // Reuse the list of TFrameId to skip loadInfo() when loading a level+ // with sequential frames.void filePathsSelected(const std::set<TFilePath> &,const std::list<std::vector<TFrameId>> &);void treeFolderChanged(const TFilePath &);- // for activating/deactivating the folder history buttons( back button &- // forward button )+ // For activating/deactivating the folder history buttons (back button &+ // forward button).void historyChanged(bool, bool);private:@@ -211,8 +211,8 @@ private:bool m_isFolder;bool m_isLink;- // calling loadInfo to the level with sequencial frames is time consuming.- // so keep the list of frameIds at the first time and try to reuse it.+ // Calling loadInfo for a level with sequential frames is time-consuming.+ // So keep the list of frameIds from the first time and try to reuse it.std::vector<TFrameId> m_frameIds;Item() : m_frameCount(0), m_validInfo(false), m_fileSize(0) {}@@ -234,7 +234,7 @@ private:DvItemViewer *m_itemViewer;FrameCountReader m_frameCountReader;- // folder history+ // Folder historyQList<QModelIndex> m_indexHistoryList;int m_currentPosition;int m_currentScroll;diff --git a/toonz/sources/toonz/scenebrowserversioncontrol.cpp b/toonz/sources/toonz/scenebrowserversioncontrol.cppindex f21c89211..4f0c2b595 100644--- a/toonz/sources/toonz/scenebrowserversioncontrol.cpp+++ b/toonz/sources/toonz/scenebrowserversioncontrol.cpp@@ -16,6 +16,8 @@#include "toonzqt/gutil.h"#include "toonzqt/icongenerator.h"+#include <QRegularExpression> // Added for QRegularExpression+namespace {//---------------------------------------------------------------------------@@ -23,12 +25,20 @@ QStringList getLevelFileNames(TFilePath path) {TFilePath dir = path.getParentDir();QDir qDir(QString::fromStdWString(dir.getWideString()));QString levelName =- QRegExp::escape(QString::fromStdWString(path.getWideName()));+ QRegularExpression::escape(QString::fromStdWString(path.getWideName()));QString levelType = QString::fromStdString(path.getType());- QString exp(levelName + ".[0-9]{1,4}." + levelType);- QRegExp regExp(exp);+ QString exp(levelName + "\\.[0-9]{1,4}\\." + levelType); // Updated escaping+ QRegularExpression regExp(exp); // UpdatedQStringList list = qDir.entryList(QDir::Files);- return list.filter(regExp);++ // Updated filtering logic for QRegularExpression+ QStringList filteredList;+ for (const QString &fileName : list) {+ if (regExp.match(fileName).hasMatch()) {+ filteredList.append(fileName);+ }+ }+ return filteredList;}} // namespace@@ -69,7 +79,7 @@ void SceneBrowser::setupVersionControlCommand(QString &file, QString &path) {//-----------------------------------------------------------------------------void SceneBrowser::setupVersionControlCommand(QStringList &files, QString &path,- int &sceneIconsCount) {+ int &sceneIconsCount) {std::vector<TFilePath> filePaths;FileSelection *fs =dynamic_cast<FileSelection *>(m_itemViewer->getPanel()->getSelection());@@ -88,11 +98,14 @@ void SceneBrowser::setupVersionControlCommand(QStringList &files, QString &path,QStringList levelNames = getLevelFileNames(fp);if (levelNames.isEmpty()) {- QString levelName =- QRegExp::escape(QString::fromStdWString(fp.getWideName()));+ QString levelName = QRegularExpression::escape(+ QString::fromStdWString(fp.getWideName()));QString levelType = QString::fromStdString(fp.getType());- QString exp(levelName + ".[0-9]{1,4}." + levelType);- QRegExp regExp(exp);+ QString exp(+ levelName ++ "_[0-9]{3}\\.(tlv|tif|tga|png|gif|bmp|jpg|jpeg|mov|avi|mp4|tpl)$");+ QRegularExpression regExp(exp,+ QRegularExpression::CaseInsensitiveOption);levelNames = node->getMissingFiles(regExp);}@@ -490,8 +503,10 @@ void SceneBrowser::getRevisionHistory() {files.removeAt(files.indexOf(file));SVNTimeline *timelineDialog = new SVNTimeline(this, path, file, files);- connect(timelineDialog, SIGNAL(commandDone(const QStringList &)), this,- SLOT(onVersionControlCommandDone(const QStringList &)));++ // Updated signal/slot connection to modern Qt5 syntax+ connect(timelineDialog, &SVNTimeline::commandDone, this,+ &SceneBrowser::onVersionControlCommandDone);timelineDialog->show();timelineDialog->raise();diff --git a/toonz/sources/toonz/shortcutpopup.cpp b/toonz/sources/toonz/shortcutpopup.cppindex f2494bf32..0c73b3020 100644--- a/toonz/sources/toonz/shortcutpopup.cpp+++ b/toonz/sources/toonz/shortcutpopup.cpp@@ -51,8 +51,8 @@ ShortcutPopup *ShortcutPopup::s_instance = nullptr;//=============================================================================// ShortcutItem// -------------// Lo ShortcutTree visualizza ShortcutItem (organizzati in folder)-// ogni ShortcutItem rappresenta una QAction (e relativo Shortcut)+// The ShortcutTree displays ShortcutItem (organized in folders)+// each ShortcutItem represents a QAction (and its Shortcut)//-----------------------------------------------------------------------------class ShortcutItem final : public QTreeWidgetItem {@@ -67,7 +67,8 @@ public:void updateText() {QString text = m_action->text();// removing accelerator key indicator- text = text.replace(QRegExp("&([^& ])"), "\\1");+ QRegularExpression regex("&([^& ])");+ text = text.replace(regex, "\\1");// removing doubled &stext = text.replace("&&", "&");setText(0, text);@@ -85,7 +86,8 @@ ShortcutViewer::ShortcutViewer(QWidget *parent): QKeySequenceEdit(parent), m_action(0), m_keysPressed(0) {setObjectName("ShortcutViewer");setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);- connect(this, SIGNAL(editingFinished()), this, SLOT(onEditingFinished()));+ connect(this, &ShortcutViewer::editingFinished, this,+ &ShortcutViewer::onEditingFinished);}//-----------------------------------------------------------------------------@@ -234,8 +236,7 @@ void ShortcutViewer::leaveEvent(QEvent *event) { update(); }// ShortcutTree//------------------------------------------------------------------------------ShortcutTree::ShortcutTree(QWidget *parent)- : QTreeWidget(parent) {+ShortcutTree::ShortcutTree(QWidget *parent) : QTreeWidget(parent) {setObjectName("ShortcutTree");setIndentation(14);setAlternatingRowColors(true);@@ -283,20 +284,22 @@ ShortcutTree::ShortcutTree(QWidget *parent)addFolder(tr("RGBA Channels"), RGBACommandType);sortItems(0, Qt::AscendingOrder);-+restoreExpandedState();- connect(- this, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),- this, SLOT(onCurrentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)));- connect(this, SIGNAL(clicked(const QModelIndex &)), this,- SLOT(onItemClicked(const QModelIndex &)));- connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem *)), this,- SLOT(onItemCollapsed(QTreeWidgetItem *)));- connect(this, &QTreeWidget::itemExpanded, [this](QTreeWidgetItem *) {+ connect(this, &ShortcutTree::currentItemChanged, this,+ &ShortcutTree::onCurrentItemChanged);++ connect(this, &ShortcutTree::clicked, this, &ShortcutTree::onItemClicked);++ connect(this, &QTreeWidget::itemCollapsed, this,+ &ShortcutTree::onItemCollapsed);++ connect(this, &QTreeWidget::itemExpanded, this, [this](QTreeWidgetItem *) {if (m_lastSearchTerm.isEmpty()) saveExpandedState();});- connect(this, &QTreeWidget::itemCollapsed, [this](QTreeWidgetItem *) {++ connect(this, &QTreeWidget::itemCollapsed, this, [this](QTreeWidgetItem *) {if (m_lastSearchTerm.isEmpty()) saveExpandedState();});}@@ -310,7 +313,7 @@ ShortcutTree::~ShortcutTree() {}void ShortcutTree::saveExpandedState() {QSettings settings;QStringList expandedFolders = collectExpandedState();-+settings.setValue("ShortcutPopup/expandedFolders", expandedFolders);settings.setValue("ShortcutPopup/expandedStateSaved", true);}@@ -330,22 +333,22 @@ void ShortcutTree::restoreExpandedState() {QStringList ShortcutTree::collectExpandedState() const {QStringList expandedFolders;-+// Save expanded state for all folders- for (QTreeWidgetItem* folder : m_folders) {+ for (QTreeWidgetItem *folder : m_folders) {if (folder && folder->isExpanded()) {expandedFolders.append(folder->text(0));}}-+// Save expanded state for all subfolders (with parent path)- for (QTreeWidgetItem* subfolder : m_subFolders) {+ for (QTreeWidgetItem *subfolder : m_subFolders) {if (subfolder && subfolder->isExpanded() && subfolder->parent()) {QString path = subfolder->parent()->text(0) + "/" + subfolder->text(0);expandedFolders.append(path);}}-+return expandedFolders;}@@ -354,7 +357,7 @@ QStringList ShortcutTree::collectExpandedState() const {void ShortcutTree::applyExpandedState(const QStringList &expandedFolders,bool useDefaultIfEmpty) {// Restore state for top-level folders- for (QTreeWidgetItem* folder : m_folders) {+ for (QTreeWidgetItem *folder : m_folders) {if (folder) {QString folderName = folder->text(0);if (!expandedFolders.isEmpty()) {@@ -364,9 +367,9 @@ void ShortcutTree::applyExpandedState(const QStringList &expandedFolders,}}}-+// Restore state for subfolders- for (QTreeWidgetItem* subfolder : m_subFolders) {+ for (QTreeWidgetItem *subfolder : m_subFolders) {if (subfolder && subfolder->parent()) {QString path = subfolder->parent()->text(0) + "/" + subfolder->text(0);if (!expandedFolders.isEmpty()) {@@ -383,28 +386,29 @@ void ShortcutTree::applyExpandedState(const QStringList &expandedFolders,void ShortcutTree::refreshTree() {// === STEP 1: Save expansion state before clearing ===QMap<QString, bool> expandedState;-+// Save state for top-level folders- for (QTreeWidgetItem* folder : m_folders) {+ for (QTreeWidgetItem *folder : m_folders) {if (folder) {expandedState[folder->text(0)] = folder->isExpanded();}}-+// Save state for sub-folders- for (QTreeWidgetItem* subfolder : m_subFolders) {+ for (QTreeWidgetItem *subfolder : m_subFolders) {if (subfolder && subfolder->parent()) {- QString fullPath = subfolder->parent()->text(0) + "/" + subfolder->text(0);+ QString fullPath =+ subfolder->parent()->text(0) + "/" + subfolder->text(0);expandedState[fullPath] = subfolder->isExpanded();}}-+// === STEP 2: Clear and rebuild ===m_items.clear();m_folders.clear();m_subFolders.clear();clear();-+// Rebuild the tree structureQTreeWidgetItem *menuCommandFolder = new QTreeWidgetItem(this);menuCommandFolder->setText(0, tr("Menu Commands"));@@ -441,10 +445,10 @@ void ShortcutTree::refreshTree() {addFolder(tr("RGBA Channels"), RGBACommandType);sortItems(0, Qt::AscendingOrder);-+// === STEP 3: Restore expansion state ===// Restore state for top-level folders (only if state exists)- for (QTreeWidgetItem* folder : m_folders) {+ for (QTreeWidgetItem *folder : m_folders) {if (folder) {QString folderName = folder->text(0);if (expandedState.contains(folderName)) {@@ -453,23 +457,24 @@ void ShortcutTree::refreshTree() {// No default behavior - keep folders collapsed if no state exists}}-+// Restore state for sub-folders (only if state exists)- for (QTreeWidgetItem* subfolder : m_subFolders) {+ for (QTreeWidgetItem *subfolder : m_subFolders) {if (subfolder && subfolder->parent()) {- QString fullPath = subfolder->parent()->text(0) + "/" + subfolder->text(0);+ QString fullPath =+ subfolder->parent()->text(0) + "/" + subfolder->text(0);if (expandedState.contains(fullPath)) {subfolder->setExpanded(expandedState[fullPath]);}// No default behavior - keep folders collapsed if no state exists}}-+// === STEP 4: Restore search filter if one was active ===if (!m_lastSearchTerm.isEmpty()) {searchItems(m_lastSearchTerm);}-+update();}@@ -500,7 +505,7 @@ void ShortcutTree::addFolder(const QString &title, int commandType,void ShortcutTree::searchItems(const QString &searchWord) {m_lastSearchTerm = searchWord;-+if (searchWord.isEmpty()) {// Reset: show all itemsfor (int i = 0; i < (int)m_items.size(); i++) m_items[i]->setHidden(false);@@ -513,16 +518,16 @@ void ShortcutTree::searchItems(const QString &searchWord) {// Open only "Menu Commands"m_folders[f]->setExpanded(m_folders[f]->text(0) == tr("Menu Commands"));}-+// Clear user collapse trackingm_userCollapsedDuringSearch.clear();-+show();emit searched(true);update();return;}-+// Starting a new search: clear user collapse trackingif (m_lastSearchTerm.isEmpty()) {m_userCollapsedDuringSearch.clear();@@ -531,7 +536,7 @@ void ShortcutTree::searchItems(const QString &searchWord) {// Multi-word search: split search term by spaces and match all wordsQStringList searchWords = searchWord.split(' ', Qt::SkipEmptyParts);QList<QTreeWidgetItem *> foundItems;-+if (searchWords.isEmpty()) {// No valid search words after splittinghide();@@ -539,15 +544,16 @@ void ShortcutTree::searchItems(const QString &searchWord) {update();return;}-+// Find items that contain ALL search words (case-insensitive)// Search in item name AND parent folder namesfor (int i = 0; i < (int)m_items.size(); i++) {QTreeWidgetItem *item = m_items[i];- QString itemText = item->text(0); // Get item name-- // Build full search text: item name + parent folder name + grandparent folder name- QString fullSearchText = itemText;+ QString itemText = item->text(0); // Get item name++ // Build full search text: item name + parent folder name + grandparent+ // folder name+ QString fullSearchText = itemText;QTreeWidgetItem *parent = item->parent();if (parent) {fullSearchText += " " + parent->text(0);@@ -556,7 +562,7 @@ void ShortcutTree::searchItems(const QString &searchWord) {fullSearchText += " " + grandparent->text(0);}}-+bool matchesAllWords = true;for (const QString &word : searchWords) {if (!fullSearchText.contains(word, Qt::CaseInsensitive)) {@@ -564,12 +570,12 @@ void ShortcutTree::searchItems(const QString &searchWord) {break;}}-+if (matchesAllWords) {foundItems.append(item);}}-+if (foundItems.isEmpty()) {hide();emit searched(false);@@ -582,7 +588,8 @@ void ShortcutTree::searchItems(const QString &searchWord) {m_items[i]->setHidden(!foundItems.contains(m_items[i]));// hide folders which does not contain matched items- // show AND expand folders containing matched items (unless user manually closed them)+ // show AND expand folders containing matched items (unless user manually+ // closed them)bool found;for (int f = 0; f < m_subFolders.size(); f++) {QTreeWidgetItem *sf = m_subFolders.at(f);@@ -594,10 +601,11 @@ void ShortcutTree::searchItems(const QString &searchWord) {}}sf->setHidden(!found);-+// Expand only if: has results AND user hasn't manually closed itif (found) {- QString path = sf->parent() ? sf->parent()->text(0) + "/" + sf->text(0) : sf->text(0);+ QString path = sf->parent() ? sf->parent()->text(0) + "/" + sf->text(0)+ : sf->text(0);if (!m_userCollapsedDuringSearch.contains(path)) {sf->setExpanded(true);}@@ -613,7 +621,7 @@ void ShortcutTree::searchItems(const QString &searchWord) {}}fol->setHidden(!found);-+// Expand only if: has results AND user hasn't manually closed itif (found) {QString folderName = fol->text(0);@@ -673,7 +681,7 @@ ShortcutPopup::ShortcutPopup(): Dialog(TApp::instance()->getMainWindow(), false, false, "Shortcut") {// Register this instances_instance = this;-+setWindowTitle(tr("Configure Shortcuts"));m_presetChoiceCB = new QComboBox(this);buildPresets();@@ -764,26 +772,39 @@ ShortcutPopup::ShortcutPopup()// m_topLayout->addWidget(m_exportButton, 0);}- connect(m_list, SIGNAL(actionSelected(QAction *)), m_sViewer,- SLOT(setAction(QAction *)));-- connect(m_removeBtn, SIGNAL(clicked()), m_sViewer, SLOT(removeShortcut()));-- connect(m_sViewer, SIGNAL(shortcutChanged()), m_list,- SLOT(onShortcutChanged()));-- connect(m_list, SIGNAL(searched(bool)), noSearchResultLabel,- SLOT(setHidden(bool)));- connect(m_searchEdit, SIGNAL(textChanged(const QString &)), this,- SLOT(onSearchTextChanged(const QString &)));- connect(m_presetChoiceCB, SIGNAL(currentIndexChanged(int)),- SLOT(onPresetChanged()));- connect(m_exportButton, SIGNAL(clicked()), SLOT(onExportButton()));- connect(m_deletePresetButton, SIGNAL(clicked()), SLOT(onDeletePreset()));- connect(m_savePresetButton, SIGNAL(clicked()), SLOT(onSavePreset()));- connect(m_loadPresetButton, SIGNAL(clicked()), SLOT(onLoadPreset()));- connect(m_clearAllShortcutsButton, SIGNAL(clicked()),- SLOT(clearAllShortcuts()));+ connect(m_list, &ShortcutTree::actionSelected, m_sViewer,+ &ShortcutViewer::setAction);++ connect(m_removeBtn, &QPushButton::clicked, m_sViewer,+ &ShortcutViewer::removeShortcut);++ connect(m_sViewer, &ShortcutViewer::shortcutChanged, m_list,+ &ShortcutTree::onShortcutChanged);++ connect(m_list, &ShortcutTree::searched, noSearchResultLabel,+ &QLabel::setHidden);++ connect(m_searchEdit, &QLineEdit::textChanged, this,+ &ShortcutPopup::onSearchTextChanged);++ connect(m_presetChoiceCB, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &ShortcutPopup::onPresetChanged);++ // Use a lambda to adapt the clicked() signal to the slot signature+ connect(m_exportButton, &QPushButton::clicked, this,+ [this]() { onExportButton(); });++ connect(m_deletePresetButton, &QPushButton::clicked, this,+ &ShortcutPopup::onDeletePreset);++ connect(m_savePresetButton, &QPushButton::clicked, this,+ &ShortcutPopup::onSavePreset);++ connect(m_loadPresetButton, &QPushButton::clicked, this,+ &ShortcutPopup::onLoadPreset);++ connect(m_clearAllShortcutsButton, &QPushButton::clicked, this,+ &ShortcutPopup::clearAllShortcuts);}//-----------------------------------------------------------------------------@@ -793,7 +814,7 @@ ShortcutPopup::~ShortcutPopup() {if (m_list) {m_list->saveExpandedState();}-+// Unregister this instanceif (s_instance == this) {s_instance = nullptr;@@ -1101,43 +1122,44 @@ void ShortcutPopup::onSavePreset() {//------------------------------------------------------------------------------void ShortcutPopup::showEvent(QShowEvent *se) {+void ShortcutPopup::showEvent(QShowEvent *se) {getCurrentPresetPref();-+// Refresh brush preset and size commands to ensure they're up-to-dateToolPresetCommandManager::instance()->refreshPresetCommands();ToolPresetCommandManager::instance()->refreshSizeCommands();-+// Restore search term from QSettingsQSettings settings;- QString lastSearchTerm = settings.value("ShortcutPopup/searchText", "").toString();-+ QString lastSearchTerm =+ settings.value("ShortcutPopup/searchText", "").toString();+// Step 1: Restore search text in the field WITHOUT triggering searchItems{QSignalBlocker blocker(m_searchEdit);m_searchEdit->setText(lastSearchTerm);}-+// Step 2: Restore folder expansion state from QSettingsm_list->restoreExpandedState();-+// Step 3: If there was a search, apply filtering WITHOUT changing expansionif (!lastSearchTerm.isEmpty()) {// Save current expansion state before filteringQStringList expandedBeforeFilter;for (int i = 0; i < m_list->topLevelItemCount(); i++) {- QTreeWidgetItem* item = m_list->topLevelItem(i);+ QTreeWidgetItem *item = m_list->topLevelItem(i);if (item && item->isExpanded()) {expandedBeforeFilter.append(item->text(0));}}-+// Apply search filter (this will change expansion)m_list->searchItems(lastSearchTerm);-+// Restore the expansion state we had before filteringfor (int i = 0; i < m_list->topLevelItemCount(); i++) {- QTreeWidgetItem* item = m_list->topLevelItem(i);+ QTreeWidgetItem *item = m_list->topLevelItem(i);if (item) {item->setExpanded(expandedBeforeFilter.contains(item->text(0)));}@@ -1152,11 +1174,11 @@ void ShortcutPopup::hideEvent(QHideEvent *he) {if (m_list) {m_list->saveExpandedState();}-+// Save search text to QSettingsQSettings settings;settings.setValue("ShortcutPopup/searchText", m_searchEdit->text());-+DVGui::Dialog::hideEvent(he);}diff --git a/toonz/sources/toonz/shortcutpopup.h b/toonz/sources/toonz/shortcutpopup.hindex 1342240e3..df5e85bd9 100644--- a/toonz/sources/toonz/shortcutpopup.h+++ b/toonz/sources/toonz/shortcutpopup.h@@ -17,10 +17,10 @@ class ShortcutItem;//=============================================================================// ShortcutViewer// ---------------// E' l'editor dello shortcut associato all'azione corrente-// Visualizza lo shortcut e permette di cambiarlo digitando direttamente-// la nuova sequenza di tasti-// Per cancellarlo bisogna chiamare removeShortcut()+// Editor for the shortcut associated with the current action+// Displays the shortcut and allows changing it by typing directly+// the new key sequence+// To delete it, call removeShortcut()//-----------------------------------------------------------------------------class ShortcutViewer final : public QKeySequenceEdit {@@ -37,6 +37,7 @@ protected:void enterEvent(QEvent *event) override;void leaveEvent(QEvent *event) override;void keyPressEvent(QKeyEvent *event) override;+public slots:void setAction(QAction *action);void removeShortcut();@@ -49,8 +50,8 @@ signals://=============================================================================// ShortcutTree// -------------// Visualizza tutti le QAction (con gli eventuali shortcut assegnati)-// Serve per selezionare la QAction corrente+// Displays all QActions (with their assigned shortcuts if any)+// Used to select the current QAction//-----------------------------------------------------------------------------class ShortcutTree final : public QTreeWidget {@@ -71,7 +72,7 @@ public:void restoreExpandedState(); // Restore expansion state from QSettingsprotected:- // aggiunge un blocco di QAction. commandType e' un+ // adds a block of QActions. commandType is a// CommandType::MenubarCommandTypevoid addFolder(const QString &title, int commandType,QTreeWidgetItem *folder = 0);@@ -94,7 +95,7 @@ signals://=============================================================================// ShortcutPopup// --------------// Questo e' il popup che l'utente utilizza per modificare gli shortcut+// This is the popup that the user uses to modify shortcuts//-----------------------------------------------------------------------------class ShortcutPopup final : public DVGui::Dialog {@@ -147,4 +148,4 @@ protected slots:void onLoadPreset();};-#endif // SHORTCUTPOPUP_H+#endif // SHORTCUTPOPUP_Hdiff --git a/toonz/sources/toonz/startuppopup.cpp b/toonz/sources/toonz/startuppopup.cppindex dee166a87..259a03b0e 100644--- a/toonz/sources/toonz/startuppopup.cpp+++ b/toonz/sources/toonz/startuppopup.cpp@@ -49,21 +49,22 @@#include <QScrollBar>#include <QMouseEvent>#include <QDesktopServices>+#include <QRegularExpression> // Added for QRegularExpressionusing namespace DVGui;namespace {-// the first value in the preset list+// The first value in the preset listconst QString custom = QObject::tr("<custom>");void removeAll(QLayout *layout) {QLayoutItem *child;while (layout->count() != 0) {child = layout->takeAt(0);- if (child->layout() != 0) {+ if (child->layout() != nullptr) {removeAll(child->layout());- } else if (child->widget() != 0) {+ } else if (child->widget() != nullptr) {delete child->widget();}@@ -143,10 +144,11 @@ StartupPopup::StartupPopup()m_existingList = new StartupScenesList(this, QSize(96, 54));- // Exclude all character which cannot fit in a filepath (Win).+ // Exclude all characters which cannot fit in a filepath (Windows).// Dots are also prohibited since they are internally managed by Toonz.- QRegExp rx("[^\\\\/:?*.\"<>|]+");- m_nameFld->setValidator(new QRegExpValidator(rx, this));+ // Migration to QRegularExpression+ QRegularExpression rx("[^\\\\/:?*.\"<>|]+");+ m_nameFld->setValidator(new QRegularExpressionValidator(rx, this));m_widthFld->setMeasure("camera.lx");m_heightFld->setMeasure("camera.ly");@@ -295,51 +297,54 @@ StartupPopup::StartupPopup()TSceneHandle *sceneHandle = app->getCurrentScene();//---- signal-slot connections- bool ret = true;- ret = ret && connect(sceneHandle, SIGNAL(sceneChanged()), this,- SLOT(onSceneChanged()));- ret = ret && connect(sceneHandle, SIGNAL(sceneSwitched()), this,- SLOT(onSceneChanged()));- ret = ret && connect(newProjectButton, SIGNAL(clicked()), this,- SLOT(onNewProjectButtonPressed()));- ret = ret && connect(openProjectButton, SIGNAL(clicked()), this,- SLOT(onOpenProjectButtonPressed()));- ret = ret && connect(exploreProjectButton, SIGNAL(clicked()), this,- SLOT(onExploreProjectButtonPressed()));- ret = ret && connect(loadOtherSceneButton, SIGNAL(clicked()), this,- SLOT(onLoadSceneButtonPressed()));- ret = ret && connect(m_projectsCB, SIGNAL(currentIndexChanged(int)),- SLOT(onProjectChanged(int)));- ret = ret &&- connect(createButton, SIGNAL(clicked()), this, SLOT(onCreateButton()));- ret = ret && connect(m_showAtStartCB, SIGNAL(stateChanged(int)), this,- SLOT(onShowAtStartChanged(int)));- ret = ret && connect(m_widthFld, SIGNAL(valueChanged()), this,- SLOT(updateResolution()));- ret = ret && connect(m_heightFld, SIGNAL(valueChanged()), this,- SLOT(updateResolution()));- ret = ret &&- connect(m_resXFld, SIGNAL(valueChanged()), this, SLOT(updateSize()));- ret = ret &&- connect(m_resYFld, SIGNAL(valueChanged()), this, SLOT(updateSize()));- ret = ret && connect(m_dpiFld, SIGNAL(editingFinished()), this,- SLOT(onDpiChanged()));- ret = ret && connect(m_presetCombo, SIGNAL(activated(const QString &)),- SLOT(onPresetSelected(const QString &)));- ret = ret && connect(m_addPresetBtn, SIGNAL(clicked()), SLOT(addPreset()));- ret = ret && connect(m_unitsCB, SIGNAL(currentIndexChanged(int)),- SLOT(onCameraUnitChanged(int)));- ret = ret &&- connect(m_removePresetBtn, SIGNAL(clicked()), SLOT(removePreset()));- ret = ret && connect(m_nameFld, SIGNAL(returnPressedNow()), createButton,- SLOT(animateClick()));- ret = ret && connect(m_autoSaveOnCB, SIGNAL(stateChanged(int)), this,- SLOT(onAutoSaveOnChanged(int)));- ret = ret && connect(m_autoSaveTimeFld, SIGNAL(editingFinished()), this,- SLOT(onAutoSaveTimeChanged()));- ret = ret && connect(m_existingList, SIGNAL(itemClicked(int)), this,- SLOT(onExistingSceneClicked(int)));- assert(ret);+ // Using modern Qt connection syntax+ connect(sceneHandle, &TSceneHandle::sceneChanged, this,+ &StartupPopup::onSceneChanged);+ connect(sceneHandle, &TSceneHandle::sceneSwitched, this,+ &StartupPopup::onSceneChanged);+ connect(newProjectButton, &QPushButton::clicked, this,+ &StartupPopup::onNewProjectButtonPressed);+ connect(openProjectButton, &QPushButton::clicked, this,+ &StartupPopup::onOpenProjectButtonPressed);+ connect(exploreProjectButton, &QPushButton::clicked, this,+ &StartupPopup::onExploreProjectButtonPressed);+ connect(loadOtherSceneButton, &QPushButton::clicked, this,+ &StartupPopup::onLoadSceneButtonPressed);+ connect(m_projectsCB, QOverload<int>::of(&QComboBox::currentIndexChanged),+ this, &StartupPopup::onProjectChanged);+ connect(createButton, &QPushButton::clicked, this,+ &StartupPopup::onCreateButton);+ connect(m_showAtStartCB, &QCheckBox::stateChanged, this,+ &StartupPopup::onShowAtStartChanged);+ connect(m_widthFld, &MeasuredDoubleLineEdit::valueChanged, this,+ &StartupPopup::updateResolution);+ connect(m_heightFld, &MeasuredDoubleLineEdit::valueChanged, this,+ &StartupPopup::updateResolution);+ connect(m_resXFld, &DoubleLineEdit::valueChanged, this,+ &StartupPopup::updateSize);+ connect(m_resYFld, &DoubleLineEdit::valueChanged, this,+ &StartupPopup::updateSize);+ connect(m_dpiFld, &DoubleLineEdit::editingFinished, this,+ &StartupPopup::onDpiChanged);+ connect(m_presetCombo, QOverload<int>::of(&QComboBox::activated), this,+ [this](int index) {+ if (index < 0) return;+ onPresetSelected(m_presetCombo->itemText(index));+ });+ connect(m_addPresetBtn, &QPushButton::clicked, this,+ &StartupPopup::addPreset);+ connect(m_unitsCB, QOverload<int>::of(&QComboBox::currentIndexChanged), this,+ &StartupPopup::onCameraUnitChanged);+ connect(m_removePresetBtn, &QPushButton::clicked, this,+ &StartupPopup::removePreset);+ connect(m_nameFld, &LineEdit::returnPressedNow, this,+ [createButton]() { createButton->animateClick(); });+ connect(m_autoSaveOnCB, &QCheckBox::stateChanged, this,+ &StartupPopup::onAutoSaveOnChanged);+ connect(m_autoSaveTimeFld, &IntLineEdit::editingFinished, this,+ &StartupPopup::onAutoSaveTimeChanged);+ connect(m_existingList, &StartupScenesList::itemClicked, this,+ &StartupPopup::onExistingSceneClicked);}//-----------------------------------------------------------------------------@@ -411,17 +416,18 @@ void StartupPopup::showEvent(QShowEvent *) {m_autoSaveOnCB->setChecked(Preferences::instance()->isAutosaveEnabled());m_autoSaveTimeFld->setEnabled(m_autoSaveOnCB->isChecked());m_autoSaveTimeFld->setValue(Preferences::instance()->getAutosavePeriod());- // update recent scenes- // clear items if they exist first+ // Update recent scenes+ // Clear items if they exist firstrefreshRecentScenes();refreshExistingScenes();- // center window- QScreen *screen = QGuiApplication::screenAt(TApp::instance()->getMainWindow()->pos());+ // Center window+ QScreen *screen =+ QGuiApplication::screenAt(TApp::instance()->getMainWindow()->pos());if (!screen) {screen = QGuiApplication::primaryScreen();}- QPoint activeMonitorCenter = screen->availableGeometry().center();- QPoint thisPopupCenter = this->rect().center();+ QPoint activeMonitorCenter = screen->availableGeometry().center();+ QPoint thisPopupCenter = this->rect().center();QPoint centeredOnActiveMonitor = activeMonitorCenter - thisPopupCenter;this->move(centeredOnActiveMonitor);}@@ -442,9 +448,9 @@ void StartupPopup::refreshRecentScenes() {} else {int i = 0;for (QString name : m_sceneNames) {- if (i > 9) break; // box can hold 10 scenes+ if (i > 9) break; // Box can hold 10 scenesQString fileName =- name.remove(0, name.indexOf(" ") + 1); // remove "#. " prefix+ name.remove(0, name.indexOf(" ") + 1); // Remove "#. " prefixQString projectName = RecentFiles::instance()->getFileProject(fileName);QString justName = QString::fromStdString(TFilePath(fileName).getName()) +(projectName != "-" ? " [" + projectName + "]" : "");@@ -454,13 +460,11 @@ void StartupPopup::refreshRecentScenes() {i++;}}- bool ret = true;for (int i = 0;i < m_recentNamesLabels.count() && i < RECENT_SCENES_MAX_COUNT; i++) {- ret = ret && connect(m_recentNamesLabels[i], SIGNAL(wasClicked(int)), this,- SLOT(onRecentSceneClicked(int)));+ connect(m_recentNamesLabels[i], &StartupLabel::wasClicked, this,+ &StartupPopup::onRecentSceneClicked);}- assert(ret);m_recentSceneLay->addStretch(1);}@@ -566,9 +570,8 @@ void StartupPopup::onCreateButton() {"\nDo you want to overwrite it?");int ret = DVGui::MsgBox(question, QObject::tr("Yes"), QObject::tr("No"), 0);if (ret == 0 || ret == 2) {- // no (or closed message box window)+ // No (or closed message box window)return;- ;}}CommandManager::instance()->execute(MI_NewScene);@@ -587,9 +590,9 @@ void StartupPopup::onCreateButton() {size);TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera()->setRes(res);- // save the scene right away+ // Save the scene right awayIoCmd::saveScene();- // this makes sure the scene viewers update to the right fps+ // This makes sure the scene viewers update to the right fpsTApp::instance()->getCurrentScene()->notifySceneSwitched();TApp::instance()->getCurrentScene()->notifyNameSceneChange();@@ -787,7 +790,7 @@ void StartupPopup::removePreset() {int index = m_presetCombo->currentIndex();if (index <= 0) return;- // confirmation dialog+ // Confirmation dialogint ret = DVGui::MsgBox(QObject::tr("Deleting \"%1\".\nAre you sure?").arg(m_presetCombo->currentText()),QObject::tr("Delete"), QObject::tr("Cancel"));@@ -818,7 +821,7 @@ void StartupPopup::onPresetSelected(const QString &str) {// m_widthFld->setValue(m_heightFld->getValue() * ar);// m_dpiFld->setValue(m_xRes / m_widthFld->getValue());- // here is the system that preserves dpi+ // Here is the system that preserves dpim_widthFld->setValue((double)xres / (double)m_dpi);m_heightFld->setValue((double)yres / (double)m_dpi);if (Preferences::instance()->getPixelsOnly()) {@@ -845,12 +848,13 @@ bool StartupPopup::parsePresetString(const QString &str, QString &name,QString &yoffset, double &ar,bool forCleanup) {/*- parsing preset string with QString::split().+ Parsing preset string with QString::split().!NOTE! fx/fy (camera size in inch) and xoffset/yoffset (camera offset used incleanup camera) are optional,in order to keep compatibility with default (Harlequin's) reslist.txt*/+ // Migration to Qt::SkipEmptyParts (no change needed for Qt 5.15)QStringList tokens = str.split(",", Qt::SkipEmptyParts);if (!(tokens.count() == 3 ||@@ -982,7 +986,7 @@ void StartupPopup::onExploreProjectButtonPressed() {//-----------------------------------------------------------------------------void StartupPopup::onSceneChanged() {- // close the box if a recent scene has been selected+ // Close the box if a recent scene has been selectedif (!TApp::instance()->getCurrentScene()->getScene()->isUntitled()) {hide();} else {@@ -1021,7 +1025,7 @@ void StartupPopup::onRecentSceneClicked(int index) {RecentFiles::instance()->refreshRecentFilesMenu(RecentFiles::Scene);for (int i = 0;i < m_recentNamesLabels.count() && i < RECENT_SCENES_MAX_COUNT; i++) {- disconnect(m_recentNamesLabels[i]);+ disconnect(m_recentNamesLabels[i], nullptr, nullptr, nullptr);}QString msg = QObject::tr("The selected scene could not be found.");DVGui::warning(msg);@@ -1061,12 +1065,8 @@ void StartupPopup::onRecentSceneClicked(int index) {void StartupPopup::onCameraUnitChanged(int index) {Preferences *pref = Preferences::instance();QStringList type;- // preference value should not be translated- type << "pixel"- << "cm"- << "mm"- << "inch"- << "field";+ // Preference value should not be translated+ type << "pixel" << "cm" << "mm" << "inch" << "field";double width = m_widthFld->getValue();double height = m_heightFld->getValue();@@ -1194,9 +1194,9 @@ StartupScenesList::StartupScenesList(QWidget *parent, const QSize &iconSize)horizontalScrollBar()->setCursor(Qt::ArrowCursor);verticalScrollBar()->setCursor(Qt::ArrowCursor);- bool ret = connect(this, SIGNAL(itemClicked(QListWidgetItem *)), this,- SLOT(onItemClicked(QListWidgetItem *)));- assert(ret);+ // Modern Qt connection+ connect(this, &QListWidget::itemClicked, this,+ &StartupScenesList::onItemClicked);clear();}diff --git a/toonz/sources/toonz/startuppopup.h b/toonz/sources/toonz/startuppopup.hindex 5943917bf..feac052b8 100644--- a/toonz/sources/toonz/startuppopup.h+++ b/toonz/sources/toonz/startuppopup.h@@ -108,7 +108,7 @@ public slots:class StartupLabel : public QLabel {Q_OBJECTpublic:- explicit StartupLabel(const QString &text = "", QWidget *parent = 0,+ explicit StartupLabel(const QString &text = "", QWidget *parent = nullptr,int index = -1);~StartupLabel();QString m_text;diff --git a/toonz/sources/toonz/svncommitdialog.cpp b/toonz/sources/toonz/svncommitdialog.cppindex f7de89098..f7746696f 100644--- a/toonz/sources/toonz/svncommitdialog.cpp+++ b/toonz/sources/toonz/svncommitdialog.cpp@@ -32,6 +32,7 @@#include <QHostInfo>#include <QTextStream>#include <QMainWindow>+#include <QRegularExpression>//=============================================================================// SVNCommitDialog@@ -41,18 +42,18 @@ SVNCommitDialog::SVNCommitDialog(QWidget *parent, const QString &workingDir,const QStringList &files, bool folderOnly,int sceneIconAdded): Dialog(TApp::instance()->getMainWindow(), true, false)- , m_commitSceneContentsCheckBox(0)+ , m_commitSceneContentsCheckBox(nullptr), m_workingDir(workingDir), m_files(files), m_folderOnly(folderOnly)- , m_targetTempFile(0)- , m_selectionCheckBox(0)- , m_selectionLabel(0)+ , m_targetTempFile(nullptr)+ , m_selectionCheckBox(nullptr)+ , m_selectionLabel(nullptr), m_sceneIconAdded(sceneIconAdded), m_folderAdded(0) {setModal(false);setAttribute(Qt::WA_DeleteOnClose, true);- setWindowTitle(tr("Version Control: Put changes"));+ setWindowTitle(tr("Version Control: Commit changes"));if (m_folderOnly)setMinimumSize(320, 320);@@ -73,7 +74,8 @@ SVNCommitDialog::SVNCommitDialog(QWidget *parent, const QString &workingDir,m_treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);m_treeWidget->setIconSize(QSize(21, 18));}- m_treeWidget->setStyleSheet("QTreeWidget { border: 1px solid gray; }");+ m_treeWidget->setStyleSheet(+ QStringLiteral("QTreeWidget { border: 1px solid gray; }"));if (m_folderOnly) {mainLayout->addWidget(m_treeWidget);@@ -81,9 +83,9 @@ SVNCommitDialog::SVNCommitDialog(QWidget *parent, const QString &workingDir,QHBoxLayout *belowTreeLayout = new QHBoxLayout;belowTreeLayout->setContentsMargins(0, 0, 0, 0);- m_selectionCheckBox = new QCheckBox(tr("Select / Deselect All"), 0);- connect(m_selectionCheckBox, SIGNAL(clicked(bool)), this,- SLOT(onSelectionCheckBoxClicked(bool)));+ m_selectionCheckBox = new QCheckBox(tr("Select / Deselect All"), nullptr);+ connect(m_selectionCheckBox, &QCheckBox::clicked, this,+ &SVNCommitDialog::onSelectionCheckBoxClicked);m_selectionLabel = new QLabel;m_selectionLabel->setText(tr("0 Selected / 0 Total"));@@ -100,9 +102,9 @@ SVNCommitDialog::SVNCommitDialog(QWidget *parent, const QString &workingDir,QHBoxLayout *hLayout = new QHBoxLayout;- m_waitingLabel = new QLabel;- QMovie *waitingMove = new QMovie(":Resources/waiting.gif");- waitingMove->setParent(this);+ m_waitingLabel = new QLabel;+ QMovie *waitingMove =+ new QMovie(QStringLiteral(":Resources/waiting.gif"), QByteArray(), this);m_waitingLabel->setMovie(waitingMove);waitingMove->setCacheMode(QMovie::CacheAll);@@ -141,11 +143,11 @@ SVNCommitDialog::SVNCommitDialog(QWidget *parent, const QString &workingDir,if (!m_folderOnly) {m_commitSceneContentsCheckBox = new QCheckBox(this);- connect(m_commitSceneContentsCheckBox, SIGNAL(toggled(bool)), this,- SLOT(onCommiSceneContentsToggled(bool)));+ connect(m_commitSceneContentsCheckBox, &QCheckBox::toggled, this,+ &SVNCommitDialog::onCommitSceneContentsToggled);m_commitSceneContentsCheckBox->setChecked(false);m_commitSceneContentsCheckBox->hide();- m_commitSceneContentsCheckBox->setText(tr("Put Scene Contents"));+ m_commitSceneContentsCheckBox->setText(tr("Commit Scene Contents"));formLayout->addRow("", m_commitSceneContentsCheckBox);}@@ -157,23 +159,24 @@ SVNCommitDialog::SVNCommitDialog(QWidget *parent, const QString &workingDir,addWidget(container, false);endHLayout();- m_commitButton = new QPushButton(tr("Put"));+ m_commitButton = new QPushButton(tr("Commit"));m_commitButton->setEnabled(false);- connect(m_commitButton, SIGNAL(clicked()), this,- SLOT(onCommitButtonClicked()));+ connect(m_commitButton, &QPushButton::clicked, this,+ &SVNCommitDialog::onCommitButtonClicked);m_cancelButton = new QPushButton(tr("Cancel"));- connect(m_cancelButton, SIGNAL(clicked()), this, SLOT(reject()));+ connect(m_cancelButton, &QPushButton::clicked, this,+ &SVNCommitDialog::reject);addButtonBarWidget(m_commitButton, m_cancelButton);// 0. Connect for svn errors (that may occur every time)- connect(&m_thread, SIGNAL(error(const QString &)), this,- SLOT(onError(const QString &)));+ connect(&m_thread, &VersionControlThread::error, this,+ &SVNCommitDialog::onError);// 1. Getting status (with show-updates enabled...)- connect(&m_thread, SIGNAL(statusRetrieved(const QString &)), this,- SLOT(onStatusRetrieved(const QString &)));+ connect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNCommitDialog::onStatusRetrieved);m_thread.getSVNStatus(m_workingDir, m_files, true);}@@ -197,12 +200,13 @@ void SVNCommitDialog::onCommitButtonClicked() {m_commitButton->setEnabled(false);- // Check the status of the scene resource in order to see if some items has- // to be added or can be directly committed+ // Check the status of the scene resource to see if some items need to be+ // added or can be directly committedif (!m_folderOnly && !m_sceneResourcesToCommit.empty()) {- m_thread.disconnect(SIGNAL(statusRetrieved(const QString &)));- connect(&m_thread, SIGNAL(statusRetrieved(const QString &)), this,- SLOT(onResourcesStatusRetrieved(const QString &)));+ QObject::disconnect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNCommitDialog::onStatusRetrieved);+ connect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNCommitDialog::onResourcesStatusRetrieved);m_thread.getSVNStatus(m_workingDir, m_sceneResourcesToCommit, true);return;}@@ -231,9 +235,9 @@ void SVNCommitDialog::addFiles() {.arg(QString::number(fileToAddCount - m_sceneIconAdded)));QStringList args;- args << "add";- args << "--parents";- args << "-N"; // Non recursive add+ args << QStringLiteral("add");+ args << QStringLiteral("--parents");+ args << QStringLiteral("-N"); // Non recursive add// Use a temporary file to store all the files listm_targetTempFile = new QFile(m_workingDir + "/" + "tempAddFile");@@ -250,12 +254,13 @@ void SVNCommitDialog::addFiles() {}m_targetTempFile->close();- args << "--targets";- args << "tempAddFile";+ args << QStringLiteral("--targets");+ args << QStringLiteral("tempAddFile");- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), SLOT(onAddDone()));- m_thread.executeCommand(m_workingDir, "svn", args);+ QObject::disconnect(&m_thread, &VersionControlThread::done, this, nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitDialog::onAddDone);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args);} elseonAddDone();}@@ -268,8 +273,8 @@ void SVNCommitDialog::commitFiles() {int fileToCommitCount = m_filesToCommit.size();if (fileToCommitCount > 0) {QStringList args;- args << "commit";- args << "-N"; // non recursive commit+ args << QStringLiteral("commit");+ args << QStringLiteral("-N"); // non recursive commit// Use a temporary file to store all the files listm_targetTempFile = new QFile(m_workingDir + "/" + "tempCommitFile");@@ -286,18 +291,21 @@ void SVNCommitDialog::commitFiles() {m_targetTempFile->close();- args << "--targets";- args << "tempCommitFile";+ args << QStringLiteral("--targets");+ args << QStringLiteral("tempCommitFile");if (!m_commentTextEdit->toPlainText().isEmpty())- args << QString("-m").append(m_commentTextEdit->toPlainText());+ args << QStringLiteral("-m").append(m_commentTextEdit->toPlainText());else- args << QString("-m").append(VersionControl::instance()->getUserName() +- " commit changes.");- m_thread.disconnect(SIGNAL(statusRetrieved(const QString &)));- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), SLOT(onCommitDone()));- m_thread.executeCommand(m_workingDir, "svn", args);+ args << QStringLiteral("-m").append(+ VersionControl::instance()->getUserName() ++ QStringLiteral(" commit changes."));+ QObject::disconnect(&m_thread, &VersionControlThread::statusRetrieved, this,+ nullptr);+ QObject::disconnect(&m_thread, &VersionControlThread::done, this, nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitDialog::onCommitDone);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args);} elseonCommitDone();}@@ -305,14 +313,13 @@ void SVNCommitDialog::commitFiles() {//-----------------------------------------------------------------------------void SVNCommitDialog::setPropertyFiles() {- m_textLabel->setText(tr("Set needs-lock property..."));+ m_textLabel->setText(tr("Setting needs-lock property..."));int count = m_filesAdded.size();if (count > 0) {QStringList args;- args << "propset"- << "svn:needs-lock"- << "'*'";+ args << QStringLiteral("propset") << QStringLiteral("svn:needs-lock")+ << QStringLiteral("'*'");// Use a temporary file to store all the files listm_targetTempFile = new QFile(m_workingDir + "/" + "tempPropSetFile");@@ -322,14 +329,15 @@ void SVNCommitDialog::setPropertyFiles() {}m_targetTempFile->close();- args << "--targets";- args << "tempPropSetFile";+ args << QStringLiteral("--targets");+ args << QStringLiteral("tempPropSetFile");- m_thread.disconnect(SIGNAL(statusRetrieved(const QString &)));- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)),- SLOT(onSetPropertyDone()));- m_thread.executeCommand(m_workingDir, "svn", args);+ QObject::disconnect(&m_thread, &VersionControlThread::statusRetrieved, this,+ nullptr);+ QObject::disconnect(&m_thread, &VersionControlThread::done, this, nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitDialog::onSetPropertyDone);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args);} elseonSetPropertyDone();}@@ -342,7 +350,7 @@ void SVNCommitDialog::switchToCloseButton() {m_commitButton->setText(tr("Close"));m_commitButton->setEnabled(true);m_cancelButton->hide();- connect(m_commitButton, SIGNAL(clicked()), this, SLOT(close()));+ connect(m_commitButton, &QPushButton::clicked, this, &SVNCommitDialog::close);}//-----------------------------------------------------------------------------@@ -351,16 +359,17 @@ void SVNCommitDialog::onAddDone() {if (m_targetTempFile) {QFile::remove(m_targetTempFile->fileName());delete m_targetTempFile;- m_targetTempFile = 0;+ m_targetTempFile = nullptr;}int fileToAddCount = m_filesToAdd.size();if (fileToAddCount + m_sceneResourcesToCommit.size() > 0) {m_textLabel->setText(tr("Getting repository status..."));- m_thread.disconnect(SIGNAL(statusRetrieved(const QString &)));- connect(&m_thread, SIGNAL(statusRetrieved(const QString &)), this,- SLOT(onStatusRetrievedAfterAdd(const QString &)));+ QObject::disconnect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNCommitDialog::onStatusRetrieved);+ connect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNCommitDialog::onStatusRetrievedAfterAdd);QStringList oldFilesAndResources;oldFilesAndResources.append(m_files);@@ -372,27 +381,32 @@ void SVNCommitDialog::onAddDone() {int resCount = m_sceneResourcesToCommit.size();for (int r = 0; r < resCount; r++) {- QString path = m_sceneResourcesToCommit.at(r);- int lastIndex = path.lastIndexOf(QRegExp("\\\\|/"));+ QString path = m_sceneResourcesToCommit.at(r);+ int lastIndex =+ path.lastIndexOf(QRegularExpression(QStringLiteral("[\\\\/]")));while (lastIndex != -1) {path = path.left(lastIndex);- if (!oldFilesAndResources.contains(path) && path != "..")+ if (!oldFilesAndResources.contains(path) && path != QLatin1String(".."))oldFilesAndResources.append(path);- lastIndex = path.lastIndexOf(QRegExp("\\\\|/"));+ lastIndex =+ path.lastIndexOf(QRegularExpression(QStringLiteral("[\\\\/]")));}}// Add also sceneIcons folderfor (int x = 0; x < m_filesToAdd.size(); x++) {QString s = m_filesToAdd.at(x);- if (s.contains("sceneIcons") && s.endsWith(".png")) {- int lastIndex = s.lastIndexOf(QRegExp("\\\\|/"));+ if (s.contains(QLatin1String("sceneIcons")) &&+ s.endsWith(QLatin1String(".png"))) {+ int lastIndex =+ s.lastIndexOf(QRegularExpression(QStringLiteral("[\\\\/]")));while (lastIndex != -1) {s = s.left(lastIndex);- if (!oldFilesAndResources.contains(s) && s != "..")+ if (!oldFilesAndResources.contains(s) && s != QLatin1String(".."))oldFilesAndResources.append(s);- lastIndex = s.lastIndexOf(QRegExp("\\\\|/"));+ lastIndex =+ s.lastIndexOf(QRegularExpression(QStringLiteral("[\\\\/]")));}}}@@ -404,7 +418,7 @@ void SVNCommitDialog::onAddDone() {m_textLabel->setText(tr("Committing %1 items...").arg(QString::number(fileToCommitCount - m_sceneIconAdded)));- // Then we commits changes (add, remove, modified files)+ // Then we commit changes (add, remove, modified files)commitFiles();}}@@ -413,12 +427,12 @@ void SVNCommitDialog::onAddDone() {void SVNCommitDialog::onCommitDone() {m_waitingLabel->hide();- m_textLabel->setText(tr("Put done successfully."));+ m_textLabel->setText(tr("Commit completed successfully."));if (m_targetTempFile) {QFile::remove(m_targetTempFile->fileName());delete m_targetTempFile;- m_targetTempFile = 0;+ m_targetTempFile = nullptr;}QStringList files;@@ -435,19 +449,20 @@ void SVNCommitDialog::onSetPropertyDone() {if (m_targetTempFile) {QFile::remove(m_targetTempFile->fileName());delete m_targetTempFile;- m_targetTempFile = 0;+ m_targetTempFile = nullptr;}if (m_filesToCommit.size() + m_sceneResourcesToCommit.size() > 0) {- int putCount = m_filesToCommit.size() - m_sceneIconAdded - m_folderAdded;+ int commitCount = m_filesToCommit.size() - m_sceneIconAdded - m_folderAdded;for (int i = 0; i < m_sceneResourcesToCommit.size(); i++) {- if (m_filesToCommit.contains(m_sceneResourcesToCommit.at(i))) putCount--;+ if (m_filesToCommit.contains(m_sceneResourcesToCommit.at(i)))+ commitCount--;}m_textLabel->setText(- tr("Putting %1 items...").arg(QString::number(putCount)));+ tr("Committing %1 items...").arg(QString::number(commitCount)));}- // Then we commits changes (add, remove, modified files)+ // Then we commit changes (add, remove, modified files)commitFiles();}@@ -457,7 +472,8 @@ void SVNCommitDialog::onResourcesStatusRetrieved(const QString &xmlResponse) {SVNStatusReader sr(xmlResponse);m_status = sr.getStatus();- m_thread.disconnect(SIGNAL(statusRetrieved(const QString &)));+ QObject::disconnect(&m_thread, &VersionControlThread::statusRetrieved, this,+ nullptr);checkFiles(true);@@ -472,19 +488,20 @@ void SVNCommitDialog::onStatusRetrieved(const QString &xmlResponse) {m_status = sr.getStatus();int height = 160;- m_thread.disconnect(SIGNAL(statusRetrieved(const QString &)));+ QObject::disconnect(&m_thread, &VersionControlThread::statusRetrieved, this,+ nullptr);checkFiles(m_folderOnly);if (!m_folderOnly) {// Add, if necessary the scene icons: only when the folder "sceneIcons" is- // unversioned the status- // doesn't contains the scene icon information, so I added here manually...+ // unversioned the status doesn't contain the scene icon information, so we+ // add here manually...if (m_sceneIconAdded != 0) {for (int i = 0; i < m_files.size(); i++) {QString s = m_files.at(i);- if (s.contains("sceneIcons") && s.endsWith(".png") &&- !m_filesToAdd.contains(s))+ if (s.contains(QLatin1String("sceneIcons")) &&+ s.endsWith(QLatin1String(".png")) && !m_filesToAdd.contains(s))m_filesToAdd.append(s);}}@@ -494,16 +511,16 @@ void SVNCommitDialog::onStatusRetrieved(const QString &xmlResponse) {int filesToPutCount = m_filesToPut.size();if (filesToPutCount == 0) {- m_textLabel->setText(tr("No items to put."));+ m_textLabel->setText(tr("No items to commit."));switchToCloseButton();} else {m_textLabel->setText(- tr("%1 items to put.").arg(filesToPutCount - m_sceneIconAdded));+ tr("%1 items to commit.").arg(filesToPutCount - m_sceneIconAdded));initTreeWidget();for (int i = 0; i < filesToPutCount; i++) {- if (m_filesToPut.at(i).endsWith(".tnz")) {+ if (m_filesToPut.at(i).endsWith(QLatin1String(".tnz"))) {m_commitSceneContentsCheckBox->show();break;}@@ -522,15 +539,15 @@ void SVNCommitDialog::onStatusRetrieved(const QString &xmlResponse) {return;}- if (m_items.size() == 0) {- m_textLabel->setText(tr("No items to put."));+ if (m_items.isEmpty()) {+ m_textLabel->setText(tr("No items to commit."));switchToCloseButton();} else {if (m_folderOnly) {updateTreeSelectionLabel();- connect(m_treeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this,- SLOT(onItemChanged(QTreeWidgetItem *)));+ connect(m_treeWidget, &QTreeWidget::itemChanged, this,+ &SVNCommitDialog::onItemChanged);m_treeWidget->show();m_selectionCheckBox->show();m_selectionLabel->show();@@ -555,15 +572,15 @@ void SVNCommitDialog::onStatusRetrievedAfterAdd(const QString &xmlResponse) {SVNStatusReader sr(xmlResponse);QList<SVNStatus> status = sr.getStatus();- m_thread.disconnect(SIGNAL(statusRetrieved(const QString &)));+ QObject::disconnect(&m_thread, &VersionControlThread::statusRetrieved, this,+ nullptr);int statusCount = status.size();for (int i = 0; i < statusCount; i++) {SVNStatus s = status.at(i);- if (s.m_item == "added") {- // Pay attention: the svn:needs-lock property (or any property) cannot be- // set on folders- // Remove folder from files to Add+ if (s.m_item == QLatin1String("added")) {+ // Note: the svn:needs-lock property (or any property) cannot be set on+ // folders Remove folder from files to AddQFileInfo fi(s.m_path);if (fi.isAbsolute()) {if (fi.isFile()) m_filesAdded.append(s.m_path);@@ -590,16 +607,18 @@ void SVNCommitDialog::checkFiles(bool isExternalFiles) {int statusCount = m_status.size();for (int i = 0; i < statusCount; i++) {SVNStatus s = m_status.at(i);- if (s.m_path == "." || s.m_path == "..") continue;- if (s.m_item == "unversioned") {+ if (s.m_path == QLatin1String(".") || s.m_path == QLatin1String(".."))+ continue;+ if (s.m_item == QLatin1String("unversioned")) {if (isExternalFiles || m_files.contains(s.m_path)) {if (m_folderOnly)addUnversionedItem(s.m_path);elsem_filesToAdd.append(s.m_path);}- } else if (s.m_item != "normal" && s.m_item != "incomplete" &&- s.m_item != "missing") {+ } else if (s.m_item != QLatin1String("normal") &&+ s.m_item != QLatin1String("incomplete") &&+ s.m_item != QLatin1String("missing")) {if (isExternalFiles || m_files.contains(s.m_path)) {if (m_folderOnly)addModifiedItem(s.m_path);@@ -613,18 +632,19 @@ void SVNCommitDialog::checkFiles(bool isExternalFiles) {//-----------------------------------------------------------------------------void SVNCommitDialog::addUnversionedItem(const QString &relativePath) {- // Split the string in order to recreate the hierarchy- QStringList list = relativePath.split(QRegExp("\\\\|/"));+ // Split the string to recreate the hierarchy+ QStringList list =+ relativePath.split(QRegularExpression(QStringLiteral("[\\\\/]")));- QTreeWidgetItem *parent = 0;- QString tempString = "";+ QTreeWidgetItem *parent = nullptr;+ QString tempString;QIcon folderIcon = QIcon(createQIcon("folder_vc", true));int levelCount = list.count();for (int i = 0; i < levelCount; i++) {i == 0 ? tempString.append(list.at(i))- : tempString.append("/" + list.at(i));+ : tempString.append('/' + list.at(i));if (m_items.contains(tempString))parent = m_items.value(tempString);else {@@ -692,14 +712,15 @@ void SVNCommitDialog::addUnversionedFolders(const QDir &dir,addUnversionedFolders(dir2, relativePath + "/" + entry);}- QStringList list = (entries.at(i)).split(QRegExp("\\\\|/"));+ QStringList list =+ (entries.at(i)).split(QRegularExpression(QStringLiteral("[\\\\/]")));QTreeWidgetItem *parent = m_items[relativePath];QString tempString = relativePath;int levelCount = list.count();for (int l = 0; l < levelCount; l++) {- tempString.append("/" + list.at(l));+ tempString.append('/' + list.at(l));if (m_items.contains(tempString))parent = m_items.value(tempString);else {@@ -725,11 +746,12 @@ void SVNCommitDialog::addUnversionedFolders(const QDir &dir,//-----------------------------------------------------------------------------void SVNCommitDialog::addModifiedItem(const QString &relativePath) {- // Split the string in order to recreate the hierarchy- QStringList list = relativePath.split(QRegExp("\\\\|/"));+ // Split the string to recreate the hierarchy+ QStringList list =+ relativePath.split(QRegularExpression(QStringLiteral("[\\\\/]")));- QTreeWidgetItem *parent = 0;- QString tempString = "";+ QTreeWidgetItem *parent = nullptr;+ QString tempString;QBrush brush(Qt::red);QIcon folderIcon = QIcon(createQIcon("folder_vc", true));@@ -737,7 +759,7 @@ void SVNCommitDialog::addModifiedItem(const QString &relativePath) {int levelCount = list.count();for (int i = 0; i < levelCount; i++) {i == 0 ? tempString.append(list.at(i))- : tempString.append("/" + list.at(i));+ : tempString.append('/' + list.at(i));if (m_items.contains(tempString))parent = m_items.value(tempString);else {@@ -763,8 +785,8 @@ void SVNCommitDialog::addModifiedItem(const QString &relativePath) {//-----------------------------------------------------------------------------void SVNCommitDialog::onItemChanged(QTreeWidgetItem *item) {- disconnect(m_treeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this,- SLOT(onItemChanged(QTreeWidgetItem *)));+ disconnect(m_treeWidget, &QTreeWidget::itemChanged, this,+ &SVNCommitDialog::onItemChanged);Qt::CheckState state = item->checkState(0);@@ -775,8 +797,8 @@ void SVNCommitDialog::onItemChanged(QTreeWidgetItem *item) {selItem->setCheckState(0, state);}- connect(m_treeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this,- SLOT(onItemChanged(QTreeWidgetItem *)));+ connect(m_treeWidget, &QTreeWidget::itemChanged, this,+ &SVNCommitDialog::onItemChanged);updateTreeSelectionLabel();}@@ -827,7 +849,7 @@ void SVNCommitDialog::onError(const QString &errorString) {if (m_targetTempFile) {QFile::remove(m_targetTempFile->fileName());delete m_targetTempFile;- m_targetTempFile = 0;+ m_targetTempFile = nullptr;}m_textLabel->show();@@ -851,9 +873,8 @@ void SVNCommitDialog::initTreeWidget() {QStringList linkedFiles;- TFilePathSet::iterator it;- for (it = fpset.begin(); it != fpset.end(); ++it) {- QString fn = toQString((*it).withoutParentDir());+ for (const TFilePath &path : fpset) {+ QString fn = toQString(path.withoutParentDir());if (m_filesToPut.contains(fn)) linkedFiles.append(fn);}@@ -879,7 +900,7 @@ void SVNCommitDialog::initTreeWidget() {//------------------------------------------------------------------------------void SVNCommitDialog::onCommiSceneContentsToggled(bool checked) {+void SVNCommitDialog::onCommitSceneContentsToggled(bool checked) {if (!checked) {m_sceneResourcesToCommit.clear();} else {@@ -888,7 +909,7 @@ void SVNCommitDialog::onCommiSceneContentsToggled(bool checked) {int fileSize = m_filesToPut.count();for (int i = 0; i < fileSize; i++) {QString fileName = m_filesToPut.at(i);- if (fileName.endsWith(".tnz")) {+ if (fileName.endsWith(QLatin1String(".tnz"))) {QStringList sceneContents =vc->getSceneContents(m_workingDir, fileName);QDir workingDir(m_workingDir);@@ -900,7 +921,7 @@ void SVNCommitDialog::onCommiSceneContentsToggled(bool checked) {}}}- m_textLabel->setText(tr("%1 items to put.")+ m_textLabel->setText(tr("%1 items to commit.").arg(m_filesToPut.size() +m_sceneResourcesToCommit.size() -m_sceneIconAdded));@@ -917,13 +938,13 @@ SVNCommitFrameRangeDialog::SVNCommitFrameRangeDialog(QWidget *parent,, m_workingDir(workingDir), m_file(file), m_hasError(false)- , m_hookFileName(QString())- , m_newHookFileName(QString())- , m_isOVLLevel(false) {+ , m_isOVLLevel(false)+ , m_scene(nullptr)+ , m_level(nullptr) {setModal(false);setAttribute(Qt::WA_DeleteOnClose, true);- setWindowTitle(tr("Version Control: Put"));+ setWindowTitle(tr("Version Control: Commit Frame Range"));setMinimumSize(350, 150);QWidget *container = new QWidget;@@ -934,9 +955,9 @@ SVNCommitFrameRangeDialog::SVNCommitFrameRangeDialog(QWidget *parent,QHBoxLayout *hLayout = new QHBoxLayout;- m_waitingLabel = new QLabel;- QMovie *waitingMove = new QMovie(":Resources/waiting.gif");- waitingMove->setParent(this);+ m_waitingLabel = new QLabel;+ QMovie *waitingMove =+ new QMovie(QStringLiteral(":Resources/waiting.gif"), QByteArray(), this);m_waitingLabel->hide();@@ -975,7 +996,7 @@ SVNCommitFrameRangeDialog::SVNCommitFrameRangeDialog(QWidget *parent,addWidget(container, false);endHLayout();- // Check if the hook file still exist+ // Check if the hook file still existsTFilePath path =TFilePath(m_workingDir.toStdWString()) + m_file.toStdWString();TFilePath hookFile = TXshSimpleLevel::getExistingHookFile(path);@@ -986,24 +1007,26 @@ SVNCommitFrameRangeDialog::SVNCommitFrameRangeDialog(QWidget *parent,m_isOVLLevel = path.getDots() == "..";- m_commitButton = new QPushButton(tr("Put"));- connect(m_commitButton, SIGNAL(clicked()), this, SLOT(onPutButtonClicked()));+ m_commitButton = new QPushButton(tr("Commit"));+ connect(m_commitButton, &QPushButton::clicked, this,+ &SVNCommitFrameRangeDialog::onCommitButtonClicked);m_cancelButton = new QPushButton(tr("Cancel"));- connect(m_cancelButton, SIGNAL(clicked()), this, SLOT(reject()));+ connect(m_cancelButton, &QPushButton::clicked, this,+ &SVNCommitFrameRangeDialog::reject);addButtonBarWidget(m_commitButton, m_cancelButton);// 0. Connect for svn errors (that may occur)- connect(&m_thread, SIGNAL(error(const QString &)), this,- SLOT(onError(const QString &)));+ connect(&m_thread, &VersionControlThread::error, this,+ &SVNCommitFrameRangeDialog::onError);}//-----------------------------------------------------------------------------void SVNCommitFrameRangeDialog::onCommitDone() {m_waitingLabel->hide();- m_textLabel->setText(tr("Put done successfully."));+ m_textLabel->setText(tr("Commit completed successfully."));QStringList files;files.append(m_file);@@ -1029,13 +1052,14 @@ void SVNCommitFrameRangeDialog::onUpdateDone() {// Step 2: LockQStringList args;- args << "lock";+ args << QStringLiteral("lock");if (!m_isOVLLevel) args << m_file;if (!m_hookFileName.isEmpty()) args << m_hookFileName;- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), this, SLOT(onLockDone()));- m_thread.executeCommand(m_workingDir, "svn", args, false);+ QObject::disconnect(&m_thread, &VersionControlThread::done, this, nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitFrameRangeDialog::onLockDone);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args, false);}//-----------------------------------------------------------------------------@@ -1050,15 +1074,15 @@ void SVNCommitFrameRangeDialog::onLockDone() {// Step 3: propgetQStringList args;- args << "proplist";+ args << QStringLiteral("proplist");args << m_file;- args << "--xml";- args << "-v";+ args << QStringLiteral("--xml");+ args << QStringLiteral("-v");- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), this,- SLOT(onPropGetDone(const QString &)));- m_thread.executeCommand(m_workingDir, "svn", args, true);+ QObject::disconnect(&m_thread, &VersionControlThread::done, this, nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitFrameRangeDialog::onPropGetDone);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args, true);}//-----------------------------------------------------------------------------@@ -1101,9 +1125,9 @@ void SVNCommitFrameRangeDialog::onPropGetDone(const QString &xmlResponse) {bool isMe =lockInfo.m_userName == userName && lockInfo.m_hostName == hostName;if (!isMe) {- if (i != 0) partialLockString.append(";");- partialLockString.append(lockInfo.m_userName + "@" + lockInfo.m_hostName +- ":" + QString::number(lockInfo.m_from) + ":" ++ if (i != 0) partialLockString.append(';');+ partialLockString.append(lockInfo.m_userName + '@' + lockInfo.m_hostName ++ ':' + QString::number(lockInfo.m_from) + ':' +QString::number(lockInfo.m_to));entryAdded++;} else@@ -1116,50 +1140,50 @@ void SVNCommitFrameRangeDialog::onPropGetDone(const QString &xmlResponse) {if (entryAdded == 0) {// Step 4: propdelQStringList args;- args << "propdel";- args << "partial-lock";+ args << QStringLiteral("propdel");+ args << QStringLiteral("partial-lock");args << m_file;- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), this,- SLOT(onPropSetDone()));- m_thread.executeCommand(m_workingDir, "svn", args, true);+ QObject::disconnect(&m_thread, &VersionControlThread::done, this, nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitFrameRangeDialog::onPropSetDone);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args, true);}// Set the partial-lock propertyelse {// Step 4: propsetQStringList args;- args << "propset";- args << "partial-lock";+ args << QStringLiteral("propset");+ args << QStringLiteral("partial-lock");args << partialLockString;args << m_file;- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), this,- SLOT(onPropSetDone()));- m_thread.executeCommand(m_workingDir, "svn", args, true);+ QObject::disconnect(&m_thread, &VersionControlThread::done, this, nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitFrameRangeDialog::onPropSetDone);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args, true);}}//-----------------------------------------------------------------------------void SVNCommitFrameRangeDialog::onPropSetDone() {- m_textLabel->setText(tr("Putting changes..."));+ m_textLabel->setText(tr("Committing changes..."));// Merge LevelTFilePath levelPath =TFilePath(m_workingDir.toStdWString()) + m_file.toStdWString();- // OVL level could only merge the temporary hook file (if exist)+ // OVL level could only merge the temporary hook file (if exists)if (m_isOVLLevel) {QDir dir(m_workingDir);- dir.setNameFilters(QStringList("*.xml"));+ dir.setNameFilters(QStringList(QStringLiteral("*.xml")));QStringList list = dir.entryList(QDir::Files | QDir::Hidden);int listCount = list.size();if (listCount > 0) {- QString prefix = QString::fromStdWString(levelPath.getWideName()) + "_" +- VersionControl::instance()->getUserName() + "_" ++ QString prefix = QString::fromStdWString(levelPath.getWideName()) + '_' ++ VersionControl::instance()->getUserName() + '_' +TSystem::getHostName();QString tempFile;@@ -1169,18 +1193,18 @@ void SVNCommitFrameRangeDialog::onPropSetDone() {if (str.startsWith(prefix)) {hookFileName = str;tempFile = QString(hookFileName);- tempFile.remove("_hooks");+ tempFile.remove(QStringLiteral("_hooks"));break;}}- QStringList temp = tempFile.split("_");+ QStringList temp = tempFile.split('_');if (temp.size() >= 4) {QString frameRangeString = temp.at(3);- frameRangeString = frameRangeString.left(frameRangeString.indexOf("."));+ frameRangeString = frameRangeString.left(frameRangeString.indexOf('.'));- QStringList rangeString = frameRangeString.split("-");+ QStringList rangeString = frameRangeString.split('-');if (rangeString.size() == 2) {TFilePath hookFile =levelPath.getParentDir() + hookFileName.toStdWString();@@ -1196,7 +1220,7 @@ void SVNCommitFrameRangeDialog::onPropSetDone() {m_level->setDirtyFlag(true);m_level->save();delete m_scene;- m_scene = 0;+ m_scene = nullptr;}}}@@ -1207,18 +1231,18 @@ void SVNCommitFrameRangeDialog::onPropSetDone() {m_level->setDirtyFlag(true);m_level->save();delete m_scene;- m_scene = 0;+ m_scene = nullptr;// Delete temporary fileQString tempFileName = QString::fromStdWString(levelPath.getWideName()) +- "_" + m_myInfo.m_userName + "_" +- m_myInfo.m_hostName + "_" +- QString::number(m_myInfo.m_from) + "-" +- QString::number(m_myInfo.m_to) + "." ++ '_' + m_myInfo.m_userName + '_' ++ m_myInfo.m_hostName + '_' ++ QString::number(m_myInfo.m_from) + '-' ++ QString::number(m_myInfo.m_to) + '.' +QString::fromStdString(levelPath.getType());TFilePath pathToRemove =- TFilePath(levelPath.getParentDir() + tempFileName.toStdWString());+ levelPath.getParentDir() + tempFileName.toStdWString();if (TSystem::doesExistFileOrLevel(pathToRemove))TSystem::removeFileOrLevel(pathToRemove);if (pathToRemove.getType() == "tlv") {@@ -1234,11 +1258,10 @@ void SVNCommitFrameRangeDialog::onPropSetDone() {}// If, after saving the level, a new hook file has been created (and- // previously there isn't an hook file)- // we have to add the new hook file to the repository and set its needs-lock- // property before committing+ // previously there wasn't a hook file) we have to add the new hook file to+ // the repository and set its needs-lock property before committingif (m_hookFileName.isEmpty()) {- // Check if a new hook file exist+ // Check if a new hook file existsTFilePath path =TFilePath(m_workingDir.toStdWString()) + m_file.toStdWString();TFilePath hookFile = TXshSimpleLevel::getHookPath(path);@@ -1250,14 +1273,15 @@ void SVNCommitFrameRangeDialog::onPropSetDone() {// Step 4a: Add hookFile to repositoryQStringList args;- args << "add";- args << "--parents";+ args << QStringLiteral("add");+ args << QStringLiteral("--parents");args << m_newHookFileName;- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), this,- SLOT(onHookFileAdded()));- m_thread.executeCommand(m_workingDir, "svn", args, true);+ QObject::disconnect(&m_thread, &VersionControlThread::done, this,+ nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitFrameRangeDialog::onHookFileAdded);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args, true);} elsecommit();} else@@ -1270,20 +1294,20 @@ void SVNCommitFrameRangeDialog::onHookFileAdded() {m_textLabel->setText(tr("Setting the needs-lock property to hook file..."));// Step 4b: set needs-lock propertyQStringList args;- args << "propset"- << "svn:needs-lock"- << "'*'";+ args << QStringLiteral("propset") << QStringLiteral("svn:needs-lock")+ << QStringLiteral("'*'");args << m_newHookFileName;- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), SLOT(commit()));- m_thread.executeCommand(m_workingDir, "svn", args);+ QObject::disconnect(&m_thread, &VersionControlThread::done, this, nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitFrameRangeDialog::commit);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args);}//-----------------------------------------------------------------------------void SVNCommitFrameRangeDialog::commit() {- m_textLabel->setText(tr("Putting changes..."));+ m_textLabel->setText(tr("Committing changes..."));// Explode, if needed the m_file (OVL)TFilePath path =@@ -1292,10 +1316,10 @@ void SVNCommitFrameRangeDialog::commit() {TFilePath dir = path.getParentDir();QDir qDir(QString::fromStdWString(dir.getWideString()));QString levelName =- QRegExp::escape(QString::fromStdWString(path.getWideName()));+ QRegularExpression::escape(QString::fromStdWString(path.getWideName()));QString levelType = QString::fromStdString(path.getType());- QString exp(levelName + ".[0-9]{1,4}." + levelType);- QRegExp regExp(exp);+ QString exp(levelName + "\\.[0-9]{1,4}\\." + levelType);+ QRegularExpression regExp(exp);QStringList list = qDir.entryList(QDir::Files);m_filesToCommit = list.filter(regExp);} else@@ -1309,25 +1333,27 @@ void SVNCommitFrameRangeDialog::commit() {// Step 5: commitQStringList args;- args << "commit";+ args << QStringLiteral("commit");int size = m_filesToCommit.size();for (int i = 0; i < size; i++) args << m_filesToCommit.at(i);// Commentif (!m_commentTextEdit->toPlainText().isEmpty())- args << QString("-m").append(m_commentTextEdit->toPlainText());+ args << QStringLiteral("-m").append(m_commentTextEdit->toPlainText());else- args << QString("-m").append(VersionControl::instance()->getUserName() +- " commit changes.");-- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), this, SLOT(onCommitDone()));- m_thread.executeCommand(m_workingDir, "svn", args, true);+ args << QStringLiteral("-m").append(+ VersionControl::instance()->getUserName() ++ QStringLiteral(" commit changes."));++ QObject::disconnect(&m_thread, &VersionControlThread::done, this, nullptr);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitFrameRangeDialog::onCommitDone);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args, true);}//------------------------------------------------------------------------------void SVNCommitFrameRangeDialog::onPutButtonClicked() {+void SVNCommitFrameRangeDialog::onCommitButtonClicked() {m_commentLabel->hide();m_commentTextEdit->hide();@@ -1341,12 +1367,13 @@ void SVNCommitFrameRangeDialog::onPutButtonClicked() {// Step 1: UpdateQStringList args;- args << "update";+ args << QStringLiteral("update");if (!m_isOVLLevel) args << m_file;if (!m_hookFileName.isEmpty()) args << m_hookFileName;- connect(&m_thread, SIGNAL(done(const QString &)), this, SLOT(onUpdateDone()));- m_thread.executeCommand(m_workingDir, "svn", args, false);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNCommitFrameRangeDialog::onUpdateDone);+ m_thread.executeCommand(m_workingDir, QStringLiteral("svn"), args, false);}//-----------------------------------------------------------------------------@@ -1354,11 +1381,10 @@ void SVNCommitFrameRangeDialog::onPutButtonClicked() {void SVNCommitFrameRangeDialog::switchToCloseButton() {m_waitingLabel->hide();m_commitButton->disconnect();- m_commitButton->setText("Close");+ m_commitButton->setText(tr("Close"));m_commitButton->setEnabled(true);m_commitButton->show();m_cancelButton->hide();- connect(m_commitButton, SIGNAL(clicked()), this, SLOT(close()));+ connect(m_commitButton, &QPushButton::clicked, this,+ &SVNCommitFrameRangeDialog::close);}--//-----------------------------------------------------------------------------diff --git a/toonz/sources/toonz/svncommitdialog.h b/toonz/sources/toonz/svncommitdialog.hindex 60df92dd1..a367bfec0 100644--- a/toonz/sources/toonz/svncommitdialog.h+++ b/toonz/sources/toonz/svncommitdialog.h@@ -71,7 +71,7 @@ class SVNCommitDialog final : public DVGui::Dialog {public:SVNCommitDialog(QWidget *parent, const QString &workingDir,const QStringList &files, bool folderOnly = false,- int m_sceneIconAdded = 0);+ int sceneIconAdded = 0); // Fixed parameter namevoid checkFiles(bool isExternalFiles = false);@@ -91,7 +91,7 @@ private:void initTreeWidget();-protected slots:+private slots: // Changed from protected slots to private slotsvoid onCommitButtonClicked();@@ -108,7 +108,8 @@ protected slots:void onStatusRetrievedAfterAdd(const QString &);void onResourcesStatusRetrieved(const QString &);- void onCommiSceneContentsToggled(bool);+ void onCommitSceneContentsToggled(+ bool); // Fixed typo: was onCommiSceneContentsToggledsignals:void done(const QStringList &);@@ -155,17 +156,16 @@ public:private:void switchToCloseButton();+ void commit(); // Added private method declaration-protected slots:+private slots: // Changed from protected slots to private slotsvoid onError(const QString &);void onPropGetDone(const QString &);void onPropSetDone();void onHookFileAdded();- void onPutButtonClicked();-- void commit();+ void onCommitButtonClicked(); // Renamed from onPutButtonClickedvoid onCommitDone();void onUpdateDone();diff --git a/toonz/sources/toonz/svnrevertdialog.cpp b/toonz/sources/toonz/svnrevertdialog.cppindex b6362912c..63411fbc0 100644--- a/toonz/sources/toonz/svnrevertdialog.cpp+++ b/toonz/sources/toonz/svnrevertdialog.cpp@@ -23,8 +23,9 @@#include <QMovie>#include <QLabel>#include <QDir>-#include <QRegExp>+#include <QRegularExpression>#include <QMainWindow>+#include <memory>//=============================================================================// SVNRevertDialog@@ -36,55 +37,60 @@ SVNRevertDialog::SVNRevertDialog(QWidget *parent, const QString &workingDir,: Dialog(TApp::instance()->getMainWindow(), true, false), m_workingDir(workingDir), m_files(files)- , m_revertSceneContentsCheckBox(0), m_folderOnly(folderOnly), m_sceneIconAdded(sceneIconAdded) {+ // Set dialog propertiessetModal(false);setMinimumSize(300, 150);setAttribute(Qt::WA_DeleteOnClose, true);setWindowTitle(tr("Version Control: Revert changes"));- QWidget *container = new QWidget;-- QVBoxLayout *mainLayout = new QVBoxLayout;+ // Create main container+ auto container = new QWidget(this);+ auto mainLayout = new QVBoxLayout;mainLayout->setAlignment(Qt::AlignHCenter);mainLayout->setContentsMargins(0, 0, 0, 0);- QHBoxLayout *hLayout = new QHBoxLayout;-- m_waitingLabel = new QLabel;- QMovie *waitingMove = new QMovie(":Resources/waiting.gif");- waitingMove->setParent(this);+ // Create waiting layout+ auto hLayout = new QHBoxLayout;+ m_waitingLabel = new QLabel(this);- m_waitingLabel->setMovie(waitingMove);- waitingMove->setCacheMode(QMovie::CacheAll);- waitingMove->start();+ // Use smart pointer for QMovie with proper parent ownership+ auto waitingMovie = new QMovie(":Resources/waiting.gif", QByteArray(), this);+ m_waitingLabel->setMovie(waitingMovie);+ waitingMovie->setCacheMode(QMovie::CacheAll);+ waitingMovie->start();- m_textLabel = new QLabel(tr("Getting repository status..."));+ m_textLabel = new QLabel(tr("Getting repository status..."), this);hLayout->addStretch();hLayout->addWidget(m_waitingLabel);hLayout->addWidget(m_textLabel);hLayout->addStretch();-mainLayout->addLayout(hLayout);- m_treeWidget = new QTreeWidget;+ // Create tree widget+ m_treeWidget = new QTreeWidget(this);m_treeWidget->setStyleSheet("QTreeWidget { border: 1px solid gray; }");m_treeWidget->header()->hide();m_treeWidget->hide();mainLayout->addWidget(m_treeWidget);+ // Create revert scene contents checkbox if not folder onlyif (!m_folderOnly) {mainLayout->addSpacing(10);- QHBoxLayout *checkBoxLayout = new QHBoxLayout;+ auto checkBoxLayout = new QHBoxLayout;checkBoxLayout->setContentsMargins(0, 0, 0, 0);- m_revertSceneContentsCheckBox = new QCheckBox(this);- connect(m_revertSceneContentsCheckBox, SIGNAL(toggled(bool)), this,- SLOT(onRevertSceneContentsToggled(bool)));++ m_revertSceneContentsCheckBox =+ new QCheckBox(tr("Revert Scene Contents"), this);m_revertSceneContentsCheckBox->setChecked(false);m_revertSceneContentsCheckBox->hide();- m_revertSceneContentsCheckBox->setText(tr("Revert Scene Contents"));++ // Modern signal/slot connection+ connect(m_revertSceneContentsCheckBox, &QCheckBox::toggled, this,+ &SVNRevertDialog::onRevertSceneContentsToggled);+checkBoxLayout->addStretch();checkBoxLayout->addWidget(m_revertSceneContentsCheckBox);checkBoxLayout->addStretch();@@ -93,81 +99,101 @@ SVNRevertDialog::SVNRevertDialog(QWidget *parent, const QString &workingDir,container->setLayout(mainLayout);+ // Add container to dialogbeginHLayout();addWidget(container, false);endHLayout();- m_revertButton = new QPushButton(tr("Revert"));+ // Create buttons+ m_revertButton = new QPushButton(tr("Revert"), this);m_revertButton->setEnabled(false);- connect(m_revertButton, SIGNAL(clicked()), this,- SLOT(onRevertButtonClicked()));+ connect(m_revertButton, &QPushButton::clicked, this,+ &SVNRevertDialog::onRevertButtonClicked);- m_cancelButton = new QPushButton(tr("Cancel"));- connect(m_cancelButton, SIGNAL(clicked()), this, SLOT(reject()));+ m_cancelButton = new QPushButton(tr("Cancel"), this);+ connect(m_cancelButton, &QPushButton::clicked, this,+ &SVNRevertDialog::reject);addButtonBarWidget(m_revertButton, m_cancelButton);- // 0. Connect for svn errors (that may occur every time)- connect(&m_thread, SIGNAL(error(const QString &)), this,- SLOT(onError(const QString &)));+ // Connect SVN thread signals using modern syntax+ // Connect for svn errors (that may occur every time)+ connect(&m_thread, &VersionControlThread::error, this,+ &SVNRevertDialog::onError);++ // Connect for status retrieval+ connect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNRevertDialog::onStatusRetrieved);- // 1. Getting status- connect(&m_thread, SIGNAL(statusRetrieved(const QString &)), this,- SLOT(onStatusRetrieved(const QString &)));+ // Start getting SVN statusm_thread.getSVNStatus(m_workingDir);}//-----------------------------------------------------------------------------void SVNRevertDialog::onStatusRetrieved(const QString &xmlResponse) {+ // Parse SVN status from XML responseSVNStatusReader sr(xmlResponse);- m_status = sr.getStatus();+ m_status = sr.getStatus();++ // Calculate initial heightint height = 50;+ // Check which files need to be revertedcheckFiles();- int fileSize = m_filesToRevert.size();- for (int i = 0; i < fileSize; i++) {- if (m_filesToRevert.at(i).endsWith(".tnz")) {- if (m_revertSceneContentsCheckBox) m_revertSceneContentsCheckBox->show();- break;+ // Show revert scene contents checkbox if .tnz files are found+ if (std::any_of(m_filesToRevert.begin(), m_filesToRevert.end(),+ [](const QString &file) { return file.endsWith(".tnz"); })) {+ if (m_revertSceneContentsCheckBox) {+ m_revertSceneContentsCheckBox->show();}}+ // Initialize tree widget with linked filesinitTreeWidget();- if (m_filesToRevert.size() == 0) {- QString msg = QString(tr("No items to revert."));- m_textLabel->setText(msg);+ // Handle case where no items need to be reverted+ if (m_filesToRevert.isEmpty()) {+ m_textLabel->setText(tr("No items to revert."));switchToCloseButton();} else {- if (m_treeWidget->isVisible()) height += (m_filesToRevert.size() * 50);+ // Adjust dialog size based on number of items+ if (m_treeWidget->isVisible()) {+ height += (m_filesToRevert.size() * 50);+ }setMinimumSize(300, std::min(height, 350));- QString msg = QString(tr("%1 items to revert."))- .arg(m_filesToRevert.size() == 1- ? 1- : m_filesToRevert.size() - m_sceneIconAdded);- m_textLabel->setText(msg);+ // Update status text+ const int itemCount = m_filesToRevert.size() - m_sceneIconAdded;+ m_textLabel->setText(+ tr("%1 items to revert.").arg(itemCount == 1 ? 1 : itemCount));+ // Hide waiting animation and enable revert buttonm_waitingLabel->hide();m_revertButton->setEnabled(true);- m_thread.disconnect(SIGNAL(statusRetrieved(const QString &)));+ // Disconnect status retrieved signal since we're done+ disconnect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNRevertDialog::onStatusRetrieved);}}//-----------------------------------------------------------------------------void SVNRevertDialog::checkFiles() {- int statusCount = m_status.size();- for (int i = 0; i < statusCount; i++) {- SVNStatus s = m_status.at(i);- if (s.m_path == "." || s.m_path == "..") continue;- if (s.m_item != "normal" && s.m_item != "unversioned") {- if (m_folderOnly || m_files.contains(s.m_path))- m_filesToRevert.append(s.m_path);+ // Filter files that need to be reverted based on SVN status+ for (const auto &status : m_status) {+ if (status.m_path == "." || status.m_path == "..") {+ continue;+ }++ // Check if file is not in normal or unversioned state+ if (status.m_item != "normal" && status.m_item != "unversioned") {+ if (m_folderOnly || m_files.contains(status.m_path)) {+ m_filesToRevert.append(status.m_path);+ }}}}@@ -175,12 +201,13 @@ void SVNRevertDialog::checkFiles() {//-----------------------------------------------------------------------------void SVNRevertDialog::initTreeWidget() {- int filesSize = m_filesToRevert.size();+ // Clear existing items+ m_treeWidget->clear();bool itemAdded = false;- for (int i = 0; i < filesSize; i++) {- QString fileName = m_filesToRevert.at(i);+ // Group linked files in tree widget+ for (const auto &fileName : m_filesToRevert) {TFilePath fp =TFilePath(m_workingDir.toStdWString()) + fileName.toStdWString();TFilePathSet fpset;@@ -188,97 +215,121 @@ void SVNRevertDialog::initTreeWidget() {QStringList linkedFiles;- TFilePathSet::iterator it;- for (it = fpset.begin(); it != fpset.end(); ++it) {- QString fn = toQString((*it).withoutParentDir());+ // Find linked files that are also in the revert list+ for (const auto &linkedFp : fpset) {+ QString fn = toQString(linkedFp.withoutParentDir());- if (m_filesToRevert.contains(fn)) linkedFiles.append(fn);+ if (m_filesToRevert.contains(fn)) {+ linkedFiles.append(fn);+ }}+ // Create tree widget item for file with linked childrenif (!linkedFiles.isEmpty()) {- itemAdded = true;- QTreeWidgetItem *twi = new QTreeWidgetItem(m_treeWidget);- twi->setText(0, fileName);- twi->setFirstColumnSpanned(false);- twi->setFlags(Qt::NoItemFlags);-- for (int i = 0; i < linkedFiles.size(); i++) {- QTreeWidgetItem *child = new QTreeWidgetItem(twi);- child->setText(0, linkedFiles.at(i));- child->setFlags(Qt::NoItemFlags);+ itemAdded = true;+ auto parentItem = new QTreeWidgetItem(m_treeWidget);+ parentItem->setText(0, fileName);+ parentItem->setFirstColumnSpanned(false);+ parentItem->setFlags(Qt::NoItemFlags);++ for (const auto &linkedFile : linkedFiles) {+ auto childItem = new QTreeWidgetItem(parentItem);+ childItem->setText(0, linkedFile);+ childItem->setFlags(Qt::NoItemFlags);}- twi->setExpanded(true);++ parentItem->setExpanded(true);}}- if (itemAdded) m_treeWidget->show();+ // Show tree widget if items were added+ if (itemAdded) {+ m_treeWidget->show();+ }}//-----------------------------------------------------------------------------void SVNRevertDialog::switchToCloseButton() {+ // Hide waiting animation and tree widgetm_waitingLabel->hide();m_treeWidget->hide();++ // Disconnect revert button and change to close functionalitym_revertButton->disconnect();- m_revertButton->setText("Close");+ m_revertButton->setText(tr("Close"));m_revertButton->setEnabled(true);++ // Hide cancel buttonm_cancelButton->hide();- connect(m_revertButton, SIGNAL(clicked()), this, SLOT(close()));++ // Connect close functionality+ connect(m_revertButton, &QPushButton::clicked, this, &SVNRevertDialog::close);}//-----------------------------------------------------------------------------void SVNRevertDialog::onRevertButtonClicked() {+ // Disable revert button to prevent multiple clicksm_revertButton->setEnabled(false);++ // Start revert processrevertFiles();}//-----------------------------------------------------------------------------void SVNRevertDialog::revertFiles() {+ // Hide UI elements and show waiting animationm_treeWidget->hide();- if (m_revertSceneContentsCheckBox) m_revertSceneContentsCheckBox->hide();+ if (m_revertSceneContentsCheckBox) {+ m_revertSceneContentsCheckBox->hide();+ }m_waitingLabel->show();- int fileToRevertSize = m_filesToRevert.size();- int sceneResourceToRevertSize = m_sceneResources.size();- int totalFilesToRevert = fileToRevertSize + sceneResourceToRevertSize;- if (totalFilesToRevert > 0) {- m_textLabel->setText(tr("Reverting %1 items...")- .arg(totalFilesToRevert == 1- ? 1- : totalFilesToRevert - m_sceneIconAdded));+ // Calculate total files to revert+ const int totalFilesToRevert =+ m_filesToRevert.size() + m_sceneResources.size();- QStringList args;- args << "revert";+ if (totalFilesToRevert > 0) {+ // Update status text+ const int displayCount = totalFilesToRevert - m_sceneIconAdded;+ m_textLabel->setText(+ tr("Reverting %1 items...").arg(displayCount == 1 ? 1 : displayCount));- for (int i = 0; i < fileToRevertSize; i++) args << m_filesToRevert.at(i);+ // Prepare SVN revert command arguments+ QStringList args = {"revert"};+ args.append(m_filesToRevert);+ args.append(m_sceneResources);- for (int i = 0; i < sceneResourceToRevertSize; i++)- args << m_sceneResources.at(i);+ // Connect done signal and execute command+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNRevertDialog::onRevertDone);- connect(&m_thread, SIGNAL(done(const QString &)), SLOT(onRevertDone()));m_thread.executeCommand(m_workingDir, "svn", args);- } else+ } else {+ // No files to revertonRevertDone();+ }}//-----------------------------------------------------------------------------void SVNRevertDialog::onRevertDone() {+ // Update status textm_textLabel->setText(tr("Revert done successfully."));- QStringList files;- for (int i = 0; i < m_filesToRevert.size(); i++)- files.append(m_filesToRevert.at(i));- emit done(files);+ // Emit done signal with reverted files+ emit done(m_filesToRevert);+ // Switch to close buttonswitchToCloseButton();}//-----------------------------------------------------------------------------void SVNRevertDialog::onError(const QString &errorString) {+ // Display error and switch to close buttonm_textLabel->setText(errorString);switchToCloseButton();update();@@ -287,26 +338,28 @@ void SVNRevertDialog::onError(const QString &errorString) {//-----------------------------------------------------------------------------void SVNRevertDialog::onRevertSceneContentsToggled(bool checked) {- if (!checked)- m_sceneResources.clear();- else {- VersionControl *vc = VersionControl::instance();-- int fileSize = m_filesToRevert.count();- for (int i = 0; i < fileSize; i++) {- QString fileName = m_filesToRevert.at(i);+ // Clear or populate scene resources based on checkbox state+ m_sceneResources.clear();++ if (checked) {+ auto vc = VersionControl::instance();++ // Find .tnz files and get their scene contents+ for (const auto &fileName : m_filesToRevert) {if (fileName.endsWith(".tnz")) {- if (m_filesToRevert.contains(fileName))+ if (m_filesToRevert.contains(fileName)) {m_sceneResources.append(vc->getSceneContents(m_workingDir, fileName));+ }}}}++ // Update status text with new item count+ const int totalItems = m_filesToRevert.size() + m_sceneResources.size();+ const int displayCount = totalItems - m_sceneIconAdded;+m_textLabel->setText(- tr("%1 items to revert.")- .arg(m_filesToRevert.size() + m_sceneResources.size() == 1- ? 1- : m_filesToRevert.size() + m_sceneResources.size() -- m_sceneIconAdded));+ tr("%1 items to revert.").arg(displayCount == 1 ? 1 : displayCount));}//=============================================================================@@ -320,6 +373,7 @@ SVNRevertFrameRangeDialog::SVNRevertFrameRangeDialog(, m_workingDir(workingDir), m_file(file), m_tempFileName(tempFileName) {+ // Set dialog propertiessetModal(false);setMinimumSize(300, 150);setAttribute(Qt::WA_DeleteOnClose, true);@@ -327,27 +381,30 @@ SVNRevertFrameRangeDialog::SVNRevertFrameRangeDialog(beginVLayout();- m_waitingLabel = new QLabel;- QMovie *waitingMove = new QMovie(":Resources/waiting.gif");- waitingMove->setParent(this);+ // Create waiting animation+ m_waitingLabel = new QLabel(this);+ auto waitingMovie = new QMovie(":Resources/waiting.gif", QByteArray(), this);- m_waitingLabel->setMovie(waitingMove);- waitingMove->setCacheMode(QMovie::CacheAll);- waitingMove->start();+ m_waitingLabel->setMovie(waitingMovie);+ waitingMovie->setCacheMode(QMovie::CacheAll);+ waitingMovie->start();m_waitingLabel->hide();- m_textLabel = new QLabel(tr("1 item to revert."));+ // Create status label+ m_textLabel = new QLabel(tr("1 item to revert."), this);addWidgets(m_waitingLabel, m_textLabel);endVLayout();- m_revertButton = new QPushButton(tr("Revert"));- connect(m_revertButton, SIGNAL(clicked()), this,- SLOT(onRevertButtonClicked()));+ // Create buttons with modern signal connections+ m_revertButton = new QPushButton(tr("Revert"), this);+ connect(m_revertButton, &QPushButton::clicked, this,+ &SVNRevertFrameRangeDialog::onRevertButtonClicked);- m_cancelButton = new QPushButton(tr("Cancel"));- connect(m_cancelButton, SIGNAL(clicked()), this, SLOT(reject()));+ m_cancelButton = new QPushButton(tr("Cancel"), this);+ connect(m_cancelButton, &QPushButton::clicked, this,+ &SVNRevertFrameRangeDialog::reject);addButtonBarWidget(m_revertButton, m_cancelButton);}@@ -355,17 +412,26 @@ SVNRevertFrameRangeDialog::SVNRevertFrameRangeDialog(//-----------------------------------------------------------------------------void SVNRevertFrameRangeDialog::switchToCloseButton() {+ // Hide waiting animationm_waitingLabel->hide();++ // Change revert button to close functionalitym_revertButton->disconnect();- m_revertButton->setText("Close");+ m_revertButton->setText(tr("Close"));m_revertButton->setEnabled(true);++ // Hide cancel buttonm_cancelButton->hide();- connect(m_revertButton, SIGNAL(clicked()), this, SLOT(close()));++ // Connect close functionality+ connect(m_revertButton, &QPushButton::clicked, this,+ &SVNRevertFrameRangeDialog::close);}//-----------------------------------------------------------------------------void SVNRevertFrameRangeDialog::onRevertButtonClicked() {+ // Disable revert button and start revert processm_revertButton->setEnabled(false);revertFiles();}@@ -373,59 +439,74 @@ void SVNRevertFrameRangeDialog::onRevertButtonClicked() {//-----------------------------------------------------------------------------void SVNRevertFrameRangeDialog::revertFiles() {+ // Show waiting animation and update statusm_waitingLabel->show();m_textLabel->setText(tr("Reverting 1 item..."));+ // Remove temporary filestry {- TFilePath pathToRemove = TFilePath(m_tempFileName.toStdWString());- if (TSystem::doesExistFileOrLevel(pathToRemove))- TSystem::removeFileOrLevel(TFilePath(m_tempFileName.toStdWString()));+ TFilePath pathToRemove(m_tempFileName.toStdWString());++ if (TSystem::doesExistFileOrLevel(pathToRemove)) {+ TSystem::removeFileOrLevel(pathToRemove);+ }++ // Handle TLV/TPL file pairsif (pathToRemove.getType() == "tlv") {pathToRemove = pathToRemove.withType("tpl");- if (TSystem::doesExistFileOrLevel(pathToRemove))+ if (TSystem::doesExistFileOrLevel(pathToRemove)) {TSystem::removeFileOrLevel(pathToRemove);+ }}+ // Remove hook files if they existTFilePath hookFilePath =pathToRemove.withName(pathToRemove.getName() + "_hooks").withType("xml");- if (TSystem::doesExistFileOrLevel(hookFilePath))++ if (TSystem::doesExistFileOrLevel(hookFilePath)) {TSystem::removeFileOrLevel(hookFilePath);+ }} catch (...) {m_textLabel->setText(tr("It is not possible to revert the file."));switchToCloseButton();return;}+ // Handle frame range filesTFilePath path =TFilePath(m_workingDir.toStdWString()) + m_file.toStdWString();if (path.getDots() == "..") {+ // Get directory and prepare regular expression for frame filesTFilePath dir = path.getParentDir();QDir qDir(QString::fromStdWString(dir.getWideString()));++ // Escape level name for regex and create patternQString levelName =- QRegExp::escape(QString::fromStdWString(path.getWideName()));+ QRegularExpression::escape(QString::fromStdWString(path.getWideName()));QString levelType = QString::fromStdString(path.getType());- QString exp(levelName + ".[0-9]{1,4}." + levelType);- QRegExp regExp(exp);++ // Create regular expression for frame files+ QString pattern = QString("%1\\.[0-9]{1,4}\\.%2").arg(levelName, levelType);+ QRegularExpression regex(pattern);++ // Filter files matching the patternQStringList list = qDir.entryList(QDir::Files);- m_files = list.filter(regExp);+ m_files = list.filter(regex);- // 0. Connect for svn errors (that may occur every time)- connect(&m_thread, SIGNAL(error(const QString &)), this,- SLOT(onError(const QString &)));+ // Connect SVN thread signals using modern syntax+ connect(&m_thread, &VersionControlThread::error, this,+ &SVNRevertFrameRangeDialog::onError);+ connect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNRevertFrameRangeDialog::onStatusRetrieved);- // 1. Getting status- connect(&m_thread, SIGNAL(statusRetrieved(const QString &)), this,- SLOT(onStatusRetrieved(const QString &)));+ // Get SVN status for filtered filesm_thread.getSVNStatus(m_workingDir, m_files);} else {+ // Single file, emit done signal and switch to close buttonm_textLabel->setText(tr("Revert done successfully."));-- QStringList files;- files.append(m_file);- emit done(files);-+ emit done({m_file});switchToCloseButton();}}@@ -433,26 +514,35 @@ void SVNRevertFrameRangeDialog::revertFiles() {//-----------------------------------------------------------------------------void SVNRevertFrameRangeDialog::onStatusRetrieved(const QString &xmlResponse) {+ // Parse SVN statusSVNStatusReader sr(xmlResponse);m_status = sr.getStatus();+ // Check which files need to be revertedcheckFiles();- int fileToRevertCount = m_filesToRevert.size();+ const int fileToRevertCount = m_filesToRevert.size();if (fileToRevertCount == 0) {+ // No files to revertm_textLabel->setText(tr("Revert done successfully."));switchToCloseButton();} else {- m_thread.disconnect(SIGNAL(statusRetrieved(const QString &)));+ // Disconnect status signal and start revert process+ disconnect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNRevertFrameRangeDialog::onStatusRetrieved);+m_textLabel->setText(tr("Reverting %1 items...").arg(QString::number(fileToRevertCount)));- QStringList args;- args << "revert";- for (int i = 0; i < fileToRevertCount; i++) args << m_filesToRevert.at(i);+ // Prepare SVN revert command+ QStringList args = {"revert"};+ args.append(m_filesToRevert);++ // Connect done signal and execute command+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNRevertFrameRangeDialog::onRevertDone);- connect(&m_thread, SIGNAL(done(const QString &)), SLOT(onRevertDone()));m_thread.executeCommand(m_workingDir, "svn", args);}}@@ -460,6 +550,7 @@ void SVNRevertFrameRangeDialog::onStatusRetrieved(const QString &xmlResponse) {//-----------------------------------------------------------------------------void SVNRevertFrameRangeDialog::onError(const QString &errorString) {+ // Display error and switch to close buttonm_textLabel->setText(errorString);switchToCloseButton();update();@@ -468,11 +559,12 @@ void SVNRevertFrameRangeDialog::onError(const QString &errorString) {//-----------------------------------------------------------------------------void SVNRevertFrameRangeDialog::checkFiles() {- int statusCount = m_status.size();- for (int i = 0; i < statusCount; i++) {- SVNStatus s = m_status.at(i);- if (s.m_item != "normal" && s.m_item != "unversioned") {- if (m_files.contains(s.m_path)) m_filesToRevert.append(s.m_path);+ // Filter files that need to be reverted based on SVN status+ for (const auto &status : m_status) {+ if (status.m_item != "normal" && status.m_item != "unversioned") {+ if (m_files.contains(status.m_path)) {+ m_filesToRevert.append(status.m_path);+ }}}}@@ -480,12 +572,8 @@ void SVNRevertFrameRangeDialog::checkFiles() {//-----------------------------------------------------------------------------void SVNRevertFrameRangeDialog::onRevertDone() {+ // Update status and emit done signalm_textLabel->setText(tr("Revert done successfully."));-- QStringList files;- for (int i = 0; i < m_filesToRevert.size(); i++)- files.append(m_filesToRevert.at(i));- emit done(files);-+ emit done(m_filesToRevert);switchToCloseButton();}diff --git a/toonz/sources/toonz/svnrevertdialog.h b/toonz/sources/toonz/svnrevertdialog.hindex 777955fbc..8fc3d7ed9 100644--- a/toonz/sources/toonz/svnrevertdialog.h+++ b/toonz/sources/toonz/svnrevertdialog.h@@ -3,111 +3,222 @@#ifndef SVN_REVERT_DIALOG_H#define SVN_REVERT_DIALOG_H+// Qt includes+#include <QList>+#include <QStringList>++// ToonzQt includes#include "toonzqt/dvdialog.h"-#include "versioncontrol.h"-#include <QList>+// Version control includes+#include "versioncontrol.h"+// Forward declarationsclass QPushButton;class QTreeWidget;class QCheckBox;+class QLabel;//------------------------------------------------------------------------------+/**+ * @brief Dialog for reverting changes in version control system.+ *+ * This dialog allows users to revert changes made to files in a Subversion+ * repository. It can handle both individual files and folders, and includes+ * special handling for scene files and their linked resources.+ */class SVNRevertDialog final : public DVGui::Dialog {Q_OBJECT- QLabel *m_waitingLabel;- QLabel *m_textLabel;+ // UI Elements+ QLabel* m_waitingLabel = nullptr;+ QLabel* m_textLabel = nullptr;+ QPushButton* m_revertButton = nullptr;+ QPushButton* m_cancelButton = nullptr;+ QTreeWidget* m_treeWidget = nullptr;+ QCheckBox* m_revertSceneContentsCheckBox = nullptr;+ // Data membersQString m_workingDir;QStringList m_files;-- QPushButton *m_revertButton;- QPushButton *m_cancelButton;-- QTreeWidget *m_treeWidget;-- VersionControlThread m_thread;-- QList<SVNStatus> m_status;-- QList<QString> m_filesToRevert;+ QStringList m_filesToRevert;QStringList m_sceneResources;+ QList<SVNStatus> m_status;+ VersionControlThread m_thread;- QCheckBox *m_revertSceneContentsCheckBox;-- // Perform a revert on one or more folder- bool m_folderOnly;-- int m_sceneIconAdded;+ // Configuration+ bool m_folderOnly = false;+ int m_sceneIconAdded = 0;public:- SVNRevertDialog(QWidget *parent, const QString &workingDir,- const QStringList &files, bool folderOnly = false,- int sceneIconAdded = 0);-+ /**+ * @brief Constructs a revert dialog.+ *+ * @param parent Parent widget.+ * @param workingDir The working directory for SVN operations.+ * @param files List of files to consider for reversion.+ * @param folderOnly Whether the operation is for folders only.+ * @param sceneIconAdded Number of scene icons added (for display+ * adjustments).+ */+ explicit SVNRevertDialog(QWidget* parent, const QString& workingDir,+ const QStringList& files, bool folderOnly = false,+ int sceneIconAdded = 0);++ /**+ * @brief Checks which files need to be reverted based on SVN status.+ */void checkFiles();private:+ /**+ * @brief Switches the dialog to close mode.+ *+ * Changes the revert button to a close button and updates the UI+ * to indicate completion.+ */void switchToCloseButton();+ /**+ * @brief Initiates the revert process for selected files.+ */void revertFiles();+ /**+ * @brief Initializes the tree widget with files to revert.+ *+ * Groups linked files (like scene resources) under parent items+ * for better visualization.+ */void initTreeWidget();-protected slots:-+private slots:+ /**+ * @brief Handles revert button click event.+ */void onRevertButtonClicked();- void onRevertDone();- void onError(const QString &);- void onStatusRetrieved(const QString &);+ /**+ * @brief Handles completion of revert operation.+ */+ void onRevertDone();+ /**+ * @brief Handles SVN errors.+ *+ * @param errorString The error message from SVN.+ */+ void onError(const QString& errorString);++ /**+ * @brief Handles retrieval of SVN status.+ *+ * @param xmlResponse The XML response from SVN status command.+ */+ void onStatusRetrieved(const QString& xmlResponse);++ /**+ * @brief Handles toggle of revert scene contents checkbox.+ *+ * @param checked Whether the checkbox is checked.+ */void onRevertSceneContentsToggled(bool checked);signals:- void done(const QStringList &);+ /**+ * @brief Signal emitted when revert operation is complete.+ *+ * @param files List of files that were reverted.+ */+ void done(const QStringList& files);};//------------------------------------------------------------------------------+/**+ * @brief Dialog for reverting frame range changes in version control system.+ *+ * Specialized dialog for reverting changes to frame ranges in animation files.+ * Handles the special case where multiple frame files need to be reverted.+ */class SVNRevertFrameRangeDialog final : public DVGui::Dialog {Q_OBJECT- QLabel *m_waitingLabel;- QLabel *m_textLabel;+ // UI Elements+ QLabel* m_waitingLabel = nullptr;+ QLabel* m_textLabel = nullptr;+ QPushButton* m_revertButton = nullptr;+ QPushButton* m_cancelButton = nullptr;+ // Data membersQString m_workingDir;QString m_file;QString m_tempFileName;-- QPushButton *m_revertButton;- QPushButton *m_cancelButton;-- VersionControlThread m_thread;- QList<SVNStatus> m_status;- QList<QString> m_filesToRevert;QStringList m_files;+ QStringList m_filesToRevert;+ QList<SVNStatus> m_status;+ VersionControlThread m_thread;public:- SVNRevertFrameRangeDialog(QWidget *parent, const QString &workingDir,- const QString &file, const QString &tempFileName);+ /**+ * @brief Constructs a frame range revert dialog.+ *+ * @param parent Parent widget.+ * @param workingDir The working directory for SVN operations.+ * @param file The main file to revert.+ * @param tempFileName Temporary file name used during the operation.+ */+ explicit SVNRevertFrameRangeDialog(QWidget* parent, const QString& workingDir,+ const QString& file,+ const QString& tempFileName);private:+ /**+ * @brief Switches the dialog to close mode.+ */void switchToCloseButton();++ /**+ * @brief Initiates the revert process for frame range files.+ */void revertFiles();+ /**+ * @brief Checks which frame files need to be reverted.+ */void checkFiles();-protected slots:+private slots:+ /**+ * @brief Handles revert button click event.+ */void onRevertButtonClicked();- void onError(const QString &);- void onStatusRetrieved(const QString &);++ /**+ * @brief Handles SVN errors.+ *+ * @param errorString The error message from SVN.+ */+ void onError(const QString& errorString);++ /**+ * @brief Handles retrieval of SVN status for frame files.+ *+ * @param xmlResponse The XML response from SVN status command.+ */+ void onStatusRetrieved(const QString& xmlResponse);++ /**+ * @brief Handles completion of revert operation.+ */void onRevertDone();signals:- void done(const QStringList &);+ /**+ * @brief Signal emitted when revert operation is complete.+ *+ * @param files List of files that were reverted.+ */+ void done(const QStringList& files);};#endif // SVN_REVERT_DIALOG_Hdiff --git a/toonz/sources/toonz/svnupdatedialog.cpp b/toonz/sources/toonz/svnupdatedialog.cppindex a9ef6427c..b236855cd 100644--- a/toonz/sources/toonz/svnupdatedialog.cpp+++ b/toonz/sources/toonz/svnupdatedialog.cpp@@ -22,7 +22,7 @@#include <QMovie>#include <QTextEdit>#include <QCheckBox>-#include <QRegExp>+#include <QRegularExpression>#include <QDir>#include <QMainWindow>@@ -35,69 +35,72 @@ SVNUpdateDialog::SVNUpdateDialog(QWidget *parent, const QString &workingDir,bool isFolderOnly, bool updateToRevision,bool nonRecursive): Dialog(TApp::instance()->getMainWindow(), true, false)- , m_updateSceneContentsCheckBox(0), m_workingDir(workingDir), m_files(files), m_updateToRevision(updateToRevision), m_nonRecursive(nonRecursive), m_sceneIconsCount(sceneIconsCount), m_someSceneIsMissing(false) {+ // Set dialog propertiessetModal(false);setMinimumSize(300, 180);setAttribute(Qt::WA_DeleteOnClose, true);setWindowTitle(tr("Version Control: Update"));- QWidget *container = new QWidget;-- QVBoxLayout *mainLayout = new QVBoxLayout;+ // Create main container+ auto container = new QWidget(this);+ auto mainLayout = new QVBoxLayout;mainLayout->setAlignment(Qt::AlignHCenter);mainLayout->setContentsMargins(0, 0, 0, 0);- QHBoxLayout *hLayout = new QHBoxLayout;-- m_waitingLabel = new QLabel;- QMovie *waitingMove = new QMovie(":Resources/waiting.gif");- waitingMove->setParent(this);+ // Create waiting layout+ auto hLayout = new QHBoxLayout;+ m_waitingLabel = new QLabel(this);- m_waitingLabel->setMovie(waitingMove);- waitingMove->setCacheMode(QMovie::CacheAll);- waitingMove->start();+ // Create waiting animation+ auto waitingMovie = new QMovie(":Resources/waiting.gif", QByteArray(), this);+ m_waitingLabel->setMovie(waitingMovie);+ waitingMovie->setCacheMode(QMovie::CacheAll);+ waitingMovie->start();- m_textLabel = new QLabel(tr("Getting repository status..."));+ m_textLabel = new QLabel(tr("Getting repository status..."), this);hLayout->addStretch();hLayout->addWidget(m_waitingLabel);hLayout->addWidget(m_textLabel);hLayout->addStretch();-mainLayout->addLayout(hLayout);- m_output = new QTextEdit;+ // Create output text area+ m_output = new QTextEdit(this);m_output->setTextInteractionFlags(Qt::NoTextInteraction);m_output->setReadOnly(true);m_output->hide();-mainLayout->addWidget(m_output);- m_conflictWidget = new ConflictWidget;+ // Create conflict resolution widget+ m_conflictWidget = new ConflictWidget(this);m_conflictWidget->hide();-mainLayout->addWidget(m_conflictWidget);- m_dateChooserWidget = new DateChooserWidget;+ // Create date/revision chooser widget+ m_dateChooserWidget = new DateChooserWidget(this);m_dateChooserWidget->hide();-mainLayout->addWidget(m_dateChooserWidget);+ // Create "Get Scene Contents" checkbox if not folder onlyif (!isFolderOnly) {- QHBoxLayout *checkBoxLayout = new QHBoxLayout;+ auto checkBoxLayout = new QHBoxLayout;checkBoxLayout->setContentsMargins(0, 0, 0, 0);- m_updateSceneContentsCheckBox = new QCheckBox(this);++ m_updateSceneContentsCheckBox =+ new QCheckBox(tr("Get Scene Contents"), this);m_updateSceneContentsCheckBox->setChecked(false);- m_updateSceneContentsCheckBox->setText(tr("Get Scene Contents"));m_updateSceneContentsCheckBox->hide();- connect(m_updateSceneContentsCheckBox, SIGNAL(toggled(bool)), this,- SLOT(onUpdateSceneContentsToggled(bool)));++ // Modern signal/slot connection+ connect(m_updateSceneContentsCheckBox, &QCheckBox::toggled, this,+ &SVNUpdateDialog::onUpdateSceneContentsToggled);checkBoxLayout->addStretch();checkBoxLayout->addWidget(m_updateSceneContentsCheckBox);@@ -109,74 +112,93 @@ SVNUpdateDialog::SVNUpdateDialog(QWidget *parent, const QString &workingDir,container->setLayout(mainLayout);+ // Add container to dialogbeginHLayout();addWidget(container, false);endHLayout();- m_updateButton = new QPushButton(tr("Update"));+ // Create update button with appropriate action+ m_updateButton = new QPushButton(tr("Update"), this);m_updateButton->hide();- if (m_updateToRevision)- connect(m_updateButton, SIGNAL(clicked()), this,- SLOT(onUpdateToRevisionButtonClicked()));- else- connect(m_updateButton, SIGNAL(clicked()), this,- SLOT(onUpdateButtonClicked()));-- m_closeButton = new QPushButton(tr("Close"));+ if (m_updateToRevision) {+ connect(m_updateButton, &QPushButton::clicked, this,+ &SVNUpdateDialog::onUpdateToRevisionButtonClicked);+ } else {+ connect(m_updateButton, &QPushButton::clicked, this,+ &SVNUpdateDialog::onUpdateButtonClicked);+ }++ // Create close and cancel buttons+ m_closeButton = new QPushButton(tr("Close"), this);m_closeButton->setEnabled(false);- connect(m_closeButton, SIGNAL(clicked()), this, SLOT(close()));+ connect(m_closeButton, &QPushButton::clicked, this, &SVNUpdateDialog::close);- m_cancelButton = new QPushButton(tr("Cancel"));- connect(m_cancelButton, SIGNAL(clicked()), this, SLOT(reject()));+ m_cancelButton = new QPushButton(tr("Cancel"), this);+ connect(m_cancelButton, &QPushButton::clicked, this,+ &SVNUpdateDialog::reject);addButtonBarWidget(m_updateButton, m_closeButton, m_cancelButton);- // 0. Connect for svn errors (that may occur every time)- connect(&m_thread, SIGNAL(error(const QString &)), this,- SLOT(onError(const QString &)));+ // Connect SVN thread signals using modern syntax+ // Connect for svn errors (that may occur every time)+ connect(&m_thread, &VersionControlThread::error, this,+ &SVNUpdateDialog::onError);- // 1. Getting status- connect(&m_thread, SIGNAL(statusRetrieved(const QString &)), this,- SLOT(onStatusRetrieved(const QString &)));+ // Connect for status retrieval+ connect(&m_thread, &VersionControlThread::statusRetrieved, this,+ &SVNUpdateDialog::onStatusRetrieved);++ // Start getting SVN statusm_thread.getSVNStatus(m_workingDir, m_files, true, false, true);}//-----------------------------------------------------------------------------void SVNUpdateDialog::onStatusRetrieved(const QString &xmlResponse) {+ // Hide waiting animationm_waitingLabel->hide();+ // Parse SVN status from XML responseSVNStatusReader sr(xmlResponse);m_status = sr.getStatus();+ // Check which files need to be updatedcheckFiles();- // Check if a scene files is found- int fileSize = m_filesToUpdate.size();- for (int i = 0; i < fileSize; i++) {- if (m_filesToUpdate.at(i).endsWith(".tnz")) {- if (fileSize == 1)- m_textLabel->setText(- tr("%1 items to update.")- .arg(m_filesToUpdate.size() + m_sceneResources.size()));- else- m_textLabel->setText(tr("%1 items to update.")- .arg(m_filesToUpdate.size() +- m_sceneResources.size() -- m_sceneIconsCount));- if (m_updateSceneContentsCheckBox && !m_someSceneIsMissing)- m_updateSceneContentsCheckBox->show();- m_updateButton->show();- m_closeButton->hide();- return;+ // Check if scene files (.tnz) are found+ bool hasTnzFiles =+ std::any_of(m_filesToUpdate.begin(), m_filesToUpdate.end(),+ [](const QString &file) { return file.endsWith(".tnz"); });++ if (hasTnzFiles) {+ // Update text label with appropriate item count+ if (m_filesToUpdate.size() == 1) {+ m_textLabel->setText(+ tr("%1 items to update.")+ .arg(m_filesToUpdate.size() + m_sceneResources.size()));+ } else {+ m_textLabel->setText(tr("%1 items to update.")+ .arg(m_filesToUpdate.size() ++ m_sceneResources.size() -+ m_sceneIconsCount));+ }++ // Show scene contents checkbox if no scenes are missing+ if (m_updateSceneContentsCheckBox && !m_someSceneIsMissing) {+ m_updateSceneContentsCheckBox->show();}++ m_updateButton->show();+ m_closeButton->hide();+ return;}+ // Handle update to specific revisionif (m_updateToRevision) {- if (m_filesWithConflict.count() > 0) {+ if (!m_filesWithConflict.isEmpty()) {m_textLabel->setText(- tr("Some items are currently modified in your working copy.\nPlease "- "commit or revert changes first."));+ tr("Some items are currently modified in your working copy.\n"+ "Please commit or revert changes first."));m_textLabel->show();switchToCloseButton();return;@@ -190,47 +212,59 @@ void SVNUpdateDialog::onStatusRetrieved(const QString &xmlResponse) {adjustSize();} else {- // Resolve first files with conflict- if (m_filesWithConflict.count() > 0) {+ // Handle conflicts in normal update+ if (!m_filesWithConflict.isEmpty()) {m_textLabel->setText(tr("Some conflict found. Select.."));m_textLabel->show();m_updateButton->setEnabled(false);m_updateButton->show();m_closeButton->hide();- QStringList fileswithConflict;- int fileswithConflictCount = m_filesWithConflict.size();- for (int i = 0; i < fileswithConflictCount; i++)- fileswithConflict.append(m_filesWithConflict.at(i));- m_conflictWidget->setFiles(fileswithConflict);+ // Set files with conflict in conflict widget+ m_conflictWidget->setFiles(m_filesWithConflict);m_conflictWidget->show();adjustSize();- connect(m_conflictWidget, SIGNAL(allConflictSetted()), this,- SLOT(onConflictSetted()));- } else++ // Connect conflict resolution signal+ connect(m_conflictWidget, &ConflictWidget::allConflictSetted, this,+ &SVNUpdateDialog::onConflictSetted);+ } else {+ // No conflicts, proceed with updateupdateFiles();+ }}}//-----------------------------------------------------------------------------void SVNUpdateDialog::checkFiles() {- int statusCount = m_status.size();- for (int i = 0; i < statusCount; i++) {- SVNStatus s = m_status.at(i);- if (s.m_path == "." || s.m_path == "..") continue;- if ((m_updateToRevision && s.m_item == "modified") ||- (s.m_item == "modified" && s.m_repoStatus == "modified"))- m_filesWithConflict.prepend(s.m_path);- else if (s.m_item == "none" || s.m_item == "missing" ||- s.m_repoStatus == "modified" || s.m_repoStatus == "modified") {- if (s.m_path.endsWith(".tnz") &&- (s.m_item == "missing" ||- (s.m_item == "none" && s.m_repoStatus == "added"))) {- TFilePath scenePath =- TFilePath(m_workingDir.toStdWString()) + s.m_path.toStdWString();+ // Clear existing lists+ m_filesWithConflict.clear();+ m_filesToUpdate.clear();++ // Check each file's status to determine if it needs update or has conflicts+ for (const auto &status : m_status) {+ if (status.m_path == "." || status.m_path == "..") {+ continue;+ }++ // Check for conflicts+ if ((m_updateToRevision && status.m_item == "modified") ||+ (status.m_item == "modified" && status.m_repoStatus == "modified")) {+ m_filesWithConflict.prepend(status.m_path);+ }+ // Check for files that need update+ else if (status.m_item == "none" || status.m_item == "missing" ||+ status.m_repoStatus == "modified") {+ // Handle missing .tnz files and their icons+ if (status.m_path.endsWith(".tnz") &&+ (status.m_item == "missing" ||+ (status.m_item == "none" && status.m_repoStatus == "added"))) {+ TFilePath scenePath = TFilePath(m_workingDir.toStdWString()) ++ status.m_path.toStdWString();TFilePath iconPath = ToonzScene::getIconPath(scenePath);QDir dir(m_workingDir);+#ifdef MACOSXm_filesToUpdate.append(dir.relativeFilePath(toQString(iconPath)));#else@@ -240,8 +274,11 @@ void SVNUpdateDialog::checkFiles() {m_sceneIconsCount++;m_someSceneIsMissing = true;}- if (m_files.count() == 1 || m_files.contains(s.m_path))- m_filesToUpdate.prepend(s.m_path);++ // Add file to update list if it's in the requested files+ if (m_files.size() == 1 || m_files.contains(status.m_path)) {+ m_filesToUpdate.prepend(status.m_path);+ }}}}@@ -249,48 +286,56 @@ void SVNUpdateDialog::checkFiles() {//-----------------------------------------------------------------------------void SVNUpdateDialog::updateFiles() {- if (m_filesToUpdate.count() == 0) {- QString msg = QString(tr("No items to update."));- m_textLabel->setText(msg);+ // Check if there are any files to update+ if (m_filesToUpdate.isEmpty()) {+ m_textLabel->setText(tr("No items to update."));m_textLabel->show();switchToCloseButton();return;}+ // Adjust UI for update operationsetMinimumSize(300, 200);- if (m_updateSceneContentsCheckBox) m_updateSceneContentsCheckBox->hide();+ if (m_updateSceneContentsCheckBox) {+ m_updateSceneContentsCheckBox->hide();+ }+m_updateButton->setEnabled(false);m_waitingLabel->hide();m_textLabel->hide();m_output->show();- QStringList args;- args << "update";+ // Prepare SVN update command arguments+ QStringList args = {"update"};+ args.append(m_filesToUpdate);+ args.append(m_sceneResources);- int filesCount = m_filesToUpdate.count();- for (int i = 0; i < filesCount; i++) {- QString file = m_filesToUpdate.at(i);- if (!file.isEmpty()) args << file;+ if (m_nonRecursive) {+ args << "--non-recursive";}- int resourceCount = m_sceneResources.size();- for (int i = 0; i < resourceCount; i++) args << m_sceneResources.at(i);+ // Disconnect previous done signal and connect new ones+ disconnect(&m_thread, &VersionControlThread::done, this,+ &SVNUpdateDialog::onUpdateDone);- if (m_nonRecursive) args << "--non-recursive";+ connect(&m_thread, &VersionControlThread::outputRetrieved, this,+ &SVNUpdateDialog::addOutputText);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNUpdateDialog::onUpdateDone);- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(outputRetrieved(const QString &)),- SLOT(addOutputText(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)),- SLOT(onUpdateDone(const QString &)));+ // Execute SVN update commandm_thread.executeCommand(m_workingDir, "svn", args, false);}//-----------------------------------------------------------------------------void SVNUpdateDialog::switchToCloseButton() {- if (m_updateSceneContentsCheckBox) m_updateSceneContentsCheckBox->hide();+ // Hide update-related UI elements and show close button+ if (m_updateSceneContentsCheckBox) {+ m_updateSceneContentsCheckBox->hide();+ }+m_cancelButton->hide();m_updateButton->hide();m_closeButton->show();@@ -300,97 +345,110 @@ void SVNUpdateDialog::switchToCloseButton() {//-----------------------------------------------------------------------------void SVNUpdateDialog::addOutputText(const QString &text) {- QRegExp regExp("Updated to revision (\\d+)\\.");+ // Remove "Updated to revision X." message using QRegularExpression+ QRegularExpression regExp("Updated to revision (\\d+)\\.");QString temp = text;temp.remove(regExp);- QStringList split = temp.split(QRegExp("\\r\\n|\\n"));+ // Split text by newlines and add to output+ QStringList split = temp.split(QRegularExpression("\\r\\n|\\n"));- for (int i = 0; i < split.size(); i++) {- QString s = split.at(i);- if (!s.isEmpty()) m_output->insertPlainText(s + "\n");+ for (const auto &line : split) {+ if (!line.isEmpty()) {+ m_output->insertPlainText(line + "\n");+ }}- QScrollBar *scrollBar = m_output->verticalScrollBar();++ // Scroll to bottom+ auto scrollBar = m_output->verticalScrollBar();scrollBar->setValue(scrollBar->maximum());}//-----------------------------------------------------------------------------void SVNUpdateDialog::onUpdateToRevisionButtonClicked() {+ // Hide UI elements for revision updatem_textLabel->hide();m_cancelButton->hide();m_updateButton->hide();m_dateChooserWidget->hide();m_output->show();- QStringList args;- args << "update";+ // Prepare SVN update command with specific revision+ QStringList args = {"update"};+ args.append(m_files);- // Pay attention: I have to perform update of the whole selected files- // (that could become updatable "looking in the past")- int filesCount = m_files.count();- for (int i = 0; i < filesCount; i++) {- QString file = m_files.at(i);- if (!file.isEmpty()) args << file;- }QString revisionString = m_dateChooserWidget->getRevisionString();-args << "-r" << revisionString;- connect(&m_thread, SIGNAL(outputRetrieved(const QString &)),- SLOT(addOutputText(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)),- SLOT(onUpdateDone(const QString &)));+ // Connect output and done signals+ connect(&m_thread, &VersionControlThread::outputRetrieved, this,+ &SVNUpdateDialog::addOutputText);+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNUpdateDialog::onUpdateDone);++ // Execute SVN update to specific revisionm_thread.executeCommand(m_workingDir, "svn", args, false);}//-----------------------------------------------------------------------------void SVNUpdateDialog::onUpdateButtonClicked() {- // Update to mine- QStringList files = m_conflictWidget->getFilesWithOption(0);- if (files.size() > 0) {+ // Update conflicted files using "mine-full" option+ auto files = m_conflictWidget->getFilesWithOption(0);+ if (!files.isEmpty()) {m_waitingLabel->show();m_textLabel->setText(tr("Updating items..."));- QStringList args;- args << "update";++ QStringList args = {"update"};args.append(files);- args << "--accept"- << "mine-full";+ args << "--accept" << "mine-full";++ // Disconnect previous done signal+ disconnect(&m_thread, &VersionControlThread::done, this,+ &SVNUpdateDialog::onUpdateToMineDone);++ // Connect for completion+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNUpdateDialog::onUpdateToMineDone);- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)),- SLOT(onUpdateToMineDone()));m_thread.executeCommand(m_workingDir, "svn", args);- } else+ } else {onUpdateToMineDone();+ }}//-----------------------------------------------------------------------------void SVNUpdateDialog::onUpdateToMineDone() {- // Update to theirs- QStringList files = m_conflictWidget->getFilesWithOption(1);- if (files.size() > 0) {+ // Update conflicted files using "theirs-full" option+ auto files = m_conflictWidget->getFilesWithOption(1);+ if (!files.isEmpty()) {m_waitingLabel->show();m_textLabel->setText(tr("Updating to their items..."));- QStringList args;- args << "update";++ QStringList args = {"update"};args.append(files);- args << "--accept"- << "theirs-full";+ args << "--accept" << "theirs-full";++ // Disconnect previous done signal+ disconnect(&m_thread, &VersionControlThread::done, this,+ &SVNUpdateDialog::onConflictResolved);++ // Connect for completion+ connect(&m_thread, &VersionControlThread::done, this,+ &SVNUpdateDialog::onConflictResolved);- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)),- SLOT(onConflictResolved()));m_thread.executeCommand(m_workingDir, "svn", args);- } else+ } else {onConflictResolved();+ }}//-----------------------------------------------------------------------------void SVNUpdateDialog::onConflictResolved() {+ // Hide conflict widget and proceed with updatem_conflictWidget->hide();updateFiles();}@@ -398,55 +456,64 @@ void SVNUpdateDialog::onConflictResolved() {//-----------------------------------------------------------------------------void SVNUpdateDialog::onError(const QString &errorString) {+ // Hide waiting animation and display errorm_waitingLabel->hide();- if (m_output->isVisible())++ if (m_output->isVisible()) {addOutputText(errorString);- else {+ } else {m_textLabel->setText(errorString);m_textLabel->show();}+switchToCloseButton();}//-----------------------------------------------------------------------------void SVNUpdateDialog::onUpdateDone(const QString &text) {+ // Add final output textaddOutputText(text);- QStringList files;- for (int i = 0; i < m_filesToUpdate.size(); i++)- files.append(m_filesToUpdate.at(i));- emit done(files);+ // Emit done signal with updated files+ emit done(m_filesToUpdate);+ // Switch to close buttonswitchToCloseButton();}//------------------------------------------------------------------------------void SVNUpdateDialog::onConflictSetted() { m_updateButton->setEnabled(true); }+void SVNUpdateDialog::onConflictSetted() {+ // Enable update button after conflict resolution+ m_updateButton->setEnabled(true);+}//-----------------------------------------------------------------------------void SVNUpdateDialog::onUpdateSceneContentsToggled(bool checked) {- if (!checked)- m_sceneResources.clear();- else {- VersionControl *vc = VersionControl::instance();-- int fileSize = m_filesToUpdate.count();- for (int i = 0; i < fileSize; i++) {- QString fileName = m_filesToUpdate.at(i);- if (fileName.endsWith(".tnz"))+ // Clear or populate scene resources based on checkbox state+ m_sceneResources.clear();++ if (checked) {+ auto vc = VersionControl::instance();++ // Find .tnz files and get their scene contents+ for (const auto &fileName : m_filesToUpdate) {+ if (fileName.endsWith(".tnz")) {m_sceneResources.append(vc->getSceneContents(m_workingDir, fileName));+ }}}- if (m_filesToUpdate.size() == 1)+ // Update text label with new item count+ if (m_filesToUpdate.size() == 1) {m_textLabel->setText(tr("%1 items to update.").arg(m_filesToUpdate.size() + m_sceneResources.size()));- else+ } else {m_textLabel->setText(tr("%1 items to update.").arg(m_filesToUpdate.size() +m_sceneResources.size() - m_sceneIconsCount));+ }}diff --git a/toonz/sources/toonz/svnupdatedialog.h b/toonz/sources/toonz/svnupdatedialog.hindex b410a91dd..edf29a8e5 100644--- a/toonz/sources/toonz/svnupdatedialog.h+++ b/toonz/sources/toonz/svnupdatedialog.h@@ -3,11 +3,16 @@#ifndef SVN_UPDATE_DIALOG_H#define SVN_UPDATE_DIALOG_H+// ToonzQt includes#include "toonzqt/dvdialog.h"++// Version control includes#include "versioncontrol.h"-#include <QList>+// Qt includes+#include <QStringList>+// Forward declarationsclass QLabel;class QPushButton;class DateChooserWidget;@@ -16,82 +21,149 @@ class QTextEdit;class QCheckBox;//------------------------------------------------------------------------------+/**+ * @brief Dialog for updating files from version control system.+ *+ * This dialog handles SVN update operations, including normal updates,+ * updates to specific revisions, and conflict resolution. It can also+ * handle scene files and their associated resources.+ */class SVNUpdateDialog final : public DVGui::Dialog {Q_OBJECT- QPushButton *m_closeButton;- QPushButton *m_cancelButton;- QPushButton *m_updateButton; // only in update to revision-- VersionControlThread m_thread;-- QCheckBox *m_updateSceneContentsCheckBox;-- QLabel *m_waitingLabel;- QLabel *m_textLabel;-- QString m_workingDir;-- QList<SVNStatus> m_status;- QStringList m_files;-- QList<QString> m_filesToUpdate;- QList<QString> m_filesWithConflict;-- QList<QString> m_sceneResources;-- bool m_updateToRevision;- bool m_nonRecursive;-- QTextEdit *m_output;-- DateChooserWidget *m_dateChooserWidget;- ConflictWidget *m_conflictWidget;-- int m_sceneIconsCount;-- // Used to choose to display "Get scene contents"- // If there is some missing .tnz files don't display "Get Scene Contents"- // checkbox.- bool m_someSceneIsMissing;+public:+ /**+ * @brief Constructs an update dialog.+ *+ * @param parent Parent widget.+ * @param workingDir The working directory for SVN operations.+ * @param filesToUpdate List of files to update.+ * @param sceneIconsCount Number of scene icons (for display adjustments).+ * @param isFolderOnly Whether the operation is for folders only.+ * @param updateToRevision Whether to update to a specific revision.+ * @param nonRecursive Whether to perform a non-recursive update.+ */+ SVNUpdateDialog(QWidget* parent, const QString& workingDir,+ const QStringList& filesToUpdate, int sceneIconsCount,+ bool isFolderOnly, bool updateToRevision, bool nonRecursive);private:+ /**+ * @brief Initiates the update process for files.+ */void updateFiles();+ /**+ * @brief Checks which files need to be updated based on SVN status.+ */void checkFiles();+ /**+ * @brief Switches the dialog to close mode.+ *+ * Changes the UI to show only the close button after operation completion.+ */void switchToCloseButton();-public:- SVNUpdateDialog(QWidget *parent, const QString &workingDir,- const QStringList &filesToUpdate, int sceneIconsCount,- bool isFolderOnly, bool updateToRevision, bool nonRecursive);--protected slots:-- void onError(const QString &);-- void onUpdateDone(const QString &);-+private slots:+ /**+ * @brief Handles SVN errors.+ *+ * @param errorString The error message from SVN.+ */+ void onError(const QString& errorString);++ /**+ * @brief Handles completion of update operation.+ *+ * @param text Output text from the update command.+ */+ void onUpdateDone(const QString& text);++ /**+ * @brief Handles completion of conflict resolution.+ */void onConflictSetted();+ /**+ * @brief Handles completion of update with "mine-full" option.+ */void onUpdateToMineDone();++ /**+ * @brief Handles completion of conflict resolution.+ */void onConflictResolved();- // Only for update to revision+ /**+ * @brief Handles update to specific revision button click.+ */void onUpdateToRevisionButtonClicked();+ /**+ * @brief Handles normal update button click.+ */void onUpdateButtonClicked();- void addOutputText(const QString &text);+ /**+ * @brief Adds text to the output display.+ *+ * @param text Text to display.+ */+ void addOutputText(const QString& text);++ /**+ * @brief Handles retrieval of SVN status.+ *+ * @param xmlResponse The XML response from SVN status command.+ */+ void onStatusRetrieved(const QString& xmlResponse);++ /**+ * @brief Handles toggle of update scene contents checkbox.+ *+ * @param checked Whether the checkbox is checked.+ */+ void onUpdateSceneContentsToggled(bool checked);- void onStatusRetrieved(const QString &);+signals:+ /**+ * @brief Signal emitted when update operation is complete.+ *+ * @param files List of files that were updated.+ */+ void done(const QStringList& files);- void onUpdateSceneContentsToggled(bool);+private:+ // UI Elements+ QPushButton* m_closeButton = nullptr;+ QPushButton* m_cancelButton = nullptr;+ QPushButton* m_updateButton = nullptr;+ QCheckBox* m_updateSceneContentsCheckBox = nullptr;+ QLabel* m_waitingLabel = nullptr;+ QLabel* m_textLabel = nullptr;+ QTextEdit* m_output = nullptr;+ DateChooserWidget* m_dateChooserWidget = nullptr;+ ConflictWidget* m_conflictWidget = nullptr;++ // SVN thread for asynchronous operations+ VersionControlThread m_thread;-signals:- void done(const QStringList &);+ // Data members+ QString m_workingDir;+ QStringList m_files;+ QStringList m_filesToUpdate;+ QStringList m_filesWithConflict;+ QStringList m_sceneResources;+ QList<SVNStatus> m_status;++ // Configuration flags+ bool m_updateToRevision = false;+ bool m_nonRecursive = false;+ bool m_someSceneIsMissing = false;++ // Counters+ int m_sceneIconsCount = 0;};-#endif // SVN_REVERT_DIALOG_H+#endif // SVN_UPDATE_DIALOG_Hdiff --git a/toonz/sources/toonz/versioncontrol.cpp b/toonz/sources/toonz/versioncontrol.cppindex d4535020c..d3f6bf9ef 100644--- a/toonz/sources/toonz/versioncontrol.cpp+++ b/toonz/sources/toonz/versioncontrol.cpp@@ -3,9 +3,12 @@#include "versioncontrol.h"#include "versioncontrolgui.h"+// ToonzQt includes#include "toonzqt/gutil.h"#include "toonzqt/dvdialog.h"#include "toonzqt/icongenerator.h"++// Toonz includes#include "toonz/sceneresources.h"#include "toonz/toonzscene.h"#include "toonz/levelset.h"@@ -16,52 +19,80 @@#include "toonz/tpalettehandle.h"#include "toonz/tscenehandle.h"#include "toonz/tproject.h"++// TnzCore includes#include "tsystem.h"#include "tenv.h"++// Tnz6 includes#include "tapp.h"#include "permissionsmanager.h"+// Qt includes#include <QFile>#include <QDir>#include <QSettings>-#include <QRegExp>+#include <QRegularExpression>namespace {-bool getFrameRange(const TFilePath &path, unsigned int &from,- unsigned int &to) {- // Set frame range+/**+ * @brief Extracts frame range from a file path pattern.+ *+ * @param path The file path pattern (e.g., "image..png").+ * @param from Output parameter for start frame.+ * @param to Output parameter for end frame.+ * @return true if frame range was found, false otherwise.+ */+bool getFrameRange(const TFilePath& path, unsigned int& from,+ unsigned int& to) {+ // Check for frame range patternif (path.getDots() == "..") {TFilePath dir = path.getParentDir();QDir qDir(QString::fromStdWString(dir.getWideString()));++ // Escape level name for regex and create patternQString levelName =- QRegExp::escape(QString::fromStdWString(path.getWideName()));+ QRegularExpression::escape(QString::fromStdWString(path.getWideName()));QString levelType = QString::fromStdString(path.getType());- QString exp(levelName + ".[0-9]{1,4}." + levelType);- QRegExp regExp(exp);++ // Create regular expression for frame files+ QString pattern = QString("%1\\.[0-9]{1,4}\\.%2").arg(levelName, levelType);+ QRegularExpression regex(pattern);++ // Get files matching the patternQStringList list = qDir.entryList(QDir::Files);- QStringList levelFrames = list.filter(regExp);+ QStringList levelFrames = list.filter(regex);++ // Initialize frame range+ from = static_cast<unsigned int>(-1);+ to = static_cast<unsigned int>(-1);- from = -1;- to = -1;- for (int i = 0; i < levelFrames.size(); i++) {+ // Determine writable frame range+ for (int i = 0; i < levelFrames.size(); ++i) {TFilePath frame = dir + TFilePath(levelFrames[i].toStdWString());- if (frame.isEmpty() || !frame.isAbsolute()) continue;++ if (frame.isEmpty() || !frame.isAbsolute()) {+ continue;+ }+TFileStatus filestatus(frame);if (filestatus.isWritable()) {- if (from == -1)- from = i;- else- to = i;- } else if (from != -1 && to != -1)+ if (from == static_cast<unsigned int>(-1)) {+ from = static_cast<unsigned int>(i);+ } else {+ to = static_cast<unsigned int>(i);+ }+ } else if (from != static_cast<unsigned int>(-1) &&+ to != static_cast<unsigned int>(-1)) {break;+ }}- if (from != -1 && to != -1)- return true;- else- return false;+ return (from != static_cast<unsigned int>(-1) &&+ to != static_cast<unsigned int>(-1));}+return false;}@@ -71,17 +102,18 @@ bool getFrameRange(const TFilePath &path, unsigned int &from,// VersionControlThread//------------------------------------------------------------------------------VersionControlThread::VersionControlThread(QObject *parent)+VersionControlThread::VersionControlThread(QObject* parent): QThread(parent), m_abort(false), m_restart(false), m_getStatus(false), m_readOutputOnDone(true)- , m_process(0) {}+ , m_process(nullptr) {}//-----------------------------------------------------------------------------VersionControlThread::~VersionControlThread() {+ // Signal thread to abort and wait for completionm_mutex.lock();m_abort = true;m_condition.wakeOne();@@ -99,59 +131,56 @@ void VersionControlThread::run() {QString binary = m_binary;QStringList args = m_args;- // Add Username and Password (if exists)-- VersionControl *vc = VersionControl::instance();-- QString userName = vc->getUserName();- QString password = vc->getPassword();+ // Add username and password if available+ VersionControl* vc = VersionControl::instance();+ QString userName = vc->getUserName();+ QString password = vc->getPassword();if (!userName.isEmpty() || !password.isEmpty()) {- args << QString("--username") << userName << QString("--password")- << password;+ args << "--username" << userName << "--password" << password;}- // Add "non-interactive" and "trust-server-cert" global options- args << "--non-interactive";- args << "--trust-server-cert";+ // Add global options+ args << "--non-interactive" << "--trust-server-cert";- QString executablePath = vc->getExecutablePath();- if (!executablePath.isEmpty()) binary = executablePath + "/" + m_binary;+ // Update binary path if executable path is specified+ QString executablePath = vc->getExecutablePath();+ if (!executablePath.isEmpty()) {+ binary = executablePath + "/" + m_binary;+ }m_mutex.unlock();+ // Check for abortif (m_abort) {- if (m_process) {- m_process->close();- disconnect(m_process, SIGNAL(readyReadStandardOutput()), this,- SLOT(onStandardOutputReady()));- delete m_process;- m_process = 0;- }+ cleanupProcess();return;}- if (m_process) {- m_process->close();- disconnect(m_process, SIGNAL(readyReadStandardOutput()), this,- SLOT(onStandardOutputReady()));- delete m_process;- m_process = 0;- }+ // Clean up previous process+ cleanupProcess();+ // Create new processm_process = new QProcess;- if (!workingDir.isEmpty() && QFile::exists(workingDir))++ // Set working directory+ if (!workingDir.isEmpty() && QFile::exists(workingDir)) {m_process->setWorkingDirectory(workingDir);+ }+ // Set environment to English localeQStringList env = QProcess::systemEnvironment();- env << "LC_MESSAGES=en_EN"; // Add this environment variables to fix the- // language to English+ env << "LC_MESSAGES=en_EN";m_process->setEnvironment(env);- if (!m_readOutputOnDone)- connect(m_process, SIGNAL(readyReadStandardOutput()), this,- SLOT(onStandardOutputReady()));+ // Connect output signal if not reading output at end+ if (!m_readOutputOnDone) {+ connect(m_process, &QProcess::readyReadStandardOutput, this,+ &VersionControlThread::onStandardOutputReady,+ Qt::DirectConnection);+ }+ // Start the processm_process->start(binary, args);if (!m_process->waitForStarted()) {QString err = QString("Unable to launch \"%1\": %2")@@ -162,7 +191,7 @@ void VersionControlThread::run() {m_process->closeWriteChannel();- // Wait until users press cancel (every 1 sec I check for abort..+ // Wait for process completion with abort checkingwhile (!m_process->waitForFinished(1000)) {if (m_abort) {m_process->kill();@@ -171,26 +200,33 @@ void VersionControlThread::run() {}}+ // Check process exit statusif (m_process->exitStatus() != QProcess::NormalExit) {QString err = QString("\"%1\" crashed.").arg(binary);emit error(err);return;}+ // Check exit codeif (m_process->exitCode()) {emit error(QString::fromUtf8(m_process->readAllStandardError().data()));return;}+ // Emit appropriate signal based on operation typeif (m_getStatus) {emit statusRetrieved(QString::fromUtf8(m_process->readAllStandardOutput().data()));m_getStatus = false;- } else+ } else {emit done(QString::fromUtf8(m_process->readAllStandardOutput().data()));+ }+ // Wait for next command or exitm_mutex.lock();- if (!m_restart) m_condition.wait(&m_mutex);+ if (!m_restart) {+ m_condition.wait(&m_mutex);+ }m_restart = false;m_mutex.unlock();}@@ -198,17 +234,32 @@ void VersionControlThread::run() {//-----------------------------------------------------------------------------+void VersionControlThread::cleanupProcess() {+ if (m_process) {+ m_process->close();+ disconnect(m_process, &QProcess::readyReadStandardOutput, this,+ &VersionControlThread::onStandardOutputReady);+ delete m_process;+ m_process = nullptr;+ }+}++//-----------------------------------------------------------------------------+void VersionControlThread::onStandardOutputReady() {QString str = QString::fromUtf8(m_process->readAllStandardOutput().data());- if (str.isEmpty()) return;+ if (str.isEmpty()) {+ return;+ }+emit outputRetrieved(str);}//------------------------------------------------------------------------------void VersionControlThread::executeCommand(const QString &workingDir,- const QString &binary,- const QStringList &args,+void VersionControlThread::executeCommand(const QString& workingDir,+ const QString& binary,+ const QStringList& args,bool readOutputOnDone) {QMutexLocker locker(&m_mutex);@@ -217,7 +268,9 @@ void VersionControlThread::executeCommand(const QString &workingDir,m_binary = binary;m_args = args;- if (m_binary.isEmpty()) return;+ if (m_binary.isEmpty()) {+ return;+ }if (!isRunning()) {start(QThread::NormalPriority);@@ -229,22 +282,27 @@ void VersionControlThread::executeCommand(const QString &workingDir,//------------------------------------------------------------------------------void VersionControlThread::getSVNStatus(const QString &path, bool showUpdates,+void VersionControlThread::getSVNStatus(const QString& path, bool showUpdates,bool nonRecursive, bool depthInfinity) {QMutexLocker locker(&m_mutex);- m_workingDir = path;- m_binary = QString("svn");- QStringList args;- args << "status";- if (showUpdates)+ m_workingDir = path;+ m_binary = "svn";+ QStringList args = {"status"};++ if (showUpdates) {args << "-vu";- else+ } else {args << "-v";- if (nonRecursive) args << "--non-recursive";- if (depthInfinity)- args << "--depth"- << "infinity";+ }++ if (nonRecursive) {+ args << "--non-recursive";+ }++ if (depthInfinity) {+ args << "--depth" << "infinity";+ }args << "--xml";m_args = args;@@ -262,29 +320,36 @@ void VersionControlThread::getSVNStatus(const QString &path, bool showUpdates,//------------------------------------------------------------------------------void VersionControlThread::getSVNStatus(const QString &path,- const QStringList &files,+void VersionControlThread::getSVNStatus(const QString& path,+ const QStringList& files,bool showUpdates, bool nonRecursive,bool depthInfinity) {QMutexLocker locker(&m_mutex);- m_workingDir = path;- m_binary = QString("svn");- QStringList args;- args << "status";- if (showUpdates)++ m_workingDir = path;+ m_binary = "svn";+ QStringList args = {"status"};++ if (showUpdates) {args << "-vu";- else+ } else {args << "-v";+ }++ // Add specific files to check+ for (const auto& file : files) {+ if (!file.isEmpty()) {+ args << file;+ }+ }- int filesCount = files.size();- for (int i = 0; i < filesCount; i++) {- QString f = files.at(i);- if (!f.isEmpty()) args << f;+ if (nonRecursive) {+ args << "--non-recursive";+ }++ if (depthInfinity) {+ args << "--depth" << "infinity";}- if (nonRecursive) args << "--non-recursive";- if (depthInfinity)- args << "--depth"- << "infinity";args << "--xml";m_args = args;@@ -305,54 +370,71 @@ void VersionControlThread::getSVNStatus(const QString &path,//-----------------------------------------------------------------------------VersionControlManager::VersionControlManager()- : m_scene(0), m_levelSet(0), m_isRunning(false), m_deleteLater(false) {- connect(&m_thread, SIGNAL(error(const QString &)), this,- SLOT(onError(const QString &)));+ : m_scene(nullptr)+ , m_levelSet(nullptr)+ , m_isRunning(false)+ , m_deleteLater(false) {+ // Modern signal/slot connection+ connect(&m_thread, &VersionControlThread::error, this,+ &VersionControlManager::onError);}//------------------------------------------------------------------------------VersionControlManager *VersionControlManager::instance() {- static VersionControlManager _instance;- return &_instance;+VersionControlManager* VersionControlManager::instance() {+ static VersionControlManager instance;+ return &instance;}//------------------------------------------------------------------------------static void setVersionControlCredentials(QString currentPath) {- VersionControl *vc = VersionControl::instance();- QList<SVNRepository> repositories = vc->getRepositories();- int repoCount = repositories.size();- for (int i = 0; i < repoCount; i++) {- SVNRepository r = repositories.at(i);- if (!currentPath.startsWith(r.m_localPath)) continue;- vc->setUserName(r.m_username);- vc->setPassword(r.m_password);- return;++namespace {+/**+ * @brief Sets version control credentials based on repository path.+ *+ * @param currentPath The current file path.+ */+void setVersionControlCredentials(const QString& currentPath) {+ VersionControl* vc = VersionControl::instance();+ auto repositories = vc->getRepositories();++ for (const auto& repo : repositories) {+ if (currentPath.startsWith(repo.m_localPath)) {+ vc->setUserName(repo.m_username);+ vc->setPassword(repo.m_password);+ return;+ }}}+} // namespace++//------------------------------------------------------------------------------void VersionControlManager::setFrameRange(TLevelSet *levelSet,+void VersionControlManager::setFrameRange(TLevelSet* levelSet,bool deleteLater) {- if (levelSet->getLevelCount() == 0) return;+ if (!levelSet || levelSet->getLevelCount() == 0) {+ return;+ }if (!m_isRunning) {- m_scene = 0; // Just to be sure+ // Reset state+ m_scene = nullptr;m_levelSet = levelSet;m_deleteLater = deleteLater;- QStringList args;- args << "proplist";-+ QStringList args = {"proplist"};bool checkVersionControl = false;bool filesAddedToArgs = false;- for (int i = 0; i < levelSet->getLevelCount(); i++) {- TXshLevel *level = levelSet->getLevel(i);- TXshSimpleLevel *sl = level->getSimpleLevel();+ // Process each level in the level set+ for (int i = 0; i < levelSet->getLevelCount(); ++i) {+ auto level = levelSet->getLevel(i);+ auto simpleLevel = level->getSimpleLevel();++ if (simpleLevel && !checkVersionControl) {+ TFilePath parentDir = simpleLevel->getScene()->decodeFilePath(+ simpleLevel->getPath().getParentDir());- if (sl && !checkVersionControl) {- TFilePath parentDir =- sl->getScene()->decodeFilePath(sl->getPath().getParentDir());if (VersionControl::instance()->isFolderUnderVersionControl(toQString(parentDir))) {checkVersionControl = true;@@ -360,49 +442,49 @@ void VersionControlManager::setFrameRange(TLevelSet *levelSet,}}- if (sl && sl->isReadOnly()) {- if (!m_scene) m_scene = sl->getScene();+ if (simpleLevel && simpleLevel->isReadOnly()) {+ if (!m_scene) {+ m_scene = simpleLevel->getScene();+ }- if (sl->getType() == PLI_XSHLEVEL || sl->getType() == TZP_XSHLEVEL) {+ // Handle different level types+ if (simpleLevel->getType() == PLI_XSHLEVEL ||+ simpleLevel->getType() == TZP_XSHLEVEL) {filesAddedToArgs = true;args << toQString(m_scene->decodeFilePath(level->getPath()));- } else if (sl->getType() == OVL_XSHLEVEL) {- unsigned int from;- unsigned int to;+ } else if (simpleLevel->getType() == OVL_XSHLEVEL) {+ unsigned int from = 0, to = 0;bool ret = getFrameRange(m_scene->decodeFilePath(level->getPath()),from, to);- if (ret)- sl->setEditableRange(++ if (ret) {+ simpleLevel->setEditableRange(from, to,VersionControl::instance()->getUserName().toStdWString());+ }}}}+ // Check if version control is neededif (!checkVersionControl || !filesAddedToArgs) {- if (m_deleteLater) {- m_deleteLater = false;- for (int i = m_levelSet->getLevelCount() - 1; i >= 0; i--) {- TXshLevel *l = m_levelSet->getLevel(i);- m_levelSet->removeLevel(l);- }- delete m_levelSet;- m_levelSet = 0;- }- m_scene = 0;+ cleanupResources();return;}- args << "--xml";- args << "-v";-+ // Prepare SVN command+ args << "--xml" << "-v";TFilePath path = m_scene->getScenePath();path = m_scene->decodeFilePath(path);QString workingDir = toQString(path.getParentDir());- m_thread.disconnect(SIGNAL(done(const QString &)));- connect(&m_thread, SIGNAL(done(const QString &)), this,- SLOT(onFrameRangeDone(const QString)));+ // Connect and execute command+ disconnect(&m_thread, &VersionControlThread::done, this,+ &VersionControlManager::onFrameRangeDone);++ connect(&m_thread, &VersionControlThread::done, this,+ &VersionControlManager::onFrameRangeDone, Qt::QueuedConnection);+m_thread.executeCommand(workingDir, "svn", args, true);m_isRunning = true;}@@ -410,60 +492,50 @@ void VersionControlManager::setFrameRange(TLevelSet *levelSet,//------------------------------------------------------------------------------void VersionControlManager::onFrameRangeDone(const QString &text) {+void VersionControlManager::onFrameRangeDone(const QString& text) {m_isRunning = false;SVNPartialLockReader lockReader(text);- QList<SVNPartialLock> list = lockReader.getPartialLock();- if (list.isEmpty()) {- if (m_deleteLater) {- m_deleteLater = false;-- for (int i = m_levelSet->getLevelCount() - 1; i >= 0; i--) {- TXshLevel *l = m_levelSet->getLevel(i);- TXshSimpleLevel *sl = l->getSimpleLevel();- if (sl) sl->clearEditableRange();- m_levelSet->removeLevel(l);- }+ auto lockList = lockReader.getPartialLock();- delete m_levelSet;- m_levelSet = 0;- }- m_scene = 0;+ if (lockList.isEmpty()) {+ cleanupResources();return;}- int listSize = list.count();- for (int l = 0; l < listSize; l++) {- SVNPartialLock pl = list.at(l);-- QList<SVNPartialLockInfo> lockInfos = pl.m_partialLockList;-- TFilePath currentPath = TFilePath(pl.m_fileName.toStdWString());+ // Process lock information+ for (const auto& lock : lockList) {+ TFilePath currentPath(lock.m_fileName.toStdWString());+ setVersionControlCredentials(toQString(currentPath));- TXshSimpleLevel *level;- for (int i = 0; i < m_levelSet->getLevelCount(); i++) {- TXshLevel *l = m_levelSet->getLevel(i);+ // Find the corresponding level+ TXshSimpleLevel* level = nullptr;+ for (int i = 0; i < m_levelSet->getLevelCount(); ++i) {+ auto l = m_levelSet->getLevel(i);TFilePath levelPath = m_scene->decodeFilePath(l->getPath());+if (levelPath == currentPath) {level = l->getSimpleLevel();break;}}- setVersionControlCredentials(toQString(currentPath));+ if (!level) {+ continue;+ }QString username = VersionControl::instance()->getUserName();QString hostName = TSystem::getHostName();- int count = lockInfos.size();- for (int i = 0; i < count; i++) {- SVNPartialLockInfo info = lockInfos.at(i);- if (info.m_userName == username && info.m_hostName == hostName) {- level->setEditableRange(info.m_from - 1, info.m_to - 1,- info.m_userName.toStdWString());+ // Find and apply lock information for current user/host+ for (const auto& lockInfo : lock.m_partialLockList) {+ if (lockInfo.m_userName == username && lockInfo.m_hostName == hostName) {+ level->setEditableRange(lockInfo.m_from - 1, lockInfo.m_to - 1,+ lockInfo.m_userName.toStdWString());invalidateIcons(level, level->getEditableRange());- TApp *app = TApp::instance();++ // Update UI if this level is current+ auto app = TApp::instance();if (app->getCurrentLevel()->getLevel() == level) {app->getPaletteController()->getCurrentLevelPalette()->setPalette(level->getPalette());@@ -474,34 +546,34 @@ void VersionControlManager::onFrameRangeDone(const QString &text) {}}- if (m_deleteLater) {- m_deleteLater = false;+ cleanupResources();+}++//------------------------------------------------------------------------------ for (int i = m_levelSet->getLevelCount() - 1; i >= 0; i--) {- TXshLevel *l = m_levelSet->getLevel(i);- m_levelSet->removeLevel(l);+void VersionControlManager::cleanupResources() {+ if (m_deleteLater && m_levelSet) {+ for (int i = m_levelSet->getLevelCount() - 1; i >= 0; --i) {+ auto level = m_levelSet->getLevel(i);+ if (auto simpleLevel = level->getSimpleLevel()) {+ simpleLevel->clearEditableRange();+ }+ m_levelSet->removeLevel(level);}delete m_levelSet;- m_levelSet = 0;+ m_levelSet = nullptr;+ m_deleteLater = false;}- m_scene = 0;++ m_scene = nullptr;}//------------------------------------------------------------------------------void VersionControlManager::onError(const QString &text) {+void VersionControlManager::onError(const QString& text) {m_isRunning = false;- if (m_deleteLater) {- m_deleteLater = false;- for (int i = m_levelSet->getLevelCount() - 1; i >= 0; i--) {- TXshLevel *l = m_levelSet->getLevel(i);- m_levelSet->removeLevel(l);- }- delete m_levelSet;- m_levelSet = 0;- }- m_scene = 0;+ cleanupResources();DVGui::warning(text);}@@ -514,9 +586,9 @@ VersionControl::VersionControl()//------------------------------------------------------------------------------VersionControl *VersionControl::instance() {- static VersionControl _instance;- return &_instance;+VersionControl* VersionControl::instance() {+ static VersionControl instance;+ return &instance;}//-----------------------------------------------------------------------------@@ -544,6 +616,8 @@ bool VersionControl::testSetup() {int repositoriesCount = 0;QString path;++ // Read configuration fileif (QFile::exists(configFileName)) {QFile file(configFileName);if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {@@ -562,8 +636,7 @@ bool VersionControl::testSetup() {return false;}-// Test if svnPath is correct (adding another "/" before binary name doesn't-// create any issue both on Windows and on Mac+ // Test if SVN executable exists at specified path#ifdef MACOSXif (!path.isEmpty() && !QFile::exists(path + "/svn"))#else@@ -576,15 +649,13 @@ bool VersionControl::testSetup() {return false;}- // Try to run svn executable, if the path is not specified in the config file,- // to test if exist- // In the meantime check for svn version+ // Test SVN installation and versionif (path.isEmpty()) {QProcess p;+ // Set environment to English localeQStringList env = QProcess::systemEnvironment();- env << "LC_MESSAGES=en_EN"; // Add this environment variables to fix the- // language to English+ env << "LC_MESSAGES=en_EN";p.setEnvironment(env);p.start("svn", QStringList("--version"));@@ -606,15 +677,15 @@ bool VersionControl::testSetup() {}QString output(p.readAllStandardOutput());-QStringList list = output.split("\n");if (!list.isEmpty()) {QString firstLine = list.first();- firstLine = firstLine.remove("svn, version 1."); //ignore the 1. since SVN decimal versions are not zero padded+ // Remove "svn, version 1." prefix to check decimal version+ firstLine = firstLine.remove("svn, version 1.");double version = firstLine.left(3).toDouble();- if (version < 5) { // only check decimal version 1.xx+ if (version < 5) {DVGui::warning(tr("The version control client application installed on your ""computer needs to be updated, otherwise some features may not "@@ -624,18 +695,25 @@ bool VersionControl::testSetup() {}}}+return true;}//------------------------------------------------------------------------------bool VersionControl::isFolderUnderVersionControl(const QString &folderPath) {++bool VersionControl::isFolderUnderVersionControl(const QString& folderPath) {QDir dir(folderPath);- if (dir.entryList(QDir::AllDirs | QDir::Hidden).contains(".svn")) return true;- // For SVN 1.7 and greater, check parent directories to see if it's under- // version control++ // Check for .svn directory+ if (dir.entryList(QDir::AllDirs | QDir::Hidden).contains(".svn")) {+ return true;+ }++ // For SVN 1.7+, check parent directorieswhile (dir.cdUp()) {- if (dir.entryList(QDir::AllDirs | QDir::Hidden).contains(".svn"))+ if (dir.entryList(QDir::AllDirs | QDir::Hidden).contains(".svn")) {return true;+ }}return false;@@ -643,267 +721,253 @@ bool VersionControl::isFolderUnderVersionControl(const QString &folderPath) {//------------------------------------------------------------------------------void VersionControl::commit(QWidget *parent, const QString &workingDir,- const QStringList &filesToCommit, bool folderOnly,+// Dialog creation methods with modern signal connections++void VersionControl::commit(QWidget* parent, const QString& workingDir,+ const QStringList& filesToCommit, bool folderOnly,int sceneIconAdded) {- SVNCommitDialog *dialog = new SVNCommitDialog(- parent, workingDir, filesToCommit, folderOnly, sceneIconAdded);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));+ auto dialog = new SVNCommitDialog(parent, workingDir, filesToCommit,+ folderOnly, sceneIconAdded);++ connect(dialog, &SVNCommitDialog::done, this, &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::revert(QWidget *parent, const QString &workingDir,- const QStringList &files, bool folderOnly,+void VersionControl::revert(QWidget* parent, const QString& workingDir,+ const QStringList& files, bool folderOnly,int sceneIconAdded) {- SVNRevertDialog *dialog = new SVNRevertDialog(parent, workingDir, files,- folderOnly, sceneIconAdded);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));+ auto dialog = new SVNRevertDialog(parent, workingDir, files, folderOnly,+ sceneIconAdded);++ connect(dialog, &SVNRevertDialog::done, this, &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::update(QWidget *parent, const QString &workingDir,- const QStringList &filesToUpdate,+void VersionControl::update(QWidget* parent, const QString& workingDir,+ const QStringList& filesToUpdate,int sceneIconsCounts, bool folderOnly,bool updateToRevision, bool nonRecursive) {- SVNUpdateDialog *dialog =+ auto dialog =new SVNUpdateDialog(parent, workingDir, filesToUpdate, sceneIconsCounts,folderOnly, updateToRevision, nonRecursive);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));++ connect(dialog, &SVNUpdateDialog::done, this, &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::updateAndLock(QWidget *parent, const QString &workingDir,- const QStringList &files,+void VersionControl::updateAndLock(QWidget* parent, const QString& workingDir,+ const QStringList& files,int workingRevision, int sceneIconAdded) {- SVNUpdateAndLockDialog *dialog = new SVNUpdateAndLockDialog(- parent, workingDir, files, workingRevision, sceneIconAdded);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));+ auto dialog = new SVNUpdateAndLockDialog(parent, workingDir, files,+ workingRevision, sceneIconAdded);++ connect(dialog, &SVNUpdateAndLockDialog::done, this,+ &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::lock(QWidget *parent, const QString &workingDir,- const QStringList &filesToLock, int sceneIconAdded) {- SVNLockDialog *dialog =+void VersionControl::lock(QWidget* parent, const QString& workingDir,+ const QStringList& filesToLock, int sceneIconAdded) {+ auto dialog =new SVNLockDialog(parent, workingDir, filesToLock, true, sceneIconAdded);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));++ connect(dialog, &SVNLockDialog::done, this, &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::unlock(QWidget *parent, const QString &workingDir,- const QStringList &filesToUnlock,+void VersionControl::unlock(QWidget* parent, const QString& workingDir,+ const QStringList& filesToUnlock,int sceneIconAdded) {- SVNLockDialog *dialog = new SVNLockDialog(parent, workingDir, filesToUnlock,- false, sceneIconAdded);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));+ auto dialog = new SVNLockDialog(parent, workingDir, filesToUnlock, false,+ sceneIconAdded);++ connect(dialog, &SVNLockDialog::done, this, &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::lockFrameRange(QWidget *parent, const QString &workingDir,- const QString &file, int frameCount) {- SVNLockFrameRangeDialog *dialog =+void VersionControl::lockFrameRange(QWidget* parent, const QString& workingDir,+ const QString& file, int frameCount) {+ auto dialog =new SVNLockFrameRangeDialog(parent, workingDir, file, frameCount);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));++ connect(dialog, &SVNLockFrameRangeDialog::done, this,+ &VersionControl::commandDone);dialog->show();dialog->raise();}-//-----------------------------------------------------------------------------+void VersionControl::lockFrameRange(QWidget* parent, const QString& workingDir,+ const QStringList& files) {+ auto dialog = new SVNLockMultiFrameRangeDialog(parent, workingDir, files);-void VersionControl::lockFrameRange(QWidget *parent, const QString &workingDir,- const QStringList &files) {- SVNLockMultiFrameRangeDialog *dialog =- new SVNLockMultiFrameRangeDialog(parent, workingDir, files);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));+ connect(dialog, &SVNLockMultiFrameRangeDialog::done, this,+ &VersionControl::commandDone);dialog->show();dialog->raise();}-//-----------------------------------------------------------------------------+void VersionControl::unlockFrameRange(QWidget* parent,+ const QString& workingDir,+ const QString& file) {+ auto dialog = new SVNUnlockFrameRangeDialog(parent, workingDir, file);-void VersionControl::unlockFrameRange(QWidget *parent,- const QString &workingDir,- const QString &file) {- SVNUnlockFrameRangeDialog *dialog =- new SVNUnlockFrameRangeDialog(parent, workingDir, file);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));+ connect(dialog, &SVNUnlockFrameRangeDialog::done, this,+ &VersionControl::commandDone);dialog->show();dialog->raise();}-//-----------------------------------------------------------------------------+void VersionControl::unlockFrameRange(QWidget* parent,+ const QString& workingDir,+ const QStringList& files) {+ auto dialog = new SVNUnlockMultiFrameRangeDialog(parent, workingDir, files);-void VersionControl::unlockFrameRange(QWidget *parent,- const QString &workingDir,- const QStringList &files) {- SVNUnlockMultiFrameRangeDialog *dialog =- new SVNUnlockMultiFrameRangeDialog(parent, workingDir, files);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));+ connect(dialog, &SVNUnlockMultiFrameRangeDialog::done, this,+ &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::showFrameRangeLockInfo(QWidget *parent,- const QString &workingDir,- const QString &file) {- SVNFrameRangeLockInfoDialog *dialog =- new SVNFrameRangeLockInfoDialog(parent, workingDir, file);+void VersionControl::showFrameRangeLockInfo(QWidget* parent,+ const QString& workingDir,+ const QString& file) {+ auto dialog = new SVNFrameRangeLockInfoDialog(parent, workingDir, file);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::showFrameRangeLockInfo(QWidget *parent,- const QString &workingDir,- const QStringList &files) {- SVNMultiFrameRangeLockInfoDialog *dialog =- new SVNMultiFrameRangeLockInfoDialog(parent, workingDir, files);+void VersionControl::showFrameRangeLockInfo(QWidget* parent,+ const QString& workingDir,+ const QStringList& files) {+ auto dialog = new SVNMultiFrameRangeLockInfoDialog(parent, workingDir, files);dialog->show();dialog->raise();}-//-----------------------------------------------------------------------------+void VersionControl::commitFrameRange(QWidget* parent,+ const QString& workingDir,+ const QString& file) {+ auto dialog = new SVNCommitFrameRangeDialog(parent, workingDir, file);-void VersionControl::commitFrameRange(QWidget *parent,- const QString &workingDir,- const QString &file) {- SVNCommitFrameRangeDialog *dialog =- new SVNCommitFrameRangeDialog(parent, workingDir, file);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));+ connect(dialog, &SVNCommitFrameRangeDialog::done, this,+ &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::revertFrameRange(QWidget *parent,- const QString &workingDir,- const QString &file,- const QString &tempFileName) {- SVNRevertFrameRangeDialog *dialog =+void VersionControl::revertFrameRange(QWidget* parent,+ const QString& workingDir,+ const QString& file,+ const QString& tempFileName) {+ auto dialog =new SVNRevertFrameRangeDialog(parent, workingDir, file, tempFileName);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));++ connect(dialog, &SVNRevertFrameRangeDialog::done, this,+ &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::deleteFiles(QWidget *parent, const QString &workingDir,- const QStringList &filesToDelete,+void VersionControl::deleteFiles(QWidget* parent, const QString& workingDir,+ const QStringList& filesToDelete,int sceneIconAdded) {- SVNDeleteDialog *dialog = new SVNDeleteDialog(- parent, workingDir, filesToDelete, false, sceneIconAdded);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));+ auto dialog = new SVNDeleteDialog(parent, workingDir, filesToDelete, false,+ sceneIconAdded);++ connect(dialog, &SVNDeleteDialog::done, this, &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::deleteFolder(QWidget *parent, const QString &workingDir,- const QString &folderName) {- SVNDeleteDialog *dialog =+void VersionControl::deleteFolder(QWidget* parent, const QString& workingDir,+ const QString& folderName) {+ auto dialog =new SVNDeleteDialog(parent, workingDir, QStringList(folderName), true, 0);- connect(dialog, SIGNAL(done(const QStringList &)), this,- SIGNAL(commandDone(const QStringList &)));++ connect(dialog, &SVNDeleteDialog::done, this, &VersionControl::commandDone);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::cleanupFolder(QWidget *parent, const QString &workingDir) {- SVNCleanupDialog *dialog = new SVNCleanupDialog(parent, workingDir);+void VersionControl::cleanupFolder(QWidget* parent, const QString& workingDir) {+ auto dialog = new SVNCleanupDialog(parent, workingDir);dialog->show();dialog->raise();}-//-------------------------------------------------------------------------------void VersionControl::purgeFolder(QWidget *parent, const QString &workingDir) {- SVNPurgeDialog *dialog = new SVNPurgeDialog(parent, workingDir);+void VersionControl::purgeFolder(QWidget* parent, const QString& workingDir) {+ auto dialog = new SVNPurgeDialog(parent, workingDir);dialog->show();dialog->raise();}//------------------------------------------------------------------------------QStringList VersionControl::getSceneContents(const QString &wokingDir,- const QString &sceneFileName) {+QStringList VersionControl::getSceneContents(const QString& workingDir,+ const QString& sceneFileName) {QStringList sceneContents;TFilePath scenePath =- TFilePath(wokingDir.toStdWString()) + sceneFileName.toStdWString();- if (!TFileStatus(scenePath).doesExist()) return sceneContents;+ TFilePath(workingDir.toStdWString()) + sceneFileName.toStdWString();++ if (!TFileStatus(scenePath).doesExist()) {+ return sceneContents;+ }ToonzScene scene;try {scene.load(scenePath);} catch (...) {+ return sceneContents;}- std::vector<TXshLevel *> levels;++ // Get all levels in the scene+ std::vector<TXshLevel*> levels;scene.getLevelSet()->listLevels(levels);- std::vector<TXshLevel *>::iterator it;- for (it = levels.begin(); it != levels.end(); ++it) {- TFilePath levelPath = scene.decodeFilePath((*it)->getPath());+ // Process each level+ for (auto level : levels) {+ TFilePath levelPath = scene.decodeFilePath(level->getPath());++ // Handle frame range filesif (levelPath.getDots() == "..") {TFilePath dir = levelPath.getParentDir();QDir qDir(QString::fromStdWString(dir.getWideString()));- QString levelName =- QRegExp::escape(QString::fromStdWString(levelPath.getWideName()));++ // Create regex pattern for frame files+ QString levelName = QRegularExpression::escape(+ QString::fromStdWString(levelPath.getWideName()));QString levelType = QString::fromStdString(levelPath.getType());- QString exp(levelName + ".[0-9]{1,4}." + levelType);- QRegExp regExp(exp);++ QString pattern =+ QString("%1\\.[0-9]{1,4}\\.%2").arg(levelName, levelType);+ QRegularExpression regex(pattern);++ // Find matching filesQStringList list = qDir.entryList(QDir::Files);- list = list.filter(regExp);- for (int i = 0; i < list.size(); i++) {- QString fileName = list.at(i);+ list = list.filter(regex);++ // Add each frame file+ for (const auto& fileName : list) {sceneContents.append(toQString(dir + fileName.toStdWString()));}- } else+ } else {sceneContents.append(toQString(levelPath));+ }+ // Get linked files for the levelTFilePathSet fpset;TXshSimpleLevel::getFiles(levelPath, fpset);- TFilePathSet::iterator it;- for (it = fpset.begin(); it != fpset.end(); ++it)- sceneContents.append(toQString(scene.decodeFilePath((*it))));+ for (const auto& linkedFile : fpset) {+ sceneContents.append(toQString(scene.decodeFilePath(linkedFile)));+ }}return sceneContents;@@ -913,22 +977,29 @@ QStringList VersionControl::getSceneContents(const QString &wokingDir,QStringList VersionControl::getCurrentSceneContents() const {QStringList contents;- ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();- if (!scene) return QStringList();- std::vector<TXshLevel *> levels;+ auto scene = TApp::instance()->getCurrentScene()->getScene();+ if (!scene) {+ return contents;+ }++ // Get all levels in current scene+ std::vector<TXshLevel*> levels;scene->getLevelSet()->listLevels(levels);- std::vector<TXshLevel *>::iterator it;- for (it = levels.begin(); it != levels.end(); ++it) {- TFilePath levelPath = scene->decodeFilePath((*it)->getPath());++ // Process each level+ for (auto level : levels) {+ TFilePath levelPath = scene->decodeFilePath(level->getPath());contents.append(toQString(levelPath));+ // Get linked files for the levelTFilePathSet fpset;TXshSimpleLevel::getFiles(levelPath, fpset);- TFilePathSet::iterator it;- for (it = fpset.begin(); it != fpset.end(); ++it)- contents.append(toQString(scene->decodeFilePath((*it))));+ for (const auto& linkedFile : fpset) {+ contents.append(toQString(scene->decodeFilePath(linkedFile)));+ }}+return contents;}diff --git a/toonz/sources/toonz/versioncontrol.h b/toonz/sources/toonz/versioncontrol.hindex 35607f8a4..10433bd0a 100644--- a/toonz/sources/toonz/versioncontrol.h+++ b/toonz/sources/toonz/versioncontrol.h@@ -3,190 +3,355 @@#ifndef VERSION_CONTROL_H#define VERSION_CONTROL_H+// Qt includes#include <QObject>#include <QThread>#include <QMutex>#include <QWaitCondition>#include <QProcess>+#include <QStringList>+// Version control includes#include "versioncontrolxmlreader.h"// Forward Declarations-class TXshSimpleLevel;class ToonzScene;class TLevelSet;+class QWidget;//------------------------------------------------------------------------------+/**+ * @brief Thread for executing version control commands asynchronously.+ *+ * This class provides a worker thread for executing Subversion (SVN) commands+ * in the background, allowing the UI to remain responsive during long-running+ * operations.+ */class VersionControlThread final : public QThread {Q_OBJECT- bool m_abort;- bool m_restart;- bool m_getStatus;-- bool m_readOutputOnDone;-- QString m_workingDir;- QString m_binary;- QStringList m_args;-- QWaitCondition m_condition;-- QProcess *m_process;-public:- QMutex m_mutex;-- VersionControlThread(QObject *parent = 0);- ~VersionControlThread();-- void executeCommand(const QString &workingDir, const QString &binary,- const QStringList &args, bool readOutputOnDone = true);-- void getSVNStatus(const QString &path, bool showUpdates = false,+ /**+ * @brief Constructs a version control thread.+ *+ * @param parent Parent QObject.+ */+ explicit VersionControlThread(QObject* parent = nullptr);++ /**+ * @brief Destructor that ensures thread termination.+ */+ ~VersionControlThread() override;++ /**+ * @brief Executes a version control command.+ *+ * @param workingDir Working directory for the command.+ * @param binary Command binary to execute.+ * @param args Command arguments.+ * @param readOutputOnDone Whether to read output after command completion.+ */+ void executeCommand(const QString& workingDir, const QString& binary,+ const QStringList& args, bool readOutputOnDone = true);++ /**+ * @brief Gets SVN status for a path.+ *+ * @param path Path to check status for.+ * @param showUpdates Whether to show updates.+ * @param nonRecursive Whether to perform non-recursive operation.+ * @param depthInfinity Whether to use infinite depth.+ */+ void getSVNStatus(const QString& path, bool showUpdates = false,bool nonRecursive = false, bool depthInfinity = false);- void getSVNStatus(const QString &path, const QStringList &files,++ /**+ * @brief Gets SVN status for specific files.+ *+ * @param path Working directory.+ * @param files List of files to check.+ * @param showUpdates Whether to show updates.+ * @param nonRecursive Whether to perform non-recursive operation.+ * @param depthInfinity Whether to use infinite depth.+ */+ void getSVNStatus(const QString& path, const QStringList& files,bool showUpdates = false, bool nonRecursive = false,bool depthInfinity = false);-protected:+ /**+ * @brief Requests thread termination.+ */+ void requestAbort();++private:+ /**+ * @brief Main thread execution loop.+ */void run() override;-protected slots:+ /**+ * @brief Cleans up the QProcess instance.+ */+ void cleanupProcess();++private slots:+ /**+ * @brief Handles standard output availability.+ */void onStandardOutputReady();signals:- void error(const QString &errorString);- void done(const QString &response);- void outputRetrieved(const QString &text);- void statusRetrieved(const QString &xmlResponse);+ /**+ * @brief Emitted when an error occurs.+ *+ * @param errorString Error description.+ */+ void error(const QString& errorString);++ /**+ * @brief Emitted when command execution completes.+ *+ * @param response Command response.+ */+ void done(const QString& response);++ /**+ * @brief Emitted when output is retrieved during execution.+ *+ * @param text Output text.+ */+ void outputRetrieved(const QString& text);++ /**+ * @brief Emitted when status retrieval completes.+ *+ * @param xmlResponse XML status response.+ */+ void statusRetrieved(const QString& xmlResponse);++private:+ // Thread control+ bool m_abort = false;+ bool m_restart = false;+ bool m_getStatus = false;+ bool m_readOutputOnDone = true;++ // Command parameters+ QString m_workingDir;+ QString m_binary;+ QStringList m_args;++ // Synchronization+ QMutex m_mutex;+ QWaitCondition m_condition;++ // Process+ QProcess* m_process = nullptr;};//------------------------------------------------------------------------------+/**+ * @brief Manager for version control frame range operations.+ *+ * Handles setting and managing frame ranges for levels under version control,+ * including lock/unlock operations for specific frame ranges.+ */class VersionControlManager final : public QObject {Q_OBJECT- VersionControlThread m_thread;-+public:+ /**+ * @brief Gets the singleton instance.+ *+ * @return VersionControlManager instance.+ */+ static VersionControlManager* instance();++ /**+ * @brief Sets frame range for levels in a level set.+ *+ * @param levelSet Level set to process.+ * @param deleteLater Whether to delete level set after processing.+ */+ void setFrameRange(TLevelSet* levelSet, bool deleteLater = false);++private:+ /**+ * @brief Private constructor for singleton pattern.+ */VersionControlManager();- //! For set Frame Range- ToonzScene *m_scene;- TLevelSet *m_levelSet;-- bool m_isRunning;- bool m_deleteLater;+ /**+ * @brief Cleans up resources.+ */+ void cleanupResources();++private slots:+ /**+ * @brief Handles completion of frame range operation.+ *+ * @param text Response text.+ */+ void onFrameRangeDone(const QString& text);++ /**+ * @brief Handles version control errors.+ *+ * @param text Error text.+ */+ void onError(const QString& text);++private:+ // Thread for async operations+ VersionControlThread m_thread;-public:- static VersionControlManager *instance();- void setFrameRange(TLevelSet *levelSet, bool deleteLater = false);+ // Scene and level set being processed+ ToonzScene* m_scene = nullptr;+ TLevelSet* m_levelSet = nullptr;-protected slots:- void onFrameRangeDone(const QString &text);- void onError(const QString &text);+ // State+ bool m_isRunning = false;+ bool m_deleteLater = false;};//------------------------------------------------------------------------------+/**+ * @brief Main version control interface.+ *+ * Provides access to version control operations and manages repositories+ * and user credentials.+ */class VersionControl final : public QObject {Q_OBJECT- QString m_userName;- QString m_password;-- VersionControl();-- QList<SVNRepository> m_repositories;-- QString m_executablePath;-public:- static VersionControl *instance();-- // Read Version Control repositories from config files+ /**+ * @brief Gets the singleton instance.+ *+ * @return VersionControl instance.+ */+ static VersionControl* instance();++ /**+ * @brief Initializes version control from configuration file.+ */void init();- // Check version control version and config file data, return false if there- // is some setup issue+ /**+ * @brief Tests version control setup.+ *+ * @return true if setup is valid, false otherwise.+ */bool testSetup();- bool isFolderUnderVersionControl(const QString &folderPath);+ /**+ * @brief Checks if a folder is under version control.+ *+ * @param folderPath Path to check.+ * @return true if folder is under version control.+ */+ bool isFolderUnderVersionControl(const QString& folderPath);- void setUserName(const QString &userName) { m_userName = userName; }+ // User credential management+ void setUserName(const QString& userName) { m_userName = userName; }QString getUserName() const { return m_userName; }- void setPassword(const QString &password) { m_password = password; }+ void setPassword(const QString& password) { m_password = password; }QString getPassword() const { return m_password; }- // filesToCommit must have relative path to the working dir- // Convert QStringList to TFilePath- void commit(QWidget *parent, const QString &workingDir,- const QStringList &filesToCommit, bool folderOnly,+ // Repository management+ QList<SVNRepository> getRepositories() const { return m_repositories; }+ QString getExecutablePath() const { return m_executablePath; }++ // File operations+ void commit(QWidget* parent, const QString& workingDir,+ const QStringList& filesToCommit, bool folderOnly,int sceneIconAdded = 0);- void update(QWidget *parent, const QString &workingDir,- const QStringList &filesToUpdate, int sceneIconsCounts,+ void update(QWidget* parent, const QString& workingDir,+ const QStringList& filesToUpdate, int sceneIconsCounts,bool folderOnly = true, bool updateToRevision = false,bool nonRecursive = false);- void updateAndLock(QWidget *parent, const QString &workingDir,- const QStringList &files, int workingRevision,++ void updateAndLock(QWidget* parent, const QString& workingDir,+ const QStringList& files, int workingRevision,int sceneIconAdded);- void revert(QWidget *parent, const QString &workingDir,- const QStringList &filesToRevert, bool folderOnly,+ void revert(QWidget* parent, const QString& workingDir,+ const QStringList& filesToRevert, bool folderOnly,int sceneIconAdded = 0);- void lock(QWidget *parent, const QString &workingDir,- const QStringList &filesToLock, int sceneIconAdded);- void unlock(QWidget *parent, const QString &workingDir,- const QStringList &filesToUnlock, int sceneIconAdded);+ // Lock operations+ void lock(QWidget* parent, const QString& workingDir,+ const QStringList& filesToLock, int sceneIconAdded);++ void unlock(QWidget* parent, const QString& workingDir,+ const QStringList& filesToUnlock, int sceneIconAdded);++ // Frame range operations+ void lockFrameRange(QWidget* parent, const QString& workingDir,+ const QString& file, int frameCount);- void lockFrameRange(QWidget *parent, const QString &workingDir,- const QString &file, int frameCount);- void lockFrameRange(QWidget *parent, const QString &workingDir,- const QStringList &files);+ void lockFrameRange(QWidget* parent, const QString& workingDir,+ const QStringList& files);- void unlockFrameRange(QWidget *parent, const QString &workingDir,- const QString &file);- void unlockFrameRange(QWidget *parent, const QString &workingDir,- const QStringList &files);+ void unlockFrameRange(QWidget* parent, const QString& workingDir,+ const QString& file);- void showFrameRangeLockInfo(QWidget *parent, const QString &workingDir,- const QString &file);- void showFrameRangeLockInfo(QWidget *parent, const QString &workingDir,- const QStringList &files);+ void unlockFrameRange(QWidget* parent, const QString& workingDir,+ const QStringList& files);- void commitFrameRange(QWidget *parent, const QString &workingDir,- const QString &file);+ void showFrameRangeLockInfo(QWidget* parent, const QString& workingDir,+ const QString& file);- void revertFrameRange(QWidget *parent, const QString &workingDir,- const QString &file, const QString &tempFileName);+ void showFrameRangeLockInfo(QWidget* parent, const QString& workingDir,+ const QStringList& files);- void deleteFiles(QWidget *parent, const QString &workingDir,- const QStringList &filesToDelete, int sceneIconAdded = 0);+ void commitFrameRange(QWidget* parent, const QString& workingDir,+ const QString& file);- void deleteFolder(QWidget *parent, const QString &workingDir,- const QString &folderName);+ void revertFrameRange(QWidget* parent, const QString& workingDir,+ const QString& file, const QString& tempFileName);- void cleanupFolder(QWidget *parent, const QString &workingDir);+ // Deletion operations+ void deleteFiles(QWidget* parent, const QString& workingDir,+ const QStringList& filesToDelete, int sceneIconAdded = 0);- void purgeFolder(QWidget *parent, const QString &workingDir);+ void deleteFolder(QWidget* parent, const QString& workingDir,+ const QString& folderName);++ // Maintenance operations+ void cleanupFolder(QWidget* parent, const QString& workingDir);+ void purgeFolder(QWidget* parent, const QString& workingDir);// Utility methods- QStringList getSceneContents(const QString &wokingDir,- const QString &sceneFileName);+ QStringList getSceneContents(const QString& workingDir,+ const QString& sceneFileName);QStringList getCurrentSceneContents() const;- QList<SVNRepository> getRepositories() const { return m_repositories; }+signals:+ /**+ * @brief Emitted when a version control command completes.+ *+ * @param files List of files affected by the command.+ */+ void commandDone(const QStringList& files);++private:+ /**+ * @brief Private constructor for singleton pattern.+ */+ VersionControl();- QString getExecutablePath() const { return m_executablePath; }+ // User credentials+ QString m_userName;+ QString m_password;-signals:- void commandDone(const QStringList &files);+ // Repository configuration+ QList<SVNRepository> m_repositories;+ QString m_executablePath;};#endif // VERSION_CONTROL_Hdiff --git a/toonz/sources/toonz/xdtsimportpopup.cpp b/toonz/sources/toonz/xdtsimportpopup.cppindex 6702017c7..425d25a1e 100644--- a/toonz/sources/toonz/xdtsimportpopup.cpp+++ b/toonz/sources/toonz/xdtsimportpopup.cpp@@ -1,3 +1,5 @@++#include "xdtsimportpopup.h"#include "tapp.h"@@ -24,87 +26,98 @@using namespace DVGui;namespace {-QIcon getColorChipIcon(TPixel32 color) {- QPixmap pm(15, 15);- pm.fill(QColor(color.r, color.g, color.b));- return QIcon(pm);++// Helper function to create color chip icon for cell marks+QIcon createColorChipIcon(TPixel32 color) {+ QPixmap pixmap(15, 15);+ pixmap.fill(QColor(color.r, color.g, color.b));+ return QIcon(pixmap);}-bool matchSequencePattern(const TFilePath& path) {- QRegularExpression pattern(- R"(- ^ # Match the start of the string- .*? # Optional prefix- \d+ # allow aFilePrefix<number>.ext- \. # Match a dot (.)- (png|jpg|jpeg|bmp|tga|tiff) # Image extensions- $ # Match the end of the string-)",- QRegularExpression::CaseInsensitiveOption |- QRegularExpression::ExtendedPatternSyntaxOption);+// Check if filename matches sequence pattern (digits before extension)+bool matchesSequencePattern(const TFilePath& path) {+ static const QRegularExpression pattern(+ R"(.*?\d+\.(png|jpg|jpeg|bmp|tga|tiff)$)",+ QRegularExpression::CaseInsensitiveOption);+return pattern.match(QString::fromStdString(path.getLevelName())).hasMatch();-};+}-bool isSharingSameParam(QString name1, QString name2) {+// Check if two filenames share same base name (without digits)+bool sharesSameBaseName(const QString& name1, const QString& name2) {std::wstring str1 = name1.toStdWString();std::wstring str2 = name2.toStdWString();+ // Remove digits from both stringsstr1.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;}-void fetchSequence(- std::vector<IoCmd::LoadResourceArguments::ResourceData>& rds) {- for (size_t i = 0; i < rds.size(); ++i) {- TFilePath currentPath = rds[i].m_path;- if (!matchSequencePattern(currentPath)) continue;+// Fetch sequence files and add them to resource data list+void fetchSequenceFiles(+ std::vector<IoCmd::LoadResourceArguments::ResourceData>& resources) {+ for (size_t i = 0; i < resources.size(); ++i) {+ const TFilePath currentPath = resources[i].m_path;+ if (!matchesSequencePattern(currentPath)) continue;- TFilePath thisFolder = currentPath.getParentDir();- QDir dir(thisFolder.getQString());+ const TFilePath parentDir = currentPath.getParentDir();+ QDir directory(parentDir.getQString());- QString searchPattern =+ const QString searchPattern ="*" + QString::fromStdString(currentPath.getDottedType());- QStringList foundFiles =- dir.entryList(QStringList(searchPattern), QDir::Files);+ const QStringList foundFiles =+ directory.entryList({searchPattern}, QDir::Files);+if (foundFiles.isEmpty()) continue;- QString thisFile = currentPath.withoutParentDir().getQString();++ const QString currentFile = currentPath.withoutParentDir().getQString();+for (const QString& foundFile : foundFiles) {- if (thisFile == foundFile) continue;+ if (currentFile == foundFile) continue;- if (isSharingSameParam(thisFile, foundFile)) {+ if (sharesSameBaseName(currentFile, foundFile)) {IoCmd::LoadResourceArguments::ResourceData newData;- newData.m_path = thisFolder + foundFile.toStdWString();- rds.insert(rds.begin() + (++i), newData);+ newData.m_path = parentDir + foundFile.toStdWString();+ resources.insert(resources.begin() + (++i), newData);}}}}+} // namespace//=============================================================================+// XDTSImportPopup implementation+//-----------------------------------------------------------------------------XDTSImportPopup::XDTSImportPopup(QStringList levelNames, ToonzScene* scene,TFilePath scenePath, bool isUextVersion,bool isSXF): m_scene(scene), m_isUext(isUextVersion)- , DVGui::Dialog(TApp::instance()->getMainWindow(), true, false,- "XDTSImport") {- QString type = isSXF ? "SXF" : "XDTS";- setWindowTitle(tr("Importing %1 file %2")- .arg(type)- .arg(QString::fromStdString(scenePath.getLevelName())));- QPushButton* loadButton = new QPushButton(tr("Load"), this);- QPushButton* cancelButton = new QPushButton(tr("Cancel"), this);-- m_tick1Combo = new QComboBox(this);- m_tick2Combo = new QComboBox(this);- QList<QComboBox*> combos = {m_tick1Combo, m_tick2Combo};-- m_renameCheckBox = new QCheckBox("Rename Image Sequence", this);+ , Dialog(TApp::instance()->getMainWindow(), true, false, "XDTSImport") {+ // Set dialog properties+ const QString fileType = isSXF ? "SXF" : "XDTS";+ setWindowTitle(+ tr("Importing %1 file %2")+ .arg(fileType, QString::fromStdString(scenePath.getLevelName())));++ // Create buttons+ auto loadButton = new QPushButton(tr("Load"), this);+ auto cancelButton = new QPushButton(tr("Cancel"), this);++ // Create combo boxes for cell marks+ m_tick1Combo = new QComboBox(this);+ m_tick2Combo = new QComboBox(this);+ QList<QComboBox*> comboBoxes = {m_tick1Combo, m_tick2Combo};++ // Create rename checkbox+ m_renameCheckBox = new QCheckBox(tr("Rename Image Sequence"), this);m_renameCheckBox->setChecked(true);++ // Create conversion combo boxm_convertCombo = new QComboBox(this);QStringList convertOptions = {tr("Do not Convert"), tr("Convert Every Level with Settings Popup"),@@ -112,26 +125,32 @@ XDTSImportPopup::XDTSImportPopup(QStringList levelNames, ToonzScene* scene,m_convertCombo->addItems(convertOptions);m_convertCombo->setCurrentIndex(0);- // Only works for 3rd Convert Option: NAA Unpainted- QWidget* convertNAAWidget = new QWidget(this);+ // Create NAA conversion widget (only visible for 3rd option)+ auto convertNAAWidget = new QWidget(this);convertNAAWidget->setVisible(false);- QHBoxLayout* convertNAALayout = new QHBoxLayout;- m_paletteCheckBox = new QCheckBox("Append Default Palette", this);+ auto convertNAALayout = new QHBoxLayout;++ m_paletteCheckBox = new QCheckBox(tr("Append Default Palette"), this);m_paletteCheckBox->setChecked(true);m_paletteCheckBox->setToolTip(tr("When activated, styles of the default ""palette\n($TOONZSTUDIOPALETTE\\Global Palettes\\Default ""Palettes\\Cleanup_Palette.tpl) will \nbe ""appended to the palette after conversion"));- QStringList dpiModes;- dpiModes << tr("Image DPI") << tr("Current Camera DPI") << tr("Custom DPI");++ QStringList dpiModes = {tr("Image DPI"), tr("Current Camera DPI"),+ tr("Custom DPI")};+m_dpiMode = new QComboBox(this);m_dpiMode->addItems(dpiModes);- m_dpiFld = new DVGui::DoubleLineEdit(this);- m_dpiFld->setValue(120);++ m_dpiFld = new DoubleLineEdit(this);+ m_dpiFld->setValue(120.0);m_dpiFld->setDisabled(true);++ // Connect DPI mode changeconnect(m_dpiMode, QOverload<int>::of(&QComboBox::currentIndexChanged), this,- [=](int index) {+ [this](int index) {m_dpiFld->setEnabled(index == 2); // Custom DPI});@@ -141,174 +160,196 @@ XDTSImportPopup::XDTSImportPopup(QStringList levelNames, ToonzScene* scene,convertNAALayout->addWidget(m_dpiMode);convertNAALayout->addWidget(m_dpiFld);convertNAAWidget->setLayout(convertNAALayout);++ // Connect conversion mode changeconnect(m_convertCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),this, [=](int index) {convertNAAWidget->setVisible(index == 2);- this->adjustSize();+ adjustSize();});+ // Create additional combo boxes for UEXT versionif (m_isUext) {m_keyFrameCombo = new QComboBox(this);m_referenceFrameCombo = new QComboBox(this);- combos << m_keyFrameCombo << m_referenceFrameCombo;+ comboBoxes << m_keyFrameCombo << m_referenceFrameCombo;}- QList<TSceneProperties::CellMark> marks = TApp::instance()- ->getCurrentScene()- ->getScene()- ->getProperties()- ->getCellMarks();- for (auto combo : combos) {- combo->addItem(tr("None"), -1);- int curId = 0;- for (auto mark : marks) {- QString label = QString("%1: %2").arg(curId).arg(mark.name);- combo->addItem(getColorChipIcon(mark.color), label, curId);- curId++;+ // Populate combo boxes with cell marks+ const auto cellMarks = TApp::instance()+ ->getCurrentScene()+ ->getScene()+ ->getProperties()+ ->getCellMarks();++ for (auto comboBox : comboBoxes) {+ comboBox->addItem(tr("None"), -1);+ int currentId = 0;++ for (const auto& mark : cellMarks) {+ const QString label = QString("%1: %2").arg(currentId).arg(mark.name);+ comboBox->addItem(createColorChipIcon(mark.color), label, currentId);+ ++currentId;}}++ // Set default selectionsm_tick1Combo->setCurrentIndex(m_tick1Combo->findData(6));m_tick2Combo->setCurrentIndex(m_tick2Combo->findData(8));+if (m_isUext) {m_keyFrameCombo->setCurrentIndex(m_keyFrameCombo->findData(0));m_referenceFrameCombo->setCurrentIndex(m_referenceFrameCombo->findData(4));}- QString description =+ // Create description label+ const QString description =tr("Please specify the level locations. Suggested paths ""are input in the fields with blue border.");- m_topLayout->addWidget(new QLabel(description, this), 0);+ m_topLayout->addWidget(new QLabel(description, this));m_topLayout->addSpacing(15);- QScrollArea* fieldsArea = new QScrollArea(this);+ // Create scroll area for file fields+ auto fieldsArea = new QScrollArea(this);fieldsArea->setWidgetResizable(true);- QWidget* fieldsWidget = new QWidget(this);-- QGridLayout* fieldsLay = new QGridLayout();- fieldsLay->setContentsMargins(0, 0, 0, 0);- fieldsLay->setHorizontalSpacing(10);- fieldsLay->setVerticalSpacing(10);- fieldsLay->addWidget(new QLabel(tr("Level Name"), this), 0, 0,- Qt::AlignLeft | Qt::AlignVCenter);- fieldsLay->addWidget(new QLabel(tr("Level Path"), this), 0, 1,- Qt::AlignLeft | Qt::AlignVCenter);- for (QString& levelName : levelNames) {- int row = fieldsLay->rowCount();- fieldsLay->addWidget(new QLabel(levelName, this), row, 0,- Qt::AlignRight | Qt::AlignVCenter);- FileField* fileField = new FileField(this);- fieldsLay->addWidget(fileField, row, 1);+ auto fieldsWidget = new QWidget(this);+ auto fieldsLayout = new QGridLayout();+ fieldsLayout->setContentsMargins(0, 0, 0, 0);+ fieldsLayout->setHorizontalSpacing(10);+ fieldsLayout->setVerticalSpacing(10);++ // Add column headers+ fieldsLayout->addWidget(new QLabel(tr("Level Name"), this), 0, 0,+ Qt::AlignLeft | Qt::AlignVCenter);+ fieldsLayout->addWidget(new QLabel(tr("Level Path"), this), 0, 1,+ Qt::AlignLeft | Qt::AlignVCenter);++ // Create file field for each level name+ for (const QString& levelName : levelNames) {+ const int row = fieldsLayout->rowCount();+ fieldsLayout->addWidget(new QLabel(levelName, this), row, 0,+ Qt::AlignRight | Qt::AlignVCenter);++ auto fileField = new FileField(this);+ fieldsLayout->addWidget(fileField, row, 1);+m_fields.insert(levelName, fileField);fileField->setFileMode(QFileDialog::AnyFile);fileField->setObjectName("SuggestiveFileField");- connect(fileField, SIGNAL(pathChanged()), this, SLOT(onPathChanged()));++ // Connect path changed signal+ connect(fileField, &FileField::pathChanged, this,+ &XDTSImportPopup::onPathChanged);}- fieldsLay->setColumnStretch(1, 1);- fieldsLay->setRowStretch(fieldsLay->rowCount(), 1);- fieldsWidget->setLayout(fieldsLay);+ fieldsLayout->setColumnStretch(1, 1);+ fieldsLayout->setRowStretch(fieldsLayout->rowCount(), 1);++ fieldsWidget->setLayout(fieldsLayout);fieldsArea->setWidget(fieldsWidget);m_topLayout->addWidget(fieldsArea, 1);- // ���T ����^�����Q�l�̃R�}�}�[�N�̃��C�A�E�g����I+ // Create cell mark group box+ auto cellMarkGroupBox =+ new QGroupBox(tr("Cell marks for %1 symbols").arg(fileType));++ auto markLayout = new QGridLayout();+ markLayout->setContentsMargins(10, 10, 10, 10);+ markLayout->setVerticalSpacing(10);+ markLayout->setHorizontalSpacing(5);- // cell mark area- QGroupBox* cellMarkGroupBox = new QGroupBox(- tr("Cell marks for %1 symbols").arg(isSXF ? "SXF" : "XDTS"));- QGridLayout* markLay = new QGridLayout();- markLay->setContentsMargins(10, 10, 10, 10);- markLay->setVerticalSpacing(10);- markLay->setHorizontalSpacing(5);{- // 0x25CB = ��, 0x25CF = ��- QChar symbol1 = isSXF ? QChar(0x25CB) : QChar('0');- QChar symbol2 = isSXF ? QChar(0x25CF) : QChar('*');- markLay->addWidget(+ // Symbols for SXF: ○ (0x25CB) and ● (0x25CF)+ // Symbols for XDTS: '0' and '*'+ const QChar symbol1 = isSXF ? QChar(0x25CB) : QChar('0');+ const QChar symbol2 = isSXF ? QChar(0x25CF) : QChar('*');++ markLayout->addWidget(new QLabel(tr("Inbetween Symbol1 (%1):").arg(symbol1), this), 0, 0,Qt::AlignRight | Qt::AlignVCenter);- markLay->addWidget(m_tick1Combo, 0, 1);- markLay->addItem(new QSpacerItem(10, 1), 0, 2);- markLay->addWidget(+ markLayout->addWidget(m_tick1Combo, 0, 1);+ markLayout->addItem(new QSpacerItem(10, 1), 0, 2);+ markLayout->addWidget(new QLabel(tr("Inbetween Symbol2 (%1):").arg(symbol2), this), 0, 3,Qt::AlignRight | Qt::AlignVCenter);- markLay->addWidget(m_tick2Combo, 0, 4);+ markLayout->addWidget(m_tick2Combo, 0, 4);if (m_isUext) {- markLay->addWidget(new QLabel(QObject::tr("Keyframe Symbol:")), 1, 0,- Qt::AlignRight | Qt::AlignVCenter);- markLay->addWidget(m_keyFrameCombo, 1, 1);- markLay->addWidget(new QLabel(QObject::tr("Reference Frame Symbol:")), 1,- 3, Qt::AlignRight | Qt::AlignVCenter);- markLay->addWidget(m_referenceFrameCombo, 1, 4);+ markLayout->addWidget(new QLabel(tr("Keyframe Symbol:"), this), 1, 0,+ Qt::AlignRight | Qt::AlignVCenter);+ markLayout->addWidget(m_keyFrameCombo, 1, 1);+ markLayout->addWidget(new QLabel(tr("Reference Frame Symbol:"), this), 1,+ 3, Qt::AlignRight | Qt::AlignVCenter);+ markLayout->addWidget(m_referenceFrameCombo, 1, 4);}}- cellMarkGroupBox->setLayout(markLay);+ cellMarkGroupBox->setLayout(markLayout);m_topLayout->addWidget(cellMarkGroupBox, 0, Qt::AlignRight);- QHBoxLayout* checkBoxLayout = new QHBoxLayout;- checkBoxLayout->addWidget(- new QLabel(QObject::tr("Convert Raster to TLV : ")));+ // Create conversion options layout+ auto checkBoxLayout = new QHBoxLayout;+ checkBoxLayout->addWidget(new QLabel(tr("Convert Raster to TLV : ")));checkBoxLayout->addWidget(m_convertCombo);checkBoxLayout->addStretch();checkBoxLayout->addWidget(m_renameCheckBox);m_topLayout->addLayout(checkBoxLayout);m_topLayout->addWidget(convertNAAWidget);- connect(loadButton, SIGNAL(clicked()), this, SLOT(accept()));- connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));++ // Connect buttons using modern signal/slot syntax+ connect(loadButton, &QPushButton::clicked, this, &QDialog::accept);+ connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject);addButtonBarWidget(loadButton, cancelButton);- this->adjustSize();+ adjustSize();updateSuggestions(scenePath.getQString());}//-----------------------------------------------------------------------------void XDTSImportPopup::onPathChanged() {- FileField* fileField = dynamic_cast<FileField*>(sender());+ auto fileField = qobject_cast<FileField*>(sender());if (!fileField) return;- QString levelName = m_fields.key(fileField);- // make the fields non-suggestive++ const QString levelName = m_fields.key(fileField);++ // Remove level from suggested list since user changed itm_pathSuggestedLevels.removeAll(levelName);- // if the path is specified under the sub-folder with the same name as the- // level, then try to make suggestions from the parent folder of it- TFilePath fp =- m_scene->decodeFilePath(TFilePath(fileField->getPath())).getParentDir();- if (QDir(fp.getQString()).dirName() == levelName)- updateSuggestions(fp.getQString());+ // Check if path is in sub-folder with same name as level+ // (common in CSP exports like foo/A/A.tlv)+ const TFilePath currentPath =+ m_scene->decodeFilePath(TFilePath(fileField->getPath()));+ const TFilePath parentDir = currentPath.getParentDir();++ QDir directory(parentDir.getQString());+ if (directory.dirName() == levelName) {+ updateSuggestions(parentDir.getQString());+ }updateSuggestions(fileField->getPath());}//------------------------------------------------------------------------------void XDTSImportPopup::updateSuggestions(const QString samplePath) {- TFilePath fp(samplePath);- fp = m_scene->decodeFilePath(fp).getParentDir();- QDir suggestFolder(fp.getQString());- QStringList filters;- filters << "*.bmp"- << "*.jpg"- << "*.jpeg"- << "*.nol"- << "*.pic"- << "*.pict"- << "*.pct"- << "*.png"- << "*.rgb"- << "*.sgi"- << "*.tga"- << "*.tif"- << "*.tiff"- << "*.tlv"- << "*.pli"- << "*.psd";+void XDTSImportPopup::updateSuggestions(const QString& samplePath) {+ TFilePath filePath(samplePath);+ filePath = m_scene->decodeFilePath(filePath).getParentDir();++ QDir suggestFolder(filePath.getQString());++ // Supported image file extensions+ static const QStringList filters = {"*.bmp", "*.jpg", "*.jpeg", "*.nol",+ "*.pic", "*.pict", "*.pct", "*.png",+ "*.rgb", "*.sgi", "*.tga", "*.tif",+ "*.tiff", "*.tlv", "*.pli", "*.psd"};+suggestFolder.setNameFilters(filters);suggestFolder.setFilter(QDir::Files);+TFilePathSet pathSet;try {TSystem::readDirectory(pathSet, suggestFolder, true);@@ -316,29 +357,34 @@ void XDTSImportPopup::updateSuggestions(const QString samplePath) {return;}- QMap<QString, FileField*>::iterator fieldsItr = m_fields.begin();- bool suggested = false;+ auto fieldsItr = m_fields.begin();+ bool suggested = false;+while (fieldsItr != m_fields.end()) {- QString levelName = fieldsItr.key();- FileField* fileField = fieldsItr.value();- // check if the field can be filled with suggestion+ const QString levelName = fieldsItr.key();+ FileField* fileField = fieldsItr.value();++ // Check if field can be filled with suggestionif (fileField->getPath().isEmpty() ||m_pathSuggestedLevels.contains(levelName)) {- // input suggestion if there is a file with the same level namebool found = false;- for (TFilePath path : pathSet) {++ // Look for file with same name as level in current folder+ for (const auto& path : pathSet) {if (path.getName() == levelName.toStdString()) {- TFilePath codedPath = m_scene->codeFilePath(path);+ const TFilePath codedPath = m_scene->codeFilePath(path);fileField->setPath(codedPath.getQString());- if (!m_pathSuggestedLevels.contains(levelName))++ if (!m_pathSuggestedLevels.contains(levelName)) {m_pathSuggestedLevels.append(levelName);+ }+found = true;break;}}- // Not found in the current folder.- // Then check if there is a sub-folder with the same name as the level- // (like foo/A/A.tlv), as CSP exports levels like that.++ // If not found, check sub-folder with same name as levelif (!found && suggestFolder.cd(levelName)) {TFilePathSet subPathSet;try {@@ -346,83 +392,91 @@ void XDTSImportPopup::updateSuggestions(const QString samplePath) {} catch (...) {return;}- for (TFilePath path : subPathSet) {++ for (const auto& path : subPathSet) {if (path.getName() == levelName.toStdString()) {- suggested = true;- TFilePath codedPath = m_scene->codeFilePath(path);+ suggested = true;+ const TFilePath codedPath = m_scene->codeFilePath(path);fileField->setPath(codedPath.getQString());- if (!m_pathSuggestedLevels.contains(levelName))++ if (!m_pathSuggestedLevels.contains(levelName)) {m_pathSuggestedLevels.append(levelName);+ }+break;}}- // back to parent folder- suggestFolder.cdUp();++ suggestFolder.cdUp(); // Return to parent folder}+if (found) suggested = true;}+++fieldsItr;}- // fallBack search- if (!suggested) updateSuggestions(fp);+ // Fallback search if no suggestions found+ if (!suggested) {+ updateSuggestions(filePath);+ }- // Repaint fields:- // - Suggested fields: highlight with a blue border- // - Non-suggested fields:- // if empty, set their internal path to the scene's parent directory,- // but clear the text so the user does not see it+ // Update field styles based on suggestion statusfieldsItr = m_fields.begin();while (fieldsItr != m_fields.end()) {- if (m_pathSuggestedLevels.contains(fieldsItr.key()))- fieldsItr.value()->setStyleSheet(- QString("#SuggestiveFileField "- "QLineEdit{border-color:#2255aa;border-width:2px;}"));- else {- fieldsItr.value()->setStyleSheet(QString(""));- if (fieldsItr.value()->getPath().isEmpty()) {- fieldsItr.value()->setPath(- m_scene->getScenePath().getParentDir().getQString());- fieldsItr.value()->getField()->clear();+ FileField* field = fieldsItr.value();++ if (m_pathSuggestedLevels.contains(fieldsItr.key())) {+ // Highlight suggested fields with blue border+ field->setStyleSheet(+ "#SuggestiveFileField QLineEdit {"+ "border-color: #2255aa;"+ "border-width: 2px;"+ "}");+ } else {+ // Clear styling for non-suggested fields+ field->setStyleSheet("");++ // Set default path but clear displayed text+ if (field->getPath().isEmpty()) {+ field->setPath(m_scene->getScenePath().getParentDir().getQString());+ field->getField()->clear();}}+++fieldsItr;}}//------------------------------------------------------------------------------// FALL BACK+void XDTSImportPopup::updateSuggestions(const TFilePath& path) {- QMap<QString, FileField*>::iterator fieldsItr = m_fields.begin();- QStringList filters;- filters << "*.bmp"- << "*.jpg"- << "*.jpeg"- << "*.nol"- << "*.pic"- << "*.pict"- << "*.pct"- << "*.png"- << "*.rgb"- << "*.sgi"- << "*.tga"- << "*.tif"- << "*.tiff";+ static const QStringList filters = {+ "*.bmp", "*.jpg", "*.jpeg", "*.nol", "*.pic", "*.pict", "*.pct",+ "*.png", "*.rgb", "*.sgi", "*.tga", "*.tif", "*.tiff"};+bool suggestFolderFound = false;QDir suggestFolder(path.getQString());+auto assignMatchingFiles = [&](QStringList& files) {- QMap<QString, FileField*>::iterator it = m_fields.begin();+ auto it = m_fields.begin();while (it != m_fields.end()) {- QString levelName = it.key();- FileField* fileField = it.value();+ const QString levelName = it.key();+ FileField* fileField = it.value();+if (fileField->getPath().isEmpty() ||m_pathSuggestedLevels.contains(levelName)) {- QString filePattern = ".*" + levelName + ".*" + ".{3,4}$";- int index = files.indexOf(QRegExp(filePattern));+ // Create regex pattern to match level name with any extension+ const QString filePattern =+ QString(".*%1.*\\.[a-zA-Z0-9]{3,4}$").arg(levelName);+ const QRegularExpression regex(filePattern);++ const int index = files.indexOf(regex);if (index != -1) {suggestFolderFound = true;- TFilePath foundPath(suggestFolder.filePath(files[index]));- TFilePath codedPath = m_scene->codeFilePath(foundPath);+ const TFilePath foundPath(suggestFolder.filePath(files[index]));+ const TFilePath codedPath = m_scene->codeFilePath(foundPath);+fileField->setPath(codedPath.getQString());files.removeAt(index);m_pathSuggestedLevels.append(levelName);@@ -432,43 +486,49 @@ void XDTSImportPopup::updateSuggestions(const TFilePath& path) {}};- // Relative Paths- QStringList relPaths = suggestFolder.entryList(+ // Search in relative paths+ QStringList relativePaths = suggestFolder.entryList(filters, QDir::Files | QDir::Readable | QDir::NoDotAndDotDot);- assignMatchingFiles(relPaths);++ assignMatchingFiles(relativePaths);if (!suggestFolderFound) {- relPaths.clear();- QStringList subDirs = suggestFolder.entryList(QDir::Dirs | QDir::Readable |- QDir::NoDotAndDotDot);+ relativePaths.clear();++ // Search in subdirectories+ const QStringList subDirs = suggestFolder.entryList(+ QDir::Dirs | QDir::Readable | QDir::NoDotAndDotDot);+for (const QString& subDirName : subDirs) {QDir subDir = suggestFolder;if (!subDir.cd(subDirName)) continue;- QStringList filesInSubDir = subDir.entryList(+ const QStringList filesInSubDir = subDir.entryList(filters, QDir::Files | QDir::Readable | QDir::NoDotAndDotDot);+for (const QString& file : filesInSubDir) {- relPaths.append(subDirName + "/" + file);+ relativePaths.append(subDirName + "/" + file);}}- assignMatchingFiles(relPaths);++ assignMatchingFiles(relativePaths);}}//------------------------------------------------------------------------------QString XDTSImportPopup::getLevelPath(QString levelName) {- FileField* field = m_fields.value(levelName);- if (!field) return QString();- return field->getPath();+QString XDTSImportPopup::getLevelPath(const QString& levelName) const {+ auto field = m_fields.value(levelName);+ return field ? field->getPath() : QString();}//-----------------------------------------------------------------------------void XDTSImportPopup::getMarkerIds(int& tick1Id, int& tick2Id, int& keyFrameId,- int& referenceFrameId) {+ int& referenceFrameId) const {tick1Id = m_tick1Combo->currentData().toInt();tick2Id = m_tick2Combo->currentData().toInt();+if (m_isUext) {keyFrameId = m_keyFrameCombo->currentData().toInt();referenceFrameId = m_referenceFrameCombo->currentData().toInt();@@ -478,50 +538,87 @@ void XDTSImportPopup::getMarkerIds(int& tick1Id, int& tick2Id, int& keyFrameId,}}+//-----------------------------------------------------------------------------+void XDTSImportPopup::accept() {QDialog::accept();- std::vector<IoCmd::LoadResourceArguments::ResourceData> rds;++ std::vector<IoCmd::LoadResourceArguments::ResourceData> resourceData;++ // Collect resource data from fieldsfor (auto it = m_fields.constBegin(); it != m_fields.constEnd(); ++it) {- auto name = it.key();- auto field = it.value();+ IoCmd::LoadResourceArguments::ResourceData data;+ data.m_path = TFilePath(it.value()->getPath());+ resourceData.push_back(data);+ }++ // Fetch sequence files if available+ fetchSequenceFiles(resourceData);++ // Rename resources if checkbox is checked+ if (m_renameCheckBox->isChecked()) {+ IoCmd::renameResources(resourceData, false);}- IoCmd::LoadResourceArguments::ResourceData d;- for (auto field : m_fields) rds.push_back(TFilePath(field->getPath()));- fetchSequence(rds);- if (m_renameCheckBox->isChecked()) IoCmd::renameResources(rds, false);- if (int ret = m_convertCombo->currentIndex()) {- if (ret == 1) {- // Convert One by One- ConvertPopup popup;- for (auto& rd : rds) {- popup.setWindowModality(Qt::ApplicationModal);- TFileType::Type type = TFileType::getInfo(rd.m_path);- if (!TFileType::isFullColor(type)) continue;- popup.setFiles({rd.m_path});- popup.show();- popup.setFormat("tlv");- popup.adjustSize();- while (popup.isVisible() || popup.isConverting())- QCoreApplication::processEvents(QEventLoop::AllEvents |- QEventLoop::WaitForMoreEvents);- TFilePath convertedPath = popup.getConvertedPath(rd.m_path);- if (!convertedPath.isEmpty()) rd.m_path = convertedPath;++ // Handle conversion based on selected option+ const int conversionOption = m_convertCombo->currentIndex();++ if (conversionOption == 1) {+ // Convert each level individually with settings popup+ ConvertPopup popup;++ for (auto& data : resourceData) {+ const TFileType::Type fileType = TFileType::getInfo(data.m_path);+ if (!TFileType::isFullColor(fileType)) continue;++ popup.setWindowModality(Qt::ApplicationModal);+ popup.setFiles({data.m_path});+ popup.setFormat("tlv");+ popup.adjustSize();+ popup.show();++ // Wait for conversion to complete+ while (popup.isVisible() || popup.isConverting()) {+ QCoreApplication::processEvents(QEventLoop::AllEvents |+ QEventLoop::WaitForMoreEvents);}- } else {- // Convert NAA Unpainted- int index = m_dpiMode->currentIndex();- double dpi = 0;- if (index == 1) {- TCamera* camera =- TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera();- if (camera) dpi = camera->getDpi().x;- } else if (index == 2)- dpi = m_dpiFld->getValue();- IoCmd::convertNAARaster2TLV(- rds, false, dpi,- m_paletteCheckBox->isChecked()); // Only Generate Inks++ const TFilePath convertedPath = popup.getConvertedPath(data.m_path);+ if (!convertedPath.isEmpty()) {+ data.m_path = convertedPath;+ }+ }+ } else if (conversionOption == 2) {+ // Convert NAA Unpainted raster to TLV+ double dpi = 0.0;+ const int dpiIndex = m_dpiMode->currentIndex();++ if (dpiIndex == 1) {+ // Use current camera DPI+ if (const auto camera = TApp::instance()+ ->getCurrentScene()+ ->getScene()+ ->getCurrentCamera()) {+ dpi = camera->getDpi().x;+ }+ } else if (dpiIndex == 2) {+ // Use custom DPI+ dpi = m_dpiFld->getValue();}++ IoCmd::convertNAARaster2TLV(+ resourceData,+ false, // not generating paints, only inks+ dpi,+ m_paletteCheckBox->isChecked() // append default palette+ );}- int i = 0;- for (auto field : m_fields) field->setPath(rds[i++].m_path.getQString());-}\ No newline at end of file++ // Update fields with potentially converted paths+ int index = 0;+ for (auto it = m_fields.begin(); it != m_fields.end(); ++it, ++index) {+ if (index < static_cast<int>(resourceData.size())) {+ it.value()->setPath(resourceData[index].m_path.getQString());+ }+ }+}diff --git a/toonz/sources/toonz/xdtsimportpopup.h b/toonz/sources/toonz/xdtsimportpopup.hindex 63e2aeb81..b6b9ee4a7 100644--- a/toonz/sources/toonz/xdtsimportpopup.h+++ b/toonz/sources/toonz/xdtsimportpopup.h@@ -1,55 +1,125 @@#pragma once+#ifndef XDTSIMPORTPOPUP_H#define XDTSIMPORTPOPUP_H+// Qt includes+#include <QMap>+#include <QStringList>+#include <QCheckBox>++// ToonzQt includes#include "toonzqt/dvdialog.h"#include "toonzqt/doublefield.h"-#include "tfilepath.h"-#include <QMap>-#include <QCheckBox>+// ToonzCore includes+#include "tfilepath.h"+// Forward declarationsnamespace DVGui {class FileField;}+class ToonzScene;class QComboBox;-class XDTSImportPopup : public DVGui::Dialog {+//=============================================================================+// XDTSImportPopup+//-----------------------------------------------------------------------------++/**+ * Dialog for importing XDTS/SXF files with level mapping and conversion+ * options.+ */+class XDTSImportPopup final : public DVGui::Dialog {Q_OBJECT++ // UI Elements+ QComboBox* m_tick1Combo = nullptr;+ QComboBox* m_tick2Combo = nullptr;+ QComboBox* m_keyFrameCombo = nullptr;+ QComboBox* m_referenceFrameCombo = nullptr;+ QCheckBox* m_renameCheckBox = nullptr;+ QComboBox* m_convertCombo = nullptr;++ // NAA conversion options (visible only for 3rd conversion option)+ QCheckBox* m_paletteCheckBox = nullptr;+ QComboBox* m_dpiMode = nullptr;+ DVGui::DoubleLineEdit* m_dpiFld = nullptr;++ // Data membersQMap<QString, DVGui::FileField*> m_fields;QStringList m_pathSuggestedLevels;- ToonzScene* m_scene;+ ToonzScene* m_scene = nullptr;+ bool m_isUext = false; // Whether loading UEXT (unofficial extension) version- QComboBox *m_tick1Combo, *m_tick2Combo, *m_keyFrameCombo,- *m_referenceFrameCombo;- QCheckBox* m_renameCheckBox;- QComboBox* m_convertCombo;+public:+ /**+ * Constructs an XDTS/SXF import dialog.+ *+ * @param levelNames List of level names to import.+ * @param scene Pointer to the current Toonz scene.+ * @param scenePath Path to the scene file being imported.+ * @param isUextVersion Whether importing UEXT version.+ * @param isSXF Whether importing SXF format (vs XDTS).+ */+ explicit XDTSImportPopup(QStringList levelNames, ToonzScene* scene,+ TFilePath scenePath, bool isUextVersion,+ bool isSXF = false);- // Only works for 3rd Convert Option: NAA Unpainted- QCheckBox* m_paletteCheckBox;- QComboBox* m_dpiMode;- DVGui::DoubleLineEdit* m_dpiFld;+ /**+ * Gets the file path for a specific level.+ *+ * @param levelName Name of the level.+ * @return The file path for the level, or empty string if not found.+ */+ QString getLevelPath(const QString& levelName) const;- bool m_isUext; // whether if the loading xdts is unofficial extension (UEXT)- // version+ /**+ * Gets the marker IDs for cell marks.+ *+ * @param tick1Id Output parameter for tick1 symbol ID.+ * @param tick2Id Output parameter for tick2 symbol ID.+ * @param keyFrameId Output parameter for keyframe symbol ID.+ * @param referenceFrameId Output parameter for reference frame symbol ID.+ */+ void getMarkerIds(int& tick1Id, int& tick2Id, int& keyFrameId,+ int& referenceFrameId) const;- void updateSuggestions(const QString samplePath);+private:+ /**+ * Updates path suggestions based on a sample path.+ *+ * Searches for files matching level names in the directory of the+ * sample path and its subdirectories.+ */+ void updateSuggestions(const QString& samplePath);- // Fallback Search+ /**+ * Fallback search for path suggestions.+ *+ * Performs a broader search when the initial suggestion method+ * doesn't find matching files.+ */void updateSuggestions(const TFilePath& path);-public:- XDTSImportPopup(QStringList levelNames, ToonzScene* scene,- TFilePath scenePath, bool isUextVersion, bool isSXF = false);- QString getLevelPath(QString levelName);- void getMarkerIds(int& tick1Id, int& tick2Id, int& keyFrameId,- int& referenceFrameId);-protected slots:+private slots:+ /**+ * Handles path changes in file fields.+ *+ * Triggered when a user modifies a file field. Updates suggestions+ * based on the new path.+ */void onPathChanged();protected:+ /**+ * Handles dialog acceptance.+ *+ * Processes all selected files, performs conversions if requested,+ * and completes the import operation.+ */void accept() override;};-#endif\ No newline at end of file+#endif // XDTSIMPORTPOPUP_Hdiff --git a/toonz/sources/toonz/xdtsio.cpp b/toonz/sources/toonz/xdtsio.cppindex 8a32459f2..433424efc 100644--- a/toonz/sources/toonz/xdtsio.cpp+++ b/toonz/sources/toonz/xdtsio.cpp@@ -37,106 +37,122 @@#include <QComboBox>#include <QLabel>#include <QGroupBox>+using namespace XdtsIo;+namespace {-static QByteArray identifierStr("exchangeDigitalTimeSheet Save Data");+// XDTS file identifier string+static const QByteArray identifierStr("exchangeDigitalTimeSheet Save Data");-QIcon getColorChipIcon(TPixel32 color) {- QPixmap pm(15, 15);- pm.fill(QColor(color.r, color.g, color.b));- return QIcon(pm);+// Create color chip icon for cell marks+QIcon createColorChipIcon(TPixel32 color) {+ QPixmap pixmap(15, 15);+ pixmap.fill(QColor(color.r, color.g, color.b));+ return QIcon(pixmap);}-int _tick1Id = -1;-int _tick2Id = -1;-int _keyFrameId = -1;-int _referenceFrameId = -1;-bool _isUextVersion = false; // set to true when XDTS is written in UEXT- // (unofficial extension) version-bool _exportAllColumn = true;+// Global variables for export configuration+int tick1Id = -1;+int tick2Id = -1;+int keyFrameId = -1;+int referenceFrameId = -1;+bool isUextVersion = false; // Whether XDTS is written in UEXT version+bool exportAllColumn = true;const QString OPTION_KEYFRAME = "OPTION_KEYFRAME";const QString OPTION_REFERENCEFRAME = "OPTION_REFERENCEFRAME";+} // namespace++//=============================================================================+// XdtsHeader implementation//------------------------------------------------------------------------------void XdtsHeader::read(const QJsonObject &json) {- QRegularExpression rx("^\\d{1,4}$");- // TODO: We could check if the keys are valid- // before attempting to read them with QJsonObject::contains(),- // but we assume that they are.++void XdtsHeader::read(const QJsonObject& json) {+ static const QRegularExpression rx("^\\d{1,4}$");+m_cut = json["cut"].toString();- if (!rx.match(m_cut).hasMatch()) // TODO: should handle an error- qWarning()- << "The XdtsHeader value 'cut' value does not match expected pattern:"- << m_cut;+ if (!rx.match(m_cut).hasMatch()) {+ qWarning() << "XdtsHeader 'cut' value does not match expected pattern:"+ << m_cut;+ }+m_scene = json["scene"].toString();- if (!rx.match(m_scene).hasMatch())- qWarning()- << "The XdtsHeader value 'scene' value does not match expected pattern:"- << m_scene;+ if (!rx.match(m_scene).hasMatch()) {+ qWarning() << "XdtsHeader 'scene' value does not match expected pattern:"+ << m_scene;+ }}-void XdtsHeader::write(QJsonObject &json) const {+void XdtsHeader::write(QJsonObject& json) const {json["cut"] = m_cut;json["scene"] = m_scene;}+//=============================================================================+// XdtsFrameDataItem implementation//------------------------------------------------------------------------------TFrameId XdtsFrameDataItem::str2Fid(const QString &str) const {+TFrameId XdtsFrameDataItem::str2Fid(const QString& str) const {if (str.isEmpty()) return TFrameId::EMPTY_FRAME;+bool ok;- int frame = str.toInt(&ok);+ const int frame = str.toInt(&ok);if (ok) return TFrameId(frame);- QString regExpStr = QString("^%1$").arg(TFilePath::fidRegExpStr());- QRegularExpression rx(regExpStr);- QRegularExpressionMatch match = rx.match(str);+ static const QRegularExpression rx(+ QString("^%1$").arg(TFilePath::fidRegExpStr()));+ const auto match = rx.match(str);if (!match.hasMatch()) return TFrameId();- if (match.captured(2).isEmpty())+ if (match.captured(2).isEmpty()) {return TFrameId(match.captured(1).toInt());- else+ } else {return TFrameId(match.captured(1).toInt(), match.captured(2));+ }}-QString XdtsFrameDataItem::fid2Str(const TFrameId &fid) const {- if (fid.getNumber() == -1)+QString XdtsFrameDataItem::fid2Str(const TFrameId& fid) const {+ if (fid.getNumber() == -1) {return QString("SYMBOL_NULL_CELL");- else if (fid.getNumber() == SYMBOL_TICK_1)+ } else if (fid.getNumber() == SYMBOL_TICK_1) {return QString("SYMBOL_TICK_1");- else if (fid.getNumber() == SYMBOL_TICK_2)+ } else if (fid.getNumber() == SYMBOL_TICK_2) {return QString("SYMBOL_TICK_2");- else if (fid.getLetter().isEmpty())+ } else if (fid.getLetter().isEmpty()) {return QString::number(fid.getNumber());+ }return QString::number(fid.getNumber()) + fid.getLetter();}-void XdtsFrameDataItem::read(const QJsonObject &json) {- m_id = DataId(qRound(json["id"].toDouble()));- QJsonArray valuesArray = json["values"].toArray();- for (const QJsonValue &value : valuesArray) {+void XdtsFrameDataItem::read(const QJsonObject& json) {+ m_id = DataId(qRound(json["id"].toDouble()));++ const auto valuesArray = json["values"].toArray();+ for (const auto& value : valuesArray) {m_values.append(value.toString());}+if (json.contains("options")) {- QJsonArray optionsArray = json["options"].toArray();- for (const QJsonValue &option : optionsArray) {+ const auto optionsArray = json["options"].toArray();+ for (const auto& option : optionsArray) {m_options.append(option.toString());}}}-void XdtsFrameDataItem::write(QJsonObject &json) const {+void XdtsFrameDataItem::write(QJsonObject& json) const {json["id"] = int(m_id);+QJsonArray valuesArray;- for (const QString &value : m_values) {+ for (const auto& value : m_values) {valuesArray.append(value);}json["values"] = valuesArray;if (!m_options.isEmpty()) {QJsonArray optionsArray;- for (const QString &option : m_options) {+ for (const auto& option : m_options) {optionsArray.append(option);}json["options"] = optionsArray;@@ -144,309 +160,344 @@ void XdtsFrameDataItem::write(QJsonObject &json) const {}XdtsFrameDataItem::FrameInfo XdtsFrameDataItem::getFrameInfo() const {- // int getCellNumber() const {- if (m_values.isEmpty())- return {TFrameId(-1), m_options}; // EMPTY- // if (m_values.isEmpty()) return 0;- QString val = m_values.at(0);- if (val == "SYMBOL_NULL_CELL")- return {TFrameId(-1), m_options}; // EMPTY- // ignore sheet symbols for now- else if (val == "SYMBOL_HYPHEN")- return {TFrameId(-2), m_options}; // IGNORE- else if (val == "SYMBOL_TICK_1")+ if (m_values.isEmpty()) {+ return {TFrameId(-1), m_options}; // EMPTY cell+ }++ const QString val = m_values.at(0);+ if (val == "SYMBOL_NULL_CELL") {+ return {TFrameId(-1), m_options}; // EMPTY cell+ } else if (val == "SYMBOL_HYPHEN") {+ return {TFrameId(-2), m_options}; // IGNORE cell+ } else if (val == "SYMBOL_TICK_1") {return {TFrameId(SYMBOL_TICK_1), m_options};- else if (val == "SYMBOL_TICK_2")+ } else if (val == "SYMBOL_TICK_2") {return {TFrameId(SYMBOL_TICK_2), m_options};- // return cell number+ }+return {str2Fid(m_values.at(0)), m_options};}+//=============================================================================+// XdtsTrackFrameItem implementation//------------------------------------------------------------------------------void XdtsTrackFrameItem::read(const QJsonObject &json) {- QJsonArray dataArray = json["data"].toArray();- for (int dataIndex = 0; dataIndex < dataArray.size(); ++dataIndex) {- QJsonObject dataObject = dataArray[dataIndex].toObject();++void XdtsTrackFrameItem::read(const QJsonObject& json) {+ const auto dataArray = json["data"].toArray();+ for (const auto& dataValue : dataArray) {XdtsFrameDataItem data;- data.read(dataObject);+ data.read(dataValue.toObject());m_data.append(data);}m_frame = json["frame"].toInt();}-void XdtsTrackFrameItem::write(QJsonObject &json) const {+void XdtsTrackFrameItem::write(QJsonObject& json) const {QJsonArray dataArray;- for (const XdtsFrameDataItem &data : m_data) {+ for (const auto& data : m_data) {QJsonObject dataObject;data.write(dataObject);dataArray.append(dataObject);}- json["data"] = dataArray;-+ json["data"] = dataArray;json["frame"] = m_frame;}-//------------------------------------------------------------------------------QPair<int, XdtsFrameDataItem::FrameInfo> XdtsTrackFrameItem::frameFinfo()const {- return QPair<int, XdtsFrameDataItem::FrameInfo>(m_frame,- m_data[0].getFrameInfo());+ return {m_frame, m_data[0].getFrameInfo()};}+//=============================================================================+// XdtsFieldTrackItem implementation//------------------------------------------------------------------------------void XdtsFieldTrackItem::read(const QJsonObject &json) {- QJsonArray frameArray = json["frames"].toArray();- for (int frameIndex = 0; frameIndex < frameArray.size(); ++frameIndex) {- QJsonObject frameObject = frameArray[frameIndex].toObject();++void XdtsFieldTrackItem::read(const QJsonObject& json) {+ const auto frameArray = json["frames"].toArray();+ for (const auto& frameValue : frameArray) {XdtsTrackFrameItem frame;- frame.read(frameObject);+ frame.read(frameValue.toObject());m_frames.append(frame);}m_trackNo = json["trackNo"].toInt();}-void XdtsFieldTrackItem::write(QJsonObject &json) const {+void XdtsFieldTrackItem::write(QJsonObject& json) const {QJsonArray frameArray;- for (const XdtsTrackFrameItem &frame : m_frames) {+ for (const auto& frame : m_frames) {QJsonObject frameObject;frame.write(frameObject);frameArray.append(frameObject);}- json["frames"] = frameArray;-+ json["frames"] = frameArray;json["trackNo"] = m_trackNo;}-//-------------------------------------------------------------------------------static bool frameLessThan(const QPair<int, XdtsFrameDataItem::FrameInfo> &v1,- const QPair<int, XdtsFrameDataItem::FrameInfo> &v2) {- return v1.first < v2.first;-}QVector<TFrameId> XdtsFieldTrackItem::getCellFrameIdTrack(- QList<int> &tick1, QList<int> &tick2, QList<int> &keyFrames,- QList<int> &refFrames) const {+ QList<int>& tick1, QList<int>& tick2, QList<int>& keyFrames,+ QList<int>& refFrames) const {QList<QPair<int, XdtsFrameDataItem::FrameInfo>> frameFinfos;- for (const XdtsTrackFrameItem &frame : m_frames)+ for (const auto& frame : m_frames) {frameFinfos.append(frame.frameFinfo());- std::sort(frameFinfos.begin(), frameFinfos.end(), frameLessThan);+ }++ std::sort(frameFinfos.begin(), frameFinfos.end(),+ [](const auto& v1, const auto& v2) { return v1.first < v2.first; });QVector<TFrameId> cells;- int currentFrame = 0;- TFrameId initialNumber = TFrameId();- for (QPair<int, XdtsFrameDataItem::FrameInfo> &frameFinfo : frameFinfos) {+ int currentFrame = 0;+ TFrameId initialNumber;++ for (auto& frameFinfo : frameFinfos) {while (currentFrame < frameFinfo.first) {- cells.append((cells.isEmpty()) ? initialNumber : cells.last());+ cells.append(cells.isEmpty() ? initialNumber : cells.last());currentFrame++;}- // CSP may export negative frame data (although it is not allowed in XDTS- // format specification) so handle such case.++ // Handle negative frame data (CSP export anomaly)if (frameFinfo.first < 0) {initialNumber = frameFinfo.second.frameId;continue;}- // ignore sheet symbols for now- TFrameId cellFid = frameFinfo.second.frameId;- if (cellFid.getNumber() == -2) // IGNORE case- cells.append((cells.isEmpty()) ? TFrameId(-1) : cells.last());- else if (cellFid.getNumber() ==- XdtsFrameDataItem::SYMBOL_TICK_1) { // SYMBOL_TICK_1- cells.append((cells.isEmpty()) ? TFrameId(-1) : cells.last());++ const TFrameId cellFid = frameFinfo.second.frameId;+ if (cellFid.getNumber() == -2) { // IGNORE case+ cells.append(cells.isEmpty() ? TFrameId(-1) : cells.last());+ } else if (cellFid.getNumber() == XdtsFrameDataItem::SYMBOL_TICK_1) {+ cells.append(cells.isEmpty() ? TFrameId(-1) : cells.last());tick1.append(currentFrame);- } else if (cellFid.getNumber() ==- XdtsFrameDataItem::SYMBOL_TICK_2) { // SYMBOL_TICK_2- cells.append((cells.isEmpty()) ? TFrameId(-1) : cells.last());+ } else if (cellFid.getNumber() == XdtsFrameDataItem::SYMBOL_TICK_2) {+ cells.append(cells.isEmpty() ? TFrameId(-1) : cells.last());tick2.append(currentFrame);- } else+ } else {cells.append(cellFid);+ }- QStringList options = frameFinfo.second.options;- if (options.contains(OPTION_KEYFRAME)) keyFrames.append(currentFrame);- if (options.contains(OPTION_REFERENCEFRAME)) refFrames.append(currentFrame);+ const QStringList options = frameFinfo.second.options;+ if (options.contains(OPTION_KEYFRAME)) {+ keyFrames.append(currentFrame);+ }+ if (options.contains(OPTION_REFERENCEFRAME)) {+ refFrames.append(currentFrame);+ }currentFrame++;}+return cells;}-QString XdtsFieldTrackItem::build(TXshCellColumn *column) {- // register the firstly-found level- TXshLevel *level = nullptr;+QString XdtsFieldTrackItem::build(TXshCellColumn* column) {+ TXshLevel* level = nullptr;TXshCell prevCell;int r0, r1;column->getRange(r0, r1);+if (r0 > 0) addFrame(0, TFrameId(-1));- for (int row = r0; row <= r1; row++) {++ for (int row = r0; row <= r1; ++row) {TXshCell cell = column->getCell(row);- // try to register the level. simple levels and sub xsheet levels are- // exported++ // Register the first found level (simple or child level)if (!level) level = cell.getSimpleLevel();if (!level) level = cell.getChildLevel();- // if the level does not match with the registered one,- // handle as the empty cell- if (!level || cell.m_level != level) cell = TXshCell();- // continue if the cell is continuous++ // If level doesn't match registered one, treat as empty cell+ if (!level || cell.m_level != level) {+ cell = TXshCell();+ }++ // Continue if cell is continuousif (prevCell == cell) {- // cell mark to ticks- if (_tick1Id >= 0 && column->getCellMark(row) == _tick1Id)+ // Handle cell marks for ticks+ if (tick1Id >= 0 && column->getCellMark(row) == tick1Id) {addFrame(row, TFrameId(XdtsFrameDataItem::SYMBOL_TICK_1));- else if (_tick2Id >= 0 && column->getCellMark(row) == _tick2Id)+ } else if (tick2Id >= 0 && column->getCellMark(row) == tick2Id) {addFrame(row, TFrameId(XdtsFrameDataItem::SYMBOL_TICK_2));+ }continue;}- if (cell.isEmpty())++ if (cell.isEmpty()) {addFrame(row, TFrameId(-1));- else {- QList<QString> options;- // cell mark for keyframe / reference frame symbols- if (_keyFrameId >= 0 && column->getCellMark(row) == _keyFrameId)+ } else {+ QStringList options;+ // Handle keyframe and reference frame symbols+ if (keyFrameId >= 0 && column->getCellMark(row) == keyFrameId) {options.append(OPTION_KEYFRAME);- else if (_referenceFrameId >= 0 &&- column->getCellMark(row) == _referenceFrameId)+ } else if (referenceFrameId >= 0 &&+ column->getCellMark(row) == referenceFrameId) {options.append(OPTION_REFERENCEFRAME);- if (!options.isEmpty()) _isUextVersion = true;+ }++ if (!options.isEmpty()) {+ isUextVersion = true;+ }+addFrame(row, cell.getFrameId(), options);}prevCell = cell;}+addFrame(r1 + 1, TFrameId(-1));- if (level)++ if (level) {return QString::fromStdWString(level->getName());- else {+ } else {m_frames.clear();return QString();}}++//=============================================================================+// XdtsTimeTableFieldItem implementation//------------------------------------------------------------------------------void XdtsTimeTableFieldItem::read(const QJsonObject &json) {+void XdtsTimeTableFieldItem::read(const QJsonObject& json) {m_fieldId = FieldId(qRound(json["fieldId"].toDouble()));- QJsonArray trackArray = json["tracks"].toArray();- for (int trackIndex = 0; trackIndex < trackArray.size(); ++trackIndex) {- QJsonObject trackObject = trackArray[trackIndex].toObject();+ const auto trackArray = json["tracks"].toArray();++ for (const auto& trackValue : trackArray) {XdtsFieldTrackItem track;- track.read(trackObject);+ track.read(trackValue.toObject());m_tracks.append(track);}}-void XdtsTimeTableFieldItem::write(QJsonObject &json) const {+void XdtsTimeTableFieldItem::write(QJsonObject& json) const {json["fieldId"] = int(m_fieldId);QJsonArray trackArray;- for (const XdtsFieldTrackItem &track : m_tracks) {++ for (const auto& track : m_tracks) {QJsonObject trackObject;track.write(trackObject);trackArray.append(trackObject);}+json["tracks"] = trackArray;}QList<int> XdtsTimeTableFieldItem::getOccupiedColumns() const {- QList<int> ret;- for (const XdtsFieldTrackItem &track : m_tracks) {- if (!track.isEmpty()) ret.append(track.getTrackNo());+ QList<int> result;+ for (const auto& track : m_tracks) {+ if (!track.isEmpty()) {+ result.append(track.getTrackNo());+ }}- return ret;+ return result;}QVector<TFrameId> XdtsTimeTableFieldItem::getColumnTrack(- int col, QList<int> &tick1, QList<int> &tick2, QList<int> &keyFrames,- QList<int> &refFrames) const {- for (const XdtsFieldTrackItem &track : m_tracks) {- if (track.getTrackNo() != col) continue;- return track.getCellFrameIdTrack(tick1, tick2, keyFrames, refFrames);+ int col, QList<int>& tick1, QList<int>& tick2, QList<int>& keyFrames,+ QList<int>& refFrames) const {+ for (const auto& track : m_tracks) {+ if (track.getTrackNo() == col) {+ return track.getCellFrameIdTrack(tick1, tick2, keyFrames, refFrames);+ }}return QVector<TFrameId>();}-void XdtsTimeTableFieldItem::build(TXsheet *xsheet, QStringList &columnLabels) {+void XdtsTimeTableFieldItem::build(TXsheet* xsheet, QStringList& columnLabels) {m_fieldId = CELL;int exportCol = 0;- for (int col = 0; col < xsheet->getFirstFreeColumnIndex(); col++) {++ for (int col = 0; col < xsheet->getFirstFreeColumnIndex(); ++col) {if (xsheet->isColumnEmpty(col)) {columnLabels.append("");- exportCol++;+ ++exportCol;continue;}- TXshCellColumn *column = xsheet->getColumn(col)->getCellColumn();- // skip non-cell column- if (!column) {- continue;- }- // skip inactive column- if (!_exportAllColumn && !column->isPreviewVisible()) {- continue;++ auto column = xsheet->getColumn(col)->getCellColumn();+ if (!column) continue; // Skip non-cell columns++ if (!exportAllColumn && !column->isPreviewVisible()) {+ continue; // Skip inactive columns}+XdtsFieldTrackItem track(exportCol);columnLabels.append(track.build(column));- if (!track.isEmpty()) m_tracks.append(track);- exportCol++;++ if (!track.isEmpty()) {+ m_tracks.append(track);+ }+ ++exportCol;}}++//=============================================================================+// XdtsTimeTableHeaderItem implementation//------------------------------------------------------------------------------void XdtsTimeTableHeaderItem::read(const QJsonObject &json) {+void XdtsTimeTableHeaderItem::read(const QJsonObject& json) {m_fieldId = FieldId(qRound(json["fieldId"].toDouble()));- QJsonArray namesArray = json["names"].toArray();- for (int nIndex = 0; nIndex < namesArray.size(); ++nIndex) {- m_names.append(namesArray[nIndex].toString());+ const auto namesArray = json["names"].toArray();++ for (const auto& nameValue : namesArray) {+ m_names.append(nameValue.toString());}}-void XdtsTimeTableHeaderItem::write(QJsonObject &json) const {+void XdtsTimeTableHeaderItem::write(QJsonObject& json) const {json["fieldId"] = int(m_fieldId);QJsonArray namesArray;- for (const QString &name : m_names) {++ for (const auto& name : m_names) {namesArray.append(name);}- json["names"] = namesArray;-}-void XdtsTimeTableHeaderItem::build(QStringList &columnLabels) {- m_names.append(columnLabels);+ json["names"] = namesArray;}+//=============================================================================+// XdtsTimeTableItem implementation//------------------------------------------------------------------------------void XdtsTimeTableItem::read(const QJsonObject &json) {+void XdtsTimeTableItem::read(const QJsonObject& json) {if (json.contains("fields")) {- QJsonArray fieldArray = json["fields"].toArray();- for (int fieldIndex = 0; fieldIndex < fieldArray.size(); ++fieldIndex) {- QJsonObject fieldObject = fieldArray[fieldIndex].toObject();+ const auto fieldArray = json["fields"].toArray();+ for (int i = 0; i < fieldArray.size(); ++i) {XdtsTimeTableFieldItem field;- field.read(fieldObject);+ field.read(fieldArray[i].toObject());m_fields.append(field);- if (field.isCellField()) m_cellFieldIndex = fieldIndex;+ if (field.isCellField()) {+ m_cellFieldIndex = i;+ }}}- m_duration = json["duration"].toInt();- m_name = json["name"].toString();- QJsonArray headerArray = json["timeTableHeaders"].toArray();- for (int headerIndex = 0; headerIndex < headerArray.size(); ++headerIndex) {- QJsonObject headerObject = headerArray[headerIndex].toObject();++ m_duration = json["duration"].toInt();+ m_name = json["name"].toString();++ const auto headerArray = json["timeTableHeaders"].toArray();+ for (int i = 0; i < headerArray.size(); ++i) {XdtsTimeTableHeaderItem header;- header.read(headerObject);+ header.read(headerArray[i].toObject());m_timeTableHeaders.append(header);- if (header.isCellField()) m_cellHeaderIndex = headerIndex;+ if (header.isCellField()) {+ m_cellHeaderIndex = i;+ }}}-void XdtsTimeTableItem::write(QJsonObject &json) const {+void XdtsTimeTableItem::write(QJsonObject& json) const {if (!m_fields.isEmpty()) {QJsonArray fieldArray;- for (const XdtsTimeTableFieldItem &field : m_fields) {+ for (const auto& field : m_fields) {QJsonObject fieldObject;field.write(fieldObject);fieldArray.append(fieldObject);}json["fields"] = fieldArray;}+json["duration"] = m_duration;json["name"] = m_name;+QJsonArray headerArray;- for (const XdtsTimeTableHeaderItem &header : m_timeTableHeaders) {+ for (const auto& header : m_timeTableHeaders) {QJsonObject headerObject;header.write(headerObject);headerArray.append(headerObject);@@ -455,148 +506,173 @@ void XdtsTimeTableItem::write(QJsonObject &json) const {}QStringList XdtsTimeTableItem::getLevelNames() const {- // obtain column labels from the headerassert(m_cellHeaderIndex >= 0);- QStringList labels = m_timeTableHeaders.at(m_cellHeaderIndex).getLayerNames();- // obtain occupied column numbers in the field+ const QStringList labels =+ m_timeTableHeaders.at(m_cellHeaderIndex).getLayerNames();+assert(m_cellFieldIndex >= 0);- QList<int> occupiedColumns =+ const QList<int> occupiedColumns =m_fields.at(m_cellFieldIndex).getOccupiedColumns();- // return the names of occupied columns- QStringList ret;- for (const int columnId : occupiedColumns) ret.append(labels.at(columnId));- return ret;++ QStringList result;+ for (const int columnId : occupiedColumns) {+ result.append(labels.at(columnId));+ }+ return result;}-void XdtsTimeTableItem::build(TXsheet *xsheet, QString name, int duration) {+void XdtsTimeTableItem::build(TXsheet* xsheet, const QString& name,+ int duration) {m_duration = duration;m_name = name;+QStringList columnLabels;XdtsTimeTableFieldItem field;field.build(xsheet, columnLabels);m_fields.append(field);- while (!columnLabels.isEmpty() && columnLabels.last().isEmpty())++ while (!columnLabels.isEmpty() && columnLabels.last().isEmpty()) {columnLabels.removeLast();+ }+if (columnLabels.isEmpty()) {m_fields.clear();return;}+XdtsTimeTableHeaderItem header;header.build(columnLabels);m_timeTableHeaders.append(header);m_cellHeaderIndex = 0;m_cellFieldIndex = 0;}++//=============================================================================+// XdtsData implementation//------------------------------------------------------------------------------void XdtsData::read(const QJsonObject &json) {+void XdtsData::read(const QJsonObject& json) {if (json.contains("header")) {- QJsonObject headerObject = json["header"].toObject();- m_header.read(headerObject);+ m_header.read(json["header"].toObject());}- QJsonArray tableArray = json["timeTables"].toArray();- for (int tableIndex = 0; tableIndex < tableArray.size(); ++tableIndex) {- QJsonObject tableObject = tableArray[tableIndex].toObject();++ const auto tableArray = json["timeTables"].toArray();+ for (const auto& tableValue : tableArray) {XdtsTimeTableItem table;- table.read(tableObject);+ table.read(tableValue.toObject());m_timeTables.append(table);}+m_version = Version(qRound(json["version"].toDouble()));- if (json.contains("subversion")) m_subversion = json["subversion"].toString();+ if (json.contains("subversion")) {+ m_subversion = json["subversion"].toString();+ }}-void XdtsData::write(QJsonObject &json) const {+void XdtsData::write(QJsonObject& json) const {if (!m_header.isEmpty()) {QJsonObject headerObject;m_header.write(headerObject);json["header"] = headerObject;}+QJsonArray tableArray;- for (const XdtsTimeTableItem &table : m_timeTables) {+ for (const auto& table : m_timeTables) {QJsonObject tableObject;table.write(tableObject);tableArray.append(tableObject);}json["timeTables"] = tableArray;- json["version"] = int(m_version);- if (!m_subversion.isEmpty()) json["subversion"] = m_subversion;+ json["version"] = int(m_version);++ if (!m_subversion.isEmpty()) {+ json["subversion"] = m_subversion;+ }}QStringList XdtsData::getLevelNames() const {- // currently support only the first page of time tablesreturn m_timeTables.at(0).getLevelNames();}-void XdtsData::build(TXsheet *xsheet, QString name, int duration) {+void XdtsData::build(TXsheet* xsheet, const QString& name, int duration) {XdtsTimeTableItem timeTable;timeTable.build(xsheet, name, duration);+if (timeTable.isEmpty()) return;+m_timeTables.append(timeTable);- if (_isUextVersion) m_subversion = "p1";+ if (::isUextVersion) {+ m_subversion = "p1";+ }}+//=============================================================================+// XDTS I/O Functions//------------------------------------------------------------------------------bool XdtsIo::loadXdtsScene(ToonzScene *scene, const TFilePath &scenePath) {+bool XdtsIo::loadXdtsScene(ToonzScene* scene, const TFilePath& scenePath) {QApplication::restoreOverrideCursor();- // read the Json file+QFile loadFile(scenePath.getQString());if (!loadFile.open(QIODevice::ReadOnly)) {- qWarning("Couldn't open save file.");+ qWarning("Couldn't open XDTS file.");return false;}QByteArray dataArray = loadFile.readAll();-if (!dataArray.startsWith(identifierStr)) {- qWarning("The first line does not start with XDTS identifier string.");+ qWarning("File does not start with XDTS identifier string.");return false;}- // remove identifier- dataArray.remove(0, identifierStr.length());- QJsonDocument loadDoc(QJsonDocument::fromJson(dataArray));+ dataArray.remove(0, identifierStr.length());+ const QJsonDocument loadDoc = QJsonDocument::fromJson(dataArray);XdtsData xdtsData;xdtsData.read(loadDoc.object());- // obtain level namesQStringList levelNames = xdtsData.getLevelNames();- // in case multiple columns have the same namelevelNames.removeDuplicates();- for (auto &name : levelNames) name = name.trimmed();+ for (auto& name : levelNames) {+ name = name.trimmed();+ }scene->clear();auto sceneProject = TProjectManager::instance()->loadSceneProject(scenePath);if (!sceneProject) return false;+scene->setProject(sceneProject);- std::string sceneFileName = scenePath.getName() + ".tnz";+ const std::string sceneFileName = scenePath.getName() + ".tnz";scene->setScenePath(scenePath.getParentDir() + sceneFileName);- // set the current scene here in order to use $scenefolder node properly- // in the file browser which opens from XDTSImportPopup+TApp::instance()->getCurrentScene()->setScene(scene);XDTSImportPopup popup(levelNames, scene, scenePath, xdtsData.isUextVersion());- int ret = popup.exec();- if (ret == QDialog::Rejected) return false;+ if (popup.exec() == QDialog::Rejected) {+ return false;+ }- QMap<QString, TXshLevel *> levels;+ QMap<QString, TXshLevel*> levels;try {- for (QString name : levelNames) {- QString levelPath = popup.getLevelPath(name);- TXshLevel *level = nullptr;- if (!levelPath.isEmpty())+ for (const QString& name : levelNames) {+ const QString levelPath = popup.getLevelPath(name);+ TXshLevel* level = nullptr;++ if (!levelPath.isEmpty()) {level = scene->loadLevel(scene->decodeFilePath(TFilePath(levelPath)),nullptr, name.toStdWString());+ }+if (!level) {- int levelType = Preferences::instance()->getDefLevelType();- level = scene->createNewLevel(levelType, name.toStdWString());+ const int levelType = Preferences::instance()->getDefLevelType();+ level = scene->createNewLevel(levelType, name.toStdWString());}+levels.insert(name, level);}} catch (...) {@@ -606,47 +682,49 @@ bool XdtsIo::loadXdtsScene(ToonzScene *scene, const TFilePath &scenePath) {int tick1Id, tick2Id, keyFrameId, referenceFrameId;popup.getMarkerIds(tick1Id, tick2Id, keyFrameId, referenceFrameId);- TFrameId tmplFId = scene->getProperties()->formatTemplateFIdForInput();+ const TFrameId tmplFId = scene->getProperties()->formatTemplateFIdForInput();+ TXsheet* xsh = scene->getXsheet();++ const XdtsTimeTableFieldItem cellField = xdtsData.timeTable().getCellField();+ const XdtsTimeTableHeaderItem cellHeader =+ xdtsData.timeTable().getCellHeader();+ const int duration = xdtsData.timeTable().getDuration();+ const QStringList layerNames = cellHeader.getLayerNames();+ const QList<int> columns = cellField.getOccupiedColumns();- TXsheet *xsh = scene->getXsheet();- XdtsTimeTableFieldItem cellField = xdtsData.timeTable().getCellField();- XdtsTimeTableHeaderItem cellHeader = xdtsData.timeTable().getCellHeader();- int duration = xdtsData.timeTable().getDuration();- QStringList layerNames = cellHeader.getLayerNames();- QList<int> columns = cellField.getOccupiedColumns();for (int column : columns) {- QString levelName = layerNames.at(column);- TXshLevel *level = levels.value(levelName.trimmed());- TXshSimpleLevel *sl = level->getSimpleLevel();+ const QString levelName = layerNames.at(column).trimmed();+ TXshLevel* level = levels.value(levelName);+ TXshSimpleLevel* sl = level ? level->getSimpleLevel() : nullptr;+QList<int> tick1, tick2, keyFrames, refFrames;- QVector<TFrameId> track =+ const QVector<TFrameId> track =cellField.getColumnTrack(column, tick1, tick2, keyFrames, refFrames);int row = 0;- std::vector<TFrameId>::iterator it;for (TFrameId fid : track) {- if (fid.getNumber() == -1) // EMPTY cell case- row++;- else {- // modify frameId to be with the same frame format as existing frames- if (sl) sl->formatFId(fid, tmplFId);- xsh->setCell(row++, column, TXshCell(level, fid));+ if (fid.getNumber() == -1) { // EMPTY cell+ ++row;+ } else {+ TFrameId fidCopy = fid; // Create non-const copy for formatFId+ if (sl) sl->formatFId(fidCopy, tmplFId);+ xsh->setCell(row++, column, TXshCell(level, fidCopy));}}- // if the last cell is not "SYMBOL_NULL_CELL", continue the cell- // to the end of the sheet- TFrameId lastFid = track.last();++ // Extend last cell to end of sheet if not empty+ TFrameId lastFid = track.last(); // Non-const variableif (lastFid.getNumber() != -1) {- // modify frameId to be with the same frame format as existing framesif (sl) sl->formatFId(lastFid, tmplFId);- for (; row < duration; row++)+ for (; row < duration; ++row) {xsh->setCell(row, column, TXshCell(level, TFrameId(lastFid)));+ }}- // set cell marks- TXshCellColumn *cellColumn = nullptr;- if (xsh->getColumn(column))- cellColumn = xsh->getColumn(column)->getCellColumn();+ // Set cell marks+ auto columnPtr = xsh->getColumn(column);+ auto cellColumn = columnPtr ? columnPtr->getCellColumn() : nullptr;+if (cellColumn) {if (tick1Id >= 0) {for (auto tick1f : tick1) cellColumn->setCellMark(tick1f, tick1Id);@@ -664,27 +742,30 @@ bool XdtsIo::loadXdtsScene(ToonzScene *scene, const TFilePath &scenePath) {}}- TStageObject *pegbar =- xsh->getStageObject(TStageObjectId::ColumnId(column));- if (pegbar) pegbar->setName(levelName.toStdString());+ if (auto pegbar = xsh->getStageObject(TStageObjectId::ColumnId(column))) {+ pegbar->setName(levelName.toStdString());+ }}+xsh->updateFrameCount();- // if the duration is shorter than frame count, then set it both in- // preview range and output range.+ // Adjust preview and output ranges if duration is shorterif (duration < xsh->getFrameCount()) {scene->getProperties()->getPreviewProperties()->setRange(0, duration - 1,1);scene->getProperties()->getOutputProperties()->setRange(0, duration - 1, 1);}- // emit signal here for updating the frame slider range of flip consoleTApp::instance()->getCurrentScene()->notifySceneChanged();- // update xsheet viewerTApp::instance()->getCurrentXsheet()->notifyXsheetChanged();+return true;}+//=============================================================================+// ExportXDTSCommand implementation+//-----------------------------------------------------------------------------+class ExportXDTSCommand final : public MenuItemHandler {public:ExportXDTSCommand() : MenuItemHandler(MI_ExportXDTS) {}@@ -692,84 +773,93 @@ public:} exportXDTSCommand;void ExportXDTSCommand::execute() {- ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();- TXsheet *xsheet = TApp::instance()->getCurrentXsheet()->getXsheet();- TFilePath fp = scene->getScenePath().withType("xdts");+ auto scene = TApp::instance()->getCurrentScene()->getScene();+ auto xsheet = TApp::instance()->getCurrentXsheet()->getXsheet();+ auto fp = scene->getScenePath().withType("xdts");- // if the current xsheet is top xsheet in the scene and the output- // frame range is specified, set the "to" frame value as durationint duration;- TOutputProperties *oprop = scene->getProperties()->getOutputProperties();+ auto oprop = scene->getProperties()->getOutputProperties();int from, to, step;- if (scene->getTopXsheet() == xsheet && oprop->getRange(from, to, step))++ if (scene->getTopXsheet() == xsheet && oprop->getRange(from, to, step)) {duration = to + 1;- else+ } else {duration = xsheet->getFrameCount();+ }+ // Pre-check if any columns can be exported{- _tick1Id = -1;- _tick2Id = -1;- _keyFrameId = -1;- _referenceFrameId = -1;- _exportAllColumn = true;- _isUextVersion = false;+ tick1Id = -1;+ tick2Id = -1;+ keyFrameId = -1;+ referenceFrameId = -1;+ exportAllColumn = true;+ isUextVersion = false;+XdtsData pre_xdtsData;pre_xdtsData.build(xsheet, QString::fromStdString(fp.getName()), duration);+if (pre_xdtsData.isEmpty()) {DVGui::error(QObject::tr("No columns can be exported."));return;}}- static GenericSaveFilePopup *savePopup = 0;- static QComboBox *tick1Id = nullptr;- static QComboBox *tick2Id = nullptr;- static QComboBox *keyFrameId = nullptr;- static QComboBox *referenceFrameId = nullptr;- static QComboBox *targetColumnCombo = nullptr;+ static GenericSaveFilePopup* savePopup = nullptr;+ static QComboBox* tick1Combo = nullptr;+ static QComboBox* tick2Combo = nullptr;+ static QComboBox* keyFrameCombo = nullptr;+ static QComboBox* referenceFrameCombo = nullptr;+ static QComboBox* targetColumnCombo = nullptr;- auto refreshCellMarkComboItems = [](QComboBox *combo) {+ auto refreshCellMarkComboItems = [](QComboBox* combo) {combo->setSizeAdjustPolicy(QComboBox::AdjustToContents);- int current = -1;- if (combo->count()) current = combo->currentData().toInt();+ int current = combo->count() ? combo->currentData().toInt() : -1;combo->clear();- QList<TSceneProperties::CellMark> marks = TApp::instance()- ->getCurrentScene()- ->getScene()- ->getProperties()- ->getCellMarks();+ const auto marks = TApp::instance()+ ->getCurrentScene()+ ->getScene()+ ->getProperties()+ ->getCellMarks();+combo->addItem(QObject::tr("None"), -1);- int curId = 0;- for (auto mark : marks) {- QString label = QString("%1: %2").arg(curId).arg(mark.name);- combo->addItem(getColorChipIcon(mark.color), label, curId);- curId++;+ int currentId = 0;++ for (const auto& mark : marks) {+ const QString label = QString("%1: %2").arg(currentId).arg(mark.name);+ combo->addItem(createColorChipIcon(mark.color), label, currentId);+ ++currentId;+ }++ if (current >= 0) {+ combo->setCurrentIndex(combo->findData(current));}- if (current >= 0) combo->setCurrentIndex(combo->findData(current));};if (!savePopup) {- // create custom widget- QWidget *customWidget = new QWidget();- tick1Id = new QComboBox();- tick2Id = new QComboBox();- keyFrameId = new QComboBox();- referenceFrameId = new QComboBox();- refreshCellMarkComboItems(tick1Id);- refreshCellMarkComboItems(tick2Id);- refreshCellMarkComboItems(keyFrameId);- refreshCellMarkComboItems(referenceFrameId);- tick1Id->setCurrentIndex(tick1Id->findData(6));- tick2Id->setCurrentIndex(tick2Id->findData(8));- keyFrameId->setCurrentIndex(keyFrameId->findData(0));- referenceFrameId->setCurrentIndex(referenceFrameId->findData(4));+ auto customWidget = new QWidget();+ tick1Combo = new QComboBox();+ tick2Combo = new QComboBox();+ keyFrameCombo = new QComboBox();+ referenceFrameCombo = new QComboBox();++ refreshCellMarkComboItems(tick1Combo);+ refreshCellMarkComboItems(tick2Combo);+ refreshCellMarkComboItems(keyFrameCombo);+ refreshCellMarkComboItems(referenceFrameCombo);++ tick1Combo->setCurrentIndex(tick1Combo->findData(6));+ tick2Combo->setCurrentIndex(tick2Combo->findData(8));+ keyFrameCombo->setCurrentIndex(keyFrameCombo->findData(0));+ referenceFrameCombo->setCurrentIndex(referenceFrameCombo->findData(4));+targetColumnCombo = new QComboBox();targetColumnCombo->addItem(QObject::tr("All columns"), true);targetColumnCombo->addItem(QObject::tr("Only active columns"), false);targetColumnCombo->setCurrentIndex(targetColumnCombo->findData(true));- QLabel *warningLabel = new QLabel();+ auto warningLabel = new QLabel();warningLabel->setFixedSize(20, 20);warningLabel->setPixmap(QPixmap(":Resources/warning.svg"));warningLabel->setToolTip(QObject::tr(@@ -777,89 +867,86 @@ void ExportXDTSCommand::execute() {"an unofficial format,\n""which may not be displayed correctly or may cause errors in ""applications other than XDTS Viewer."));- // The original image and reference symbols will be exported in an- // unofficial format, which may not be displayed correctly or may cause- // errors in applications other than XDTS Viewer.-- QVBoxLayout *customLay = new QVBoxLayout();- customLay->setContentsMargins(5, 5, 5, 5);- customLay->setSpacing(10);- {- QGroupBox *cellMarkGroupBox =- new QGroupBox(QObject::tr("Cell marks for XDTS symbols"));-- QGridLayout *cellMarkLay = new QGridLayout();- cellMarkLay->setContentsMargins(10, 10, 10, 10);- cellMarkLay->setVerticalSpacing(10);- cellMarkLay->setHorizontalSpacing(5);- {- cellMarkLay->addWidget(- new QLabel(QObject::tr("Inbetween Symbol1 (O):")), 0, 0,- Qt::AlignRight | Qt::AlignVCenter);- cellMarkLay->addWidget(tick1Id, 0, 1);- cellMarkLay->addItem(new QSpacerItem(10, 1), 0, 2);- cellMarkLay->addWidget(- new QLabel(QObject::tr("Inbetween Symbol2 (*):")), 0, 3,- Qt::AlignRight | Qt::AlignVCenter);- cellMarkLay->addWidget(tick2Id, 0, 4);-- cellMarkLay->addWidget(new QLabel(QObject::tr("Keyframe Symbol:")), 1,- 0, Qt::AlignRight | Qt::AlignVCenter);- cellMarkLay->addWidget(keyFrameId, 1, 1);- cellMarkLay->addWidget(- new QLabel(QObject::tr("Reference Frame Symbol:")), 1, 3,- Qt::AlignRight | Qt::AlignVCenter);- cellMarkLay->addWidget(referenceFrameId, 1, 4);- cellMarkLay->addWidget(warningLabel, 1, 5);- }- cellMarkGroupBox->setLayout(cellMarkLay);- customLay->addWidget(cellMarkGroupBox, 0, Qt::AlignRight);-- QHBoxLayout *bottomLay = new QHBoxLayout();- bottomLay->setContentsMargins(0, 0, 0, 0);- bottomLay->setSpacing(10);- {- bottomLay->addWidget(new QLabel(QObject::tr("Target column")), 1,- Qt::AlignRight | Qt::AlignVCenter);- bottomLay->addWidget(targetColumnCombo, 0);- }- customLay->addLayout(bottomLay);- }- customWidget->setLayout(customLay);++ auto customLayout = new QVBoxLayout();+ customLayout->setContentsMargins(5, 5, 5, 5);+ customLayout->setSpacing(10);++ auto cellMarkGroupBox =+ new QGroupBox(QObject::tr("Cell marks for XDTS symbols"));+ auto cellMarkLayout = new QGridLayout();+ cellMarkLayout->setContentsMargins(10, 10, 10, 10);+ cellMarkLayout->setVerticalSpacing(10);+ cellMarkLayout->setHorizontalSpacing(5);++ cellMarkLayout->addWidget(new QLabel(QObject::tr("Inbetween Symbol1 (O):")),+ 0, 0, Qt::AlignRight | Qt::AlignVCenter);+ cellMarkLayout->addWidget(tick1Combo, 0, 1);+ cellMarkLayout->addItem(new QSpacerItem(10, 1), 0, 2);+ cellMarkLayout->addWidget(new QLabel(QObject::tr("Inbetween Symbol2 (*):")),+ 0, 3, Qt::AlignRight | Qt::AlignVCenter);+ cellMarkLayout->addWidget(tick2Combo, 0, 4);++ cellMarkLayout->addWidget(new QLabel(QObject::tr("Keyframe Symbol:")), 1, 0,+ Qt::AlignRight | Qt::AlignVCenter);+ cellMarkLayout->addWidget(keyFrameCombo, 1, 1);+ cellMarkLayout->addWidget(+ new QLabel(QObject::tr("Reference Frame Symbol:")), 1, 3,+ Qt::AlignRight | Qt::AlignVCenter);+ cellMarkLayout->addWidget(referenceFrameCombo, 1, 4);+ cellMarkLayout->addWidget(warningLabel, 1, 5);++ cellMarkGroupBox->setLayout(cellMarkLayout);+ customLayout->addWidget(cellMarkGroupBox, 0, Qt::AlignRight);++ auto bottomLayout = new QHBoxLayout();+ bottomLayout->setContentsMargins(0, 0, 0, 0);+ bottomLayout->setSpacing(10);+ bottomLayout->addWidget(new QLabel(QObject::tr("Target column")), 1,+ Qt::AlignRight | Qt::AlignVCenter);+ bottomLayout->addWidget(targetColumnCombo, 0);++ customLayout->addLayout(bottomLayout);+ customWidget->setLayout(customLayout);savePopup = new GenericSaveFilePopup(QObject::tr("Export Exchange Digital Time Sheet (XDTS)"), customWidget);savePopup->addFilterType("xdts");} else {- refreshCellMarkComboItems(tick1Id);- refreshCellMarkComboItems(tick2Id);- refreshCellMarkComboItems(keyFrameId);- refreshCellMarkComboItems(referenceFrameId);+ refreshCellMarkComboItems(tick1Combo);+ refreshCellMarkComboItems(tick2Combo);+ refreshCellMarkComboItems(keyFrameCombo);+ refreshCellMarkComboItems(referenceFrameCombo);}- if (!scene->isUntitled())++ if (!scene->isUntitled()) {savePopup->setFolder(fp.getParentDir());- else+ } else {savePopup->setFolder(TProjectManager::instance()->getCurrentProject()->getScenesPath());+ }+savePopup->setFilename(fp.withoutParentDir());fp = savePopup->getPath();+if (fp.isEmpty()) return;QFile saveFile(fp.getQString());-if (!saveFile.open(QIODevice::WriteOnly)) {qWarning("Couldn't open save file.");return;}- _tick1Id = tick1Id->currentData().toInt();- _tick2Id = tick2Id->currentData().toInt();- _keyFrameId = keyFrameId->currentData().toInt();- _referenceFrameId = referenceFrameId->currentData().toInt();- _exportAllColumn = targetColumnCombo->currentData().toBool();- _isUextVersion = false;+ tick1Id = tick1Combo->currentData().toInt();+ tick2Id = tick2Combo->currentData().toInt();+ keyFrameId = keyFrameCombo->currentData().toInt();+ referenceFrameId = referenceFrameCombo->currentData().toInt();+ exportAllColumn = targetColumnCombo->currentData().toBool();+ isUextVersion = false;+XdtsData xdtsData;xdtsData.build(xsheet, QString::fromStdString(fp.getName()), duration);+if (xdtsData.isEmpty()) {DVGui::error(QObject::tr("No columns can be exported."));return;@@ -872,18 +959,20 @@ void ExportXDTSCommand::execute() {jsonByteArrayData.prepend(identifierStr + '\n');saveFile.write(jsonByteArrayData);- QString str = QObject::tr("The file %1 has been exported successfully.")- .arg(QString::fromStdString(fp.getLevelName()));+ const QString message =+ QObject::tr("The file %1 has been exported successfully.")+ .arg(QString::fromStdString(fp.getLevelName()));- std::vector<QString> buttons = {QObject::tr("OK"),- QObject::tr("Open containing folder")};- int ret = DVGui::MsgBox(DVGui::INFORMATION, str, buttons);+ const std::vector<QString> buttons = {QObject::tr("OK"),+ QObject::tr("Open containing folder")};+ const int ret = DVGui::MsgBox(DVGui::INFORMATION, message, buttons);if (ret == 2) {- TFilePath folderPath = fp.getParentDir();- if (TSystem::isUNC(folderPath))+ const TFilePath folderPath = fp.getParentDir();+ if (TSystem::isUNC(folderPath)) {QDesktopServices::openUrl(QUrl(folderPath.getQString()));- else+ } else {QDesktopServices::openUrl(QUrl::fromLocalFile(folderPath.getQString()));+ }}}diff --git a/toonz/sources/toonz/xdtsio.h b/toonz/sources/toonz/xdtsio.hindex fe2464fa2..201e1aa3c 100644--- a/toonz/sources/toonz/xdtsio.h+++ b/toonz/sources/toonz/xdtsio.h@@ -1,4 +1,5 @@#pragma once+#ifndef XDTSIO_H#define XDTSIO_H@@ -9,262 +10,238 @@#include <QPair>#include <QStringList>-#include <iostream>-class ToonzScene;-class TFilePath;class TXsheet;class TXshCellColumn;class QJsonObject;namespace XdtsIo {-enum FieldId { CELL = 0, DIALOG = 3, CAMERAWORK = 5 };-// (*1) Field: Input location of each timesheet instruction.-// Fields are divided into cells, dialog, and camerawork.-// [FieldId] [field name] [details]-// 0 Cell Field for cell numbers-// 3 Dialog Field for speaker names and line timing-// 5 Camerawork Field for camerawork instructions+//=============================================================================+// Field IDs - Correspond to different types of timesheet instructions+//=============================================================================++enum FieldId {+ CELL = 0, // Field for cell numbers+ DIALOG = 3, // Field for speaker names and line timing+ CAMERAWORK = 5 // Field for camerawork instructions+};++//=============================================================================+// XdtsHeader - Cut/Scene information+//=============================================================================-// "description": "Cut / scene information",class XdtsHeader {- //"description": "Cut No."- //"pattern" : "\\d{1,4}"- QString m_cut;- //"description": "Scene No.",- //"pattern" : "\\d{1,4}"- QString m_scene;-- // "required": ["cut", "scene"]+ QString m_cut; // Cut number (pattern: \d{1,4})+ QString m_scene; // Scene number (pattern: \d{1,4})+public:- void read(const QJsonObject &json);- void write(QJsonObject &json) const;+ void read(const QJsonObject& json);+ void write(QJsonObject& json) const;+bool isEmpty() const { return m_cut.isEmpty() && m_scene.isEmpty(); }};-//"description": "Frame instruction information",+//=============================================================================+// XdtsFrameDataItem - Frame instruction information+//=============================================================================+class XdtsFrameDataItem {- //"description": "Instruction type(*2)",- //*2 Currently only supports instructions with id=0.enum DataId { Default = 0 } m_id;-- //"description": "Instruction value(*3)",QList<QString> m_values;- // "minItems" : 1,- //"required": ["id", "values"]-- //(*3) Values are different depending on the field type.- // Values for each field are as follows.- // [Field name: Cell]- // Enter the cell number string and special instruction string(*4)- // (value element numbers: 1)- // [Field name: Dialog]- // In the dialog's first frame, enter the speaker name in the first- // element, and the dialog's string in the second element.- // When the line lasts for multiple frames, specify the character- // string "SYMBOL_HYPHEN" up to the end frame.- // (value element numbers: 1�`2)- // [Field name: Camerawork]- // In the camerawork's first frame, enter the camerawork instruction- // string When the camerawork lasts for multiple frames, specify the- // character string "SYMBOL_HYPHEN" up to the end frame.- // (value element numbers: 1)-- //(*4) Special instruction character strings- // [Character string] [Instruction] [Valid field]- // SYMBOL_TICK_1 Inbetween symbol(��) Cell- // SYMBOL_TICK_2 Reverse sheet symbol(��) Cell- // SYMBOL_NULL_CELL Empty cell symbol(�~) Cell- // SYMBOL_HYPHEN Continue previous All fields- // field instruction-- //------------------- // new parameter introduced in PONOC customized version- QList<QString> m_options;- // [Character string] [Instruction] [Valid field]- // OPTION_KEYFRAME ����t���[���i�ԍ����Z�ň͂ށj �Z��- // OPTION_REFERENCEFRAME ���Q�l�t���[���i�ԍ������ň͂ށj �Z��- //-------------------- TFrameId str2Fid(const QString &) const;- QString fid2Str(const TFrameId &) const;+ QList<QString> m_options; // Extended options for Ponoc customized version++ TFrameId str2Fid(const QString& str) const;+ QString fid2Str(const TFrameId& fid) const;public:enum { SYMBOL_TICK_1 = -100, SYMBOL_TICK_2 = -200 };- XdtsFrameDataItem() : m_id(Default), m_options() {}- XdtsFrameDataItem(TFrameId fId, QList<QString> options = QList<QString>())+ XdtsFrameDataItem() : m_id(Default) {}+ explicit XdtsFrameDataItem(TFrameId fid, const QList<QString>& options = {}): m_id(Default), m_options(options) {- m_values.append(fid2Str(fId));+ m_values.append(fid2Str(fid));}- void read(const QJsonObject &json);- void write(QJsonObject &json) const;++ void read(const QJsonObject& json);+ void write(QJsonObject& json) const;struct FrameInfo {TFrameId frameId;QStringList options;};+FrameInfo getFrameInfo() const;};-//"description": "Individual layer frame information",+//=============================================================================+// XdtsTrackFrameItem - Individual layer frame information+//=============================================================================+class XdtsTrackFrameItem {- //"description": "Frame instruction information",QList<XdtsFrameDataItem> m_data;+ int m_frame = 0; // Frame number (0 for first frame)- //"description": "Frame No.(*5)",- // (*5) Set as 0 when specifying the first frame.- //"minimum" : 0- int m_frame;-- //"required": ["data", "frame"]public:XdtsTrackFrameItem() = default;- XdtsTrackFrameItem(int frame, TFrameId fId,- QList<QString> options = QList<QString>())+ XdtsTrackFrameItem(int frame, TFrameId fid,+ const QList<QString>& options = {}): m_frame(frame) {- m_data.append(XdtsFrameDataItem(fId, options));+ m_data.append(XdtsFrameDataItem(fid, options));}- void read(const QJsonObject &json);- void write(QJsonObject &json) const;++ void read(const QJsonObject& json);+ void write(QJsonObject& json) const;+QPair<int, XdtsFrameDataItem::FrameInfo> frameFinfo() const;};-//"description": "Individual field layer info",+//=============================================================================+// XdtsFieldTrackItem - Individual field layer info+//=============================================================================+class XdtsFieldTrackItem {- //"description": "Individual layer frame information",QList<XdtsTrackFrameItem> m_frames;+ int m_trackNo = 0; // Layer number (0 for bottom layer)- //"description": "Layer No.(*6)",- // (*6) Set as 0 for the bottom layer.- // corresponds to column numbers in OT- int m_trackNo;- // "minimum" : 0-- //"required": ["frames", "trackNo"]public:- XdtsFieldTrackItem(int trackNo = 0) : m_trackNo(trackNo) {}- void read(const QJsonObject &json);- void write(QJsonObject &json) const;+ explicit XdtsFieldTrackItem(int trackNo = 0) : m_trackNo(trackNo) {}++ void read(const QJsonObject& json);+ void write(QJsonObject& json) const;+bool isEmpty() const { return m_frames.isEmpty(); }int getTrackNo() const { return m_trackNo; }- QVector<TFrameId> getCellFrameIdTrack(QList<int> &tick1, QList<int> &tick2,- QList<int> &keyFrames,- QList<int> &refFrames) const;-- QString build(TXshCellColumn *);- void addFrame(int frame, TFrameId fId,- QList<QString> options = QList<QString>()) {- m_frames.append(XdtsTrackFrameItem(frame, fId, options));++ QVector<TFrameId> getCellFrameIdTrack(QList<int>& tick1, QList<int>& tick2,+ QList<int>& keyFrames,+ QList<int>& refFrames) const;++ QString build(TXshCellColumn* column);++ void addFrame(int frame, TFrameId fid, const QList<QString>& options = {}) {+ m_frames.append(XdtsTrackFrameItem(frame, fid, options));}};-class XdtsTimeTableFieldItem {- // "description": "Field type(*1)",- FieldId m_fieldId;+//=============================================================================+// XdtsTimeTableFieldItem - Field type with multiple tracks+//=============================================================================- //"description": "Individual field layer info",+class XdtsTimeTableFieldItem {+ FieldId m_fieldId = CELL;QList<XdtsFieldTrackItem> m_tracks;- //"required": ["fieldId", "tracks"]public:- XdtsTimeTableFieldItem(FieldId fieldId = CELL) : m_fieldId(fieldId) {}- void read(const QJsonObject &json);- void write(QJsonObject &json) const;- bool isCellField() { return m_fieldId == CELL; }+ explicit XdtsTimeTableFieldItem(FieldId fieldId = CELL)+ : m_fieldId(fieldId) {}++ void read(const QJsonObject& json);+ void write(QJsonObject& json) const;++ bool isCellField() const { return m_fieldId == CELL; }QList<int> getOccupiedColumns() const;- QVector<TFrameId> getColumnTrack(int col, QList<int> &tick1,- QList<int> &tick2, QList<int> &keyFrames,- QList<int> &refFrames) const;- void build(TXsheet *, QStringList &);+ QVector<TFrameId> getColumnTrack(int column, QList<int>& tick1,+ QList<int>& tick2, QList<int>& keyFrames,+ QList<int>& refFrames) const;++ void build(TXsheet* xsheet, QStringList& columnLabels);};-class XdtsTimeTableHeaderItem {- //"description": "Field type(*1)",- FieldId m_fieldId;+//=============================================================================+// XdtsTimeTableHeaderItem - Layer name information+//=============================================================================- //"description": "Layer name array(*7)",- //(*7) Specify layer names with trackNo's that match numbers counted as 0,1,2,- // etc.- QStringList m_names;+class XdtsTimeTableHeaderItem {+ FieldId m_fieldId = CELL;+ QStringList m_names; // Layer names matching track numbers- //"required": ["fieldId", "names"]public:- XdtsTimeTableHeaderItem(FieldId fieldId = CELL) : m_fieldId(fieldId) {}- void read(const QJsonObject &json);- void write(QJsonObject &json) const;- bool isCellField() { return m_fieldId == CELL; }+ explicit XdtsTimeTableHeaderItem(FieldId fieldId = CELL)+ : m_fieldId(fieldId) {}++ void read(const QJsonObject& json);+ void write(QJsonObject& json) const;++ bool isCellField() const { return m_fieldId == CELL; }QStringList getLayerNames() const { return m_names; }- void build(QStringList &);- void addName(QString name) { m_names.append(name); }+ void build(const QStringList& columnLabels) { m_names = columnLabels; }+ void addName(const QString& name) { m_names.append(name); }};+//=============================================================================+// XdtsTimeTableItem - Timesheet with fields and headers+//=============================================================================+class XdtsTimeTableItem {- //"description": "Individual field info",QList<XdtsTimeTableFieldItem> m_fields;- int m_cellFieldIndex = -1;- //"description": "Timesheet total frames",- //"minimum" : 1- int m_duration;-- //"description": "Timesheet name",- QString m_name;-- // "description": "Individual field layer name",QList<XdtsTimeTableHeaderItem> m_timeTableHeaders;++ int m_cellFieldIndex = -1;int m_cellHeaderIndex = -1;- //"required": ["duration", "name", "timeTableHeaders"]+ int m_duration = 0;+ QString m_name;public:- void read(const QJsonObject &json);- void write(QJsonObject &json) const;+ void read(const QJsonObject& json);+ void write(QJsonObject& json) const;+QStringList getLevelNames() const;- XdtsTimeTableFieldItem getCellField() { return m_fields[m_cellFieldIndex]; }- XdtsTimeTableHeaderItem getCellHeader() {- return m_timeTableHeaders[m_cellHeaderIndex];++ XdtsTimeTableFieldItem getCellField() const {+ return m_fields.value(m_cellFieldIndex);}- int getDuration() { return m_duration; }- void build(TXsheet *, QString, int duration);- bool isEmpty() {++ XdtsTimeTableHeaderItem getCellHeader() const {+ return m_timeTableHeaders.value(m_cellHeaderIndex);+ }++ int getDuration() const { return m_duration; }++ void build(TXsheet* xsheet, const QString& name, int duration);++ bool isEmpty() const {return m_duration == 0 || m_fields.isEmpty() ||m_timeTableHeaders.isEmpty();}};-// "$schema": "http://json-schema.org/draft-07/schema",+//=============================================================================+// XdtsData - Complete XDTS document structure+//=============================================================================+class XdtsData {XdtsHeader m_header;-- //"description": "Timesheet info",- //"minItems" : 1,QList<XdtsTimeTableItem> m_timeTables;- // "description": "XTDS file format version",- enum Version { Ver_2018_11_29 = 5 } m_version;-- // https://github.com/shun-iwasawa/XDTS-uext/blob/main/md/XDTS-uext.md- // "description": "extension version identifier(*9)",- // *9 Set the string "p1" (to indicate the Studio Ponoc extended version 1).- QString m_subversion;+ enum Version { Ver_2018_11_29 = 5 } m_version = Ver_2018_11_29;+ QString m_subversion; // "p1" for Ponoc extended version- //"required": ["timeTables", "version"]public:- XdtsData(Version version = Ver_2018_11_29)- : m_version(version), m_subversion() {}- void read(const QJsonObject &json);- void write(QJsonObject &json) const;+ explicit XdtsData(Version version = Ver_2018_11_29) : m_version(version) {}++ void read(const QJsonObject& json);+ void write(QJsonObject& json) const;+QStringList getLevelNames() const;- XdtsTimeTableItem &timeTable() { return m_timeTables[0]; }- void build(TXsheet *, QString, int duration);- bool isEmpty() { return m_timeTables.isEmpty(); }- bool isUextVersion() { return !m_subversion.isEmpty(); }++ XdtsTimeTableItem& timeTable() { return m_timeTables[0]; }+ const XdtsTimeTableItem& timeTable() const { return m_timeTables[0]; }++ void build(TXsheet* xsheet, const QString& name, int duration);++ bool isEmpty() const { return m_timeTables.isEmpty(); }+ bool isUextVersion() const { return !m_subversion.isEmpty(); }};-bool loadXdtsScene(ToonzScene *scene, const TFilePath &scenePath);+//=============================================================================+// Public interface functions+//=============================================================================++bool loadXdtsScene(ToonzScene* scene, const TFilePath& scenePath);} // namespace XdtsIo-#endif+#endif // XDTSIO_Hdiff --git a/toonz/sources/toonz/xshcellviewer.cpp b/toonz/sources/toonz/xshcellviewer.cppindex 00e3298a6..c6489a02f 100644--- a/toonz/sources/toonz/xshcellviewer.cpp+++ b/toonz/sources/toonz/xshcellviewer.cpp@@ -1,5 +1,3 @@--#include "xshcellviewer.h"// Tnz6 includes@@ -73,6 +71,7 @@#include <QToolTip>#include <QApplication>#include <QClipboard>+#include <QRegularExpression>namespace {@@ -104,7 +103,7 @@ bool selectionContainTlvImage(TCellSelection *selection, TXsheet *xsheet,int r0, r1, c0, c1;selection->getSelectedCells(r0, c0, r1, c1);- // Verifico se almeno un livello della selezione e' un tlv+ // Check if at least one level in the selection is a tlvint c, r;for (c = c0; c <= c1; c++)for (r = r0; r <= r1; r++) {@@ -127,7 +126,7 @@ bool selectionContainRasterImage(TCellSelection *selection, TXsheet *xsheet,int r0, r1, c0, c1;selection->getSelectedCells(r0, c0, r1, c1);- // Verifico se almeno un livello della selezione e' un tlv+ // Check if at least one level in the selection is a rasterint c, r;for (c = c0; c <= c1; c++)for (r = r0; r <= r1; r++) {@@ -148,8 +147,8 @@ bool selectionContainRasterImage(TCellSelection *selection, TXsheet *xsheet,bool selectionContainLevelImage(TCellSelection *selection, TXsheet *xsheet) {int r0, r1, c0, c1;selection->getSelectedCells(r0, c0, r1, c1);- // Verifico se almeno un livello della selezione e' un tlv, un pli o un- // fullcolor (!= .psd)+ // Check if at least one level in the selection is a tlv, pli, or fullcolor+ // (!= .psd)int c, r;for (c = c0; c <= c1; c++)for (r = r0; r <= r1; r++) {@@ -173,9 +172,9 @@ bool selectionContainLevelImage(TCellSelection *selection, TXsheet *xsheet) {*/void parse_with_letter(const QString &text, std::wstring &levelName,TFrameId &fid) {- QRegExp spaces("\\t|\\s");- QRegExp numbers("\\d+");- QRegExp characters("[^\\d+]");+ static QRegularExpression spaces("\\t|\\s");+ static QRegularExpression numbers("\\d+");+ static QRegularExpression characters("[^\\d+]");QString str = text;// remove final spaces@@ -297,11 +296,11 @@ void parse_with_letter(const QString &text, std::wstring &levelName,//-----------------------------------------------------------------------------void parse(const QString &text, std::wstring &levelName, TFrameId &fid) {- QRegExp spaces("\\t|\\s");- QRegExp numbers("\\d+");- QRegExp characters("[^\\d+]");- QRegExp fidWithSuffix(TFilePath::fidRegExpStr());- // QRegExp fidWithSuffix("([0-9]+)([a-z]?)");+ static QRegularExpression spaces("\\t|\\s");+ static QRegularExpression numbers("\\d+");+ static QRegularExpression characters("[^\\d+]");+ static QRegularExpression fidWithSuffix(TFilePath::fidRegExpStr());+QString str = text;// remove final spaces@@ -313,18 +312,21 @@ void parse(const QString &text, std::wstring &levelName, TFrameId &fid) {fid = TFrameId::NO_FRAME;return;}+int lastSpaceIndex = str.lastIndexOf(spaces);if (lastSpaceIndex == -1) {if (str.contains(numbers) && !str.contains(characters)) {levelName = L"";fid = TFrameId(str.toInt());- } else if (fidWithSuffix.exactMatch(str)) {- levelName = L"";- fid = TFrameId(fidWithSuffix.cap(1).toInt(), fidWithSuffix.cap(2));- // fidWithSuffix.cap(2) == "" ? 0 : fidWithSuffix.cap(2).toLatin1()[0]);- } else if (str.contains(characters)) {- levelName = text.toStdWString();- fid = TFrameId::NO_FRAME;+ } else {+ QRegularExpressionMatch match = fidWithSuffix.match(str);+ if (match.hasMatch() && match.capturedLength(0) == str.length()) {+ levelName = L"";+ fid = TFrameId(match.captured(1).toInt(), match.captured(2));+ } else if (str.contains(characters)) {+ levelName = text.toStdWString();+ fid = TFrameId::NO_FRAME;+ }}} else {QString lastString = str.right(str.size() - 1 - lastSpaceIndex);@@ -332,14 +334,16 @@ void parse(const QString &text, std::wstring &levelName, TFrameId &fid) {QString firstString = str.left(lastSpaceIndex);levelName = firstString.toStdWString();fid = TFrameId(lastString.toInt());- } else if (fidWithSuffix.exactMatch(lastString)) {- QString firstString = str.left(lastSpaceIndex);- levelName = firstString.toStdWString();- fid = TFrameId(fidWithSuffix.cap(1).toInt(), fidWithSuffix.cap(2));- // fidWithSuffix.cap(2) == "" ? 0 : fidWithSuffix.cap(2).toLatin1()[0]);- } else if (lastString.contains(characters)) {- levelName = text.toStdWString();- fid = TFrameId::NO_FRAME;+ } else {+ QRegularExpressionMatch match = fidWithSuffix.match(lastString);+ if (match.hasMatch() && match.capturedLength(0) == lastString.length()) {+ QString firstString = str.left(lastSpaceIndex);+ levelName = firstString.toStdWString();+ fid = TFrameId(match.captured(1).toInt(), match.captured(2));+ } else if (lastString.contains(characters)) {+ levelName = text.toStdWString();+ fid = TFrameId::NO_FRAME;+ }}}}@@ -473,7 +477,7 @@ class RenameCellUndo final : public TUndo {const TXshCell m_newCell;public:- // indices sono le colonne inserite+ // indices are the inserted columnsRenameCellUndo(int row, int col, TXshCell oldCell, TXshCell newCell): m_row(row), m_col(col), m_oldCell(oldCell), m_newCell(newCell) {}@@ -617,7 +621,9 @@ int SetCellMarkUndo::getHistoryType() { return HistoryType::Xsheet; }RenameCellField::RenameCellField(QWidget *parent, XsheetViewer *viewer): QLineEdit(parent), m_viewer(viewer), m_row(-1), m_col(-1) {- connect(this, SIGNAL(returnPressed()), SLOT(onReturnPressed()));+ // Modern Qt5 signal-slot syntax+ connect(this, &QLineEdit::returnPressed, this,+ &RenameCellField::onReturnPressed);setContextMenuPolicy(Qt::PreventContextMenu);setObjectName("RenameCellField");setAttribute(Qt::WA_TranslucentBackground, true);@@ -653,7 +659,7 @@ void RenameCellField::showInRowCol(int row, int col, bool multiColumnSelected) {setFont(font);setAlignment(Qt::AlignRight | Qt::AlignBottom);- // Se la cella non e' vuota setto il testo+ // If the cell is not empty, set the textTXsheet *xsh = m_viewer->getXsheet();// adjust text position@@ -828,7 +834,6 @@ void RenameCellField::renameSoundTextColumn(TXshSoundTextColumn *sndTextCol,void RenameCellField::renameCell() {QString newName = text();- // std::wstring newName = s.toStdWString();setText("");@@ -873,8 +878,7 @@ void RenameCellField::renameCell() {// rename cells for each column in the selectionfor (int c = c0; c <= c1; c++) {// if there is no level at the current cell, take the level from the- // previous frames- // (when editing not empty column)+ // previous frames (when editing not empty column)if (xsheet->isColumnEmpty(c)) {// find a level with name same as the column (if the preferences option// is set to do so)@@ -1046,11 +1050,10 @@ bool RenameCellField::eventFilter(QObject *obj, QEvent *e) {// These are usually standard ctrl/command strokes for text editing.// Default to standard behavior and don't execute OT's action while renaming- // cell if users prefer to do so.- // Or, always invoke OT's commands when renaming cell even the standard- // command strokes for text editing.- // The latter option is demanded by Japanese animation industry in order to- // gain efficiency for inputting xsheet.+ // cell if users prefer to do so. Or, always invoke OT's commands when+ // renaming cell even the standard command strokes for text editing. The+ // latter option is demanded by Japanese animation industry in order to gain+ // efficiency for inputting xsheet.if (!Preferences::instance()->isShortcutCommandsWhileRenamingCellEnabled() &&(actionId == "MI_Undo" || actionId == "MI_Redo" ||actionId == "MI_Clear" || actionId == "MI_Copy" ||@@ -1139,16 +1142,18 @@ void RenameCellField::keyPressEvent(QKeyEvent *event) {//-----------------------------------------------------------------------------void RenameCellField::showEvent(QShowEvent *) {- bool ret = connect(TApp::instance()->getCurrentXsheet(),- SIGNAL(xsheetChanged()), this, SLOT(onXsheetChanged()));- assert(ret);+ // Modern Qt5 signal-slot syntax+ connect(TApp::instance()->getCurrentXsheet(), &TXsheetHandle::xsheetChanged,+ this, &RenameCellField::onXsheetChanged);}//-----------------------------------------------------------------------------void RenameCellField::hideEvent(QHideEvent *) {- disconnect(TApp::instance()->getCurrentXsheet(), SIGNAL(xsheetChanged()),- this, SLOT(onXsheetChanged()));+ // Modern Qt5 signal-slot syntax+ disconnect(TApp::instance()->getCurrentXsheet(),+ &TXsheetHandle::xsheetChanged, this,+ &RenameCellField::onXsheetChanged);}//-----------------------------------------------------------------------------@@ -1344,7 +1349,7 @@ void CellArea::drawCells(QPainter &p, const QRect toBeUpdated) {}// check if the column is referencebool isReference = true;- if (column) { // Verifico se la colonna e' una mask+ if (column) { // Check if the column is a maskif (column->isControl() || column->isRendered() ||column->getMeshColumn())isReference = false;@@ -2098,17 +2103,6 @@ void CellArea::drawLevelCell(QPainter &p, int row, int col, bool isReference,: m_viewer->getTextColor();p.setPen(penColor);- /*- QString fontName = Preferences::instance()->getInterfaceFont();- if (fontName == "") {-#ifdef _WIN32- fontName = "Arial";-#else- fontName = "Helvetica";-#endif- }- static QFont font(fontName, -1, QFont::Normal);- */QFont font = p.font();font.setPixelSize(XSHEET_FONT_PX_SIZE);p.setFont(font);@@ -3182,7 +3176,7 @@ class CycleUndo final : public TUndo {CellArea *m_area;public:- // indices sono le colonne inserite+ // indices are the inserted columnsCycleUndo(TStageObject *pegbar, CellArea *area): m_pegbar(pegbar), m_area(area) {}void undo() const override {@@ -3302,16 +3296,16 @@ void CellArea::mousePressEvent(QMouseEvent *event) {// TObjectHandle *oh = TApp::instance()->getCurrentObject();// oh->setObjectId(m_viewer->getObjectId(col));- // gmt, 28/12/2009. Non dovrebbe essere necessario, visto che dopo- // verra cambiata la colonna e quindi l'oggetto corrente- // Inoltre, facendolo qui, c'e' un problema con il calcolo del dpi- // (cfr. SceneViewer::onLevelChanged()): setObjectId() chiama (in cascata)- // onLevelChanged(), ma la colonna corrente risulta ancora quella di prima e- // quindi- // il dpi viene calcolato male. Quando si cambia la colonna l'oggetto- // corrente risulta- // gia' aggiornato e quindi non ci sono altre chiamate a onLevelChanged()- // cfr bug#5235+ // gmt, 12/28/2009. This should not be necessary, since afterwards+ // the column will be changed and therefore the current object+ // will be updated.+ // Moreover, doing it here causes a problem with DPI calculation+ // (see SceneViewer::onLevelChanged()): setObjectId() calls (in cascade)+ // onLevelChanged(), but the current column is still the previous one, and+ // therefore+ // the DPI is calculated incorrectly. When the column is changed, the+ // current object is already updated, so there are no further calls to+ // onLevelChanged() see bug#5235TStageObject *pegbar = xsh->getStageObject(m_viewer->getObjectId(col));@@ -3474,7 +3468,7 @@ void CellArea::mouseMoveEvent(QMouseEvent *event) {QPoint pos = event->pos();QRect visibleRect = visibleRegion().boundingRect();if (m_isPanning) {- // Pan tasto centrale+ // Middle button panm_viewer->scroll(m_pos - pos);return;}@@ -3501,7 +3495,7 @@ void CellArea::mouseMoveEvent(QMouseEvent *event) {TXsheet *xsh = m_viewer->getXsheet();- // Verifico se e' una colonna sound+ // Check if it's a sound columnTXshColumn *column = xsh->getColumn(col);bool isSoundColumn = false;bool isZeraryColumn = false;@@ -3612,11 +3606,11 @@ void CellArea::mouseDoubleClickEvent(QMouseEvent *event) {CellPosition cellPosition = m_viewer->xyToPosition(event->pos());int row = cellPosition.frame();int col = cellPosition.layer();- // Se la colonna e' sound non devo fare nulla+ // If the column is sound, do nothingTXshColumn *column = m_viewer->getXsheet()->getColumn(col);if (column && column->getSoundColumn()) return;- // Se ho cliccato su una nota devo aprire il popup+ // If I clicked on a note, open the popupTXshNoteSet *notes = m_viewer->getXsheet()->getNotes();int i;for (i = notes->getCount() - 1; i >= 0; i--) {@@ -3636,8 +3630,8 @@ void CellArea::mouseDoubleClickEvent(QMouseEvent *event) {if (col == -1) return;- // in modalita' xsheet as animation sheet non deve essere possibile creare- // livelli con doppio click: se la cella e' vuota non bisogna fare nulla+ // In xsheet as animation sheet mode, it should not be possible to create+ // levels with double click: if the cell is empty, do nothingif ((Preferences::instance()->isAnimationSheetEnabled() &&m_viewer->getXsheet()->getCell(row, col).isEmpty())) {TXshColumn *column = m_viewer->getXsheet()->getColumn(col);@@ -3663,7 +3657,7 @@ void CellArea::contextMenuEvent(QContextMenuEvent *event) {QMenu menu(this);- // Verifico se ho cliccato su una nota+ // Check if I clicked on a noteTXshNoteSet *notes = m_viewer->getXsheet()->getNotes();int i;for (i = notes->getCount() - 1; i >= 0; i--) {@@ -3713,11 +3707,11 @@ void CellArea::contextMenuEvent(QContextMenuEvent *event) {->isLocked()) // on the line between two keyframescreateKeyLineMenu(menu, row, col);} else if (m_viewer->getCellSelection()->isCellSelected(- row, col) && // La cella e' selezionata+ row, col) && // The cell is selected(abs(r1 - r0) > 0 ||abs(c1 - c0) >- 0)) // Il numero di celle selezionate e' maggiore di 1- { // Sono su una selezione di celle+ 0)) // The number of selected cells is greater than 1+ { // I'm on a cell selectionm_viewer->setCurrentColumn(col);int e, f;bool areCellsEmpty = false;@@ -3939,8 +3933,8 @@ void CellArea::createCellMenu(QMenu &menu, bool isCellSelected, TXshCell cell,->listLevels(levels);if (!levels.empty()) {QMenu *replaceMenu = replaceLevelMenu->addMenu(tr("Replace with"));- connect(replaceMenu, SIGNAL(triggered(QAction *)), this,- SLOT(onReplaceByCastedLevel(QAction *)));+ connect(replaceMenu, &QMenu::triggered, this,+ &CellArea::onReplaceByCastedLevel);for (int i = 0; i < (int)levels.size(); i++) {if (!levels[i]->getSimpleLevel() && !levels[i]->getChildLevel())continue;@@ -4074,7 +4068,7 @@ void CellArea::createCellMenu(QMenu &menu, bool isCellSelected, TXshCell cell,markAction->setChecked(markId == -1);markAction->setEnabled(markId != -1);markAction->setData(QList<QVariant>{row, col, -1});- connect(markAction, SIGNAL(triggered()), this, SLOT(onSetCellMark()));+ connect(markAction, &QAction::triggered, this, &CellArea::onSetCellMark);QList<TSceneProperties::CellMark> marks = TApp::instance()->getCurrentScene()->getScene()@@ -4088,7 +4082,7 @@ void CellArea::createCellMenu(QMenu &menu, bool isCellSelected, TXshCell cell,markAction->setChecked(markId == curId);markAction->setEnabled(markId != curId);markAction->setData(QList<QVariant>{row, col, curId});- connect(markAction, SIGNAL(triggered()), this, SLOT(onSetCellMark()));+ connect(markAction, &QAction::triggered, this, &CellArea::onSetCellMark);curId++;}@@ -4181,7 +4175,7 @@ void CellArea::createKeyLineMenu(QMenu &menu, int row, int col) {menu.addAction(cmdManager->getAction(MI_SetConstantSpeed));menu.addSeparator();} else {- // Se le due chiavi non sono linear aggiungo il comando ResetInterpolation+ // If the two keys are not linear, add ResetInterpolation commandbool isR0FullK = pegbar->isFullKeyframe(r0);bool isR1FullK = pegbar->isFullKeyframe(r1);TDoubleKeyframe::Type r0Type =@@ -4234,8 +4228,8 @@ void CellArea::createKeyLineMenu(QMenu &menu, int row, int col) {actionGroup->addAction(act);menu.addAction(act);}- connect(actionGroup, SIGNAL(triggered(QAction *)), this,- SLOT(onStepChanged(QAction *)));+ connect(actionGroup, &QActionGroup::triggered, this,+ &CellArea::onStepChanged);}//-----------------------------------------------------------------------------@@ -4243,9 +4237,9 @@ void CellArea::createKeyLineMenu(QMenu &menu, int row, int col) {void CellArea::createNoteMenu(QMenu &menu) {QAction *openAct = menu.addAction(tr("Open Memo"));QAction *deleteAct = menu.addAction(tr("Delete Memo"));- bool ret = connect(openAct, SIGNAL(triggered()), this, SLOT(openNote()));- ret =- ret && connect(deleteAct, SIGNAL(triggered()), this, SLOT(deleteNote()));+ bool ret = connect(openAct, &QAction::triggered, this, &CellArea::openNote);+ ret = ret &&+ connect(deleteAct, &QAction::triggered, this, &CellArea::deleteNote);}//-----------------------------------------------------------------------------diff --git a/toonz/sources/toonz/xshcellviewer.h b/toonz/sources/toonz/xshcellviewer.hindex 87c4b33d8..c8a1d2fa1 100644--- a/toonz/sources/toonz/xshcellviewer.h+++ b/toonz/sources/toonz/xshcellviewer.h@@ -72,7 +72,7 @@ protected slots:// CellArea//------------------------------------------------------------------------------//! La classe si occupa della visualizzazione delle celle nel viewer.+//! The class handles the display of cells in the viewerclass CellArea final : public QWidget {Q_OBJECT@@ -129,7 +129,7 @@ class CellArea final : public QWidget {void drawFocusCellBorder(QPainter &p);- // Restistusce true+ // Returns truebool getEaseHandles(int r0, int r1, double e0, double e1, int &rh0, int &rh1);bool isKeyFrameArea(int col, int row, QPoint mouseInCell);@@ -141,17 +141,16 @@ public:CellArea(XsheetViewer *parent, Qt::WindowFlags flags = Qt::WindowFlags());~CellArea();+ // Event handlersvoid mouseMoveEvent(QMouseEvent *event) override;- // display upper-directional smart tab only when pressing ctrl key+ // Display upper-directional smart tab only when pressing ctrl keyvoid onControlPressed(bool pressed);const bool isControlPressed();- // edit current cell's ID+ // Edit current cell's IDvoid onNumberPressed(int number);- // void keyUpDownPressed(int newRow);-void showRenameField(int row, int col, bool multiColumnSelected = false) {m_renameCell->showInRowCol(row, col, multiColumnSelected);}@@ -170,25 +169,23 @@ protected:void dropEvent(QDropEvent *event) override;bool event(QEvent *event) override;- /*!Crea il menu' del tasto destro che si visualizza quando si clicca sulla-cella,-distinguendo i due casi: cella piena, cella vuota.*/+ /*! Creates the right-click menu that appears when clicking on a cell,+ distinguishing between the two cases: full cell, empty cell. */void createCellMenu(QMenu &menu, bool isCellSelected, TXshCell cell, int row,int col);- //! Crea il menu' del tasto destro che si visualizza si clicca su un key- //! frame.+ //! Creates the right-click menu that appears when clicking on a key framevoid createKeyMenu(QMenu &menu);- //! Crea il menu' del tasto destro che si visualizza quando si clicca sulla- //! linea tre due key frame.+ //! Creates the right-click menu that appears when clicking on the line+ //! between two key framesvoid createKeyLineMenu(QMenu &menu, int row, int col);- //! Crea il menu' del tasto destro che si visualizza quando si sopra una nota.+ //! Creates the right-click menu that appears when hovering over a notevoid createNoteMenu(QMenu &menu);protected slots:void openNote();void deleteNote();void onStepChanged(QAction *);- // replace level with another level in the cast+ // Replace level with another level in the castvoid onReplaceByCastedLevel(QAction *action);void onSetCellMark();};