From 0975e6599597998bffaadd9432c8fe58058c264b Mon Sep 17 00:00:00 2001 From: Phil Hoffmann Date: Mon, 6 Nov 2023 11:14:39 +0100 Subject: [PATCH] Fixed lots of minor code smells --- app/logger.cpp | 10 +- app/logger.h | 6 +- app/ui/FileDialog/filedialogbackend.cpp | 4 +- app/ui/FileDialog/filedialogbackend.h | 2 +- app/ui/tools/generators/NameGenerator.qml | 4 +- src/addons/addonrepositorymanager.cpp | 23 ++-- src/common/models/customobjectlistmodel.cpp | 8 +- src/common/models/customobjectlistmodel.h | 2 +- src/common/models/customsharedptrlistmodel.h | 6 +- src/common/models/treeitem.cpp | 3 +- src/common/settings/quicksettingsmanager.cpp | 2 +- src/common/settings/quicksettingsmanager.h | 2 +- src/common/settings/settingsmanager.cpp | 24 ++--- src/common/utils/fileutils.cpp | 6 +- src/common/utils/stringutils.cpp | 4 +- src/common/utils/utils.h | 2 +- src/filesystem/cache/filecache.cpp | 2 +- src/filesystem/cache/filecache.h | 2 +- src/filesystem/fileaccess.h | 1 + src/filesystem/fileaccesslocal.cpp | 27 +++-- src/filesystem/fileaccesslocal.h | 2 + src/filesystem/fileaccessnextcloud.cpp | 26 ++--- src/filesystem/fileaccessnextcloud.h | 6 +- src/filesystem/multigethelper.h | 6 +- src/filesystem/results/filecheckresult.cpp | 2 +- src/filesystem/results/filecheckresult.h | 2 +- src/filesystem/results/filedataresult.cpp | 2 +- src/filesystem/results/filedataresult.h | 10 +- src/filesystem/results/filelistresult.h | 5 +- src/filesystem/results/filemulticheckresult.h | 12 +-- src/filesystem/results/fileresult.cpp | 2 +- src/filesystem/results/fileresult.h | 2 +- src/messages/messagemanager.cpp | 3 +- src/resources/notes/style.css | 3 +- src/services/nextcloud/nextcloud.cpp | 10 +- src/services/nextcloud/nextcloud.h | 2 +- src/services/rest/restrequest.h | 3 - src/services/rest/restserviceconnector.cpp | 23 ++-- src/services/rest/restserviceconnector.h | 8 +- src/services/spotify/api/playerapi.cpp | 10 +- src/services/spotify/api/playerapi.h | 4 +- src/services/spotify/api/playlistsapi.cpp | 6 +- src/services/spotify/api/tracksapi.cpp | 4 +- .../abstractspotifyclientcontroller.cpp | 4 +- .../spotify/clients/librespotcontroller.cpp | 2 +- src/services/spotify/spotify.cpp | 6 +- src/tools/audio/audiosaveload.cpp | 21 ++-- src/tools/audio/audiosaveload.h | 16 ++- src/tools/audio/audiotool.cpp | 42 +++----- src/tools/audio/audiotool.h | 18 ++-- src/tools/audio/editor/audioeditor.cpp | 100 ++++++++---------- src/tools/audio/editor/audioeditor.h | 14 +-- .../audio/editor/audioeditorfilebrowser.cpp | 24 ++--- .../audio/editor/audioeditorfilebrowser.h | 6 +- src/tools/audio/editor/audioexporter.cpp | 23 ++-- src/tools/audio/editor/audioexporter.h | 10 +- .../audio/editor/unsplash/unsplashimage.cpp | 6 +- .../audio/editor/unsplash/unsplashimage.h | 4 +- .../audio/editor/unsplash/unsplashparser.cpp | 10 +- .../audio/editor/unsplash/unsplashparser.h | 2 +- src/tools/audio/metadata/metadatareader.cpp | 32 +++--- src/tools/audio/mpris/mprismanager.cpp | 2 +- src/tools/audio/mpris/mprismanager.h | 2 +- src/tools/audio/mpris/mprisplayeradaptor.h | 4 +- .../audio/players/bufferedaudioplayer.cpp | 4 +- src/tools/audio/players/bufferedaudioplayer.h | 6 +- src/tools/audio/players/musicplayer.cpp | 22 ++-- src/tools/audio/players/radioplayer.h | 3 - .../audio/players/soundplayercontroller.h | 8 +- src/tools/audio/players/spotifyplayer.cpp | 12 +-- .../audio/playlist/resolvingaudioplaylist.cpp | 10 +- .../audio/playlist/resolvingaudioplaylist.h | 2 +- src/tools/audio/project/audiocategory.cpp | 8 +- src/tools/audio/project/audiocategory.h | 5 +- src/tools/audio/project/audioelement.cpp | 8 +- src/tools/audio/project/audioelement.h | 3 +- src/tools/audio/project/audiofile.cpp | 7 +- src/tools/audio/project/audiofile.h | 1 + src/tools/audio/project/audiofilemodel.cpp | 9 +- src/tools/audio/project/audiofilemodel.h | 4 +- src/tools/audio/project/audioproject.cpp | 10 +- src/tools/audio/project/audioproject.h | 3 +- src/tools/audio/project/audioscenario.cpp | 47 ++++---- src/tools/audio/project/audioscenario.h | 3 +- src/tools/audio/thumbnails/audiothumbnail.h | 3 +- .../audiothumbnailcollagegenerator.cpp | 12 +-- .../audiothumbnailcollagegenerator.h | 4 +- .../thumbnails/audiothumbnailgenerator.cpp | 2 +- .../thumbnails/loaders/fileimageloader.cpp | 6 +- .../thumbnails/loaders/spotifyimageloader.cpp | 26 ++--- .../thumbnails/loaders/spotifyimageloader.h | 2 +- .../thumbnails/loaders/tagimageloader.cpp | 51 ++++----- .../audio/thumbnails/loaders/tagimageloader.h | 2 +- .../thumbnails/loaders/webimageloader.cpp | 6 +- src/tools/characters/character.cpp | 8 +- src/tools/characters/character.h | 2 +- src/tools/characters/charactertool.cpp | 14 +-- src/tools/characters/charactertool.h | 8 +- .../viewers/characterimageviewer.cpp | 7 +- .../characters/viewers/characterviewer.h | 3 +- src/tools/combat_tracker/combatant.cpp | 4 +- src/tools/combat_tracker/combatant.h | 10 +- src/tools/combat_tracker/combattracker.cpp | 14 ++- src/tools/combat_tracker/combattracker.h | 4 +- .../combat_tracker/combattrackerstate.cpp | 2 +- src/tools/converter/convertereditor.cpp | 15 +-- src/tools/converter/convertereditor.h | 2 +- src/tools/converter/convertertool.cpp | 7 +- src/tools/converter/convertertool.h | 6 +- src/tools/dicetool.cpp | 8 +- .../names/abstractnamegenerator.cpp | 2 +- .../generators/names/abstractnamegenerator.h | 4 +- src/tools/generators/names/namegenerator.cpp | 4 +- src/tools/maps/map.h | 4 +- src/tools/maps/mapmarker.cpp | 6 +- src/tools/maps/mapmarker.h | 13 +-- src/tools/maps/maptool.cpp | 5 +- src/tools/notes/markdownhighlighter.cpp | 10 +- src/tools/notes/notessaveload.cpp | 40 +++---- src/tools/notes/notessaveload.h | 18 ++-- src/tools/notes/notestool.cpp | 25 +++-- src/tools/notes/notestool.h | 2 +- src/tools/shop/baseshoptool.cpp | 4 +- src/tools/shop/baseshoptool.h | 2 +- src/tools/shop/itemeditor.cpp | 16 +-- src/tools/shop/itemeditor.h | 4 +- src/tools/shop/project/item.cpp | 4 +- src/tools/shop/project/item.h | 2 +- src/tools/shop/project/itemshop.cpp | 11 +- src/tools/shop/project/itemshop.h | 2 +- src/tools/shop/project/shopcategory.cpp | 14 +-- src/tools/shop/project/shopcategory.h | 8 +- src/tools/shop/project/shopproject.cpp | 6 +- src/tools/shop/project/shopproject.h | 6 +- src/tools/shop/shopeditor.cpp | 20 ++-- src/tools/shop/shopeditor.h | 16 +-- src/tools/shop/shoptool.cpp | 6 +- src/tools/shop/shoptool.h | 4 +- tests/testhelper/abstracttest.cpp | 1 + 139 files changed, 622 insertions(+), 681 deletions(-) diff --git a/app/logger.cpp b/app/logger.cpp index 66a867c5..9f5cd530 100644 --- a/app/logger.cpp +++ b/app/logger.cpp @@ -9,7 +9,7 @@ Q_LOGGING_CATEGORY(gmLogger, "gm.logger") -static constexpr const char *RELATIVE_LOGFILE_PATH = ".gm-companion/log.txt"; +static constexpr auto RELATIVE_LOGFILE_PATH = ".gm-companion/log.txt"; Logger::Logger() { @@ -30,14 +30,6 @@ Logger::Logger() qInstallMessageHandler(messageHandler); } -Logger::~Logger() -{ - if (m_logFile.isOpen()) - { - m_logFile.close(); - } -} - void Logger::messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { auto timestamp = QDateTime::currentDateTime(); diff --git a/app/logger.h b/app/logger.h index 49defd96..d7349faa 100644 --- a/app/logger.h +++ b/app/logger.h @@ -9,18 +9,16 @@ class Logger { public: Logger(); - ~Logger(); - Q_DISABLE_COPY_MOVE(Logger); static void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg); private: - inline static QFile m_logFile; + QFile m_logFile; inline static QTextStream m_logStream; inline static QMutex m_logMutex; static void createLogFileDir(const QString &filePath); - static void clearOldLog(); + void clearOldLog(); static auto msgTypeToPrefix(QtMsgType type) -> QString; }; diff --git a/app/ui/FileDialog/filedialogbackend.cpp b/app/ui/FileDialog/filedialogbackend.cpp index afcf894e..098d3881 100644 --- a/app/ui/FileDialog/filedialogbackend.cpp +++ b/app/ui/FileDialog/filedialogbackend.cpp @@ -105,7 +105,7 @@ void FileDialogBackend::createFolder(const QString &folderName) { const auto path = FileUtils::fileInDir(folderName, currentDir()); - File::createDirAsync(path).then([this](FileResult &&result) { + File::createDirAsync(path).then([this](const FileResult &result) { if (!result.success()) { qCWarning(gmFileDialog()) << result.errorMessage(); @@ -153,7 +153,7 @@ void FileDialogBackend::stopCurrentRequest() } } -void FileDialogBackend::onFileListReceived(FileListResult &&result) +void FileDialogBackend::onFileListReceived(const FileListResult &result) { auto countBefore = a_entries.count(); diff --git a/app/ui/FileDialog/filedialogbackend.h b/app/ui/FileDialog/filedialogbackend.h index 4106ae23..7eac45fa 100644 --- a/app/ui/FileDialog/filedialogbackend.h +++ b/app/ui/FileDialog/filedialogbackend.h @@ -55,7 +55,7 @@ public slots: void stopCurrentRequest(); void clearForward(); - void onFileListReceived(FileListResult &&result); + void onFileListReceived(const FileListResult &result); private slots: void onCurrentDirChanged(const QString &dir); diff --git a/app/ui/tools/generators/NameGenerator.qml b/app/ui/tools/generators/NameGenerator.qml index a7ad4e66..64919b3a 100644 --- a/app/ui/tools/generators/NameGenerator.qml +++ b/app/ui/tools/generators/NameGenerator.qml @@ -68,8 +68,8 @@ Page { buttonText: modelData.name - anchors.left: parent.left - anchors.right: parent.right + anchors.left: parent ? parent.left : undefined + anchors.right: parent ? parent.right : undefined onClicked: { if (NameGeneratorTool.loadGenerator(index)) { diff --git a/src/addons/addonrepositorymanager.cpp b/src/addons/addonrepositorymanager.cpp index 6bb65c6a..7083c49f 100644 --- a/src/addons/addonrepositorymanager.cpp +++ b/src/addons/addonrepositorymanager.cpp @@ -82,14 +82,15 @@ void AddonRepositoryManager::fetchAllRepositoryData() foreach (const auto *repo, repositories()) { - auto future = fetchRepositoryDataAsync(repo->url()).then([this, repo](std::vector &&info) { - if (!info.empty()) - { - qCDebug(gmAddonRepoManager()) << "Successfully read addon repository" << repo->url(); - } + auto future = + fetchRepositoryDataAsync(repo->url()).then([this, repo](const std::vector &info) { + if (!info.empty()) + { + qCDebug(gmAddonRepoManager()) << "Successfully read addon repository" << repo->url(); + } - m_releaseInfos.insert(m_releaseInfos.end(), info.begin(), info.end()); - }); + m_releaseInfos.insert(m_releaseInfos.end(), info.begin(), info.end()); + }); combinator << future; } @@ -213,10 +214,10 @@ auto AddonRepositoryManager::parseRepositoryData(const QByteArray &data) -> std: auto release = getNewestCompatibleRelease(entry["releases"_L1].toArray()); if (release.isEmpty()) continue; - result.push_back(AddonReleaseInfo(entry["id"_L1].toString(), entry["name"_L1].toString(), - entry["name_short"_L1].toString(), release["version"_L1].toString(), - entry["author"_L1].toString(), entry["description"_L1].toString(), - release["download"_L1].toString())); + result.emplace_back(AddonReleaseInfo(entry["id"_L1].toString(), entry["name"_L1].toString(), + entry["name_short"_L1].toString(), release["version"_L1].toString(), + entry["author"_L1].toString(), entry["description"_L1].toString(), + release["download"_L1].toString())); } return result; diff --git a/src/common/models/customobjectlistmodel.cpp b/src/common/models/customobjectlistmodel.cpp index 0939ebfc..9ec68ea3 100644 --- a/src/common/models/customobjectlistmodel.cpp +++ b/src/common/models/customobjectlistmodel.cpp @@ -9,7 +9,7 @@ CustomObjectListModel::CustomObjectListModel(bool isOwning, QObject *parent) auto CustomObjectListModel::rowCount(const QModelIndex &parent) const -> int { Q_UNUSED(parent) - return m_objects.size(); + return static_cast(m_objects.size()); } auto CustomObjectListModel::headerData(int section, Qt::Orientation orientation, int role) const -> QVariant @@ -55,9 +55,9 @@ void CustomObjectListModel::replaceAll(const QList &objects) auto CustomObjectListModel::removeRows(int row, int count, const QModelIndex &parent) -> bool { const auto firstIndex = row; - auto lastIndex = row + count - 1; - if (Utils::isInBounds(m_objects, firstIndex) && Utils::isInBounds(m_objects, lastIndex)) + if (auto lastIndex = row + count - 1; + Utils::isInBounds(m_objects, firstIndex) && Utils::isInBounds(m_objects, lastIndex)) { beginRemoveRows(parent, firstIndex, lastIndex); @@ -100,7 +100,7 @@ void CustomObjectListModel::append(QObject *object, const QModelIndex &parent) { takeOwnershipIfRequired(object); - const auto lastIndex = m_objects.size(); + const auto lastIndex = static_cast(m_objects.size()); beginInsertRows(parent, lastIndex, lastIndex); m_objects.append(object); endInsertRows(); diff --git a/src/common/models/customobjectlistmodel.h b/src/common/models/customobjectlistmodel.h index bd2ed4f7..65e4dcfc 100644 --- a/src/common/models/customobjectlistmodel.h +++ b/src/common/models/customobjectlistmodel.h @@ -16,7 +16,7 @@ class CustomObjectListModel : public QAbstractListModel explicit CustomObjectListModel(bool isOwning, QObject *parent = nullptr); [[nodiscard]] auto rowCount(const QModelIndex &parent = QModelIndex()) const -> int override; - [[nodiscard]] virtual auto data(const QModelIndex &index, int role) const -> QVariant override = 0; + [[nodiscard]] auto data(const QModelIndex &index, int role) const -> QVariant override = 0; [[nodiscard]] auto headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const -> QVariant override; diff --git a/src/common/models/customsharedptrlistmodel.h b/src/common/models/customsharedptrlistmodel.h index fc03bc5d..a49cb2b0 100644 --- a/src/common/models/customsharedptrlistmodel.h +++ b/src/common/models/customsharedptrlistmodel.h @@ -22,7 +22,7 @@ template class CustomSharedPtrListModel : public QAbstractListModel [[nodiscard]] auto rowCount(const QModelIndex &parent = QModelIndex()) const -> int override { Q_UNUSED(parent) - return m_objects.size(); + return static_cast(m_objects.size()); } [[nodiscard]] auto headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const @@ -51,9 +51,9 @@ template class CustomSharedPtrListModel : public QAbstractListModel auto removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) -> bool override { const auto firstIndex = row; - auto lastIndex = row + count - 1; - if (Utils::isInBounds(m_objects, firstIndex) && Utils::isInBounds(m_objects, lastIndex)) + if (auto lastIndex = row + count - 1; + Utils::isInBounds(m_objects, firstIndex) && Utils::isInBounds(m_objects, lastIndex)) { beginRemoveRows(parent, firstIndex, lastIndex); m_objects.erase(m_objects.begin() + firstIndex, m_objects.begin() + firstIndex + count); diff --git a/src/common/models/treeitem.cpp b/src/common/models/treeitem.cpp index e953ec9a..9a499c81 100755 --- a/src/common/models/treeitem.cpp +++ b/src/common/models/treeitem.cpp @@ -6,7 +6,7 @@ using namespace Qt::Literals::StringLiterals; TreeItem::TreeItem(const QString &name, int depth, bool canToggle, QObject *parent) : BaseProjectItem(name, parent), a_canToggle(canToggle), a_depth(depth) { - if (auto *parentItem = qobject_cast(parent); parentItem) + if (const QPointer parentItem = qobject_cast(parent); parentItem) { connect(this, &TreeItem::childItemsChanged, parentItem, &TreeItem::childItemsChanged); connect(this, &TreeItem::destroyed, parentItem, &TreeItem::childItemsChanged); @@ -132,7 +132,6 @@ void TreeItem::onChildIsCheckedChanged() emit isCheckedChanged(); } return; - case CheckedState::Checked: default: checkedChildren++; break; diff --git a/src/common/settings/quicksettingsmanager.cpp b/src/common/settings/quicksettingsmanager.cpp index 4a4a0080..a084b1b1 100644 --- a/src/common/settings/quicksettingsmanager.cpp +++ b/src/common/settings/quicksettingsmanager.cpp @@ -18,7 +18,7 @@ void QuickSettingsManager::setPath(const QString &path, const QString &value) SettingsManager::setPath(path, value); } -auto QuickSettingsManager::getLanguageIndex() -> int +auto QuickSettingsManager::getLanguageIndex() -> qsizetype { auto language = SettingsManager::getLanguageString(); auto languages = getLanguageNames(); diff --git a/src/common/settings/quicksettingsmanager.h b/src/common/settings/quicksettingsmanager.h index 72ef5c7d..0521b938 100644 --- a/src/common/settings/quicksettingsmanager.h +++ b/src/common/settings/quicksettingsmanager.h @@ -75,7 +75,7 @@ class QuickSettingsManager : public QObject Q_INVOKABLE static QString getPath(const QString &path); Q_INVOKABLE static void setPath(const QString &path, const QString &value); - Q_INVOKABLE static int getLanguageIndex(); + Q_INVOKABLE static qsizetype getLanguageIndex(); Q_INVOKABLE static QStringList getLanguageNames(); Q_INVOKABLE void setLanguage(const QString &language); diff --git a/src/common/settings/settingsmanager.cpp b/src/common/settings/settingsmanager.cpp index 9b732263..27efa140 100755 --- a/src/common/settings/settingsmanager.cpp +++ b/src/common/settings/settingsmanager.cpp @@ -119,12 +119,14 @@ void SettingsManager::setServerUrl(const QString &url, const QString &service) auto SettingsManager::getPassword(const QString &username, const QString &service) -> QString { + using namespace QKeychain; + // job is deleted automatically when finished - auto *job = new QKeychain::ReadPasswordJob(u"gm-companion.%1"_s.arg(service)); + auto *job = new ReadPasswordJob(u"gm-companion.%1"_s.arg(service)); job->setKey(username); QEventLoop loop; - job->connect(job, &QKeychain::ReadPasswordJob::finished, &loop, &QEventLoop::quit); + connect(job, &ReadPasswordJob::finished, &loop, &QEventLoop::quit); job->start(); loop.exec(); @@ -140,13 +142,15 @@ auto SettingsManager::getPassword(const QString &username, const QString &servic auto SettingsManager::setPassword(const QString &username, const QString &password, const QString &service) -> bool { + using namespace QKeychain; + // job is deleted automatically when finished - auto *job = new QKeychain::WritePasswordJob(u"gm-companion.%1"_s.arg(service)); + auto *job = new WritePasswordJob(u"gm-companion.%1"_s.arg(service)); job->setKey(username); job->setTextData(password); QEventLoop loop; - job->connect(job, &QKeychain::WritePasswordJob::finished, &loop, &QEventLoop::quit); + connect(job, &WritePasswordJob::finished, &loop, &QEventLoop::quit); job->start(); loop.exec(); @@ -173,11 +177,9 @@ auto SettingsManager::getDefaultPath(const QString &setting, const QString &grou /// Default value is PATHS_GROUP. auto SettingsManager::getActivePathGroup() -> QString { - auto cloudMode = instance()->get(u"cloudMode"_s, u"local"_s); - - if (cloudMode == "GoogleDrive"_L1) return cloudMode; - - if (cloudMode == "NextCloud"_L1) return cloudMode; + if (auto cloudMode = instance()->get(u"cloudMode"_s, u"local"_s); + cloudMode == "GoogleDrive"_L1 || cloudMode == "NextCloud"_L1) + return cloudMode; return PATHS_GROUP; } @@ -203,9 +205,7 @@ auto SettingsManager::getIsAddonEnabled(const QString &addon) -> bool /// Updates the settings if something changed from a previous version void SettingsManager::updateSettings() { - const auto cloudMode = get(u"cloudMode"_s, u"0"_s); - - if (cloudMode == "0"_L1) + if (const auto cloudMode = get(u"cloudMode"_s, u"0"_s); cloudMode == "0"_L1) { set(u"cloudMode"_s, u"local"_s); } diff --git a/src/common/utils/fileutils.cpp b/src/common/utils/fileutils.cpp index 62232285..730a78fc 100755 --- a/src/common/utils/fileutils.cpp +++ b/src/common/utils/fileutils.cpp @@ -94,10 +94,10 @@ auto FileUtils::incrementFileName(const QString &fileName) -> QString { if (fileName.isEmpty()) return u""_s; - auto nameAndSuffix = splitFileNameAndSuffix(fileName); - auto incrementedName = incrementName(nameAndSuffix.first); + auto [name, suffix] = splitFileNameAndSuffix(fileName); + auto incrementedName = incrementName(name); - return incrementedName + '.' + nameAndSuffix.second; + return incrementedName + '.' + suffix; } auto FileUtils::incrementName(const QString &name) -> QString diff --git a/src/common/utils/stringutils.cpp b/src/common/utils/stringutils.cpp index ea663db3..377071ee 100644 --- a/src/common/utils/stringutils.cpp +++ b/src/common/utils/stringutils.cpp @@ -40,12 +40,12 @@ auto StringUtils::rot13(const QString &input) -> QString { if (lowCaps.contains(character)) { - const int index = lowCaps.indexOf(character); + const auto index = lowCaps.indexOf(character); encrypted.append(lowCaps.at(index + ROT13_PLACES)); } else if (upperCaps.contains(character)) { - const int index = upperCaps.indexOf(character); + const auto index = upperCaps.indexOf(character); encrypted.append(upperCaps.at(index + ROT13_PLACES)); } else diff --git a/src/common/utils/utils.h b/src/common/utils/utils.h index fde687c1..02463187 100755 --- a/src/common/utils/utils.h +++ b/src/common/utils/utils.h @@ -28,7 +28,7 @@ class Utils template static auto isInBounds(const T &list, qsizetype index) -> bool { - return index > -1 && index < list.size(); + return index > -1 && index < std::size(list); } template static auto copyList(const QList &original) -> QList diff --git a/src/filesystem/cache/filecache.cpp b/src/filesystem/cache/filecache.cpp index 253805b6..1609a38b 100644 --- a/src/filesystem/cache/filecache.cpp +++ b/src/filesystem/cache/filecache.cpp @@ -88,7 +88,7 @@ auto FileCache::copyEntry(const QString &path, const QString ©) -> bool return false; } -auto FileCache::checkEntry(const QString &path) -> bool +auto FileCache::checkEntry(const QString &path) const -> bool { return m_entries.contains(path) && m_entries.value(path)->isFresh(m_expirationTimeMs); } diff --git a/src/filesystem/cache/filecache.h b/src/filesystem/cache/filecache.h index ff935d1b..86c0945a 100644 --- a/src/filesystem/cache/filecache.h +++ b/src/filesystem/cache/filecache.h @@ -16,7 +16,7 @@ class FileCache auto removeEntry(const QString &path) -> bool; auto moveEntry(const QString &oldPath, const QString &newPath) -> bool; auto copyEntry(const QString &path, const QString ©) -> bool; - auto checkEntry(const QString &path) -> bool; + auto checkEntry(const QString &path) const -> bool; void printEntries() const; diff --git a/src/filesystem/fileaccess.h b/src/filesystem/fileaccess.h index 5c950024..9a23ccc5 100755 --- a/src/filesystem/fileaccess.h +++ b/src/filesystem/fileaccess.h @@ -17,6 +17,7 @@ class FileAccess { public: FileAccess() = default; + virtual ~FileAccess() = default; Q_DISABLE_COPY_MOVE(FileAccess); virtual auto getDataAsync(const QString &path, bool allowCache) -> QFuture = 0; diff --git a/src/filesystem/fileaccesslocal.cpp b/src/filesystem/fileaccesslocal.cpp index 7d1b1978..d35c1d56 100755 --- a/src/filesystem/fileaccesslocal.cpp +++ b/src/filesystem/fileaccesslocal.cpp @@ -34,7 +34,7 @@ auto FileAccessLocal::getDataAsync(const QString &path, bool allowCache) -> QFut qCDebug(gmFileAccessLocal()) << "Getting data from file:" << path << "..."; return QtConcurrent::run(&FileAccessLocal::getData, path, allowCache).then(&m_context, [](FileDataResult &&result) { - return result; + return std::move(result); }); } @@ -54,7 +54,7 @@ auto FileAccessLocal::getDataAsync(const QStringList &paths, bool allowCache) -> return results; }) - .then(&m_context, [](std::vector &&result) { return result; }); + .then(&m_context, [](std::vector &&result) { return std::move(result); }); } /// Create a directory @@ -81,7 +81,7 @@ auto FileAccessLocal::createDirAsync(const QString &path) -> QFuture { qCDebug(gmFileAccessLocal()) << "Creating directory:" << path << "..."; return QtConcurrent::run(&FileAccessLocal::createDir, QDir(path)).then(&m_context, [](FileResult &&result) { - return result; + return std::move(result); }); } @@ -133,16 +133,13 @@ auto FileAccessLocal::saveAsync(const QString &path, const QByteArray &data) -> { qCDebug(gmFileAccessLocal()) << "Saving file:" << path << "..."; return QtConcurrent::run(&FileAccessLocal::save, path, data).then(&m_context, [](FileResult &&result) { - return result; + return std::move(result); }); } auto FileAccessLocal::move(const QString &oldPath, const QString &newPath) -> FileResult { - QFile f(oldPath); - QFileInfo const info(newPath); - - if (!info.dir().exists()) + if (QFileInfo const info(newPath); !info.dir().exists()) { auto createDirResult = createDir(info.dir()); if (!createDirResult.success()) @@ -153,6 +150,8 @@ auto FileAccessLocal::move(const QString &oldPath, const QString &newPath) -> Fi } } + QFile f(oldPath); + if (!f.rename(newPath)) { auto errorMessage = @@ -169,7 +168,7 @@ auto FileAccessLocal::moveAsync(const QString &oldPath, const QString &newPath) { qCDebug(gmFileAccessLocal()) << "Moving file:" << oldPath << "->" << newPath << "..."; return QtConcurrent::run(&FileAccessLocal::move, oldPath, newPath).then(&m_context, [](FileResult &&result) { - return result; + return std::move(result); }); } @@ -199,7 +198,7 @@ auto FileAccessLocal::deleteAsync(const QString &path) -> QFuture return FileResult(true); }) - .then(&m_context, [](FileResult &&result) { return result; }); + .then(&m_context, [](FileResult &&result) { return std::move(result); }); } auto FileAccessLocal::copy(const QString &path, const QString ©) -> FileResult @@ -233,7 +232,7 @@ auto FileAccessLocal::copyAsync(const QString &path, const QString ©) -> QFu { qCDebug(gmFileAccessLocal()) << "Copying file:" << path << "->" << copy << "..."; return QtConcurrent::run(&FileAccessLocal::copy, path, copy).then(&m_context, [](FileResult &&result) { - return result; + return std::move(result); }); } @@ -245,7 +244,7 @@ auto FileAccessLocal::listAsync(const QString &path, bool files, bool folders) - return FileListResult(path, dir.entryList(getDirFilter(false, folders)), dir.entryList(getDirFilter(files, false))); }) - .then(&m_context, [](FileListResult &&result) { return result; }); + .then(&m_context, [](FileListResult &&result) { return std::move(result); }); } /// Check if a file exists @@ -261,7 +260,7 @@ auto FileAccessLocal::check(const QString &path, bool allowCache) -> FileCheckRe auto FileAccessLocal::checkAsync(const QString &path, bool allowCache) -> QFuture { return QtConcurrent::run(&FileAccessLocal::check, path, allowCache).then(&m_context, [](FileCheckResult &&result) { - return result; + return std::move(result); }); } @@ -276,7 +275,7 @@ auto FileAccessLocal::checkAsync(const QStringList &paths, bool allowCache) -> Q } return result; }) - .then(&m_context, [](FileMultiCheckResult &&result) { return result; }); + .then(&m_context, [](FileMultiCheckResult &&result) { return std::move(result); }); } auto FileAccessLocal::getDirFilter(bool files, bool folders) -> QFlags diff --git a/src/filesystem/fileaccesslocal.h b/src/filesystem/fileaccesslocal.h index bc6cfd97..eaf74cf2 100755 --- a/src/filesystem/fileaccesslocal.h +++ b/src/filesystem/fileaccesslocal.h @@ -11,6 +11,8 @@ class FileAccessLocal : public FileAccess { public: FileAccessLocal() = default; + virtual ~FileAccessLocal() = default; + Q_DISABLE_COPY_MOVE(FileAccessLocal) auto getDataAsync(const QString &path, bool allowCache) -> QFuture override; auto getDataAsync(const QStringList &paths, bool allowCache) -> QFuture> override; diff --git a/src/filesystem/fileaccessnextcloud.cpp b/src/filesystem/fileaccessnextcloud.cpp index f3b4af76..7baebffe 100644 --- a/src/filesystem/fileaccessnextcloud.cpp +++ b/src/filesystem/fileaccessnextcloud.cpp @@ -56,7 +56,7 @@ auto FileAccessNextcloud::createDirThenContinue(const QString &dir, const T1 &ar { return createDirAsync(dir) .then([arg1, arg2, func](FileResult &&result) { - if (!result.success()) return QtFuture::makeReadyFuture(result); + if (!result.success()) return QtFuture::makeReadyFuture(std::move(result)); return func(arg1, arg2); }) .unwrap(); @@ -72,8 +72,7 @@ auto FileAccessNextcloud::saveAsync(const QString &path, const QByteArray &data) .then([this, future, path, data](QNetworkReply *reply) { if (replyHasError(reply)) { - const auto isDirMissing = reply->error() == QNetworkReply::ContentNotFoundError; - if (isDirMissing) + if (const auto isDirMissing = reply->error() == QNetworkReply::ContentNotFoundError; isDirMissing) { return deleteReplyAndReturn( createDirThenContinue( @@ -109,8 +108,7 @@ auto FileAccessNextcloud::moveAsync(const QString &oldPath, const QString &newPa if (replyHasError(reply)) { - const auto isDirMissing = reply->error() == QNetworkReply::ContentConflictError; - if (isDirMissing) + if (const auto isDirMissing = reply->error() == QNetworkReply::ContentConflictError; isDirMissing) { return deleteReplyAndReturn( createDirThenContinue(FileUtils::dirFromPath(newPath), oldPath, newPath, @@ -170,8 +168,7 @@ auto FileAccessNextcloud::copyAsync(const QString &path, const QString ©) -> .then([this, future, path, copy](QNetworkReply *reply) { if (replyHasError(reply)) { - const auto isDirMissing = reply->error() == QNetworkReply::ContentConflictError; - if (isDirMissing) + if (const auto isDirMissing = reply->error() == QNetworkReply::ContentConflictError; isDirMissing) { return deleteReplyAndReturn( createDirThenContinue( @@ -207,7 +204,7 @@ auto FileAccessNextcloud::listAsync(const QString &path, bool files, bool folder return future.then([future, path, files, folders](QNetworkReply *reply) { if (replyHasError(reply)) { - const auto errorMessage = makeAndPrintError(u"Could not list content of folder %1"_s.arg(path), reply); + auto errorMessage = makeAndPrintError(u"Could not list content of folder %1"_s.arg(path), reply); return deleteReplyAndReturn(FileListResult(path, std::move(errorMessage)), reply); } @@ -254,9 +251,9 @@ auto FileAccessNextcloud::parseListResponse(const QByteArray &data, const QStrin } } else if (files && xml.name() == "getcontenttype"_L1 && - !xml.readElementText(QXmlStreamReader::SkipChildElements).isEmpty()) + !xml.readElementText(QXmlStreamReader::SkipChildElements).isEmpty() && !element.isEmpty()) { - if (!element.isEmpty()) fileList << element; + fileList << element; } } } @@ -304,9 +301,8 @@ auto FileAccessNextcloud::checkAsync(const QString &path, bool allowCache) -> QF return future.then([future, path](QNetworkReply *reply) { const auto doesExist = reply->error() != QNetworkReply::ContentNotFoundError; - const auto hasError = replyHasError(reply) && doesExist; - if (hasError) + if (const auto hasError = replyHasError(reply) && doesExist; hasError) { auto errorMessage = makeAndPrintError(u"Could not check if file %1 exists"_s.arg(path), reply); return deleteReplyAndReturn(FileCheckResult(path, std::move(errorMessage)), reply); @@ -329,7 +325,7 @@ auto FileAccessNextcloud::encodePath(const QString &data) -> QByteArray return QUrl::toPercentEncoding(data, "/"); } -auto FileAccessNextcloud::replyHasError(QNetworkReply *reply) -> bool +auto FileAccessNextcloud::replyHasError(const QNetworkReply *reply) -> bool { return reply->error() != QNetworkReply::NoError; } @@ -353,8 +349,8 @@ auto FileAccessNextcloud::makeMoveHeaders(const QString &newPath) -> QList auto FileAccessNextcloud::deleteReplyAndReturn(T value, QNetworkReply *reply) -> T +template auto FileAccessNextcloud::deleteReplyAndReturn(T &&value, QNetworkReply *reply) -> T { QScopedPointer scopedReply(reply); - return value; + return std::move(value); } diff --git a/src/filesystem/fileaccessnextcloud.h b/src/filesystem/fileaccessnextcloud.h index d3ba4e9f..fe2e1bd4 100644 --- a/src/filesystem/fileaccessnextcloud.h +++ b/src/filesystem/fileaccessnextcloud.h @@ -13,6 +13,8 @@ class FileAccessNextcloud : public FileAccess { public: explicit FileAccessNextcloud(Services::NextCloud &nextcloud); + virtual ~FileAccessNextcloud() = default; + Q_DISABLE_COPY_MOVE(FileAccessNextcloud) auto getDataAsync(const QString &path, bool allowCache) -> QFuture override; auto getDataAsync(const QStringList &paths, bool allowCache) -> QFuture> override; @@ -30,12 +32,12 @@ class FileAccessNextcloud : public FileAccess FileCache m_cache; static auto encodePath(const QString &data) -> QByteArray; - static auto replyHasError(QNetworkReply *reply) -> bool; + static auto replyHasError(const QNetworkReply *reply) -> bool; static auto makeAndPrintError(const QString &errorMessage, const QNetworkReply *reply) -> QString; static auto replyErrorToString(const QNetworkReply *reply) -> QString; static auto makeMoveHeaders(const QString &newPath) -> QList>; - template static auto deleteReplyAndReturn(T value, QNetworkReply *reply) -> T; + template static auto deleteReplyAndReturn(T &&value, QNetworkReply *reply) -> T; template auto createDirThenContinue(const QString &dir, const T1 &arg1, const T2 &arg2, diff --git a/src/filesystem/multigethelper.h b/src/filesystem/multigethelper.h index d98dfdc0..05591b55 100644 --- a/src/filesystem/multigethelper.h +++ b/src/filesystem/multigethelper.h @@ -25,12 +25,14 @@ template class MultiGetHelper [[nodiscard]] auto getNextPath() -> QString { - return m_paths.at(index++); + auto value = m_paths.at(index); + index++; + return value; } void addResult(ResultType &&result) { - m_results.push_back(result); + m_results.emplace_back(std::move(result)); } [[nodiscard]] auto getResults() const -> std::vector diff --git a/src/filesystem/results/filecheckresult.cpp b/src/filesystem/results/filecheckresult.cpp index 1d0d3414..88beed69 100644 --- a/src/filesystem/results/filecheckresult.cpp +++ b/src/filesystem/results/filecheckresult.cpp @@ -5,7 +5,7 @@ using namespace Qt::Literals::StringLiterals; using namespace Files; using namespace Services; -auto FileCheckResult::fromRestReply(RestReply &&reply, const QString &path) -> FileCheckResult +auto FileCheckResult::fromRestReply(const RestReply &reply, const QString &path) -> FileCheckResult { bool success = true; QString errorMessage; diff --git a/src/filesystem/results/filecheckresult.h b/src/filesystem/results/filecheckresult.h index cba86548..58b32628 100644 --- a/src/filesystem/results/filecheckresult.h +++ b/src/filesystem/results/filecheckresult.h @@ -23,7 +23,7 @@ class FileCheckResult : public FileResult { } - static auto fromRestReply(Services::RestReply &&reply, const QString &path) -> FileCheckResult; + static auto fromRestReply(const Services::RestReply &reply, const QString &path) -> FileCheckResult; [[nodiscard]] auto path() const -> const QString & { diff --git a/src/filesystem/results/filedataresult.cpp b/src/filesystem/results/filedataresult.cpp index 475d7566..9a1d35cc 100644 --- a/src/filesystem/results/filedataresult.cpp +++ b/src/filesystem/results/filedataresult.cpp @@ -5,7 +5,7 @@ using namespace Qt::Literals::StringLiterals; using namespace Files; using namespace Services; -auto FileDataResult::fromRestReply(RestReply &&reply) -> FileDataResult +auto FileDataResult::fromRestReply(const RestReply &reply) -> FileDataResult { bool success = true; QString errorMessage; diff --git a/src/filesystem/results/filedataresult.h b/src/filesystem/results/filedataresult.h index 59964d96..b0f93197 100644 --- a/src/filesystem/results/filedataresult.h +++ b/src/filesystem/results/filedataresult.h @@ -10,13 +10,7 @@ namespace Files class FileDataResult : public FileResult { public: - explicit FileDataResult(const QString &errorMessage) : FileResult(errorMessage) - { - } - - explicit FileDataResult(QString &&errorMessage) : FileResult(std::move(errorMessage)) - { - } + using FileResult::FileResult; explicit FileDataResult(const QByteArray &data) : FileResult(true, QByteArray()), m_data(data) { @@ -26,7 +20,7 @@ class FileDataResult : public FileResult { } - static auto fromRestReply(Services::RestReply &&reply) -> FileDataResult; + static auto fromRestReply(const Services::RestReply &reply) -> FileDataResult; [[nodiscard]] auto data() const -> const QByteArray & { diff --git a/src/filesystem/results/filelistresult.h b/src/filesystem/results/filelistresult.h index b4656354..c2e314c7 100644 --- a/src/filesystem/results/filelistresult.h +++ b/src/filesystem/results/filelistresult.h @@ -3,7 +3,6 @@ #include "fileresult.h" #include -using namespace Qt::Literals::StringLiterals; namespace Files { @@ -26,8 +25,8 @@ class FileListResult : public FileResult { } - [[nodiscard]] auto filesFull(const QString &wildcard = u""_s) const -> QStringList; - [[nodiscard]] auto foldersFull(const QString &wildcard = u""_s) const -> QStringList; + [[nodiscard]] auto filesFull(const QString &wildcard = QLatin1String()) const -> QStringList; + [[nodiscard]] auto foldersFull(const QString &wildcard = QLatin1String()) const -> QStringList; [[nodiscard]] auto folders() const -> const QStringList & { diff --git a/src/filesystem/results/filemulticheckresult.h b/src/filesystem/results/filemulticheckresult.h index c8f747cc..38cfade4 100644 --- a/src/filesystem/results/filemulticheckresult.h +++ b/src/filesystem/results/filemulticheckresult.h @@ -10,22 +10,16 @@ namespace Files class FileMultiCheckResult : public FileResult { public: + using FileResult::FileResult; + explicit FileMultiCheckResult(std::vector &&results) : FileResult(true), m_results(std::move(results)) { } - explicit FileMultiCheckResult(bool success, const QString &errorMessage) : FileResult(success, errorMessage) - { - } - - explicit FileMultiCheckResult(bool success) : FileResult(success) - { - } - void add(FileCheckResult &&result) { - m_results.push_back(result); + m_results.emplace_back(std::move(result)); } [[nodiscard]] auto results() const -> const std::vector & diff --git a/src/filesystem/results/fileresult.cpp b/src/filesystem/results/fileresult.cpp index 309fec87..4f98acff 100644 --- a/src/filesystem/results/fileresult.cpp +++ b/src/filesystem/results/fileresult.cpp @@ -5,7 +5,7 @@ using namespace Qt::Literals::StringLiterals; using namespace Files; using namespace Services; -auto FileResult::fromRestReply(RestReply &&reply) -> FileResult +auto FileResult::fromRestReply(const RestReply &reply) -> FileResult { bool success = true; QString errorMessage; diff --git a/src/filesystem/results/fileresult.h b/src/filesystem/results/fileresult.h index add16029..ccb3d8a3 100644 --- a/src/filesystem/results/fileresult.h +++ b/src/filesystem/results/fileresult.h @@ -30,7 +30,7 @@ class FileResult { } - static auto fromRestReply(Services::RestReply &&reply) -> FileResult; + static auto fromRestReply(const Services::RestReply &reply) -> FileResult; [[nodiscard]] auto success() const -> bool { diff --git a/src/messages/messagemanager.cpp b/src/messages/messagemanager.cpp index 17352a4c..c42b2c4e 100644 --- a/src/messages/messagemanager.cpp +++ b/src/messages/messagemanager.cpp @@ -21,7 +21,8 @@ void MessageManager::addMessage(std::shared_ptr message) { if (QThread::currentThread() != this->thread()) { - QTimer::singleShot(0, this, [this, message = std::move(message)]() { addMessage(message); }); + QTimer::singleShot(std::chrono::milliseconds::zero(), this, + [this, message = std::move(message)]() { addMessage(std::move(message)); }); return; } diff --git a/src/resources/notes/style.css b/src/resources/notes/style.css index 3e1f84e1..85bba8be 100644 --- a/src/resources/notes/style.css +++ b/src/resources/notes/style.css @@ -14,7 +14,6 @@ code { padding-bottom: 0.2em; margin: 0; font-size: 85%; - /* background-color: #1f1f1f; */ border-radius: 3px; } p { @@ -31,4 +30,4 @@ a { a:hover { color: #f33; border-bottom-color: #f33; -} \ No newline at end of file +} diff --git a/src/services/nextcloud/nextcloud.cpp b/src/services/nextcloud/nextcloud.cpp index 1101c9e0..5366a7ed 100644 --- a/src/services/nextcloud/nextcloud.cpp +++ b/src/services/nextcloud/nextcloud.cpp @@ -18,7 +18,7 @@ constexpr auto MAX_AUTH_POLLS = 20; Q_LOGGING_CATEGORY(gmNextCloud, "gm.service.nextcloud") -NextCloud::NextCloud(QQmlEngine &engine, QObject *parent) : NextCloud(*engine.networkAccessManager(), parent) +NextCloud::NextCloud(const QQmlEngine &engine, QObject *parent) : NextCloud(*engine.networkAccessManager(), parent) { } @@ -86,15 +86,15 @@ auto NextCloud::sendDavRequest(const QByteArray &method, const QString &path, co if (!headers.isEmpty()) { - for (const auto &pair : headers) + for (const auto &[key, value] : headers) { - if (pair.first == "Destination") + if (key == "Destination") { - request.setRawHeader(pair.first, getPathUrl(pair.second).toUtf8()); + request.setRawHeader(key, getPathUrl(value).toUtf8()); } else { - request.setRawHeader(pair.first, pair.second); + request.setRawHeader(key, value); } } } diff --git a/src/services/nextcloud/nextcloud.h b/src/services/nextcloud/nextcloud.h index 74a09f8f..72c480fd 100644 --- a/src/services/nextcloud/nextcloud.h +++ b/src/services/nextcloud/nextcloud.h @@ -21,7 +21,7 @@ class NextCloud : public Services::Service QML_ONLY_SINGLETON_FACTORY(NextCloud) public: - explicit NextCloud(QQmlEngine &engine, QObject *parent); + explicit NextCloud(const QQmlEngine &engine, QObject *parent); explicit NextCloud(QNetworkAccessManager &networkManager, QObject *parent); explicit NextCloud(const QString &serviceName, QNetworkAccessManager &networkManager, QObject *parent); diff --git a/src/services/rest/restrequest.h b/src/services/rest/restrequest.h index 0372e0c7..4a5abaf6 100644 --- a/src/services/rest/restrequest.h +++ b/src/services/rest/restrequest.h @@ -8,8 +8,6 @@ namespace Services class RestRequest { - Q_GADGET - public: enum class Type { @@ -18,7 +16,6 @@ class RestRequest POST, CUSTOM }; - Q_ENUM(Type) explicit RestRequest(const QNetworkRequest &request, Type type, QByteArray data = {}, QByteArray verb = {}) : RestRequest(-1, request, type, std::move(data), std::move(verb)) diff --git a/src/services/rest/restserviceconnector.cpp b/src/services/rest/restserviceconnector.cpp index 23d25bdc..923b2f6a 100644 --- a/src/services/rest/restserviceconnector.cpp +++ b/src/services/rest/restserviceconnector.cpp @@ -101,10 +101,10 @@ void RESTServiceConnector::dequeueRequests() QString reason; while (canSendRequest(reason) && !m_requestQueue.empty()) { - auto pair = std::move(m_requestQueue.front()); + auto [reply, request] = std::move(m_requestQueue.front()); m_requestQueue.pop(); - sendRequest(std::move(pair.second), std::move(pair.first)); + sendRequest(std::move(request), std::move(reply)); } } @@ -141,8 +141,9 @@ auto RESTServiceConnector::canSendRequest(QString &reason) -> bool auto RESTServiceConnector::enqueueRequest(RestRequest &&request, QPromise &&reply) -> QFuture { auto future = reply.future(); - request.id(m_nextQueueId++); - m_requestQueue.push(std::make_pair(std::move(reply), std::move(request))); + request.id(m_nextQueueId); + m_nextQueueId++; + m_requestQueue.emplace(std::make_pair(std::move(reply), std::move(request))); // try to dispatch request dequeueRequests(); @@ -153,11 +154,11 @@ auto RESTServiceConnector::markRequestActive(RestRequest &&request, QPromise int +auto RESTServiceConnector::maxConcurrentRequests() const -> size_t { return m_maxConcurrentRequests; } @@ -177,12 +178,12 @@ auto RESTServiceConnector::isTokenExpired() const -> bool return !m_tokenExpireTime.isValid() || QDateTime::currentDateTime() > m_tokenExpireTime; } -auto RESTServiceConnector::activeRequestCount() const -> int +auto RESTServiceConnector::activeRequestCount() const -> size_t { return m_activeRequests.size(); } -auto RESTServiceConnector::wasRateLimitReached(QNetworkReply::NetworkError error, const QByteArray &data) -> bool +auto RESTServiceConnector::wasRateLimitReached(QNetworkReply::NetworkError error, const QByteArray &data) const -> bool { if (error == QNetworkReply::UnknownContentError) { @@ -193,11 +194,11 @@ auto RESTServiceConnector::wasRateLimitReached(QNetworkReply::NetworkError error // Sometimes services (like google drive) hide rate limit errors in 403s if (error == QNetworkReply::ContentAccessDenied) { - const auto error = QJsonDocument::fromJson(data).object()["error"_L1].toObject(); + const auto errorObject = QJsonDocument::fromJson(data).object()["error"_L1].toObject(); - if (error.contains("errors"_L1)) + if (errorObject.contains("errors"_L1)) { - foreach (const auto &entry, error["errors"_L1].toArray()) + foreach (const auto &entry, errorObject["errors"_L1].toArray()) { return entry["reason"_L1].toString() == "userRateLimitExceeded"_L1; } diff --git a/src/services/rest/restserviceconnector.h b/src/services/rest/restserviceconnector.h index 446de51d..2f4f7c9e 100644 --- a/src/services/rest/restserviceconnector.h +++ b/src/services/rest/restserviceconnector.h @@ -57,7 +57,7 @@ protected slots: auto markRequestActive(RestRequest &&request, QPromise &&reply) -> QFuture; virtual void sendRequest(RestRequest &&request, QPromise &&reply) = 0; - [[nodiscard]] auto maxConcurrentRequests() const -> int; + [[nodiscard]] auto maxConcurrentRequests() const -> size_t; void setMaxConcurrentRequests(int count); [[nodiscard]] virtual auto getAccessToken() -> QString @@ -73,14 +73,14 @@ protected slots: bool m_wasConfigured = false; private: - [[nodiscard]] auto activeRequestCount() const -> int; + [[nodiscard]] auto activeRequestCount() const -> size_t; - [[nodiscard]] auto wasRateLimitReached(QNetworkReply::NetworkError error, const QByteArray &data) -> bool; + [[nodiscard]] auto wasRateLimitReached(QNetworkReply::NetworkError error, const QByteArray &data) const -> bool; void handleRateLimit(std::pair, RestRequest> &&pair, const QList &headers); bool m_isOnCooldown = false; - int m_maxConcurrentRequests = 1; + size_t m_maxConcurrentRequests = 1; int m_nextQueueId = 1; QStringList m_recoverableErrors; QDateTime m_tokenExpireTime; diff --git a/src/services/spotify/api/playerapi.cpp b/src/services/spotify/api/playerapi.cpp index 4ed6c620..0798b039 100644 --- a/src/services/spotify/api/playerapi.cpp +++ b/src/services/spotify/api/playerapi.cpp @@ -217,7 +217,7 @@ auto PlayerAPI::getCurrentlyPlaying(const QStringList &additionalTypes, const QS query.addQueryItem(u"market"_s, u"from_token"_s); url.setQuery(query); - const auto callback = [](RestReply &&reply) -> QFuture { + const auto callback = [](const RestReply &reply) -> QFuture { if (reply.hasError()) { qCWarning(gmSpotifyPlayer()) << reply.errorText(); @@ -249,7 +249,7 @@ auto PlayerAPI::devices() -> QFuture { const QUrl url(u"https://api.spotify.com/v1/me/player/devices"_s); - const auto callback = [](RestReply &&reply) { + const auto callback = [](const RestReply &reply) { const auto json = QJsonDocument::fromJson(reply.data()).object(); const auto devices = json["devices"_L1].toArray(); return SpotifyDevice::fromJson(devices); @@ -274,7 +274,7 @@ auto PlayerAPI::repeat(SpotifyRepeatMode mode, const QString &deviceId) const -> case SpotifyRepeatMode::Off: return repeat(u"off"_s, deviceId); default: - qCCritical(gmSpotifyPlayer()) << "repeat(): unknown repeat mode" << mode; + qCCritical(gmSpotifyPlayer()) << "repeat(): unknown repeat mode" << static_cast(mode); return {}; } } @@ -373,8 +373,8 @@ auto PlayerAPI::addToQueue(const QString &uri) const -> QFuture auto PlayerAPI::addToQueue(const QString &uri, const QString &deviceId) const -> QFuture { - const auto type = SpotifyUtils::getUriType(uri); - if (!(type == SpotifyUtils::SpotifyType::Track || type == SpotifyUtils::SpotifyType::Episode)) + if (const auto type = SpotifyUtils::getUriType(uri); + !(type == SpotifyUtils::SpotifyType::Track || type == SpotifyUtils::SpotifyType::Episode)) { qCWarning(gmSpotifyPlayer()) << R"(addToQueue(): "uri" must be a track or episode!)"; return {}; diff --git a/src/services/spotify/api/playerapi.h b/src/services/spotify/api/playerapi.h index 0de9cc35..f9289ecc 100644 --- a/src/services/spotify/api/playerapi.h +++ b/src/services/spotify/api/playerapi.h @@ -17,7 +17,6 @@ class Spotify; class PlayerAPI { - Q_GADGET friend Spotify; public: @@ -72,7 +71,7 @@ class PlayerAPI /// Get information about a user’s available devices [[nodiscard]] auto devices() -> QFuture; - enum SpotifyRepeatMode + enum class SpotifyRepeatMode { /// Repeat current track Track, @@ -81,7 +80,6 @@ class PlayerAPI /// Don't repeat Off }; - Q_ENUM(SpotifyRepeatMode) /// Set the repeat mode for the user's playback. Options are repeat-track, repeat-context, and off (current device) [[nodiscard]] auto repeat(SpotifyRepeatMode mode) const -> QFuture; diff --git a/src/services/spotify/api/playlistsapi.cpp b/src/services/spotify/api/playlistsapi.cpp index 5f7fe34a..adc94c24 100644 --- a/src/services/spotify/api/playlistsapi.cpp +++ b/src/services/spotify/api/playlistsapi.cpp @@ -30,7 +30,7 @@ auto PlaylistsAPI::getPlaylist(const QString &id) -> QFuture query.addQueryItem(u"market"_s, u"from_token"_s); url.setQuery(query); - const auto callback = [](RestReply &&reply) -> QFuture { + const auto callback = [](const RestReply &reply) -> QFuture { if (reply.hasError()) { qCWarning(gmSpotifyPlaylists()) << reply.errorText(); @@ -58,7 +58,7 @@ auto PlaylistsAPI::getPlaylistTracks(const QString &id) -> QFuture QFuture { + const auto callback = [this](const RestReply &reply) -> QFuture { if (reply.hasError()) { qCWarning(gmSpotifyPlaylists()) << reply.errorText(); @@ -80,7 +80,7 @@ auto PlaylistsAPI::getPlaylistTracks(SpotifyTrackList &&tracklist) -> QFuture QFuture query.addQueryItem(u"market"_s, u"from_token"_s); url.setQuery(query); - const auto callback = [](RestReply &&reply) -> QFuture { + const auto callback = [](const RestReply &reply) -> QFuture { if (reply.hasError()) { qCWarning(gmSpotifyTracks()) << "getTrack():" << reply.errorText(); @@ -66,7 +66,7 @@ auto TracksAPI::getTracks(const QStringList &ids, std::vector &&pr query.addQueryItem(u"market"_s, u"from_token"_s); url.setQuery(query); - const auto callback = [this, ids, previous = std::move(previous)](RestReply &&reply) mutable { + const auto callback = [this, ids, previous = std::move(previous)](const RestReply &reply) mutable { if (reply.hasError()) { qCWarning(gmSpotifyTracks()) << "getTracks():" << reply.errorText(); diff --git a/src/services/spotify/clients/abstractspotifyclientcontroller.cpp b/src/services/spotify/clients/abstractspotifyclientcontroller.cpp index 49a94d87..668bf1e1 100644 --- a/src/services/spotify/clients/abstractspotifyclientcontroller.cpp +++ b/src/services/spotify/clients/abstractspotifyclientcontroller.cpp @@ -20,7 +20,7 @@ AbstractSpotifyClientController::AbstractSpotifyClientController(QObject *parent auto AbstractSpotifyClientController::getDevice(const QString &name) -> QFuture { - const auto callback = [name](SpotifyDeviceList &&deviceList) { + const auto callback = [name](const SpotifyDeviceList &deviceList) { foreach (const auto &device, deviceList.devices) { if (device.name == name) return device; @@ -46,7 +46,7 @@ void AbstractSpotifyClientController::setActiveDevice(const SpotifyDevice &devic << "but it is inactive, setting as active device ..."; auto future = Spotify::instance()->player.transfer({device.id}); - const auto onReply = [this](RestReply &&reply) { + const auto onReply = [this](const RestReply &reply) { if (reply.hasError()) updateStatus(Status::Type::Error, reply.errorText()); }; diff --git a/src/services/spotify/clients/librespotcontroller.cpp b/src/services/spotify/clients/librespotcontroller.cpp index b054aedc..ce8f78cb 100644 --- a/src/services/spotify/clients/librespotcontroller.cpp +++ b/src/services/spotify/clients/librespotcontroller.cpp @@ -148,7 +148,7 @@ void LibrespotController::setAsActiveDevice() { qCDebug(gmLibrespotController()) << "Setting librespot instance as active device ..."; - const auto callback = [this](SpotifyDevice &&device) { + const auto callback = [this](const SpotifyDevice &device) { if (device.id.isEmpty()) { if (m_tryAgainIfSettingActiveFails) diff --git a/src/services/spotify/spotify.cpp b/src/services/spotify/spotify.cpp index 78f6c63b..ffa6d14a 100644 --- a/src/services/spotify/spotify.cpp +++ b/src/services/spotify/spotify.cpp @@ -99,7 +99,7 @@ auto Spotify::get(const QNetworkRequest &request, bool isAuthRequired) -> QFutur const auto callback = [this](RestReply &&reply) { handleNetworkError(reply); - return reply; + return std::move(reply); }; return m_connector->get(request, isAuthRequired).then(callback); @@ -116,7 +116,7 @@ auto Spotify::put(const QNetworkRequest &request, const QByteArray &data) -> QFu const auto callback = [this](RestReply &&reply) { handleNetworkError(reply); - return reply; + return std::move(reply); }; return m_connector->put(request, data).then(callback); @@ -133,7 +133,7 @@ auto Spotify::post(const QNetworkRequest &request, const QByteArray &data) -> QF const auto callback = [this](RestReply &&reply) { handleNetworkError(reply); - return reply; + return std::move(reply); }; return m_connector->post(request, data).then(callback); diff --git a/src/tools/audio/audiosaveload.cpp b/src/tools/audio/audiosaveload.cpp index 9f092100..41b38ba6 100644 --- a/src/tools/audio/audiosaveload.cpp +++ b/src/tools/audio/audiosaveload.cpp @@ -16,10 +16,13 @@ using namespace Files; Q_LOGGING_CATEGORY(gmAudioSaveLoad, "gm.audio.saveload") +static constexpr auto PROJECT_FILE_SUFFIX = ".audio"; + /** * @brief Find audio project files */ -auto AudioSaveLoad::findProjectsAsync(QObject *context, const QString &folder) -> QFuture> +auto AudioSaveLoad::findProjectsAsync(const QObject *context, const QString &folder) + -> QFuture> { qCDebug(gmAudioSaveLoad()) << "Finding audio projects ..."; @@ -38,7 +41,7 @@ auto AudioSaveLoad::loadProject(const QByteArray &data, QObject *parent) -> Audi return new AudioProject(doc.object(), parent); } -auto AudioSaveLoad::loadProjects(QObject *context, FileListResult &&files) -> QFuture> +auto AudioSaveLoad::loadProjects(const QObject *context, FileListResult &&files) -> QFuture> { QStringList fileNames; const auto filePaths = files.filesFull(); @@ -52,7 +55,7 @@ auto AudioSaveLoad::loadProjects(QObject *context, FileListResult &&files) -> QF auto futureContents = File::getDataAsync(fileNames); - return futureContents.then([context](std::vector &&contents) { + return futureContents.then([context](const std::vector &contents) { qCDebug(gmAudioSaveLoad()) << "Found audio projects."; std::vector projects; projects.reserve(contents.size()); @@ -77,7 +80,7 @@ auto AudioSaveLoad::findMissingFilesAsync(const QList &audioFiles, auto futureCheckResult = File::checkAsync(filePaths, true); return futureCheckResult - .then([audioFiles, basePath](FileMultiCheckResult &&multiResult) { + .then([audioFiles, basePath](const FileMultiCheckResult &multiResult) { const auto foundPaths = multiResult.existing(); for (auto *audioFile : audioFiles) @@ -149,9 +152,9 @@ auto AudioSaveLoad::saveProject(AudioProject *project, const QString &folder) -> auto AudioSaveLoad::saveProject(AudioProject *project, const QString &filePath, const QByteArray &data) -> QFuture { return File::saveAsync(filePath, data) - .then([project](FileResult &&result) { + .then([project](const FileResult &result) { project->isSaved(result.success()); - return true; + return result.success(); }) .onCanceled([]() { return false; }); } @@ -163,7 +166,7 @@ auto AudioSaveLoad::saveRenamedProject(AudioProject *project, const QString &fil auto future = File::moveAsync(filePathOld, filePath); return future - .then([filePath, data, project](FileResult &&result) { + .then([filePath, data, project](const FileResult &result) { if (!result.success()) return QtFuture::makeReadyFuture(false); project->wasRenamed(false); @@ -173,7 +176,7 @@ auto AudioSaveLoad::saveRenamedProject(AudioProject *project, const QString &fil .unwrap(); } -auto AudioSaveLoad::deleteProject(AudioProject *project, const QString &folder) -> QFuture +auto AudioSaveLoad::deleteProject(const AudioProject *project, const QString &folder) -> QFuture { if (!project) { @@ -181,7 +184,7 @@ auto AudioSaveLoad::deleteProject(AudioProject *project, const QString &folder) } auto filePath = getProjectFolder(folder) + "/" + project->name() + PROJECT_FILE_SUFFIX; - return File::deleteAsync(filePath).then([](FileResult &&result) { return result.success(); }).onCanceled([]() { + return File::deleteAsync(filePath).then([](const FileResult &result) { return result.success(); }).onCanceled([]() { return false; }); } diff --git a/src/tools/audio/audiosaveload.h b/src/tools/audio/audiosaveload.h index e0c5ae3b..dcc677c5 100644 --- a/src/tools/audio/audiosaveload.h +++ b/src/tools/audio/audiosaveload.h @@ -12,29 +12,25 @@ namespace Files class FileListResult; } -using namespace Qt::Literals::StringLiterals; - class AudioSaveLoad { public: AudioSaveLoad() = delete; - static auto findProjectsAsync(QObject *context, const QString &folder = u""_s) + static auto findProjectsAsync(const QObject *context, const QString &folder = QLatin1String()) -> QFuture>; static auto loadProject(const QByteArray &data, QObject *parent) -> AudioProject *; - static auto findMissingFilesAsync(const QList &audioFiles, const QString &basePath) - -> QFuture; + static auto findMissingFilesAsync(const QList &audioFiles, const QString &basePath) -> QFuture; - static auto saveProject(AudioProject *project, const QString &folder = u""_s) -> QFuture; + static auto saveProject(AudioProject *project, const QString &folder = QLatin1String()) -> QFuture; - static auto deleteProject(AudioProject *project, const QString &folder = u""_s) -> QFuture; + static auto deleteProject(const AudioProject *project, const QString &folder = QLatin1String()) -> QFuture; private: - static constexpr const auto PROJECT_FILE_SUFFIX = ".audio"; - - static auto loadProjects(QObject *context, Files::FileListResult &&files) -> QFuture>; + static auto loadProjects(const QObject *context, Files::FileListResult &&files) + -> QFuture>; static auto getFilePathsToCheck(const QList &audioFiles, const QString &basePath) -> QStringList; static auto saveProject(AudioProject *project, const QString &filePath, const QByteArray &data) -> QFuture; diff --git a/src/tools/audio/audiotool.cpp b/src/tools/audio/audiotool.cpp index 5d22935f..5bf130e8 100644 --- a/src/tools/audio/audiotool.cpp +++ b/src/tools/audio/audiotool.cpp @@ -119,7 +119,7 @@ void AudioTool::setCurrentProject(int index) emit currentProjectChanged(a_currentProject); } -auto AudioTool::getCurrentProjectIndex() -> int +auto AudioTool::getCurrentProjectIndex() const -> qsizetype { if (!currentProject()) return 0; @@ -178,13 +178,9 @@ void AudioTool::onStateChanged(AudioPlayer::State state) */ void AudioTool::next() { - switch (m_musicElementType) + if (m_musicElementType == AudioElement::Type::Music) { - case AudioElement::Type::Music: musicPlayer.next(); - break; - default: - return; } } @@ -239,13 +235,9 @@ void AudioTool::stop() */ void AudioTool::again() { - switch (m_musicElementType) + if (m_musicElementType == AudioElement::Type::Music) { - case AudioElement::Type::Music: musicPlayer.again(); - break; - default: - break; } } @@ -253,7 +245,7 @@ void AudioTool::again() * @brief Set volume of music players (music, radio) * @param volume Volume, float between 0 and 1 */ -void AudioTool::setMusicVolume(qreal volume) +void AudioTool::setMusicVolume(float volume) { // Convert volume to logarithmic scale auto logarithmicVolume = makeLogarithmicVolume(volume); @@ -274,7 +266,7 @@ void AudioTool::setMusicVolume(qreal volume) * @brief Set volume of sound players * @param volume Volume, float between 0 and 1 */ -void AudioTool::setSoundVolume(qreal volume) +void AudioTool::setSoundVolume(float volume) { auto linearVolume = makeLinearVolume(volume); auto logarithmicVolume = makeLogarithmicVolume(volume); @@ -283,12 +275,12 @@ void AudioTool::setSoundVolume(qreal volume) soundPlayerController.setVolume(linearVolume, logarithmicVolume); } -auto AudioTool::makeLinearVolume(qreal linearVolume) -> int +auto AudioTool::makeLinearVolume(float linearVolume) -> int { return qRound(linearVolume * VOLUME_FACTOR); } -auto AudioTool::makeLogarithmicVolume(qreal linearVolume) -> int +auto AudioTool::makeLogarithmicVolume(float linearVolume) -> int { return qRound(QAudio::convertVolume(linearVolume, QAudio::LogarithmicVolumeScale, QAudio::LinearVolumeScale) * VOLUME_FACTOR); @@ -296,13 +288,12 @@ auto AudioTool::makeLogarithmicVolume(qreal linearVolume) -> int auto AudioTool::playlistQml() -> QQmlListProperty { - switch (m_musicElementType) + if (m_musicElementType == AudioElement::Type::Music) { - case AudioElement::Type::Music: return musicPlayer.playlistQml(); - default: - return {}; } + + return {}; } /** @@ -311,14 +302,13 @@ auto AudioTool::playlistQml() -> QQmlListProperty */ auto AudioTool::index() const -> int { - switch (m_musicElementType) + if (m_musicElementType == AudioElement::Type::Music) { - case AudioElement::Type::Music: qCDebug(gmAudioTool()) << musicPlayer.playlistIndex(); return musicPlayer.playlistIndex(); - default: - return 0; } + + return 0; } /** @@ -327,13 +317,9 @@ auto AudioTool::index() const -> int */ void AudioTool::setMusicIndex(int index) { - switch (m_musicElementType) + if (m_musicElementType == AudioElement::Type::Music) { - case AudioElement::Type::Music: musicPlayer.setIndex(index); - break; - default: - return; } } diff --git a/src/tools/audio/audiotool.h b/src/tools/audio/audiotool.h index 3bf8cb5c..c18bfd1a 100644 --- a/src/tools/audio/audiotool.h +++ b/src/tools/audio/audiotool.h @@ -50,7 +50,7 @@ class AudioTool : public AbstractTool // Project void updateProjectList(); Q_INVOKABLE void setCurrentProject(int index); - Q_INVOKABLE int getCurrentProjectIndex(); + Q_INVOKABLE qsizetype getCurrentProjectIndex() const; [[nodiscard]] auto soundController() -> SoundPlayerController * { @@ -62,13 +62,13 @@ class AudioTool : public AbstractTool { return m_musicVolume; } - Q_INVOKABLE void setMusicVolume(qreal volume); + Q_INVOKABLE void setMusicVolume(float volume); [[nodiscard]] auto soundVolume() const -> qreal { return m_soundVolume; } - Q_INVOKABLE void setSoundVolume(qreal volume); + Q_INVOKABLE void setSoundVolume(float volume); // Playback control Q_INVOKABLE void play(AudioElement *element); @@ -129,13 +129,13 @@ private slots: AudioElement::Type m_musicElementType = AudioElement::Type::Music; // Volume - static constexpr qreal DEFAULT_MUSIC_VOLUME = 0.25; - static constexpr qreal DEFAULT_SOUND_VOLUME = 0.25; + static constexpr float DEFAULT_MUSIC_VOLUME = 0.25; + static constexpr float DEFAULT_SOUND_VOLUME = 0.25; static constexpr int VOLUME_FACTOR = 100; - qreal m_musicVolume = DEFAULT_MUSIC_VOLUME; - qreal m_soundVolume = DEFAULT_SOUND_VOLUME; + float m_musicVolume = DEFAULT_MUSIC_VOLUME; + float m_soundVolume = DEFAULT_SOUND_VOLUME; - static auto makeLinearVolume(qreal linearVolume) -> int; - static auto makeLogarithmicVolume(qreal linearVolume) -> int; + static auto makeLinearVolume(float linearVolume) -> int; + static auto makeLogarithmicVolume(float linearVolume) -> int; }; diff --git a/src/tools/audio/editor/audioeditor.cpp b/src/tools/audio/editor/audioeditor.cpp index b69bdc31..046a5a08 100644 --- a/src/tools/audio/editor/audioeditor.cpp +++ b/src/tools/audio/editor/audioeditor.cpp @@ -123,7 +123,7 @@ void AudioEditor::createProject(const QString &name) madeChanges(); } -void AudioEditor::createProjectFromTemplate(AudioProject *other) +void AudioEditor::createProjectFromTemplate(const AudioProject *other) { if (!other) return; @@ -239,7 +239,7 @@ void AudioEditor::createCategory(const QString &name) } } -void AudioEditor::createCategoryFromTemplate(AudioCategory *other) +void AudioEditor::createCategoryFromTemplate(const AudioCategory *other) { if (!m_currentProject || !other) return; @@ -283,7 +283,7 @@ void AudioEditor::deleteCategory() if (!categoryExists()) return; auto *category = m_currentProject->currentCategory(); - auto *scenario = category->currentScenario(); + const auto *scenario = category->currentScenario(); qCDebug(gmAudioEditor) << "Deleting current category:" << category->name() << "..."; @@ -310,7 +310,7 @@ void AudioEditor::setCurrentScenario(int index) { if (!categoryExists()) return; - auto *category = m_currentProject->currentCategory(); + const auto *category = m_currentProject->currentCategory(); if (!Utils::isInBounds(category->scenarios(), index)) { @@ -359,7 +359,7 @@ void AudioEditor::onCurrentScenarioChanged() const */ void AudioEditor::onProjectSavedChanged() { - auto *project = qobject_cast(sender()); + const auto *project = qobject_cast(sender()); if (project && !project->isSaved()) { madeChanges(); @@ -402,7 +402,7 @@ void AudioEditor::createScenario(const QString &name, bool isSubscenario) const } } -void AudioEditor::createScenarioFromTemplate(AudioScenario *other, bool isSubscenario) +void AudioEditor::createScenarioFromTemplate(const AudioScenario *other, bool isSubscenario) { if (!categoryExists() || !other) return; @@ -501,12 +501,9 @@ void AudioEditor::deleteSubScenario(AudioScenario *subscenario) qCWarning(gmAudioEditor()) << "Error: Could not delete subscenario" << subscenario->name(); } - if (m_currentElement.isNull()) + if (m_currentElement.isNull() && !loadFirstElement(scenario)) { - if (!loadFirstElement(scenario)) - { - emit currentElementChanged(); - } + emit currentElementChanged(); } } @@ -560,7 +557,7 @@ void AudioEditor::loadElement(QObject *element) /** * @brief Load the first element of a scenario. */ -auto AudioEditor::loadFirstElement(AudioScenario *scenario) -> bool +auto AudioEditor::loadFirstElement(const AudioScenario *scenario) -> bool { if (!scenario) { @@ -573,11 +570,9 @@ auto AudioEditor::loadFirstElement(AudioScenario *scenario) -> bool scenario = m_currentProject->currentScenario(); } - auto elements = scenario->elements(true); - - if (!elements.isEmpty()) + if (const auto elements = scenario->elements(true); !elements.isEmpty()) { - loadElement(elements.first()); + loadElement(elements.constFirst()); return true; } @@ -595,7 +590,7 @@ void AudioEditor::clearCurrentElement() emit currentElementChanged(); } -void AudioEditor::createElement(const QString &name, AudioElement::Type type, int subscenario) +void AudioEditor::createElement(const QString &name, AudioElement::Type type, int subscenario) const { if (!scenarioExists() || name.isEmpty()) return; @@ -607,8 +602,7 @@ void AudioEditor::createElement(const QString &name, AudioElement::Type type, in auto path = scenario->path(); // index -1 means no subscenario - const auto subscenarios = scenario->scenarios(); - if (Utils::isInBounds(subscenarios, subscenario)) + if (const auto subscenarios = scenario->scenarios(); Utils::isInBounds(subscenarios, subscenario)) { scenario = subscenarios[subscenario]; } @@ -618,7 +612,7 @@ void AudioEditor::createElement(const QString &name, AudioElement::Type type, in onCurrentScenarioChanged(); } -void AudioEditor::createElementFromTemplate(AudioElement *other, int subscenario) +void AudioEditor::createElementFromTemplate(const AudioElement *other, int subscenario) const { if (!scenarioExists() || !other) return; @@ -629,8 +623,7 @@ void AudioEditor::createElementFromTemplate(AudioElement *other, int subscenario if (!scenario) return; // index -1 means no subscenario - const auto subscenarios = scenario->scenarios(); - if (Utils::isInBounds(subscenarios, subscenario)) + if (const auto subscenarios = scenario->scenarios(); Utils::isInBounds(subscenarios, subscenario)) { scenario = subscenarios[subscenario]; } @@ -683,7 +676,6 @@ void AudioEditor::deleteCurrentElement() qCWarning(gmAudioEditor()) << "Error: Could not delete element, no scenario selected."; } - // m_currentElement.clear(); emit currentElementChanged(); } @@ -711,26 +703,29 @@ void AudioEditor::saveProject() { qCDebug(gmAudioEditor) << "Saving projects ..."; - if (!a_projects.empty()) + if (a_projects.empty()) { - foreach (auto *project, a_projects) + isSaved(true); + return; + } + + foreach (auto *project, a_projects) + { + if (project == m_currentProject) { - if (project == m_currentProject) - { - emit showInfoBar(tr("Saving ...")); - - AudioSaveLoad::saveProject(project) - .then([this](bool success) { - if (success) emit showInfoBar(tr("Saved!")); - else - emit showInfoBar(tr("Error: Could not save project!")); - }) - .onCanceled([this]() { emit showInfoBar(tr("Error: Could not save project!")); }); - } - else - { - AudioSaveLoad::saveProject(project); - } + emit showInfoBar(tr("Saving ...")); + + AudioSaveLoad::saveProject(project) + .then([this](bool success) { + if (success) emit showInfoBar(tr("Saved!")); + else + emit showInfoBar(tr("Error: Could not save project!")); + }) + .onCanceled([this]() { emit showInfoBar(tr("Error: Could not save project!")); }); + } + else + { + AudioSaveLoad::saveProject(project); } } @@ -782,9 +777,7 @@ auto AudioEditor::addUrl(const QString &url, int mode, const QString &title) -> AudioFile *audioFile = nullptr; - const auto isSpotify = mode == 1; - - if (isSpotify) + if (const auto isSpotify = mode == 1; isSpotify) { audioFile = new AudioFile(SpotifyUtils::makeUri(url), AudioFile::Source::Spotify, title, m_currentElement); } @@ -809,17 +802,12 @@ auto AudioEditor::addYtUrl(const QString &videoUrl) -> bool qCDebug(gmAudioEditor) << "Adding YouTube URL to element" << QString(*m_currentElement) << ":" << videoUrl; - auto *audioFile = new AudioFile(videoUrl, AudioFile::Source::Youtube, u""_s, m_currentElement); - if (!addAudioFile(audioFile)) return false; + if (auto *audioFile = new AudioFile(videoUrl, AudioFile::Source::Youtube, u""_s, m_currentElement); + !addAudioFile(audioFile)) + return false; qCWarning(gmAudioEditor()) << "Youtube integration is broken!"; - // auto *video = ytClient->getVideo(videoUrl); - // connect(video, &YouTube::Videos::Video::ready, audioFile, [audioFile, video]() { - // audioFile->title(video->title()); - // video->deleteLater(); - // }); - return true; } @@ -890,17 +878,17 @@ void AudioEditor::removeMissingFiles() auto files = m_currentElement->files(); QList indices; - for (int i = files.length() - 1; i > 0; i--) + for (auto i = files.length() - 1; i > 0; i--) { const auto *file = files.at(i); if (file && file->missing()) { - indices.prepend(i); + indices.prepend(static_cast(i)); } } - foreach (const int index, indices) + foreach (const auto index, indices) { removeFile(index, false); } @@ -930,7 +918,7 @@ void AudioEditor::moveFile(int index, int positions) * @param index Index of the file to change * @param folder New folder where file can be found */ -void AudioEditor::replaceFileFolder(int index, const QString &folder) +void AudioEditor::replaceFileFolder(int index, const QString &folder) const { if (!m_currentElement || !scenarioExists()) return; diff --git a/src/tools/audio/editor/audioeditor.h b/src/tools/audio/editor/audioeditor.h index 808ddc2c..1200ac98 100644 --- a/src/tools/audio/editor/audioeditor.h +++ b/src/tools/audio/editor/audioeditor.h @@ -62,7 +62,7 @@ class AudioEditor : public AbstractTool // Project Q_INVOKABLE void setCurrentProject(int index); Q_INVOKABLE void createProject(const QString &name); - Q_INVOKABLE void createProjectFromTemplate(AudioProject *other); + Q_INVOKABLE void createProjectFromTemplate(const AudioProject *other); Q_INVOKABLE void renameProject(const QString &name); Q_INVOKABLE void deleteProject(); Q_INVOKABLE void saveProject(); @@ -77,7 +77,7 @@ class AudioEditor : public AbstractTool Q_INVOKABLE void setCurrentCategory(int index); Q_INVOKABLE void setCurrentCategory(AudioCategory *category); Q_INVOKABLE void createCategory(const QString &name); - Q_INVOKABLE void createCategoryFromTemplate(AudioCategory *other); + Q_INVOKABLE void createCategoryFromTemplate(const AudioCategory *other); Q_INVOKABLE void renameCategory(const QString &name); Q_INVOKABLE void deleteCategory(); @@ -85,7 +85,7 @@ class AudioEditor : public AbstractTool Q_INVOKABLE void setCurrentScenario(int index); Q_INVOKABLE void setCurrentScenario(AudioScenario *scenario); Q_INVOKABLE void createScenario(const QString &name, bool isSubscenario = false) const; - Q_INVOKABLE void createScenarioFromTemplate(AudioScenario *other, bool isSubscenario); + Q_INVOKABLE void createScenarioFromTemplate(const AudioScenario *other, bool isSubscenario); Q_INVOKABLE void renameScenario(const QString &name) const; Q_INVOKABLE void deleteScenario(); Q_INVOKABLE void deleteSubScenario(AudioScenario *subscenario); @@ -98,14 +98,14 @@ class AudioEditor : public AbstractTool Q_INVOKABLE void setSubscenario(int index) const; // Create new element - Q_INVOKABLE void createElement(const QString &name, AudioElement::Type type, int subscenario); - Q_INVOKABLE void createElementFromTemplate(AudioElement *other, int subscenario); + Q_INVOKABLE void createElement(const QString &name, AudioElement::Type type, int subscenario) const; + Q_INVOKABLE void createElementFromTemplate(const AudioElement *other, int subscenario) const; // Edit element Q_INVOKABLE void removeFile(int index, bool findMissing = true); Q_INVOKABLE void moveFile(int index, int positions); Q_INVOKABLE void removeMissingFiles(); - Q_INVOKABLE void replaceFileFolder(int index, const QString &folder); + Q_INVOKABLE void replaceFileFolder(int index, const QString &folder) const; Q_INVOKABLE bool addFile(QStringList path, const QString &filename); Q_INVOKABLE bool addUrl(const QString &url, int mode, const QString &title = QLatin1String()); Q_INVOKABLE bool addYtUrl(const QString &videoUrl); @@ -159,7 +159,7 @@ public slots: AudioProject *m_currentProject = nullptr; QPointer m_currentElement; - auto loadFirstElement(AudioScenario *scenario = nullptr) -> bool; + auto loadFirstElement(const AudioScenario *scenario = nullptr) -> bool; void clearCurrentElement(); int m_fileIndex{}; diff --git a/src/tools/audio/editor/audioeditorfilebrowser.cpp b/src/tools/audio/editor/audioeditorfilebrowser.cpp index 341a063d..c08d021a 100644 --- a/src/tools/audio/editor/audioeditorfilebrowser.cpp +++ b/src/tools/audio/editor/audioeditorfilebrowser.cpp @@ -30,12 +30,13 @@ void AudioEditorFileBrowser::addFiles(const QStringList &path, int index, bool f qCDebug(gmAudioEditorFileBrowser()) << "Adding files:" << m_basePath << path << index << folders; const auto dir = FileUtils::fileInDir(FileUtils::dirFromFolders(path), m_basePath); - Files::File::listAsync(dir, !folders, folders).then([this, path, folders, index](Files::FileListResult &&result) { - if (!result.success()) return; + Files::File::listAsync(dir, !folders, folders) + .then([this, path, folders, index](const Files::FileListResult &result) { + if (!result.success()) return; - addFilesToModel(folders ? result.folders() : result.files(), path, folders ? 3 : static_cast(type()), - index); - }); + addFilesToModel(folders ? result.folders() : result.files(), path, folders ? 3 : static_cast(type()), + index); + }); } void AudioEditorFileBrowser::addFilesToModel(const QStringList &files, const QStringList &path, int type, int index) @@ -110,9 +111,8 @@ void AudioEditorFileBrowser::openFolder(bool open, const QString &folder, const foreach (auto *element, m_fileModel.elements()) { - auto *file = qobject_cast(element); - - if ((file->name() == folder) && (file->path() == path)) + if (const auto *file = qobject_cast(element); + (file->name() == folder) && (file->path() == path)) { if (open) { @@ -151,7 +151,7 @@ void AudioEditorFileBrowserModel::append(QObject *item) emit isEmptyChanged(); } -void AudioEditorFileBrowserModel::remove(QObject *item) +void AudioEditorFileBrowserModel::remove(const QObject *item) { for (int i = 0; i < m_items.size(); ++i) { @@ -179,7 +179,7 @@ void AudioEditorFileBrowserModel::clear() { if (m_items.isEmpty()) return; - beginRemoveRows(QModelIndex(), 0, m_items.count() - 1); + beginRemoveRows(QModelIndex(), 0, static_cast(m_items.count()) - 1); while (!m_items.empty()) { @@ -195,9 +195,9 @@ void AudioEditorFileBrowserModel::setElements(const QList &el { clear(); - for (int i = elements.size() - 1; i > -1; i--) + for (auto i = elements.size() - 1; i > -1; i--) { - append(elements[i]); + append(elements.at(i)); } emit isEmptyChanged(); diff --git a/src/tools/audio/editor/audioeditorfilebrowser.h b/src/tools/audio/editor/audioeditorfilebrowser.h index 60d29a31..e7a40d49 100644 --- a/src/tools/audio/editor/audioeditorfilebrowser.h +++ b/src/tools/audio/editor/audioeditorfilebrowser.h @@ -27,7 +27,7 @@ class AudioEditorFile : public QObject { } - [[nodiscard]] auto depth() const -> int + [[nodiscard]] auto depth() const -> qsizetype { return path().count(); } @@ -44,7 +44,7 @@ class AudioEditorFileBrowserModel : public QAbstractListModel [[nodiscard]] auto rowCount(const QModelIndex &) const -> int override { - return m_items.size(); + return static_cast(m_items.size()); } [[nodiscard]] auto data(const QModelIndex &index, int role) const -> QVariant override; @@ -70,7 +70,7 @@ class AudioEditorFileBrowserModel : public QAbstractListModel } void insert(int index, QObject *item); - void remove(QObject *item); + void remove(const QObject *item); void append(QObject *item); signals: diff --git a/src/tools/audio/editor/audioexporter.cpp b/src/tools/audio/editor/audioexporter.cpp index 268f4e3c..7cfbb084 100644 --- a/src/tools/audio/editor/audioexporter.cpp +++ b/src/tools/audio/editor/audioexporter.cpp @@ -5,6 +5,8 @@ #include "utils/fileutils.h" #include +using namespace Qt::Literals::StringLiterals; + Q_LOGGING_CATEGORY(gmAudioExporter, "gm.audio.exporter") /** @@ -29,7 +31,7 @@ void AudioExporter::exportFiles() auto *worker = new Worker(m_path, m_project); worker->moveToThread(&workerThread); - connect(worker, &Worker::copiedFiles, [=]() { worker->deleteLater(); }); + connect(worker, &Worker::copiedFiles, [worker]() { worker->deleteLater(); }); connect(worker, &Worker::progressChanged, this, &AudioExporter::updateProgress); connect(this, &AudioExporter::startCopying, worker, &Worker::startCopying); workerThread.start(); @@ -39,7 +41,11 @@ void AudioExporter::exportFiles() void AudioExporter::updateProgress(float progress) { m_progress = progress; - if (m_progress >= 1) m_progress = 0; + if (m_progress >= 1) + { + m_progress = 0; + } + emit progressChanged(); } @@ -78,9 +84,7 @@ void Worker::collectFilesToExport() { if (Q_UNLIKELY(!m_project)) return; - // Categories - const auto categories = m_project->categories(); - for (auto *category : categories) + foreach (const auto *category, m_project->categories()) { if (category && category->isChecked() != TreeItem::CheckedState::Unchecked) { @@ -101,7 +105,7 @@ auto Worker::copyNext() -> bool { if (m_fileCount > 0) { - const float percent = static_cast(m_exportCount++) / m_fileCount; + const float percent = static_cast(m_exportCount++) / static_cast(m_fileCount); emit progressChanged(percent); qCDebug(gmAudioExporter()) << " Progress:" << m_exportCount << "/" << m_fileCount << "(" << percent * 100 << "%)"; @@ -157,16 +161,15 @@ auto Worker::copyFile(const QString &filePath, const QString &base, const QStrin return true; } -void Worker::copyElements(AudioScenario *scenario) +void Worker::copyElements(const AudioScenario *scenario) { if (Q_UNLIKELY(!scenario)) return; - for (auto *element : scenario->elements(true)) + foreach (const auto *element, scenario->elements(true)) { if (element && element->isChecked() != TreeItem::CheckedState::Unchecked) { - const auto files = element->files(); - for (auto *file : files) + foreach (const auto *file, element->files()) { // Only export local files if (file->source() != AudioFile::Source::File) continue; diff --git a/src/tools/audio/editor/audioexporter.h b/src/tools/audio/editor/audioexporter.h index 9cf82d19..6a634808 100644 --- a/src/tools/audio/editor/audioexporter.h +++ b/src/tools/audio/editor/audioexporter.h @@ -7,8 +7,6 @@ #include #include -using namespace Qt::Literals::StringLiterals; - class Worker : public QObject { Q_OBJECT @@ -30,10 +28,10 @@ public slots: QQueue m_soundFiles; QQueue m_radioFiles; - int m_fileCount = 0; - int m_exportCount = 0; + qsizetype m_fileCount = 0; + qsizetype m_exportCount = 0; - void copyElements(AudioScenario *scenario); + void copyElements(const AudioScenario *scenario); void collectFilesToExport(); auto copyNext() -> bool; @@ -90,7 +88,7 @@ class AudioExporter : public QObject QPointer m_model = nullptr; float m_progress = 0; - QString m_path = u""_s; + QString m_path; public slots: void updateProgress(float progress); diff --git a/src/tools/audio/editor/unsplash/unsplashimage.cpp b/src/tools/audio/editor/unsplash/unsplashimage.cpp index 44fda56a..0e9f4323 100644 --- a/src/tools/audio/editor/unsplash/unsplashimage.cpp +++ b/src/tools/audio/editor/unsplash/unsplashimage.cpp @@ -18,7 +18,7 @@ void ImageListModel::insert(QObject *item) endInsertRows(); } -void ImageListModel::remove(QObject *item) +void ImageListModel::remove(const QObject *item) { for (int i = 0; i < m_items.size(); ++i) { @@ -52,8 +52,8 @@ void ImageListModel::setElements(QList elements) { clear(); - for (int i = elements.size() - 1; i > -1; i--) + for (auto i = elements.size() - 1; i > -1; i--) { - insert(elements[i]); + insert(elements.at(i)); } } diff --git a/src/tools/audio/editor/unsplash/unsplashimage.h b/src/tools/audio/editor/unsplash/unsplashimage.h index 7574b78a..9a57ca86 100644 --- a/src/tools/audio/editor/unsplash/unsplashimage.h +++ b/src/tools/audio/editor/unsplash/unsplashimage.h @@ -43,7 +43,7 @@ class ImageListModel : public QAbstractListModel [[nodiscard]] auto rowCount(const QModelIndex &) const -> int override { - return m_items.size(); + return static_cast(m_items.size()); } [[nodiscard]] auto data(const QModelIndex &index, int role) const -> QVariant override; @@ -52,7 +52,7 @@ class ImageListModel : public QAbstractListModel public slots: void insert(QObject *item); - void remove(QObject *item); + void remove(const QObject *item); protected: [[nodiscard]] auto roleNames() const -> QHash override; diff --git a/src/tools/audio/editor/unsplash/unsplashparser.cpp b/src/tools/audio/editor/unsplash/unsplashparser.cpp index f0f751fa..b68c76eb 100644 --- a/src/tools/audio/editor/unsplash/unsplashparser.cpp +++ b/src/tools/audio/editor/unsplash/unsplashparser.cpp @@ -14,9 +14,9 @@ using namespace Qt::Literals::StringLiterals; Q_LOGGING_CATEGORY(gmUnsplashParser, "gm.unsplash.parser") -UnsplashParser::UnsplashParser(QQmlEngine *engine, QObject *parent) : QObject(parent) +UnsplashParser::UnsplashParser(const QQmlEngine *engine, QObject *parent) + : QObject(parent), m_networkManager(engine->networkAccessManager()) { - m_networkManager = engine->networkAccessManager(); parse(); } @@ -27,12 +27,12 @@ auto UnsplashParser::model() -> ImageListModel * void UnsplashParser::parse() { - QNetworkRequest request(QUrl("https://gist.githubusercontent.com/PhilInTheGaps/0d61b30b0f5ccc00f4abd81566a4cf77/" - "raw/gm-companion-unsplash.json")); + QNetworkRequest request(QUrl( + u"https://gist.githubusercontent.com/PhilInTheGaps/0d61b30b0f5ccc00f4abd81566a4cf77/raw/gm-companion-unsplash.json"_s)); auto reply = m_networkManager->get(request); - connect(reply, &QNetworkReply::finished, this, [=]() { + connect(reply, &QNetworkReply::finished, this, [this, reply]() { qCDebug(gmUnsplashParser()) << "Received Unsplash JSON file."; if (reply->error() != QNetworkReply::NoError) diff --git a/src/tools/audio/editor/unsplash/unsplashparser.h b/src/tools/audio/editor/unsplash/unsplashparser.h index 66ae49ef..56f4a9a7 100644 --- a/src/tools/audio/editor/unsplash/unsplashparser.h +++ b/src/tools/audio/editor/unsplash/unsplashparser.h @@ -16,7 +16,7 @@ class UnsplashParser : public QObject Q_PROPERTY(ImageListModel *model READ model CONSTANT) public: - explicit UnsplashParser(QQmlEngine *engine, QObject *parent = nullptr); + explicit UnsplashParser(const QQmlEngine *engine, QObject *parent = nullptr); [[nodiscard]] auto model() -> ImageListModel *; diff --git a/src/tools/audio/metadata/metadatareader.cpp b/src/tools/audio/metadata/metadatareader.cpp index 664b1778..5f71b99c 100644 --- a/src/tools/audio/metadata/metadatareader.cpp +++ b/src/tools/audio/metadata/metadatareader.cpp @@ -17,13 +17,6 @@ void MetaDataReader::setMetaData(const AudioMetaData &metaData) m_metaData.apply(metaData); } -// void MetaDataReader::updateMetaData(QMediaPlayer *mediaPlayer) -//{ -// if (!m_metaData) m_metaData = new AudioMetaData(this); - -// setDuration(mediaPlayer->duration() * 1000); -//} - void MetaDataReader::setMetaData(QMediaMetaData::Key key, const QVariant &value) { if (!value.isValid() || value.isNull()) return; @@ -135,26 +128,31 @@ void MetaDataReader::setMetaData(const QString &key, const QVariant &value) void MetaDataReader::loadMetaData(const QString &path, const QByteArray &data) { - const TagLib::ByteVector bvector(data.data(), data.length()); + const TagLib::ByteVector bvector(data.data(), static_cast(data.length())); auto bvstream = std::make_unique(bvector); const TagLib::FileRef ref(bvstream.get()); - auto *tag = ref.tag(); + const auto *tag = ref.tag(); if (!tag || tag->isEmpty()) return; qCDebug(gmAudioMetaData()) << "Updating meta data from data ..."; - auto title = tag->title(); - if (!title.isEmpty()) m_metaData.title(QString::fromStdString(title.to8Bit(true))); + if (auto title = tag->title(); !title.isEmpty()) + { + m_metaData.title(QString::fromStdString(title.to8Bit(true))); + } - auto artist = tag->artist(); - if (!artist.isEmpty()) m_metaData.artist(QString::fromStdString(artist.to8Bit(true)).split(", ")); + if (auto artist = tag->artist(); !artist.isEmpty()) + { + m_metaData.artist(QString::fromStdString(artist.to8Bit(true)).split(", ")); + } - auto album = tag->album(); - if (!album.isEmpty()) m_metaData.album(QString::fromStdString(album.to8Bit(true))); + if (auto album = tag->album(); !album.isEmpty()) + { + m_metaData.album(QString::fromStdString(album.to8Bit(true))); + } - auto pixmap = TagImageLoader::loadFromData(path, std::move(bvstream)); - if (!pixmap.isNull()) + if (auto pixmap = TagImageLoader::loadFromData(path, std::move(bvstream)); !pixmap.isNull()) { m_metaData.cover(StringUtils::stringFromImage(pixmap)); } diff --git a/src/tools/audio/mpris/mprismanager.cpp b/src/tools/audio/mpris/mprismanager.cpp index d9416db2..9c31c597 100644 --- a/src/tools/audio/mpris/mprismanager.cpp +++ b/src/tools/audio/mpris/mprismanager.cpp @@ -34,7 +34,7 @@ void MprisManager::setPlaybackStatus(AudioPlayer::State status) sendMprisUpdateSignal(u"PlaybackStatus"_s, m_mprisPlayerAdaptor->playbackStatus()); } -void MprisManager::setVolume(double volume) +void MprisManager::setVolume(double volume) const { m_mprisPlayerAdaptor->setVolume(volume); } diff --git a/src/tools/audio/mpris/mprismanager.h b/src/tools/audio/mpris/mprismanager.h index 5438a6d4..624b860a 100644 --- a/src/tools/audio/mpris/mprismanager.h +++ b/src/tools/audio/mpris/mprismanager.h @@ -14,7 +14,7 @@ class MprisManager : public QObject explicit MprisManager(QObject *parent = nullptr); void setPlaybackStatus(AudioPlayer::State status); - void setVolume(double volume); + void setVolume(double volume) const; void setMetaDataReader(MetaDataReader *reader); signals: diff --git a/src/tools/audio/mpris/mprisplayeradaptor.h b/src/tools/audio/mpris/mprisplayeradaptor.h index 7d0dd6e1..5e7ad768 100644 --- a/src/tools/audio/mpris/mprisplayeradaptor.h +++ b/src/tools/audio/mpris/mprisplayeradaptor.h @@ -45,7 +45,7 @@ class MprisPlayerAdaptor : public QDBusAbstractAdaptor { /* Not Implemented */ } - [[nodiscard]] auto rate() -> double + [[nodiscard]] auto rate() const -> double { return 1.0; } @@ -72,7 +72,7 @@ class MprisPlayerAdaptor : public QDBusAbstractAdaptor return m_Volume; } void setVolume(double /*volume*/) const - { + { /* Not Implemented */ } [[nodiscard]] auto position() const -> qlonglong diff --git a/src/tools/audio/players/bufferedaudioplayer.cpp b/src/tools/audio/players/bufferedaudioplayer.cpp index f10cedb3..991f46ba 100644 --- a/src/tools/audio/players/bufferedaudioplayer.cpp +++ b/src/tools/audio/players/bufferedaudioplayer.cpp @@ -38,7 +38,7 @@ auto BufferedAudioPlayer::element() const -> QPointer return m_element; } -void BufferedAudioPlayer::setIndex(int index) +void BufferedAudioPlayer::setIndex(qsizetype index) { playlistIndex(index); @@ -112,7 +112,7 @@ void BufferedAudioPlayer::handleUnsupportedMediaSource(const AudioFile &file) next(); } -void BufferedAudioPlayer::onFileReceived(Files::FileDataResult &&result) +void BufferedAudioPlayer::onFileReceived(const Files::FileDataResult &result) { if (!result.success() || result.data().isEmpty()) { diff --git a/src/tools/audio/players/bufferedaudioplayer.h b/src/tools/audio/players/bufferedaudioplayer.h index 87ac8410..e0b7f2c2 100644 --- a/src/tools/audio/players/bufferedaudioplayer.h +++ b/src/tools/audio/players/bufferedaudioplayer.h @@ -25,7 +25,7 @@ class BufferedAudioPlayer : public AudioPlayer QML_UNCREATABLE("") Q_PROPERTY(QQmlListProperty playlist READ playlistQml NOTIFY playlistChanged FINAL) - AUTO_PROPERTY_VAL2(int, playlistIndex, 0); + AUTO_PROPERTY_VAL2(qsizetype, playlistIndex, 0); public: explicit BufferedAudioPlayer(const QString &settingsId, QNetworkAccessManager &networkManager, QObject *parent); @@ -33,7 +33,7 @@ class BufferedAudioPlayer : public AudioPlayer [[nodiscard]] auto playlistQml() -> QQmlListProperty; [[nodiscard]] auto element() const -> QPointer; - void setIndex(int index); + void setIndex(qsizetype index); public slots: virtual void play(AudioElement *element); @@ -53,7 +53,7 @@ public slots: void play(const QByteArray &data); auto loadPlaylist() -> QFuture; virtual void handleUnsupportedMediaSource(const AudioFile &file); - void onFileReceived(Files::FileDataResult &&result); + void onFileReceived(const Files::FileDataResult &result); [[nodiscard]] auto fileSource() const -> AudioFile::Source; void setPlaylist(std::unique_ptr playlist); diff --git a/src/tools/audio/players/musicplayer.cpp b/src/tools/audio/players/musicplayer.cpp index 954c61cd..e626b050 100644 --- a/src/tools/audio/players/musicplayer.cpp +++ b/src/tools/audio/players/musicplayer.cpp @@ -37,16 +37,13 @@ void MusicPlayer::play() void MusicPlayer::pause() { - switch (fileSource()) + if (fileSource() == AudioFile::Source::Spotify) { - case AudioFile::Source::Spotify: m_spotifyPlayer.pause(); - break; - - default: - BufferedAudioPlayer::pause(); - break; + return; } + + BufferedAudioPlayer::pause(); } void MusicPlayer::stop() @@ -58,16 +55,13 @@ void MusicPlayer::stop() void MusicPlayer::again() { - switch (fileSource()) + if (fileSource() == AudioFile::Source::Spotify) { - case AudioFile::Source::Spotify: m_spotifyPlayer.again(); - break; - - default: - BufferedAudioPlayer::again(); - break; + return; } + + BufferedAudioPlayer::again(); } void MusicPlayer::setVolume(int linear, int logarithmic) diff --git a/src/tools/audio/players/radioplayer.h b/src/tools/audio/players/radioplayer.h index 17c62614..6b21c65c 100644 --- a/src/tools/audio/players/radioplayer.h +++ b/src/tools/audio/players/radioplayer.h @@ -11,9 +11,6 @@ class RadioPlayer : public BufferedAudioPlayer explicit RadioPlayer(QNetworkAccessManager &networkManager, MetaDataReader &metaDataReader, QObject *parent = nullptr); -signals: - void metaDataChanged(const QMediaMetaData &metaData); - private slots: void onMetaDataChanged(const QMediaMetaData &data); diff --git a/src/tools/audio/players/soundplayercontroller.h b/src/tools/audio/players/soundplayercontroller.h index e6004ac1..c22ca5b7 100644 --- a/src/tools/audio/players/soundplayercontroller.h +++ b/src/tools/audio/players/soundplayercontroller.h @@ -23,10 +23,10 @@ class SoundPlayerController : public AudioPlayer public slots: void play() override - { + { /* Not Implemented */ } void pause() override - { + { /* Not Implemented */ } void stop() override { @@ -34,10 +34,10 @@ public slots: } void setVolume(int linear, int logarithmic) override; void next() override - { + { /* Not Implemented */ } void again() override - { + { /* Not Implemented */ } private: diff --git a/src/tools/audio/players/spotifyplayer.cpp b/src/tools/audio/players/spotifyplayer.cpp index 51abd7da..a7d61799 100644 --- a/src/tools/audio/players/spotifyplayer.cpp +++ b/src/tools/audio/players/spotifyplayer.cpp @@ -58,7 +58,7 @@ void SpotifyPlayer::play(const QString &uri) qCDebug(gmAudioSpotify) << "Playing:" << uri; m_currentUri = uri; - const auto callback = [this](RestReply &&reply) { + const auto callback = [this](const RestReply &reply) { if (reply.hasError()) { qCWarning(gmAudioSpotify()) << reply.errorText(); @@ -86,7 +86,7 @@ void SpotifyPlayer::play() qCDebug(gmAudioSpotify) << "Continuing playback ..."; - Spotify::instance()->player.play().then([this](RestReply &&reply) { + Spotify::instance()->player.play().then([this](const RestReply &reply) { if (reply.hasError()) { qCWarning(gmAudioSpotify()) << "Could not continue playback:" << reply.errorText(); @@ -120,7 +120,7 @@ void SpotifyPlayer::pause() m_songDurationTimer.stop(); m_metaDataTimer.stop(); - Spotify::instance()->player.pause().then([](RestReply &&reply) { + Spotify::instance()->player.pause().then([](const RestReply &reply) { if (reply.hasError()) { qCWarning(gmAudioSpotify()) << "Could not pause playback:" << reply.errorText(); @@ -157,7 +157,7 @@ void SpotifyPlayer::next() { qCDebug(gmAudioSpotify) << "Skipping to next track ..."; - Spotify::instance()->player.next().then([this](RestReply &&reply) { + Spotify::instance()->player.next().then([this](const RestReply &reply) { if (reply.hasError()) { qCWarning(gmAudioSpotify()) << "Could not skip track:" << reply.errorText(); @@ -175,7 +175,7 @@ void SpotifyPlayer::again() { qCDebug(gmAudioSpotify) << "Playing track again ..."; - Spotify::instance()->player.seek(1).then([](RestReply &&reply) { + Spotify::instance()->player.seek(1).then([](const RestReply &reply) { if (reply.hasError()) { qCWarning(gmAudioSpotify()) << "Could not play track again:" << reply.errorText(); @@ -200,7 +200,7 @@ void SpotifyPlayer::getCurrentSong() { qCDebug(gmAudioSpotify) << "Getting info on current song ..."; - const auto callback = [this](SpotifyCurrentTrack &&track) { + const auto callback = [this](const SpotifyCurrentTrack &track) { if (track.track.uri != m_currentUri) { qCDebug(gmAudioSpotify()) << "Found track" << track.track.uri << "is not the expected track" diff --git a/src/tools/audio/playlist/resolvingaudioplaylist.cpp b/src/tools/audio/playlist/resolvingaudioplaylist.cpp index 2b77a6cb..920a68e0 100644 --- a/src/tools/audio/playlist/resolvingaudioplaylist.cpp +++ b/src/tools/audio/playlist/resolvingaudioplaylist.cpp @@ -34,7 +34,7 @@ auto ResolvingAudioPlaylist::resolve() -> QFuture auto ResolvingAudioPlaylist::unwrapEntries() -> QFuture { QList> futures; - AudioFile *audioFile = nullptr; + const AudioFile *audioFile = nullptr; for (qsizetype i = 0; i < length(); i++) { @@ -58,7 +58,9 @@ auto ResolvingAudioPlaylist::unwrapEntries() -> QFuture } } - return QtFuture::whenAll(futures.begin(), futures.end()).then([](QList> &&) {}); + return QtFuture::whenAll(futures.begin(), futures.end()).then([](const QList> &) { + // empty continuation to return void + }); } auto ResolvingAudioPlaylist::unwrapPlaylistFile(qsizetype index, const AudioFile &file) -> QFuture @@ -85,7 +87,7 @@ auto ResolvingAudioPlaylist::unwrapPlaylistFile(qsizetype index, const AudioFile case AudioFile::Source::File: { const auto path = FileUtils::fileInDir(file.url(), SettingsManager::getPath(m_settingsId)); return Files::File::getDataAsync(path).then( - [callback](Files::FileDataResult &&result) { callback(result.data()); }); + [callback](const Files::FileDataResult &result) { callback(result.data()); }); break; } case AudioFile::Source::Web: { @@ -173,7 +175,7 @@ void ResolvingAudioPlaylist::loadTitles() loadSpotifyTitles(spotifyTracks); } -void ResolvingAudioPlaylist::loadSpotifyTitles(const QList &tracks) +void ResolvingAudioPlaylist::loadSpotifyTitles(const QList &tracks) const { if (tracks.isEmpty()) return; diff --git a/src/tools/audio/playlist/resolvingaudioplaylist.h b/src/tools/audio/playlist/resolvingaudioplaylist.h index 026bcd93..4b20a7a9 100644 --- a/src/tools/audio/playlist/resolvingaudioplaylist.h +++ b/src/tools/audio/playlist/resolvingaudioplaylist.h @@ -18,7 +18,7 @@ class ResolvingAudioPlaylist : public AudioPlaylist auto unwrapSpotify(qsizetype index, const AudioFile &file) -> QFuture; void loadTitles(); - void loadSpotifyTitles(const QList &tracks); + void loadSpotifyTitles(const QList &tracks) const; static auto isPlaylist(const QString &file) -> bool; diff --git a/src/tools/audio/project/audiocategory.cpp b/src/tools/audio/project/audiocategory.cpp index 9651fa34..c1138eae 100644 --- a/src/tools/audio/project/audiocategory.cpp +++ b/src/tools/audio/project/audiocategory.cpp @@ -39,11 +39,11 @@ AudioCategory::AudioCategory(const QJsonObject &object, const QString &path, Aud const auto scenarios = object["scenarios"_L1].toArray(); a_scenarios.reserve(scenarios.size()); - foreach (const auto &scenario, scenarios) + foreach (const auto &scenarioJson, scenarios) { - auto *object = new AudioScenario(scenario.toObject(), m_path, this); - prepareScenario(object); - a_scenarios.append(object); + auto *scenario = new AudioScenario(scenarioJson.toObject(), m_path, this); + prepareScenario(scenario); + a_scenarios.append(scenario); } if (!a_scenarios.isEmpty()) setCurrentScenario(a_scenarios.first()); diff --git a/src/tools/audio/project/audiocategory.h b/src/tools/audio/project/audiocategory.h index 629c6314..45e4631a 100644 --- a/src/tools/audio/project/audiocategory.h +++ b/src/tools/audio/project/audiocategory.h @@ -17,6 +17,7 @@ class AudioCategory : public TreeItem AudioProject *parent); explicit AudioCategory(const AudioCategory &other); explicit AudioCategory(const QJsonObject &object, const QString &path, AudioProject *parent); + ~AudioCategory() override = default; [[nodiscard]] auto toJson() const -> QJsonObject; [[nodiscard]] auto isCheckable() const -> bool override @@ -39,9 +40,9 @@ class AudioCategory : public TreeItem auto setCurrentScenario(AudioScenario *scenario) -> bool; Q_PROPERTY(int scenarioIndex READ scenarioIndex NOTIFY currentScenarioChanged) - [[nodiscard]] auto scenarioIndex() const -> int + [[nodiscard]] auto scenarioIndex() const -> int // needs to be int for qml { - return a_scenarios.indexOf(m_currentScenario); + return static_cast(a_scenarios.indexOf(m_currentScenario)); } [[nodiscard]] auto containsScenario(const QString &name) const -> bool; diff --git a/src/tools/audio/project/audioelement.cpp b/src/tools/audio/project/audioelement.cpp index b8bbf558..3cd6b3aa 100644 --- a/src/tools/audio/project/audioelement.cpp +++ b/src/tools/audio/project/audioelement.cpp @@ -12,7 +12,7 @@ using namespace Qt::Literals::StringLiterals; Q_LOGGING_CATEGORY(gmAudioElement, "gm.audio.project.element") AudioElement::AudioElement(const QString &name, Type type, const QString &path, AudioScenario *parent) - : TreeItem(name, path.split(u"/"_s).length() - 1, false, parent), a_type(type) + : TreeItem(name, static_cast(path.split(u"/"_s).length()) - 1, false, parent), a_type(type) { this->name(name); m_path = path + "/" + typeToString(type) + "/" + name; @@ -20,7 +20,7 @@ AudioElement::AudioElement(const QString &name, Type type, const QString &path, } AudioElement::AudioElement(const QJsonObject &object, Type type, const QString &path, AudioScenario *parent) - : TreeItem(u""_s, path.split(u"/"_s).length() - 1, false, parent), a_type(type) + : TreeItem(u""_s, static_cast(path.split(u"/"_s).length()) - 1, false, parent), a_type(type) { name(object["name"_L1].toString()); mode(static_cast(object["mode"_L1].toInt())); @@ -110,9 +110,7 @@ auto AudioElement::removeFile(int index) -> bool */ auto AudioElement::moveFile(int from, int steps) -> bool { - const int to = from + steps; - - if (Utils::isInBounds(m_files, to)) + if (const int to = from + steps; Utils::isInBounds(m_files, to)) { m_files.move(from, to); emit filesChanged(); diff --git a/src/tools/audio/project/audioelement.h b/src/tools/audio/project/audioelement.h index 6290237b..edf5eb3a 100644 --- a/src/tools/audio/project/audioelement.h +++ b/src/tools/audio/project/audioelement.h @@ -37,6 +37,7 @@ class AudioElement : public TreeItem explicit AudioElement(const QString &name, Type type, const QString &path, AudioScenario *parent); explicit AudioElement(const QJsonObject &object, Type type, const QString &path, AudioScenario *parent); explicit AudioElement(const AudioElement &other); + ~AudioElement() override = default; [[nodiscard]] auto toJson() const -> QJsonObject; @@ -65,7 +66,7 @@ class AudioElement : public TreeItem static auto compare(const AudioElement *e1, const AudioElement *e2) -> bool; - inline operator QString() const + explicit inline operator QString() const { return QStringLiteral("%1 (%2)").arg(name(), typeToString(type())); } diff --git a/src/tools/audio/project/audiofile.cpp b/src/tools/audio/project/audiofile.cpp index 46f98088..0696cb9e 100644 --- a/src/tools/audio/project/audiofile.cpp +++ b/src/tools/audio/project/audiofile.cpp @@ -32,11 +32,10 @@ auto AudioFile::displayName() const -> QString { if (!title().isEmpty()) return title(); - switch (source()) + if (source() == Source::File) { - case Source::File: return FileUtils::fileName(url()); - default: - return url(); } + + return url(); } diff --git a/src/tools/audio/project/audiofile.h b/src/tools/audio/project/audiofile.h index f6ac3fde..c012297b 100644 --- a/src/tools/audio/project/audiofile.h +++ b/src/tools/audio/project/audiofile.h @@ -25,6 +25,7 @@ class AudioFile : public QObject explicit AudioFile(const QString &url, Source source, const QString &title, QObject *parent); explicit AudioFile(const QJsonObject &object, QObject *parent = nullptr); explicit AudioFile(const AudioFile &other); + ~AudioFile() override = default; [[nodiscard]] auto printableUrl() const -> QString; [[nodiscard]] auto toJson() const -> QJsonObject; diff --git a/src/tools/audio/project/audiofilemodel.cpp b/src/tools/audio/project/audiofilemodel.cpp index 7c457cab..85c2a0ae 100644 --- a/src/tools/audio/project/audiofilemodel.cpp +++ b/src/tools/audio/project/audiofilemodel.cpp @@ -18,7 +18,7 @@ void AudioFileModel::insert(int index, QObject *item) void AudioFileModel::append(QObject *item) { - beginInsertRows(QModelIndex(), m_items.size(), m_items.size()); + beginInsertRows(QModelIndex(), static_cast(m_items.size()), static_cast(m_items.size())); m_items.append(item); endInsertRows(); @@ -28,8 +28,9 @@ void AudioFileModel::append(QObject *item) auto AudioFileModel::moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild) -> bool { - int destination = destinationChild > sourceRow ? destinationChild + 1 : destinationChild; - if (beginMoveRows(sourceParent, sourceRow, sourceRow, destinationParent, destination)) + + if (int destination = destinationChild > sourceRow ? destinationChild + 1 : destinationChild; + beginMoveRows(sourceParent, sourceRow, sourceRow, destinationParent, destination)) { m_items.move(sourceRow, destinationChild); endMoveRows(); @@ -39,7 +40,7 @@ auto AudioFileModel::moveRow(const QModelIndex &sourceParent, int sourceRow, con return false; } -void AudioFileModel::remove(QObject *item) +void AudioFileModel::remove(const QObject *item) { for (int i = 0; i < m_items.size(); ++i) { diff --git a/src/tools/audio/project/audiofilemodel.h b/src/tools/audio/project/audiofilemodel.h index 0ceb7929..3ff5dfaf 100644 --- a/src/tools/audio/project/audiofilemodel.h +++ b/src/tools/audio/project/audiofilemodel.h @@ -18,7 +18,7 @@ class AudioFileModel : public QAbstractListModel [[nodiscard]] auto rowCount(const QModelIndex & /*parent*/) const -> int override { - return m_items.size(); + return static_cast(m_items.size()); } [[nodiscard]] auto data(const QModelIndex &index, int role) const -> QVariant override; @@ -35,7 +35,7 @@ class AudioFileModel : public QAbstractListModel } void insert(int index, QObject *item); - void remove(QObject *item); + void remove(const QObject *item); void remove(int index); void append(QObject *item); auto moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, diff --git a/src/tools/audio/project/audioproject.cpp b/src/tools/audio/project/audioproject.cpp index 4f981584..d6b434b6 100644 --- a/src/tools/audio/project/audioproject.cpp +++ b/src/tools/audio/project/audioproject.cpp @@ -37,11 +37,11 @@ AudioProject::AudioProject(QJsonObject object, QObject *parent) const auto categories = object["categories"_L1].toArray(); a_categories.reserve(categories.size()); - foreach (const auto &category, categories) + foreach (const auto &categoryJson, categories) { - auto *object = new AudioCategory(category.toObject(), name(), this); - prepareCategory(object); - a_categories.append(object); + auto *category = new AudioCategory(categoryJson.toObject(), name(), this); + prepareCategory(category); + a_categories.append(category); } if (!a_categories.isEmpty()) setCurrentCategory(a_categories.constFirst()); @@ -115,7 +115,7 @@ auto AudioProject::setCurrentCategory(AudioCategory *category) -> bool return false; } -auto AudioProject::categoryIndex() const -> int +auto AudioProject::categoryIndex() const -> qsizetype { return a_categories.indexOf(m_currentCategory); } diff --git a/src/tools/audio/project/audioproject.h b/src/tools/audio/project/audioproject.h index 9e159b23..3f40cf4d 100644 --- a/src/tools/audio/project/audioproject.h +++ b/src/tools/audio/project/audioproject.h @@ -19,6 +19,7 @@ class AudioProject : public TreeItem AudioProject(const QString &name, int version, QList categories, QObject *parent = nullptr); AudioProject(const AudioProject &other, QObject *parent = nullptr); AudioProject(QJsonObject object, QObject *parent = nullptr); + ~AudioProject() override = default; [[nodiscard]] auto toJson() const -> QJsonObject; [[nodiscard]] auto isCheckable() const -> bool override @@ -32,7 +33,7 @@ class AudioProject : public TreeItem auto setCurrentCategory(AudioCategory *category) -> bool; Q_PROPERTY(int categoryIndex READ categoryIndex NOTIFY currentCategoryChanged) - [[nodiscard]] auto categoryIndex() const -> int; + [[nodiscard]] auto categoryIndex() const -> qsizetype; auto deleteCategory(AudioCategory *category) -> bool; auto addCategory(AudioCategory *category, bool setAsCurrent = false) -> bool; [[nodiscard]] auto containsCategory(const QString &name) const -> bool; diff --git a/src/tools/audio/project/audioscenario.cpp b/src/tools/audio/project/audioscenario.cpp index e39fc697..42c8bf4f 100644 --- a/src/tools/audio/project/audioscenario.cpp +++ b/src/tools/audio/project/audioscenario.cpp @@ -11,7 +11,7 @@ Q_LOGGING_CATEGORY(gmAudioScenario, "gm.audio.project.scenario") AudioScenario::AudioScenario(const QString &name, const QString &path, const QList &elements, const QList &scenarios, bool isSubscenario, QObject *parent) - : TreeItem(name, path.split(u"/"_s).length() - 1, true, parent), a_scenarios(scenarios), + : TreeItem(name, static_cast(path.split(u"/"_s).length()) - 1, true, parent), a_scenarios(scenarios), a_isSubscenario(isSubscenario), m_path(path + u"/"_s + name), m_elements(elements) { this->name(name); @@ -46,39 +46,39 @@ AudioScenario::AudioScenario(const AudioScenario &other) } AudioScenario::AudioScenario(const QJsonObject &object, const QString &path, bool isSubscenario, QObject *parent) - : TreeItem(u""_s, path.split(u"/"_s).length() - 1, true, parent), a_isSubscenario(isSubscenario) + : TreeItem(u""_s, static_cast(path.split(u"/"_s).length()) - 1, true, parent), a_isSubscenario(isSubscenario) { name(object["name"_L1].toString()); m_path = path + u"/"_s + name(); connect(this, &AudioScenario::scenariosChanged, this, &AudioScenario::onScenariosChanged); - foreach (const auto &element, object["music_elements"_L1].toArray()) + foreach (const auto &elementJson, object["music_elements"_L1].toArray()) { - auto *object = new AudioElement(element.toObject(), AudioElement::Type::Music, m_path, this); - prepareElement(object); - m_elements.append(object); + auto *element = new AudioElement(elementJson.toObject(), AudioElement::Type::Music, m_path, this); + prepareElement(element); + m_elements.append(element); } - foreach (const auto &element, object["sound_elements"_L1].toArray()) + foreach (const auto &elementJson, object["sound_elements"_L1].toArray()) { - auto *object = new AudioElement(element.toObject(), AudioElement::Type::Sound, m_path, this); - prepareElement(object); - m_elements.append(object); + auto *element = new AudioElement(elementJson.toObject(), AudioElement::Type::Sound, m_path, this); + prepareElement(element); + m_elements.append(element); } - foreach (const auto &element, object["radio_elements"_L1].toArray()) + foreach (const auto &elementJson, object["radio_elements"_L1].toArray()) { - auto *object = new AudioElement(element.toObject(), AudioElement::Type::Radio, m_path, this); - prepareElement(object); - m_elements.append(object); + auto *element = new AudioElement(elementJson.toObject(), AudioElement::Type::Radio, m_path, this); + prepareElement(element); + m_elements.append(element); } - foreach (const auto &scenario, object["scenarios"_L1].toArray()) + foreach (const auto &scenarioJson, object["scenarios"_L1].toArray()) { - auto *object = new AudioScenario(scenario.toObject(), m_path, this); - prepareScenario(object); - a_scenarios.append(object); + auto *scenario = new AudioScenario(scenarioJson.toObject(), m_path, this); + prepareScenario(scenario); + a_scenarios.append(scenario); } updateModel(); @@ -227,10 +227,9 @@ auto AudioScenario::moveElement(AudioElement *element, int steps) -> bool { if (!element) return false; - int index = m_elements.indexOf(element); - int indexNew = index + steps; + auto index = m_elements.indexOf(element); - if (Utils::isInBounds(m_elements, indexNew)) + if (auto indexNew = index + steps; Utils::isInBounds(m_elements, indexNew)) { qCDebug(gmAudioScenario()) << index << indexNew; m_elements.move(index, indexNew); @@ -365,8 +364,8 @@ auto AudioScenario::moveScenario(AudioScenario *scenario, int steps) -> bool return false; } - const int from = a_scenarios.indexOf(scenario); - const int to = from + steps; + const auto from = a_scenarios.indexOf(scenario); + const auto to = from + steps; if (Utils::isInBounds(a_scenarios, to)) { @@ -399,7 +398,7 @@ auto AudioScenario::prepareElement(AudioElement *element) -> void connect(element, &AudioElement::filesChanged, this, &AudioScenario::wasEdited); } -void AudioScenario::releaseElement(AudioElement *element) const +void AudioScenario::releaseElement(const AudioElement *element) const { if (!element || element->parent() != this) return; diff --git a/src/tools/audio/project/audioscenario.h b/src/tools/audio/project/audioscenario.h index 484210c0..e7f5d35a 100644 --- a/src/tools/audio/project/audioscenario.h +++ b/src/tools/audio/project/audioscenario.h @@ -20,6 +20,7 @@ class AudioScenario : public TreeItem explicit AudioScenario(const AudioScenario &other); explicit AudioScenario(const QJsonObject &object, const QString &path, AudioCategory *parent); explicit AudioScenario(const QJsonObject &object, const QString &path, AudioScenario *parent); + ~AudioScenario() override = default; [[nodiscard]] auto toJson() const -> QJsonObject; [[nodiscard]] auto isCheckable() const -> bool override @@ -82,7 +83,7 @@ private slots: QList m_elements; void prepareElement(AudioElement *element); - void releaseElement(AudioElement *element) const; + void releaseElement(const AudioElement *element) const; void prepareScenario(AudioScenario *scenario); void updateModel(); }; diff --git a/src/tools/audio/thumbnails/audiothumbnail.h b/src/tools/audio/thumbnails/audiothumbnail.h index c5ab358b..cf825dab 100755 --- a/src/tools/audio/thumbnails/audiothumbnail.h +++ b/src/tools/audio/thumbnails/audiothumbnail.h @@ -59,7 +59,8 @@ class AudioThumbnail : public QObject private: AudioElement *element = nullptr; - QString m_imageId, m_relativeUrl; + QString m_imageId; + QString m_relativeUrl; QList> m_collageIcons; bool m_imageIdCounter = false; }; diff --git a/src/tools/audio/thumbnails/audiothumbnailcollagegenerator.cpp b/src/tools/audio/thumbnails/audiothumbnailcollagegenerator.cpp index dc0bc68c..ff4cdaed 100755 --- a/src/tools/audio/thumbnails/audiothumbnailcollagegenerator.cpp +++ b/src/tools/audio/thumbnails/audiothumbnailcollagegenerator.cpp @@ -19,7 +19,7 @@ auto AudioThumbnailCollageGenerator::makeCollageAsync(QPointer ele return future.then([element]() { return generateCollageImage(element); }); } -auto AudioThumbnailCollageGenerator::findPixmapsForCollageAsync(QPointer element, int index, +auto AudioThumbnailCollageGenerator::findPixmapsForCollageAsync(QPointer element, qsizetype index, int fileCount, int failCount) -> QFuture { if (!element) return QtFuture::makeReadyFuture(); @@ -71,7 +71,7 @@ auto AudioThumbnailCollageGenerator::findPixmapsForCollageAsync(QPointer element) -> bool { - return element && element->type() != AudioElement::Type::Radio && element->files().length() > 0; + return element && element->type() != AudioElement::Type::Radio && !element->files().isEmpty(); } /** @@ -115,9 +115,9 @@ auto AudioThumbnailCollageGenerator::generateCollageImage(QPointer { if (i > 3) break; - QRectF target = getTargetRect(thumbnailSize(), images.count(), i); - QRectF source = getSourceRect(images[i].rect(), images.count(), i); - painter.drawPixmap(target, images[i], source); + QRectF target = getTargetRect(thumbnailSize(), static_cast(images.count()), i); + QRectF source = getSourceRect(images.at(i).rect(), static_cast(images.count()), i); + painter.drawPixmap(target, images.at(i), source); } painter.end(); @@ -156,7 +156,7 @@ auto AudioThumbnailCollageGenerator::getTargetRect(QSize imageSize, int imageCou const qreal width = imageCount == 4 ? imageSize.width() / 2 : imageSize.width() / imageCount; const qreal height = imageCount == 4 ? imageSize.height() / 2 : imageSize.height(); const qreal left = imageCount == 4 ? width * ((index + 1) % 2) : width * index; - const qreal top = imageCount == 4 ? (index > 1 ? height : 0) : 0; + const qreal top = imageCount == 4 && index > 1 ? height : 0; return {left, top, width, height}; } diff --git a/src/tools/audio/thumbnails/audiothumbnailcollagegenerator.h b/src/tools/audio/thumbnails/audiothumbnailcollagegenerator.h index 56b0eb14..8f1ae0e1 100755 --- a/src/tools/audio/thumbnails/audiothumbnailcollagegenerator.h +++ b/src/tools/audio/thumbnails/audiothumbnailcollagegenerator.h @@ -16,8 +16,8 @@ class AudioThumbnailCollageGenerator static auto generateCollageImage(QPointer element) -> QPixmap; static auto getUniquePixmaps(QPointer thumbnail) -> QList; - static auto findPixmapsForCollageAsync(QPointer element, int index, int fileCount, int failCount) - -> QFuture; + static auto findPixmapsForCollageAsync(QPointer element, qsizetype index, int fileCount, + int failCount) -> QFuture; static auto getTargetRect(QSize imageSize, int imageCount, int index) -> QRectF; static auto getSourceRect(QRect imageRect, int imageCount, int index) -> QRectF; diff --git a/src/tools/audio/thumbnails/audiothumbnailgenerator.cpp b/src/tools/audio/thumbnails/audiothumbnailgenerator.cpp index 8141e071..03a97d7a 100755 --- a/src/tools/audio/thumbnails/audiothumbnailgenerator.cpp +++ b/src/tools/audio/thumbnails/audiothumbnailgenerator.cpp @@ -45,7 +45,7 @@ void AudioThumbnailGenerator::receivedImage(QPointer element, cons { qCDebug(gmAudioThumbnailGenerator()) << "Received pixmap is null, making collage as fallback ..."; AudioThumbnailCollageGenerator::makeCollageAsync(element).then( - [element](const QPixmap &pixmap) { receivedImage(element, pixmap, false); }); + [element](const QPixmap &collage) { receivedImage(element, collage, false); }); return; } diff --git a/src/tools/audio/thumbnails/loaders/fileimageloader.cpp b/src/tools/audio/thumbnails/loaders/fileimageloader.cpp index 0facb33a..51843bcf 100755 --- a/src/tools/audio/thumbnails/loaders/fileimageloader.cpp +++ b/src/tools/audio/thumbnails/loaders/fileimageloader.cpp @@ -10,8 +10,10 @@ using namespace Files; auto FileImageLoader::loadImageAsync(const QString &path) -> QFuture { // Try to load from cache - QPixmap pixmap; - if (AudioThumbnailCache::tryGet(path, &pixmap)) return QtFuture::makeReadyFuture(pixmap); + if (QPixmap pixmap; AudioThumbnailCache::tryGet(path, &pixmap)) + { + return QtFuture::makeReadyFuture(pixmap); + } auto future = File::getDataAsync(path); diff --git a/src/tools/audio/thumbnails/loaders/spotifyimageloader.cpp b/src/tools/audio/thumbnails/loaders/spotifyimageloader.cpp index 43148469..c47bf53a 100755 --- a/src/tools/audio/thumbnails/loaders/spotifyimageloader.cpp +++ b/src/tools/audio/thumbnails/loaders/spotifyimageloader.cpp @@ -23,7 +23,7 @@ constexpr int CRITICAL_TRACK_QUEUE_LENGTH = 50; constexpr int DEFAULT_TIMEOUT_MS = 200; constexpr int RANDOM_TIMEOUT_MS = 100; -auto SpotifyImageLoader::loadImageAsync(AudioFile *audioFile) -> QFuture +auto SpotifyImageLoader::loadImageAsync(const AudioFile *audioFile) -> QFuture { return loadImageAsync(audioFile->url()); } @@ -34,8 +34,7 @@ auto SpotifyImageLoader::loadImageAsync(const QString &uri) -> QFuture const auto id = SpotifyUtils::getIdFromUri(uri); // Try to get image from cache - QPixmap image; - if (AudioThumbnailCache::tryGet(id, &image)) + if (QPixmap image; AudioThumbnailCache::tryGet(id, &image)) { return QtFuture::makeReadyFuture(image); } @@ -81,11 +80,11 @@ void SpotifyImageLoader::enqueueRequest(const QString &id, SpotifyUtils::Spotify auto SpotifyImageLoader::loadPlaylistImageAsync(const QString &id) -> QFuture { - const auto callback = [id](const SpotifyPlaylist &playlist) { + const auto playlistCallback = [id](const SpotifyPlaylist &playlist) { const auto url = playlist.images.front().url; auto future = Services::Spotify::instance()->get(url, false); - const auto callback = [id, url](const RestReply &reply) { + const auto imageCallback = [id, url](const RestReply &reply) { QPixmap image; if (image.loadFromData(reply.data())) @@ -97,11 +96,11 @@ auto SpotifyImageLoader::loadPlaylistImageAsync(const QString &id) -> QFutureplaylists.getPlaylist(id); - return future.then(callback).unwrap(); + return future.then(playlistCallback).unwrap(); } void SpotifyImageLoader::startRequest(SpotifyUtils::SpotifyType type) @@ -152,19 +151,18 @@ void SpotifyImageLoader::receivedRequest(RestReply &&reply, SpotifyUtils::Spotif const auto url = images.first()["url"_L1].toString(); - QPixmap image; - if (AudioThumbnailCache::tryGet(url, &image)) + if (QPixmap image; AudioThumbnailCache::tryGet(url, &image)) { fulfillPromises(id, image); continue; } const auto request = QNetworkRequest(url); - auto future = Spotify::instance()->get(request); + auto future = Spotify::instance()->get(request, false); - const auto callback = [id, url](const RestReply &reply) { + const auto callback = [id, url](const RestReply &imageReply) { QPixmap image; - if (image.loadFromData(reply.data())) + if (image.loadFromData(imageReply.data())) { AudioThumbnailCache::instance()->insertImage(url, image); AudioThumbnailCache::instance()->insertImage(id, image); @@ -207,9 +205,7 @@ auto SpotifyImageLoader::getBatchIds(SpotifyUtils::SpotifyType type) -> QStringL auto SpotifyImageLoader::shouldTimerBeStopped(SpotifyUtils::SpotifyType type) -> bool { - const auto *queue = getQueue(type); - - if (queue) + if (const auto *queue = getQueue(type); queue) { return queue->length() >= getCriticalQueueLength(type); } diff --git a/src/tools/audio/thumbnails/loaders/spotifyimageloader.h b/src/tools/audio/thumbnails/loaders/spotifyimageloader.h index 94db7ee7..904cc9cf 100755 --- a/src/tools/audio/thumbnails/loaders/spotifyimageloader.h +++ b/src/tools/audio/thumbnails/loaders/spotifyimageloader.h @@ -16,7 +16,7 @@ class SpotifyImageLoader { public: - static auto loadImageAsync(AudioFile *audioFile) -> QFuture; + static auto loadImageAsync(const AudioFile *audioFile) -> QFuture; static auto loadImageAsync(const QString &uri) -> QFuture; private: diff --git a/src/tools/audio/thumbnails/loaders/tagimageloader.cpp b/src/tools/audio/thumbnails/loaders/tagimageloader.cpp index 41a47b41..3992d290 100755 --- a/src/tools/audio/thumbnails/loaders/tagimageloader.cpp +++ b/src/tools/audio/thumbnails/loaders/tagimageloader.cpp @@ -17,7 +17,7 @@ Q_LOGGING_CATEGORY(gmAudioTagImageLoader, "gm.audio.thumbnails.loaders.tag") using namespace TagLib; -auto TagImageLoader::loadImageAsync(AudioElement *element, AudioFile *audioFile) -> QFuture +auto TagImageLoader::loadImageAsync(const AudioElement *element, const AudioFile *audioFile) -> QFuture { // Paranoid pointer check if (!audioFile) return QtFuture::makeReadyFuture(QPixmap()); @@ -34,8 +34,7 @@ auto TagImageLoader::loadImageAsync(AudioElement *element, AudioFile *audioFile) path = FileUtils::fileInDir(audioFile->url(), path); // Try to retrieve image from cache - QPixmap pixmap; - if (AudioThumbnailCache::tryGet(path, &pixmap)) + if (QPixmap pixmap; AudioThumbnailCache::tryGet(path, &pixmap)) { return QtFuture::makeReadyFuture(pixmap); } @@ -53,7 +52,7 @@ auto TagImageLoader::loadFromFileAsync(const QString &path, bool isLocalFile) -> auto TagImageLoader::loadFromData(const QString &path, const QByteArray &data) -> QPixmap { - const ByteVector bvector(data.data(), data.length()); + const ByteVector bvector(data.data(), static_cast(data.length())); auto bvstream = std::make_unique(bvector); return loadFromData(path, std::move(bvstream)); @@ -66,33 +65,27 @@ auto TagImageLoader::loadFromData(const QString &path, std::unique_ptr(data.get(), ID3v2::FrameFactory::instance()); - return loadFromMpeg(std::move(mpeg), path); + return loadFromMpeg(std::make_unique(data.get(), ID3v2::FrameFactory::instance()), path); } case FileUtils::MimeType::OGA: { - Ogg::FLAC::File flac(data.get()); - if (flac.isValid()) + if (Ogg::FLAC::File flac(data.get()); flac.isValid()) { return loadFromFlac(flac, path); } - Ogg::Vorbis::File vorbis(data.get()); - return loadFromVorbis(vorbis, path); + return loadFromVorbis(Ogg::Vorbis::File(data.get()), path); } case FileUtils::MimeType::Vorbis: { - Ogg::Vorbis::File vorbis(data.get()); - return loadFromVorbis(vorbis, path); + return loadFromVorbis(Ogg::Vorbis::File(data.get()), path); } case FileUtils::MimeType::FLAC: { - FLAC::File flac(data.get(), ID3v2::FrameFactory::instance()); - if (flac.isValid()) return loadFromFlac(flac, path); + if (FLAC::File flac(data.get(), ID3v2::FrameFactory::instance()); flac.isValid()) + return loadFromFlac(flac, path); - Ogg::FLAC::File oggflac(data.get()); - return loadFromFlac(oggflac, path); + return loadFromFlac(Ogg::FLAC::File(data.get()), path); } case FileUtils::MimeType::WAV: { - RIFF::WAV::File wav(data.get()); - return loadFromWav(wav, path); + return loadFromWav(RIFF::WAV::File(data.get()), path); } default: qCDebug(gmAudioTagImageLoader()) << "Could not load image from" << path << "mime type is not supported yet"; @@ -104,7 +97,7 @@ auto TagImageLoader::loadViaTempFileAsync(const QString &path) -> QFuture QPixmap auto TagImageLoader::loadFromMpeg(const QString &path) -> QPixmap { - auto mpeg = std::make_unique(QFile::encodeName(path).constData()); - return loadFromMpeg(std::move(mpeg), path); + return loadFromMpeg(std::make_unique(QFile::encodeName(path).constData()), path); } auto TagImageLoader::loadFromMpeg(std::unique_ptr mpeg, const QString &path) -> QPixmap @@ -232,8 +224,7 @@ auto TagImageLoader::pixmapFromId3v2Frames(const ID3v2::FrameList &frames) -> QP auto TagImageLoader::loadFromOga(const QString &path) -> QPixmap { // Can be of type FLAC or Vorbis, check FLAC first - auto flac = Ogg::FLAC::File(QFile::encodeName(path).constData()); - if (flac.isValid()) + if (auto flac = Ogg::FLAC::File(QFile::encodeName(path).constData()); flac.isValid()) { return loadFromFlac(flac, path); } @@ -244,8 +235,7 @@ auto TagImageLoader::loadFromOga(const QString &path) -> QPixmap auto TagImageLoader::loadFromVorbis(const QString &path) -> QPixmap { - const auto file = Ogg::Vorbis::File(QFile::encodeName(path).constData()); - return loadFromVorbis(file, path); + return loadFromVorbis(Ogg::Vorbis::File(QFile::encodeName(path).constData()), path); } auto TagImageLoader::loadFromVorbis(const Ogg::Vorbis::File &file, const QString &path) -> QPixmap @@ -261,14 +251,12 @@ auto TagImageLoader::loadFromVorbis(const Ogg::Vorbis::File &file, const QString auto TagImageLoader::loadFromFlac(const QString &path) -> QPixmap { - auto flac = FLAC::File(QFile::encodeName(path).constData()); - if (flac.isValid()) + if (auto flac = FLAC::File(QFile::encodeName(path).constData()); flac.isValid()) { return loadFromFlac(flac, path); } - auto oggflac = Ogg::FLAC::File(QFile::encodeName(path).constData()); - if (oggflac.isValid()) + if (auto oggflac = Ogg::FLAC::File(QFile::encodeName(path).constData()); oggflac.isValid()) { return loadFromFlac(oggflac, path); } @@ -341,11 +329,10 @@ auto TagImageLoader::loadFromXiphComment(Ogg::XiphComment *tag, const QString &p auto TagImageLoader::loadFromWav(const QString &path) -> QPixmap { - const auto file = RIFF::WAV::File(QFile::encodeName(path).constData()); - return loadFromWav(file, path); + return loadFromWav(RIFF::WAV::File(QFile::encodeName(path).constData()), path); } -auto TagImageLoader::loadFromWav(const TagLib::RIFF::WAV::File &file, const QString &path) -> QPixmap +auto TagImageLoader::loadFromWav(const RIFF::WAV::File &file, const QString &path) -> QPixmap { if (!file.isValid()) { diff --git a/src/tools/audio/thumbnails/loaders/tagimageloader.h b/src/tools/audio/thumbnails/loaders/tagimageloader.h index bd47bf18..11b27de1 100755 --- a/src/tools/audio/thumbnails/loaders/tagimageloader.h +++ b/src/tools/audio/thumbnails/loaders/tagimageloader.h @@ -17,7 +17,7 @@ class TagImageLoader { public: - static auto loadImageAsync(AudioElement *element, AudioFile *audioFile) -> QFuture; + static auto loadImageAsync(const AudioElement *element, const AudioFile *audioFile) -> QFuture; static auto loadFromFileAsync(const QString &path, bool isLocalFile) -> QFuture; static auto loadFromData(const QString &path, const QByteArray &data) -> QPixmap; static auto loadFromData(const QString &path, std::unique_ptr data) -> QPixmap; diff --git a/src/tools/audio/thumbnails/loaders/webimageloader.cpp b/src/tools/audio/thumbnails/loaders/webimageloader.cpp index 05c44843..5fa09c9d 100755 --- a/src/tools/audio/thumbnails/loaders/webimageloader.cpp +++ b/src/tools/audio/thumbnails/loaders/webimageloader.cpp @@ -12,8 +12,10 @@ auto WebImageLoader::loadImageAsync(const QString &url, QNetworkAccessManager *n qCDebug(gmAudioWebImageLoader()) << "Loading image from web:" << url << "..."; // Try to load from cache - QPixmap pixmap; - if (AudioThumbnailCache::tryGet(url, &pixmap)) return QtFuture::makeReadyFuture(pixmap); + if (QPixmap pixmap; AudioThumbnailCache::tryGet(url, &pixmap)) + { + return QtFuture::makeReadyFuture(pixmap); + } // Load from url const auto request = QNetworkRequest(QUrl(url)); diff --git a/src/tools/characters/character.cpp b/src/tools/characters/character.cpp index 3eceac91..f960653d 100644 --- a/src/tools/characters/character.cpp +++ b/src/tools/characters/character.cpp @@ -42,7 +42,7 @@ void Character::loadFiles() void Character::loadFileList() { - Files::File::listAsync(folder(), true, false).then([this](Files::FileListResult &&result) { + Files::File::listAsync(folder(), true, false).then([this](const Files::FileListResult &result) { if (!result.success()) return; foreach (const auto &fileName, result.files()) @@ -54,18 +54,18 @@ void Character::loadFileList() }); } -void Character::loadFileData(int index) +void Character::loadFileData(qsizetype index) { if (!Utils::isInBounds(files(), index)) return; - if (!m_files[index]->data().isEmpty()) + if (!m_files.at(index)->data().isEmpty()) { qCDebug(gmCharactersCharacter()) << "File data already loaded."; emit fileDataLoaded(index, m_files.at(index)->data()); return; } - Files::File::getDataAsync(m_files.at(index)->path()).then([this, index](Files::FileDataResult &&result) { + Files::File::getDataAsync(m_files.at(index)->path()).then([this, index](const Files::FileDataResult &result) { if (!result.success()) return; m_files.at(index)->data(result.data()); diff --git a/src/tools/characters/character.h b/src/tools/characters/character.h index 1502b727..50421326 100644 --- a/src/tools/characters/character.h +++ b/src/tools/characters/character.h @@ -45,7 +45,7 @@ class Character : public QObject void loadFiles(); void loadFileList(); - void loadFileData(int index); + void loadFileData(qsizetype index); signals: void fileListLoaded(const QList &files); diff --git a/src/tools/characters/charactertool.cpp b/src/tools/characters/charactertool.cpp index 406c25c9..8e9ea139 100644 --- a/src/tools/characters/charactertool.cpp +++ b/src/tools/characters/charactertool.cpp @@ -38,7 +38,7 @@ auto CharacterTool::characters() const -> QStringList { QStringList names; - for (auto *character : m_characters) + foreach (const auto *character, m_characters) { if (!m_active != !m_inactiveCharacters.contains(character->name())) { @@ -60,18 +60,18 @@ void CharacterTool::updateCharacter() const // } } -void CharacterTool::setCurrentCharacter(int index) +void CharacterTool::setCurrentCharacter(qsizetype index) { auto characterNames = characters(); if (!Utils::isInBounds(characterNames, index)) return; - auto name = characterNames[index]; + const auto &name = characterNames.at(index); m_currentCharacter = nullptr; for (int i = 0; i < m_characters.length(); i++) { - auto *character = m_characters.at(i); + const auto *character = m_characters.at(i); if (character && (index >= i) && (character->name() == name)) { @@ -114,13 +114,13 @@ void CharacterTool::setCurrentCategory(int index) m_currentViewer->setCurrentCategory(index); } -void CharacterTool::toggleCharacterActive(int index) +void CharacterTool::toggleCharacterActive(qsizetype index) { auto characterNames = characters(); if (!Utils::isInBounds(characterNames, index)) return; - auto name = characterNames[index]; + const auto &name = characterNames.at(index); if (m_active) m_inactiveCharacters.append(name); else @@ -209,7 +209,7 @@ void CharacterTool::loadCharacters() qCDebug(gmCharactersTool()) << "Loaded inactive character list, now loading character files and folders ..."; const auto dir = SettingsManager::getPath(u"characters"_s); - Files::File::listAsync(dir, true, true).then([this](Files::FileListResult &&result) { + Files::File::listAsync(dir, true, true).then([this](const Files::FileListResult &result) { receivedCharacterFiles(result.files()); receivedCharacterFolders(result.folders()); }); diff --git a/src/tools/characters/charactertool.h b/src/tools/characters/charactertool.h index f4d2c338..7a5a769f 100644 --- a/src/tools/characters/charactertool.h +++ b/src/tools/characters/charactertool.h @@ -36,9 +36,9 @@ class CharacterTool : public AbstractTool } Q_PROPERTY(int categoryIndex READ categoryIndex NOTIFY categoryChanged) - [[nodiscard]] auto categoryIndex() const -> int + [[nodiscard]] auto categoryIndex() const -> int // needs to be int for qml { - return m_currentViewer ? m_currentViewer->categoryIndex() : 0; + return m_currentViewer ? static_cast(m_currentViewer->categoryIndex()) : 0; } Q_PROPERTY(int pageIndex READ pageIndex NOTIFY pageIndexChanged) @@ -54,9 +54,9 @@ class CharacterTool : public AbstractTool { return m_active; } - Q_INVOKABLE void toggleCharacterActive(int index); + Q_INVOKABLE void toggleCharacterActive(qsizetype index); - Q_INVOKABLE void setCurrentCharacter(int index); + Q_INVOKABLE void setCurrentCharacter(qsizetype index); Q_INVOKABLE void displayActiveCharacters(bool active); public slots: diff --git a/src/tools/characters/viewers/characterimageviewer.cpp b/src/tools/characters/viewers/characterimageviewer.cpp index 36c55491..85879720 100644 --- a/src/tools/characters/viewers/characterimageviewer.cpp +++ b/src/tools/characters/viewers/characterimageviewer.cpp @@ -39,8 +39,11 @@ void CharacterImageViewer::onCharacterFileListLoaded(const QListname()); + } + emit categoriesChanged(); if (!m_categories.isEmpty()) setCurrentCategory(0); @@ -152,7 +155,7 @@ void CharacterImageViewer::setCurrentCategory(qsizetype index) if ((m_currentCharacter->type() == 1) && (index > 0)) { - setPDFPage(index); + setPDFPage(static_cast(index)); } else { diff --git a/src/tools/characters/viewers/characterviewer.h b/src/tools/characters/viewers/characterviewer.h index cb9ca94e..34e56014 100644 --- a/src/tools/characters/viewers/characterviewer.h +++ b/src/tools/characters/viewers/characterviewer.h @@ -2,6 +2,7 @@ #include "tools/characters/character.h" #include +#include #include class CharacterViewer : public QObject @@ -46,5 +47,5 @@ class CharacterViewer : public QObject QStringList m_categories; qsizetype m_categoryIndex = 0; - Character *m_currentCharacter = nullptr; + QPointer m_currentCharacter = nullptr; }; diff --git a/src/tools/combat_tracker/combatant.cpp b/src/tools/combat_tracker/combatant.cpp index 9985f947..ba2e2a19 100644 --- a/src/tools/combat_tracker/combatant.cpp +++ b/src/tools/combat_tracker/combatant.cpp @@ -38,7 +38,7 @@ auto CombatantListModel::data(const QModelIndex &index, int /*role*/) const -> Q auto CombatantListModel::append(QObject *item) -> void { - beginInsertRows(QModelIndex(), m_items.length(), m_items.length()); + beginInsertRows(QModelIndex(), static_cast(m_items.length()), static_cast(m_items.length())); m_items.push_back(item); endInsertRows(); } @@ -54,7 +54,7 @@ auto CombatantListModel::remove(int index) -> void auto CombatantListModel::remove(QObject *item) -> void { - const auto index = m_items.indexOf(item); + const auto index = static_cast(m_items.indexOf(item)); remove(index); } diff --git a/src/tools/combat_tracker/combatant.h b/src/tools/combat_tracker/combatant.h index 22c6cb6e..4e9e0310 100644 --- a/src/tools/combat_tracker/combatant.h +++ b/src/tools/combat_tracker/combatant.h @@ -7,8 +7,6 @@ #include #include -using namespace Qt::Literals::StringLiterals; - class Combatant : public QObject { Q_OBJECT @@ -30,10 +28,10 @@ class Combatant : public QObject [[nodiscard]] auto toJson() const -> QJsonObject; static auto fromJson(const QJsonObject &json, QObject *parent) -> Combatant *; - inline operator QString() const + explicit inline operator QString() const { - return u"%1 (Ini: %2 [%3], Health: %4)"_s.arg(name(), QString::number(ini()), QString::number(priority()), - QString::number(health())); + return QStringLiteral("%1 (Ini: %2 [%3], Health: %4)") + .arg(name(), QString::number(ini()), QString::number(priority()), QString::number(health())); } }; @@ -48,7 +46,7 @@ class CombatantListModel : public QAbstractListModel [[nodiscard]] auto rowCount(const QModelIndex & /*parent*/) const -> int override { - return m_items.size(); + return static_cast(m_items.size()); } [[nodiscard]] auto data(const QModelIndex &index, int role) const -> QVariant override; diff --git a/src/tools/combat_tracker/combattracker.cpp b/src/tools/combat_tracker/combattracker.cpp index b8ebb298..6dc89735 100644 --- a/src/tools/combat_tracker/combattracker.cpp +++ b/src/tools/combat_tracker/combattracker.cpp @@ -13,7 +13,7 @@ using namespace Qt::Literals::StringLiterals; Q_LOGGING_CATEGORY(gmCombatTracker, "gm.combat.tracker") -CombatTracker::CombatTracker(QQmlEngine *qmlEngine, QObject *parent) : AbstractTool(parent), m_effectTool(this) +CombatTracker::CombatTracker(const QQmlEngine *qmlEngine, QObject *parent) : AbstractTool(parent), m_effectTool(this) { if (qmlEngine) { @@ -26,7 +26,7 @@ CombatTracker::CombatTracker(QQmlEngine *qmlEngine, QObject *parent) : AbstractT auto CombatTracker::create(QQmlEngine *qmlEngine, QJSEngine *jsEngine) -> CombatTracker * { - Q_UNUSED(jsEngine); + Q_UNUSED(jsEngine) return new CombatTracker(qmlEngine, qmlEngine); } @@ -134,7 +134,7 @@ void CombatTracker::sortByIni(bool keepDelay) if (combatant) { - m_state.currentIndex(combatants().indexOf(combatant)); + m_state.currentIndex(static_cast(combatants().indexOf(combatant))); } } @@ -276,9 +276,9 @@ auto CombatTracker::getCombatant(int index) -> Combatant * return nullptr; } -void CombatTracker::resetDelayForAll() +void CombatTracker::resetDelayForAll() const { - for (auto *combatant : combatants()) + foreach (auto *combatant, combatants()) { if (Q_LIKELY(combatant)) combatant->delay(false); } @@ -290,9 +290,7 @@ void CombatTracker::loadData() { if (isDataLoaded()) return; - auto tempFile = getCacheFile(); - - if (tempFile.exists() && tempFile.open(QIODevice::ReadOnly)) + if (auto tempFile = getCacheFile(); tempFile.exists() && tempFile.open(QIODevice::ReadOnly)) { const auto data = tempFile.readAll(); tempFile.close(); diff --git a/src/tools/combat_tracker/combattracker.h b/src/tools/combat_tracker/combattracker.h index eca4009e..2a20b743 100644 --- a/src/tools/combat_tracker/combattracker.h +++ b/src/tools/combat_tracker/combattracker.h @@ -20,7 +20,7 @@ class CombatTracker : public AbstractTool public: CombatTracker() = delete; - explicit CombatTracker(QQmlEngine *qmlEngine, QObject *parent = nullptr); + explicit CombatTracker(const QQmlEngine *qmlEngine, QObject *parent = nullptr); static auto create(QQmlEngine *qmlEngine, QJSEngine *jsEngine) -> CombatTracker *; Q_PROPERTY(int currentRound READ currentRound NOTIFY currentRoundChanged) @@ -74,7 +74,7 @@ public slots: [[nodiscard]] auto combatants() const -> QList; [[nodiscard]] auto getCombatant(int index) -> Combatant *; - void resetDelayForAll(); + void resetDelayForAll() const; void saveToDisk() const; static auto getCacheFile() -> QFile; diff --git a/src/tools/combat_tracker/combattrackerstate.cpp b/src/tools/combat_tracker/combattrackerstate.cpp index c9c64181..541f8b12 100644 --- a/src/tools/combat_tracker/combattrackerstate.cpp +++ b/src/tools/combat_tracker/combattrackerstate.cpp @@ -48,7 +48,7 @@ void CombatTrackerState::moveCombatant(int from, int to) void CombatTrackerState::moveCombatantToBack(int from) { - moveCombatant(from, m_combatants.size() - 1); + moveCombatant(from, static_cast(m_combatants.size()) - 1); } void CombatTrackerState::addCombatant(Combatant *combatant) diff --git a/src/tools/converter/convertereditor.cpp b/src/tools/converter/convertereditor.cpp index 4a6bb372..fb08710d 100644 --- a/src/tools/converter/convertereditor.cpp +++ b/src/tools/converter/convertereditor.cpp @@ -3,7 +3,6 @@ #include "src/common/utils/fileutils.h" #include #include -#include using namespace Qt::Literals::StringLiterals; @@ -19,7 +18,7 @@ auto ConverterEditor::createProject(const QString &name) -> bool { if (name.isEmpty()) return false; - gsl::owner project = new ConverterProject(name, this); + auto *project = new ConverterProject(name, this); a_projects << project; emit projectsChanged(); @@ -61,7 +60,7 @@ auto ConverterEditor::createCategory(const QString &name) -> bool { if (!currentProject() || name.isEmpty()) return false; - gsl::owner category = new ConverterCategory(name, currentProject()); + auto *category = new ConverterCategory(name, currentProject()); auto categories = currentProject()->categories(); categories << category; @@ -119,7 +118,7 @@ auto ConverterEditor::createUnit(const QString &name, const QString &value) -> b if (!ok) return false; - gsl::owner unit = new ConverterUnit(name, number, currentCategory()); + auto *unit = new ConverterUnit(name, number, currentCategory()); auto units = currentCategory()->units(); units << unit; @@ -212,7 +211,7 @@ void ConverterEditor::onProjectsChanged() currentProject(a_projects.constFirst()); } -void ConverterEditor::onCurrentProjectChanged(ConverterProject *project) +void ConverterEditor::onCurrentProjectChanged(const ConverterProject *project) { if (!project) return; @@ -244,8 +243,10 @@ void ConverterEditor::backupV1Projects() if (entries.isEmpty()) return; - QDir const backupDir(backupPath); - if (!backupDir.exists()) backupDir.mkpath(backupPath); + if (QDir const backupDir(backupPath); !backupDir.exists()) + { + backupDir.mkpath(backupPath); + } for (const auto &entry : entries) { diff --git a/src/tools/converter/convertereditor.h b/src/tools/converter/convertereditor.h index 7aa2ad21..2ee8e5a4 100644 --- a/src/tools/converter/convertereditor.h +++ b/src/tools/converter/convertereditor.h @@ -41,7 +41,7 @@ public slots: private slots: void onProjectsChanged(); - void onCurrentProjectChanged(ConverterProject *project); + void onCurrentProjectChanged(const ConverterProject *project); private: static auto getLocalProjectPath() -> QString; diff --git a/src/tools/converter/convertertool.cpp b/src/tools/converter/convertertool.cpp index 819cf672..2639b9f6 100644 --- a/src/tools/converter/convertertool.cpp +++ b/src/tools/converter/convertertool.cpp @@ -60,7 +60,7 @@ void ConverterTool::onProjectsChanged() currentProject(a_projects.constFirst()); } -void ConverterTool::onCurrentProjectChanged(ConverterProject *project) +void ConverterTool::onCurrentProjectChanged(const ConverterProject *project) { if (!project || project->categories().isEmpty()) { @@ -72,7 +72,7 @@ void ConverterTool::onCurrentProjectChanged(ConverterProject *project) currentCategory(categories.first()); } -void ConverterTool::onCurrentCategoryChanged(ConverterCategory *category) +void ConverterTool::onCurrentCategoryChanged(const ConverterCategory *category) { if (!category || category->units().isEmpty()) { @@ -192,7 +192,8 @@ void ConverterTool::forceReloadData() loadData(); } -auto ConverterTool::convert(ConverterUnit *fromUnit, const QString &fromValue, ConverterUnit *toUnit) -> QString +auto ConverterTool::convert(const ConverterUnit *fromUnit, const QString &fromValue, const ConverterUnit *toUnit) + -> QString { if (!fromUnit || !toUnit) return u""_s; diff --git a/src/tools/converter/convertertool.h b/src/tools/converter/convertertool.h index 150f6042..d740c8a7 100644 --- a/src/tools/converter/convertertool.h +++ b/src/tools/converter/convertertool.h @@ -25,7 +25,7 @@ class ConverterTool : public AbstractTool explicit ConverterTool(QObject *parent = nullptr); static auto create(QQmlEngine *qmlEngine, QJSEngine *jsEngine) -> ConverterTool *; - Q_INVOKABLE static QString convert(ConverterUnit *fromUnit, const QString &fromValue, ConverterUnit *toUnit); + Q_INVOKABLE static QString convert(const ConverterUnit *fromUnit, const QString &fromValue, const ConverterUnit *toUnit); Q_PROPERTY(ConverterEditor *editor READ editor CONSTANT) [[nodiscard]] auto editor() -> ConverterEditor *; @@ -41,8 +41,8 @@ public slots: private slots: void onProjectsChanged(); - void onCurrentProjectChanged(ConverterProject *project); - void onCurrentCategoryChanged(ConverterCategory *category); + void onCurrentProjectChanged(const ConverterProject *project); + void onCurrentCategoryChanged(const ConverterCategory *category); void onEditorSavedChanged(bool isSaved); void onAddonManagerLoadingChanged(bool isLoading); diff --git a/src/tools/dicetool.cpp b/src/tools/dicetool.cpp index 75a07d8d..2623f232 100644 --- a/src/tools/dicetool.cpp +++ b/src/tools/dicetool.cpp @@ -63,8 +63,10 @@ auto DiceTool::getSuccessMax() -> int auto DiceTool::roll() -> int { int result = 0; - int criticalSuccesses = 0, criticalFailures = 0; - int criticalSuccess = 0, criticalFailure = 0; + int criticalSuccesses = 0; + int criticalFailures = 0; + int criticalSuccess = 0; + int criticalFailure = 0; // Initialize values for crits if (getMinMax()) @@ -102,7 +104,7 @@ auto DiceTool::roll() -> int for (int i = 0; i < m_amount; i++) { // Generate random integer - int temp = rand() % m_sides + 1; + int temp = QRandomGenerator::system()->bounded(m_sides) + 1; // Check for critical successes or failures if (temp == criticalSuccess) criticalSuccesses++; diff --git a/src/tools/generators/names/abstractnamegenerator.cpp b/src/tools/generators/names/abstractnamegenerator.cpp index 7dbc5cc9..7be3832e 100644 --- a/src/tools/generators/names/abstractnamegenerator.cpp +++ b/src/tools/generators/names/abstractnamegenerator.cpp @@ -6,7 +6,7 @@ AbstractNameGenerator::AbstractNameGenerator(QObject *parent, QString name, QStr QStringList prefixes, QStringList suffixes) : QObject{parent}, a_name{std::move(name)}, a_categories(std::move(categories)), a_prefixes(std::move(prefixes)), a_suffixes(std::move(suffixes)), a_generatedNames(buildEmptyNameList()), - a_enabledCategories(buildInitialEnabledCategoryList()), a_activePrefix(0), a_activeSuffix(0) + a_enabledCategories(buildInitialEnabledCategoryList()) { } diff --git a/src/tools/generators/names/abstractnamegenerator.h b/src/tools/generators/names/abstractnamegenerator.h index c1cec914..8e5d447b 100644 --- a/src/tools/generators/names/abstractnamegenerator.h +++ b/src/tools/generators/names/abstractnamegenerator.h @@ -25,8 +25,8 @@ class AbstractNameGenerator : public QObject AUTO_PROPERTY(QList, generatedNames) AUTO_PROPERTY(QList, enabledCategories) - AUTO_PROPERTY_VAL(int, activePrefix) - AUTO_PROPERTY_VAL(int, activeSuffix) + AUTO_PROPERTY_VAL2(int, activePrefix, 0) + AUTO_PROPERTY_VAL2(int, activeSuffix, 0) private: [[nodiscard]] auto buildEmptyNameList() const -> QList; diff --git a/src/tools/generators/names/namegenerator.cpp b/src/tools/generators/names/namegenerator.cpp index 9afaddf2..55b5b281 100644 --- a/src/tools/generators/names/namegenerator.cpp +++ b/src/tools/generators/names/namegenerator.cpp @@ -73,9 +73,9 @@ auto NameGenerator::findAndReadAllFiles(const QString &path) -> QByteArrayList QByteArrayList result; result.reserve(entries.length()); - for (int i = 0; i < entries.length(); i++) + foreach (const auto &entry, entries) { - QFile file(FileUtils::fileInDir(entries[i], path)); + QFile file(FileUtils::fileInDir(entry, path)); if (file.open(QIODevice::ReadOnly)) { diff --git a/src/tools/maps/map.h b/src/tools/maps/map.h index d8238bda..7a667542 100644 --- a/src/tools/maps/map.h +++ b/src/tools/maps/map.h @@ -61,12 +61,12 @@ class MapListModel : public QAbstractListModel [[nodiscard]] auto rowCount(const QModelIndex & /*parent*/) const -> int override { - return m_items.size(); + return size(); } [[nodiscard]] auto data(const QModelIndex &index, int role) const -> QVariant override; [[nodiscard]] auto size() const -> int { - return m_items.size(); + return static_cast(m_items.size()); } void setElements(QList elements); diff --git a/src/tools/maps/mapmarker.cpp b/src/tools/maps/mapmarker.cpp index 87f6894a..b4a6d4ee 100644 --- a/src/tools/maps/mapmarker.cpp +++ b/src/tools/maps/mapmarker.cpp @@ -38,7 +38,7 @@ void MapMarkerModel::insert(QObject *item) endInsertRows(); } -void MapMarkerModel::remove(QObject *item) +void MapMarkerModel::remove(const QObject *item) { for (int i = 0; i < m_items.size(); ++i) { @@ -72,9 +72,9 @@ void MapMarkerModel::setElements(const QList &elements) { clear(); - for (int i = elements.size() - 1; i > -1; i--) + for (auto i = elements.size() - 1; i > -1; i--) { - insert(elements[i]); + insert(elements.at(i)); } } diff --git a/src/tools/maps/mapmarker.h b/src/tools/maps/mapmarker.h index 448f8b5f..850d6833 100644 --- a/src/tools/maps/mapmarker.h +++ b/src/tools/maps/mapmarker.h @@ -17,8 +17,8 @@ class MapMarker : public QObject AUTO_PROPERTY(QString, description) AUTO_PROPERTY(QString, color) AUTO_PROPERTY(QString, icon) - Q_PROPERTY(int x READ x NOTIFY xChanged) - Q_PROPERTY(int y READ y NOTIFY yChanged) + Q_PROPERTY(qreal x READ x NOTIFY xChanged) + Q_PROPERTY(qreal y READ y NOTIFY yChanged) public: explicit MapMarker(const QString &name, const QString &description, qreal x, qreal y, const QString &icon, @@ -50,7 +50,8 @@ class MapMarker : public QObject void yChanged(); private: - qreal m_x = 0, m_y = 0; + qreal m_x = 0; + qreal m_y = 0; }; // Model for QML @@ -64,11 +65,11 @@ class MapMarkerModel : public QAbstractListModel [[nodiscard]] auto rowCount(const QModelIndex & /*parent*/) const -> int override { - return m_items.size(); + return size(); } [[nodiscard]] auto size() const -> int { - return m_items.size(); + return static_cast(m_items.size()); } [[nodiscard]] auto data(const QModelIndex &index, int role) const -> QVariant override; @@ -92,7 +93,7 @@ class MapMarkerModel : public QAbstractListModel public slots: void insert(QObject *item); - void remove(QObject *item); + void remove(const QObject *item); protected: [[nodiscard]] auto roleNames() const -> QHash override; diff --git a/src/tools/maps/maptool.cpp b/src/tools/maps/maptool.cpp index a11a0a68..dd64d675 100644 --- a/src/tools/maps/maptool.cpp +++ b/src/tools/maps/maptool.cpp @@ -143,8 +143,7 @@ void MapTool::setMapIndex(int index) auto MapTool::currentMarker() const -> MapMarker * { - const auto &elements = m_mapMarkerModel.elements(); - if (Utils::isInBounds(elements, markerIndex())) + if (const auto &elements = m_mapMarkerModel.elements(); Utils::isInBounds(elements, markerIndex())) { return m_mapMarkerModel.elements().at(markerIndex()); } @@ -179,7 +178,7 @@ void MapTool::findCategories() qCDebug(gmMapsTool()) << "Finding map categories ..."; const auto dir = SettingsManager::getPath(u"maps"_s); - Files::File::listAsync(dir, false, true).then([this](Files::FileListResult &&result) { + Files::File::listAsync(dir, false, true).then([this](const Files::FileListResult &result) { receivedCategories(result.folders()); }); } diff --git a/src/tools/notes/markdownhighlighter.cpp b/src/tools/notes/markdownhighlighter.cpp index f736a4ca..1f2f1f47 100644 --- a/src/tools/notes/markdownhighlighter.cpp +++ b/src/tools/notes/markdownhighlighter.cpp @@ -62,9 +62,9 @@ void MarkdownHighlighter::applyRegexMatch(const QString &text, const QString &re { auto match = iterator.next(); - for (int i = match.capturedStart(group); i < match.capturedEnd(group); i++) + for (auto i = match.capturedStart(group); i < match.capturedEnd(group); i++) { - setFormat(i, 1, combineFormats(format(i), charFormat)); + setFormat(static_cast(i), 1, combineFormats(format(i), charFormat)); } } } @@ -85,9 +85,9 @@ auto MarkdownHighlighter::combineFormats(const QTextCharFormat &one, const QText format.setForeground(one.foreground()); } - auto isTypeWriter = one.fontStyleHint() == QFont::TypeWriter || two.fontStyleHint() == QFont::TypeWriter; - - if (isTypeWriter) format.setFontStyleHint(QFont::TypeWriter); + if (auto isTypeWriter = one.fontStyleHint() == QFont::TypeWriter || two.fontStyleHint() == QFont::TypeWriter; + isTypeWriter) + format.setFontStyleHint(QFont::TypeWriter); return format; } diff --git a/src/tools/notes/notessaveload.cpp b/src/tools/notes/notessaveload.cpp index 62e209d9..42edd120 100644 --- a/src/tools/notes/notessaveload.cpp +++ b/src/tools/notes/notessaveload.cpp @@ -22,7 +22,7 @@ void NotesSaveLoad::loadBooks() const auto directory = SettingsManager::getPath(u"notes"_s); - Files::File::listAsync(directory, false, true).then([this](Files::FileListResult &&result) { + Files::File::listAsync(directory, false, true).then([this](const Files::FileListResult &result) { buildBooks(result.folders(), nullptr); }); } @@ -30,7 +30,7 @@ void NotesSaveLoad::loadBooks() /** * Load chapter directories in book directory */ -void NotesSaveLoad::loadChapters() +void NotesSaveLoad::loadChapters() const { QPointer book = qobject_cast(sender()); if (!book) return; @@ -39,7 +39,7 @@ void NotesSaveLoad::loadChapters() qCDebug(gmNotesSaveLoad()) << "Loading chapters in" << directory; - Files::File::listAsync(directory, false, true).then([this, book](Files::FileListResult &&result) { + Files::File::listAsync(directory, false, true).then([this, book](const Files::FileListResult &result) { if (!book) return; buildChapters(result.folders(), *book); }); @@ -66,7 +66,7 @@ void NotesSaveLoad::loadPages() /** * Load content from page file */ -void NotesSaveLoad::loadPageContent() +void NotesSaveLoad::loadPageContent() const { QPointer page = qobject_cast(sender()); if (!page) return; @@ -75,7 +75,7 @@ void NotesSaveLoad::loadPageContent() qCDebug(gmNotesSaveLoad()) << "Loading page content of" << fileName; - Files::File::getDataAsync(fileName).then([page](Files::FileDataResult &&result) { + Files::File::getDataAsync(fileName).then([page](const Files::FileDataResult &result) { if (!page) return; page->onContentLoaded(result.data()); }); @@ -84,7 +84,7 @@ void NotesSaveLoad::loadPageContent() /** * Write page content to file */ -void NotesSaveLoad::savePage() +void NotesSaveLoad::savePage() const { QPointer page = qobject_cast(sender()); if (!page) return; @@ -93,7 +93,7 @@ void NotesSaveLoad::savePage() qCDebug(gmNotesSaveLoad()) << "Saving page content of" << fileName; - Files::File::saveAsync(fileName, page->content().toUtf8()).then([page](Files::FileResult &&result) { + Files::File::saveAsync(fileName, page->content().toUtf8()).then([page](const Files::FileResult &result) { if (!page) return; page->setIsSaved(result.success()); }); @@ -102,7 +102,7 @@ void NotesSaveLoad::savePage() /** * Rename a chapter folder */ -void NotesSaveLoad::renameChapter(const QString &oldPath) +void NotesSaveLoad::renameChapter(const QString &oldPath) const { const auto *chapter = qobject_cast(sender()); if (!chapter || oldPath == chapter->path()) return; @@ -119,7 +119,7 @@ void NotesSaveLoad::renameChapter(const QString &oldPath) /** * Rename a page file to it's new name */ -void NotesSaveLoad::renamePage(const QString &oldPath) +void NotesSaveLoad::renamePage(const QString &oldPath) const { const QPointer page = qobject_cast(sender()); if (!page || oldPath == page->path()) return; @@ -136,7 +136,7 @@ void NotesSaveLoad::renamePage(const QString &oldPath) /** * Delete chapter folder */ -void NotesSaveLoad::deleteChapter() +void NotesSaveLoad::deleteChapter() const { QPointer chapter = qobject_cast(sender()); if (!chapter) return; @@ -149,7 +149,7 @@ void NotesSaveLoad::deleteChapter() for (auto *page : pages) page->close(); - Files::File::deleteAsync(path).then([chapter](Files::FileResult &&result) { + Files::File::deleteAsync(path).then([chapter](const Files::FileResult &result) { if (!chapter) return; if (result.success()) @@ -167,7 +167,7 @@ void NotesSaveLoad::deleteChapter() /** * Delete page file */ -void NotesSaveLoad::deletePage() +void NotesSaveLoad::deletePage() const { QPointer page = qobject_cast(sender()); if (!page) return; @@ -178,7 +178,7 @@ void NotesSaveLoad::deletePage() page->close(); - Files::File::deleteAsync(path).then([page](Files::FileResult &&result) { + Files::File::deleteAsync(path).then([page](const Files::FileResult &result) { if (!page) return; if (result.success()) @@ -202,8 +202,8 @@ void NotesSaveLoad::createBook(const QString &name, TreeItem *root) qCDebug(gmNotesSaveLoad()) << "Creating book" << name; const auto path = FileUtils::fileInDir(name, SettingsManager::getPath(u"notes"_s)); - Files::File::createDirAsync(path).then([this, name, root](Files::FileResult &&) { - if (!root) return; + Files::File::createDirAsync(path).then([this, name, root](const Files::FileResult &result) { + if (!root || !result.success()) return; buildBooks({name}, root); }); } @@ -211,7 +211,7 @@ void NotesSaveLoad::createBook(const QString &name, TreeItem *root) /** * Create a new chapter folder */ -void NotesSaveLoad::createChapter(const QString &name) +void NotesSaveLoad::createChapter(const QString &name) const { if (name.isEmpty()) return; @@ -229,8 +229,8 @@ void NotesSaveLoad::createChapter(const QString &name) const auto localPath = FileUtils::fileInDir(name, book->path()); const auto path = FileUtils::fileInDir(localPath, SettingsManager::getPath(u"notes"_s)); - Files::File::createDirAsync(path).then([this, name, book](Files::FileResult &&) { - if (!book) return; + Files::File::createDirAsync(path).then([this, name, book](const Files::FileResult &result) { + if (!book || !result.success()) return; buildChapters({name}, *book); }); } @@ -265,7 +265,7 @@ void NotesSaveLoad::createPage(const QString &name) const auto path = FileUtils::fileInDir(localPath, SettingsManager::getPath(u"notes"_s)); const auto data = "# " + name.toUtf8() + "\n"; - Files::File::saveAsync(path, data).then([this, correctName, chapter](Files::FileResult &&result) { + Files::File::saveAsync(path, data).then([this, correctName, chapter](const Files::FileResult &result) { if (!chapter) return; if (!result.success()) @@ -284,7 +284,7 @@ void NotesSaveLoad::createPage(const QString &name) /** * Save the page as a PDF */ -void NotesSaveLoad::exportPage(NoteBookPage &page, const QTextDocument &document) +void NotesSaveLoad::exportPage(const NoteBookPage &page, const QTextDocument &document) { qCDebug(gmNotesSaveLoad()) << "Exporting page as pdf ..."; diff --git a/src/tools/notes/notessaveload.h b/src/tools/notes/notessaveload.h index ae926b83..a51586be 100644 --- a/src/tools/notes/notessaveload.h +++ b/src/tools/notes/notessaveload.h @@ -10,7 +10,7 @@ class NotesSaveLoad : public QObject public: using QObject::QObject; - static void exportPage(NoteBookPage &page, const QTextDocument &document); + static void exportPage(const NoteBookPage &page, const QTextDocument &document); public slots: void loadBooks(); @@ -29,17 +29,17 @@ public slots: static auto getPdfPath(const NoteBookPage &page) -> QString; private slots: - void loadChapters(); + void loadChapters() const; void loadPages(); - void loadPageContent(); - void savePage(); + void loadPageContent() const; + void savePage() const; - void createChapter(const QString &name); + void createChapter(const QString &name) const; void createPage(const QString &name); - void renameChapter(const QString &oldPath); - void renamePage(const QString &oldPath); + void renameChapter(const QString &oldPath) const; + void renamePage(const QString &oldPath) const; - void deleteChapter(); - void deletePage(); + void deleteChapter() const; + void deletePage() const; }; diff --git a/src/tools/notes/notestool.cpp b/src/tools/notes/notestool.cpp index 1766ea12..1acc2e75 100644 --- a/src/tools/notes/notestool.cpp +++ b/src/tools/notes/notestool.cpp @@ -29,8 +29,7 @@ void NotesTool::setQmlTextDoc(QQuickTextDocument *qmlTextDoc) if (!m_qmlTextDoc || !m_qmlTextDoc->textDocument()) return; // Load style sheet - QFile f(u":/notes/style.css"_s); - if (f.open(QIODevice::ReadOnly)) + if (QFile f(u":/notes/style.css"_s); f.open(QIODevice::ReadOnly)) { const QString style = f.readAll(); m_qmlTextDoc->textDocument()->setDefaultStyleSheet(style); @@ -104,10 +103,10 @@ void NotesTool::exportPdf() { if (editMode() || !m_currentPage || !m_qmlTextDoc) return; - auto *textDoc = m_qmlTextDoc->textDocument(); + const auto *textDoc = m_qmlTextDoc->textDocument(); if (!textDoc) return; - m_saveLoad.exportPage(*m_currentPage, *textDoc); + NotesSaveLoad::exportPage(*m_currentPage, *textDoc); } /** @@ -129,7 +128,7 @@ void NotesTool::createBook(const QString &name) /** * Connect signals of newly loaded pages */ -void NotesTool::onPagesLoaded(const QList &pages) +void NotesTool::onPagesLoaded(const QList &pages) const { foreach (const auto *page, pages) { @@ -200,7 +199,7 @@ void NotesTool::onClosePage() { qCDebug(gmNotesTool()) << "Closing page ..."; - int i = 0; + qsizetype i = 0; foreach (auto *page, a_openedPages) { @@ -215,11 +214,15 @@ void NotesTool::onClosePage() break; } - if (i >= a_openedPages.length()) i = a_openedPages.length() - 1; - - auto *newPage = a_openedPages.at(i); + if (i >= a_openedPages.length()) + { + i = a_openedPages.length() - 1; + } - if (newPage) newPage->toggle(); + if (auto *newPage = a_openedPages.at(i); newPage) + { + newPage->toggle(); + } break; } @@ -261,7 +264,7 @@ void NotesTool::onDocumentEdited() { if (!m_currentPage || !m_qmlTextDoc) return; - auto *doc = m_qmlTextDoc->textDocument(); + const auto *doc = m_qmlTextDoc->textDocument(); if (editMode()) { diff --git a/src/tools/notes/notestool.h b/src/tools/notes/notestool.h index 9b6aeca6..d3e36591 100644 --- a/src/tools/notes/notestool.h +++ b/src/tools/notes/notestool.h @@ -74,7 +74,7 @@ public slots: private slots: void onNoteBooksLoaded(TreeItem *root); - void onPagesLoaded(const QList &pages); + void onPagesLoaded(const QList &pages) const; void onPageClicked(); void onPageContentLoaded(); void onPageHtmlLoaded(); diff --git a/src/tools/shop/baseshoptool.cpp b/src/tools/shop/baseshoptool.cpp index 4facb644..b448895f 100644 --- a/src/tools/shop/baseshoptool.cpp +++ b/src/tools/shop/baseshoptool.cpp @@ -35,10 +35,10 @@ void BaseShopTool::onShopFilesFound(Files::FileListResult &&result) } Files::File::getDataAsync(files).then( - [this](std::vector &&results) { onShopFileDataReceived(std::move(results)); }); + [this](const std::vector &results) { onShopFileDataReceived(results); }); } -void BaseShopTool::onShopFileDataReceived(std::vector &&results) +void BaseShopTool::onShopFileDataReceived(const std::vector &results) { qCDebug(gmShopsBaseTool()) << "Loading" << results.size() << "projects ..."; diff --git a/src/tools/shop/baseshoptool.h b/src/tools/shop/baseshoptool.h index ae38e2db..0885274b 100644 --- a/src/tools/shop/baseshoptool.h +++ b/src/tools/shop/baseshoptool.h @@ -28,7 +28,7 @@ public slots: protected: void onShopFilesFound(Files::FileListResult &&result); - void onShopFileDataReceived(std::vector &&results); + void onShopFileDataReceived(const std::vector &results); void setFirstProjectAsCurrent(); }; diff --git a/src/tools/shop/itemeditor.cpp b/src/tools/shop/itemeditor.cpp index 274e3739..83f3d8ee 100644 --- a/src/tools/shop/itemeditor.cpp +++ b/src/tools/shop/itemeditor.cpp @@ -63,9 +63,9 @@ auto ItemEditor::addItem(const QString &name, const QString &price, const QStrin if (name.isEmpty() || category.isEmpty()) return false; auto *item = new Item(name, price, description.replace("\n"_L1, " "_L1), category, this); - const auto insert = Item::findLastIndexWithCategory(category, Utils::toList(m_itemModel.getAll())) + 1; - if (insert <= 0) + if (const auto insert = Item::findLastIndexWithCategory(category, Utils::toList(m_itemModel.getAll())) + 1; + insert <= 0) { m_itemModel.append(item); } @@ -130,7 +130,7 @@ void ItemEditor::loadData() const auto path = FileUtils::fileInDir(u"CustomItems.items"_s, SettingsManager::getPath(u"shops"_s)); Files::File::checkAsync(path) - .then([this](Files::FileCheckResult &&result) { onFileCheckReceived(std::move(result)); }) + .then([this](const Files::FileCheckResult &result) { onFileCheckReceived(result); }) .onCanceled([this]() { isLoading(false); }); } @@ -147,22 +147,22 @@ auto ItemEditor::defaultGroupName() -> QString return tr("Custom"); } -void ItemEditor::onFileCheckReceived(Files::FileCheckResult &&result) +void ItemEditor::onFileCheckReceived(const Files::FileCheckResult &checkResult) { - const auto &path = result.path(); + const auto &path = checkResult.path(); - if (!result.success() || !result.exists()) + if (!checkResult.success() || !checkResult.exists()) { isLoading(false); return; } Files::File::getDataAsync(path) - .then([this](Files::FileDataResult &&result) { onDataReceived(std::move(result)); }) + .then([this](const Files::FileDataResult &dataResult) { onDataReceived(dataResult); }) .onCanceled([this]() { isLoading(false); }); } -void ItemEditor::onDataReceived(Files::FileDataResult &&result) +void ItemEditor::onDataReceived(const Files::FileDataResult &result) { if (!result.success()) { diff --git a/src/tools/shop/itemeditor.h b/src/tools/shop/itemeditor.h index a2a587d4..55fd7cbd 100644 --- a/src/tools/shop/itemeditor.h +++ b/src/tools/shop/itemeditor.h @@ -50,6 +50,6 @@ public slots: static auto defaultGroupName() -> QString; - void onFileCheckReceived(Files::FileCheckResult &&result); - void onDataReceived(Files::FileDataResult &&result); + void onFileCheckReceived(const Files::FileCheckResult &checkResult); + void onDataReceived(const Files::FileDataResult &result); }; diff --git a/src/tools/shop/project/item.cpp b/src/tools/shop/project/item.cpp index fd626603..761f9000 100644 --- a/src/tools/shop/project/item.cpp +++ b/src/tools/shop/project/item.cpp @@ -32,9 +32,9 @@ auto Item::toJson() const -> QJsonObject return QJsonObject{{"name", name()}, {"price", price()}, {"description", description()}, {"category", category()}}; } -auto Item::findLastIndexWithCategory(const QString &category, const QList &items) -> int +auto Item::findLastIndexWithCategory(const QString &category, const QList &items) -> qsizetype { - for (int i = items.size() - 1; i >= 0; i--) + for (auto i = items.size() - 1; i >= 0; i--) { if (items.at(i) && items.at(i)->category() == category) return i; } diff --git a/src/tools/shop/project/item.h b/src/tools/shop/project/item.h index 64706b4b..a0b7a768 100644 --- a/src/tools/shop/project/item.h +++ b/src/tools/shop/project/item.h @@ -27,7 +27,7 @@ class Item : public BaseProjectItem [[nodiscard]] auto toJson() const -> QJsonObject; - static auto findLastIndexWithCategory(const QString &category, const QList &items) -> int; + static auto findLastIndexWithCategory(const QString &category, const QList &items) -> qsizetype; }; class ItemModel : public CustomObjectListModel diff --git a/src/tools/shop/project/itemshop.cpp b/src/tools/shop/project/itemshop.cpp index f2d2a51b..5bde1178 100644 --- a/src/tools/shop/project/itemshop.cpp +++ b/src/tools/shop/project/itemshop.cpp @@ -70,11 +70,14 @@ void ItemShop::addItem(const Item &item) { auto *copy = new Item(item, this); - int insert = Item::findLastIndexWithCategory(copy->category(), items()) + 1; - - if (insert <= 0) a_items.append(copy); + if (auto insert = Item::findLastIndexWithCategory(copy->category(), items()) + 1; insert <= 0) + { + a_items.append(copy); + } else + { a_items.insert(insert, copy); + } emit itemsChanged(a_items); } @@ -90,7 +93,7 @@ auto ItemShop::deleteItem(int index) -> bool return true; } -void ItemShop::connectSignals() +void ItemShop::connectSignals() const { connect(this, &ItemShop::ownerChanged, this, &ItemShop::wasEdited); connect(this, &ItemShop::descriptionChanged, this, &ItemShop::wasEdited); diff --git a/src/tools/shop/project/itemshop.h b/src/tools/shop/project/itemshop.h index 23eb4d06..6e797d43 100644 --- a/src/tools/shop/project/itemshop.h +++ b/src/tools/shop/project/itemshop.h @@ -29,5 +29,5 @@ class ItemShop : public BaseProjectItem auto deleteItem(int index) -> bool; private: - void connectSignals(); + void connectSignals() const; }; diff --git a/src/tools/shop/project/shopcategory.cpp b/src/tools/shop/project/shopcategory.cpp index 8934366a..51563109 100644 --- a/src/tools/shop/project/shopcategory.cpp +++ b/src/tools/shop/project/shopcategory.cpp @@ -60,9 +60,9 @@ void ShopCategory::addShop(ItemShop *shop) } /// Delete a shop, returns the shop's index -auto ShopCategory::deleteShop(ItemShop *shop) -> int +auto ShopCategory::deleteShop(ItemShop *shop) -> qsizetype { - const int index = a_shops.indexOf(shop); + const auto index = a_shops.indexOf(shop); if (index < 0) return index; a_shops.removeAt(index); @@ -74,7 +74,7 @@ auto ShopCategory::deleteShop(ItemShop *shop) -> int auto ShopCategory::moveShop(ItemShop *shop, int positions) -> bool { - const int index = a_shops.indexOf(shop); + const auto index = a_shops.indexOf(shop); if (!Utils::isInBounds(a_shops, index + positions)) return false; @@ -83,20 +83,20 @@ auto ShopCategory::moveShop(ItemShop *shop, int positions) -> bool return true; } -void ShopCategory::connectShops() +void ShopCategory::connectShops() const { - foreach (auto *shop, shops()) + foreach (const auto *shop, shops()) { connectShop(shop); } } -void ShopCategory::connectShop(ItemShop *shop) +void ShopCategory::connectShop(const ItemShop *shop) const { connect(shop, &ItemShop::wasEdited, this, &ShopCategory::wasEdited); } -void ShopCategory::connectSignals() +void ShopCategory::connectSignals() const { connect(this, &ShopCategory::shopsChanged, this, &ShopCategory::wasEdited); } diff --git a/src/tools/shop/project/shopcategory.h b/src/tools/shop/project/shopcategory.h index 2087edbf..262d3ace 100644 --- a/src/tools/shop/project/shopcategory.h +++ b/src/tools/shop/project/shopcategory.h @@ -23,11 +23,11 @@ class ShopCategory : public BaseProjectItem [[nodiscard]] auto toJson() const -> QJsonObject; void addShop(ItemShop *shop); - auto deleteShop(ItemShop *shop) -> int; + auto deleteShop(ItemShop *shop) -> qsizetype; auto moveShop(ItemShop *shop, int positions) -> bool; private: - void connectShops(); - void connectShop(ItemShop *shop); - void connectSignals(); + void connectShops() const; + void connectShop(const ItemShop *shop) const; + void connectSignals() const; }; diff --git a/src/tools/shop/project/shopproject.cpp b/src/tools/shop/project/shopproject.cpp index 55e6fae6..d80a375b 100644 --- a/src/tools/shop/project/shopproject.cpp +++ b/src/tools/shop/project/shopproject.cpp @@ -98,7 +98,7 @@ auto ShopProject::deleteCategory(ShopCategory *category) -> bool return true; } -void ShopProject::onCurrentCategoryChanged(ShopCategory *category) +void ShopProject::onCurrentCategoryChanged(const ShopCategory *category) { if (m_categoryConnection) { @@ -124,7 +124,7 @@ void ShopProject::connectSignals() const connect(this, &ShopProject::categoriesChanged, this, &ShopProject::wasEdited); } -void ShopProject::connectCategories() +void ShopProject::connectCategories() const { foreach (auto *category, categories()) { @@ -132,7 +132,7 @@ void ShopProject::connectCategories() } } -void ShopProject::connectCategory(ShopCategory *category) const +void ShopProject::connectCategory(const ShopCategory *category) const { connect(category, &ShopCategory::wasEdited, this, &ShopProject::wasEdited); } diff --git a/src/tools/shop/project/shopproject.h b/src/tools/shop/project/shopproject.h index 0e724219..7e7fe07c 100644 --- a/src/tools/shop/project/shopproject.h +++ b/src/tools/shop/project/shopproject.h @@ -33,13 +33,13 @@ class ShopProject : public BaseProjectItem void currentShopChanged(ItemShop *currentShop); private slots: - void onCurrentCategoryChanged(ShopCategory *category); + void onCurrentCategoryChanged(const ShopCategory *category); void onWasEdited(); private: void connectSignals() const; - void connectCategories(); - void connectCategory(ShopCategory *category) const; + void connectCategories() const; + void connectCategory(const ShopCategory *category) const; QMetaObject::Connection m_categoryConnection; }; diff --git a/src/tools/shop/shopeditor.cpp b/src/tools/shop/shopeditor.cpp index 8c279b00..5016a522 100644 --- a/src/tools/shop/shopeditor.cpp +++ b/src/tools/shop/shopeditor.cpp @@ -71,7 +71,7 @@ void ShopEditor::onItemFilesFound(Files::FileListResult &&result) return; } - Files::File::getDataAsync(files).then([this](std::vector &&results) { + Files::File::getDataAsync(files).then([this](const std::vector &results) { QList groups = {}; groups.reserve(results.size()); @@ -122,14 +122,14 @@ auto ShopEditor::deleteProject(ShopProject *project) -> bool return true; } -auto ShopEditor::deleteCategory(ShopCategory *category) -> bool +auto ShopEditor::deleteCategory(ShopCategory *category) const -> bool { if (!currentProject() || !category) return false; return currentProject()->deleteCategory(category); } -auto ShopEditor::moveShop(int positions) -> bool +auto ShopEditor::moveShop(int positions) const -> bool { qCDebug(gmShopsEditor()) << "Moving shop by" << positions << "position(s) ..."; @@ -139,11 +139,11 @@ auto ShopEditor::moveShop(int positions) -> bool } /// Delete the current shop -auto ShopEditor::deleteShop() -> bool +auto ShopEditor::deleteShop() const -> bool { if (!isCurrentShopValid()) return false; - const qsizetype index = currentProject()->currentCategory()->deleteShop(currentShop()); + const auto index = currentProject()->currentCategory()->deleteShop(currentShop()); if (!currentProject()->currentCategory()->shops().isEmpty()) { @@ -249,7 +249,7 @@ auto ShopEditor::createShop(const QString &name) -> bool return true; } -void ShopEditor::connectProject(ShopProject *project) const +void ShopEditor::connectProject(const ShopProject *project) const { connect(project, &ShopProject::wasEdited, this, &ShopEditor::onProjectWasEdited); connect(project, &ShopProject::currentShopChanged, this, &ShopEditor::onCurrentShopChanged); @@ -347,7 +347,7 @@ void ShopEditor::onProjectWasEdited() madeChanges(); } -void ShopEditor::onCurrentProjectChanged(ShopProject *currentProject) +void ShopEditor::onCurrentProjectChanged(const ShopProject *currentProject) { if (!currentProject || !currentProject->currentCategory()) { @@ -358,7 +358,7 @@ void ShopEditor::onCurrentProjectChanged(ShopProject *currentProject) onCurrentShopChanged(currentProject->currentCategory()->currentShop()); } -void ShopEditor::onCurrentShopChanged(ItemShop *currentShop) +void ShopEditor::onCurrentShopChanged(const ItemShop *currentShop) { if (!currentShop) { @@ -369,7 +369,7 @@ void ShopEditor::onCurrentShopChanged(ItemShop *currentShop) m_itemModelShop.replaceAll(Utils::toQObjectList(currentShop->items())); } -void ShopEditor::onCurrentItemGroupChanged(ItemGroup *currentGroup) +void ShopEditor::onCurrentItemGroupChanged(const ItemGroup *currentGroup) { if (!currentGroup) { @@ -386,7 +386,7 @@ void ShopEditor::onDisabledItemCategoriesChanged(const QStringList &categories) m_itemModelGroupProxy.setFilterRegularExpression(ex); } -void ShopEditor::onIsLoadingChanged(bool isLoading) +void ShopEditor::onIsLoadingChanged(bool isLoading) const { if (isLoading) return; diff --git a/src/tools/shop/shopeditor.h b/src/tools/shop/shopeditor.h index 74937a20..3c12c74c 100644 --- a/src/tools/shop/shopeditor.h +++ b/src/tools/shop/shopeditor.h @@ -46,10 +46,10 @@ class ShopEditor : public BaseShopTool Q_INVOKABLE bool createThing(const QString &name, ShopEditor::Type type); Q_INVOKABLE bool deleteProject(ShopProject *project); - Q_INVOKABLE bool deleteCategory(ShopCategory *category); + Q_INVOKABLE bool deleteCategory(ShopCategory *category) const; - Q_INVOKABLE bool moveShop(int positions); - Q_INVOKABLE bool deleteShop(); + Q_INVOKABLE bool moveShop(int positions) const; + Q_INVOKABLE bool deleteShop() const; Q_INVOKABLE bool addItem(int index); Q_INVOKABLE bool deleteItem(int index); @@ -80,7 +80,7 @@ public slots: auto createCategory(const QString &name) -> bool; auto createShop(const QString &name) -> bool; - void connectProject(ShopProject *project) const; + void connectProject(const ShopProject *project) const; void sendProjectCopiesToTool(); [[nodiscard]] auto isCurrentShopValid() const -> bool; @@ -91,9 +91,9 @@ public slots: private slots: void itemEditorSaved(ItemGroup *group); void onProjectWasEdited(); - void onCurrentProjectChanged(ShopProject *currentProject); - void onCurrentShopChanged(ItemShop *currentShop); - void onCurrentItemGroupChanged(ItemGroup *currentGroup); + void onCurrentProjectChanged(const ShopProject *currentProject); + void onCurrentShopChanged(const ItemShop *currentShop); + void onCurrentItemGroupChanged(const ItemGroup *currentGroup); void onDisabledItemCategoriesChanged(const QStringList &categories); - void onIsLoadingChanged(bool isLoading); + void onIsLoadingChanged(bool isLoading) const; }; diff --git a/src/tools/shop/shoptool.cpp b/src/tools/shop/shoptool.cpp index fd4bc497..25ada61d 100644 --- a/src/tools/shop/shoptool.cpp +++ b/src/tools/shop/shoptool.cpp @@ -12,11 +12,11 @@ ShopTool::ShopTool(QObject *parent) : BaseShopTool(parent), m_shopEditor(this) auto ShopTool::create(QQmlEngine *qmlEngine, QJSEngine *jsEngine) -> ShopTool * { - Q_UNUSED(jsEngine); + Q_UNUSED(jsEngine) return new ShopTool(qmlEngine); } -void ShopTool::onCurrentProjectChanged(ShopProject *project) +void ShopTool::onCurrentProjectChanged(const ShopProject *project) { if (m_projectConnection) { @@ -32,7 +32,7 @@ void ShopTool::onCurrentProjectChanged(ShopProject *project) onCurrentShopChanged(shop); } -void ShopTool::onCurrentShopChanged(ItemShop *shop) +void ShopTool::onCurrentShopChanged(const ItemShop *shop) { if (!shop) return; diff --git a/src/tools/shop/shoptool.h b/src/tools/shop/shoptool.h index e228e15c..d46fcfe0 100644 --- a/src/tools/shop/shoptool.h +++ b/src/tools/shop/shoptool.h @@ -30,7 +30,7 @@ class ShopTool : public BaseShopTool QMetaObject::Connection m_projectConnection; private slots: - void onCurrentProjectChanged(ShopProject *project); - void onCurrentShopChanged(ItemShop *shop); + void onCurrentProjectChanged(const ShopProject *project); + void onCurrentShopChanged(const ItemShop *shop); void onShopEditorSaved(const QList &projects); }; diff --git a/tests/testhelper/abstracttest.cpp b/tests/testhelper/abstracttest.cpp index 3bf74041..4bdf57f9 100644 --- a/tests/testhelper/abstracttest.cpp +++ b/tests/testhelper/abstracttest.cpp @@ -5,6 +5,7 @@ #include #include +using namespace Qt::Literals::StringLiterals; using namespace Files; AbstractTest::AbstractTest() : StaticAbstractTest()