OpenToonz - An open-source full-featured 2D animation creation software
C
Improve thread safety and runtime error handling in TSystem
Anderson Prado4600efb66b94
diff --git a/toonz/sources/common/tsystem/tsystem.cpp b/toonz/sources/common/tsystem/tsystem.cppindex 3b79d7c06..7d03d668a 100644--- a/toonz/sources/common/tsystem/tsystem.cpp+++ b/toonz/sources/common/tsystem/tsystem.cpp@@ -1,6 +1,9 @@++#include "tsystem.h"#include <set>+#include <atomic>#include "tfilepath_io.h"#include "tconvert.h"@@ -21,7 +24,6 @@#include <QCoreApplication>#include <QUuid>#include <QRegularExpression>-#include <QDesktopServices>#include <QHostInfo>@@ -37,14 +39,24 @@ inline QString toQString(const TFilePath &path) {return QString::fromStdWString(path.getWideString());}-int HasMainLoop = -1;+std::atomic<int> HasMainLoop{-1}; // Changed to atomic for thread safety} // namespace//------------------------------------------------------------------------------------TFileStatus::TFileStatus(const TFilePath &path) {- m_fileInfo = QFileInfo(QString::fromStdWString(path.getWideString()));- m_exist = m_fileInfo.exists();+TFileStatus::TFileStatus(const TFilePath &path)+ : m_fileInfo(QString::fromStdWString(path.getWideString()))+ , m_exist(false) // safe default value; see NOTE below+// During static init (e.g., EnvGlobals) before QCoreApplication exists.+// m_exist defaults to false. Proper fix requires refactoring init order in+// tenv.cpp, tcontenthistory.cpp, etc. to create QCoreApplication first.+// Workaround avoids crashes.+{+ if (QCoreApplication::instance() == nullptr) {+ return; // avoids premature exists() doesn't crash during static+ // initialization+ }+ m_exist = m_fileInfo.exists();}//-----------------------------------------------------------------------------------@@ -110,16 +122,32 @@ bool TFileStatus::isLink() const { return m_fileInfo.isSymLink(); }//-----------------------------------------------------------------------------------bool TSystem::doHaveMainLoop() {- if (HasMainLoop == -1)- assert(!"you MUST call the TSystem::hasMainLoop function in the main of the program!");- return HasMainLoop == 1;+ int current = HasMainLoop.load(std::memory_order_acquire);++ if (current == -1) {+#ifdef QT_DEBUG+ qFatal("TSystem::hasMainLoop was not called");+#else+ qWarning("Main loop not initialized");+#endif+ return false;+ }+ return current == 1;}//-----------------------------------------------------------------------------------void TSystem::hasMainLoop(bool state) {- assert(HasMainLoop == -1);- HasMainLoop = state ? 1 : 0;+ int expected = -1;+ int desired = state ? 1 : 0;++ if (!HasMainLoop.compare_exchange_strong(expected, desired,+ std::memory_order_acq_rel,+ std::memory_order_acquire)) {+#ifdef QT_DEBUG+ qWarning("TSystem::hasMainLoop called multiple times (debug check)");+#endif+ }}//-----------------------------------------------------------------------------------@@ -130,8 +158,7 @@ QString TSystem::getHostName() { return QHostInfo::localHostName(); }QString TSystem::getUserName() {QStringList list = QProcess::systemEnvironment();- int j;- for (j = 0; j < list.size(); j++) {+ for (int j = 0; j < list.size(); j++) {QString value = list.at(j);QString user;#ifdef _WIN32@@ -161,15 +188,15 @@ TFilePath TSystem::getTestDir(std::string name) {QString TSystem::getSystemValue(const TFilePath &name) {QStringList strlist = toQString(name).split("\\", Qt::SkipEmptyParts);- assert(strlist.size() > 3);- assert(strlist.at(0) == "SOFTWARE");+ if (strlist.size() <= 3 || strlist.at(0) != "SOFTWARE") {+ qWarning("Invalid system value path format");+ return QString();+ }QSettings qs(QSettings::SystemScope, strlist.at(1), strlist.at(2));- int i;QString varName;-- for (i = 3; i < strlist.size(); i++) {+ for (int i = 3; i < strlist.size(); i++) {varName += strlist.at(i);if (i < strlist.size() - 1) varName += "//";}@@ -192,12 +219,10 @@ TFilePath TSystem::getDllDir() { return getBinDir(); }TFilePath TSystem::getUniqueFile(QString field) {QString uuid = QUuid::createUuid()- .toString()- .replace("-", "")+ .toString(QUuid::Id128).replace("{", "").replace("}", "")- .toLatin1()- .data();+ .replace("-", "");QString path = QDir::tempPath() + QString("\\") + field + uuid;@@ -221,19 +246,22 @@ TFilePathSet getPathsToCreate(const TFilePath &path) {void setPathsPermissions(const TFilePathSet &pathSet,QFile::Permissions permissions) {- TFilePathSet::const_iterator it;- for (it = pathSet.begin(); it != pathSet.end(); it++) {- QFile f(toQString(*it));+ for (const auto &path : pathSet) {+ QFile f(toQString(path));f.setPermissions(permissions);}}} // namespace-// gestire exception+// handle exceptionvoid TSystem::mkDir(const TFilePath &path) {TFilePathSet pathSet = getPathsToCreate(path);QString qPath = toQString(path);- assert(!qPath.contains("+"));++ if (qPath.contains("+")) {+ throw TSystemException(path, "Invalid character '+' in path!");+ }+if (!QDir::current().mkpath(qPath))throw TSystemException(path, "can't create folder!");@@ -244,7 +272,7 @@ void TSystem::mkDir(const TFilePath &path) {}//-------------------------------------------------------------// gestire exception+// handle exceptionvoid TSystem::rmDir(const TFilePath &path) {if (!QDir(toQString(path.getParentDir())).rmdir(QString::fromStdString(path.getName())))@@ -257,10 +285,8 @@ void TSystem::rmDir(const TFilePath &path) {namespace {void rmDirTree(const QString &path) {- int i;QFileInfoList fil = QDir(path).entryInfoList();- for (i = 0; i < fil.size(); i++) {- QFileInfo fi = fil.at(i);+ for (const QFileInfo &fi : fil) {if (fi.fileName() == QString(".") || fi.fileName() == QString(".."))continue;QString son = fi.absoluteFilePath();@@ -287,9 +313,7 @@ void TSystem::copyDir(const TFilePath &dst, const TFilePath &src) {QDir::current().mkdir(toQString(dst));- int i;- for (i = 0; i < fil.size(); i++) {- QFileInfo fi = fil.at(i);+ for (const QFileInfo &fi : fil) {if (fi.fileName() == QString(".") || fi.fileName() == QString(".."))continue;if (fi.isDir()) {@@ -303,60 +327,97 @@ void TSystem::copyDir(const TFilePath &dst, const TFilePath &src) {}}-//------------------------------------------------------------/*+void TSystem::touchFile(const TFilePath &path)+{+QFile f(toQString(path));+if (!f.open(QIODevice::ReadWrite))+throw TSystemException(path, "can't touch file!");+else+f.close();+}+*/+//------------------------------------------------------------+/*+#ifdef _WIN32+std::wstring getFormattedMessage(DWORD lastError)+{+LPVOID lpMsgBuf;+FormatMessage(+FORMAT_MESSAGE_ALLOCATE_BUFFER |+FORMAT_MESSAGE_FROM_SYSTEM |+FORMAT_MESSAGE_IGNORE_INSERTS,+NULL,+lastError,+MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language+(LPTSTR) &lpMsgBuf,+0,+NULL+);+int wSize = MultiByteToWideChar(0,0,(char*)lpMsgBuf,-1,0,0);+if(!wSize)+return std::wstring();+wchar_t* wBuffer = new wchar_t [wSize+1];+MultiByteToWideChar(0,0,(char*)lpMsgBuf,-1,wBuffer,wSize);+wBuffer[wSize]='\0';+std::wstring wmsg(wBuffer);+delete []wBuffer;+LocalFree(lpMsgBuf);+return wmsg;+}-//------------------------------------------------------------#endif+*/-//------------------------------------------------------------void TSystem::copyFile(const TFilePath &dst, const TFilePath &src,bool overwrite) {- assert(dst != TFilePath());+ if (dst.isEmpty()) {+ throw TSystemException(dst, "Destination path is empty!");+ }if (dst == src) return;@@ -364,7 +425,10 @@ void TSystem::copyFile(const TFilePath &dst, const TFilePath &src,touchParentDir(dst);const QString &qDst = toQString(dst);- if (overwrite && QFile::exists(qDst)) QFile::remove(qDst);+ if (overwrite && QFile::exists(qDst)) {+ if (!QFile::remove(qDst))+ throw TSystemException(dst, "can't remove existing file!");+ }if (!QFile::copy(toQString(src), qDst))throw TSystemException(dst, "can't copy file!");@@ -374,12 +438,17 @@ void TSystem::copyFile(const TFilePath &dst, const TFilePath &src,void TSystem::renameFile(const TFilePath &dst, const TFilePath &src,bool overwrite) {- assert(dst != TFilePath());+ if (dst.isEmpty()) {+ throw TSystemException(dst, "Destination path is empty!");+ }if (dst == src) return;const QString &qDst = toQString(dst);- if (overwrite && QFile::exists(qDst)) QFile::remove(qDst);+ if (overwrite && QFile::exists(qDst)) {+ if (!QFile::remove(qDst))+ throw TSystemException(dst, "can't remove existing file!");+ }if (!QFile::rename(toQString(src), qDst))throw TSystemException(dst, "can't rename file!");@@ -387,7 +456,7 @@ void TSystem::renameFile(const TFilePath &dst, const TFilePath &src,//-------------------------------------------------------------// gestire gli errori con GetLastError?+// handle errors with GetLastError?void TSystem::deleteFile(const TFilePath &fp) {if (!QFile::remove(toQString(fp)))throw TSystemException(fp, "can't delete file!");@@ -414,18 +483,22 @@ public:const std::wstring a_str = a.getWideString();const std::wstring b_str = b.getWideString();- unsigned int i = 0;- int case_compare = -1;- while (a_str[i] || b_str[i]) {- if (a_str[i] != b_str[i]) {- const wchar_t a_wchar = towlower(a_str[i]);- const wchar_t b_wchar = towlower(b_str[i]);+ size_t i = 0;+ int case_compare = -1;+ const size_t maxLen = std::max(a_str.size(), b_str.size());+ for (size_t i = 0; i < maxLen; ++i) {+ wchar_t a_char = (i < a_str.size()) ? a_str[i] : L'\0';+ wchar_t b_char = (i < b_str.size()) ? b_str[i] : L'\0';++ if (a_char != b_char) {+ const wchar_t a_wchar = towlower(a_char);+ const wchar_t b_wchar = towlower(b_char);if (a_wchar < b_wchar) {return true;} else if (a_wchar > b_wchar) {return false;} else if (case_compare == -1) {- case_compare = a_str[i] < b_str[i];+ case_compare = (a_char < b_char) ? 1 : 0;}}i++;@@ -488,9 +561,12 @@ void TSystem::readDirectory_DirItems(QStringList &dst, const TFilePath &path) {HANDLE hFind =FindFirstFile((const wchar_t *)dir_search_path.utf16(), &find_dir_data);if (hFind != INVALID_HANDLE_VALUE) {- addEntry();- while (FindNextFile(hFind, &find_dir_data)) addEntry();+ do {+ addEntry();+ } while (FindNextFile(hFind, &find_dir_data));+ FindClose(hFind); // FIXED: Added FindClose}+for (const QString &name : entries) dst.push_back(QString(name));#else@@ -528,18 +604,19 @@ void TSystem::readDirectory(TFilePathSet &groupFpSet, TFilePathSet &allFpSet,HANDLE hFind =FindFirstFile((const wchar_t *)dir_search_path.utf16(), &find_dir_data);if (hFind != INVALID_HANDLE_VALUE) {- addEntry();- while (FindNextFile(hFind, &find_dir_data)) addEntry();+ do {+ addEntry();+ } while (FindNextFile(hFind, &find_dir_data));+ FindClose(hFind); // FIXED: Added FindClose}#elsefil = QDir(toQString(path)).entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable);#endif- if (fil.size() == 0) return;- for (int i = 0; i < fil.size(); i++) {- QString fi = fil.at(i);+ if (fil.empty()) return;+ for (const QString &fi : fil) {TFilePath son = path + TFilePath(fi.toStdWString());// store all file paths@@ -548,7 +625,7 @@ void TSystem::readDirectory(TFilePathSet &groupFpSet, TFilePathSet &allFpSet,// in case of the sequential filesif (son.getDots() == "..") son = son.withFrame();- // store the group. insersion avoids duplication of the item+ // store the group. insertion avoids duplication of the itemfileSet_group.insert(son);}@@ -572,15 +649,16 @@ void TSystem::readDirectory(TFilePathSet &dst, const QDir &dir,// store name filtersbool hasNameFilter = false;- QList<QRegExp> nameFilters;+ QList<QRegularExpression> nameFilters;for (const QString &nameFilter : dir.nameFilters()) {if (nameFilter == "*") {hasNameFilter = false;break;}- QRegExp regExp(nameFilter);- regExp.setPatternSyntax(QRegExp::Wildcard);- nameFilters.append(regExp);+ // Convert wildcard pattern to regular expression+ QString pattern =+ QRegularExpression::wildcardToRegularExpression(nameFilter);+ nameFilters.append(QRegularExpression(pattern));hasNameFilter = true;}@@ -606,8 +684,9 @@ void TSystem::readDirectory(TFilePathSet &dst, const QDir &dir,// name filterif (hasNameFilter) {bool matched = false;- for (const QRegExp ®Exp : nameFilters) {- if (regExp.exactMatch(fileName)) {+ for (const QRegularExpression ®Exp : nameFilters) {+ QRegularExpressionMatch match = regExp.match(fileName);+ if (match.hasMatch()) {matched = true;break;}@@ -621,8 +700,10 @@ void TSystem::readDirectory(TFilePathSet &dst, const QDir &dir,HANDLE hFind =FindFirstFile((const wchar_t *)dir_search_path.utf16(), &find_dir_data);if (hFind != INVALID_HANDLE_VALUE) {- addEntry();- while (FindNextFile(hFind, &find_dir_data)) addEntry();+ do {+ addEntry();+ } while (FindNextFile(hFind, &find_dir_data));+ FindClose(hFind); // FIXED: Added FindClose}#elseentries = (dir.entryList(dir.filter() | QDir::NoDotAndDotDot));@@ -632,9 +713,8 @@ void TSystem::readDirectory(TFilePathSet &dst, const QDir &dir,std::set<TFilePath, CaselessFilepathLess> fpSet;- int e, eCount = entries.size();- for (e = 0; e != eCount; ++e) {- TFilePath path(dirPath + TFilePath(entries.at(e).toStdWString()));+ for (const QString &entry : entries) {+ TFilePath path(dirPath + TFilePath(entry.toStdWString()));if (groupFrames && path.getDots() == "..") path = path.withFrame();@@ -664,9 +744,8 @@ void TSystem::readDirectory(TFilePathSet &dst, const TFilePath &path,void TSystem::readDirectory(TFilePathSet &dst, const TFilePathSet &pathSet,bool groupFrames, bool onlyFiles,bool getHiddenFiles) {- for (TFilePathSet::const_iterator it = pathSet.begin(); it != pathSet.end();- it++)- readDirectory(dst, *it, groupFrames, onlyFiles);+ for (const auto &path : pathSet)+ readDirectory(dst, path, groupFrames, onlyFiles, getHiddenFiles);}//------------------------------------------------------------@@ -698,9 +777,7 @@ void TSystem::readDirectoryTree(TFilePathSet &dst, const TFilePath &path,std::set<TFilePath, CaselessFilepathLess> fpSet;QFileInfoList fil = QDir(toQString(path)).entryInfoList();- int i;- for (i = 0; i < fil.size(); i++) {- QFileInfo fi = fil.at(i);+ for (const QFileInfo &fi : fil) {if (fi.fileName() == QString(".") || fi.fileName() == QString(".."))continue;TFilePath son = TFilePath(fi.filePath().toStdWString());@@ -722,9 +799,8 @@ void TSystem::readDirectoryTree(TFilePathSet &dst, const TFilePath &path,void TSystem::readDirectoryTree(TFilePathSet &dst, const TFilePathSet &pathSet,bool groupFrames, bool onlyFiles) {- for (TFilePathSet::const_iterator it = pathSet.begin(); it != pathSet.end();- it++)- readDirectoryTree(dst, *it, groupFrames, onlyFiles);+ for (const auto &path : pathSet)+ readDirectoryTree(dst, path, groupFrames, onlyFiles);}//------------------------------------------------------------@@ -749,14 +825,12 @@ TFilePathSet TSystem::readDirectoryTree(const TFilePathSet &pathSet,TFilePathSet TSystem::packLevelNames(const TFilePathSet &fps) {std::set<TFilePath> tmpSet;- TFilePathSet::const_iterator cit;- for (cit = fps.begin(); cit != fps.end(); ++cit)- tmpSet.insert(cit->getParentDir() + cit->getLevelName());+ for (const auto &fp : fps)+ tmpSet.insert(fp.getParentDir() + fp.getLevelName());TFilePathSet fps2;- for (std::set<TFilePath>::const_iterator c_sit = tmpSet.begin();- c_sit != tmpSet.end(); ++c_sit) {- fps2.push_back(*c_sit);+ for (const auto &fp : tmpSet) {+ fps2.push_back(fp);}return fps2;}@@ -766,9 +840,8 @@ TFilePathSet TSystem::packLevelNames(const TFilePathSet &fps) {TFilePathSet TSystem::getDisks() {TFilePathSet filePathSet;QFileInfoList fil = QDir::drives();- int i;- for (i = 0; i < fil.size(); i++)- filePathSet.push_back(TFilePath(fil.at(i).filePath().toStdWString()));+ for (const QFileInfo &fi : fil)+ filePathSet.push_back(TFilePath(fi.filePath().toStdWString()));return filePathSet;}@@ -778,9 +851,10 @@ TFilePathSet TSystem::getDisks() {class LocalThread final : public QThread {public:static LocalThread *currentThread() {- return (LocalThread *)QThread::currentThread();+ QThread *current = QThread::currentThread();+ return dynamic_cast<LocalThread *>(current); // Safer cast}- void sleep(TINT64 delay) { msleep(delay); }+ void sleep(TINT64 delay) { msleep(static_cast<unsigned long>(delay)); }};void TSystem::sleep(TINT64 delay) {@@ -804,23 +878,33 @@ bool TSystem::doesExistFileOrLevel(const TFilePath &fp) {try {files = TSystem::readDirectory(parentDir, false, true, true);} catch (...) {+ return false;}- TFilePathSet::iterator it, end = files.end();- for (it = files.begin(); it != end; ++it) {- if (it->getLevelNameW() == fp.getLevelNameW()) return true;+ for (const auto &file : files) {+ if (file.getLevelNameW() == fp.getLevelNameW()) return true;}} else if (fp.getType() == "psd") {QString name(QString::fromStdWString(fp.getWideName()));name.append(QString::fromStdString(fp.getDottedType()));- int sepPos = name.indexOf("#");- int dotPos = name.indexOf(".", sepPos);- int removeChars = dotPos - sepPos;- int doubleUnderscorePos = name.indexOf("__", sepPos);- if (doubleUnderscorePos > 0) removeChars = doubleUnderscorePos - sepPos;+ int sepPos = name.indexOf("#");+ if (sepPos >= 0) {+ int dotPos = name.indexOf(".", sepPos);+ int doubleUnderscorePos = name.indexOf("__", sepPos);- name.remove(sepPos, removeChars);+ int removeChars = 0;+ if (dotPos > sepPos) {+ removeChars = dotPos - sepPos;+ }+ if (doubleUnderscorePos > 0 && doubleUnderscorePos < dotPos) {+ removeChars = doubleUnderscorePos - sepPos;+ }++ if (removeChars > 0) {+ name.remove(sepPos, removeChars);+ }+ }TFilePath psdpath(fp.getParentDir() + TFilePath(name.toStdWString()));if (TFileStatus(psdpath).doesExist()) return true;@@ -837,17 +921,17 @@ void TSystem::copyFileOrLevel_throw(const TFilePath &dst,TFilePathSet files;files = TSystem::readDirectory(src.getParentDir(), false);- TFilePathSet::iterator it, end = files.end();- for (it = files.begin(); it != end; ++it) {- if (it->getLevelNameW() == src.getLevelNameW()) {- TFilePath src1 = *it;- TFilePath dst1 = dst.withFrame(it->getFrame());+ for (const auto &file : files) {+ if (file.getLevelNameW() == src.getLevelNameW()) {+ TFilePath src1 = file;+ TFilePath dst1 = dst.withFrame(file.getFrame());TSystem::copyFile(dst1, src1);}}- } else+ } else {TSystem::copyFile(dst, src);+ }}//--------------------------------------------------------------@@ -856,23 +940,25 @@ bool TSystem::renameImageSequence(const TFilePathSet &files,const TFilePath &levelPath,int prefixLength) {std::string levelBaseName = levelPath.withoutParentDir().getName();- assert(files.begin()->isAbsolute() && levelPath.isAbsolute());- // TSystem::readDirectory(levelPath.getParentDir(), false);+ if (files.empty() || !files.begin()->isAbsolute() ||+ !levelPath.isAbsolute()) {+ return false;+ }std::wstring wstr;TFilePath dst;for (const TFilePath &file : files) {wstr = file.getWideName();- if (wstr.size() > prefixLength)+ if (wstr.size() > static_cast<size_t>(prefixLength))wstr = wstr.substr(prefixLength);elsewstr.clear();- dst = file.getParentDir() +(levelBaseName + "." + TFrameId(wstr).expand()- + file.getDottedType());+ dst = file.getParentDir() + (levelBaseName + "." + TFrameId(wstr).expand() ++ file.getDottedType());try {- TSystem::renameFile(dst, file);+ TSystem::renameFile(dst, file, false);} catch (...) {return false;}@@ -886,8 +972,7 @@ void TSystem::renameFileOrLevel_throw(const TFilePath &dst,if (renamePalette && ((src.getType() == "tlv") || (src.getType() == "tzp") ||(src.getType() == "tzu"))) {// Special case: since renames cannot be 'grouped' in the UI, palettes are- // automatically- // renamed here if required+ // automatically renamed here if requiredconst char *type = (src.getType() == "tlv") ? "tpl" : "plt";TFilePath srcpltname(src.withNoFrame().withType(type));@@ -902,16 +987,17 @@ void TSystem::renameFileOrLevel_throw(const TFilePath &dst,TFilePathSet files;files = TSystem::readDirectory(src.getParentDir(), false);- for (TFilePathSet::iterator it = files.begin(); it != files.end(); it++) {- if (it->getLevelName() == src.getLevelName()) {- TFilePath src1 = *it;- TFilePath dst1 = dst.withFrame(it->getFrame());+ for (const auto &file : files) {+ if (file.getLevelName() == src.getLevelName()) {+ TFilePath src1 = file;+ TFilePath dst1 = dst.withFrame(file.getFrame());TSystem::renameFile(dst1, src1);}}- } else+ } else {TSystem::renameFile(dst, src);+ }}//--------------------------------------------------------------@@ -921,12 +1007,12 @@ void TSystem::removeFileOrLevel_throw(const TFilePath &fp) {TFilePathSet files;files = TSystem::readDirectory(fp.getParentDir(), false, true, true);- TFilePathSet::iterator it, end = files.end();- for (it = files.begin(); it != end; ++it) {- if (it->getLevelName() == fp.getLevelName()) TSystem::deleteFile(*it);+ for (const auto &file : files) {+ if (file.getLevelName() == fp.getLevelName()) TSystem::deleteFile(file);}- } else+ } else {TSystem::deleteFile(fp);+ }}//--------------------------------------------------------------@@ -936,12 +1022,12 @@ void TSystem::hideFileOrLevel_throw(const TFilePath &fp) {TFilePathSet files;files = TSystem::readDirectory(fp.getParentDir(), false);- TFilePathSet::iterator it, end = files.end();- for (it = files.begin(); it != end; ++it) {- if (it->getLevelNameW() == fp.getLevelNameW()) TSystem::hideFile(*it);+ for (const auto &file : files) {+ if (file.getLevelNameW() == fp.getLevelNameW()) TSystem::hideFile(file);}- } else+ } else {TSystem::hideFile(fp);+ }}//--------------------------------------------------------------@@ -951,13 +1037,13 @@ void TSystem::moveFileOrLevelToRecycleBin_throw(const TFilePath &fp) {TFilePathSet files;files = TSystem::readDirectory(fp.getParentDir(), false, true, true);- TFilePathSet::iterator it, end = files.end();- for (it = files.begin(); it != end; ++it) {- if (it->getLevelNameW() == fp.getLevelNameW())- TSystem::moveFileToRecycleBin(*it);+ for (const auto &file : files) {+ if (file.getLevelNameW() == fp.getLevelNameW())+ TSystem::moveFileToRecycleBin(file);}- } else+ } else {TSystem::moveFileToRecycleBin(fp);+ }}//--------------------------------------------------------------@@ -1037,41 +1123,32 @@ bool TSystem::touchParentDir(const TFilePath &fp) {bool TSystem::showDocument(const TFilePath &path) {#ifdef _WIN32- unsigned long long ret = (unsigned long long)ShellExecuteW(- 0, L"open", path.getWideString().c_str(), 0, 0, SW_SHOWNORMAL);- if (ret <= 32) {+ HINSTANCE ret = ShellExecuteW(0, L"open", path.getWideString().c_str(), 0, 0,+ SW_SHOWNORMAL);++ // ShellExecute returns a value greater than 32 if successful+ if (reinterpret_cast<intptr_t>(ret) <= 32) {+ qWarning("Can't open document: %ls", path.getWideString().c_str());return false;- throw TSystemException(path, "Can't open");}return true;#else- std::string cmd = "open ";- std::string thePath(::to_string(path));- UINT pos = 0, count = 0;- // std::string newPath;- char newPath[2048];-- while (pos < thePath.size()) {- char c = thePath[pos];- if (c == ' ') newPath[count++] = '\\';-- newPath[count++] = c;- ++pos;+ // Use QDesktopServices for cross-platform support+ QUrl url = QUrl::fromLocalFile(toQString(path));+ if (!QDesktopServices::openUrl(url)) {+ qWarning("Can't open document: %s", toQString(path).toUtf8().constData());+ return false;}- newPath[count] = 0;-- cmd = cmd + std::string(newPath);- system(cmd.c_str());return true;#endif}bool TSystem::isDLLBlackListed(QString dllFile) {- QStringList dllBlackList = {"lvcod64.dll", "ff_vfw.dll", "tsccvid64.dll",- "hapcodec.dll"};+ static const QStringList dllBlackList = {"lvcod64.dll", "ff_vfw.dll",+ "tsccvid64.dll", "hapcodec.dll"};- for (int x = 0; x < dllBlackList.count(); x++) {- if (dllFile.contains(dllBlackList.at(x), Qt::CaseInsensitive)) {+ for (const QString &blacklisted : dllBlackList) {+ if (dllFile.contains(blacklisted, Qt::CaseInsensitive)) {return true;}}@@ -1083,14 +1160,16 @@ bool TSystem::isDLLBlackListed(QString dllFile) {#include <windows.h>-void TSystem::sleep(TINT64 delay) { Sleep((DWORD)delay); }--// gestire gli errori con GetLastError?-void TSystem::deleteFile(const TFilePath &fp) { assert(false); }+void TSystem::sleep(TINT64 delay) { Sleep(static_cast<DWORD>(delay)); }-void TSystem::rmDirTree(const TFilePath &path) { assert(false); }+// handle errors with GetLastError?+void TSystem::deleteFile(const TFilePath &fp) {+ // Empty implementation for light version+}-//------------------------------------------------------------+void TSystem::rmDirTree(const TFilePath &path) {+ // Empty implementation for light version+}//------------------------------------------------------------@@ -1112,7 +1191,8 @@ TSystemException::TSystemException(const TFilePath &fname,: m_fname(fname), m_err(-1), m_msg(::to_wstring(msg)) {}//---------------------------------------------------------------TSystemException::TSystemException(const TFilePath &fname, const std::wstring &msg)+TSystemException::TSystemException(const TFilePath &fname,+ const std::wstring &msg): m_fname(fname), m_err(-1), m_msg(msg) {}//--------------------------------------------------------------diff --git a/toonz/sources/include/tsystem.h b/toonz/sources/include/tsystem.hindex 2ca9583a9..75bb0c5ca 100644--- a/toonz/sources/include/tsystem.h+++ b/toonz/sources/include/tsystem.h@@ -3,7 +3,7 @@#ifndef TSYSTEM_INCLUDED#define TSYSTEM_INCLUDED-//#include "texception.h"+// #include "texception.h"#ifndef _WIN32#include <sys/stat.h>@@ -23,8 +23,8 @@#include "tfilepath.h"-// tutte le info ritornate da stat e access-// piu' info 'toonzesche' : cos'e': directory, livello, immagine, testo, ecc.+// all info returned by stat and access+// plus 'toonz-like' info: what is it: directory, level, image, text, etc.#ifndef TNZCORE_LIGHT@@ -81,11 +81,9 @@ public:// DVAPI ostream&operator<<(ostream&out, const TSystemException &e);namespace TSystem {-// cambiare i nomi. Niente T (c'e' gia' in TSystem). Usiamo la convenzione-// solita per-// i nomi composti (maiuscole e non '_'). Facciamo tutto minuscolo con-// l'iniziale maiuscola-// es. MaxPathLen;+// change names. No T (already in TSystem). Use the usual convention for+// compound names (capitals and no '_'). Let's use lowercase with initial+// capital e.g. MaxPathLen;extern const int MaxPathLen; // Maximum length of full pathextern const int MaxFNameLen; // Maximum length of filename component@@ -96,7 +94,7 @@ DVAPI void hasMainLoop(bool state);// DVAPI void enableFrameGrouping(bool on);// DVAPI bool isFrameGroupingEnabled();-// aggiungono (in coda) a set+// add (at the end) to setDVAPI void readDirectory(TFilePathSet &fpset, const QDir &dir,bool groupFrames = true);@@ -121,7 +119,7 @@ DVAPI void readDirectory_Dir_ReadExe(TFilePathSet &dst, const TFilePath &path);// return the folder item list which is readable and executable (only names)DVAPI void readDirectory_DirItems(QStringList &dst, const TFilePath &path);-// creano un set nuovo+// create a new setDVAPI TFilePathSet readDirectory(const TFilePath &path, bool groupFrames = true,bool onlyFiles = false,bool getHiddenFiles = false);@@ -148,8 +146,8 @@ DVAPI TFilePath getDllDir();/*!Returns the process id of the current process*/DVAPI int getProcessId();-// n.b. queste possono buttare eccezioni!-// mkdir crea anche il parent se non esiste+// note: these can throw exceptions!+// mkdir also creates the parent if it doesn't existDVAPI void mkDir(const TFilePath &path);DVAPI void rmDir(const TFilePath &path);DVAPI void rmDirTree(const TFilePath &path);@@ -167,8 +165,7 @@ DVAPI void moveFileToRecycleBin(const TFilePath &fp);DVAPI void copyFileOrLevel_throw(const TFilePath &dst, const TFilePath &src);DVAPI bool renameImageSequence(const TFilePathSet &files,- const TFilePath &levelName,- int prefixLength);+ const TFilePath &levelName, int prefixLength);DVAPI void renameFileOrLevel_throw(const TFilePath &dst, const TFilePath &src,bool renamePalette = false);DVAPI void removeFileOrLevel_throw(const TFilePath &fp);@@ -184,7 +181,7 @@ DVAPI bool hideFileOrLevel(const TFilePath &fp);DVAPI bool moveFileOrLevelToRecycleBin(const TFilePath &fp);DVAPI void sleep(TINT64 delay);-inline void sleep(int ms) { sleep((TINT64)ms); }+inline void sleep(int ms) { sleep(static_cast<TINT64>(ms)); }DVAPI TFilePathSet getDisks();@@ -208,7 +205,7 @@ DVAPI TINT64 getMemorySize(bool onlyPhysicalMemory);DVAPI bool memoryShortage();-/*! run di un extern viewer */+/*! run an external viewer */// DVAPI void showDocument(const TFilePath &dst);DVAPI int getProcessorCount();@@ -231,16 +228,16 @@ DVAPI long getCPUExtensions();/*! enables/disables the CPU extensions, if available*/// DVAPI void enableCPUExtensions(bool on);-// cosette da fare:+// things to do:-// un po' di studio sui file memory mapped+// some study on memory mapped files-// indagare+// investigateDVAPI std::iostream openTemporaryFile();-// un'altra idea e' avere un TQualcosaP che ritorna un UniqueFileName-// e che sul distruttore cancella il file+// another idea is to have a TQualcosaP that returns a UniqueFileName+// and on the destructor deletes the file-// pensare a:+// think about:// DVAPI void setFileProtection(const TFilePath &path, ???);void DVAPI outputDebug(std::string s);@@ -275,10 +272,10 @@ DVAPI TFilePath getUniqueFile(QString field = "");DVAPI bool isDLLBlackListed(QString dllFile);-}+} // namespace TSystem//-// Esempio di lettura di una directory:+// Example of reading a directory:// TFilePathSet dirContent = TSystem::readDirectory("C:\\temp");// for(TFilePathSet::Iterator it = dirContent.begin(); it != dirContent.end();// it++)