Skip to content

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

C

Modernize TFilePath and sanitize path handling

Anderson Prado2746ccb90750
diff --git a/toonz/sources/common/tsystem/tfilepath.cpp b/toonz/sources/common/tsystem/tfilepath.cpp
index 3103efbc0..e4e91d1a8 100644
--- a/toonz/sources/common/tsystem/tfilepath.cpp
+++ b/toonz/sources/common/tsystem/tfilepath.cpp
@@ -1,19 +1,19 @@
#ifdef _WIN32
-// #define UNICODE // per le funzioni di conversione da/a UNC
+// #define UNICODE // for UNC conversion functions
#include <windows.h>
#include <lm.h>
-const char slash = '\\';
-const char auxslash = '/';
-const char wslash = L'\\';
-const char wauxslash = L'/';
+const char slash = '\\';
+const char auxslash = '/';
+const wchar_t wslash = L'\\';
+const wchar_t wauxslash = L'/';
#else
-const char slash = '/';
-const char auxslash = '\\';
-const char wslash = '/';
-const char wauxslash = '\\';
+const char slash = '/';
+const char auxslash = '\\';
+const wchar_t wslash = L'/';
+const wchar_t wauxslash = L'\\';
#endif
//=============================================================================
@@ -27,7 +27,7 @@ const char wauxslash = '\\';
// QT
#include <QObject>
-#include <QRegExp>
+#include <QRegularExpression>
bool TFilePath::m_underscoreFormatAllowed = true;
@@ -71,9 +71,9 @@ bool isNumbers(std::wstring str, int fromSeg, int toSeg) {
return false;
}
- // Not the right format if we see too many letters.
- // At the time of this logic, we only expect 1 letter. Can expand to 2 or
- // more later, if we want.
+ // Not the right format if we see too many letters. At the time of this
+ // logic, we only expect 1 letter. Can expand to 2 or more later.
+
if (numLetters > 1) return false;
return true; // We're good!
@@ -87,43 +87,38 @@ bool checkForSeqNum(QString type) {
return false;
}
-bool parseFrame(const std::wstring &str, int &frame, QString &letter, int &padding) {
- if (str.empty())
- return false;
+bool parseFrame(const std::wstring &str, int &frame, QString &letter,
+ int &padding) {
+ if (str.empty()) return false;
int i = 0, number = 0;
- while(i < (int)str.size() && str[i] >= L'0' && str[i] <= L'9')
+ while (i < (int)str.size() && str[i] >= L'0' && str[i] <= L'9')
number = number * 10 + str[i++] - L'0';
int digits = i;
- wchar_t l = str[i] >= L'a' && str[i] <= L'z' ? str[i++]
- : str[i] >= L'A' && str[i] <= L'Z' ? str[i++]
- : L'\0';
- if (digits <= 0 || i < (int)str.size())
- return false;
+ wchar_t l = str[i] >= L'a' && str[i] <= L'z' ? str[i++]
+ : str[i] >= L'A' && str[i] <= L'Z' ? str[i++]
+ : L'\0';
+ if (digits <= 0 || i < (int)str.size()) return false;
- frame = number;
- letter = l ? QString(1, QChar(l)) : QString();
+ frame = number;
+ letter = l ? QString(1, QChar(l)) : QString();
padding = str[0] == L'0' ? digits : 0;
return true;
}
}; // namespace
-
TFrameId::TFrameId(const std::string &str, char s)
- : m_frame(EMPTY_FRAME), m_letter(), m_zeroPadding(4), m_startSeqInd(s)
-{
+ : m_frame(EMPTY_FRAME), m_letter(), m_zeroPadding(4), m_startSeqInd(s) {
if (str.empty()) return;
if (!parseFrame(to_wstring(str), m_frame, m_letter, m_zeroPadding))
m_frame = NO_FRAME;
}
TFrameId::TFrameId(const std::wstring &str, char s)
- : m_frame(EMPTY_FRAME), m_letter(), m_zeroPadding(4), m_startSeqInd(s)
-{
+ : m_frame(EMPTY_FRAME), m_letter(), m_zeroPadding(4), m_startSeqInd(s) {
if (str.empty()) return;
- if (!parseFrame(str, m_frame, m_letter, m_zeroPadding))
- m_frame = NO_FRAME;
+ if (!parseFrame(str, m_frame, m_letter, m_zeroPadding)) m_frame = NO_FRAME;
}
// TFrameId::operator string() const
@@ -182,9 +177,8 @@ inline bool isSlash(wchar_t c) { return c == wslash || c == wauxslash; }
//-----------------------------------------------------------------------------
-// cerca l'ultimo '/' o '\'. Se non c'e' ritorna -1
-// di modo che la sottostringa che parte da getLastSlash() + 1 e'
-// nome.frame.tipo
+// look for the last '/' or '\'. If not found return -1
+// so that the substring starting from getLastSlash() + 1 is name.frame.type
inline int getLastSlash(const std::wstring &path) {
int i;
for (i = path.length() - 1; i >= 0 && !isSlash(path[i]); i--) {
@@ -198,8 +192,8 @@ inline int getLastSlash(const std::wstring &path) {
void TFilePath::setPath(string path)
{
bool isUncName = false;
- // elimino i '//', './' e '/' finali; raddrizzo gli slash 'storti'.
- // se il path comincia con "<alpha>:" aggiungo uno slash
+ // remove '//', './' and trailing '/'; fix wrong slashes.
+ // if path starts with "<alpha>:" add a slash
int length =path.length();
int pos = 0;
if(path.length()>=2 && isalpha(path[0]) && path[1] == ':')
@@ -209,8 +203,8 @@ bool isUncName = false;
if(path.length()==2 || !isSlash(path[pos])) m_path.append(1,slash);
}
#ifdef _WIN32
- else //se si tratta di un path in formato UNC e' del tipo "\\\\MachineName"
- //RICONTROLLARE! SE SI HA IP ADDRESS FALLIVA!
+ else // if it's a UNC path it's like "\\\\MachineName"
+ // DOUBLE CHECK! IF WE HAVE IP ADDRESS IT FAILED!
if (path.length() >= 3 && path[0] == '\\' && path[1] == '\\' &&
(isalpha(path[2]) || isdigit(path[2])) )
{
@@ -245,18 +239,16 @@ bool isUncName = false;
m_path.append(1,path[pos]);
}
- // rimuovo l'eventuale '/' finale (a meno che m_path == "/" o m_path ==
-"<letter>:\"
- // oppure sia UNC (Windows only) )
+ // remove trailing '/' (unless m_path == "/" or m_path == "<letter>:\"
+ // or it's UNC (Windows only) )
if(!(m_path.length()==1 && m_path[0] == slash ||
m_path.length()==3 && isalpha(m_path[0]) && m_path[1] == ':' &&
m_path[2] == slash)
&& m_path.length()>1 && m_path[m_path.length()-1] == slash)
m_path.erase(m_path.length()-1, 1);
- if (isUncName && m_path.find_last_of('\\') == 1) // e' indicato solo il nome
-della macchina...
- m_path.append(1, slash);
+ if (isUncName && m_path.find_last_of('\\') == 1) // only machine name is
+specified... m_path.append(1, slash);
}
*/
@@ -279,8 +271,8 @@ void append(string &out, wchar_t c)
void TFilePath::setPath(std::wstring path) {
bool isUncName = false;
- // elimino i '//', './' e '/' finali; raddrizzo gli slash 'storti'.
- // se il path comincia con "<alpha>:" aggiungo uno slash
+ // remove '//', './' and trailing '/'; fix wrong slashes.
+ // if path starts with "<alpha>:" add a slash
int length = path.length();
int pos = 0;
@@ -291,7 +283,7 @@ void TFilePath::setPath(std::wstring path) {
pos = 2;
if (path.length() == 2 || !isSlash(path[pos])) m_path.append(1, wslash);
}
- // se si tratta di un path in formato UNC e' del tipo "\\\\MachineName"
+ // if it's a UNC path it's like "\\\\MachineName"
else if ((path.length() >= 3 && path[0] == L'\\' && path[1] == L'\\' &&
iswalnum(path[2])) ||
(path.length() >= 3 && path[0] == L'/' && path[1] == L'/' &&
@@ -316,7 +308,7 @@ void TFilePath::setPath(std::wstring path) {
int firstSlashPos = pos;
do pos++;
while (pos < length && isSlash(path[pos]));
- if (firstSlashPos == 0 && pos == 4) // Caso "\\\\MachineName"
+ if (firstSlashPos == 0 && pos == 4) // Case "\\\\MachineName"
m_path.append(2, wslash);
else
m_path.append(1, wslash);
@@ -325,18 +317,17 @@ void TFilePath::setPath(std::wstring path) {
m_path.append(1, path[pos]);
}
- // rimuovo l'eventuale '/' finale (a meno che m_path == "/" o m_path ==
- // "<letter>:\"
- // oppure sia UNC (Windows only) )
+ // remove trailing '/' (unless m_path == "/" or m_path == "<letter>:\"
+ // or it's UNC (Windows only) )
if (!((m_path.length() == 1 && m_path[0] == wslash) ||
(m_path.length() == 3 && iswalpha(m_path[0]) && m_path[1] == L':' &&
m_path[2] == wslash)) &&
(m_path.length() > 1 && m_path[m_path.length() - 1] == wslash))
m_path.erase(m_path.length() - 1, 1);
- if (isUncName && !(m_path.find_last_of(L'\\') > 1 ||
- m_path.find_last_of(L'/') >
- 1)) // e' indicato solo il nome della macchina...
+ if (isUncName &&
+ !(m_path.find_last_of(L'\\') > 1 ||
+ m_path.find_last_of(L'/') > 1)) // only machine name is specified...
m_path.append(1, wslash);
}
@@ -391,8 +382,8 @@ bool TFilePath::operator<(const TFilePath &fp) const {
while (i2 != -1 || j2 != -1) {
iName = (i2 != -1) ? m_path.substr(i1, i2 - i1) : m_path;
jName = (j2 != -1) ? fp.m_path.substr(j1, j2 - j1) : fp.m_path;
-// se le due parti di path, conpresi tra slash sono uguali
-// itero il processo di confronto altrimenti ritorno
+// if the two path parts, between slashes, are equal
+// iterate the comparison process otherwise return
#ifdef _WIN32
char differ;
differ = _wcsicmp(iName.c_str(), jName.c_str());
@@ -439,14 +430,23 @@ if(i==wstring::npos) {ka = a; a = L"";}
//-----------------------------------------------------------------------------
TFilePath &TFilePath::operator+=(const TFilePath &fp) {
- assert(!fp.isAbsolute());
+ if (fp.isAbsolute()) {
+ // Log error or handle appropriately
+ qWarning("Cannot append absolute path to another path");
+ return *this;
+ }
+
if (fp.isEmpty())
return *this;
else if (isEmpty()) {
*this = fp;
return *this;
} else if (m_path.length() != 1 || m_path[0] != slash) {
- assert(!m_path.empty());
+ if (m_path.empty()) {
+ // Handle empty path case
+ *this = fp;
+ return *this;
+ }
if (!isSlash(m_path[m_path.length() - 1])) m_path.append(1, wslash);
m_path += fp.m_path;
return *this;
@@ -570,8 +570,8 @@ bool TFilePath::isRoot() const {
//-----------------------------------------------------------------------------
-// ritorna ""(niente tipo, niente punto), "." (file con tipo) o ".." (file con
-// tipo e frame)
+// returns "" (no type, no dot), "." (file with type) or ".." (file with type
+// and frame)
std::string TFilePath::getDots() const {
if (!TFilePath::m_useStandard) {
TFilePathInfo info = analyzePath();
@@ -586,7 +586,7 @@ std::string TFilePath::getDots() const {
if (isFfmpegType()) return ".";
int i = getLastSlash(m_path);
std::wstring str = m_path.substr(i + 1);
- // potrei anche avere a.b.c.d dove d e' l'estensione
+ // I could also have a.b.c.d where d is the extension
i = str.rfind(L".");
if (i == (int)std::wstring::npos || str == L"..") return "";
@@ -610,7 +610,7 @@ QChar TFilePath::getSepChar() const {
if (isFfmpegType()) return QChar();
int i = getLastSlash(m_path);
std::wstring str = m_path.substr(i + 1);
- // potrei anche avere a.b.c.d dove d e' l'estensione
+ // I could also have a.b.c.d where d is the extension
i = str.rfind(L".");
if (i == (int)std::wstring::npos || str == L"..") return QChar();
@@ -634,7 +634,7 @@ QChar TFilePath::getSepChar() const {
//-----------------------------------------------------------------------------
std::string TFilePath::getDottedType()
- const // ritorna l'estensione con PUNTO (se c'e')
+ const // returns extension with DOT (if present)
{
if (!TFilePath::m_useStandard) {
QString ext = analyzePath().extension;
@@ -652,8 +652,7 @@ std::string TFilePath::getDottedType()
//-----------------------------------------------------------------------------
-std::string TFilePath::getUndottedType()
- const // ritorna l'estensione senza PUNTO
+std::string TFilePath::getUndottedType() const // returns extension without DOT
{
if (!TFilePath::m_useStandard) {
QString ext = analyzePath().extension;
@@ -663,7 +662,6 @@ std::string TFilePath::getUndottedType()
return ext.toLower().toStdString();
}
- //-----
size_t i = getLastSlash(m_path);
std::wstring str = m_path.substr(i + 1);
i = str.rfind(L".");
@@ -678,10 +676,9 @@ std::wstring TFilePath::getWideName() const // noDot! noSlash!
if (!TFilePath::m_useStandard) {
return analyzePath().levelName.toStdWString();
}
- //-----
QString type = QString::fromStdString(getType()).toLower();
- int i = getLastSlash(m_path); // cerco l'ultimo slash
+ int i = getLastSlash(m_path); // look for the last slash
std::wstring str = m_path.substr(i + 1);
i = str.rfind(L".");
if (i == (int)std::wstring::npos) return str;
@@ -705,13 +702,13 @@ std::string TFilePath::getName() const // noDot! noSlash!
}
//-----------------------------------------------------------------------------
-// es. TFilePath("/pippo/pluto.0001.gif").getLevelName() == "pluto..gif"
+// e.g. TFilePath("/pippo/pluto.0001.gif").getLevelName() == "pluto..gif"
std::string TFilePath::getLevelName() const {
return ::to_string(getLevelNameW());
}
//-----------------------------------------------------------------------------
-// es. TFilePath("/pippo/pluto.0001.gif").getLevelName() == "pluto..gif"
+// e.g. TFilePath("/pippo/pluto.0001.gif").getLevelName() == "pluto..gif"
std::wstring TFilePath::getLevelNameW() const {
if (!TFilePath::m_useStandard) {
@@ -722,10 +719,9 @@ std::wstring TFilePath::getLevelNameW() const {
name += "." + info.extension;
return name.toStdWString();
}
- //-----
- int i = getLastSlash(m_path); // cerco l'ultimo slash
- std::wstring str = m_path.substr(i + 1); // str e' m_path senza directory
+ int i = getLastSlash(m_path); // look for the last slash
+ std::wstring str = m_path.substr(i + 1); // str is m_path without directory
QString type = QString::fromStdString(getType()).toLower();
if (isFfmpegType()) return str;
int j = str.rfind(L"."); // str[j..] = ".type"
@@ -734,7 +730,7 @@ std::wstring TFilePath::getLevelNameW() const {
if (i == (int)std::wstring::npos && m_underscoreFormatAllowed)
i = str.substr(0, j).rfind(L'_');
- if (j == i || j - i == 1) // prova.tif o prova..tif
+ if (j == i || j - i == 1) // prova.tif or prova..tif
return str;
if (!checkForSeqNum(type) || !isNumbers(str, i, j) ||
@@ -748,7 +744,7 @@ std::wstring TFilePath::getLevelNameW() const {
TFilePath TFilePath::getParentDir() const // noSlash!
{
- int i = getLastSlash(m_path); // cerco l'ultimo slash
+ int i = getLastSlash(m_path); // look for the last slash
if (i < 0) {
if (m_path.length() >= 2 &&
((L'a' <= m_path[0] && m_path[0] <= L'z') ||
@@ -769,15 +765,12 @@ bool TFilePath::isLevelName() const {
if (!TFilePath::m_useStandard) {
return analyzePath().fId.getNumber() == TFrameId::EMPTY_FRAME;
}
- //-----
QString type = QString::fromStdString(getType()).toLower();
if (isFfmpegType() || !checkForSeqNum(type)) return false;
try {
return getFrame() == TFrameId(TFrameId::EMPTY_FRAME);
- }
-
- catch (...) {
+ } catch (...) {
return false;
}
}
@@ -788,8 +781,8 @@ TFrameId TFilePath::getFrame() const {
}
//-----
- int i = getLastSlash(m_path); // cerco l'ultimo slash
- std::wstring str = m_path.substr(i + 1); // str e' il path senza parentdir
+ int i = getLastSlash(m_path); // look for the last slash
+ std::wstring str = m_path.substr(i + 1); // str is the path without parentdir
QString type = QString::fromStdString(getType()).toLower();
i = str.rfind(L'.');
if (i == (int)std::wstring::npos || str == L"." || str == L"..")
@@ -808,7 +801,7 @@ TFrameId TFilePath::getFrame() const {
if (!checkForSeqNum(type) || !isNumbers(str, j, i))
return TFrameId(TFrameId::NO_FRAME);
- return TFrameId(str.substr(j+1, i-j-1), str[j]);
+ return TFrameId(str.substr(j + 1, i - j - 1), str[j]);
}
//-----------------------------------------------------------------------------
@@ -827,12 +820,16 @@ bool TFilePath::isUneditable() const {
//-----------------------------------------------------------------------------
TFilePath TFilePath::withType(const std::string &type) const {
- assert(type.length() < 2 || type.substr(0, 2) != "..");
- int i = getLastSlash(m_path); // cerco l'ultimo slash
- std::wstring str = m_path.substr(i + 1); // str e' il path senza parentdir
+ if (type.length() >= 2 && type.substr(0, 2) == "..") {
+ qWarning("Invalid type: %s", type.c_str());
+ return *this;
+ }
+
+ int i = getLastSlash(m_path); // look for the last slash
+ std::wstring str = m_path.substr(i + 1); // str is the path without parentdir
int j = str.rfind(L'.');
if (j == (int)std::wstring::npos || str == L"..")
- // il path originale non ha tipo
+ // the original path has no type
{
if (type == "")
return *this;
@@ -841,7 +838,7 @@ TFilePath TFilePath::withType(const std::string &type) const {
else
return TFilePath(m_path + ::to_wstring("." + type));
} else
- // il path originale ha gia' il tipo
+ // the original path already has a type
{
if (type == "")
return TFilePath(m_path.substr(0, i + j + 1));
@@ -875,8 +872,8 @@ TFilePath TFilePath::withName(const std::wstring &name) const {
return TFilePath(ret);
}
- int i = getLastSlash(m_path); // cerco l'ultimo slash
- std::wstring str = m_path.substr(i + 1); // str e' il path senza parentdir
+ int i = getLastSlash(m_path); // look for the last slash
+ std::wstring str = m_path.substr(i + 1); // str is the path without parentdir
QString type = QString::fromStdString(getType()).toLower();
int j;
j = str.rfind(L'.');
@@ -906,7 +903,7 @@ TFilePath TFilePath::withName(const std::wstring &name) const {
//-----------------------------------------------------------------------------
TFilePath TFilePath::withParentDir(const TFilePath &dir) const {
- int i = getLastSlash(m_path); // cerco l'ultimo slash
+ int i = getLastSlash(m_path); // look for the last slash
return dir + TFilePath(m_path.substr(i + 1));
}
@@ -941,10 +938,14 @@ TFilePath TFilePath::withFrame(const TFrameId &frame,
//-----------------
const std::wstring dot = L".", dotDot = L"..";
- int i = getLastSlash(m_path); // cerco l'ultimo slash
- std::wstring str = m_path.substr(i + 1); // str e' il path senza parentdir
+ int i = getLastSlash(m_path); // look for the last slash
+ std::wstring str = m_path.substr(i + 1); // str is the path without parentdir
QString type = QString::fromStdString(getType()).toLower();
- assert(str != dot && str != dotDot);
+ if (str == dot || str == dotDot) {
+ qWarning("Invalid path for frame operation: %ls", str.c_str());
+ return *this;
+ }
+
int j = str.rfind(L'.');
const char *ch = ".";
// Override format input because it may be wrong.
@@ -1006,21 +1007,21 @@ TFilePath TFilePath::withFrame(const TFrameId &frame,
bool TFilePath::isAncestorOf(const TFilePath &possibleDescendent) const {
size_t len = m_path.length();
if (len == 0) {
- // il punto e' antenato di tutti i path non assoluti
+ // the dot is ancestor of all non-absolute paths
return !possibleDescendent.isAbsolute();
}
- // un path e' antenato di se stesso
+ // a path is ancestor of itself
if (m_path == possibleDescendent.m_path) return true;
int possibleDescendentLen = possibleDescendent.m_path.length();
- // altrimenti l'antenato deve essere piu' corto
+ // otherwise the ancestor must be shorter
if ((int)len >= possibleDescendentLen) return false;
- // e deve coincidere con la prima parte del discendente
+ // and must match the first part of the descendant
if (toLower(m_path) != toLower(possibleDescendent.m_path.substr(0, len)))
return false;
- // se l'antenato non finisce con slash ci deve essere uno slash nel
- // discendente, subito dopo
+ // if the ancestor does not end with slash there must be a slash in the
+ // descendant, right after
if (m_path[len - 1] != wslash && possibleDescendent.m_path[len] != wslash)
return false;
@@ -1091,7 +1092,17 @@ QString TFilePath::fidRegExpStr() {
//-----------------------------------------------------------------------------
TFilePath::TFilePathInfo TFilePath::analyzePath() const {
- assert(!TFilePath::m_useStandard);
+ // analyzePath should only be called when m_useStandard is false
+ if (TFilePath::m_useStandard) {
+#ifdef QT_DEBUG
+ qWarning(
+ "analyzePath called with m_useStandard enabled - returning empty "
+ "TFilePathInfo");
+#endif
+ // Return empty structure since standard path analysis should be used
+ // instead
+ return TFilePathInfo();
+ }
TFilePath::TFilePathInfo info;
@@ -1112,73 +1123,54 @@ TFilePath::TFilePathInfo TFilePath::analyzePath() const {
// Extension: letters other than "._" or \/:,;*?"<>| or " "(space)
const QString extensionRegExp("([^\\._ \\\\/:,;*?\"<>|]+)");
- // ignore frame numbers on non-sequential (i.e. movie) extension case :
- // hoge_0001.mp4
- // QRegExp rx_mf("^" + levelNameRegExp + "\\." + extensionRegExp + "$");
- // if (rx_mf.indexIn(levelName) != -1) {
- // QString ext = rx_mf.cap(2);
- // if (!checkForSeqNum(ext)) {
- // info.levelName = rx_mf.cap(1);
- // info.sepChar = QChar();
- // info.fId = TFrameId(TFrameId::NO_FRAME, 0, 0); // initialize with NO_PAD
- // info.extension = ext;
- // return info;
- // }
- //}
-
- // hogehoge.0001a.jpg
- // empty frame case : hogehoge..jpg
- // empty level name case : ..jpg .0001a.jpg
- QRegExp rx("^(?:" + levelNameRegExp + ")?" + sepCharRegExp +
- "(?:" + fIdRegExp + ")?" + "\\." + extensionRegExp + "$");
- if (rx.indexIn(fileName) != -1) {
- assert(rx.captureCount() == 5);
- info.levelName = rx.cap(1);
- info.sepChar = rx.cap(2)[0];
- info.extension = rx.cap(5);
- // ignore frame numbers on non-sequential (i.e. movie) extension case :
- // hoge_0001.mp4
+ // Modern QRegularExpression implementation
+ QRegularExpression rx("^(?:" + levelNameRegExp + ")?" + sepCharRegExp +
+ "(?:" + fIdRegExp + ")?" + "\\." + extensionRegExp +
+ "$");
+ QRegularExpressionMatch match = rx.match(fileName);
+
+ if (match.hasMatch()) {
+ info.levelName = match.captured(1);
+ info.sepChar =
+ match.captured(2).isEmpty() ? QChar() : match.captured(2).at(0);
+ info.extension = match.captured(5);
+
+ // ignore frame numbers on non-sequential (i.e. movie) extension case
if (!checkForSeqNum(info.extension)) {
- info.levelName = rx.cap(1) + rx.cap(2);
- if (!rx.cap(3).isEmpty()) info.levelName += rx.cap(3);
- if (!rx.cap(4).isEmpty()) info.levelName += rx.cap(4);
+ info.levelName = match.captured(1) + match.captured(2);
+ if (!match.captured(3).isEmpty()) info.levelName += match.captured(3);
+ if (!match.captured(4).isEmpty()) info.levelName += match.captured(4);
info.sepChar = QChar();
info.fId = TFrameId(TFrameId::NO_FRAME, 0, 0); // initialize with NO_PAD
} else {
- QString numberStr = rx.cap(3);
- if (numberStr.isEmpty()) // empty frame case : hogehoge..jpg
+ QString numberStr = match.captured(3);
+ if (numberStr.isEmpty()) { // empty frame case : hogehoge..jpg
info.fId =
TFrameId(TFrameId::EMPTY_FRAME, 0, 4, info.sepChar.toLatin1());
- else {
+ } else {
int number = numberStr.toInt();
int padding = 0;
- if (numberStr[0] == "0") // with padding
- padding = numberStr.count();
+ if (!numberStr.isEmpty() && numberStr[0] == '0') { // with padding
+ padding = numberStr.length();
+ }
QString suffix;
- if (!rx.cap(4).isEmpty()) suffix = rx.cap(4);
+ if (!match.captured(4).isEmpty()) suffix = match.captured(4);
info.fId = TFrameId(number, suffix, padding, info.sepChar.toLatin1());
}
}
return info;
}
- // QRegExp rx_ef("^" + levelNameRegExp + sepCharRegExp + "\\." +
- // extensionRegExp + "$"); if (rx_ef.indexIn(levelName) != -1) {
- // info.levelName = rx_ef.cap(1);
- // info.sepChar = rx_ef.cap(2)[0];
- // info.fId = TFrameId(TFrameId::EMPTY_FRAME, 0, 4, info.sepChar.toLatin1());
- // info.extension = rx_ef.cap(3);
- // return info;
- //}
-
// no frame case : hogehoge.jpg
// no level name case : .jpg
- QRegExp rx_nf("^(?:" + levelNameRegExp + ")?\\." + extensionRegExp + "$");
- if (rx_nf.indexIn(fileName) != -1) {
- if (!rx_nf.cap(1).isEmpty()) info.levelName = rx_nf.cap(1);
+ QRegularExpression rx_nf("^(?:" + levelNameRegExp + ")?\\." +
+ extensionRegExp + "$");
+ match = rx_nf.match(fileName);
+ if (match.hasMatch()) {
+ if (!match.captured(1).isEmpty()) info.levelName = match.captured(1);
info.sepChar = QChar();
info.fId = TFrameId(TFrameId::NO_FRAME, 0, 0); // initialize with NO_PAD
- info.extension = rx_nf.cap(2);
+ info.extension = match.captured(2);
return info;
}
diff --git a/toonz/sources/include/tfilepath.h b/toonz/sources/include/tfilepath.h
index f07b3ce7e..ab98160f4 100644
--- a/toonz/sources/include/tfilepath.h
+++ b/toonz/sources/include/tfilepath.h
@@ -20,23 +20,23 @@
//-----------------------------------------------------------------------------
/*
- This is an example of how to use TFilePath and TFrameId classes.
+ Example of using TFilePath and TFrameId classes.
*/
//!\include frameid_ex.cpp
-//! The class TFrameId describes a frame identified by an integer number of four
-//! figures and, in case, by a character (necessary for added frames)
+//! The TFrameId class describes a frame identified by a four-digit integer and
+//! optionally by a character (necessary for appended frames)
class DVAPI TFrameId {
int m_frame;
- QString m_letter; // serve per i frame "aggiunti" del tipo pippo.0001a.tzp =>
- // f=1 c='a'
+ QString
+ m_letter; // Used for "appended" frames like pippo.0001a.tzp => f=1 c='a'
int m_zeroPadding;
char m_startSeqInd;
public:
enum {
- EMPTY_FRAME = -1, // es. pippo..tif
- NO_FRAME = -2 // es. pippo.tif
+ EMPTY_FRAME = -1, // e.g., pippo..tif
+ NO_FRAME = -2 // e.g., pippo.tif
};
enum FrameFormat {
@@ -53,7 +53,7 @@ public:
: m_frame(f), m_letter(""), m_zeroPadding(4), m_startSeqInd('.') {}
TFrameId(int f, char c, int p = 4, char s = '.')
: m_frame(f), m_zeroPadding(p), m_startSeqInd(s) {
- m_letter = (c == '\0') ? "" : QString(c);
+ m_letter = (c == '\0') ? QString() : QString(1, QChar(c));
}
TFrameId(int f, QString str, int p = 4, char s = '.')
: m_frame(f), m_letter(str), m_zeroPadding(p), m_startSeqInd(s) {}
@@ -129,14 +129,13 @@ inline std::ostream &operator<<(std::ostream &out, const TFrameId &f) {
//-----------------------------------------------------------------------------
-/*!The class TFilePath defines a file path.Its constructor creates a string
- according
- to the platform and to certain rules.For more information see the
+/*!The TFilePath class defines a file path. Its constructor creates a string
+ according to the platform and specific rules. For more information see the
constructor.*/
class DVAPI TFilePath {
static bool m_underscoreFormatAllowed;
- // specifies file path condition for sequential image for each project.
+ // Specifies file path condition for sequential images per project.
// See filepathproperties.h
static bool m_useStandard;
static bool m_acceptNonAlphabetSuffix;
@@ -155,15 +154,14 @@ class DVAPI TFilePath {
void setPath(std::wstring path);
public:
- /*! this static method allows correct reading of levels in the form
- * pippo_0001.tif (represented always as pippo..tif) */
+ /*! This static method allows correct reading of levels in the form
+ * pippo_0001.tif (always represented as pippo..tif) */
static void setUnderscoreFormatAllowed(bool state) {
m_underscoreFormatAllowed = state;
}
- // called from TProjectManager::getCurrentProject() and
- // ProjectPopup::updateProjectFromFields
- // returns true if something changed
+ // Called from TProjectManager::getCurrentProject() and
+ // ProjectPopup::updateProjectFromFields Returns true if something changed
static bool setFilePathProperties(bool useStandard, bool acceptNonAlphaSuffix,
int letterCountForSuffix) {
if (m_useStandard == useStandard &&
@@ -178,11 +176,10 @@ public:
static bool useStandard() { return m_useStandard; }
static QString fidRegExpStr();
- /*!This constructor creates a string removing redundances ('//', './',etc.)
-and final slashes,
- correcting (redressing) the "twisted" slashes.
- Note that if the current directory is ".", it becomes "".
-If the path is "<alpha>:" a slash will be added*/
+ /*!This constructor creates a string by removing redundancies ('//', './',
+ etc.) and trailing slashes, correcting (redressing) "twisted" slashes.
+ Note: if the current directory is ".", it becomes "".
+ If the path is "<alpha>:", a slash will be added*/
explicit TFilePath(const char *path = "");
explicit TFilePath(const std::string &path);
@@ -206,43 +203,44 @@ If the path is "<alpha>:" a slash will be added*/
QString getQString() const;
/*!Returns:
- a. "" if there is no filename extension
- b. "." if there is a filename extension but no frame
- c.".." if there are both filename extension and frame */
- std::string getDots() const; // ritorna ""(no estensione), "."(estensione, no
- // frame) o ".."(estensione e frame)
-
- /*!Returns the filename extension, including leading period (.).
- Returns "" if there is no filename extension.*/
- std::string getDottedType() const; // ritorna l'estensione con il PUNTO (se
- // non c'e' estensione ritorna "")
-
- /*!Returns the filename extension, excluding leading period (.).
- Returns "" if there is no filename extension.*/
- std::string getUndottedType() const; // ritorna l'estensione senza PUNTO
-
- /*!It is equal to getUndottedType():
- Returns the filename extension, excluding leading period (.).
- Returns "" if there is no filename extension.*/
+ a. "" if there is no file extension
+ b. "." if there is a file extension but no frame
+ c.".." if there are both a file extension and a frame */
+ std::string getDots() const; // Returns "" (no extension), "." (extension, no
+ // frame) or ".." (extension and frame)
+
+ /*!Returns the file extension, including the leading period (.).
+ Returns "" if there is no file extension.*/
+ std::string getDottedType()
+ const; // Returns the extension WITH the DOT (if no extension returns "")
+
+ /*!Returns the file extension, excluding the leading period (.).
+ Returns "" if there is no file extension.*/
+ std::string getUndottedType() const; // Returns the extension WITHOUT the DOT
+
+ /*!Same as getUndottedType():
+ Returns the file extension, excluding the leading period (.).
+ Returns "" if there is no file extension.*/
std::string getType() const {
return getUndottedType();
- } // ritorna l'estensione SENZA PUNTO
+ } // Returns the extension WITHOUT the DOT
/*!Returns the base filename (no extension, no dots, no slash)*/
std::string getName() const; // noDot! noSlash!
std::wstring getWideName() const; // noDot! noSlash!
- /*!Returns the filename (with extension, excluding in case the frame number).
- ex.: TFilePath("/pippo/pluto.0001.gif").getLevelName() == "pluto..gif"
+ /*!Returns the filename (with extension, excluding the frame number if
+ present). ex.: TFilePath("/pippo/pluto.0001.gif").getLevelName() ==
+ "pluto..gif"
*/
std::string getLevelName()
- const; // es. TFilePath("/pippo/pluto.0001.gif").getLevelName() ==
+ const; // e.g., TFilePath("/pippo/pluto.0001.gif").getLevelName() ==
// "pluto..gif"
std::wstring getLevelNameW()
- const; // es. TFilePath("/pippo/pluto.0001.gif").getLevelName() ==
+ const; // e.g., TFilePath("/pippo/pluto.0001.gif").getLevelName() ==
// "pluto..gif"
- /*!Returns the parent directory excluding the eventual final slash.*/
+ /*!Returns the parent directory excluding any trailing slash.*/
TFilePath getParentDir() const; // noSlash!;
TFrameId getFrame() const;
@@ -254,25 +252,24 @@ If the path is "<alpha>:" a slash will be added*/
bool isRoot() const;
bool isEmpty() const { return m_path == L""; }
- /*!Return a TFilePath with extension type.
-type is a string that indicate the filename extension(ex:. bmp or .bmp)*/
+ /*!Returns a TFilePath with the specified extension type.
+type is a string indicating the file extension (e.g., .bmp or bmp)*/
TFilePath withType(const std::string &type) const;
- /*!Return a TFilePath with filename "name".*/
+ /*!Returns a TFilePath with filename "name".*/
TFilePath withName(const std::string &name) const;
- /*!Return a TFilePath with filename "name". Unicode*/
+ /*!Returns a TFilePath with filename "name". Unicode*/
TFilePath withName(const std::wstring &name) const;
- /*!Return a TFilePath with parent directory "dir".*/
+ /*!Returns a TFilePath with parent directory "dir".*/
TFilePath withParentDir(const TFilePath &dir) const;
- /*!Return a TFilePath without parent directory */
+ /*!Returns a TFilePath without a parent directory */
TFilePath withoutParentDir() const { return withParentDir(TFilePath()); }
- /*!Return a TFilePath with frame "frame".*/
+ /*!Returns a TFilePath with frame "frame".*/
TFilePath withFrame(
const TFrameId &frame,
TFrameId::FrameFormat format = TFrameId::USE_CURRENT_FORMAT) const;
- /*!Return a TFilePath with a frame identified by an integer number "f".*/
+ /*!Returns a TFilePath with a frame identified by an integer "f".*/
TFilePath withFrame(int f) const { return withFrame(TFrameId(f)); }
- /*!Return a TFilePath with a frame identified by an integer and by a
- * character*/
+ /*!Returns a TFilePath with a frame identified by an integer and a character*/
TFilePath withFrame(int f, char letter) const {
return withFrame(TFrameId(f, letter));
}
@@ -303,12 +300,12 @@ type is a string that indicate the filename extension(ex:. bmp or .bmp)*/
bool isAncestorOf(const TFilePath &) const;
TFilePath operator-(
- const TFilePath &fp) const; // TFilePath("/a/b/c.txt")-TFilePath("/a/")
+ const TFilePath &fp) const; // TFilePath("/a/b/c.txt") - TFilePath("/a/")
// == TFilePath("b/c.txt");
- // se fp.isAncestorOf(this) == false ritorna this
+ // If fp.isAncestorOf(this) == false, returns this
bool match(const TFilePath &fp)
- const; // sono uguali a meno del numero di digits del frame
+ const; // They are equal except for the number of frame digits
// '/a/b/c.txt' => head='a' tail='b/c.txt'
void split(std::wstring &head, TFilePath &tail) const;