Krita is a free and open source cross-platform application that offers an end-to-end solution for creating digital art files from scratch built on the KDE and Qt frameworks.
C++
/*
* SPDX-FileCopyrightText: 2019 Dmitry Kazakov <[email protected]>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#include "KisFileUtils.h"
#include <QString>
#include <QFileInfo>
#include <QDir>
#include <QRegularExpression>
#include <KisPortingUtils.h>
namespace KritaUtils {
QString resolveAbsoluteFilePath(const QString &baseDir, const QString &fileName)
{
if (QFileInfo(fileName).isAbsolute()) {
return fileName;
}
QFileInfo fallbackBaseDirInfo(baseDir);
return QFileInfo(QDir(fallbackBaseDirInfo.isDir() ?
fallbackBaseDirInfo.absoluteFilePath() :
fallbackBaseDirInfo.absolutePath()),
fileName).absoluteFilePath();
}
QString deduplicateFileName(const QString &fileName,
const QString &separator,
std::function<bool(QString)> fileAllowedCallback)
{
const QFileInfo fileInfo(fileName);
int counter = 0;
QString proposedFileName = fileInfo.fileName();
QString baseName = fileInfo.baseName();
QString completeSuffix = fileInfo.completeSuffix();
/**
* Search for the separator around the leftmost dot in the filename
* and try to reuse its counter.
*
* The design choice is that there cannot be any dots to the left
* from the separator. Separator itself can have dots, but it cannot
* be a part of the file extension.
*/
QRegularExpression rex(QString("^([^.]+)%1\\d+(\\.(.+))?$").arg(separator));
auto match = rex.match(proposedFileName);
if (match.hasMatch()) {
using KisPortingUtils::stringRemoveFirst;
baseName = match.captured(1);
completeSuffix = stringRemoveFirst(match.captured(2));
}
while (!fileAllowedCallback(proposedFileName)) {
QStringList fileParts = {baseName, separator, QString::number(counter++)};
if (!completeSuffix.isEmpty()) {
fileParts += ".";
fileParts += completeSuffix;
}
proposedFileName = fileParts.join("");
}
return proposedFileName;
}
bool isSubPath(const QString &baseDir, const QString &targetPath)
{
auto normalize = [](const QString &path) -> QString {
QFileInfo info(path);
QString canonical = info.canonicalFilePath();
// if path exists, use canonicalFilePath (which will handle symlinks),
// if not, generate a normalized version of the path using
// QDir::cleanPath, which doesn't require the path to be a real one.
return canonical.isEmpty() ? QDir::cleanPath(info.absoluteFilePath()) : canonical;
};
const QString cleanBase = normalize(baseDir);
const QString cleanTarget = normalize(targetPath);
const QString rel = QDir(cleanBase).relativeFilePath(cleanTarget);
return !rel.isEmpty() && rel != "." && !rel.startsWith("..") && !QDir::isAbsolutePath(rel);
}
}