From 49e0594495b4eda94d87c3ced8c1935fd3de3452 Mon Sep 17 00:00:00 2001 From: Jonas Kvinge Date: Thu, 11 Apr 2024 02:56:01 +0200 Subject: [PATCH] Disable automatic conversions from 8-bit strings --- CMakeLists.txt | 7 + ext/libstrawberry-common/core/logging.cpp | 34 ++-- ext/libstrawberry-common/core/workerpool.h | 4 +- ext/libstrawberry-tagreader/tagreaderbase.cpp | 14 +- ext/libstrawberry-tagreader/tagreadergme.cpp | 2 +- .../tagreadertaglib.cpp | 8 +- src/CMakeLists.txt | 2 + src/analyzer/analyzercontainer.cpp | 13 +- src/collection/collection.cpp | 5 +- src/collection/collectionbackend.cpp | 36 ++-- src/collection/collectionfilterwidget.cpp | 23 ++- src/collection/collectionmodel.cpp | 113 +++++------ src/collection/collectionmodel.h | 6 +- src/collection/collectionquery.cpp | 56 +++--- src/collection/collectionview.cpp | 3 +- src/collection/collectionwatcher.cpp | 15 +- src/collection/collectionwatcher.h | 6 +- src/collection/savedgroupingmanager.cpp | 15 +- src/context/contextalbum.cpp | 4 +- src/context/contextview.cpp | 33 +-- src/core/commandlineoptions.cpp | 8 +- src/core/database.cpp | 20 +- src/core/database.h | 2 +- src/core/filesystemmusicstorage.cpp | 4 +- src/core/iconloader.cpp | 7 +- src/core/iconmapper.h | 188 +++++++++--------- src/core/mac_startup.mm | 1 - src/core/mainwindow.cpp | 73 +++---- src/core/mainwindow.h | 3 +- src/core/mpris2.cpp | 62 +++--- src/core/mpris2.h | 4 - src/core/networkaccessmanager.cpp | 2 +- src/core/networkproxyfactory.cpp | 3 +- src/core/player.cpp | 13 +- src/core/settings.cpp | 120 +++++++++++ src/core/settings.h | 51 +++++ src/core/settingsprovider.cpp | 2 +- src/core/song.cpp | 40 ++-- src/core/songloader.cpp | 14 +- src/core/stylesheetloader.cpp | 8 +- src/core/tagreaderclient.cpp | 8 +- src/core/tagreaderclient.h | 2 - src/core/threadsafenetworkdiskcache.cpp | 4 +- src/core/translations.cpp | 2 +- .../albumcoverchoicecontroller.cpp | 31 +-- src/covermanager/albumcoverexport.cpp | 10 +- src/covermanager/albumcoverfetchersearch.cpp | 4 +- src/covermanager/albumcoverimageresult.h | 2 +- src/covermanager/albumcoverloaderoptions.cpp | 11 +- src/covermanager/albumcovermanager.cpp | 23 ++- src/covermanager/albumcoversearcher.cpp | 2 +- src/covermanager/coverexportrunnable.cpp | 16 +- src/covermanager/coverproviders.cpp | 3 +- src/covermanager/coversearchstatistics.cpp | 2 +- .../coversearchstatisticsdialog.cpp | 8 +- src/covermanager/currentalbumcoverloader.cpp | 2 +- src/covermanager/deezercoverprovider.cpp | 16 +- src/covermanager/discogscoverprovider.cpp | 24 +-- src/covermanager/lastfmcoverprovider.cpp | 48 ++--- src/covermanager/lastfmcoverprovider.h | 4 - src/covermanager/musicbrainzcoverprovider.cpp | 16 +- src/covermanager/musicbrainzcoverprovider.h | 5 - src/covermanager/musixmatchcoverprovider.cpp | 4 +- src/covermanager/opentidalcoverprovider.cpp | 31 +-- src/covermanager/qobuzcoverprovider.cpp | 16 +- src/covermanager/spotifycoverprovider.cpp | 83 ++++---- src/covermanager/spotifycoverprovider.h | 9 - src/covermanager/tidalcoverprovider.cpp | 18 +- src/device/cddalister.cpp | 12 +- src/device/cddasongloader.cpp | 4 +- src/device/connecteddevice.cpp | 2 +- src/device/devicedatabasebackend.cpp | 4 +- src/device/deviceinfo.cpp | 2 +- src/device/devicelister.cpp | 12 +- src/device/devicemanager.cpp | 10 +- src/device/giolister.cpp | 12 +- src/device/gpoddevice.cpp | 12 +- src/device/mtpdevice.cpp | 2 +- src/device/udisks2lister.cpp | 42 ++-- src/device/udisks2lister.h | 2 - src/dialogs/about.cpp | 10 +- src/dialogs/addstreamdialog.cpp | 2 + src/dialogs/console.cpp | 2 +- src/dialogs/edittagdialog.cpp | 81 ++++---- src/dialogs/messagedialog.cpp | 3 +- src/dialogs/saveplaylistsdialog.cpp | 5 +- src/dialogs/snapdialog.cpp | 2 +- src/dialogs/trackselectiondialog.cpp | 4 +- src/engine/alsadevicefinder.cpp | 4 +- src/engine/alsapcmdevicefinder.cpp | 12 +- src/engine/chromaprinter.cpp | 2 +- src/engine/ebur128analysis.cpp | 10 +- src/engine/enginebase.cpp | 3 +- src/engine/gstengine.cpp | 44 ++-- src/engine/gstengine.h | 2 +- src/engine/gstenginepipeline.cpp | 12 +- src/engine/pulsedevicefinder.cpp | 2 +- src/engine/vlcengine.cpp | 16 +- src/equalizer/equalizer.cpp | 47 ++--- src/globalshortcuts/globalshortcutgrabber.cpp | 2 +- .../globalshortcutsbackend-gnome.cpp | 26 +-- .../globalshortcutsbackend-gnome.h | 4 - .../globalshortcutsbackend-kde.cpp | 18 +- .../globalshortcutsbackend-kde.h | 3 - .../globalshortcutsbackend-mate.cpp | 26 +-- .../globalshortcutsbackend-mate.h | 4 - .../globalshortcutsbackend-x11.cpp | 2 +- src/globalshortcuts/globalshortcutsmanager.h | 4 +- src/internet/internetsearchmodel.cpp | 4 +- src/internet/internetsearchview.cpp | 21 +- src/internet/internettabsview.cpp | 15 +- src/internet/localredirectserver.cpp | 5 +- src/lyrics/azlyricscomlyricsprovider.cpp | 14 +- src/lyrics/azlyricscomlyricsprovider.h | 6 - src/lyrics/chartlyricsprovider.cpp | 20 +- src/lyrics/chartlyricsprovider.h | 1 - src/lyrics/elyricsnetlyricsprovider.cpp | 16 +- src/lyrics/elyricsnetlyricsprovider.h | 6 - src/lyrics/geniuslyricsprovider.cpp | 59 +++--- src/lyrics/geniuslyricsprovider.h | 9 - src/lyrics/htmllyricsprovider.cpp | 8 +- src/lyrics/letraslyricsprovider.cpp | 10 +- src/lyrics/lololyricsprovider.cpp | 20 +- src/lyrics/lololyricsprovider.h | 1 - src/lyrics/lyricsproviders.cpp | 3 +- src/lyrics/musixmatchlyricsprovider.cpp | 16 +- src/lyrics/ovhlyricsprovider.cpp | 2 +- src/lyrics/songlyricscomlyricsprovider.cpp | 20 +- src/lyrics/songlyricscomlyricsprovider.h | 6 - src/main.cpp | 23 ++- src/moodbar/moodbarcontroller.cpp | 2 +- src/moodbar/moodbaritemdelegate.cpp | 3 +- src/moodbar/moodbarloader.cpp | 11 +- src/moodbar/moodbarpipeline.cpp | 2 +- src/moodbar/moodbarproxystyle.cpp | 7 +- src/musicbrainz/acoustidclient.cpp | 22 +- src/musicbrainz/acoustidclient.h | 4 - src/musicbrainz/musicbrainzclient.cpp | 86 ++++---- src/musicbrainz/musicbrainzclient.h | 8 - src/organize/organize.cpp | 4 +- src/organize/organizedialog.cpp | 25 ++- src/organize/organizedialog.h | 3 - src/organize/organizeformat.cpp | 86 ++++---- src/organize/organizeformat.h | 2 - src/osd/osdbase.cpp | 7 +- src/osd/osddbus.cpp | 2 +- src/osd/osdpretty.cpp | 10 +- src/osd/osdpretty.h | 2 +- src/playlist/playlist.cpp | 19 +- src/playlist/playlistbackend.cpp | 12 +- src/playlist/playlistcontainer.cpp | 11 +- src/playlist/playlistcontainer.h | 3 +- src/playlist/playlistdelegates.cpp | 4 +- src/playlist/playlistfilterparser.cpp | 70 +++---- src/playlist/playlistheader.cpp | 3 +- src/playlist/playlistlistcontainer.cpp | 7 +- src/playlist/playlistlistmodel.cpp | 4 +- src/playlist/playlistlistview.cpp | 6 +- src/playlist/playlistmanager.cpp | 15 +- src/playlist/playlistproxystyle.cpp | 2 +- src/playlist/playlistsaveoptionsdialog.cpp | 3 +- src/playlist/playlisttabbar.cpp | 11 +- src/playlist/playlistview.cpp | 7 +- src/playlistparsers/asxiniparser.cpp | 2 +- src/playlistparsers/asxparser.cpp | 24 +-- src/playlistparsers/cueparser.cpp | 96 ++++----- src/playlistparsers/cueparser.h | 16 -- src/playlistparsers/m3uparser.cpp | 13 +- src/playlistparsers/parserbase.cpp | 2 +- src/playlistparsers/playlistparser.cpp | 2 +- src/playlistparsers/plsparser.cpp | 2 +- src/playlistparsers/wplparser.cpp | 24 +-- src/playlistparsers/xspfparser.cpp | 43 ++-- src/providers/musixmatchprovider.cpp | 6 +- src/qobuz/qobuzbaserequest.cpp | 10 +- src/qobuz/qobuzfavoriterequest.cpp | 16 +- src/qobuz/qobuzrequest.cpp | 46 ++--- src/qobuz/qobuzservice.cpp | 55 ++--- src/qobuz/qobuzservice.h | 14 +- src/qobuz/qobuzstreamurlrequest.cpp | 18 +- src/queue/queue.cpp | 18 +- src/queue/queue.h | 2 - src/queue/queueview.cpp | 3 +- src/radios/radiochannel.cpp | 2 +- src/radios/radiomodel.cpp | 4 +- src/radios/radioparadiseservice.cpp | 10 +- src/radios/radioparadiseservice.h | 1 - src/radios/radioviewcontainer.cpp | 3 +- src/radios/somafmservice.cpp | 10 +- src/radios/somafmservice.h | 1 - src/scrobbler/audioscrobbler.h | 2 +- src/scrobbler/lastfmimport.cpp | 37 ++-- src/scrobbler/lastfmscrobbler.cpp | 2 +- src/scrobbler/librefmscrobbler.cpp | 2 +- src/scrobbler/listenbrainzscrobbler.cpp | 88 ++++---- src/scrobbler/listenbrainzscrobbler.h | 9 - src/scrobbler/scrobblercache.cpp | 2 +- src/scrobbler/scrobblersettings.cpp | 7 +- src/scrobbler/scrobblingapi20.cpp | 83 ++++---- src/scrobbler/scrobblingapi20.h | 3 - src/scrobbler/subsonicscrobbler.cpp | 4 +- src/settings/appearancesettingspage.cpp | 13 +- src/settings/backendsettingspage.cpp | 40 ++-- src/settings/backendsettingspage.h | 3 - src/settings/behavioursettingspage.cpp | 27 +-- src/settings/collectionsettingspage.cpp | 13 +- src/settings/contextsettingspage.cpp | 17 +- src/settings/coverssettingspage.cpp | 23 ++- src/settings/globalshortcutssettingspage.cpp | 17 +- src/settings/globalshortcutssettingspage.h | 1 - src/settings/lyricssettingspage.cpp | 5 +- src/settings/moodbarsettingspage.cpp | 7 +- src/settings/networkproxysettingspage.cpp | 7 +- src/settings/notificationssettingspage.cpp | 7 +- src/settings/playlistsettingspage.cpp | 7 +- src/settings/qobuzsettingspage.cpp | 7 +- src/settings/scrobblersettingspage.cpp | 9 +- src/settings/settingsdialog.cpp | 11 +- src/settings/settingsdialog.h | 1 - src/settings/settingspage.cpp | 7 +- src/settings/settingspage.h | 7 +- src/settings/subsonicsettingspage.cpp | 7 +- src/settings/tidalsettingspage.cpp | 25 +-- src/smartplaylists/smartplaylistsearch.cpp | 14 +- .../smartplaylistsearchterm.cpp | 58 +++--- .../smartplaylistsearchtermwidget.cpp | 2 +- src/smartplaylists/smartplaylistsmodel.cpp | 39 ++-- src/smartplaylists/smartplaylistsmodel.h | 5 +- .../smartplaylistsviewcontainer.cpp | 3 +- src/smartplaylists/smartplaylistwizard.cpp | 2 +- src/subsonic/subsonicbaserequest.cpp | 24 +-- src/subsonic/subsonicrequest.cpp | 18 +- src/subsonic/subsonicscrobblerequest.cpp | 6 +- src/subsonic/subsonicservice.cpp | 47 +++-- src/subsonic/subsonicservice.h | 4 - src/subsonic/subsonicurlhandler.cpp | 2 +- src/tidal/tidalbaserequest.cpp | 10 +- src/tidal/tidalfavoriterequest.cpp | 18 +- src/tidal/tidalrequest.cpp | 36 ++-- src/tidal/tidalservice.cpp | 121 +++++------ src/tidal/tidalservice.h | 17 +- src/tidal/tidalstreamurlrequest.cpp | 18 +- src/transcoder/transcodedialog.cpp | 46 +++-- src/transcoder/transcodedialog.h | 2 - src/transcoder/transcoder.cpp | 27 +-- src/transcoder/transcoderoptionsaac.cpp | 14 +- src/transcoder/transcoderoptionsaac.h | 2 - src/transcoder/transcoderoptionsasf.cpp | 16 +- src/transcoder/transcoderoptionsasf.h | 2 - src/transcoder/transcoderoptionsdialog.cpp | 2 +- src/transcoder/transcoderoptionsflac.cpp | 14 +- src/transcoder/transcoderoptionsflac.h | 2 - src/transcoder/transcoderoptionsmp3.cpp | 14 +- src/transcoder/transcoderoptionsmp3.h | 2 - src/transcoder/transcoderoptionsopus.cpp | 14 +- src/transcoder/transcoderoptionsopus.h | 2 - src/transcoder/transcoderoptionsspeex.cpp | 14 +- src/transcoder/transcoderoptionsspeex.h | 2 - src/transcoder/transcoderoptionsvorbis.cpp | 14 +- src/transcoder/transcoderoptionsvorbis.h | 2 - src/transcoder/transcoderoptionswavpack.cpp | 14 +- src/transcoder/transcoderoptionswavpack.h | 2 - src/utilities/coverutils.cpp | 28 +-- src/utilities/envutils.cpp | 12 +- src/utilities/filemanagerutils.cpp | 18 +- src/utilities/fileutils.cpp | 16 +- src/utilities/imageutils.cpp | 6 +- src/utilities/macaddrutils.cpp | 2 +- src/utilities/searchparserutils.cpp | 4 +- src/utilities/strutils.cpp | 48 ++--- src/utilities/timeutils.cpp | 8 +- src/widgets/fancytabwidget.cpp | 11 +- src/widgets/fileview.cpp | 5 +- src/widgets/freespacebar.cpp | 2 +- src/widgets/lineedit.h | 4 +- src/widgets/loginstatewidget.cpp | 6 +- src/widgets/playingwidget.cpp | 13 +- src/widgets/ratingwidget.cpp | 7 +- src/widgets/ratingwidget.h | 5 +- src/widgets/trackslider.cpp | 7 +- src/widgets/volumeslider.cpp | 2 +- 281 files changed, 2321 insertions(+), 2121 deletions(-) create mode 100644 src/core/settings.cpp create mode 100644 src/core/settings.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 074091453d..31b8b51eb6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -508,8 +508,15 @@ add_definitions( -DQT_NO_CAST_TO_ASCII -DQT_NO_NARROWING_CONVERSIONS_IN_CONNECT -DQT_NO_FOREACH + -DQT_ASCII_CAST_WARNINGS ) +if(BUILD_WITH_QT6) + add_definitions("-DQT_NO_CAST_FROM_ASCII") +else() + add_definitions("-DQT_RESTRICTED_CAST_FROM_ASCII") +endif() + if(WIN32) add_definitions(-DUNICODE) if(MSVC) diff --git a/ext/libstrawberry-common/core/logging.cpp b/ext/libstrawberry-common/core/logging.cpp index 8cf8e6e856..49fb17b72f 100644 --- a/ext/libstrawberry-common/core/logging.cpp +++ b/ext/libstrawberry-common/core/logging.cpp @@ -67,8 +67,8 @@ static QIODevice *sNullDevice = nullptr; const char *kDefaultLogLevels = "*:3"; -static const char *kMessageHandlerMagic = "__logging_message__"; -static const size_t kMessageHandlerMagicLength = strlen(kMessageHandlerMagic); +static constexpr char kMessageHandlerMagic[] = "__logging_message__"; +static const size_t kMessageHandlerMagicLen = strlen(kMessageHandlerMagic); static QtMessageHandler sOriginalMessageHandler = nullptr; template @@ -135,9 +135,9 @@ class LoggedDebug : public DebugBase { static void MessageHandler(QtMsgType type, const QMessageLogContext&, const QString &message) { - if (message.startsWith(kMessageHandlerMagic)) { + if (message.startsWith(QLatin1String(kMessageHandlerMagic))) { QByteArray message_data = message.toUtf8(); - fprintf(type == QtCriticalMsg || type == QtFatalMsg ? stderr : stdout, "%s\n", message_data.constData() + kMessageHandlerMagicLength); + fprintf(type == QtCriticalMsg || type == QtFatalMsg ? stderr : stdout, "%s\n", message_data.constData() + kMessageHandlerMagicLen); fflush(type == QtCriticalMsg || type == QtFatalMsg ? stderr : stdout); return; } @@ -157,7 +157,7 @@ static void MessageHandler(QtMsgType type, const QMessageLogContext&, const QStr break; } - for (const QString &line : message.split('\n')) { + for (const QString &line : message.split(QLatin1Char('\n'))) { BufferedDebug d = CreateLogger(level, QStringLiteral("unknown"), -1, nullptr); d << line.toLocal8Bit().constData(); if (d.buf_) { @@ -193,8 +193,8 @@ void SetLevels(const QString &levels) { if (!sClassLevels) return; - for (const QString &item : levels.split(',')) { - const QStringList class_level = item.split(':'); + for (const QString &item : levels.split(QLatin1Char(','))) { + const QStringList class_level = item.split(QLatin1Char(':')); QString class_name; bool ok = false; @@ -212,7 +212,7 @@ void SetLevels(const QString &levels) { continue; } - if (class_name.isEmpty() || class_name == "*") { + if (class_name.isEmpty() || class_name == QStringLiteral("*")) { sDefaultLevel = static_cast(level); } else { @@ -225,8 +225,8 @@ void SetLevels(const QString &levels) { static QString ParsePrettyFunction(const char *pretty_function) { // Get the class name out of the function name. - QString class_name = pretty_function; - const qint64 paren = class_name.indexOf('('); + QString class_name = QLatin1String(pretty_function); + const qint64 paren = class_name.indexOf(QLatin1Char('(')); if (paren != -1) { const qint64 colons = class_name.lastIndexOf(QLatin1String("::"), paren); if (colons != -1) { @@ -237,7 +237,7 @@ static QString ParsePrettyFunction(const char *pretty_function) { } } - const qint64 space = class_name.lastIndexOf(' '); + const qint64 space = class_name.lastIndexOf(QLatin1Char(' ')); if (space != -1) { class_name = class_name.mid(space + 1); } @@ -259,7 +259,7 @@ static T CreateLogger(Level level, const QString &class_name, int line, const ch case Level_Fatal: level_name = " FATAL "; break; } - QString filter_category = (category != nullptr) ? category : class_name; + QString filter_category = (category != nullptr) ? QLatin1String(category) : class_name; // Check the settings to see if we're meant to show or hide this message. Level threshold_level = sDefaultLevel; if (sClassLevels && sClassLevels->contains(filter_category)) { @@ -272,10 +272,10 @@ static T CreateLogger(Level level, const QString &class_name, int line, const ch QString function_line = class_name; if (line != -1) { - function_line += ":" + QString::number(line); + function_line += QStringLiteral(":") + QString::number(line); } if (category) { - function_line += "(" + QString(category) + ")"; + function_line += QStringLiteral("(") + QLatin1String(category) + QStringLiteral(")"); } QtMsgType type = QtDebugMsg; @@ -326,9 +326,9 @@ QString DarwinDemangle(const QString &symbol); QString DarwinDemangle(const QString &symbol) { # if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QStringList split = symbol.split(' ', Qt::SkipEmptyParts); + QStringList split = symbol.split(QLatin1Char(' '), Qt::SkipEmptyParts); # else - QStringList split = symbol.split(' ', QString::SkipEmptyParts); + QStringList split = symbol.split(QLatin1Char(' '), QString::SkipEmptyParts); # endif QString mangled_function = split[3]; return CXXDemangle(mangled_function); @@ -392,7 +392,7 @@ namespace { template QString print_duration(T duration, const std::string &unit) { - return QStringLiteral("%1%2").arg(duration.count()).arg(unit.c_str()); + return QStringLiteral("%1%2").arg(duration.count()).arg(QString::fromStdString(unit)); } } // namespace diff --git a/ext/libstrawberry-common/core/workerpool.h b/ext/libstrawberry-common/core/workerpool.h index c53d97584b..e2ebab6b86 100644 --- a/ext/libstrawberry-common/core/workerpool.h +++ b/ext/libstrawberry-common/core/workerpool.h @@ -247,11 +247,11 @@ void WorkerPool::DoStart() { search_path << QStringLiteral("/usr/local/libexec"); #endif #if defined(Q_OS_MACOS) - search_path << QDir::cleanPath(QCoreApplication::applicationDirPath() + "/../PlugIns"); + search_path << QDir::cleanPath(QCoreApplication::applicationDirPath() + QStringLiteral("/../PlugIns")); #endif for (const QString &path_prefix : search_path) { - const QString executable_path = path_prefix + "/" + executable_name_; + const QString executable_path = path_prefix + QLatin1Char('/') + executable_name_; if (QFile::exists(executable_path)) { executable_path_ = executable_path; qLog(Debug) << "Using worker" << executable_name_ << "from" << path_prefix; diff --git a/ext/libstrawberry-tagreader/tagreaderbase.cpp b/ext/libstrawberry-tagreader/tagreaderbase.cpp index 13eab8d236..cd5300e012 100644 --- a/ext/libstrawberry-tagreader/tagreaderbase.cpp +++ b/ext/libstrawberry-tagreader/tagreaderbase.cpp @@ -74,7 +74,7 @@ TagReaderBase::Cover TagReaderBase::LoadCoverFromRequest(const spb::tagreader::S } QString cover_mime_type; if (request.has_cover_mime_type()) { - cover_mime_type = QByteArray(request.cover_mime_type().data(), static_cast(request.cover_mime_type().size())); + cover_mime_type = QString::fromStdString(request.cover_mime_type()); } return LoadCoverFromRequest(song_filename, cover_filename, cover_data, cover_mime_type); @@ -94,7 +94,7 @@ TagReaderBase::Cover TagReaderBase::LoadCoverFromRequest(const spb::tagreader::S } QString cover_mime_type; if (request.has_cover_mime_type()) { - cover_mime_type = QByteArray(request.cover_mime_type().data(), static_cast(request.cover_mime_type().size())); + cover_mime_type = QString::fromStdString(request.cover_mime_type()); } return LoadCoverFromRequest(song_filename, cover_filename, cover_data, cover_mime_type); @@ -118,17 +118,21 @@ TagReaderBase::Cover TagReaderBase::LoadCoverFromRequest(const QString &song_fil if (cover_mime_type.isEmpty()) { cover_mime_type = QMimeDatabase().mimeTypeForData(cover_data).name(); } - if (cover_mime_type == "image/jpeg") { + if (cover_mime_type == QStringLiteral("image/jpeg")) { qLog(Debug) << "Using cover from JPEG data for" << song_filename; return Cover(cover_data, cover_mime_type); } - if (cover_mime_type == "image/png") { + if (cover_mime_type == QStringLiteral("image/png")) { qLog(Debug) << "Using cover from PNG data for" << song_filename; return Cover(cover_data, cover_mime_type); } // Convert image to JPEG. qLog(Debug) << "Converting cover to JPEG data for" << song_filename; - QImage cover_image(cover_data); + QImage cover_image; + if (!cover_image.loadFromData(cover_data)) { + qLog(Error) << "Failed to load image from cover data for" << song_filename; + return Cover(); + } cover_data.clear(); QBuffer buffer(&cover_data); if (buffer.open(QIODevice::WriteOnly)) { diff --git a/ext/libstrawberry-tagreader/tagreadergme.cpp b/ext/libstrawberry-tagreader/tagreadergme.cpp index 96be7f684c..73ff1db87c 100644 --- a/ext/libstrawberry-tagreader/tagreadergme.cpp +++ b/ext/libstrawberry-tagreader/tagreadergme.cpp @@ -226,7 +226,7 @@ void GME::VGM::Read(const QFileInfo &file_info, spb::tagreader::SongMetadata *so #else fileTagStream.setCodec("UTF-16"); #endif - QStringList strings = fileTagStream.readLine(0).split(QChar('\0')); + QStringList strings = fileTagStream.readLine(0).split(QLatin1Char('\0')); if (strings.count() < 10) return; // VGM standard dictates string tag data exist in specific order. diff --git a/ext/libstrawberry-tagreader/tagreadertaglib.cpp b/ext/libstrawberry-tagreader/tagreadertaglib.cpp index fca4e0f9c3..1d78a58f2e 100644 --- a/ext/libstrawberry-tagreader/tagreadertaglib.cpp +++ b/ext/libstrawberry-tagreader/tagreadertaglib.cpp @@ -368,7 +368,7 @@ bool TagReaderTagLib::ReadFile(const QString &filename, spb::tagreader::SongMeta for (uint i = 0; i < map["COMM"].size(); ++i) { const TagLib::ID3v2::CommentsFrame *frame = dynamic_cast(map["COMM"][i]); - if (frame && TStringToQString(frame->description()) != "iTunNORM") { + if (frame && TStringToQString(frame->description()) != QStringLiteral("iTunNORM")) { TStringToStdString(frame->text(), song->mutable_comment()); break; } @@ -663,7 +663,7 @@ bool TagReaderTagLib::ReadFile(const QString &filename, spb::tagreader::SongMeta } if (!disc.isEmpty()) { - const qint64 i = disc.indexOf('/'); + const qint64 i = disc.indexOf(QLatin1Char('/')); if (i != -1) { // disc.right( i ).toInt() is total number of discs, we don't use this at the moment song->set_disc(disc.left(i).toInt()); @@ -1311,10 +1311,10 @@ void TagReaderTagLib::SetEmbeddedArt(TagLib::MP4::File *aac_file, TagLib::MP4::T } else { TagLib::MP4::CoverArt::Format cover_format = TagLib::MP4::CoverArt::Format::JPEG; - if (mime_type == "image/jpeg") { + if (mime_type == QStringLiteral("image/jpeg")) { cover_format = TagLib::MP4::CoverArt::Format::JPEG; } - else if (mime_type == "image/png") { + else if (mime_type == QStringLiteral("image/png")) { cover_format = TagLib::MP4::CoverArt::Format::PNG; } else { diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ff638d63e0..522e9882bd 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -24,6 +24,7 @@ set(SOURCES core/networktimeouts.cpp core/networkproxyfactory.cpp core/qtfslistener.cpp + core/settings.cpp core/settingsprovider.cpp core/signalchecker.cpp core/song.cpp @@ -307,6 +308,7 @@ set(HEADERS core/threadsafenetworkdiskcache.h core/networktimeouts.h core/qtfslistener.h + core/settings.h core/songloader.h core/tagreaderclient.h core/taskmanager.h diff --git a/src/analyzer/analyzercontainer.cpp b/src/analyzer/analyzercontainer.cpp index adbafa63ec..c6259466bd 100644 --- a/src/analyzer/analyzercontainer.cpp +++ b/src/analyzer/analyzercontainer.cpp @@ -44,6 +44,7 @@ #include "core/logging.h" #include "core/shared_ptr.h" +#include "core/settings.h" #include "engine/enginebase.h" using namespace std::chrono_literals; @@ -178,9 +179,9 @@ void AnalyzerContainer::ChangeFramerate(int new_framerate) { void AnalyzerContainer::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); - QString type = s.value("type", "BlockAnalyzer").toString(); + QString type = s.value("type", QStringLiteral("BlockAnalyzer")).toString(); current_framerate_ = s.value(kSettingsFramerate, kMediumFramerate).toInt(); s.endGroup(); @@ -191,7 +192,7 @@ void AnalyzerContainer::Load() { } else { for (int i = 0; i < analyzer_types_.count(); ++i) { - if (type == analyzer_types_[i]->className()) { + if (type == QString::fromUtf8(analyzer_types_[i]->className())) { ChangeAnalyzer(i); actions_[i]->setChecked(true); break; @@ -215,7 +216,7 @@ void AnalyzerContainer::SaveFramerate(const int framerate) { // For now, framerate is common for all analyzers. Maybe each analyzer should have its own framerate? current_framerate_ = framerate; - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue(kSettingsFramerate, current_framerate_); s.endGroup(); @@ -224,9 +225,9 @@ void AnalyzerContainer::SaveFramerate(const int framerate) { void AnalyzerContainer::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); - s.setValue("type", current_analyzer_ ? current_analyzer_->metaObject()->className() : QVariant()); + s.setValue("type", current_analyzer_ ? QString::fromUtf8(current_analyzer_->metaObject()->className()) : QVariant()); s.endGroup(); } diff --git a/src/collection/collection.cpp b/src/collection/collection.cpp index 9ba6b7c147..184f2ad343 100644 --- a/src/collection/collection.cpp +++ b/src/collection/collection.cpp @@ -37,6 +37,7 @@ #include "core/thread.h" #include "core/song.h" #include "core/logging.h" +#include "core/settings.h" #include "utilities/threadutils.h" #include "collection.h" #include "collectionwatcher.h" @@ -69,7 +70,7 @@ SCollection::SCollection(Application *app, QObject *parent) backend()->moveToThread(app->database()->thread()); qLog(Debug) << &*backend_ << "moved to thread" << app->database()->thread(); - backend_->Init(app->database(), app->task_manager(), Song::Source::Collection, kSongsTable, kFtsTable, kDirsTable, kSubdirsTable); + backend_->Init(app->database(), app->task_manager(), Song::Source::Collection, QLatin1String(kSongsTable), QLatin1String(kFtsTable), QLatin1String(kDirsTable), QLatin1String(kSubdirsTable)); model_ = new CollectionModel(backend_, app_, this); @@ -179,7 +180,7 @@ void SCollection::ReloadSettings() { watcher_->ReloadSettingsAsync(); model_->ReloadSettings(); - QSettings s; + Settings s; s.beginGroup(CollectionSettingsPage::kSettingsGroup); save_playcounts_to_files_ = s.value("save_playcounts", false).toBool(); save_ratings_to_files_ = s.value("save_ratings", false).toBool(); diff --git a/src/collection/collectionbackend.cpp b/src/collection/collectionbackend.cpp index 2807bc20c7..3d5c10c9a8 100644 --- a/src/collection/collectionbackend.cpp +++ b/src/collection/collectionbackend.cpp @@ -939,7 +939,7 @@ QStringList CollectionBackend::GetAll(const QString &column, const CollectionFil QSqlDatabase db(db_->Connect()); CollectionQuery query(db, songs_table_, fts_table_, filter_options); - query.SetColumnSpec("DISTINCT " + column); + query.SetColumnSpec(QStringLiteral("DISTINCT ") + column); query.AddCompilationRequirement(false); if (!query.Exec()) { @@ -969,14 +969,14 @@ QStringList CollectionBackend::GetAllArtistsWithAlbums(const CollectionFilterOpt CollectionQuery query(db, songs_table_, fts_table_, opt); query.SetColumnSpec(QStringLiteral("DISTINCT albumartist")); query.AddCompilationRequirement(false); - query.AddWhere(QStringLiteral("album"), "", QStringLiteral("!=")); + query.AddWhere(QStringLiteral("album"), QLatin1String(""), QStringLiteral("!=")); // Albums with no 'albumartist' (extract 'artist'): CollectionQuery query2(db, songs_table_, fts_table_, opt); query2.SetColumnSpec(QStringLiteral("DISTINCT artist")); query2.AddCompilationRequirement(false); - query2.AddWhere(QStringLiteral("album"), "", QStringLiteral("!=")); - query2.AddWhere(QStringLiteral("albumartist"), "", QStringLiteral("=")); + query2.AddWhere(QStringLiteral("album"), QLatin1String(""), QStringLiteral("!=")); + query2.AddWhere(QStringLiteral("albumartist"), QLatin1String(""), QStringLiteral("=")); if (!query.Exec()) { ReportErrors(query); @@ -1065,7 +1065,7 @@ SongList CollectionBackend::GetSongsByAlbum(const QString &album, const Collecti bool CollectionBackend::ExecCollectionQuery(CollectionQuery *query, SongList &songs) { - query->SetColumnSpec("%songs_table.ROWID, " + Song::kColumnSpec); + query->SetColumnSpec(QStringLiteral("%songs_table.ROWID, ") + Song::kColumnSpec); if (!query->Exec()) return false; @@ -1080,7 +1080,7 @@ bool CollectionBackend::ExecCollectionQuery(CollectionQuery *query, SongList &so bool CollectionBackend::ExecCollectionQuery(CollectionQuery *query, SongMap &songs) { - query->SetColumnSpec("%songs_table.ROWID, " + Song::kColumnSpec); + query->SetColumnSpec(QStringLiteral("%songs_table.ROWID, ") + Song::kColumnSpec); if (!query->Exec()) return false; @@ -1301,9 +1301,9 @@ SongList CollectionBackend::GetSongsBySongId(const QStringList &song_ids, QSqlDa QStringList song_ids2; song_ids2.reserve(song_ids.count()); for (const QString &song_id : song_ids) { - song_ids2 << "'" + song_id + "'"; + song_ids2 << QLatin1Char('\'') + song_id + QLatin1Char('\''); } - QString in = song_ids2.join(QStringLiteral(",")); + QString in = song_ids2.join(QLatin1Char(',')); SqlQuery q(db); q.prepare(QStringLiteral("SELECT ROWID, %1 FROM %2 WHERE SONG_ID IN (%3)").arg(Song::kColumnSpec, songs_table_, in)); @@ -1358,7 +1358,7 @@ SongList CollectionBackend::GetCompilationSongs(const QString &album, const Coll QSqlDatabase db(db_->Connect()); CollectionQuery query(db, songs_table_, fts_table_, opt); - query.SetColumnSpec("%songs_table.ROWID, " + Song::kColumnSpec); + query.SetColumnSpec(QStringLiteral("%songs_table.ROWID, ") + Song::kColumnSpec); query.AddCompilationRequirement(true); query.AddWhere(QStringLiteral("album"), album); @@ -1553,7 +1553,7 @@ CollectionBackend::AlbumList CollectionBackend::GetAlbums(const QString &artist, key.append(album_info.album_artist); } if (!album_info.album.isEmpty()) { - if (!key.isEmpty()) key.append("-"); + if (!key.isEmpty()) key.append(QLatin1Char('-')); key.append(album_info.album); } if (!filetype.isEmpty()) { @@ -1622,7 +1622,7 @@ void CollectionBackend::UpdateEmbeddedAlbumArt(const QString &effective_albumart // Get the songs before they're updated CollectionQuery query(db, songs_table_, fts_table_); - query.SetColumnSpec("ROWID, " + Song::kColumnSpec); + query.SetColumnSpec(QStringLiteral("ROWID, ") + Song::kColumnSpec); query.AddWhere(QStringLiteral("effective_albumartist"), effective_albumartist); query.AddWhere(QStringLiteral("album"), album); @@ -1684,7 +1684,7 @@ void CollectionBackend::UpdateManualAlbumArt(const QString &effective_albumartis QSqlDatabase db(db_->Connect()); CollectionQuery query(db, songs_table_, fts_table_); - query.SetColumnSpec("ROWID, " + Song::kColumnSpec); + query.SetColumnSpec(QStringLiteral("ROWID, ") + Song::kColumnSpec); query.AddWhere(QStringLiteral("effective_albumartist"), effective_albumartist); query.AddWhere(QStringLiteral("album"), album); @@ -1742,7 +1742,7 @@ void CollectionBackend::UnsetAlbumArt(const QString &effective_albumartist, cons QSqlDatabase db(db_->Connect()); CollectionQuery query(db, songs_table_, fts_table_); - query.SetColumnSpec("ROWID, " + Song::kColumnSpec); + query.SetColumnSpec(QStringLiteral("ROWID, ") + Song::kColumnSpec); query.AddWhere(QStringLiteral("effective_albumartist"), effective_albumartist); query.AddWhere(QStringLiteral("album"), album); @@ -1799,7 +1799,7 @@ void CollectionBackend::ClearAlbumArt(const QString &effective_albumartist, cons QSqlDatabase db(db_->Connect()); CollectionQuery query(db, songs_table_, fts_table_); - query.SetColumnSpec("ROWID, " + Song::kColumnSpec); + query.SetColumnSpec(QStringLiteral("ROWID, ") + Song::kColumnSpec); query.AddWhere(QStringLiteral("effective_albumartist"), effective_albumartist); query.AddWhere(QStringLiteral("album"), album); @@ -1854,7 +1854,7 @@ void CollectionBackend::ForceCompilation(const QString &album, const QListReportErrors(q); return; @@ -2017,7 +2017,7 @@ void CollectionBackend::DeleteAll() { { SqlQuery q(db); - q.prepare("DELETE FROM " + fts_table_); + q.prepare(QStringLiteral("DELETE FROM ") + fts_table_); if (!q.Exec()) { db_->ReportErrors(q); return; @@ -2220,7 +2220,7 @@ void CollectionBackend::ExpireSongs(const int directory_id, const int expire_una QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); SqlQuery q(db); - q.prepare(QString("SELECT %1.ROWID, " + Song::JoinSpec(QStringLiteral("%1")) + " FROM %1 LEFT JOIN playlist_items ON %1.ROWID = playlist_items.collection_id WHERE %1.directory_id = :directory_id AND %1.unavailable = 1 AND %1.lastseen > 0 AND %1.lastseen < :time AND playlist_items.collection_id IS NULL").arg(songs_table_)); + q.prepare(QStringLiteral("SELECT %1.ROWID, ").arg(songs_table_) + Song::JoinSpec(songs_table_) + QStringLiteral(" FROM %1 LEFT JOIN playlist_items ON %1.ROWID = playlist_items.collection_id WHERE %1.directory_id = :directory_id AND %1.unavailable = 1 AND %1.lastseen > 0 AND %1.lastseen < :time AND playlist_items.collection_id IS NULL").arg(songs_table_)); q.BindValue(QStringLiteral(":directory_id"), directory_id); q.BindValue(QStringLiteral(":time"), QDateTime::currentDateTime().toSecsSinceEpoch() - (expire_unavailable_songs_days * 86400)); if (!q.Exec()) { diff --git a/src/collection/collectionfilterwidget.cpp b/src/collection/collectionfilterwidget.cpp index 19dde695da..03d903d42c 100644 --- a/src/collection/collectionfilterwidget.cpp +++ b/src/collection/collectionfilterwidget.cpp @@ -46,6 +46,7 @@ #include "core/iconloader.h" #include "core/song.h" #include "core/logging.h" +#include "core/settings.h" #include "collectionfilteroptions.h" #include "collectionmodel.h" #include "savedgroupingmanager.h" @@ -85,7 +86,7 @@ CollectionFilterWidget::CollectionFilterWidget(QWidget *parent) tr("searches the collection for all artists that contain the word %1. ").arg(QStringLiteral("Strawbs")) + QStringLiteral("

") + tr("Search terms for numerical fields can be prefixed with %1 or %2 to refine the search, e.g.: ") - .arg(" =, !=, <, >, <=", ">=") + + .arg(QStringLiteral(" =, !=, <, >, <="), QStringLiteral(">=")) + QStringLiteral("") + tr("rating") + QStringLiteral("") + @@ -181,7 +182,7 @@ void CollectionFilterWidget::Init(CollectionModel *model) { // Load settings if (!settings_group_.isEmpty()) { - QSettings s; + Settings s; s.beginGroup(settings_group_); int version = 0; if (s.contains(group_by_version())) version = s.value(group_by_version(), 0).toInt(); @@ -217,7 +218,7 @@ void CollectionFilterWidget::SetSettingsPrefix(const QString &prefix) { void CollectionFilterWidget::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); int iconsize = s.value(AppearanceSettingsPage::kIconSizeConfigureButtons, 20).toInt(); s.endGroup(); @@ -306,13 +307,13 @@ QActionGroup *CollectionFilterWidget::CreateGroupByActions(const QString &saved_ ret->addAction(sep1); // Read saved groupings - QSettings s; + Settings s; s.beginGroup(saved_groupings_settings_group); int version = s.value("version").toInt(); if (version == 1) { QStringList saved = s.childKeys(); for (int i = 0; i < saved.size(); ++i) { - if (saved.at(i) == "version") continue; + if (saved.at(i) == QStringLiteral("version")) continue; QByteArray bytes = s.value(saved.at(i)).toByteArray(); QDataStream ds(&bytes, QIODevice::ReadOnly); CollectionModel::Grouping g; @@ -323,7 +324,7 @@ QActionGroup *CollectionFilterWidget::CreateGroupByActions(const QString &saved_ else { QStringList saved = s.childKeys(); for (int i = 0; i < saved.size(); ++i) { - if (saved.at(i) == "version") continue; + if (saved.at(i) == QStringLiteral("version")) continue; s.remove(saved.at(i)); } } @@ -361,17 +362,17 @@ void CollectionFilterWidget::SaveGroupBy() { qLog(Debug) << "Saving current grouping to" << name; - QSettings s; - if (settings_group_.isEmpty() || settings_group_ == CollectionSettingsPage::kSettingsGroup) { + Settings s; + if (settings_group_.isEmpty() || settings_group_ == QLatin1String(CollectionSettingsPage::kSettingsGroup)) { s.beginGroup(SavedGroupingManager::kSavedGroupingsSettingsGroup); } else { - s.beginGroup(QString(SavedGroupingManager::kSavedGroupingsSettingsGroup) + "_" + settings_group_); + s.beginGroup(QLatin1String(SavedGroupingManager::kSavedGroupingsSettingsGroup) + QLatin1Char('_') + settings_group_); } QByteArray buffer; QDataStream datastream(&buffer, QIODevice::WriteOnly); datastream << model_->GetGroupBy(); - s.setValue("version", "1"); + s.setValue("version", QStringLiteral("1")); s.setValue(name, buffer); s.endGroup(); @@ -425,7 +426,7 @@ void CollectionFilterWidget::GroupByClicked(QAction *action) { void CollectionFilterWidget::GroupingChanged(const CollectionModel::Grouping g, const bool separate_albums_by_grouping) { if (!settings_group_.isEmpty()) { - QSettings s; + Settings s; s.beginGroup(settings_group_); s.setValue(group_by_version(), 1); s.setValue(group_by_key(1), static_cast(g[0])); diff --git a/src/collection/collectionmodel.cpp b/src/collection/collectionmodel.cpp index ab977cca46..28d1444e39 100644 --- a/src/collection/collectionmodel.cpp +++ b/src/collection/collectionmodel.cpp @@ -61,6 +61,7 @@ #include "core/logging.h" #include "core/taskmanager.h" #include "core/sqlrow.h" +#include "core/settings.h" #include "collectionfilteroptions.h" #include "collectionquery.h" #include "collectionqueryoptions.h" @@ -117,7 +118,7 @@ CollectionModel::CollectionModel(SharedPtr backend, Applicati if (app_ && !sIconCache) { sIconCache = new QNetworkDiskCache(this); - sIconCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/" + kPixmapDiskCacheDir); + sIconCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/") + QLatin1String(kPixmapDiskCacheDir)); QObject::connect(app_, &Application::ClearPixmapDiskCache, this, &CollectionModel::ClearDiskCache); } @@ -177,7 +178,7 @@ void CollectionModel::set_sort_skips_articles(const bool sort_skips_articles) { void CollectionModel::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(CollectionSettingsPage::kSettingsGroup); @@ -247,7 +248,7 @@ void CollectionModel::SongsDiscovered(const SongList &songs) { GroupBy group_by = group_by_[i]; if (group_by == GroupBy::None) break; - if (!key.isEmpty()) key.append("-"); + if (!key.isEmpty()) key.append(QLatin1Char('-')); // Special case: if the song is a compilation and the current GroupBy level is Artists, then we want the Various Artists node :( if (IsArtistGroupBy(group_by) && song.is_compilation()) { @@ -329,33 +330,33 @@ QString CollectionModel::ContainerKey(const GroupBy group_by, const bool separat break; case GroupBy::Album: key = TextOrUnknown(song.album()); - if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); - if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); + if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id()); + if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping()); break; case GroupBy::AlbumDisc: key = PrettyAlbumDisc(song.album(), song.disc()); - if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); - if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); + if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id()); + if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping()); break; case GroupBy::YearAlbum: key = PrettyYearAlbum(song.year(), song.album()); - if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); - if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); + if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id()); + if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping()); break; case GroupBy::YearAlbumDisc: key = PrettyYearAlbumDisc(song.year(), song.album(), song.disc()); - if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); - if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); + if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id()); + if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping()); break; case GroupBy::OriginalYearAlbum: key = PrettyYearAlbum(song.effective_originalyear(), song.album()); - if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); - if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); + if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id()); + if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping()); break; case GroupBy::OriginalYearAlbumDisc: key = PrettyYearAlbumDisc(song.effective_originalyear(), song.album(), song.disc()); - if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); - if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); + if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id()); + if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping()); break; case GroupBy::Disc: key = PrettyDisc(song.disc()); @@ -433,7 +434,7 @@ QString CollectionModel::DividerKey(const GroupBy group_by, CollectionItem *item case GroupBy::FileType: { QChar c = item->sort_text[0]; if (c.isDigit()) return QStringLiteral("0"); - if (c == ' ') return QString(); + if (c == QLatin1Char(' ')) return QString(); if (c.decompositionTag() != QChar::NoDecomposition) { QString decomposition = c.decomposition(); return QChar(decomposition[0]); @@ -487,31 +488,31 @@ QString CollectionModel::DividerDisplayText(const GroupBy group_by, const QStrin case GroupBy::Genre: case GroupBy::FileType: case GroupBy::Format: - if (key == "0") return QStringLiteral("0-9"); + if (key == QLatin1String("0")) return QStringLiteral("0-9"); return key.toUpper(); case GroupBy::YearAlbum: case GroupBy::YearAlbumDisc: case GroupBy::OriginalYearAlbum: case GroupBy::OriginalYearAlbumDisc: - if (key == "0000") return tr("Unknown"); + if (key == QStringLiteral("0000")) return tr("Unknown"); return key.toUpper(); case GroupBy::Year: case GroupBy::OriginalYear: - if (key == "0000") return tr("Unknown"); + if (key == QStringLiteral("0000")) return tr("Unknown"); return QString::number(key.toInt()); // To remove leading 0s case GroupBy::Samplerate: - if (key == "000") return tr("Unknown"); + if (key == QStringLiteral("000")) return tr("Unknown"); return QString::number(key.toInt()); // To remove leading 0s case GroupBy::Bitdepth: - if (key == "000") return tr("Unknown"); + if (key == QStringLiteral("000")) return tr("Unknown"); return QString::number(key.toInt()); // To remove leading 0s case GroupBy::Bitrate: - if (key == "000") return tr("Unknown"); + if (key == QStringLiteral("000")) return tr("Unknown"); return QString::number(key.toInt()); // To remove leading 0s case GroupBy::None: @@ -631,13 +632,13 @@ QString CollectionModel::AlbumIconPixmapCacheKey(const QModelIndex &idx) const { idx_copy = idx_copy.parent(); } - return Song::TextForSource(backend_->source()) + "/" + path.join(QStringLiteral("/")); + return Song::TextForSource(backend_->source()) + QStringLiteral("/") + path.join(QStringLiteral("/")); } QUrl CollectionModel::AlbumIconPixmapDiskCacheKey(const QString &cache_key) const { - return QUrl(QUrl::toPercentEncoding(cache_key)); + return QUrl(QString::fromLatin1(QUrl::toPercentEncoding(cache_key))); } @@ -1061,37 +1062,37 @@ void CollectionModel::SetQueryColumnSpec(const GroupBy group_by, const bool sepa break; case GroupBy::Album:{ QString query(QStringLiteral("DISTINCT album, album_id")); - if (separate_albums_by_grouping) query.append(", grouping"); + if (separate_albums_by_grouping) query.append(QStringLiteral(", grouping")); query_options->set_column_spec(query); break; } case GroupBy::AlbumDisc:{ QString query(QStringLiteral("DISTINCT album, album_id, disc")); - if (separate_albums_by_grouping) query.append(", grouping"); + if (separate_albums_by_grouping) query.append(QStringLiteral(", grouping")); query_options->set_column_spec(query); break; } case GroupBy::YearAlbum:{ QString query(QStringLiteral("DISTINCT year, album, album_id")); - if (separate_albums_by_grouping) query.append(", grouping"); + if (separate_albums_by_grouping) query.append(QStringLiteral(", grouping")); query_options->set_column_spec(query); break; } case GroupBy::YearAlbumDisc:{ QString query(QStringLiteral("DISTINCT year, album, album_id, disc")); - if (separate_albums_by_grouping) query.append(", grouping"); + if (separate_albums_by_grouping) query.append(QStringLiteral(", grouping")); query_options->set_column_spec(query); break; } case GroupBy::OriginalYearAlbum:{ QString query(QStringLiteral("DISTINCT year, originalyear, album, album_id")); - if (separate_albums_by_grouping) query.append(", grouping"); + if (separate_albums_by_grouping) query.append(QStringLiteral(", grouping")); query_options->set_column_spec(query); break; } case GroupBy::OriginalYearAlbumDisc:{ QString query(QStringLiteral("DISTINCT year, originalyear, album, album_id, disc")); - if (separate_albums_by_grouping) query.append(", grouping"); + if (separate_albums_by_grouping) query.append(QStringLiteral(", grouping")); query_options->set_column_spec(query); break; } @@ -1133,7 +1134,7 @@ void CollectionModel::SetQueryColumnSpec(const GroupBy group_by, const bool sepa break; case GroupBy::None: case GroupBy::GroupByCount: - query_options->set_column_spec("%songs_table.ROWID, " + Song::kColumnSpec); + query_options->set_column_spec(QStringLiteral("%songs_table.ROWID, ") + Song::kColumnSpec); break; } @@ -1269,7 +1270,7 @@ CollectionItem *CollectionModel::ItemFromQuery(const GroupBy group_by, const boo CollectionItem *item = InitItem(group_by, signal, parent, container_level); if (parent != root_ && !parent->key.isEmpty()) { - item->key = parent->key + "-"; + item->key = parent->key + QLatin1Char('-'); } switch (group_by) { @@ -1363,7 +1364,7 @@ CollectionItem *CollectionModel::ItemFromQuery(const GroupBy group_by, const boo item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata)); const int year = std::max(0, item->metadata.year()); item->display_text = QString::number(year); - item->sort_text = SortTextForNumber(year) + " "; + item->sort_text = SortTextForNumber(year) + QLatin1Char(' '); break; } case GroupBy::OriginalYear:{ @@ -1371,7 +1372,7 @@ CollectionItem *CollectionModel::ItemFromQuery(const GroupBy group_by, const boo item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata)); const int year = std::max(0, item->metadata.originalyear()); item->display_text = QString::number(year); - item->sort_text = SortTextForNumber(year) + " "; + item->sort_text = SortTextForNumber(year) + QLatin1Char(' '); break; } case GroupBy::Genre:{ @@ -1424,7 +1425,7 @@ CollectionItem *CollectionModel::ItemFromQuery(const GroupBy group_by, const boo item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata)); const int samplerate = std::max(0, item->metadata.samplerate()); item->display_text = QString::number(samplerate); - item->sort_text = SortTextForNumber(samplerate) + " "; + item->sort_text = SortTextForNumber(samplerate) + QLatin1Char(' '); break; } case GroupBy::Bitdepth:{ @@ -1432,7 +1433,7 @@ CollectionItem *CollectionModel::ItemFromQuery(const GroupBy group_by, const boo item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata)); const int bitdepth = std::max(0, item->metadata.bitdepth()); item->display_text = QString::number(bitdepth); - item->sort_text = SortTextForNumber(bitdepth) + " "; + item->sort_text = SortTextForNumber(bitdepth) + QLatin1Char(' '); break; } case GroupBy::Bitrate:{ @@ -1440,7 +1441,7 @@ CollectionItem *CollectionModel::ItemFromQuery(const GroupBy group_by, const boo item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata)); const int bitrate = std::max(0, item->metadata.bitrate()); item->display_text = QString::number(bitrate); - item->sort_text = SortTextForNumber(bitrate) + " "; + item->sort_text = SortTextForNumber(bitrate) + QLatin1Char(' '); break; } case GroupBy::None: @@ -1468,7 +1469,7 @@ CollectionItem *CollectionModel::ItemFromSong(const GroupBy group_by, const bool CollectionItem *item = InitItem(group_by, signal, parent, container_level); if (parent != root_ && !parent->key.isEmpty()) { - item->key = parent->key + "-"; + item->key = parent->key + QLatin1Char('-'); } switch (group_by) { @@ -1562,7 +1563,7 @@ CollectionItem *CollectionModel::ItemFromSong(const GroupBy group_by, const bool item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s)); const int year = std::max(0, s.year()); item->display_text = QString::number(year); - item->sort_text = SortTextForNumber(year) + " "; + item->sort_text = SortTextForNumber(year) + QLatin1Char(' '); break; } case GroupBy::OriginalYear:{ @@ -1570,7 +1571,7 @@ CollectionItem *CollectionModel::ItemFromSong(const GroupBy group_by, const bool item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s)); const int year = std::max(0, s.effective_originalyear()); item->display_text = QString::number(year); - item->sort_text = SortTextForNumber(year) + " "; + item->sort_text = SortTextForNumber(year) + QLatin1Char(' '); break; } case GroupBy::Genre:{ @@ -1623,7 +1624,7 @@ CollectionItem *CollectionModel::ItemFromSong(const GroupBy group_by, const bool item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s)); const int samplerate = std::max(0, s.samplerate()); item->display_text = QString::number(samplerate); - item->sort_text = SortTextForNumber(samplerate) + " "; + item->sort_text = SortTextForNumber(samplerate) + QLatin1Char(' '); break; } case GroupBy::Bitdepth:{ @@ -1631,7 +1632,7 @@ CollectionItem *CollectionModel::ItemFromSong(const GroupBy group_by, const bool item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s)); const int bitdepth = std::max(0, s.bitdepth()); item->display_text = QString::number(bitdepth); - item->sort_text = SortTextForNumber(bitdepth) + " "; + item->sort_text = SortTextForNumber(bitdepth) + QLatin1Char(' '); break; } case GroupBy::Bitrate:{ @@ -1639,7 +1640,7 @@ CollectionItem *CollectionModel::ItemFromSong(const GroupBy group_by, const bool item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s)); const int bitrate = std::max(0, s.bitrate()); item->display_text = QString::number(bitrate); - item->sort_text = SortTextForNumber(bitrate) + " "; + item->sort_text = SortTextForNumber(bitrate) + QLatin1Char(' '); break; } case GroupBy::None: @@ -1658,7 +1659,7 @@ CollectionItem *CollectionModel::ItemFromSong(const GroupBy group_by, const bool } FinishItem(group_by, signal, create_divider, parent, item); - if (s.url().scheme() == "cdda") item->lazy_loaded = true; + if (s.url().scheme() == QStringLiteral("cdda")) item->lazy_loaded = true; return item; @@ -1678,7 +1679,7 @@ void CollectionModel::FinishItem(const GroupBy group_by, const bool signal, cons if (create_divider && show_dividers_) { QString divider_key = DividerKey(group_by, item); if (!divider_key.isEmpty()) { - item->sort_text.prepend(divider_key + " "); + item->sort_text.prepend(divider_key + QLatin1Char(' ')); } if (!divider_key.isEmpty() && !divider_nodes_.contains(divider_key)) { @@ -1689,7 +1690,7 @@ void CollectionModel::FinishItem(const GroupBy group_by, const bool signal, cons CollectionItem *divider = new CollectionItem(CollectionItem::Type_Divider, root_); divider->key = divider_key; divider->display_text = DividerDisplayText(group_by, divider_key); - divider->sort_text = divider_key + " "; + divider->sort_text = divider_key + QStringLiteral(" "); divider->lazy_loaded = true; divider_nodes_[divider_key] = divider; @@ -1712,14 +1713,14 @@ QString CollectionModel::TextOrUnknown(const QString &text) { QString CollectionModel::PrettyYearAlbum(const int year, const QString &album) { if (year <= 0) return TextOrUnknown(album); - return QString::number(year) + " - " + TextOrUnknown(album); + return QString::number(year) + QStringLiteral(" - ") + TextOrUnknown(album); } QString CollectionModel::PrettyAlbumDisc(const QString &album, const int disc) { if (disc <= 0 || Song::AlbumContainsDisc(album)) return TextOrUnknown(album); - else return TextOrUnknown(album) + " - (Disc " + QString::number(disc) + ")"; + else return TextOrUnknown(album) + QStringLiteral(" - (Disc ") + QString::number(disc) + QStringLiteral(")"); } @@ -1728,9 +1729,9 @@ QString CollectionModel::PrettyYearAlbumDisc(const int year, const QString &albu QString str; if (year <= 0) str = TextOrUnknown(album); - else str = QString::number(year) + " - " + TextOrUnknown(album); + else str = QString::number(year) + QStringLiteral(" - ") + TextOrUnknown(album); - if (!Song::AlbumContainsDisc(album) && disc > 0) str += " - (Disc " + QString::number(disc) + ")"; + if (!Song::AlbumContainsDisc(album) && disc > 0) str += QStringLiteral(" - (Disc ") + QString::number(disc) + QStringLiteral(")"); return str; @@ -1738,7 +1739,7 @@ QString CollectionModel::PrettyYearAlbumDisc(const int year, const QString &albu QString CollectionModel::PrettyDisc(const int disc) { - return "Disc " + QString::number(std::max(1, disc)); + return QStringLiteral("Disc ") + QString::number(std::max(1, disc)); } @@ -1764,7 +1765,7 @@ QString CollectionModel::SortTextForArtist(QString artist, const bool skip_artic for (const auto &i : Song::kArticles) { if (artist.startsWith(i)) { qint64 ilen = i.length(); - artist = artist.right(artist.length() - ilen) + ", " + i.left(ilen - 1); + artist = artist.right(artist.length() - ilen) + QStringLiteral(", ") + i.left(ilen - 1); break; } } @@ -1776,7 +1777,7 @@ QString CollectionModel::SortTextForArtist(QString artist, const bool skip_artic QString CollectionModel::SortTextForNumber(const int number) { - return QStringLiteral("%1").arg(number, 4, 10, QChar('0')); + return QStringLiteral("%1").arg(number, 4, 10, QLatin1Char('0')); } QString CollectionModel::SortTextForYear(const int year) { @@ -1858,10 +1859,10 @@ bool CollectionModel::CompareItems(const CollectionItem *a, const CollectionItem } -qint64 CollectionModel::MaximumCacheSize(QSettings *s, const char *size_id, const char *size_unit_id, const qint64 cache_size_default) { +qint64 CollectionModel::MaximumCacheSize(Settings *s, const char *size_id, const char *size_unit_id, const qint64 cache_size_default) { - qint64 size = s->value(size_id, cache_size_default).toInt(); - int unit = s->value(size_unit_id, static_cast(CollectionSettingsPage::CacheSizeUnit::MB)).toInt() + 1; + qint64 size = s->value(QLatin1String(size_id), cache_size_default).toInt(); + int unit = s->value(QLatin1String(size_unit_id), static_cast(CollectionSettingsPage::CacheSizeUnit::MB)).toInt() + 1; do { size *= 1024; diff --git a/src/collection/collectionmodel.h b/src/collection/collectionmodel.h index d520a6b497..fb61ef0bd6 100644 --- a/src/collection/collectionmodel.h +++ b/src/collection/collectionmodel.h @@ -55,7 +55,7 @@ #include "collectionqueryoptions.h" #include "collectionitem.h" -class QSettings; +class Settings; class Application; class CollectionBackend; @@ -82,7 +82,7 @@ class CollectionModel : public SimpleTreeModel { LastRole }; - // These values get saved in QSettings - don't change them + // These values get saved in Settings - don't change them enum class GroupBy { None = 0, AlbumArtist = 1, @@ -275,7 +275,7 @@ class CollectionModel : public SimpleTreeModel { QVariant AlbumIcon(const QModelIndex &idx); QVariant data(const CollectionItem *item, const int role) const; bool CompareItems(const CollectionItem *a, const CollectionItem *b) const; - static qint64 MaximumCacheSize(QSettings *s, const char *size_id, const char *size_unit_id, const qint64 cache_size_default); + static qint64 MaximumCacheSize(Settings *s, const char *size_id, const char *size_unit_id, const qint64 cache_size_default); private: SharedPtr backend_; diff --git a/src/collection/collectionquery.cpp b/src/collection/collectionquery.cpp index 62d060bb2a..2a2657718f 100644 --- a/src/collection/collectionquery.cpp +++ b/src/collection/collectionquery.cpp @@ -62,18 +62,18 @@ CollectionQuery::CollectionQuery(const QSqlDatabase &db, const QString &songs_ta #endif QString query; for (QString token : tokens) { - token.remove('(') - .remove(')') - .remove('"') - .replace('-', ' '); - - if (token.contains(':')) { - const QString columntoken = token.section(':', 0, 0); - QString subtoken = token.section(':', 1, -1).replace(QLatin1String(":"), QLatin1String(" ")).trimmed(); + token.remove(QLatin1Char('(')) + .remove(QLatin1Char(')')) + .remove(QLatin1Char('"')) + .replace(QLatin1Char('-'), QLatin1Char(' ')); + + if (token.contains(QLatin1Char(':'))) { + const QString columntoken = token.section(QLatin1Char(':'), 0, 0); + QString subtoken = token.section(QLatin1Char(':'), 1, -1).replace(QLatin1String(":"), QLatin1String(" ")).trimmed(); if (subtoken.isEmpty()) continue; - if (Song::kFtsColumns.contains("fts" + columntoken, Qt::CaseInsensitive)) { - if (!query.isEmpty()) query.append(" "); - query += "fts" + columntoken + ":\"" + subtoken + "\"*"; + if (Song::kFtsColumns.contains(QLatin1String("fts") + columntoken, Qt::CaseInsensitive)) { + if (!query.isEmpty()) query.append(QLatin1String(" ")); + query += QStringLiteral("fts") + columntoken + QStringLiteral(":\"") + subtoken + QStringLiteral("\"*"); } else if (Song::kNumericalColumns.contains(columntoken, Qt::CaseInsensitive)) { QString comparator = RemoveSqlOperator(subtoken); @@ -82,7 +82,7 @@ CollectionQuery::CollectionQuery(const QSqlDatabase &db, const QString &songs_ta } else if (columntoken.compare(QLatin1String("length"), Qt::CaseInsensitive) == 0) { // Time is saved in nanoseconds, so add 9 0's - QString parsedTime = QString::number(Utilities::ParseSearchTime(subtoken)) + "000000000"; + QString parsedTime = QString::number(Utilities::ParseSearchTime(subtoken)) + QStringLiteral("000000000"); AddWhere(columntoken, parsedTime, comparator); } else { @@ -93,14 +93,14 @@ CollectionQuery::CollectionQuery(const QSqlDatabase &db, const QString &songs_ta else { token = token.replace(QLatin1String(":"), QLatin1String(" ")).trimmed(); if (!token.isEmpty()) { - if (!query.isEmpty()) query.append(" "); - query += "\"" + token + "\"*"; + if (!query.isEmpty()) query.append(QLatin1Char(' ')); + query += QLatin1Char('\"') + token + QStringLiteral("\"*"); } } } else { - if (!query.isEmpty()) query.append(" "); - query += "\"" + token + "\"*"; + if (!query.isEmpty()) query.append(QLatin1Char(' ')); + query += QLatin1Char('\"') + token + QStringLiteral("\"*"); } } if (!query.isEmpty()) { @@ -141,7 +141,7 @@ QString CollectionQuery::RemoveSqlOperator(QString &token) { } token.remove(rxOp); - if (op == "!=") { + if (op == QStringLiteral("!=")) { op = QStringLiteral("<>"); } @@ -161,7 +161,7 @@ void CollectionQuery::AddWhere(const QString &column, const QVariant &value, con bound_values_ << single_value; } - where_clauses_ << QString("%1 IN (" + final_values.join(QStringLiteral(",")) + ")").arg(column); + where_clauses_ << QStringLiteral("%1 IN (%2)").arg(column, final_values.join(QStringLiteral(","))); } else { // Do integers inline - sqlite seems to get confused when you pass integers to bound parameters @@ -205,19 +205,19 @@ void CollectionQuery::AddWhereRating(const QVariant &value, const QString &op) { // You can't query the database for a float, due to float precision errors, // So we have to use a certain tolerance, so that the searched value is definetly included. const float tolerance = 0.001F; - if (op == "<") { + if (op == QStringLiteral("<")) { AddWhere(QStringLiteral("rating"), parsed_rating-tolerance, QStringLiteral("<")); } - else if (op == ">") { + else if (op == QStringLiteral(">")) { AddWhere(QStringLiteral("rating"), parsed_rating+tolerance, QStringLiteral(">")); } - else if (op == "<=") { + else if (op == QStringLiteral("<=")) { AddWhere(QStringLiteral("rating"), parsed_rating+tolerance, QStringLiteral("<=")); } - else if (op == ">=") { + else if (op == QStringLiteral(">=")) { AddWhere(QStringLiteral("rating"), parsed_rating-tolerance, QStringLiteral(">=")); } - else if (op == "<>") { + else if (op == QStringLiteral("<>")) { where_clauses_ << QStringLiteral("(rating?)"); bound_values_ << parsed_rating - tolerance; bound_values_ << parsed_rating + tolerance; @@ -239,7 +239,7 @@ void CollectionQuery::AddCompilationRequirement(const bool compilation) { QString CollectionQuery::GetInnerQuery() const { return duplicates_only_ - ? QString(" INNER JOIN (select * from duplicated_songs) dsongs " + ? QStringLiteral(" INNER JOIN (select * from duplicated_songs) dsongs " "ON (%songs_table.artist = dsongs.dup_artist " "AND %songs_table.album = dsongs.dup_album " "AND %songs_table.title = dsongs.dup_title) ") @@ -262,14 +262,14 @@ bool CollectionQuery::Exec() { where_clauses << QStringLiteral("unavailable = 0"); } - if (!where_clauses.isEmpty()) sql += " WHERE " + where_clauses.join(QStringLiteral(" AND ")); + if (!where_clauses.isEmpty()) sql += QStringLiteral(" WHERE ") + where_clauses.join(QStringLiteral(" AND ")); - if (!order_by_.isEmpty()) sql += " ORDER BY " + order_by_; + if (!order_by_.isEmpty()) sql += QStringLiteral(" ORDER BY ") + order_by_; - if (limit_ != -1) sql += " LIMIT " + QString::number(limit_); + if (limit_ != -1) sql += QStringLiteral(" LIMIT ") + QString::number(limit_); sql.replace(QLatin1String("%songs_table"), songs_table_); - sql.replace(QLatin1String("%fts_table_noprefix"), fts_table_.section('.', -1, -1)); + sql.replace(QLatin1String("%fts_table_noprefix"), fts_table_.section(QLatin1Char('.'), -1, -1)); sql.replace(QLatin1String("%fts_table"), fts_table_); if (!QSqlQuery::prepare(sql)) return false; diff --git a/src/collection/collectionview.cpp b/src/collection/collectionview.cpp index 0b438dc32c..fc4d182cad 100644 --- a/src/collection/collectionview.cpp +++ b/src/collection/collectionview.cpp @@ -52,6 +52,7 @@ #include "core/mimedata.h" #include "core/musicstorage.h" #include "core/deletefiles.h" +#include "core/settings.h" #include "utilities/filemanagerutils.h" #include "collection.h" #include "collectionbackend.h" @@ -224,7 +225,7 @@ bool CollectionView::RestoreLevelFocus(const QModelIndex &parent) { void CollectionView::ReloadSettings() { - QSettings settings; + Settings settings; settings.beginGroup(CollectionSettingsPage::kSettingsGroup); SetAutoOpen(settings.value("auto_open", false).toBool()); diff --git a/src/collection/collectionwatcher.cpp b/src/collection/collectionwatcher.cpp index 86310bf82f..08ee9fbfe8 100644 --- a/src/collection/collectionwatcher.cpp +++ b/src/collection/collectionwatcher.cpp @@ -48,6 +48,7 @@ #include "core/logging.h" #include "core/tagreaderclient.h" #include "core/taskmanager.h" +#include "core/settings.h" #include "utilities/imageutils.h" #include "utilities/timeconstants.h" #include "collectiondirectory.h" @@ -150,7 +151,7 @@ void CollectionWatcher::ReloadSettingsAsync() { void CollectionWatcher::ReloadSettings() { const bool was_monitoring_before = monitor_; - QSettings s; + Settings s; s.beginGroup(CollectionSettingsPage::kSettingsGroup); scan_on_startup_ = s.value("startup_scan", true).toBool(); monitor_ = s.value("monitor", true).toBool(); @@ -316,7 +317,7 @@ SongList CollectionWatcher::ScanTransaction::FindSongsInSubdirectory(const QStri if (cached_songs_dirty_) { const SongList songs = watcher_->backend_->FindSongsInDirectory(dir_); for (const Song &song : songs) { - const QString p = song.url().toLocalFile().section('/', 0, -2); + const QString p = song.url().toLocalFile().section(QLatin1Char('/'), 0, -2); cached_songs_.insert(p, song); } cached_songs_dirty_ = false; @@ -334,7 +335,7 @@ bool CollectionWatcher::ScanTransaction::HasSongsWithMissingFingerprint(const QS if (cached_songs_missing_fingerprint_dirty_) { const SongList songs = watcher_->backend_->SongsWithMissingFingerprint(dir_); for (const Song &song : songs) { - const QString p = song.url().toLocalFile().section('/', 0, -2); + const QString p = song.url().toLocalFile().section(QLatin1Char('/'), 0, -2); cached_songs_missing_fingerprint_.insert(p, song); } cached_songs_missing_fingerprint_dirty_ = false; @@ -349,7 +350,7 @@ bool CollectionWatcher::ScanTransaction::HasSongsWithMissingLoudnessCharacterist if (cached_songs_missing_loudness_characteristics_dirty_) { const SongList songs = watcher_->backend_->SongsWithMissingLoudnessCharacteristics(dir_); for (const Song &song : songs) { - const QString p = song.url().toLocalFile().section('/', 0, -2); + const QString p = song.url().toLocalFile().section(QLatin1Char('/'), 0, -2); cached_songs_missing_loudness_characteristics_.insert(p, song); } cached_songs_missing_loudness_characteristics_dirty_ = false; @@ -510,7 +511,7 @@ void CollectionWatcher::ScanSubdirectory(const QString &path, const CollectionSu else { QString ext_part(ExtensionPart(child)); QString dir_part(DirectoryPart(child)); - if (kIgnoredExtensions.contains(child_info.suffix(), Qt::CaseInsensitive) || child_info.baseName() == "qt_temp") { + if (kIgnoredExtensions.contains(child_info.suffix(), Qt::CaseInsensitive) || child_info.baseName() == QStringLiteral("qt_temp")) { t->AddToProgress(1); } else if (sValidImages.contains(ext_part)) { @@ -643,7 +644,7 @@ void CollectionWatcher::ScanSubdirectory(const QString &path, const CollectionSu } } #endif - if (song_tracking_ && !fingerprint.isEmpty() && fingerprint != "NONE" && FindSongsByFingerprint(file, fingerprint, &matching_songs)) { + if (song_tracking_ && !fingerprint.isEmpty() && fingerprint != QStringLiteral("NONE") && FindSongsByFingerprint(file, fingerprint, &matching_songs)) { // The song is in the database and still on disk. // Check the mtime to see if it's been changed since it was added. @@ -1308,7 +1309,7 @@ void CollectionWatcher::RescanSongs(const SongList &songs) { QStringList scanned_paths; for (const Song &song : songs) { if (stop_requested_ || abort_requested_) break; - const QString song_path = song.url().toLocalFile().section('/', 0, -2); + const QString song_path = song.url().toLocalFile().section(QLatin1Char('/'), 0, -2); if (scanned_paths.contains(song_path)) continue; ScanTransaction transaction(this, song.directory_id(), false, true, mark_songs_unavailable_); CollectionSubdirectoryList subdirs(transaction.GetAllSubdirs()); diff --git a/src/collection/collectionwatcher.h b/src/collection/collectionwatcher.h index 4b1c0a016f..dd413479eb 100644 --- a/src/collection/collectionwatcher.h +++ b/src/collection/collectionwatcher.h @@ -252,14 +252,14 @@ class CollectionWatcher : public QObject { }; inline QString CollectionWatcher::NoExtensionPart(const QString &fileName) { - return fileName.contains('.') ? fileName.section('.', 0, -2) : QLatin1String(""); + return fileName.contains(QLatin1Char('.')) ? fileName.section(QLatin1Char('.'), 0, -2) : QLatin1String(""); } // Thanks Amarok inline QString CollectionWatcher::ExtensionPart(const QString &fileName) { - return fileName.contains( '.' ) ? fileName.mid( fileName.lastIndexOf('.') + 1 ).toLower() : QLatin1String(""); + return fileName.contains(QLatin1Char('.')) ? fileName.mid(fileName.lastIndexOf(QLatin1Char('.')) + 1).toLower() : QLatin1String(""); } inline QString CollectionWatcher::DirectoryPart(const QString &fileName) { - return fileName.section('/', 0, -2); + return fileName.section(QLatin1Char('/'), 0, -2); } #endif // COLLECTIONWATCHER_H diff --git a/src/collection/savedgroupingmanager.cpp b/src/collection/savedgroupingmanager.cpp index c58b76435f..ae2501251b 100644 --- a/src/collection/savedgroupingmanager.cpp +++ b/src/collection/savedgroupingmanager.cpp @@ -36,6 +36,7 @@ #include "core/logging.h" #include "core/iconloader.h" +#include "core/settings.h" #include "settings/collectionsettingspage.h" #include "collectionmodel.h" #include "savedgroupingmanager.h" @@ -72,11 +73,11 @@ SavedGroupingManager::~SavedGroupingManager() { QString SavedGroupingManager::GetSavedGroupingsSettingsGroup(const QString &settings_group) { - if (settings_group.isEmpty() || settings_group == CollectionSettingsPage::kSettingsGroup) { - return kSavedGroupingsSettingsGroup; + if (settings_group.isEmpty() || settings_group == QLatin1String(CollectionSettingsPage::kSettingsGroup)) { + return QLatin1String(kSavedGroupingsSettingsGroup); } else { - return QString(kSavedGroupingsSettingsGroup) + "_" + settings_group; + return QLatin1String(kSavedGroupingsSettingsGroup) + QStringLiteral("_") + settings_group; } } @@ -157,13 +158,13 @@ QString SavedGroupingManager::GroupByToString(const CollectionModel::GroupBy g) void SavedGroupingManager::UpdateModel() { model_->setRowCount(0); // don't use clear, it deletes headers - QSettings s; + Settings s; s.beginGroup(saved_groupings_settings_group_); int version = s.value("version").toInt(); if (version == 1) { QStringList saved = s.childKeys(); for (int i = 0; i < saved.size(); ++i) { - if (saved.at(i) == "version") continue; + if (saved.at(i) == QStringLiteral("version")) continue; QByteArray bytes = s.value(saved.at(i)).toByteArray(); QDataStream ds(&bytes, QIODevice::ReadOnly); CollectionModel::Grouping g; @@ -181,7 +182,7 @@ void SavedGroupingManager::UpdateModel() { else { QStringList saved = s.childKeys(); for (int i = 0; i < saved.size(); ++i) { - if (saved.at(i) == "version") continue; + if (saved.at(i) == QStringLiteral("version")) continue; s.remove(saved.at(i)); } } @@ -192,7 +193,7 @@ void SavedGroupingManager::UpdateModel() { void SavedGroupingManager::Remove() { if (ui_->list->selectionModel()->hasSelection()) { - QSettings s; + Settings s; s.beginGroup(saved_groupings_settings_group_); for (const QModelIndex &idx : ui_->list->selectionModel()->selectedRows()) { if (idx.isValid()) { diff --git a/src/context/contextalbum.cpp b/src/context/contextalbum.cpp index bb718a22b4..aeec499e01 100644 --- a/src/context/contextalbum.cpp +++ b/src/context/contextalbum.cpp @@ -61,7 +61,7 @@ ContextAlbum::ContextAlbum(QWidget *parent) pixmap_current_opacity_(1.0), desired_height_(width()) { - setObjectName("context-widget-album"); + setObjectName(QStringLiteral("context-widget-album")); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); @@ -266,7 +266,7 @@ void ContextAlbum::SearchCoverInProgress() { downloading_covers_ = true; // Show a spinner animation - spinner_animation_ = make_unique(":/pictures/spinner.gif", QByteArray(), this); + spinner_animation_ = make_unique(QStringLiteral(":/pictures/spinner.gif"), QByteArray(), this); QObject::connect(&*spinner_animation_, &QMovie::updated, this, &ContextAlbum::Update); spinner_animation_->start(); update(); diff --git a/src/context/contextview.cpp b/src/context/contextview.cpp index 48d40d5b93..874b3c3632 100644 --- a/src/context/contextview.cpp +++ b/src/context/contextview.cpp @@ -51,6 +51,7 @@ #include "core/application.h" #include "core/player.h" #include "core/song.h" +#include "core/settings.h" #include "utilities/strutils.h" #include "utilities/timeutils.h" #include "widgets/resizabletextedit.h" @@ -112,25 +113,25 @@ ContextView::ContextView(QWidget *parent) setLayout(layout_container_); - layout_container_->setObjectName("context-layout-container"); + layout_container_->setObjectName(QStringLiteral("context-layout-container")); layout_container_->setContentsMargins(0, 0, 0, 0); layout_container_->addWidget(scrollarea_); - scrollarea_->setObjectName("context-scrollarea"); + scrollarea_->setObjectName(QStringLiteral("context-scrollarea")); scrollarea_->setWidgetResizable(true); scrollarea_->setWidget(widget_scrollarea_); scrollarea_->setContentsMargins(0, 0, 0, 0); scrollarea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollarea_->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - widget_scrollarea_->setObjectName("context-widget-scrollarea"); + widget_scrollarea_->setObjectName(QStringLiteral("context-widget-scrollarea")); widget_scrollarea_->setLayout(layout_scrollarea_); widget_scrollarea_->setContentsMargins(0, 0, 0, 0); textedit_top_->setReadOnly(true); textedit_top_->setFrameShape(QFrame::NoFrame); - layout_scrollarea_->setObjectName("context-layout-scrollarea"); + layout_scrollarea_->setObjectName(QStringLiteral("context-layout-scrollarea")); layout_scrollarea_->setContentsMargins(15, 15, 15, 15); layout_scrollarea_->addWidget(textedit_top_); layout_scrollarea_->addWidget(widget_album_); @@ -291,20 +292,20 @@ void ContextView::ReloadSettings() { QString default_font; #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - if (QFontDatabase::families().contains(ContextSettingsPage::kDefaultFontFamily)) { + if (QFontDatabase::families().contains(QLatin1String(ContextSettingsPage::kDefaultFontFamily))) { #else - if (QFontDatabase().families().contains(ContextSettingsPage::kDefaultFontFamily)) { + if (QFontDatabase().families().contains(QLatin1String(ContextSettingsPage::kDefaultFontFamily))) { #endif - default_font = ContextSettingsPage::kDefaultFontFamily; + default_font = QLatin1String(ContextSettingsPage::kDefaultFontFamily); } else { default_font = font().family(); } - QSettings s; + Settings s; s.beginGroup(ContextSettingsPage::kSettingsGroup); - title_fmt_ = s.value(ContextSettingsPage::kSettingsTitleFmt, "%title% - %artist%").toString(); - summary_fmt_ = s.value(ContextSettingsPage::kSettingsSummaryFmt, "%album%").toString(); + title_fmt_ = s.value(ContextSettingsPage::kSettingsTitleFmt, QStringLiteral("%title% - %artist%")).toString(); + summary_fmt_ = s.value(ContextSettingsPage::kSettingsSummaryFmt, QStringLiteral("%album%")).toString(); action_show_album_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[static_cast(ContextSettingsPage::ContextSettingsOrder::ALBUM)], true).toBool()); action_show_data_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[static_cast(ContextSettingsPage::ContextSettingsOrder::TECHNICAL_DATA)], false).toBool()); action_show_lyrics_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[static_cast(ContextSettingsPage::ContextSettingsOrder::SONG_LYRICS)], true).toBool()); @@ -390,7 +391,7 @@ void ContextView::FadeStopFinished() { } void ContextView::SetLabelText(QLabel *label, int value, const QString &suffix, const QString &def) { - label->setText(value <= 0 ? def : (QString::number(value) + " " + suffix)); + label->setText(value <= 0 ? def : (QString::number(value) + QStringLiteral(" ") + suffix)); } void ContextView::UpdateNoSong() { @@ -635,7 +636,7 @@ void ContextView::UpdateLyrics(const quint64 id, const QString &provider, const lyrics_ = QStringLiteral("No lyrics found.\n"); } else { - lyrics_ = lyrics + "\n\n(Lyrics from " + provider + ")\n"; + lyrics_ = lyrics + QStringLiteral("\n\n(Lyrics from ") + provider + QStringLiteral(")\n"); } lyrics_id_ = -1; @@ -692,7 +693,7 @@ void ContextView::AlbumCoverLoaded(const Song &song, const QImage &image) { void ContextView::ActionShowAlbum() { - QSettings s; + Settings s; s.beginGroup(ContextSettingsPage::kSettingsGroup); s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast(ContextSettingsPage::ContextSettingsOrder::ALBUM)], action_show_album_->isChecked()); s.endGroup(); @@ -702,7 +703,7 @@ void ContextView::ActionShowAlbum() { void ContextView::ActionShowData() { - QSettings s; + Settings s; s.beginGroup(ContextSettingsPage::kSettingsGroup); s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast(ContextSettingsPage::ContextSettingsOrder::TECHNICAL_DATA)], action_show_data_->isChecked()); s.endGroup(); @@ -712,7 +713,7 @@ void ContextView::ActionShowData() { void ContextView::ActionShowLyrics() { - QSettings s; + Settings s; s.beginGroup(ContextSettingsPage::kSettingsGroup); s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast(ContextSettingsPage::ContextSettingsOrder::SONG_LYRICS)], action_show_lyrics_->isChecked()); s.endGroup(); @@ -725,7 +726,7 @@ void ContextView::ActionShowLyrics() { void ContextView::ActionSearchLyrics() { - QSettings s; + Settings s; s.beginGroup(ContextSettingsPage::kSettingsGroup); s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast(ContextSettingsPage::ContextSettingsOrder::SEARCH_LYRICS)], action_search_lyrics_->isChecked()); s.endGroup(); diff --git a/src/core/commandlineoptions.cpp b/src/core/commandlineoptions.cpp index 9c995f7ab4..cfbf5666a1 100644 --- a/src/core/commandlineoptions.cpp +++ b/src/core/commandlineoptions.cpp @@ -100,7 +100,7 @@ CommandlineOptions::CommandlineOptions(int argc, char **argv) play_track_at_(-1), show_osd_(false), toggle_pretty_osd_(false), - log_levels_(logging::kDefaultLogLevels) { + log_levels_(QLatin1String(logging::kDefaultLogLevels)) { #ifdef Q_OS_WIN32 Q_UNUSED(argv); @@ -108,7 +108,7 @@ CommandlineOptions::CommandlineOptions(int argc, char **argv) #ifdef Q_OS_MACOS // Remove -psn_xxx option that Mac passes when opened from Finder. - RemoveArg("-psn", 1); + RemoveArg(QStringLiteral("-psn"), 1); #endif // Remove the -session option that KDE passes @@ -214,7 +214,7 @@ bool CommandlineOptions::Parse() { switch (c) { case 'h': { QString translated_help_text = - QString(kHelpText) + QString::fromUtf8(kHelpText) .arg(QObject::tr("Usage"), QObject::tr("options"), QObject::tr("URL(s)"), QObject::tr("Player options"), QObject::tr("Start the playlist currently playing"), @@ -429,7 +429,7 @@ QString CommandlineOptions::DecodeName(wchar_t *opt) { #else QString CommandlineOptions::OptArgToString(char *opt) { - return QString(opt); + return QString::fromUtf8(opt); } QString CommandlineOptions::DecodeName(char *opt) { diff --git a/src/core/database.cpp b/src/core/database.cpp index 8e42214a64..b7e492ed83 100644 --- a/src/core/database.cpp +++ b/src/core/database.cpp @@ -50,7 +50,7 @@ const char *Database::kDatabaseFilename = "strawberry.db"; const int Database::kSchemaVersion = 18; const int Database::kMinSupportedSchemaVersion = 10; -const char *Database::kMagicAllSongsTables = "%allsongstables"; +constexpr char Database::kMagicAllSongsTables[] = "%allsongstables"; int Database::sNextConnectionId = 1; QMutex Database::sNextConnectionIdMutex; @@ -131,14 +131,14 @@ QSqlDatabase Database::Connect() { //qLog(Debug) << "Opened database with connection id" << connection_id; if (injected_database_name_.isNull()) { - db.setDatabaseName(directory_ + "/" + kDatabaseFilename); + db.setDatabaseName(directory_ + QLatin1Char('/') + QLatin1String(kDatabaseFilename)); } else { db.setDatabaseName(injected_database_name_); } if (!db.open()) { - app_->AddError("Database: " + db.lastError().text()); + app_->AddError(QStringLiteral("Database: ") + db.lastError().text()); return db; } @@ -405,16 +405,16 @@ void Database::ExecSongTablesCommands(QSqlDatabase &db, const QStringList &song_ for (const QString &command : commands) { // There are now lots of "songs" tables that need to have the same schema: songs and device_*_songs. // We allow a magic value in the schema files to update all songs tables at once. - if (command.contains(kMagicAllSongsTables)) { + if (command.contains(QLatin1String(kMagicAllSongsTables))) { for (const QString &table : song_tables) { // Another horrible hack: device songs tables don't have matching _fts tables, so if this command tries to touch one, ignore it. - if (table.startsWith(QLatin1String("device_")) && command.contains(QString(kMagicAllSongsTables) + "_fts")) { + if (table.startsWith(QLatin1String("device_")) && command.contains(QLatin1String(kMagicAllSongsTables) + QStringLiteral("_fts"))) { continue; } qLog(Info) << "Updating" << table << "for" << kMagicAllSongsTables; QString new_command(command); - new_command.replace(kMagicAllSongsTables, table); + new_command.replace(QLatin1String(kMagicAllSongsTables), table); SqlQuery query(db); query.prepare(new_command); if (!query.Exec()) { @@ -443,7 +443,7 @@ QStringList Database::SongsTables(QSqlDatabase &db, const int schema_version) { // look for the tables in the main db for (const QString &table : db.tables()) { - if (table == "songs" || table.endsWith(QLatin1String("_songs"))) ret << table; + if (table == QStringLiteral("songs") || table.endsWith(QLatin1String("_songs"))) ret << table; } // look for the tables in attached dbs @@ -453,7 +453,7 @@ QStringList Database::SongsTables(QSqlDatabase &db, const int schema_version) { q.prepare(QStringLiteral("SELECT NAME FROM %1.sqlite_master WHERE type='table' AND name='songs' OR name LIKE '%songs'").arg(key)); if (q.Exec()) { while (q.next()) { - QString tab_name = key + "." + q.value(0).toString(); + QString tab_name = key + QStringLiteral(".") + q.value(0).toString(); ret << tab_name; } } @@ -495,13 +495,13 @@ bool Database::IntegrityCheck(const QSqlDatabase &db) { QString message = q.value(0).toString(); // If no errors are found, a single row with the value "ok" is returned - if (message == "ok") { + if (message == QStringLiteral("ok")) { ok = true; break; } else { if (!error_reported) { app_->AddError(tr("Database corruption detected.")); } - app_->AddError("Database: " + message); + app_->AddError(QStringLiteral("Database: ") + message); error_reported = true; } } diff --git a/src/core/database.h b/src/core/database.h index 4cd0ec80f7..01bd584c0c 100644 --- a/src/core/database.h +++ b/src/core/database.h @@ -63,7 +63,7 @@ class Database : public QObject { static const int kSchemaVersion; static const int kMinSupportedSchemaVersion; static const char *kDatabaseFilename; - static const char *kMagicAllSongsTables; + static const char kMagicAllSongsTables[]; void ExitAsync(); QSqlDatabase Connect(); diff --git a/src/core/filesystemmusicstorage.cpp b/src/core/filesystemmusicstorage.cpp index f613420eee..67a018c56b 100644 --- a/src/core/filesystemmusicstorage.cpp +++ b/src/core/filesystemmusicstorage.cpp @@ -39,13 +39,13 @@ FilesystemMusicStorage::FilesystemMusicStorage(const Song::Source source, const bool FilesystemMusicStorage::CopyToStorage(const CopyJob &job, QString &error_text) { const QFileInfo src = QFileInfo(job.source_); - const QFileInfo dest = QFileInfo(root_ + "/" + job.destination_); + const QFileInfo dest = QFileInfo(root_ + QStringLiteral("/") + job.destination_); QFileInfo cover_src; QFileInfo cover_dest; if (job.albumcover_ && !job.cover_source_.isEmpty() && !job.cover_dest_.isEmpty()) { cover_src = QFileInfo(job.cover_source_); - cover_dest = QFileInfo(root_ + "/" + job.cover_dest_); + cover_dest = QFileInfo(root_ + QStringLiteral("/") + job.cover_dest_); } // Don't do anything if the destination is the same as the source diff --git a/src/core/iconloader.cpp b/src/core/iconloader.cpp index 4a2c2ec32e..8238474f77 100644 --- a/src/core/iconloader.cpp +++ b/src/core/iconloader.cpp @@ -29,6 +29,7 @@ #include #include "core/logging.h" +#include "settings.h" #include "iconmapper.h" #include "settings/appearancesettingspage.h" #include "iconloader.h" @@ -39,14 +40,14 @@ bool IconLoader::custom_icons_ = false; void IconLoader::Init() { #if !defined(Q_OS_MACOS) && !defined(Q_OS_WIN) - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); system_icons_ = s.value("system_icons", false).toBool(); s.endGroup(); #endif QDir dir; - if (dir.exists(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/icons")) { + if (dir.exists(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/icons"))) { custom_icons_ = true; } @@ -118,7 +119,7 @@ QIcon IconLoader::Load(const QString &name, const bool system_icon, const int fi } if (custom_icons_) { - QString custom_icon_path = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/icons/%1x%2/%3.png"; + QString custom_icon_path = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/icons/%1x%2/%3.png"); for (int s : sizes) { QString filename(custom_icon_path.arg(s).arg(s).arg(name)); if (QFile::exists(filename)) ret.addFile(filename, QSize(s, s)); diff --git a/src/core/iconmapper.h b/src/core/iconmapper.h index 340d81488d..6b4848a56c 100644 --- a/src/core/iconmapper.h +++ b/src/core/iconmapper.h @@ -38,100 +38,100 @@ struct IconProperties { static const QMap iconmapper_ = { // clazy:exclude=non-pod-global-static - { "albums", { {"media-optical"}} }, - { "alsa", { {}} }, - { "application-exit", { {}} }, - { "applications-internet", { {}} }, - { "bluetooth", { {"preferences-system-bluetooth", "bluetooth-active"}} }, - { "cdcase", { {"cdcover", "media-optical"}} }, - { "media-optical", { {"cd"}} }, - { "configure", { {}} }, - { "device-ipod-nano", { {}} }, - { "device-ipod", { {}} }, - { "device-phone", { {}} }, - { "device", { {"drive-removable-media-usb-pendrive"}} }, - { "device-usb-drive", { {}} }, - { "device-usb-flash", { {}} }, - { "dialog-error", { {}} }, - { "dialog-information", { {}} }, - { "dialog-ok-apply", { {}} }, - { "dialog-password", { {}} }, - { "dialog-warning", { {}} }, - { "document-download", { {"download"}} }, - { "document-new", { {}} }, - { "document-open-folder", { {}} }, - { "document-open", { {}} }, - { "document-save", { {}} }, - { "document-search", { {}} }, - { "document-open-remote", { {}} }, - { "download", { {"applications-internet", "network-workgroup"}} }, - { "edit-clear-list", { {"edit-clear-list","edit-clear-all"}} }, - { "edit-clear-locationbar-ltr", { {"edit-clear-locationbar-ltr"}} }, - { "edit-copy", { {}} }, - { "edit-delete", { {}} }, - { "edit-find", { {}} }, - { "edit-redo", { {}} }, - { "edit-rename", { {}} }, - { "edit-undo", { {}} }, - { "electrocompaniet", { {}} }, - { "equalizer", { {"view-media-equalizer"}} }, - { "folder-new", { {}} }, - { "folder", { {}} }, - { "folder-sound", { {"folder-music"}} }, - { "footsteps", { {"go-jump"}} }, - { "go-down", { {}} }, - { "go-home", { {}} }, - { "go-jump", { {}} }, - { "go-next", { {}} }, - { "go-previous", { {}} }, - { "go-up", { {}} }, - { "gstreamer", { {"phonon-gstreamer"}} }, - { "headset", { {"audio-headset"}} }, - { "help-hint", { {}} }, - { "intel", { {}} }, - { "jack", { {"audio-input-line"}} }, - { "keyboard", { {"input-keyboard"}} }, - { "list-add", { {}} }, - { "list-remove", { {}} }, - { "love", { {"heart", "emblem-favorite"}} }, - { "mcintosh-player", { {}} }, - { "mcintosh", { {}} }, - { "mcintosh-text", { {}} }, - { "media-eject", { {}} }, - { "media-playback-pause", { {"media-pause"}} }, - { "media-playlist-repeat", { {}} }, - { "media-playlist-shuffle", { {""}} }, - { "media-playback-start", { {"media-play", "media-playback-playing"}} }, - { "media-seek-backward", { {}} }, - { "media-seek-forward", { {}} }, - { "media-skip-backward", { {}} }, - { "media-skip-forward", { {}} }, - { "media-playback-stop", { {"media-stop"}} }, - { "moodbar", { {"preferences-desktop-icons"}} }, - { "nvidia", { {}} }, - { "pulseaudio", { {}} }, - { "realtek", { {}} }, - { "scrobble-disabled", { {}} }, - { "scrobble", { {"love"}} }, - { "search", { {}} }, - { "soundcard", { {"audiocard", "audio-card"}} }, - { "speaker", { {}} }, - { "star-grey", { {}} }, - { "star", { {}} }, - { "strawberry", { {}} }, - { "subsonic", { {}} }, - { "tidal", { {}} }, - { "tools-wizard", { {}} }, - { "view-choose", { {}} }, - { "view-fullscreen", { {}} }, - { "view-media-lyrics", { {}} }, - { "view-media-playlist", { {}} }, - { "view-media-visualization", { {"preferences-desktop-theme"}} }, - { "view-refresh", { {}} }, - { "library-music", { {"vinyl"}} }, - { "vlc", { {}} }, - { "zoom-in", { {}} }, - { "zoom-out", { {}, 0, 0 } } + { QStringLiteral("albums"), { {QStringLiteral("media-optical")}} }, + { QStringLiteral("alsa"), { {}} }, + { QStringLiteral("application-exit"), { {}} }, + { QStringLiteral("applications-internet"), { {}} }, + { QStringLiteral("bluetooth"), { {QStringLiteral("preferences-system-bluetooth"), QStringLiteral("bluetooth-active")}} }, + { QStringLiteral("cdcase"), { {QStringLiteral("cdcover"), QStringLiteral("media-optical")}} }, + { QStringLiteral("media-optical"), { {QStringLiteral("cd")}} }, + { QStringLiteral("configure"), { {}} }, + { QStringLiteral("device-ipod-nano"), { {}} }, + { QStringLiteral("device-ipod"), { {}} }, + { QStringLiteral("device-phone"), { {}} }, + { QStringLiteral("device"), { {QStringLiteral("drive-removable-media-usb-pendrive")}} }, + { QStringLiteral("device-usb-drive"), { {}} }, + { QStringLiteral("device-usb-flash"), { {}} }, + { QStringLiteral("dialog-error"), { {}} }, + { QStringLiteral("dialog-information"), { {}} }, + { QStringLiteral("dialog-ok-apply"), { {}} }, + { QStringLiteral("dialog-password"), { {}} }, + { QStringLiteral("dialog-warning"), { {}} }, + { QStringLiteral("document-download"), { {QStringLiteral("download")}} }, + { QStringLiteral("document-new"), { {}} }, + { QStringLiteral("document-open-folder"), { {}} }, + { QStringLiteral("document-open"), { {}} }, + { QStringLiteral("document-save"), { {}} }, + { QStringLiteral("document-search"), { {}} }, + { QStringLiteral("document-open-remote"), { {}} }, + { QStringLiteral("download"), { {QStringLiteral("applications-internet"), QStringLiteral("network-workgroup")}} }, + { QStringLiteral("edit-clear-list"), { {QStringLiteral("edit-clear-list"), QStringLiteral("edit-clear-all")}} }, + { QStringLiteral("edit-clear-locationbar-ltr"), { {QStringLiteral("edit-clear-locationbar-ltr")}} }, + { QStringLiteral("edit-copy"), { {}} }, + { QStringLiteral("edit-delete"), { {}} }, + { QStringLiteral("edit-find"), { {}} }, + { QStringLiteral("edit-redo"), { {}} }, + { QStringLiteral("edit-rename"), { {}} }, + { QStringLiteral("edit-undo"), { {}} }, + { QStringLiteral("electrocompaniet"), { {}} }, + { QStringLiteral("equalizer"), { {QStringLiteral("view-media-equalizer")}} }, + { QStringLiteral("folder-new"), { {}} }, + { QStringLiteral("folder"), { {}} }, + { QStringLiteral("folder-sound"), { {QStringLiteral("folder-music")}} }, + { QStringLiteral("footsteps"), { {QStringLiteral("go-jump")}} }, + { QStringLiteral("go-down"), { {}} }, + { QStringLiteral("go-home"), { {}} }, + { QStringLiteral("go-jump"), { {}} }, + { QStringLiteral("go-next"), { {}} }, + { QStringLiteral("go-previous"), { {}} }, + { QStringLiteral("go-up"), { {}} }, + { QStringLiteral("gstreamer"), { {QStringLiteral("phonon-gstreamer")}} }, + { QStringLiteral("headset"), { {QStringLiteral("audio-headset")}} }, + { QStringLiteral("help-hint"), { {}} }, + { QStringLiteral("intel"), { {}} }, + { QStringLiteral("jack"), { {QStringLiteral("audio-input-line")}} }, + { QStringLiteral("keyboard"), { {QStringLiteral("input-keyboard")}} }, + { QStringLiteral("list-add"), { {}} }, + { QStringLiteral("list-remove"), { {}} }, + { QStringLiteral("love"), { {QStringLiteral("heart"), QStringLiteral("emblem-favorite")}} }, + { QStringLiteral("mcintosh-player"), { {}} }, + { QStringLiteral("mcintosh"), { {}} }, + { QStringLiteral("mcintosh-text"), { {}} }, + { QStringLiteral("media-eject"), { {}} }, + { QStringLiteral("media-playback-pause"), { {QStringLiteral("media-pause")}} }, + { QStringLiteral("media-playlist-repeat"), { {}} }, + { QStringLiteral("media-playlist-shuffle"), { {QLatin1String("")}} }, + { QStringLiteral("media-playback-start"), { {QStringLiteral("media-play"), QStringLiteral("media-playback-playing")}} }, + { QStringLiteral("media-seek-backward"), { {}} }, + { QStringLiteral("media-seek-forward"), { {}} }, + { QStringLiteral("media-skip-backward"), { {}} }, + { QStringLiteral("media-skip-forward"), { {}} }, + { QStringLiteral("media-playback-stop"), { {QStringLiteral("media-stop")}} }, + { QStringLiteral("moodbar"), { {QStringLiteral("preferences-desktop-icons")}} }, + { QStringLiteral("nvidia"), { {}} }, + { QStringLiteral("pulseaudio"), { {}} }, + { QStringLiteral("realtek"), { {}} }, + { QStringLiteral("scrobble-disabled"), { {}} }, + { QStringLiteral("scrobble"), { {QStringLiteral("love")}} }, + { QStringLiteral("search"), { {}} }, + { QStringLiteral("soundcard"), { {QStringLiteral("audiocard"), QStringLiteral("audio-card")}} }, + { QStringLiteral("speaker"), { {}} }, + { QStringLiteral("star-grey"), { {}} }, + { QStringLiteral("star"), { {}} }, + { QStringLiteral("strawberry"), { {}} }, + { QStringLiteral("subsonic"), { {}} }, + { QStringLiteral("tidal"), { {}} }, + { QStringLiteral("tools-wizard"), { {}} }, + { QStringLiteral("view-choose"), { {}} }, + { QStringLiteral("view-fullscreen"), { {}} }, + { QStringLiteral("view-media-lyrics"), { {}} }, + { QStringLiteral("view-media-playlist"), { {}} }, + { QStringLiteral("view-media-visualization"), { {QStringLiteral("preferences-desktop-theme")}} }, + { QStringLiteral("view-refresh"), { {}} }, + { QStringLiteral("library-music"), { {QStringLiteral("vinyl")}} }, + { QStringLiteral("vlc"), { {}} }, + { QStringLiteral("zoom-in"), { {}} }, + { QStringLiteral("zoom-out"), { {}, 0, 0 } } }; diff --git a/src/core/mac_startup.mm b/src/core/mac_startup.mm index 11091bc855..b70c9ac11c 100644 --- a/src/core/mac_startup.mm +++ b/src/core/mac_startup.mm @@ -60,7 +60,6 @@ #include #include #include -#include #include diff --git a/src/core/mainwindow.cpp b/src/core/mainwindow.cpp index 49d9e58dc4..e04bd9c581 100644 --- a/src/core/mainwindow.cpp +++ b/src/core/mainwindow.cpp @@ -104,6 +104,7 @@ # include "qtsystemtrayicon.h" #endif #include "networkaccessmanager.h" +#include "settings.h" #include "utilities/envutils.h" #include "utilities/filemanagerutils.h" #include "utilities/timeconstants.h" @@ -301,13 +302,13 @@ MainWindow::MainWindow(Application *app, SharedPtr tray_icon, OS }), smartplaylists_view_(new SmartPlaylistsViewContainer(app, this)), #ifdef HAVE_SUBSONIC - subsonic_view_(new InternetSongsView(app_, app->internet_services()->ServiceBySource(Song::Source::Subsonic), SubsonicSettingsPage::kSettingsGroup, SettingsDialog::Page::Subsonic, this)), + subsonic_view_(new InternetSongsView(app_, app->internet_services()->ServiceBySource(Song::Source::Subsonic), QString::fromUtf8(SubsonicSettingsPage::kSettingsGroup), SettingsDialog::Page::Subsonic, this)), #endif #ifdef HAVE_TIDAL - tidal_view_(new InternetTabsView(app_, app->internet_services()->ServiceBySource(Song::Source::Tidal), TidalSettingsPage::kSettingsGroup, SettingsDialog::Page::Tidal, this)), + tidal_view_(new InternetTabsView(app_, app->internet_services()->ServiceBySource(Song::Source::Tidal), QString::fromUtf8(TidalSettingsPage::kSettingsGroup), SettingsDialog::Page::Tidal, this)), #endif #ifdef HAVE_QOBUZ - qobuz_view_(new InternetTabsView(app_, app->internet_services()->ServiceBySource(Song::Source::Qobuz), QobuzSettingsPage::kSettingsGroup, SettingsDialog::Page::Qobuz, this)), + qobuz_view_(new InternetTabsView(app_, app->internet_services()->ServiceBySource(Song::Source::Qobuz), QString::fromUtf8(QobuzSettingsPage::kSettingsGroup), SettingsDialog::Page::Qobuz, this)), #endif radio_view_(new RadioViewContainer(this)), lastfm_import_dialog_(new LastFMImportDialog(app_->lastfm_import(), this)), @@ -398,7 +399,7 @@ MainWindow::MainWindow(Application *app, SharedPtr tray_icon, OS // Add the playing widget to the fancy tab widget ui_->tabs->addBottomWidget(ui_->widget_playing); //ui_->tabs->SetBackgroundPixmap(QPixmap(":/pictures/strawberry-background.png")); - ui_->tabs->Load(kSettingsGroup); + ui_->tabs->Load(QString::fromUtf8(kSettingsGroup)); track_position_timer_->setInterval(kTrackPositionUpdateTimeMs); QObject::connect(track_position_timer_, &QTimer::timeout, this, &MainWindow::UpdateTrackPosition); @@ -448,7 +449,7 @@ MainWindow::MainWindow(Application *app, SharedPtr tray_icon, OS // Help menu ui_->action_about_strawberry->setIcon(IconLoader::Load(QStringLiteral("strawberry"))); - ui_->action_about_qt->setIcon(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png")); + ui_->action_about_qt->setIcon(QIcon(QStringLiteral(":/qt-project.org/qmessagebox/images/qtlogo-64.png"))); // Music menu @@ -690,7 +691,7 @@ MainWindow::MainWindow(Application *app, SharedPtr tray_icon, OS QAction *collection_config_action = new QAction(IconLoader::Load(QStringLiteral("configure")), tr("Configure collection..."), this); QObject::connect(collection_config_action, &QAction::triggered, this, &MainWindow::ShowCollectionConfig); - collection_view_->filter_widget()->SetSettingsGroup(CollectionSettingsPage::kSettingsGroup); + collection_view_->filter_widget()->SetSettingsGroup(QLatin1String(CollectionSettingsPage::kSettingsGroup)); collection_view_->filter_widget()->Init(app_->collection()->model()); QAction *separator = new QAction(this); @@ -952,7 +953,7 @@ MainWindow::MainWindow(Application *app, SharedPtr tray_icon, OS #else BehaviourSettingsPage::StartupBehaviour startupbehaviour = BehaviourSettingsPage::StartupBehaviour::Remember; { - QSettings s; + Settings s; s.beginGroup(BehaviourSettingsPage::kSettingsGroup); startupbehaviour = static_cast(s.value("startupbehaviour", static_cast(BehaviourSettingsPage::StartupBehaviour::Remember)).toInt()); s.endGroup(); @@ -1024,18 +1025,18 @@ MainWindow::MainWindow(Application *app, SharedPtr tray_icon, OS } #ifdef HAVE_QTSPARKLE - QUrl sparkle_url(QTSPARKLE_URL); + QUrl sparkle_url(QLatin1String(QTSPARKLE_URL)); if (!sparkle_url.isEmpty()) { qLog(Debug) << "Creating Qt Sparkle updater"; qtsparkle::Updater *updater = new qtsparkle::Updater(sparkle_url, this); - updater->SetVersion(STRAWBERRY_VERSION_PACKAGE); + updater->SetVersion(QStringLiteral(STRAWBERRY_VERSION_PACKAGE)); QObject::connect(check_updates, &QAction::triggered, updater, &qtsparkle::Updater::CheckNow); } #endif #ifdef Q_OS_LINUX if (!Utilities::GetEnv(QStringLiteral("SNAP")).isEmpty() && !Utilities::GetEnv(QStringLiteral("SNAP_NAME")).isEmpty()) { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); const bool ignore_snap = s.value("ignore_snap", false).toBool(); s.endGroup(); @@ -1049,30 +1050,30 @@ MainWindow::MainWindow(Application *app, SharedPtr tray_icon, OS #if defined(Q_OS_MACOS) if (Utilities::ProcessTranslated()) { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); const bool ignore_rosetta = s.value("ignore_rosetta", false).toBool(); s.endGroup(); if (!ignore_rosetta) { MessageDialog *rosetta_message = new MessageDialog(this); - rosetta_message->set_settings_group(kSettingsGroup); - rosetta_message->set_do_not_show_message_again("ignore_rosetta"); + rosetta_message->set_settings_group(QLatin1String(kSettingsGroup)); + rosetta_message->set_do_not_show_message_again(QStringLiteral("ignore_rosetta")); rosetta_message->setAttribute(Qt::WA_DeleteOnClose); - rosetta_message->ShowMessage(tr("Strawberry running under Rosetta"), tr("You are running Strawberry under Rosetta. Running Strawberry under Rosetta is unsupported and known to have issues. You should download Strawberry for the correct CPU architecture from %1").arg("downloads.strawberrymusicplayer.org"), IconLoader::Load("dialog-warning")); + rosetta_message->ShowMessage(tr("Strawberry running under Rosetta"), tr("You are running Strawberry under Rosetta. Running Strawberry under Rosetta is unsupported and known to have issues. You should download Strawberry for the correct CPU architecture from %1").arg(QStringLiteral("downloads.strawberrymusicplayer.org")), IconLoader::Load(QStringLiteral("dialog-warning"))); } } #endif { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); - const QString do_not_show_sponsor_message_key = QStringLiteral("do_not_show_sponsor_message"); + constexpr char do_not_show_sponsor_message_key[] = "do_not_show_sponsor_message"; const bool do_not_show_sponsor_message = s.value(do_not_show_sponsor_message_key, false).toBool(); s.endGroup(); if (!do_not_show_sponsor_message) { MessageDialog *sponsor_message = new MessageDialog(this); - sponsor_message->set_settings_group(kSettingsGroup); - sponsor_message->set_do_not_show_message_again(do_not_show_sponsor_message_key); + sponsor_message->set_settings_group(QLatin1String(kSettingsGroup)); + sponsor_message->set_do_not_show_message_again(QLatin1String(do_not_show_sponsor_message_key)); sponsor_message->setAttribute(Qt::WA_DeleteOnClose); sponsor_message->ShowMessage(tr("Sponsoring Strawberry"), tr("Strawberry is free and open source software. If you like Strawberry, please consider sponsoring the project. For more information about sponsorship see our website %1").arg(QStringLiteral("www.strawberrymusicplayer.org")), IconLoader::Load(QStringLiteral("dialog-information"))); } @@ -1089,7 +1090,7 @@ MainWindow::~MainWindow() { void MainWindow::ReloadSettings() { - QSettings s; + Settings s; #ifdef Q_OS_MACOS constexpr bool keeprunning_available = true; @@ -1252,7 +1253,7 @@ void MainWindow::SaveSettings() { SaveGeometry(); SavePlaybackStatus(); app_->player()->SaveVolume(); - ui_->tabs->SaveSettings(kSettingsGroup); + ui_->tabs->SaveSettings(QLatin1String(kSettingsGroup)); ui_->playlist->view()->SaveSettings(); app_->scrobbler()->WriteCache(); @@ -1507,7 +1508,7 @@ void MainWindow::SaveGeometry() { void MainWindow::SavePlaybackStatus() { - QSettings s; + Settings s; s.beginGroup(Player::kSettingsGroup); s.setValue("playback_state", static_cast(app_->player()->GetState())); @@ -1526,7 +1527,7 @@ void MainWindow::SavePlaybackStatus() { void MainWindow::LoadPlaybackStatus() { - QSettings s; + Settings s; s.beginGroup(BehaviourSettingsPage::kSettingsGroup); const bool resume_playback = s.value("resumeplayback", false).toBool(); @@ -1550,7 +1551,7 @@ void MainWindow::ResumePlayback() { qLog(Debug) << "Resuming playback"; - QSettings s; + Settings s; s.beginGroup(Player::kSettingsGroup); const EngineBase::State playback_state = static_cast(s.value("playback_state", static_cast(EngineBase::State::Empty)).toInt()); int playback_playlist = s.value("playback_playlist", -1).toInt(); @@ -2054,7 +2055,7 @@ void MainWindow::PlaylistRightClick(const QPoint global_pos, const QModelIndex & QString column_name = Playlist::column_name(column); QString column_value = app_->playlist_manager()->current()->data(source_index).toString(); - if (column_value.length() > 25) column_value = column_value.left(25) + "..."; + if (column_value.length() > 25) column_value = column_value.left(25) + QStringLiteral("..."); ui_->action_selection_set_value->setText(tr("Set %1 to \"%2\"...").arg(column_name.toLower(), column_value)); ui_->action_edit_value->setText(tr("Edit tag \"%1\"...").arg(column_name)); @@ -2297,7 +2298,7 @@ void MainWindow::AddFile() { PlaylistParser parser(app_->collection_backend()); // Show dialog - QStringList file_names = QFileDialog::getOpenFileNames(this, tr("Add file"), directory, QStringLiteral("%1 (%2);;%3;;%4").arg(tr("Music"), FileView::kFileFilter, parser.filters(PlaylistParser::Type::Load), tr(kAllFilesFilterSpec))); + QStringList file_names = QFileDialog::getOpenFileNames(this, tr("Add file"), directory, QStringLiteral("%1 (%2);;%3;;%4").arg(tr("Music"), QLatin1String(FileView::kFileFilter), parser.filters(PlaylistParser::Type::Load), tr(kAllFilesFilterSpec))); if (file_names.isEmpty()) return; @@ -2341,7 +2342,7 @@ void MainWindow::AddCDTracks() { MimeData *mimedata = new MimeData; // We are putting empty data, but we specify cdda mimetype to indicate that we want to load audio cd tracks mimedata->open_in_new_playlist_ = true; - mimedata->setData(Playlist::kCddaMimeType, QByteArray()); + mimedata->setData(QString::fromUtf8(Playlist::kCddaMimeType), QByteArray()); AddToPlaylist(mimedata); } @@ -2375,7 +2376,7 @@ void MainWindow::ShowInCollection() { } QString search; if (!songs.isEmpty()) { - search = "artist:" + songs.first().artist() + " album:" + songs.first().album(); + search = QStringLiteral("artist:") + songs.first().artist() + QStringLiteral(" album:") + songs.first().album(); } collection_view_->filter_widget()->ShowInCollection(search); @@ -2468,9 +2469,9 @@ void MainWindow::CommandlineOptionsReceived(const CommandlineOptions &options) { break; case CommandlineOptions::PlayerAction::ResizeWindow:{ - if (options.window_size().contains('x') && options.window_size().length() >= 4) { - QString str_w = options.window_size().left(options.window_size().indexOf('x')); - QString str_h = options.window_size().right(options.window_size().length() - options.window_size().indexOf('x') - 1); + if (options.window_size().contains(QLatin1Char('x')) && options.window_size().length() >= 4) { + QString str_w = options.window_size().left(options.window_size().indexOf(QLatin1Char('x'))); + QString str_h = options.window_size().right(options.window_size().length() - options.window_size().indexOf(QLatin1Char('x')) - 1); bool w_ok = false; bool h_ok = false; int w = str_w.toInt(&w_ok); @@ -2509,7 +2510,7 @@ void MainWindow::CommandlineOptionsReceived(const CommandlineOptions &options) { #ifdef HAVE_TIDAL for (const QUrl &url : options.urls()) { - if (url.scheme() == "tidal" && url.host() == "login") { + if (url.scheme() == QStringLiteral("tidal") && url.host() == QStringLiteral("login")) { emit AuthorizationUrlReceived(url); return; } @@ -2587,7 +2588,7 @@ bool MainWindow::LoadUrl(const QString &url) { return true; } #ifdef HAVE_TIDAL - else if (url.startsWith(QLatin1String("tidal://login"))) { + else if (url.startsWith(QStringLiteral("tidal://login"))) { emit AuthorizationUrlReceived(QUrl(url)); return true; } @@ -2951,11 +2952,11 @@ void MainWindow::CheckFullRescanRevisions() { // if we have any... if (!reasons.isEmpty()) { - QString message = tr("The version of Strawberry you've just updated to requires a full collection rescan because of the new features listed below:") + "

    "; + QString message = tr("The version of Strawberry you've just updated to requires a full collection rescan because of the new features listed below:") + QStringLiteral("
      "); for (const QString &reason : reasons) { - message += ("
    • " + reason + "
    • "); + message += QStringLiteral("
    • ") + reason + QStringLiteral("
    • "); } - message += "
    " + tr("Would you like to run a full rescan right now?"); + message += QStringLiteral("
") + tr("Would you like to run a full rescan right now?"); if (QMessageBox::question(this, tr("Collection rescan notice"), message, QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { app_->collection()->FullScan(); } @@ -3262,7 +3263,7 @@ void MainWindow::PlaylistDelete() { app_->player()->Next(); } - SharedPtr storage = make_shared(Song::Source::LocalFile, "/"); + SharedPtr storage = make_shared(Song::Source::LocalFile, QStringLiteral("/")); DeleteFiles *delete_files = new DeleteFiles(app_->task_manager(), storage, true); QObject::connect(delete_files, &DeleteFiles::Finished, this, &MainWindow::DeleteFilesFinished); delete_files->Start(selected_songs); diff --git a/src/core/mainwindow.h b/src/core/mainwindow.h index 1f033f2dba..cc74565d97 100644 --- a/src/core/mainwindow.h +++ b/src/core/mainwindow.h @@ -52,6 +52,7 @@ #include "platforminterface.h" #include "song.h" #include "tagreaderclient.h" +#include "settings.h" #include "engine/enginebase.h" #include "osd/osdbase.h" #include "playlist/playlist.h" @@ -379,7 +380,7 @@ class MainWindow : public QMainWindow, public PlatformInterface { QTimer *track_position_timer_; QTimer *track_slider_timer_; - QSettings settings_; + Settings settings_; bool keep_running_; bool playing_widget_; diff --git a/src/core/mpris2.cpp b/src/core/mpris2.cpp index 13a0ffb856..c30b839386 100644 --- a/src/core/mpris2.cpp +++ b/src/core/mpris2.cpp @@ -94,9 +94,9 @@ const QDBusArgument &operator>>(const QDBusArgument &arg, MaybePlaylist &playlis namespace mpris { -const char *Mpris2::kMprisObjectPath = "/org/mpris/MediaPlayer2"; -const char *Mpris2::kServiceName = "org.mpris.MediaPlayer2.strawberry"; -const char *Mpris2::kFreedesktopPath = "org.freedesktop.DBus.Properties"; +constexpr char kMprisObjectPath[] = "/org/mpris/MediaPlayer2"; +constexpr char kServiceName[] = "org.mpris.MediaPlayer2.strawberry"; +constexpr char kFreedesktopPath[] = "org.freedesktop.DBus.Properties"; Mpris2::Mpris2(Application *app, QObject *parent) : QObject(parent), @@ -108,13 +108,13 @@ Mpris2::Mpris2(Application *app, QObject *parent) new Mpris2Player(this); new Mpris2Playlists(this); - if (!QDBusConnection::sessionBus().registerService(kServiceName)) { - qLog(Warning) << "Failed to register" << QString(kServiceName) << "on the session bus"; + if (!QDBusConnection::sessionBus().registerService(QLatin1String(kServiceName))) { + qLog(Warning) << "Failed to register" << kServiceName << "on the session bus"; return; } - if (!QDBusConnection::sessionBus().registerObject(kMprisObjectPath, this)) { - qLog(Warning) << "Failed to register" << QString(kMprisObjectPath) << "on the session bus"; + if (!QDBusConnection::sessionBus().registerObject(QLatin1String(kMprisObjectPath), this)) { + qLog(Warning) << "Failed to register" << kMprisObjectPath << "on the session bus"; return; } @@ -131,13 +131,13 @@ Mpris2::Mpris2(Application *app, QObject *parent) app_name_[0] = app_name_[0].toUpper(); - QStringList data_dirs = QString(qgetenv("XDG_DATA_DIRS")).split(QStringLiteral(":")); + QStringList data_dirs = QString::fromUtf8(qgetenv("XDG_DATA_DIRS")).split(QLatin1Char(':')); - if (!data_dirs.contains("/usr/local/share")) { + if (!data_dirs.contains(QStringLiteral("/usr/local/share"))) { data_dirs.append(QStringLiteral("/usr/local/share")); } - if (!data_dirs.contains("/usr/share")) { + if (!data_dirs.contains(QStringLiteral("/usr/share"))) { data_dirs.append(QStringLiteral("/usr/share")); } @@ -150,7 +150,7 @@ Mpris2::Mpris2(Application *app, QObject *parent) } if (desktopfilepath_.isEmpty()) { - desktopfilepath_ = QGuiApplication::desktopFileName() + ".desktop"; + desktopfilepath_ = QGuiApplication::desktopFileName() + QStringLiteral(".desktop"); } } @@ -195,7 +195,7 @@ void Mpris2::EmitNotification(const QString &name, const QVariant &value) { void Mpris2::EmitNotification(const QString &name, const QVariant &value, const QString &mprisEntity) { - QDBusMessage msg = QDBusMessage::createSignal(kMprisObjectPath, kFreedesktopPath, QStringLiteral("PropertiesChanged")); + QDBusMessage msg = QDBusMessage::createSignal(QLatin1String(kMprisObjectPath), QLatin1String(kFreedesktopPath), QStringLiteral("PropertiesChanged")); QVariantMap map; map.insert(name, value); QVariantList args = QVariantList() << mprisEntity << map << QStringList(); @@ -207,18 +207,18 @@ void Mpris2::EmitNotification(const QString &name, const QVariant &value, const void Mpris2::EmitNotification(const QString &name) { QVariant value; - if (name == "PlaybackStatus") value = PlaybackStatus(); - else if (name == "LoopStatus") value = LoopStatus(); - else if (name == "Shuffle") value = Shuffle(); - else if (name == "Metadata") value = Metadata(); - else if (name == "Rating") value = Rating(); - else if (name == "Volume") value = Volume(); - else if (name == "Position") value = Position(); - else if (name == "CanPlay") value = CanPlay(); - else if (name == "CanPause") value = CanPause(); - else if (name == "CanSeek") value = CanSeek(); - else if (name == "CanGoNext") value = CanGoNext(); - else if (name == "CanGoPrevious") value = CanGoPrevious(); + if (name == QStringLiteral("PlaybackStatus")) value = PlaybackStatus(); + else if (name == QStringLiteral("LoopStatus")) value = LoopStatus(); + else if (name == QStringLiteral("Shuffle")) value = Shuffle(); + else if (name == QStringLiteral("Metadata")) value = Metadata(); + else if (name == QStringLiteral("Rating")) value = Rating(); + else if (name == QStringLiteral("Volume")) value = Volume(); + else if (name == QStringLiteral("Position")) value = Position(); + else if (name == QStringLiteral("CanPlay")) value = CanPlay(); + else if (name == QStringLiteral("CanPause")) value = CanPause(); + else if (name == QStringLiteral("CanSeek")) value = CanSeek(); + else if (name == QStringLiteral("CanGoNext")) value = CanGoNext(); + else if (name == QStringLiteral("CanGoPrevious")) value = CanGoPrevious(); if (value.isValid()) EmitNotification(name, value); @@ -240,7 +240,7 @@ QString Mpris2::DesktopEntryAbsolutePath() const { } -QString Mpris2::DesktopEntry() const { return QGuiApplication::desktopFileName() + ".desktop"; } +QString Mpris2::DesktopEntry() const { return QGuiApplication::desktopFileName() + QStringLiteral(".desktop"); } QStringList Mpris2::SupportedUriSchemes() const { @@ -325,13 +325,13 @@ void Mpris2::SetLoopStatus(const QString &value) { PlaylistSequence::RepeatMode mode = PlaylistSequence::RepeatMode::Off; - if (value == "None") { + if (value == QStringLiteral("None")) { mode = PlaylistSequence::RepeatMode::Off; } - else if (value == "Track") { + else if (value == QStringLiteral("Track")) { mode = PlaylistSequence::RepeatMode::Track; } - else if (value == "Playlist") { + else if (value == QStringLiteral("Playlist")) { mode = PlaylistSequence::RepeatMode::Playlist; } @@ -460,7 +460,7 @@ bool Mpris2::CanPlay() const { // This one's a bit different than MPRIS 1 - we want this to be true even when the song is already paused or stopped. bool Mpris2::CanPause() const { - return (app_->player()->GetCurrentItem() && app_->player()->GetState() == EngineBase::State::Playing && !(app_->player()->GetCurrentItem()->options() & PlaylistItem::Option::PauseDisabled)) || PlaybackStatus() == "Paused" || PlaybackStatus() == "Stopped"; + return (app_->player()->GetCurrentItem() && app_->player()->GetState() == EngineBase::State::Playing && !(app_->player()->GetCurrentItem()->options() & PlaylistItem::Option::PauseDisabled)) || PlaybackStatus() == QStringLiteral("Paused") || PlaybackStatus() == QStringLiteral("Stopped"); } bool Mpris2::CanSeek() const { return CanSeek(app_->player()->GetState()); } @@ -594,7 +594,7 @@ MaybePlaylist Mpris2::ActivePlaylist() const { void Mpris2::ActivatePlaylist(const QDBusObjectPath &playlist_id) { - QStringList split_path = playlist_id.path().split('/'); + QStringList split_path = playlist_id.path().split(QLatin1Char('/')); qLog(Debug) << Q_FUNC_INFO << playlist_id.path() << split_path; if (split_path.isEmpty()) { return; @@ -648,7 +648,7 @@ void Mpris2::PlaylistChangedSlot(Playlist *playlist) { void Mpris2::PlaylistCollectionChanged(Playlist *playlist) { Q_UNUSED(playlist); - EmitNotification(QStringLiteral("PlaylistCount"), "", QStringLiteral("org.mpris.MediaPlayer2.Playlists")); + EmitNotification(QStringLiteral("PlaylistCount"), QLatin1String(""), QStringLiteral("org.mpris.MediaPlayer2.Playlists")); } } // namespace mpris diff --git a/src/core/mpris2.h b/src/core/mpris2.h index b2a7b1e7c0..b3ec2544c8 100644 --- a/src/core/mpris2.h +++ b/src/core/mpris2.h @@ -232,10 +232,6 @@ class Mpris2 : public QObject { QString DesktopEntryAbsolutePath() const; private: - static const char *kMprisObjectPath; - static const char *kServiceName; - static const char *kFreedesktopPath; - Application *app_; QString app_name_; diff --git a/src/core/networkaccessmanager.cpp b/src/core/networkaccessmanager.cpp index 0a5d260e5a..916bb7ff9a 100644 --- a/src/core/networkaccessmanager.cpp +++ b/src/core/networkaccessmanager.cpp @@ -57,7 +57,7 @@ QNetworkReply *NetworkAccessManager::createRequest(Operation op, const QNetworkR new_request.setHeader(QNetworkRequest::UserAgentHeader, user_agent); if (op == QNetworkAccessManager::PostOperation && !new_request.header(QNetworkRequest::ContentTypeHeader).isValid()) { - new_request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + new_request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); } // Prefer the cache unless the caller has changed the setting already diff --git a/src/core/networkproxyfactory.cpp b/src/core/networkproxyfactory.cpp index 479329dba5..0fbbf44389 100644 --- a/src/core/networkproxyfactory.cpp +++ b/src/core/networkproxyfactory.cpp @@ -29,6 +29,7 @@ #include #include "core/logging.h" +#include "core/settings.h" #include "networkproxyfactory.h" NetworkProxyFactory *NetworkProxyFactory::sInstance = nullptr; @@ -78,7 +79,7 @@ void NetworkProxyFactory::ReloadSettings() { QMutexLocker l(&mutex_); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); mode_ = static_cast(s.value("mode", static_cast(Mode::System)).toInt()); diff --git a/src/core/player.cpp b/src/core/player.cpp index 0dc1fc99dd..b9e06af55e 100644 --- a/src/core/player.cpp +++ b/src/core/player.cpp @@ -36,6 +36,7 @@ #include #include "core/logging.h" +#include "core/settings.h" #include "utilities/timeconstants.h" #include "scoped_ptr.h" @@ -94,7 +95,7 @@ Player::Player(Application *app, QObject *parent) seek_step_sec_(10), play_offset_nanosec_(0) { - QSettings s; + Settings s; s.beginGroup(BackendSettingsPage::kSettingsGroup); EngineBase::Type enginetype = EngineBase::TypeFromName(s.value("engine", EngineBase::Name(EngineBase::Type::GStreamer)).toString().toLower()); s.endGroup(); @@ -139,7 +140,7 @@ EngineBase::Type Player::CreateEngine(EngineBase::Type enginetype) { } if (use_enginetype != enginetype) { // Engine was set to something else. Reset output and device. - QSettings s; + Settings s; s.beginGroup(BackendSettingsPage::kSettingsGroup); s.setValue("engine", EngineBase::Name(use_enginetype)); s.setValue("output", engine_->DefaultOutput()); @@ -159,7 +160,7 @@ EngineBase::Type Player::CreateEngine(EngineBase::Type enginetype) { void Player::Init() { - QSettings s; + Settings s; if (!engine_) { s.beginGroup(BackendSettingsPage::kSettingsGroup); @@ -203,7 +204,7 @@ void Player::Init() { void Player::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(PlaylistSettingsPage::kSettingsGroup); continue_on_error_ = s.value("continue_on_error", false).toBool(); @@ -221,7 +222,7 @@ void Player::ReloadSettings() { void Player::LoadVolume() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); const uint volume = s.value("volume", 100).toInt(); s.endGroup(); @@ -232,7 +233,7 @@ void Player::LoadVolume() { void Player::SaveVolume() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("volume", volume_); s.endGroup(); diff --git a/src/core/settings.cpp b/src/core/settings.cpp new file mode 100644 index 0000000000..94c6d3f8de --- /dev/null +++ b/src/core/settings.cpp @@ -0,0 +1,120 @@ +/* + * Strawberry Music Player + * Copyright 2024, Jonas Kvinge + * + * Strawberry is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Strawberry is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Strawberry. If not, see . + * + */ + +#include +#include +#include + +#include "settings.h" + +Settings::Settings(QObject *parent) + : QSettings(parent) {} + +Settings::Settings(const QString &filename, const Format format, QObject *parent) + : QSettings(filename, format, parent) {} + +// Cmpatibility with Qt 5 + +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + +void Settings::beginGroup(const char *prefix) { + + QSettings::beginGroup(QLatin1String(prefix)); + +} + +void Settings::beginGroup(const QString &prefix) { + + QSettings::beginGroup(prefix); + +} + +bool Settings::contains(const char *key) const { + + return QSettings::contains(QLatin1String(key)); + +} + +bool Settings::contains(const QString &key) const { + + return QSettings::contains(key); + +} + +QVariant Settings::value(const char *key, const QVariant &default_value) const { + + return QSettings::value(QLatin1String(key), default_value); + +} + +QVariant Settings::value(const QString &key, const QVariant &default_value) const { + + return QSettings::value(key, default_value); + +} + +void Settings::setValue(const char *key, const QVariant &value) { + + QSettings::setValue(QLatin1String(key), value); + +} + +void Settings::setValue(const QString &key, const QVariant &value) { + + QSettings::setValue(key, value); + +} + +int Settings::beginReadArray(const char *prefix) { + + return QSettings::beginReadArray(QLatin1String(prefix)); + +} + +int Settings::beginReadArray(const QString &prefix) { + + return QSettings::beginReadArray(prefix); + +} + +void Settings::beginWriteArray(const char *prefix, int size) { + + QSettings::beginWriteArray(QLatin1String(prefix), size); + +} + +void Settings::beginWriteArray(const QString &prefix, int size) { + + QSettings::beginWriteArray(prefix, size); + +} + +void Settings::remove(const char *key) { + + QSettings::remove(QLatin1String(key)); + +} + +void Settings::remove(const QString &key) { + + QSettings::remove(key); + +} + +#endif diff --git a/src/core/settings.h b/src/core/settings.h new file mode 100644 index 0000000000..7060e47865 --- /dev/null +++ b/src/core/settings.h @@ -0,0 +1,51 @@ +/* + * Strawberry Music Player + * Copyright 2024, Jonas Kvinge + * + * Strawberry is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Strawberry is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Strawberry. If not, see . + * + */ + +#ifndef SETTINGS_H +#define SETTINGS_H + +#include +#include +#include + +class Settings : public QSettings { + Q_OBJECT + + public: + explicit Settings(QObject *parent = nullptr); + explicit Settings(const QString &filename, const Format format, QObject *parent = nullptr); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // Compatibility with Qt 5 + void beginGroup(const char *prefix); + void beginGroup(const QString &prefix); + bool contains(const char *key) const; + bool contains(const QString &key) const; + QVariant value(const char *key, const QVariant &default_value = QVariant()) const; + QVariant value(const QString &key, const QVariant &default_value = QVariant()) const; + void setValue(const char *key, const QVariant &value); + void setValue(const QString &key, const QVariant &value); + int beginReadArray(const char *prefix); + int beginReadArray(const QString &prefix); + void beginWriteArray(const char *prefix, int size = -1); + void beginWriteArray(const QString &prefix, int size = -1); + void remove(const char *key); + void remove(const QString &key); +#endif +}; + +#endif // SETTINGS_H diff --git a/src/core/settingsprovider.cpp b/src/core/settingsprovider.cpp index 7c6e887b04..5df62e9982 100644 --- a/src/core/settingsprovider.cpp +++ b/src/core/settingsprovider.cpp @@ -30,7 +30,7 @@ DefaultSettingsProvider::DefaultSettingsProvider() = default; void DefaultSettingsProvider::set_group(const char *group) { while (!backend_.group().isEmpty()) backend_.endGroup(); - backend_.beginGroup(group); + backend_.beginGroup(QLatin1String(group)); } QVariant DefaultSettingsProvider::value(const QString &key, const QVariant &default_value) const { diff --git a/src/core/song.cpp b/src/core/song.cpp index 5c5f26db80..4909e31673 100644 --- a/src/core/song.cpp +++ b/src/core/song.cpp @@ -659,7 +659,7 @@ QString Song::sortable(const QString &v) { for (const auto &i : kArticles) { if (copy.startsWith(i)) { qint64 ilen = i.length(); - return copy.right(copy.length() - ilen) + ", " + copy.left(ilen - 1); + return copy.right(copy.length() - ilen) + QStringLiteral(", ") + copy.left(ilen - 1); } } @@ -668,7 +668,7 @@ QString Song::sortable(const QString &v) { } QString Song::JoinSpec(const QString &table) { - return Utilities::Prepend(table + ".", kColumns).join(QStringLiteral(", ")); + return Utilities::Prepend(table + QLatin1Char('.'), kColumns).join(QStringLiteral(", ")); } QString Song::PrettyTitle() const { @@ -686,7 +686,7 @@ QString Song::PrettyTitleWithArtist() const { QString title(PrettyTitle()); - if (!d->artist_.isEmpty()) title = d->artist_ + " - " + title; + if (!d->artist_.isEmpty()) title = d->artist_ + QStringLiteral(" - ") + title; return title; @@ -722,7 +722,7 @@ QString Song::TitleWithCompilationArtist() const { if (title.isEmpty()) title = d->basefilename_; - if (is_compilation() && !d->artist_.isEmpty() && !d->artist_.contains(QLatin1String("various"), Qt::CaseInsensitive)) title = d->artist_ + " - " + title; + if (is_compilation() && !d->artist_.isEmpty() && !d->artist_.contains(QLatin1String("various"), Qt::CaseInsensitive)) title = d->artist_ + QStringLiteral(" - ") + title; return title; @@ -894,11 +894,11 @@ bool Song::IsSimilar(const Song &other) const { Song::Source Song::SourceFromURL(const QUrl &url) { if (url.isLocalFile()) return Source::LocalFile; - else if (url.scheme() == "cdda") return Source::CDDA; - else if (url.scheme() == "tidal") return Source::Tidal; - else if (url.scheme() == "subsonic") return Source::Subsonic; - else if (url.scheme() == "qobuz") return Source::Qobuz; - else if (url.scheme() == "http" || url.scheme() == "https" || url.scheme() == "rtsp") { + else if (url.scheme() == QStringLiteral("cdda")) return Source::CDDA; + else if (url.scheme() == QStringLiteral("tidal")) return Source::Tidal; + else if (url.scheme() == QStringLiteral("subsonic")) return Source::Subsonic; + else if (url.scheme() == QStringLiteral("qobuz")) return Source::Qobuz; + else if (url.scheme() == QStringLiteral("http") || url.scheme() == QStringLiteral("https") || url.scheme() == QStringLiteral("rtsp")) { if (url.host().endsWith(QLatin1String("tidal.com"), Qt::CaseInsensitive)) { return Source::Tidal; } if (url.host().endsWith(QLatin1String("qobuz.com"), Qt::CaseInsensitive)) { return Source::Qobuz; } if (url.host().endsWith(QLatin1String("somafm.com"), Qt::CaseInsensitive)) { return Source::SomaFM; } @@ -1075,7 +1075,7 @@ QIcon Song::IconForFiletype(const FileType filetype) { case FileType::CDDA: return IconLoader::Load(QStringLiteral("cd")); case FileType::Stream: return IconLoader::Load(QStringLiteral("applications-internet")); case FileType::Unknown: - default: return IconLoader::Load(QStringLiteral("edit-delete")); + default: return IconLoader::Load(QStringLiteral("edit-delete")); } } @@ -1189,22 +1189,22 @@ QString Song::ImageCacheDir(const Source source) { switch (source) { case Source::Collection: - return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/collectionalbumcovers"; + return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/collectionalbumcovers"); case Source::Subsonic: - return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/subsonicalbumcovers"; + return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/subsonicalbumcovers"); case Source::Tidal: - return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/tidalalbumcovers"; + return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/tidalalbumcovers"); case Source::Qobuz: - return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/qobuzalbumcovers"; + return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/qobuzalbumcovers"); case Source::Device: - return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/devicealbumcovers"; + return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/devicealbumcovers"); case Source::LocalFile: case Source::CDDA: case Source::Stream: case Source::SomaFM: case Source::RadioParadise: case Source::Unknown: - return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/albumcovers"; + return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/albumcovers"); } return QString(); @@ -1460,8 +1460,8 @@ void Song::InitArtManual() { // If we don't have cover art, check if we have one in the cache if (d->art_manual_.isEmpty() && !effective_albumartist().isEmpty() && !effective_album().isEmpty()) { - QString filename(CoverUtils::Sha1CoverHash(effective_albumartist(), effective_album()).toHex() + ".jpg"); - QString path(ImageCacheDir(d->source_) + "/" + filename); + QString filename = QString::fromLatin1(CoverUtils::Sha1CoverHash(effective_albumartist(), effective_album()).toHex()) + QStringLiteral(".jpg"); + QString path(ImageCacheDir(d->source_) + QLatin1Char('/') + filename); if (QFile::exists(path)) { d->art_manual_ = QUrl::fromLocalFile(path); } @@ -1509,7 +1509,7 @@ void Song::InitFromItdb(Itdb_Track *track, const QString &prefix) { d->source_ = Source::Device; QString filename = QString::fromLocal8Bit(track->ipod_path); - filename.replace(':', '/'); + filename.replace(QLatin1Char(':'), QLatin1Char('/')); if (prefix.contains(QLatin1String("://"))) { set_url(QUrl(prefix + filename)); } @@ -1533,7 +1533,7 @@ void Song::InitFromItdb(Itdb_Track *track, const QString &prefix) { QString cover_path = ImageCacheDir(Source::Device); QDir dir(cover_path); if (!dir.exists()) dir.mkpath(cover_path); - QString cover_file = cover_path + "/" + CoverUtils::Sha1CoverHash(effective_albumartist(), effective_album()).toHex() + ".jpg"; + QString cover_file = cover_path + QLatin1Char('/') + QString::fromLatin1(CoverUtils::Sha1CoverHash(effective_albumartist(), effective_album()).toHex()) + QStringLiteral(".jpg"); GError *error = nullptr; if (dir.exists() && gdk_pixbuf_save(pixbuf, cover_file.toUtf8().constData(), "jpeg", &error, nullptr)) { d->art_manual_ = QUrl::fromLocalFile(cover_file); diff --git a/src/core/songloader.cpp b/src/core/songloader.cpp index 1ded5ff00f..d527a90edc 100644 --- a/src/core/songloader.cpp +++ b/src/core/songloader.cpp @@ -237,7 +237,7 @@ SongLoader::Result SongLoader::LoadLocal(const QString &filename) { QSqlDatabase db(collection_backend_->db()->Connect()); CollectionQuery query(db, collection_backend_->songs_table(), collection_backend_->fts_table()); - query.SetColumnSpec("%songs_table.ROWID, " + Song::kColumnSpec); + query.SetColumnSpec(QStringLiteral("%songs_table.ROWID, ") + Song::kColumnSpec); query.AddWhere(QStringLiteral("url"), url.toEncoded()); if (query.Exec() && query.Next()) { @@ -302,7 +302,7 @@ SongLoader::Result SongLoader::LoadLocalAsync(const QString &filename) { // It's a CUE - create virtual tracks QFile cue(matching_cue); if (cue.open(QIODevice::ReadOnly)) { - const SongList songs = cue_parser_->Load(&cue, matching_cue, QDir(filename.section('/', 0, -2))); + const SongList songs = cue_parser_->Load(&cue, matching_cue, QDir(filename.section(QLatin1Char('/'), 0, -2))); cue.close(); for (const Song &song : songs) { if (song.is_valid()) songs_ << song; @@ -542,9 +542,9 @@ void SongLoader::TypeFound(GstElement*, uint, GstCaps *caps, void *self) { if (instance->state_ != State::WaitingForType) return; // Check the mimetype - instance->mime_type_ = gst_structure_get_name(gst_caps_get_structure(caps, 0)); + instance->mime_type_ = QString::fromUtf8(gst_structure_get_name(gst_caps_get_structure(caps, 0))); qLog(Debug) << "Mime type is" << instance->mime_type_; - if (instance->mime_type_ == "text/plain" || instance->mime_type_ == "text/uri-list") { + if (instance->mime_type_ == QStringLiteral("text/plain") || instance->mime_type_ == QStringLiteral("text/uri-list")) { // Yeah it might be a playlist, let's get some data and have a better look instance->state_ = State::WaitingForMagic; return; @@ -634,12 +634,12 @@ void SongLoader::ErrorMessageReceived(GstMessage *msg) { qLog(Error) << error->message; qLog(Error) << debugs; - QString message_str = error->message; + QString message_str = QString::fromUtf8(error->message); g_error_free(error); g_free(debugs); - if (state_ == State::WaitingForType && message_str == gst_error_get_message(GST_STREAM_ERROR, GST_STREAM_ERROR_TYPE_NOT_FOUND)) { + if (state_ == State::WaitingForType && message_str == QString::fromUtf8(gst_error_get_message(GST_STREAM_ERROR, GST_STREAM_ERROR_TYPE_NOT_FOUND))) { // Don't give up - assume it's a playlist and see if one of our parsers can read it. state_ = State::WaitingForMagic; return; @@ -697,7 +697,7 @@ void SongLoader::MagicReady() { qLog(Debug) << "Magic says" << parser_->name(); - if (parser_->name() == "ASX/INI" && url_.scheme() == "http") { + if (parser_->name() == QStringLiteral("ASX/INI") && url_.scheme() == QStringLiteral("http")) { // This is actually a weird MS-WMSP stream. Changing the protocol to MMS from HTTP makes it playable. parser_ = nullptr; url_.setScheme(QStringLiteral("mms")); diff --git a/src/core/stylesheetloader.cpp b/src/core/stylesheetloader.cpp index ac452931d5..0c92d4b4d2 100644 --- a/src/core/stylesheetloader.cpp +++ b/src/core/stylesheetloader.cpp @@ -115,7 +115,7 @@ void StyleSheetLoader::UpdateStyleSheet(QWidget *widget, SharedPtrstylesheet_current_) { @@ -127,9 +127,9 @@ void StyleSheetLoader::UpdateStyleSheet(QWidget *widget, SharedPtrreplace("%palette-" + name + "-lighter", palette.color(role).lighter().name(), Qt::CaseInsensitive); - css->replace("%palette-" + name + "-darker", palette.color(role).darker().name(), Qt::CaseInsensitive); - css->replace("%palette-" + name, palette.color(role).name(), Qt::CaseInsensitive); + css->replace(QStringLiteral("%palette-") + name + QStringLiteral("-lighter"), palette.color(role).lighter().name(), Qt::CaseInsensitive); + css->replace(QStringLiteral("%palette-") + name + QStringLiteral("-darker"), palette.color(role).darker().name(), Qt::CaseInsensitive); + css->replace(QStringLiteral("%palette-") + name, palette.color(role).name(), Qt::CaseInsensitive); } diff --git a/src/core/tagreaderclient.cpp b/src/core/tagreaderclient.cpp index 62c287b5c4..18ec6c6be8 100644 --- a/src/core/tagreaderclient.cpp +++ b/src/core/tagreaderclient.cpp @@ -29,7 +29,6 @@ #include #include #include -#include #include "core/logging.h" #include "core/workerpool.h" @@ -37,7 +36,10 @@ #include "song.h" #include "tagreaderclient.h" -const char *TagReaderClient::kWorkerExecutableName = "strawberry-tagreader"; +namespace { +constexpr char kWorkerExecutableName[] = "strawberry-tagreader"; +} + TagReaderClient *TagReaderClient::sInstance = nullptr; TagReaderClient::TagReaderClient(QObject *parent) : QObject(parent), worker_pool_(new WorkerPool(this)) { @@ -45,7 +47,7 @@ TagReaderClient::TagReaderClient(QObject *parent) : QObject(parent), worker_pool sInstance = this; original_thread_ = thread(); - worker_pool_->SetExecutableName(kWorkerExecutableName); + worker_pool_->SetExecutableName(QLatin1String(kWorkerExecutableName)); QObject::connect(worker_pool_, &WorkerPool::WorkerFailedToStart, this, &TagReaderClient::WorkerFailedToStart); } diff --git a/src/core/tagreaderclient.h b/src/core/tagreaderclient.h index 1ad2dd71c3..643849aeb1 100644 --- a/src/core/tagreaderclient.h +++ b/src/core/tagreaderclient.h @@ -48,8 +48,6 @@ class TagReaderClient : public QObject { using HandlerType = AbstractMessageHandler; using ReplyType = HandlerType::ReplyType; - static const char *kWorkerExecutableName; - void Start(); void ExitAsync(); diff --git a/src/core/threadsafenetworkdiskcache.cpp b/src/core/threadsafenetworkdiskcache.cpp index 077d6bbbee..986c745e99 100644 --- a/src/core/threadsafenetworkdiskcache.cpp +++ b/src/core/threadsafenetworkdiskcache.cpp @@ -46,9 +46,9 @@ ThreadSafeNetworkDiskCache::ThreadSafeNetworkDiskCache(QObject *parent) : QAbstr if (!sCache) { sCache = new QNetworkDiskCache; #ifdef Q_OS_WIN32 - sCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/strawberry/networkcache"); + sCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QStringLiteral("/strawberry/networkcache")); #else - sCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/networkcache"); + sCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/networkcache")); #endif } diff --git a/src/core/translations.cpp b/src/core/translations.cpp index 0256be5009..4c2fab96f7 100644 --- a/src/core/translations.cpp +++ b/src/core/translations.cpp @@ -39,7 +39,7 @@ Translations::~Translations() { void Translations::LoadTranslation(const QString &prefix, const QString &path, const QString &language) { QTranslator *t = new PoTranslator; - if (t->load(prefix + "_" + language, path)) { + if (t->load(prefix + QLatin1Char('_') + language, path)) { QCoreApplication::installTranslator(t); translations_ << t; } diff --git a/src/covermanager/albumcoverchoicecontroller.cpp b/src/covermanager/albumcoverchoicecontroller.cpp index dca91f5b23..08100dae22 100644 --- a/src/covermanager/albumcoverchoicecontroller.cpp +++ b/src/covermanager/albumcoverchoicecontroller.cpp @@ -62,6 +62,7 @@ #include "core/song.h" #include "core/iconloader.h" #include "core/tagreaderclient.h" +#include "core/settings.h" #include "collection/collectionfilteroptions.h" #include "collection/collectionbackend.h" @@ -131,7 +132,7 @@ void AlbumCoverChoiceController::Init(Application *app) { app_ = app; cover_fetcher_ = new AlbumCoverFetcher(app_->cover_providers(), app->network(), this); - cover_searcher_ = new AlbumCoverSearcher(QIcon(":/pictures/cdcase.png"), app, this); + cover_searcher_ = new AlbumCoverSearcher(QIcon(QStringLiteral(":/pictures/cdcase.png")), app, this); cover_searcher_->Init(cover_fetcher_); QObject::connect(cover_fetcher_, &AlbumCoverFetcher::AlbumCoverFetched, this, &AlbumCoverChoiceController::AlbumCoverFetched); @@ -140,11 +141,11 @@ void AlbumCoverChoiceController::Init(Application *app) { void AlbumCoverChoiceController::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(CoversSettingsPage::kSettingsGroup); cover_options_.cover_type = static_cast(s.value(CoversSettingsPage::kSaveType, static_cast(CoverOptions::CoverType::Cache)).toInt()); cover_options_.cover_filename = static_cast(s.value(CoversSettingsPage::kSaveFilename, static_cast(CoverOptions::CoverFilename::Pattern)).toInt()); - cover_options_.cover_pattern = s.value(CoversSettingsPage::kSavePattern, "%albumartist-%album").toString(); + cover_options_.cover_pattern = s.value(CoversSettingsPage::kSavePattern, QStringLiteral("%albumartist-%album")).toString(); cover_options_.cover_overwrite = s.value(CoversSettingsPage::kSaveOverwrite, false).toBool(); cover_options_.cover_lowercase = s.value(CoversSettingsPage::kSaveLowercase, false).toBool(); cover_options_.cover_replace_spaces = s.value(CoversSettingsPage::kSaveReplaceSpaces, false).toBool(); @@ -175,7 +176,7 @@ AlbumCoverImageResult AlbumCoverChoiceController::LoadImageFromFile(Song *song) return AlbumCoverImageResult(); } - QString cover_file = QFileDialog::getOpenFileName(this, tr("Load cover from disk"), GetInitialPathForFileDialog(*song, QString()), tr(kLoadImageFileFilter) + ";;" + tr(kAllFilesFilter)); + QString cover_file = QFileDialog::getOpenFileName(this, tr("Load cover from disk"), GetInitialPathForFileDialog(*song, QString()), tr(kLoadImageFileFilter) + QStringLiteral(";;") + tr(kAllFilesFilter)); if (cover_file.isEmpty()) return AlbumCoverImageResult(); QFile file(cover_file); @@ -206,7 +207,7 @@ QUrl AlbumCoverChoiceController::LoadCoverFromFile(Song *song) { if (!song->url().isValid() || !song->url().isLocalFile() || song->effective_albumartist().isEmpty() || song->album().isEmpty()) return QUrl(); - QString cover_file = QFileDialog::getOpenFileName(this, tr("Load cover from disk"), GetInitialPathForFileDialog(*song, QString()), tr(kLoadImageFileFilter) + ";;" + tr(kAllFilesFilter)); + QString cover_file = QFileDialog::getOpenFileName(this, tr("Load cover from disk"), GetInitialPathForFileDialog(*song, QString()), tr(kLoadImageFileFilter) + QStringLiteral(";;") + tr(kAllFilesFilter)); if (cover_file.isEmpty() || QImage(cover_file).isNull()) return QUrl(); switch (get_save_album_cover_type()) { @@ -235,23 +236,23 @@ void AlbumCoverChoiceController::SaveCoverToFileManual(const Song &song, const A if (!song.effective_albumartist().isEmpty()) { initial_file_name = initial_file_name + song.effective_albumartist(); } - initial_file_name = initial_file_name + "-" + (song.effective_album().isEmpty() ? tr("unknown") : song.effective_album()) + ".jpg"; + initial_file_name = initial_file_name + QStringLiteral("-") + (song.effective_album().isEmpty() ? tr("unknown") : song.effective_album()) + QStringLiteral(".jpg"); initial_file_name = initial_file_name.toLower(); initial_file_name.replace(QRegularExpression(QStringLiteral("\\s")), QStringLiteral("-")); - initial_file_name.remove(QRegularExpression(QString(kInvalidFatCharactersRegex), QRegularExpression::CaseInsensitiveOption)); + initial_file_name.remove(QRegularExpression(QLatin1String(kInvalidFatCharactersRegex), QRegularExpression::CaseInsensitiveOption)); - QString save_filename = QFileDialog::getSaveFileName(this, tr("Save album cover"), GetInitialPathForFileDialog(song, initial_file_name), tr(kSaveImageFileFilter) + ";;" + tr(kAllFilesFilter)); + QString save_filename = QFileDialog::getSaveFileName(this, tr("Save album cover"), GetInitialPathForFileDialog(song, initial_file_name), tr(kSaveImageFileFilter) + QStringLiteral(";;") + tr(kAllFilesFilter)); if (save_filename.isEmpty()) return; QFileInfo fileinfo(save_filename); if (fileinfo.suffix().isEmpty()) { - save_filename.append(".jpg"); + save_filename.append(QStringLiteral(".jpg")); fileinfo.setFile(save_filename); } if (!QImageWriter::supportedImageFormats().contains(fileinfo.completeSuffix().toUtf8().toLower())) { - save_filename = Utilities::PathWithoutFilenameExtension(save_filename) + ".jpg"; + save_filename = Utilities::PathWithoutFilenameExtension(save_filename) + QStringLiteral(".jpg"); fileinfo.setFile(save_filename); } @@ -289,8 +290,8 @@ QString AlbumCoverChoiceController::GetInitialPathForFileDialog(const Song &song } // If no automatic art, start in the song's folder - if (!song.url().isEmpty() && song.url().isValid() && song.url().isLocalFile() && song.url().toLocalFile().contains('/')) { - return song.url().toLocalFile().section('/', 0, -2) + filename; + if (!song.url().isEmpty() && song.url().isValid() && song.url().isLocalFile() && song.url().toLocalFile().contains(QLatin1Char('/'))) { + return song.url().toLocalFile().section(QLatin1Char('/'), 0, -2) + filename; } return QDir::home().absolutePath() + filename; @@ -472,13 +473,13 @@ void AlbumCoverChoiceController::ShowCover(const Song &song, const QPixmap &pixm // Use Artist - Album as the window title QString title_text(song.effective_albumartist()); - if (!song.effective_album().isEmpty()) title_text += " - " + song.effective_album(); + if (!song.effective_album().isEmpty()) title_text += QStringLiteral(" - ") + song.effective_album(); QLabel *label = new QLabel(dialog); label->setPixmap(pixmap); // Add (WxHpx) to the title before possibly resizing - title_text += " (" + QString::number(pixmap.width()) + "x" + QString::number(pixmap.height()) + "px)"; + title_text += QStringLiteral(" (") + QString::number(pixmap.width()) + QStringLiteral("x") + QString::number(pixmap.height()) + QStringLiteral("px)"); // If the cover is larger than the screen, resize the window 85% seems to be enough to account for title bar and taskbar etc. QScreen *screen = Utilities::GetScreen(this); @@ -663,7 +664,7 @@ QUrl AlbumCoverChoiceController::SaveCoverToFileAutomatic(const Song::Source sou if (source == Song::Source::Collection && !cover_options_.cover_overwrite && !force_overwrite && get_save_album_cover_type() == CoverOptions::CoverType::Album && cover_options_.cover_filename == CoverOptions::CoverFilename::Pattern && file.exists()) { while (file.exists()) { QFileInfo fileinfo(file.fileName()); - file.setFileName(fileinfo.path() + "/0" + fileinfo.fileName()); + file.setFileName(fileinfo.path() + QStringLiteral("/0") + fileinfo.fileName()); } filepath = file.fileName(); } diff --git a/src/covermanager/albumcoverexport.cpp b/src/covermanager/albumcoverexport.cpp index 96b3a2568b..dcbd315588 100644 --- a/src/covermanager/albumcoverexport.cpp +++ b/src/covermanager/albumcoverexport.cpp @@ -33,6 +33,8 @@ #include "albumcoverexport.h" #include "ui_albumcoverexport.h" +#include "core/settings.h" + const char *AlbumCoverExport::kSettingsGroup = "AlbumCoverExport"; AlbumCoverExport::AlbumCoverExport(QWidget *parent) : QDialog(parent), ui_(new Ui_AlbumCoverExport) { @@ -47,17 +49,17 @@ AlbumCoverExport::~AlbumCoverExport() { delete ui_; } AlbumCoverExport::DialogResult AlbumCoverExport::Exec() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); // Restore last accepted settings - ui_->fileName->setText(s.value("fileName", "cover").toString()); + ui_->fileName->setText(s.value("fileName", QStringLiteral("cover")).toString()); ui_->doNotOverwrite->setChecked(static_cast(s.value("overwrite", static_cast(OverwriteMode::None)).toInt()) == OverwriteMode::None); ui_->overwriteAll->setChecked(static_cast(s.value("overwrite", static_cast(OverwriteMode::All)).toInt()) == OverwriteMode::All); ui_->overwriteSmaller->setChecked(static_cast(s.value("overwrite", static_cast(OverwriteMode::Smaller)).toInt()) == OverwriteMode::Smaller); ui_->forceSize->setChecked(s.value("forceSize", false).toBool()); - ui_->width->setText(s.value("width", "").toString()); - ui_->height->setText(s.value("height", "").toString()); + ui_->width->setText(s.value("width", QLatin1String("")).toString()); + ui_->height->setText(s.value("height", QLatin1String("")).toString()); ui_->export_downloaded->setChecked(s.value("export_downloaded", true).toBool()); ui_->export_embedded->setChecked(s.value("export_embedded", false).toBool()); diff --git a/src/covermanager/albumcoverfetchersearch.cpp b/src/covermanager/albumcoverfetchersearch.cpp index 2b04a69737..d5e149f70d 100644 --- a/src/covermanager/albumcoverfetchersearch.cpp +++ b/src/covermanager/albumcoverfetchersearch.cpp @@ -320,8 +320,8 @@ void AlbumCoverFetcherSearch::ProviderCoverFetchFinished(QNetworkReply *reply) { } else { QString mimetype = reply->header(QNetworkRequest::ContentTypeHeader).toString(); - if (mimetype.contains(';')) { - mimetype = mimetype.left(mimetype.indexOf(';')); + if (mimetype.contains(QLatin1Char(';'))) { + mimetype = mimetype.left(mimetype.indexOf(QLatin1Char(';'))); } if (ImageUtils::SupportedImageMimeTypes().contains(mimetype, Qt::CaseInsensitive) || ImageUtils::SupportedImageFormats().contains(mimetype, Qt::CaseInsensitive)) { QByteArray image_data = reply->readAll(); diff --git a/src/covermanager/albumcoverimageresult.h b/src/covermanager/albumcoverimageresult.h index 2ec4e87e6e..5c4514c446 100644 --- a/src/covermanager/albumcoverimageresult.h +++ b/src/covermanager/albumcoverimageresult.h @@ -41,7 +41,7 @@ class AlbumCoverImageResult { QImage image; bool is_valid() const { return !image_data.isNull() || !image.isNull(); } - bool is_jpeg() const { return mime_type == "image/jpeg" && !image_data.isEmpty(); } + bool is_jpeg() const { return mime_type == QStringLiteral("image/jpeg") && !image_data.isEmpty(); } }; Q_DECLARE_METATYPE(AlbumCoverImageResult) diff --git a/src/covermanager/albumcoverloaderoptions.cpp b/src/covermanager/albumcoverloaderoptions.cpp index 2a0826a7e1..0d8523f12c 100644 --- a/src/covermanager/albumcoverloaderoptions.cpp +++ b/src/covermanager/albumcoverloaderoptions.cpp @@ -21,6 +21,7 @@ #include +#include "core/settings.h" #include "settings/coverssettingspage.h" AlbumCoverLoaderOptions::AlbumCoverLoaderOptions(const Options _options, const QSize _desired_scaled_size, const qreal _device_pixel_ratio, const Types &_types) @@ -33,21 +34,21 @@ AlbumCoverLoaderOptions::Types AlbumCoverLoaderOptions::LoadTypes() { Types cover_types; - QSettings s; + Settings s; s.beginGroup(CoversSettingsPage::kSettingsGroup); const QStringList all_cover_types = QStringList() << QStringLiteral("art_unset") << QStringLiteral("art_embedded") << QStringLiteral("art_manual") << QStringLiteral("art_automatic"); const QStringList cover_types_strlist = s.value(CoversSettingsPage::kTypes, all_cover_types).toStringList(); for (const QString &cover_type_str : cover_types_strlist) { - if (cover_type_str == "art_unset") { + if (cover_type_str == QStringLiteral("art_unset")) { cover_types << AlbumCoverLoaderOptions::Type::Unset; } - else if (cover_type_str == "art_embedded") { + else if (cover_type_str == QStringLiteral("art_embedded")) { cover_types << AlbumCoverLoaderOptions::Type::Embedded; } - else if (cover_type_str == "art_manual") { + else if (cover_type_str == QStringLiteral("art_manual")) { cover_types << AlbumCoverLoaderOptions::Type::Manual; } - else if (cover_type_str == "art_automatic") { + else if (cover_type_str == QStringLiteral("art_automatic")) { cover_types << AlbumCoverLoaderOptions::Type::Automatic; } } diff --git a/src/covermanager/albumcovermanager.cpp b/src/covermanager/albumcovermanager.cpp index 9c7521310d..641a7d4363 100644 --- a/src/covermanager/albumcovermanager.cpp +++ b/src/covermanager/albumcovermanager.cpp @@ -70,6 +70,7 @@ #include "core/tagreaderclient.h" #include "core/database.h" #include "core/sqlrow.h" +#include "core/settings.h" #include "utilities/strutils.h" #include "utilities/fileutils.h" #include "utilities/imageutils.h" @@ -218,7 +219,7 @@ void AlbumCoverManager::Init() { QObject::connect(ui_->action_load, &QAction::triggered, this, &AlbumCoverManager::LoadSelectedToPlaylist); // Restore settings - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); if (s.contains("geometry")) { @@ -279,12 +280,12 @@ void AlbumCoverManager::closeEvent(QCloseEvent *e) { void AlbumCoverManager::LoadGeometry() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); - if (s.contains("geometry")) { + if (s.contains(QStringLiteral("geometry"))) { restoreGeometry(s.value("geometry").toByteArray()); } - if (s.contains("splitter_state")) { + if (s.contains(QStringLiteral("splitter_state"))) { ui_->splitter->restoreState(s.value("splitter_state").toByteArray()); } else { @@ -300,7 +301,7 @@ void AlbumCoverManager::LoadGeometry() { void AlbumCoverManager::SaveSettings() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("geometry", saveGeometry()); s.setValue("splitter_state", ui_->splitter->saveState()); @@ -397,7 +398,7 @@ void AlbumCoverManager::ArtistChanged(QListWidgetItem *current) { display_text = album_info.album; } else { - display_text = album_info.album_artist + " - " + album_info.album; + display_text = album_info.album_artist + QStringLiteral(" - ") + album_info.album; } AlbumItem *album_item = new AlbumItem(icon_nocover_item_, display_text, ui_->albums); @@ -413,7 +414,7 @@ void AlbumCoverManager::ArtistChanged(QListWidgetItem *current) { album_item->setToolTip(album_info.album); } else { - album_item->setToolTip(album_info.album_artist + " - " + album_info.album); + album_item->setToolTip(album_info.album_artist + QStringLiteral(" - ") + album_info.album); } album_item->setData(Role_ArtEmbedded, album_info.art_embedded); @@ -497,7 +498,7 @@ bool AlbumCoverManager::ShouldHide(const AlbumItem &album_item, const QString &f return false; } - QStringList query = filter.split(' '); + QStringList query = filter.split(QLatin1Char(' ')); for (const QString &s : query) { bool in_text = album_item.text().contains(s, Qt::CaseInsensitive); bool in_albumartist = album_item.data(Role_AlbumArtist).toString().contains(s, Qt::CaseInsensitive); @@ -558,7 +559,7 @@ void AlbumCoverManager::UpdateStatusText() { .arg(fetch_statistics_.missing_images_); if (fetch_statistics_.bytes_transferred_ > 0) { - message += ", " + tr("%1 transferred").arg(Utilities::PrettySize(fetch_statistics_.bytes_transferred_)); + message += QStringLiteral(", ") + tr("%1 transferred").arg(Utilities::PrettySize(fetch_statistics_.bytes_transferred_)); } statusBar()->showMessage(message); @@ -632,7 +633,7 @@ Song AlbumCoverManager::AlbumItemAsSong(AlbumItem *album_item) { QString title = album_item->data(Role_Album).toString(); QString artist_name = album_item->data(Role_AlbumArtist).toString(); if (!artist_name.isEmpty()) { - result.set_title(artist_name + " - " + title); + result.set_title(artist_name + QStringLiteral(" - ") + title); } else { result.set_title(title); @@ -876,7 +877,7 @@ SongList AlbumCoverManager::GetSongsInAlbum(const QModelIndex &idx) const { QSqlDatabase db(collection_backend_->db()->Connect()); CollectionQuery q(db, collection_backend_->songs_table(), collection_backend_->fts_table()); - q.SetColumnSpec("ROWID," + Song::kColumnSpec); + q.SetColumnSpec(QStringLiteral("ROWID,") + Song::kColumnSpec); q.AddWhere(QStringLiteral("album"), idx.data(Role_Album).toString()); q.SetOrderBy(QStringLiteral("disc, track, title")); diff --git a/src/covermanager/albumcoversearcher.cpp b/src/covermanager/albumcoversearcher.cpp index 7495885684..2855683f45 100644 --- a/src/covermanager/albumcoversearcher.cpp +++ b/src/covermanager/albumcoversearcher.cpp @@ -220,7 +220,7 @@ void AlbumCoverSearcher::SearchFinished(const quint64 id, const CoverProviderSea QStandardItem *item = new QStandardItem; item->setIcon(no_cover_icon_); - item->setText(result.artist + " - " + result.album); + item->setText(result.artist + QStringLiteral(" - ") + result.album); item->setData(result.image_url, Role_ImageURL); item->setData(new_id, Role_ImageRequestId); item->setData(false, Role_ImageFetchFinished); diff --git a/src/covermanager/coverexportrunnable.cpp b/src/covermanager/coverexportrunnable.cpp index 050af0fee3..9f5460bde6 100644 --- a/src/covermanager/coverexportrunnable.cpp +++ b/src/covermanager/coverexportrunnable.cpp @@ -84,7 +84,7 @@ void CoverExportRunnable::ProcessAndExportCover() { if (dialog_result_.export_downloaded_ && song_.art_manual_is_valid()) { const QString cover_path = song_.art_manual().toLocalFile(); if (image.load(cover_path)) { - extension = cover_path.section('.', -1); + extension = cover_path.section(QLatin1Char('.'), -1); } } break; @@ -92,7 +92,7 @@ void CoverExportRunnable::ProcessAndExportCover() { if (dialog_result_.export_downloaded_ && song_.art_automatic_is_valid()) { const QString cover_path = song_.art_automatic().toLocalFile(); if (image.load(cover_path)) { - extension = cover_path.section('.', -1); + extension = cover_path.section(QLatin1Char('.'), -1); } } break; @@ -110,8 +110,8 @@ void CoverExportRunnable::ProcessAndExportCover() { image = image.scaled(QSize(dialog_result_.width_, dialog_result_.height_), Qt::IgnoreAspectRatio); } - QString cover_dir = song_.url().toLocalFile().section('/', 0, -2); - QString new_file = cover_dir + '/' + dialog_result_.filename_ + '.' + (song_.art_embedded() ? QStringLiteral("jpg") : extension); + QString cover_dir = song_.url().toLocalFile().section(QLatin1Char('/'), 0, -2); + QString new_file = cover_dir + QLatin1Char('/') + dialog_result_.filename_ + QLatin1Char('.') + (song_.art_embedded() ? QStringLiteral("jpg") : extension); // If the file exists, do not override! if (dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode::None && QFile::exists(new_file)) { @@ -177,7 +177,7 @@ void CoverExportRunnable::ExportCover() { if (dialog_result_.export_downloaded_ && song_.art_manual_is_valid()) { cover_path = song_.art_manual().toLocalFile(); if (image.load(cover_path)) { - extension = cover_path.section('.', -1); + extension = cover_path.section(QLatin1Char('.'), -1); } } break; @@ -185,7 +185,7 @@ void CoverExportRunnable::ExportCover() { if (dialog_result_.export_downloaded_ && song_.art_automatic_is_valid()) { cover_path = song_.art_automatic().toLocalFile(); if (image.load(cover_path)) { - extension = cover_path.section('.', -1); + extension = cover_path.section(QLatin1Char('.'), -1); } } break; @@ -198,8 +198,8 @@ void CoverExportRunnable::ExportCover() { return; } - QString cover_dir = song_.url().toLocalFile().section('/', 0, -2); - QString new_file = cover_dir + '/' + dialog_result_.filename_ + '.' + extension; + QString cover_dir = song_.url().toLocalFile().section(QLatin1Char('/'), 0, -2); + QString new_file = cover_dir + QLatin1Char('/') + dialog_result_.filename_ + QLatin1Char('.') + extension; // If the file exists, do not override! if (dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode::None && QFile::exists(new_file)) { diff --git a/src/covermanager/coverproviders.cpp b/src/covermanager/coverproviders.cpp index 4042ec1a0e..927f03db83 100644 --- a/src/covermanager/coverproviders.cpp +++ b/src/covermanager/coverproviders.cpp @@ -30,6 +30,7 @@ #include #include "core/logging.h" +#include "core/settings.h" #include "coverprovider.h" #include "coverproviders.h" @@ -56,7 +57,7 @@ void CoverProviders::ReloadSettings() { all_providers.insert(provider->order(), provider->name()); } - QSettings s; + Settings s; s.beginGroup(CoversSettingsPage::kSettingsGroup); QStringList providers_enabled = s.value(CoversSettingsPage::kProviders, QStringList() << all_providers.values()).toStringList(); s.endGroup(); diff --git a/src/covermanager/coversearchstatistics.cpp b/src/covermanager/coversearchstatistics.cpp index 2ad4d4b416..e9558a1c68 100644 --- a/src/covermanager/coversearchstatistics.cpp +++ b/src/covermanager/coversearchstatistics.cpp @@ -63,6 +63,6 @@ QString CoverSearchStatistics::AverageDimensions() const { return QStringLiteral("0x0"); } - return QString::number(chosen_width_ / chosen_images_) + "x" + QString::number(chosen_height_ / chosen_images_); + return QString::number(chosen_width_ / chosen_images_) + QStringLiteral("x") + QString::number(chosen_height_ / chosen_images_); } diff --git a/src/covermanager/coversearchstatisticsdialog.cpp b/src/covermanager/coversearchstatisticsdialog.cpp index 0b5539671e..5cce787ab4 100644 --- a/src/covermanager/coversearchstatisticsdialog.cpp +++ b/src/covermanager/coversearchstatisticsdialog.cpp @@ -43,7 +43,7 @@ CoverSearchStatisticsDialog::CoverSearchStatisticsDialog(QWidget *parent) details_layout_->setSpacing(0); setStyleSheet( - "#details {" + QStringLiteral("#details {" " background-color: palette(base);" "}" "#details QLabel[type=\"label\"] {" @@ -54,7 +54,7 @@ CoverSearchStatisticsDialog::CoverSearchStatisticsDialog(QWidget *parent) "#details QLabel[type=\"value\"] {" " font-weight: bold;" " max-width: 100px;" - "}"); + "}")); } CoverSearchStatisticsDialog::~CoverSearchStatisticsDialog() { delete ui_; } @@ -92,8 +92,8 @@ void CoverSearchStatisticsDialog::AddLine(const QString &label, const QString &v QLabel *label1 = new QLabel(label); QLabel *label2 = new QLabel(value); - label1->setProperty("type", "label"); - label2->setProperty("type", "value"); + label1->setProperty("type", QStringLiteral("label")); + label2->setProperty("type", QStringLiteral("value")); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(label1); diff --git a/src/covermanager/currentalbumcoverloader.cpp b/src/covermanager/currentalbumcoverloader.cpp index 5f5a97ee9e..41f4d86592 100644 --- a/src/covermanager/currentalbumcoverloader.cpp +++ b/src/covermanager/currentalbumcoverloader.cpp @@ -41,7 +41,7 @@ using std::make_unique; CurrentAlbumCoverLoader::CurrentAlbumCoverLoader(Application *app, QObject *parent) : QObject(parent), app_(app), - temp_file_pattern_(QDir::tempPath() + "/strawberry-cover-XXXXXX.jpg"), + temp_file_pattern_(QDir::tempPath() + QStringLiteral("/strawberry-cover-XXXXXX.jpg")), id_(0) { options_.options = AlbumCoverLoaderOptions::Option::RawImageData | AlbumCoverLoaderOptions::Option::OriginalImage | AlbumCoverLoaderOptions::Option::ScaledImage; diff --git a/src/covermanager/deezercoverprovider.cpp b/src/covermanager/deezercoverprovider.cpp index 82a0967b29..da23558d02 100644 --- a/src/covermanager/deezercoverprovider.cpp +++ b/src/covermanager/deezercoverprovider.cpp @@ -72,27 +72,27 @@ bool DeezerCoverProvider::StartSearch(const QString &artist, const QString &albu QString query = artist; if (album.isEmpty() && !title.isEmpty()) { resource = QStringLiteral("search/track"); - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1Char(' ')); query.append(title); } else { resource = QStringLiteral("search/album"); if (!album.isEmpty()) { - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1Char(' ')); query.append(album); } } - const ParamList params = ParamList() << Param("output", "json") - << Param("q", query) - << Param("limit", QString::number(kLimit)); + const ParamList params = ParamList() << Param(QStringLiteral("output"), QStringLiteral("json")) + << Param(QStringLiteral("q"), query) + << Param(QStringLiteral("limit"), QString::number(kLimit)); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromUtf8(QUrl::toPercentEncoding(param.first)), QString::fromUtf8(QUrl::toPercentEncoding(param.second))); } - QUrl url(kApiUrl + QStringLiteral("/") + resource); + QUrl url(QLatin1String(kApiUrl) + QStringLiteral("/") + resource); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); @@ -237,7 +237,7 @@ void DeezerCoverProvider::HandleSearchReply(QNetworkReply *reply, const int id) continue; } QString type = obj_album[QStringLiteral("type")].toString(); - if (type != "album") { + if (type != QStringLiteral("album")) { Error(QStringLiteral("Invalid Json reply, data array value album object has incorrect type returned"), obj_album); continue; } diff --git a/src/covermanager/discogscoverprovider.cpp b/src/covermanager/discogscoverprovider.cpp index d519d1fcd3..873ea0f8d0 100644 --- a/src/covermanager/discogscoverprovider.cpp +++ b/src/covermanager/discogscoverprovider.cpp @@ -126,28 +126,28 @@ void DiscogsCoverProvider::FlushRequests() { void DiscogsCoverProvider::SendSearchRequest(SharedPtr search) { - ParamList params = ParamList() << Param("format", "album") - << Param("artist", search->artist.toLower()) - << Param("release_title", search->album.toLower()); + ParamList params = ParamList() << Param(QStringLiteral("format"), QStringLiteral("album")) + << Param(QStringLiteral("artist"), search->artist.toLower()) + << Param(QStringLiteral("release_title"), search->album.toLower()); switch (search->type) { case DiscogsCoverType::Master: - params << Param("type", "master"); + params << Param(QStringLiteral("type"), QStringLiteral("master")); break; case DiscogsCoverType::Release: - params << Param("type", "release"); + params << Param(QStringLiteral("type"), QStringLiteral("release")); break; } - QNetworkReply *reply = CreateRequest(QUrl(kUrlSearch), params); + QNetworkReply *reply = CreateRequest(QUrl(QString::fromLatin1(kUrlSearch)), params); QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, search]() { HandleSearchReply(reply, search->id); }); } QNetworkReply *DiscogsCoverProvider::CreateRequest(QUrl url, const ParamList ¶ms_provided) { - ParamList params = ParamList() << Param("key", QByteArray::fromBase64(kAccessKeyB64)) - << Param("secret", QByteArray::fromBase64(kSecretKeyB64)) + ParamList params = ParamList() << Param(QStringLiteral("key"), QString::fromUtf8(QByteArray::fromBase64(kAccessKeyB64))) + << Param(QStringLiteral("secret"), QString::fromUtf8(QByteArray::fromBase64(kSecretKeyB64))) << params_provided; QUrlQuery url_query; @@ -157,8 +157,8 @@ QNetworkReply *DiscogsCoverProvider::CreateRequest(QUrl url, const ParamList &pa using EncodedParam = QPair; for (const Param ¶m : params) { EncodedParam encoded_param(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); - query_items << QString(encoded_param.first + "=" + encoded_param.second); - url_query.addQueryItem(encoded_param.first, encoded_param.second); + query_items << QString::fromUtf8(encoded_param.first) + QStringLiteral("=") + QString::fromUtf8(encoded_param.second); + url_query.addQueryItem(QString::fromUtf8(encoded_param.first), QString::fromUtf8(encoded_param.second)); } url.setQuery(url_query); @@ -167,7 +167,7 @@ QNetworkReply *DiscogsCoverProvider::CreateRequest(QUrl url, const ParamList &pa const QByteArray signature(Utilities::HmacSha256(QByteArray::fromBase64(kSecretKeyB64), data_to_sign)); // Add the signature to the request - url_query.addQueryItem(QStringLiteral("Signature"), QUrl::toPercentEncoding(signature.toBase64())); + url_query.addQueryItem(QStringLiteral("Signature"), QString::fromUtf8(QUrl::toPercentEncoding(QString::fromUtf8(signature.toBase64())))); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); @@ -427,7 +427,7 @@ void DiscogsCoverProvider::HandleReleaseReply(QNetworkReply *reply, const int se continue; } QString type = obj_image[QStringLiteral("type")].toString(); - if (type != "primary") { + if (type != QStringLiteral("primary")) { continue; } int width = obj_image[QStringLiteral("width")].toInt(); diff --git a/src/covermanager/lastfmcoverprovider.cpp b/src/covermanager/lastfmcoverprovider.cpp index ce1a97d5ac..aeb86811aa 100644 --- a/src/covermanager/lastfmcoverprovider.cpp +++ b/src/covermanager/lastfmcoverprovider.cpp @@ -46,9 +46,11 @@ #include "albumcoverfetcher.h" #include "lastfmcoverprovider.h" -const char *LastFmCoverProvider::kUrl = "https://ws.audioscrobbler.com/2.0/"; -const char *LastFmCoverProvider::kApiKey = "211990b4c96782c05d1536e7219eb56e"; -const char *LastFmCoverProvider::kSecret = "80fd738f49596e9709b1bf9319c444a8"; +namespace { +constexpr char kUrl[] = "https://ws.audioscrobbler.com/2.0/"; +constexpr char kApiKey[] = "211990b4c96782c05d1536e7219eb56e"; +constexpr char kSecret[] = "80fd738f49596e9709b1bf9319c444a8"; +} // namespace LastFmCoverProvider::LastFmCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider(QStringLiteral("Last.fm"), true, false, 1.0, true, false, app, network, parent) {} @@ -74,21 +76,21 @@ bool LastFmCoverProvider::StartSearch(const QString &artist, const QString &albu if (album.isEmpty() && !title.isEmpty()) { method = QStringLiteral("track.search"); type = QStringLiteral("track"); - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1String(" ")); query.append(title); } else { method = QStringLiteral("album.search"); type = QStringLiteral("album"); if (!album.isEmpty()) { - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1String(" ")); query.append(album); } } - ParamList params = ParamList() << Param("api_key", kApiKey) - << Param("lang", QLocale().name().left(2).toLower()) - << Param("method", method) + ParamList params = ParamList() << Param(QStringLiteral("api_key"), QLatin1String(kApiKey)) + << Param(QStringLiteral("lang"), QLocale().name().left(2).toLower()) + << Param(QStringLiteral("method"), method) << Param(type, query); std::sort(params.begin(), params.end()); @@ -96,21 +98,21 @@ bool LastFmCoverProvider::StartSearch(const QString &artist, const QString &albu QUrlQuery url_query; QString data_to_sign; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromUtf8(QUrl::toPercentEncoding(param.first)), QString::fromUtf8(QUrl::toPercentEncoding(param.second))); data_to_sign += param.first + param.second; } - data_to_sign += kSecret; + data_to_sign += QLatin1String(kSecret); QByteArray const digest = QCryptographicHash::hash(data_to_sign.toUtf8(), QCryptographicHash::Md5); - QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, '0').toLower(); + QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, QLatin1Char('0')).toLower(); - url_query.addQueryItem(QUrl::toPercentEncoding(QStringLiteral("api_sig")), QUrl::toPercentEncoding(signature)); - url_query.addQueryItem(QUrl::toPercentEncoding(QStringLiteral("format")), QUrl::toPercentEncoding(QStringLiteral("json"))); + url_query.addQueryItem(QString::fromUtf8(QUrl::toPercentEncoding(QStringLiteral("api_sig"))), QString::fromUtf8(QUrl::toPercentEncoding(signature))); + url_query.addQueryItem(QString::fromUtf8(QUrl::toPercentEncoding(QStringLiteral("format"))), QString::fromUtf8(QUrl::toPercentEncoding(QStringLiteral("json")))); - QUrl url(kUrl); + QUrl url(QString::fromUtf8(kUrl)); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); QNetworkReply *reply = network_->post(req, url_query.toString(QUrl::FullyEncoded).toUtf8()); replies_ << reply; QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, id, type]() { QueryFinished(reply, id, type); }); @@ -172,7 +174,7 @@ void LastFmCoverProvider::QueryFinished(QNetworkReply *reply, const int id, cons QJsonValue value_matches; - if (type == "album") { + if (type == QStringLiteral("album")) { if (obj_results.contains(QStringLiteral("albummatches"))) { value_matches = obj_results[QStringLiteral("albummatches")]; } @@ -182,7 +184,7 @@ void LastFmCoverProvider::QueryFinished(QNetworkReply *reply, const int id, cons return; } } - else if (type == "track") { + else if (type == QStringLiteral("track")) { if (obj_results.contains(QStringLiteral("trackmatches"))) { value_matches = obj_results[QStringLiteral("trackmatches")]; } @@ -234,7 +236,7 @@ void LastFmCoverProvider::QueryFinished(QNetworkReply *reply, const int id, cons } QString artist = obj[QStringLiteral("artist")].toString(); QString album; - if (type == "album") { + if (type == QStringLiteral("album")) { album = obj[QStringLiteral("name")].toString(); } @@ -308,7 +310,7 @@ QByteArray LastFmCoverProvider::GetReplyData(QNetworkReply *reply) { if (json_obj.contains(QStringLiteral("error")) && json_obj.contains(QStringLiteral("message"))) { int code = json_obj[QStringLiteral("error")].toInt(); QString message = json_obj[QStringLiteral("message")].toString(); - error = "Error: " + QString::number(code) + ": " + message; + error = QStringLiteral("Error: ") + QString::number(code) + QStringLiteral(": ") + message; } } if (error.isEmpty()) { @@ -337,10 +339,10 @@ void LastFmCoverProvider::Error(const QString &error, const QVariant &debug) { LastFmCoverProvider::LastFmImageSize LastFmCoverProvider::ImageSizeFromString(const QString &size) { - if (size == "small") return LastFmImageSize::Small; - else if (size == "medium") return LastFmImageSize::Medium; - else if (size == "large") return LastFmImageSize::Large; - else if (size == "extralarge") return LastFmImageSize::ExtraLarge; + if (size == QStringLiteral("small")) return LastFmImageSize::Small; + else if (size == QStringLiteral("medium")) return LastFmImageSize::Medium; + else if (size == QStringLiteral("large")) return LastFmImageSize::Large; + else if (size == QStringLiteral("extralarge")) return LastFmImageSize::ExtraLarge; else return LastFmImageSize::Unknown; } diff --git a/src/covermanager/lastfmcoverprovider.h b/src/covermanager/lastfmcoverprovider.h index e35e6f4271..2a7f1b8445 100644 --- a/src/covermanager/lastfmcoverprovider.h +++ b/src/covermanager/lastfmcoverprovider.h @@ -62,10 +62,6 @@ class LastFmCoverProvider : public JsonCoverProvider { void Error(const QString &error, const QVariant &debug = QVariant()) override; private: - static const char *kUrl; - static const char *kApiKey; - static const char *kSecret; - QList replies_; }; diff --git a/src/covermanager/musicbrainzcoverprovider.cpp b/src/covermanager/musicbrainzcoverprovider.cpp index ddac33e20d..5655a6f124 100644 --- a/src/covermanager/musicbrainzcoverprovider.cpp +++ b/src/covermanager/musicbrainzcoverprovider.cpp @@ -44,10 +44,12 @@ #include "jsoncoverprovider.h" #include "musicbrainzcoverprovider.h" -const char *MusicbrainzCoverProvider::kReleaseSearchUrl = "https://musicbrainz.org/ws/2/release/"; -const char *MusicbrainzCoverProvider::kAlbumCoverUrl = "https://coverartarchive.org/release/%1/front"; -const int MusicbrainzCoverProvider::kLimit = 8; -const int MusicbrainzCoverProvider::kRequestsDelay = 1000; +namespace { +static constexpr char kReleaseSearchUrl[] = "https://musicbrainz.org/ws/2/release/"; +static constexpr char kAlbumCoverUrl[] = "https://coverartarchive.org/release/%1/front"; +static constexpr int kLimit = 8; +static constexpr int kRequestsDelay = 1000; +} // namespace MusicbrainzCoverProvider::MusicbrainzCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider(QStringLiteral("MusicBrainz"), true, false, 1.5, true, false, app, network, parent), @@ -89,14 +91,14 @@ bool MusicbrainzCoverProvider::StartSearch(const QString &artist, const QString void MusicbrainzCoverProvider::SendSearchRequest(const SearchRequest &request) { - QString query = QStringLiteral("release:\"%1\" AND artist:\"%2\"").arg(request.album.trimmed().replace('"', QLatin1String("\\\"")), request.artist.trimmed().replace('"', QLatin1String("\\\""))); + QString query = QStringLiteral("release:\"%1\" AND artist:\"%2\"").arg(request.album.trimmed().replace(QLatin1Char('"'), QLatin1String("\\\"")), request.artist.trimmed().replace(QLatin1Char('"'), QLatin1String("\\\""))); QUrlQuery url_query; url_query.addQueryItem(QStringLiteral("query"), query); url_query.addQueryItem(QStringLiteral("limit"), QString::number(kLimit)); url_query.addQueryItem(QStringLiteral("fmt"), QStringLiteral("json")); - QUrl url(kReleaseSearchUrl); + QUrl url(QString::fromLatin1(kReleaseSearchUrl)); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); @@ -214,7 +216,7 @@ void MusicbrainzCoverProvider::HandleSearchReply(QNetworkReply *reply, const int QString album = obj_release[QStringLiteral("title")].toString(); CoverProviderSearchResult cover_result; - QUrl url(QString(kAlbumCoverUrl).arg(id)); + QUrl url(QLatin1String(kAlbumCoverUrl).arg(id)); cover_result.artist = artist; cover_result.album = album; cover_result.image_url = url; diff --git a/src/covermanager/musicbrainzcoverprovider.h b/src/covermanager/musicbrainzcoverprovider.h index 3a315db968..bc2a1ac702 100644 --- a/src/covermanager/musicbrainzcoverprovider.h +++ b/src/covermanager/musicbrainzcoverprovider.h @@ -64,11 +64,6 @@ class MusicbrainzCoverProvider : public JsonCoverProvider { void Error(const QString &error, const QVariant &debug = QVariant()) override; private: - static const char *kReleaseSearchUrl; - static const char *kAlbumCoverUrl; - static const int kLimit; - static const int kRequestsDelay; - QTimer *timer_flush_requests_; QQueue queue_search_requests_; QList replies_; diff --git a/src/covermanager/musixmatchcoverprovider.cpp b/src/covermanager/musixmatchcoverprovider.cpp index f8b1747357..f5247bd386 100644 --- a/src/covermanager/musixmatchcoverprovider.cpp +++ b/src/covermanager/musixmatchcoverprovider.cpp @@ -100,13 +100,13 @@ void MusixmatchCoverProvider::HandleSearchReply(QNetworkReply *reply, const int return; } - QByteArray data = reply->readAll(); + const QByteArray data = reply->readAll(); if (data.isEmpty()) { Error(QStringLiteral("Empty reply received from server.")); emit SearchFinished(id, results); return; } - QString content = data; + const QString content = QString::fromUtf8(data); const QString data_begin = QStringLiteral(""); if (!content.contains(data_begin) || !content.contains(data_end)) { diff --git a/src/covermanager/opentidalcoverprovider.cpp b/src/covermanager/opentidalcoverprovider.cpp index e3294776b0..36d965e76d 100644 --- a/src/covermanager/opentidalcoverprovider.cpp +++ b/src/covermanager/opentidalcoverprovider.cpp @@ -39,19 +39,20 @@ #include "core/application.h" #include "core/networkaccessmanager.h" #include "core/logging.h" +#include "core/settings.h" #include "utilities/timeconstants.h" #include "albumcoverfetcher.h" #include "jsoncoverprovider.h" #include "opentidalcoverprovider.h" namespace { -constexpr char kSettingsGroup[] = "OpenTidal"; -constexpr char kAuthUrl[] = "https://auth.tidal.com/v1/oauth2/token"; -constexpr char kApiUrl[] = "https://openapi.tidal.com"; -constexpr char kApiClientIdB64[] = "RHBwV3FpTEM4ZFJSV1RJaQ=="; -constexpr char kApiClientSecretB64[] = "cGk0QmxpclZXQWlteWpBc0RnWmZ5RmVlRzA2b3E1blVBVTljUW1IdFhDST0="; -constexpr int kLimit = 10; -constexpr const int kRequestsDelay = 1000; +static constexpr char kSettingsGroup[] = "OpenTidal"; +static constexpr char kAuthUrl[] = "https://auth.tidal.com/v1/oauth2/token"; +static constexpr char kApiUrl[] = "https://openapi.tidal.com"; +static constexpr char kApiClientIdB64[] = "RHBwV3FpTEM4ZFJSV1RJaQ=="; +static constexpr char kApiClientSecretB64[] = "cGk0QmxpclZXQWlteWpBc0RnWmZ5RmVlRzA2b3E1blVBVTljUW1IdFhDST0="; +static constexpr int kLimit = 10; +static constexpr const int kRequestsDelay = 1000; } // namespace using std::make_shared; @@ -112,7 +113,7 @@ void OpenTidalCoverProvider::CancelSearch(const int id) { void OpenTidalCoverProvider::LoadSession() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); token_type_ = s.value("token_type").toString(); access_token_ = s.value("access_token").toString(); @@ -155,7 +156,7 @@ void OpenTidalCoverProvider::Login() { login_in_progress_ = true; last_login_attempt_ = QDateTime::currentDateTime(); - QUrl url(kAuthUrl); + QUrl url(QString::fromLatin1(kAuthUrl)); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); req.setRawHeader("Authorization", "Basic " + QByteArray(QByteArray::fromBase64(kApiClientIdB64) + ":" + QByteArray::fromBase64(kApiClientSecretB64)).toBase64()); @@ -208,7 +209,7 @@ void OpenTidalCoverProvider::LoginFinished(QNetworkReply *reply) { login_time_ = QDateTime::currentDateTime().toSecsSinceEpoch(); expires_in_ = json_obj[QStringLiteral("expires_in")].toInt(); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("token_type", token_type_); s.setValue("access_token", access_token_); @@ -293,23 +294,23 @@ void OpenTidalCoverProvider::SendSearchRequest(SearchRequestPtr search_request) QString query = search_request->artist; if (!search_request->album.isEmpty()) { - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QStringLiteral(" ")); query.append(search_request->album); } else if (!search_request->title.isEmpty()) { - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QStringLiteral(" ")); query.append(search_request->title); } QUrlQuery url_query; - url_query.addQueryItem(QStringLiteral("query"), QUrl::toPercentEncoding(query)); + url_query.addQueryItem(QStringLiteral("query"), QString::fromUtf8(QUrl::toPercentEncoding(query))); url_query.addQueryItem(QStringLiteral("limit"), QString::number(kLimit)); url_query.addQueryItem(QStringLiteral("countryCode"), QStringLiteral("US")); - QUrl url(QString(kApiUrl) + QStringLiteral("/search")); + QUrl url(QLatin1String(kApiUrl) + QStringLiteral("/search")); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/vnd.tidal.v1+json"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/vnd.tidal.v1+json")); req.setRawHeader("Authorization", token_type_.toUtf8() + " " + access_token_.toUtf8()); QNetworkReply *reply = network_->get(req); diff --git a/src/covermanager/qobuzcoverprovider.cpp b/src/covermanager/qobuzcoverprovider.cpp index 749f1ea100..4bf8b03c96 100644 --- a/src/covermanager/qobuzcoverprovider.cpp +++ b/src/covermanager/qobuzcoverprovider.cpp @@ -71,34 +71,34 @@ bool QobuzCoverProvider::StartSearch(const QString &artist, const QString &album QString query = artist; if (album.isEmpty() && !title.isEmpty()) { resource = QStringLiteral("track/search"); - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1Char(' ')); query.append(title); } else { resource = QStringLiteral("album/search"); if (!album.isEmpty()) { - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1Char(' ')); query.append(album); } } - ParamList params = ParamList() << Param("query", query) - << Param("limit", QString::number(kLimit)) - << Param("app_id", service_->app_id().toUtf8()); + ParamList params = ParamList() << Param(QStringLiteral("query"), query) + << Param(QStringLiteral("limit"), QString::number(kLimit)) + << Param(QStringLiteral("app_id"), service_->app_id()); std::sort(params.begin(), params.end()); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromUtf8(QUrl::toPercentEncoding(param.first)), QString::fromUtf8(QUrl::toPercentEncoding(param.second))); } - QUrl url(QString(QobuzService::kApiUrl) + QStringLiteral("/") + resource); + QUrl url(QLatin1String(QobuzService::kApiUrl) + QLatin1Char('/') + resource); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); req.setRawHeader("X-App-Id", service_->app_id().toUtf8()); req.setRawHeader("X-User-Auth-Token", service_->user_auth_token().toUtf8()); QNetworkReply *reply = network_->get(req); diff --git a/src/covermanager/spotifycoverprovider.cpp b/src/covermanager/spotifycoverprovider.cpp index 897133c976..873b8e4e78 100644 --- a/src/covermanager/spotifycoverprovider.cpp +++ b/src/covermanager/spotifycoverprovider.cpp @@ -45,6 +45,7 @@ #include "core/application.h" #include "core/networkaccessmanager.h" #include "core/logging.h" +#include "core/settings.h" #include "utilities/randutils.h" #include "utilities/timeconstants.h" #include "internet/localredirectserver.h" @@ -52,14 +53,16 @@ #include "jsoncoverprovider.h" #include "spotifycoverprovider.h" -const char *SpotifyCoverProvider::kSettingsGroup = "Spotify"; -const char *SpotifyCoverProvider::kOAuthAuthorizeUrl = "https://accounts.spotify.com/authorize"; -const char *SpotifyCoverProvider::kOAuthAccessTokenUrl = "https://accounts.spotify.com/api/token"; -const char *SpotifyCoverProvider::kOAuthRedirectUrl = "http://localhost:63111/"; -const char *SpotifyCoverProvider::kClientIDB64 = "ZTZjY2Y2OTQ5NzY1NGE3NThjOTAxNWViYzdiMWQzMTc="; -const char *SpotifyCoverProvider::kClientSecretB64 = "N2ZlMDMxODk1NTBlNDE3ZGI1ZWQ1MzE3ZGZlZmU2MTE="; -const char *SpotifyCoverProvider::kApiUrl = "https://api.spotify.com/v1"; -const int SpotifyCoverProvider::kLimit = 10; +namespace { +constexpr char kSettingsGroup[] = "Spotify"; +constexpr char kOAuthAuthorizeUrl[] = "https://accounts.spotify.com/authorize"; +constexpr char kOAuthAccessTokenUrl[] = "https://accounts.spotify.com/api/token"; +constexpr char kOAuthRedirectUrl[] = "http://localhost:63111/"; +constexpr char kClientIDB64[] = "ZTZjY2Y2OTQ5NzY1NGE3NThjOTAxNWViYzdiMWQzMTc="; +constexpr char kClientSecretB64[] = "N2ZlMDMxODk1NTBlNDE3ZGI1ZWQ1MzE3ZGZlZmU2MTE="; +constexpr char kApiUrl[] = "https://api.spotify.com/v1"; +constexpr int kLimit = 10; +} // namespace SpotifyCoverProvider::SpotifyCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider(QStringLiteral("Spotify"), true, true, 2.5, true, true, app, network, parent), @@ -70,7 +73,7 @@ SpotifyCoverProvider::SpotifyCoverProvider(Application *app, SharedPtrurl().port()); RequestAccessToken(code, redirect_url); } @@ -212,17 +215,17 @@ void SpotifyCoverProvider::RequestAccessToken(const QString &code, const QUrl &r refresh_login_timer_.stop(); - ParamList params = ParamList() << Param("client_id", QByteArray::fromBase64(kClientIDB64)) - << Param("client_secret", QByteArray::fromBase64(kClientSecretB64)); + ParamList params = ParamList() << Param(QStringLiteral("client_id"), QLatin1String(kClientIDB64)) + << Param(QStringLiteral("client_secret"), QLatin1String(kClientSecretB64)); if (!code.isEmpty() && !redirect_url.isEmpty()) { - params << Param("grant_type", "authorization_code"); - params << Param("code", code); - params << Param("redirect_uri", redirect_url.toString()); + params << Param(QStringLiteral("grant_type"), QStringLiteral("authorization_code")); + params << Param(QStringLiteral("code"), code); + params << Param(QStringLiteral("redirect_uri"), redirect_url.toString()); } else if (!refresh_token_.isEmpty() && is_enabled()) { - params << Param("grant_type", "refresh_token"); - params << Param("refresh_token", refresh_token_); + params << Param(QStringLiteral("grant_type"), QStringLiteral("refresh_token")); + params << Param(QStringLiteral("refresh_token"), refresh_token_); } else { return; @@ -230,14 +233,14 @@ void SpotifyCoverProvider::RequestAccessToken(const QString &code, const QUrl &r QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromUtf8(QUrl::toPercentEncoding(param.first)), QString::fromUtf8(QUrl::toPercentEncoding(param.second))); } - QUrl new_url(kOAuthAccessTokenUrl); + QUrl new_url(QString::fromLatin1(kOAuthAccessTokenUrl)); QNetworkRequest req(new_url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - QString auth_header_data = QByteArray::fromBase64(kClientIDB64) + QStringLiteral(":") + QByteArray::fromBase64(kClientSecretB64); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); + QString auth_header_data = QString::fromUtf8(QByteArray::fromBase64(kClientIDB64)) + QStringLiteral(":") + QString::fromUtf8(QByteArray::fromBase64(kClientSecretB64)); req.setRawHeader("Authorization", "Basic " + auth_header_data.toUtf8().toBase64()); QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8(); @@ -334,7 +337,7 @@ void SpotifyCoverProvider::AccessTokenRequestFinished(QNetworkReply *reply) { expires_in_ = json_obj[QStringLiteral("expires_in")].toInt(); login_time_ = QDateTime::currentDateTime().toSecsSinceEpoch(); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("access_token", access_token_); s.setValue("refresh_token", refresh_token_); @@ -366,32 +369,32 @@ bool SpotifyCoverProvider::StartSearch(const QString &artist, const QString &alb if (album.isEmpty() && !title.isEmpty()) { type = QStringLiteral("track"); extract = QStringLiteral("tracks"); - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1Char(' ')); query.append(title); } else { type = QStringLiteral("album"); extract = QStringLiteral("albums"); if (!album.isEmpty()) { - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1Char(' ')); query.append(album); } } - ParamList params = ParamList() << Param("q", query) - << Param("type", type) - << Param("limit", QString::number(kLimit)); + ParamList params = ParamList() << Param(QStringLiteral("q"), query) + << Param(QStringLiteral("type"), type) + << Param(QStringLiteral("limit"), QString::number(kLimit)); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromUtf8(QUrl::toPercentEncoding(param.first)), QString::fromUtf8(QUrl::toPercentEncoding(param.second))); } - QUrl url(kApiUrl + QStringLiteral("/search")); + QUrl url(QLatin1String(kApiUrl) + QStringLiteral("/search")); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); req.setRawHeader("Authorization", "Bearer " + access_token_.toUtf8()); QNetworkReply *reply = network_->get(req); diff --git a/src/covermanager/spotifycoverprovider.h b/src/covermanager/spotifycoverprovider.h index a0a5bd1099..3432b05d5c 100644 --- a/src/covermanager/spotifycoverprovider.h +++ b/src/covermanager/spotifycoverprovider.h @@ -70,15 +70,6 @@ class SpotifyCoverProvider : public JsonCoverProvider { void RequestAccessToken(const QString &code = QString(), const QUrl &redirect_url = QUrl()); private: - static const char *kSettingsGroup; - static const char *kClientIDB64; - static const char *kClientSecretB64; - static const char *kOAuthAuthorizeUrl; - static const char *kOAuthAccessTokenUrl; - static const char *kOAuthRedirectUrl; - static const char *kApiUrl; - static const int kLimit; - LocalRedirectServer *server_; QStringList login_errors_; QString code_verifier_; diff --git a/src/covermanager/tidalcoverprovider.cpp b/src/covermanager/tidalcoverprovider.cpp index c0892da8a2..0ee4117de6 100644 --- a/src/covermanager/tidalcoverprovider.cpp +++ b/src/covermanager/tidalcoverprovider.cpp @@ -72,31 +72,31 @@ bool TidalCoverProvider::StartSearch(const QString &artist, const QString &album QString query = artist; if (album.isEmpty() && !title.isEmpty()) { resource = QStringLiteral("search/tracks"); - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1Char(' ')); query.append(title); } else { resource = QStringLiteral("search/albums"); if (!album.isEmpty()) { - if (!query.isEmpty()) query.append(" "); + if (!query.isEmpty()) query.append(QLatin1Char(' ')); query.append(album); } } - ParamList params = ParamList() << Param("query", query) - << Param("limit", QString::number(kLimit)) - << Param("countryCode", service_->country_code()); + ParamList params = ParamList() << Param(QStringLiteral("query"), query) + << Param(QStringLiteral("limit"), QString::number(kLimit)) + << Param(QStringLiteral("countryCode"), service_->country_code()); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } - QUrl url(QString(TidalService::kApiUrl) + QStringLiteral("/") + resource); + QUrl url(QString::fromLatin1(TidalService::kApiUrl) + QLatin1Char('/') + resource); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); if (service_->oauth() && !service_->access_token().isEmpty()) req.setRawHeader("authorization", "Bearer " + service_->access_token().toUtf8()); else if (!service_->session_id().isEmpty()) req.setRawHeader("X-Tidal-SessionId", service_->session_id().toUtf8()); @@ -252,7 +252,7 @@ void TidalCoverProvider::HandleSearchReply(QNetworkReply *reply, const int id) { << qMakePair(QStringLiteral("750x750"), QSize(750, 750)) << qMakePair(QStringLiteral("640x640"), QSize(640, 640)); for (const QPair &cover_size : cover_sizes) { - QUrl cover_url(QStringLiteral("%1/images/%2/%3.jpg").arg(TidalService::kResourcesUrl, cover, cover_size.first)); + QUrl cover_url(QStringLiteral("%1/images/%2/%3.jpg").arg(QLatin1String(TidalService::kResourcesUrl), cover).arg(cover_size.first)); cover_result.image_url = cover_url; cover_result.image_size = cover_size.second; results << cover_result; diff --git a/src/device/cddalister.cpp b/src/device/cddalister.cpp index 77e44f626a..9318986625 100644 --- a/src/device/cddalister.cpp +++ b/src/device/cddalister.cpp @@ -51,7 +51,7 @@ QString CddaLister::DeviceManufacturer(const QString &id) { cdio_hwinfo_t cd_info; if (cdio_get_hwinfo(cdio, &cd_info)) { cdio_destroy(cdio); - return QString(cd_info.psz_vendor); + return QString::fromUtf8(cd_info.psz_vendor); } cdio_destroy(cdio); return QString(); @@ -64,7 +64,7 @@ QString CddaLister::DeviceModel(const QString &id) { cdio_hwinfo_t cd_info; if (cdio_get_hwinfo(cdio, &cd_info)) { cdio_destroy(cdio); - return QString(cd_info.psz_model); + return QString::fromUtf8(cd_info.psz_model); } cdio_destroy(cdio); return QString(); @@ -85,15 +85,15 @@ QString CddaLister::MakeFriendlyName(const QString &id) { cdio_hwinfo_t cd_info; if (cdio_get_hwinfo(cdio, &cd_info)) { cdio_destroy(cdio); - return QString(cd_info.psz_model); + return QString::fromUtf8(cd_info.psz_model); } cdio_destroy(cdio); - return QStringLiteral("CD (") + id + ")"; + return QStringLiteral("CD (") + id + QStringLiteral(")"); } QList CddaLister::MakeDeviceUrls(const QString &id) { - return QList() << QUrl("cdda://" + id); + return QList() << QUrl(QStringLiteral("cdda://") + id); } void CddaLister::UnmountDevice(const QString &id) { @@ -116,7 +116,7 @@ bool CddaLister::Init() { return false; } for (; *devices != nullptr; ++devices) { - QString device(*devices); + QString device = QString::fromUtf8(*devices); QFileInfo device_info(device); if (device_info.isSymLink()) { device = device_info.symLinkTarget(); diff --git a/src/device/cddasongloader.cpp b/src/device/cddasongloader.cpp index 75c2235e8d..2793b07df5 100644 --- a/src/device/cddasongloader.cpp +++ b/src/device/cddasongloader.cpp @@ -82,7 +82,7 @@ void CddaSongLoader::LoadSongs() { GError *error = nullptr; cdda_ = gst_element_make_from_uri(GST_URI_SRC, "cdda://", nullptr, &error); if (error) { - Error(QStringLiteral("%1: %2").arg(error->code).arg(error->message)); + Error(QStringLiteral("%1: %2").arg(error->code).arg(QString::fromUtf8(error->message))); } if (!cdda_) return; @@ -199,7 +199,7 @@ void CddaSongLoader::LoadSongs() { gst_message_parse_tag(msg_tag, &tags); char *string_mb = nullptr; if (gst_tag_list_get_string(tags, GST_TAG_CDDA_MUSICBRAINZ_DISCID, &string_mb)) { - QString musicbrainz_discid(string_mb); + QString musicbrainz_discid = QString::fromUtf8(string_mb); qLog(Info) << "MusicBrainz discid: " << musicbrainz_discid; MusicBrainzClient *musicbrainz_client = new MusicBrainzClient(network_); diff --git a/src/device/connecteddevice.cpp b/src/device/connecteddevice.cpp index 134e500164..fdd14403b0 100644 --- a/src/device/connecteddevice.cpp +++ b/src/device/connecteddevice.cpp @@ -60,7 +60,7 @@ ConnectedDevice::ConnectedDevice(const QUrl &url, DeviceLister *lister, const QS backend_->moveToThread(app_->database()->thread()); qLog(Debug) << &*backend_ << "for device" << unique_id_ << "moved to thread" << app_->database()->thread(); - if (url_.scheme() != "cdda") { + if (url_.scheme() != QStringLiteral("cdda")) { QObject::connect(&*backend_, &CollectionBackend::TotalSongCountUpdated, this, &ConnectedDevice::BackendTotalSongCountUpdated); } diff --git a/src/device/devicedatabasebackend.cpp b/src/device/devicedatabasebackend.cpp index de93c20838..2e30ab400f 100644 --- a/src/device/devicedatabasebackend.cpp +++ b/src/device/devicedatabasebackend.cpp @@ -219,13 +219,13 @@ void DeviceDatabaseBackend::SetDeviceOptions(const int id, const QString &friend QSqlDatabase db(db_->Connect()); SqlQuery q(db); - q.prepare( + q.prepare(QStringLiteral( "UPDATE devices" " SET friendly_name=:friendly_name," " icon=:icon_name," " transcode_mode=:transcode_mode," " transcode_format=:transcode_format" - " WHERE ROWID=:id"); + " WHERE ROWID=:id")); q.BindValue(QStringLiteral(":friendly_name"), friendly_name); q.BindValue(QStringLiteral(":icon_name"), icon_name); q.BindValue(QStringLiteral(":transcode_mode"), static_cast(mode)); diff --git a/src/device/deviceinfo.cpp b/src/device/deviceinfo.cpp index 6d08981c1a..aee700a746 100644 --- a/src/device/deviceinfo.cpp +++ b/src/device/deviceinfo.cpp @@ -64,7 +64,7 @@ void DeviceInfo::InitFromDb(const DeviceDatabaseBackend::Device &dev) { transcode_format_ = dev.transcode_format_; icon_name_ = dev.icon_name_; - QStringList unique_ids = dev.unique_id_.split(','); + QStringList unique_ids = dev.unique_id_.split(QLatin1Char(',')); for (const QString &id : unique_ids) { backends_ << Backend(nullptr, id); } diff --git a/src/device/devicelister.cpp b/src/device/devicelister.cpp index 9ffa31b0b8..e52072b4cf 100644 --- a/src/device/devicelister.cpp +++ b/src/device/devicelister.cpp @@ -223,9 +223,9 @@ QUrl DeviceLister::MakeUrlFromLocalPath(const QString &path) const { } bool DeviceLister::IsIpod(const QString &path) const { - return QFile::exists(path + "/iTunes_Control") || - QFile::exists(path + "/iPod_Control") || - QFile::exists(path + "/iTunes/iTunes_Control"); + return QFile::exists(path + QStringLiteral("/iTunes_Control")) || + QFile::exists(path + QStringLiteral("/iPod_Control")) || + QFile::exists(path + QStringLiteral("/iTunes/iTunes_Control")); } QVariantList DeviceLister::GuessIconForPath(const QString &path) { @@ -239,7 +239,7 @@ QVariantList DeviceLister::GuessIconForPath(const QString &path) { const Itdb_IpodInfo *info = itdb_device_get_ipod_info(device); if (info->ipod_model == ITDB_IPOD_MODEL_INVALID) { - ret << "device-ipod"; + ret << QStringLiteral("device-ipod"); } else { QString model = GetIpodModel(info->ipod_model); @@ -255,7 +255,7 @@ QVariantList DeviceLister::GuessIconForPath(const QString &path) { } if (ret.isEmpty()) { - ret << "device-ipod"; + ret << QStringLiteral("device-ipod"); } } @@ -275,7 +275,7 @@ QVariantList DeviceLister::GuessIconForModel(const QString &vendor, const QStrin QVariantList ret; if (vendor.startsWith(QLatin1String("Google")) && model.contains(QLatin1String("Nexus"))) { - ret << "phone-google-nexus-one"; + ret << QStringLiteral("phone-google-nexus-one"); } return ret; diff --git a/src/device/devicemanager.cpp b/src/device/devicemanager.cpp index f20e7a46df..2b83fb3b2f 100644 --- a/src/device/devicemanager.cpp +++ b/src/device/devicemanager.cpp @@ -245,7 +245,7 @@ void DeviceManager::LoadAllDevices() { void DeviceManager::AddDeviceFromDB(DeviceInfo *info) { - QStringList icon_names = info->icon_name_.split(','); + QStringList icon_names = info->icon_name_.split(QLatin1Char(',')); QVariantList icons; icons.reserve(icon_names.count()); for (const QString &icon_name : icon_names) { @@ -604,17 +604,17 @@ SharedPtr DeviceManager::Connect(DeviceInfo *info) { // If we get here it means that this URL scheme wasn't supported. // If it was "ipod" or "mtp" then the user compiled out support and the device won't work properly. - if (url.scheme() == "mtp" || url.scheme() == "gphoto2") { + if (url.scheme() == QStringLiteral("mtp") || url.scheme() == QStringLiteral("gphoto2")) { if (QMessageBox::critical(nullptr, tr("This device will not work properly"), - tr("This is an MTP device, but you compiled Strawberry without libmtp support.") + " " + + tr("This is an MTP device, but you compiled Strawberry without libmtp support.") + QStringLiteral(" ") + tr("If you continue, this device will work slowly and songs copied to it may not work."), QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort) return ret; } - if (url.scheme() == "ipod") { + if (url.scheme() == QStringLiteral("ipod")) { if (QMessageBox::critical(nullptr, tr("This device will not work properly"), - tr("This is an iPod, but you compiled Strawberry without libgpod support.") + " " + + tr("This is an iPod, but you compiled Strawberry without libgpod support.") + QStringLiteral(" ") + tr("If you continue, this device will work slowly and songs copied to it may not work."), QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort) return ret; diff --git a/src/device/giolister.cpp b/src/device/giolister.cpp index c20f9a9c19..b2efb3f24b 100644 --- a/src/device/giolister.cpp +++ b/src/device/giolister.cpp @@ -69,7 +69,7 @@ bool GioLister::DeviceInfo::is_suitable() const { if (filesystem_type.isEmpty()) return true; - return filesystem_type != "udf" && filesystem_type != "smb" && filesystem_type != "cifs" && filesystem_type != "ssh" && filesystem_type != "isofs"; + return filesystem_type != QStringLiteral("udf") && filesystem_type != QStringLiteral("smb") && filesystem_type != QStringLiteral("cifs") && filesystem_type != QStringLiteral("ssh") && filesystem_type != QStringLiteral("isofs"); } @@ -189,9 +189,9 @@ QVariantMap GioLister::DeviceHardwareInfo(const QString &id) { if (!devices_.contains(id)) return ret; const DeviceInfo &info = devices_[id]; - ret[QT_TR_NOOP("Mount point")] = info.mount_path; - ret[QT_TR_NOOP("Device")] = info.volume_unix_device; - ret[QT_TR_NOOP("URI")] = info.mount_uri; + ret[QT_TR_NOOP(QStringLiteral("Mount point"))] = info.mount_path; + ret[QT_TR_NOOP(QStringLiteral("Device"))] = info.volume_unix_device; + ret[QT_TR_NOOP(QStringLiteral("URI"))] = info.mount_uri; return ret; } @@ -503,7 +503,7 @@ void GioLister::DeviceInfo::ReadMountInfo(GMount *mount) { // Query the file's info for a filesystem ID // Only afc devices (that I know of) give reliably unique IDs - if (filesystem_type == "afc") { + if (filesystem_type == QStringLiteral("afc")) { error = nullptr; info = g_file_query_info(root, G_FILE_ATTRIBUTE_ID_FILESYSTEM, G_FILE_QUERY_INFO_NONE, nullptr, &error); if (error) { @@ -528,7 +528,7 @@ void GioLister::DeviceInfo::ReadVolumeInfo(GVolume *volume) { GFile *root = g_volume_get_activation_root(volume); if (root) { - volume_root_uri = g_file_get_uri(root); + volume_root_uri = QString::fromUtf8(g_file_get_uri(root)); g_object_unref(root); } diff --git a/src/device/gpoddevice.cpp b/src/device/gpoddevice.cpp index 87efc20459..621d16fff0 100644 --- a/src/device/gpoddevice.cpp +++ b/src/device/gpoddevice.cpp @@ -195,12 +195,12 @@ bool GPodDevice::CopyToStorage(const CopyJob &job, QString &error_text) { bool result = false; if (!job.cover_image_.isNull()) { #ifdef Q_OS_LINUX - QString temp_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/organize"; + QString temp_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/organize"); #else QString temp_path = QStandardPaths::writableLocation(QStandardPaths::TempLocation); #endif if (!QDir(temp_path).exists()) QDir().mkpath(temp_path); - SharedPtr cover_file = make_shared(temp_path + "/track-albumcover-XXXXXX.jpg"); + SharedPtr cover_file = make_shared(temp_path + QStringLiteral("/track-albumcover-XXXXXX.jpg")); cover_file->setAutoRemove(true); if (cover_file->open()) { cover_file->close(); @@ -281,7 +281,7 @@ bool GPodDevice::WriteDatabase(QString &error_text) { cover_files_.clear(); if (!success) { if (error) { - error_text = tr("Writing database failed: %1").arg(error->message); + error_text = tr("Writing database failed: %1").arg(QString::fromUtf8(error->message)); g_error_free(error); } else { @@ -327,17 +327,17 @@ bool GPodDevice::RemoveTrackFromITunesDb(const QString &path, const QString &rel QString ipod_filename = path; if (!relative_to.isEmpty() && path.startsWith(relative_to)) { - ipod_filename.remove(0, relative_to.length() + (relative_to.endsWith('/') ? -1 : 0)); + ipod_filename.remove(0, relative_to.length() + (relative_to.endsWith(QLatin1Char('/')) ? -1 : 0)); } - ipod_filename.replace('/', ':'); + ipod_filename.replace(QLatin1Char('/'), QLatin1Char(':')); // Find the track in the itdb, identify it by its filename Itdb_Track *track = nullptr; for (GList *tracks = db_->tracks; tracks != nullptr; tracks = tracks->next) { Itdb_Track *t = static_cast(tracks->data); - if (t->ipod_path == ipod_filename) { + if (QString::fromUtf8(t->ipod_path) == ipod_filename) { track = t; break; } diff --git a/src/device/mtpdevice.cpp b/src/device/mtpdevice.cpp index a3ecf06d89..48307ff8b5 100644 --- a/src/device/mtpdevice.cpp +++ b/src/device/mtpdevice.cpp @@ -226,7 +226,7 @@ bool MtpDevice::DeleteFromStorage(const DeleteJob &job) { // Extract the ID from the song's URL QString filename = job.metadata_.url().path(); - filename.remove('/'); + filename.remove(QLatin1Char('/')); bool ok = false; uint32_t id = filename.toUInt(&ok); diff --git a/src/device/udisks2lister.cpp b/src/device/udisks2lister.cpp index d6f268bb5e..471121296a 100644 --- a/src/device/udisks2lister.cpp +++ b/src/device/udisks2lister.cpp @@ -57,6 +57,10 @@ using std::make_unique; using std::make_shared; +namespace { +constexpr char kUDisks2Service[] = "org.freedesktop.UDisks2"; +} + Udisks2Lister::Udisks2Lister(QObject *parent) : DeviceLister(parent) {} Udisks2Lister::~Udisks2Lister() = default; @@ -116,11 +120,11 @@ QVariantMap Udisks2Lister::DeviceHardwareInfo(const QString &id) { QVariantMap result; const PartitionData &data = device_data_[id]; - result[QT_TR_NOOP("D-Bus path")] = data.dbus_path; - result[QT_TR_NOOP("Serial number")] = data.serial; - result[QT_TR_NOOP("Mount points")] = data.mount_paths.join(QStringLiteral(", ")); - result[QT_TR_NOOP("Partition label")] = data.label; - result[QT_TR_NOOP("UUID")] = data.uuid; + result[QT_TR_NOOP(QStringLiteral("D-Bus path"))] = data.dbus_path; + result[QT_TR_NOOP(QStringLiteral("Serial number"))] = data.serial; + result[QT_TR_NOOP(QStringLiteral("Mount points"))] = data.mount_paths.join(QStringLiteral(", ")); + result[QT_TR_NOOP(QStringLiteral("Partition label"))] = data.label; + result[QT_TR_NOOP(QStringLiteral("UUID"))] = data.uuid; return result; @@ -149,7 +153,7 @@ void Udisks2Lister::UnmountDevice(const QString &id) { QReadLocker locker(&device_data_lock_); if (!device_data_.contains(id)) return; - OrgFreedesktopUDisks2FilesystemInterface filesystem(udisks2_service_, device_data_[id].dbus_path, QDBusConnection::systemBus()); + OrgFreedesktopUDisks2FilesystemInterface filesystem(QLatin1String(kUDisks2Service), device_data_[id].dbus_path, QDBusConnection::systemBus()); if (filesystem.isValid()) { auto unmount_result = filesystem.Unmount(QVariantMap()); @@ -160,7 +164,7 @@ void Udisks2Lister::UnmountDevice(const QString &id) { return; } - OrgFreedesktopUDisks2DriveInterface drive(udisks2_service_, device_data_[id].dbus_drive_path, QDBusConnection::systemBus()); + OrgFreedesktopUDisks2DriveInterface drive(QLatin1String(kUDisks2Service), device_data_[id].dbus_drive_path, QDBusConnection::systemBus()); if (drive.isValid()) { auto eject_result = drive.Eject(QVariantMap()); @@ -185,7 +189,7 @@ void Udisks2Lister::UpdateDeviceFreeSpace(const QString &id) { bool Udisks2Lister::Init() { - udisks2_interface_ = make_unique(udisks2_service_, "/org/freedesktop/UDisks2", QDBusConnection::systemBus()); + udisks2_interface_ = make_unique(QLatin1String(kUDisks2Service), QStringLiteral("/org/freedesktop/UDisks2"), QDBusConnection::systemBus()); QDBusPendingReply reply = udisks2_interface_->GetManagedObjects(); reply.waitForFinished(); @@ -222,17 +226,17 @@ void Udisks2Lister::DBusInterfaceAdded(const QDBusObjectPath &path, const Interf for (auto interface = interfaces.constBegin(); interface != interfaces.constEnd(); ++interface) { - if (interface.key() != "org.freedesktop.UDisks2.Job") continue; + if (interface.key() != QStringLiteral("org.freedesktop.UDisks2.Job")) continue; - SharedPtr job = make_shared(udisks2_service_, path.path(), QDBusConnection::systemBus()); + SharedPtr job = make_shared(QLatin1String(kUDisks2Service), path.path(), QDBusConnection::systemBus()); if (!job->isValid()) continue; bool is_mount_job = false; - if (job->operation() == "filesystem-mount") { + if (job->operation() == QStringLiteral("filesystem-mount")) { is_mount_job = true; } - else if (job->operation() == "filesystem-unmount") { + else if (job->operation() == QStringLiteral("filesystem-unmount")) { is_mount_job = false; } else { @@ -365,11 +369,11 @@ void Udisks2Lister::HandleFinishedUnmountJob(const PartitionData &partition_data Udisks2Lister::PartitionData Udisks2Lister::ReadPartitionData(const QDBusObjectPath &path) { PartitionData result; - OrgFreedesktopUDisks2FilesystemInterface filesystem(udisks2_service_, path.path(), QDBusConnection::systemBus()); - OrgFreedesktopUDisks2BlockInterface block(udisks2_service_, path.path(), QDBusConnection::systemBus()); + OrgFreedesktopUDisks2FilesystemInterface filesystem(QLatin1String(kUDisks2Service), path.path(), QDBusConnection::systemBus()); + OrgFreedesktopUDisks2BlockInterface block(QLatin1String(kUDisks2Service), path.path(), QDBusConnection::systemBus()); if (filesystem.isValid() && block.isValid() && !filesystem.mountPoints().empty()) { - OrgFreedesktopUDisks2DriveInterface drive(udisks2_service_, block.drive().path(), QDBusConnection::systemBus()); + OrgFreedesktopUDisks2DriveInterface drive(QLatin1String(kUDisks2Service), block.drive().path(), QDBusConnection::systemBus()); if (drive.isValid() && drive.mediaRemovable()) { result.dbus_path = path.path(); @@ -384,18 +388,14 @@ Udisks2Lister::PartitionData Udisks2Lister::ReadPartitionData(const QDBusObjectP result.capacity = drive.size(); if (result.label.isEmpty()) { - result.friendly_name = result.model + " " + result.uuid; + result.friendly_name = result.model + QStringLiteral(" ") + result.uuid; } else { result.friendly_name = result.label; } for (const QByteArray &p : filesystem.mountPoints()) { -#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) // Workaround a bytearray to string conversion issue with Qt 6 - QString mountpoint = QByteArray(p.data(), static_cast(strlen(p.data()))); -#else - QString mountpoint = p; -#endif + const QString mountpoint = QString::fromUtf8(p.data(), p.size()); result.mount_paths.push_back(mountpoint); } diff --git a/src/device/udisks2lister.h b/src/device/udisks2lister.h index f7e64a4dc9..84e0d9d31d 100644 --- a/src/device/udisks2lister.h +++ b/src/device/udisks2lister.h @@ -124,8 +124,6 @@ class Udisks2Lister : public DeviceLister { private: ScopedPtr udisks2_interface_; - - static constexpr char udisks2_service_[] = "org.freedesktop.UDisks2"; }; #endif // UDISKS2LISTER_H diff --git a/src/dialogs/about.cpp b/src/dialogs/about.cpp index 8963f8baae..61c6d3402a 100644 --- a/src/dialogs/about.cpp +++ b/src/dialogs/about.cpp @@ -142,7 +142,7 @@ QString About::ContributorsHtml() const { ret += tr("Author and maintainer"); ret += QLatin1String(""); for (const Person &person : strawberry_authors_) { - ret += "
" + PersonToHtml(person); + ret += QStringLiteral("
") + PersonToHtml(person); } ret += QStringLiteral("

"); @@ -151,7 +151,7 @@ QString About::ContributorsHtml() const { ret += tr("Contributors"); ret += QLatin1String(""); for (const Person &person : strawberry_contributors_) { - ret += "
" + PersonToHtml(person); + ret += QStringLiteral("
") + PersonToHtml(person); } ret += QStringLiteral("

"); @@ -160,7 +160,7 @@ QString About::ContributorsHtml() const { ret += tr("Clementine authors"); ret += QLatin1String(""); for (const Person &person : clementine_authors_) { - ret += "
" + PersonToHtml(person); + ret += QStringLiteral("
") + PersonToHtml(person); } ret += QStringLiteral("

"); @@ -169,7 +169,7 @@ QString About::ContributorsHtml() const { ret += tr("Clementine contributors"); ret += QLatin1String(""); for (const Person &person : clementine_contributors_) { - ret += "
" + PersonToHtml(person); + ret += QStringLiteral("
") + PersonToHtml(person); } ret += QStringLiteral("

"); @@ -178,7 +178,7 @@ QString About::ContributorsHtml() const { ret += tr("Thanks to"); ret += QLatin1String(""); for (const Person &person : strawberry_thanks_) { - ret += "
" + PersonToHtml(person); + ret += QStringLiteral("
") + PersonToHtml(person); } ret += QStringLiteral("

"); diff --git a/src/dialogs/addstreamdialog.cpp b/src/dialogs/addstreamdialog.cpp index 27b762cd05..94ea6c7d3b 100644 --- a/src/dialogs/addstreamdialog.cpp +++ b/src/dialogs/addstreamdialog.cpp @@ -28,6 +28,8 @@ #include #include +#include "core/settings.h" + AddStreamDialog::AddStreamDialog(QWidget *parent) : QDialog(parent), ui_(new Ui_AddStreamDialog) { ui_->setupUi(this); diff --git a/src/dialogs/console.cpp b/src/dialogs/console.cpp index a58dc68148..2510d84b4d 100644 --- a/src/dialogs/console.cpp +++ b/src/dialogs/console.cpp @@ -69,7 +69,7 @@ void Console::RunQuery() { return; } - ui_.output->append("> " + query.executedQuery() + ""); + ui_.output->append(QStringLiteral("> ") + query.executedQuery() + QStringLiteral("")); while (query.next() && query.isValid()) { QSqlRecord record = query.record(); diff --git a/src/dialogs/edittagdialog.cpp b/src/dialogs/edittagdialog.cpp index bf64311185..8b3bc095d6 100644 --- a/src/dialogs/edittagdialog.cpp +++ b/src/dialogs/edittagdialog.cpp @@ -73,6 +73,7 @@ #include "core/iconloader.h" #include "core/logging.h" #include "core/tagreaderclient.h" +#include "core/settings.h" #include "utilities/strutils.h" #include "utilities/timeutils.h" #include "utilities/imageutils.h" @@ -140,7 +141,7 @@ EditTagDialog::EditTagDialog(Application *app, QWidget *parent) ui_->loading_label->hide(); ui_->label_lyrics->hide(); - ui_->fetch_tag->setIcon(QPixmap::fromImage(QImage(":/pictures/musicbrainz.png"))); + ui_->fetch_tag->setIcon(QPixmap::fromImage(QImage(QStringLiteral(":/pictures/musicbrainz.png")))); #ifdef HAVE_MUSICBRAINZ ui_->fetch_tag->setEnabled(true); #else @@ -271,7 +272,7 @@ void EditTagDialog::showEvent(QShowEvent *e) { resize(width(), sizeHint().height()); // Restore the tab that was current last time. - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); if (s.contains("geometry")) { restoreGeometry(s.value("geometry").toByteArray()); @@ -292,7 +293,7 @@ void EditTagDialog::showEvent(QShowEvent *e) { void EditTagDialog::hideEvent(QHideEvent *e) { // Save the current tab - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("geometry", saveGeometry()); s.setValue("current_tab", ui_->tab_widget->currentIndex()); @@ -305,7 +306,7 @@ void EditTagDialog::hideEvent(QHideEvent *e) { void EditTagDialog::accept() { // Show the loading indicator - if (!SetLoading(tr("Saving tracks") + "...")) return; + if (!SetLoading(tr("Saving tracks") + QStringLiteral("..."))) return; SaveData(); @@ -410,7 +411,7 @@ QList EditTagDialog::LoadData(const SongList &songs) { void EditTagDialog::SetSongs(const SongList &s, const PlaylistItemPtrList &items) { // Show the loading indicator - if (!SetLoading(tr("Loading tracks") + "...")) return; + if (!SetLoading(tr("Loading tracks") + QStringLiteral("..."))) return; data_.clear(); playlist_items_ = items; @@ -472,21 +473,21 @@ void EditTagDialog::SetSongListVisibility(bool visible) { QVariant EditTagDialog::Data::value(const Song &song, const QString &id) { - if (id == "title") return song.title(); - if (id == "artist") return song.artist(); - if (id == "album") return song.album(); - if (id == "albumartist") return song.albumartist(); - if (id == "composer") return song.composer(); - if (id == "performer") return song.performer(); - if (id == "grouping") return song.grouping(); - if (id == "genre") return song.genre(); - if (id == "comment") return song.comment(); - if (id == "lyrics") return song.lyrics(); - if (id == "track") return song.track(); - if (id == "disc") return song.disc(); - if (id == "year") return song.year(); - if (id == "compilation") return song.compilation(); - if (id == "rating") { return song.rating(); } + if (id == QStringLiteral("title")) return song.title(); + if (id == QStringLiteral("artist")) return song.artist(); + if (id == QStringLiteral("album")) return song.album(); + if (id == QStringLiteral("albumartist")) return song.albumartist(); + if (id == QStringLiteral("composer")) return song.composer(); + if (id == QStringLiteral("performer")) return song.performer(); + if (id == QStringLiteral("grouping")) return song.grouping(); + if (id == QStringLiteral("genre")) return song.genre(); + if (id == QStringLiteral("comment")) return song.comment(); + if (id == QStringLiteral("lyrics")) return song.lyrics(); + if (id == QStringLiteral("track")) return song.track(); + if (id == QStringLiteral("disc")) return song.disc(); + if (id == QStringLiteral("year")) return song.year(); + if (id == QStringLiteral("compilation")) return song.compilation(); + if (id == QStringLiteral("rating")) { return song.rating(); } qLog(Warning) << "Unknown ID" << id; return QVariant(); @@ -494,21 +495,21 @@ QVariant EditTagDialog::Data::value(const Song &song, const QString &id) { void EditTagDialog::Data::set_value(const QString &id, const QVariant &value) { - if (id == "title") current_.set_title(value.toString()); - else if (id == "artist") current_.set_artist(value.toString()); - else if (id == "album") current_.set_album(value.toString()); - else if (id == "albumartist") current_.set_albumartist(value.toString()); - else if (id == "composer") current_.set_composer(value.toString()); - else if (id == "performer") current_.set_performer(value.toString()); - else if (id == "grouping") current_.set_grouping(value.toString()); - else if (id == "genre") current_.set_genre(value.toString()); - else if (id == "comment") current_.set_comment(value.toString()); - else if (id == "lyrics") current_.set_lyrics(value.toString()); - else if (id == "track") current_.set_track(value.toInt()); - else if (id == "disc") current_.set_disc(value.toInt()); - else if (id == "year") current_.set_year(value.toInt()); - else if (id == "compilation") current_.set_compilation(value.toBool()); - else if (id == "rating") { current_.set_rating(value.toFloat()); } + if (id == QStringLiteral("title")) current_.set_title(value.toString()); + else if (id == QStringLiteral("artist")) current_.set_artist(value.toString()); + else if (id == QStringLiteral("album")) current_.set_album(value.toString()); + else if (id == QStringLiteral("albumartist")) current_.set_albumartist(value.toString()); + else if (id == QStringLiteral("composer")) current_.set_composer(value.toString()); + else if (id == QStringLiteral("performer")) current_.set_performer(value.toString()); + else if (id == QStringLiteral("grouping")) current_.set_grouping(value.toString()); + else if (id == QStringLiteral("genre")) current_.set_genre(value.toString()); + else if (id == QStringLiteral("comment")) current_.set_comment(value.toString()); + else if (id == QStringLiteral("lyrics")) current_.set_lyrics(value.toString()); + else if (id == QStringLiteral("track")) current_.set_track(value.toInt()); + else if (id == QStringLiteral("disc")) current_.set_disc(value.toInt()); + else if (id == QStringLiteral("year")) current_.set_year(value.toInt()); + else if (id == QStringLiteral("compilation")) current_.set_compilation(value.toBool()); + else if (id == QStringLiteral("rating")) { current_.set_rating(value.toFloat()); } else qLog(Warning) << "Unknown ID" << id; } @@ -687,7 +688,7 @@ void EditTagDialog::SelectionChanged() { QString summary; if (indexes.count() == 1) { - summary += "

" + first_song.PrettyTitleWithArtist().toHtmlEscaped() + "

"; + summary += QStringLiteral("

") + first_song.PrettyTitleWithArtist().toHtmlEscaped() + QStringLiteral("

"); } else { summary += QLatin1String("

"); @@ -701,7 +702,7 @@ void EditTagDialog::SelectionChanged() { if ((art_different && first_cover_action != UpdateCoverAction::New) || action_different) { tags_cover_art_id_ = -1; // Cancels any pending art load. ui_->tags_art->clear(); - ui_->tags_art->setText(kArtDifferentHintText); + ui_->tags_art->setText(QLatin1String(kArtDifferentHintText)); album_cover_choice_controller_->show_cover_action()->setEnabled(false); album_cover_choice_controller_->cover_to_file_action()->setEnabled(false); album_cover_choice_controller_->cover_from_file_action()->setEnabled(enable_change_art); @@ -761,7 +762,7 @@ void EditTagDialog::UpdateUI(const QModelIndexList &indexes) { } void EditTagDialog::SetText(QLabel *label, const int value, const QString &suffix, const QString &def) { - label->setText(value <= 0 ? def : (QString::number(value) + " " + suffix)); + label->setText(value <= 0 ? def : (QString::number(value) + QStringLiteral(" ") + suffix)); } void EditTagDialog::SetDate(QLabel *label, const uint time) { @@ -783,7 +784,7 @@ void EditTagDialog::UpdateSummaryTab(const Song &song) { cover_options.device_pixel_ratio = devicePixelRatioF(); summary_cover_art_id_ = app_->album_cover_loader()->LoadImageAsync(cover_options, song); - ui_->summary->setText("

" + song.PrettyTitleWithArtist().toHtmlEscaped() + "

"); + ui_->summary->setText(QStringLiteral("

") + song.PrettyTitleWithArtist().toHtmlEscaped() + QStringLiteral("

")); ui_->length->setText(Utilities::PrettyTimeNanosec(song.length_nanosec())); @@ -1206,7 +1207,7 @@ void EditTagDialog::SaveData() { cover_url = ref.cover_result_.cover_url; } else { - QString cover_hash = CoverUtils::Sha1CoverHash(ref.current_.effective_albumartist(), ref.current_.album()).toHex(); + QString cover_hash = QString::fromUtf8(CoverUtils::Sha1CoverHash(ref.current_.effective_albumartist(), ref.current_.album()).toHex()); if (cover_urls.contains(cover_hash)) { cover_url = cover_urls[cover_hash]; } diff --git a/src/dialogs/messagedialog.cpp b/src/dialogs/messagedialog.cpp index 09735a6fd2..1084e681ae 100644 --- a/src/dialogs/messagedialog.cpp +++ b/src/dialogs/messagedialog.cpp @@ -30,6 +30,7 @@ #include #include +#include "core/settings.h" #include "utilities/screenutils.h" #include "messagedialog.h" #include "ui_messagedialog.h" @@ -77,7 +78,7 @@ void MessageDialog::ShowMessage(const QString &title, const QString &message, co void MessageDialog::DoNotShowMessageAgain() { if (!settings_group_.isEmpty() && !do_not_show_message_again_.isEmpty()) { - QSettings s; + Settings s; s.beginGroup(settings_group_); s.setValue(do_not_show_message_again_, ui_->checkbox_do_not_show_message_again->isChecked()); s.endGroup(); diff --git a/src/dialogs/saveplaylistsdialog.cpp b/src/dialogs/saveplaylistsdialog.cpp index 2e07114644..18699cdff2 100644 --- a/src/dialogs/saveplaylistsdialog.cpp +++ b/src/dialogs/saveplaylistsdialog.cpp @@ -29,13 +29,14 @@ #include "saveplaylistsdialog.h" #include "ui_saveplaylistsdialog.h" +#include "core/settings.h" #include "playlist/playlist.h" SavePlaylistsDialog::SavePlaylistsDialog(const QStringList &types, const QString &default_extension, QWidget *parent) : QDialog(parent), ui_(new Ui_SavePlaylistsDialog) { ui_->setupUi(this); - QSettings s; + Settings s; s.beginGroup(Playlist::kSettingsGroup); QString last_save_path = s.value("last_save_all_path", QDir::homePath()).toString(); QString last_save_extension = s.value("last_save_all_extension", default_extension).toString(); @@ -79,7 +80,7 @@ void SavePlaylistsDialog::accept() { return; } - QSettings s; + Settings s; s.beginGroup(Playlist::kSettingsGroup); s.setValue("last_save_all_path", path); s.setValue("last_save_all_extension", ui_->combobox_type->currentText()); diff --git a/src/dialogs/snapdialog.cpp b/src/dialogs/snapdialog.cpp index 67b50b0f07..340a8d9b14 100644 --- a/src/dialogs/snapdialog.cpp +++ b/src/dialogs/snapdialog.cpp @@ -86,7 +86,7 @@ SnapDialog::SnapDialog(QWidget *parent) : MessageDialog(parent) { ui_->label_text->adjustSize(); adjustSize(); - settings_group_ = MainWindow::kSettingsGroup; + settings_group_ = QLatin1String(MainWindow::kSettingsGroup); do_not_show_message_again_ = QStringLiteral("ignore_snap"); if (parent) { diff --git a/src/dialogs/trackselectiondialog.cpp b/src/dialogs/trackselectiondialog.cpp index 5f51daa2b3..279ad8fe34 100644 --- a/src/dialogs/trackselectiondialog.cpp +++ b/src/dialogs/trackselectiondialog.cpp @@ -176,7 +176,7 @@ void TrackSelectionDialog::UpdateStack() { if (tag_data.pending_) { ui_->stack->setCurrentWidget(ui_->loading_page); - ui_->progress->set_text(tag_data.progress_string_ + "..."); + ui_->progress->set_text(tag_data.progress_string_ + QStringLiteral("...")); return; } else if (tag_data.results_.isEmpty()) { @@ -286,7 +286,7 @@ void TrackSelectionDialog::SaveData(const QList &data) { void TrackSelectionDialog::accept() { if (save_on_close_) { - SetLoading(tr("Saving tracks") + "..."); + SetLoading(tr("Saving tracks") + QStringLiteral("...")); // Save tags in the background QFuture future = QtConcurrent::run(&TrackSelectionDialog::SaveData, data_); diff --git a/src/engine/alsadevicefinder.cpp b/src/engine/alsadevicefinder.cpp index 58da7a27f3..e4819032a4 100644 --- a/src/engine/alsadevicefinder.cpp +++ b/src/engine/alsadevicefinder.cpp @@ -31,7 +31,7 @@ #include "alsadevicefinder.h" #include "enginedevice.h" -AlsaDeviceFinder::AlsaDeviceFinder() : DeviceFinder(QStringLiteral("alsa"), { "alsa", "alsasink" }) {} +AlsaDeviceFinder::AlsaDeviceFinder() : DeviceFinder(QStringLiteral("alsa"), { QStringLiteral("alsa"), QStringLiteral("alsasink") }) {} EngineDeviceList AlsaDeviceFinder::ListDevices() { @@ -91,7 +91,7 @@ EngineDeviceList AlsaDeviceFinder::ListDevices() { } EngineDevice device; - device.description = QStringLiteral("%1 %2").arg(snd_ctl_card_info_get_name(cardinfo), snd_pcm_info_get_name(pcminfo)); + device.description = QStringLiteral("%1 %2").arg(QString::fromUtf8(snd_ctl_card_info_get_name(cardinfo)), QString::fromUtf8(snd_pcm_info_get_name(pcminfo))); device.iconname = device.GuessIconName(); device.card = card; device.device = dev; diff --git a/src/engine/alsapcmdevicefinder.cpp b/src/engine/alsapcmdevicefinder.cpp index ebe5084d49..9bfa964c49 100644 --- a/src/engine/alsapcmdevicefinder.cpp +++ b/src/engine/alsapcmdevicefinder.cpp @@ -28,7 +28,7 @@ #include "alsapcmdevicefinder.h" #include "enginedevice.h" -AlsaPCMDeviceFinder::AlsaPCMDeviceFinder() : DeviceFinder(QStringLiteral("alsa"), { "alsa", "alsasink" }) {} +AlsaPCMDeviceFinder::AlsaPCMDeviceFinder() : DeviceFinder(QStringLiteral("alsa"), { QStringLiteral("alsa"), QStringLiteral("alsasink") }) {} EngineDeviceList AlsaPCMDeviceFinder::ListDevices() { @@ -45,22 +45,22 @@ EngineDeviceList AlsaPCMDeviceFinder::ListDevices() { char *hint_desc = snd_device_name_get_hint(*n, "DESC"); if (hint_io && hint_name && hint_desc && strcmp(hint_io, "Output") == 0) { - QString name(hint_name); + const QString name = QString::fromUtf8(hint_name); char *desc_last = hint_desc; QString description; for (char *desc_i = hint_desc; desc_i && *desc_i != '\0'; ++desc_i) { if (*desc_i == '\n') { *desc_i = '\0'; - if (!description.isEmpty()) description.append(' '); - description.append(desc_last); + if (!description.isEmpty()) description.append(QLatin1Char(' ')); + description.append(QString::fromUtf8(desc_last)); desc_last = desc_i + 1; } } if (desc_last) { - if (!description.isEmpty()) description.append(' '); - description.append(desc_last); + if (!description.isEmpty()) description.append(QLatin1Char(' ')); + description.append(QString::fromUtf8(desc_last)); } EngineDevice device; diff --git a/src/engine/chromaprinter.cpp b/src/engine/chromaprinter.cpp index fd81c5f1b7..ecc999429c 100644 --- a/src/engine/chromaprinter.cpp +++ b/src/engine/chromaprinter.cpp @@ -183,7 +183,7 @@ QString Chromaprinter::CreateFingerprint() { gst_element_set_state(pipeline, GST_STATE_NULL); gst_object_unref(pipeline); - return fingerprint; + return QString::fromUtf8(fingerprint); } diff --git a/src/engine/ebur128analysis.cpp b/src/engine/ebur128analysis.cpp index da71c08ac8..e804347767 100644 --- a/src/engine/ebur128analysis.cpp +++ b/src/engine/ebur128analysis.cpp @@ -208,7 +208,7 @@ class EBUR128AnalysisImpl { FrameFormat::FrameFormat(GstCaps *caps) : channels(0), channel_mask(0), samplerate(0) { GstStructure *structure = gst_caps_get_structure(caps, 0); - QString format_str = gst_structure_get_string(structure, "format"); + QString format_str = QString::fromUtf8(gst_structure_get_string(structure, "format")); gst_structure_get_int(structure, "rate", &samplerate); gst_structure_get_int(structure, "channels", &channels); const GValue *value = gst_structure_get_value(structure, "channel-mask"); @@ -216,16 +216,16 @@ FrameFormat::FrameFormat(GstCaps *caps) : channels(0), channel_mask(0), samplera channel_mask = gst_value_get_bitmask(value); } - if (format_str == "S16LE") { + if (format_str == QStringLiteral("S16LE")) { format = DataFormat::S16; } - else if (format_str == "S32LE") { + else if (format_str == QStringLiteral("S32LE")) { format = DataFormat::S32; } - else if (format_str == "F32LE") { + else if (format_str == QStringLiteral("F32LE")) { format = DataFormat::FP32; } - else if (format_str == "F64LE") { + else if (format_str == QStringLiteral("F64LE")) { format = DataFormat::FP64; } else { diff --git a/src/engine/enginebase.cpp b/src/engine/enginebase.cpp index 4019d357a4..38e44f4687 100644 --- a/src/engine/enginebase.cpp +++ b/src/engine/enginebase.cpp @@ -33,6 +33,7 @@ #include "utilities/envutils.h" #include "utilities/timeconstants.h" #include "core/networkproxyfactory.h" +#include "core/settings.h" #include "enginebase.h" #include "settings/backendsettingspage.h" #include "settings/networkproxysettingspage.h" @@ -161,7 +162,7 @@ void EngineBase::SetVolume(const uint volume) { void EngineBase::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(BackendSettingsPage::kSettingsGroup); diff --git a/src/engine/gstengine.cpp b/src/engine/gstengine.cpp index e220cdd690..7bd75afd19 100644 --- a/src/engine/gstengine.cpp +++ b/src/engine/gstengine.cpp @@ -416,22 +416,22 @@ EngineBase::OutputDetailsList GstEngine::GetOutputsList() const { GstElementFactory *factory = GST_ELEMENT_FACTORY(future->data); const QString metadata = QString::fromUtf8(gst_element_factory_get_metadata(factory, GST_ELEMENT_METADATA_KLASS)); const QString name = QString::fromUtf8(gst_plugin_feature_get_name(future->data)); - if (metadata.startsWith(QLatin1String("Sink/Audio"), Qt::CaseInsensitive) || name == "pipewiresink" || (metadata.startsWith(QLatin1String("Source/Audio"), Qt::CaseInsensitive) && name.contains(QLatin1String("sink")))) { + if (metadata.startsWith(QLatin1String("Sink/Audio"), Qt::CaseInsensitive) || name == QStringLiteral("pipewiresink") || (metadata.startsWith(QLatin1String("Source/Audio"), Qt::CaseInsensitive) && name.contains(QLatin1String("sink")))) { QString description = QString::fromUtf8(gst_element_factory_get_metadata(factory, GST_ELEMENT_METADATA_DESCRIPTION)); - if (name == "wasapi2sink" && description == "Stream audio to an audio capture device through WASAPI") { - description.append("2"); + if (name == QStringLiteral("wasapi2sink") && description == QStringLiteral("Stream audio to an audio capture device through WASAPI")) { + description.append(QLatin1Char('2')); } - else if (name == "pipewiresink" && description == "Send video to PipeWire") { + else if (name == QStringLiteral("pipewiresink") && description == QStringLiteral("Send video to PipeWire")) { description = QStringLiteral("Send audio to PipeWire"); } OutputDetails output; output.name = name; output.description = description; - if (output.name == kAutoSink) output.iconname = QStringLiteral("soundcard"); - else if (output.name == kALSASink || output.name == kOSS4Sink) output.iconname = QStringLiteral("alsa"); - else if (output.name == kJackAudioSink) output.iconname = QStringLiteral("jack"); - else if (output.name == kPulseSink) output.iconname = QStringLiteral("pulseaudio"); - else if (output.name == kA2DPSink || output.name == kAVDTPSink) output.iconname = QStringLiteral("bluetooth"); + if (output.name == QLatin1String(kAutoSink)) output.iconname = QStringLiteral("soundcard"); + else if (output.name == QLatin1String(kALSASink) || output.name == QLatin1String(kOSS4Sink)) output.iconname = QStringLiteral("alsa"); + else if (output.name == QLatin1String(kJackAudioSink)) output.iconname = QStringLiteral("jack"); + else if (output.name == QLatin1String(kPulseSink)) output.iconname = QStringLiteral("pulseaudio"); + else if (output.name == QLatin1String(kA2DPSink) || output.name == QLatin1String(kAVDTPSink)) output.iconname = QStringLiteral("bluetooth"); else output.iconname = QStringLiteral("soundcard"); outputs << output; } @@ -453,22 +453,22 @@ bool GstEngine::ValidOutput(const QString &output) { } bool GstEngine::CustomDeviceSupport(const QString &output) { - return (output == kALSASink || output == kOpenALSASink || output == kOSSSink || output == kOSS4Sink || output == kPulseSink || output == kA2DPSink || output == kAVDTPSink || output == kJackAudioSink); + return output == QLatin1String(kALSASink) || output == QLatin1String(kOpenALSASink) || output == QLatin1String(kOSSSink) || output == QLatin1String(kOSS4Sink) || output == QLatin1String(kPulseSink) || output == QLatin1String(kA2DPSink) || output == QLatin1String(kAVDTPSink) || output == QLatin1String(kJackAudioSink); } bool GstEngine::ALSADeviceSupport(const QString &output) { - return (output == kALSASink); + return output == QLatin1String(kALSASink); } bool GstEngine::ExclusiveModeSupport(const QString &output) { - return output == kWASAPISink; + return output == QLatin1String(kWASAPISink); } void GstEngine::ReloadSettings() { EngineBase::ReloadSettings(); - if (output_.isEmpty()) output_ = kAutoSink; + if (output_.isEmpty()) output_ = QLatin1String(kAutoSink); } @@ -722,20 +722,20 @@ QByteArray GstEngine::FixupUrl(const QUrl &url) { // QUrl::fromLocalFile does this when given a \\host\share\file path on Windows. // Munge it back into a path that gstreamer will recognise. if (url.isLocalFile() && !url.host().isEmpty()) { - QString str = "file:////" + url.host() + url.path(); + QString str = QStringLiteral("file:////") + url.host() + url.path(); uri = str.toUtf8(); } - else if (url.scheme() == "cdda") { + else if (url.scheme() == QStringLiteral("cdda")) { QString str; if (url.path().isEmpty()) { str = url.toString(); - str.remove(str.lastIndexOf(QChar('a')), 1); + str.remove(str.lastIndexOf(QLatin1Char('a')), 1); } else { // Currently, Gstreamer can't handle input CD devices inside cdda URL. // So we handle them ourselves: we extract the track number and re-create a URL with only cdda:// + the track number (which can be handled by Gstreamer). // We keep the device in mind, and we will set it later using SourceSetupCallback - QStringList path = url.path().split('/'); + QStringList path = url.path().split(QLatin1Char('/')); str = QStringLiteral("cdda://%1").arg(path.takeLast()); QString device = path.join(QStringLiteral("/")); if (current_pipeline_) current_pipeline_->SetSourceDevice(device); @@ -918,8 +918,8 @@ void GstEngine::StreamDiscovered(GstDiscoverer*, GstDiscovererInfo *info, GError GstDiscovererResult result = gst_discoverer_info_get_result(info); if (result != GST_DISCOVERER_OK) { - QString error_message = GSTdiscovererErrorMessage(result); - qLog(Error) << QStringLiteral("Stream discovery for %1 failed: %2").arg(discovered_url, error_message); + const QString error_message = GSTdiscovererErrorMessage(result); + qLog(Error) << QStringLiteral("Stream discovery for %1 failed: %2").arg(QString::fromUtf8(discovered_url), error_message); return; } @@ -949,8 +949,8 @@ void GstEngine::StreamDiscovered(GstDiscoverer*, GstDiscovererInfo *info, GError for (guint i = 0; i < caps_size; ++i) { GstStructure *gst_structure = gst_caps_get_structure(caps, i); if (!gst_structure) continue; - QString mimetype = gst_structure_get_name(gst_structure); - if (!mimetype.isEmpty() && mimetype != "audio/mpeg") { + QString mimetype = QString::fromUtf8(gst_structure_get_name(gst_structure)); + if (!mimetype.isEmpty() && mimetype != QStringLiteral("audio/mpeg")) { engine_metadata.filetype = Song::FiletypeByMimetype(mimetype); if (engine_metadata.filetype == Song::FileType::Unknown) { qLog(Error) << "Unknown mimetype" << mimetype; @@ -960,7 +960,7 @@ void GstEngine::StreamDiscovered(GstDiscoverer*, GstDiscovererInfo *info, GError if (engine_metadata.filetype == Song::FileType::Unknown) { gchar *codec_description = gst_pb_utils_get_codec_description(caps); - QString filetype_description = (codec_description ? QString(codec_description) : QString()); + QString filetype_description = (codec_description ? QString::fromUtf8(codec_description) : QString()); g_free(codec_description); if (!filetype_description.isEmpty()) { engine_metadata.filetype = Song::FiletypeByDescription(filetype_description); diff --git a/src/engine/gstengine.h b/src/engine/gstengine.h index be7828f7f9..2cb58150c2 100644 --- a/src/engine/gstengine.h +++ b/src/engine/gstengine.h @@ -78,7 +78,7 @@ class GstEngine : public EngineBase, public GstBufferConsumer { OutputDetailsList GetOutputsList() const override; bool ValidOutput(const QString &output) override; - QString DefaultOutput() override { return kAutoSink; } + QString DefaultOutput() override { return QString::fromUtf8(kAutoSink); } bool CustomDeviceSupport(const QString &output) override; bool ALSADeviceSupport(const QString &output) override; bool ExclusiveModeSupport(const QString &output) override; diff --git a/src/engine/gstenginepipeline.cpp b/src/engine/gstenginepipeline.cpp index 237befbbce..98f542b59a 100644 --- a/src/engine/gstenginepipeline.cpp +++ b/src/engine/gstenginepipeline.cpp @@ -321,7 +321,7 @@ QString GstEnginePipeline::GstStateText(const GstState state) { GstElement *GstEnginePipeline::CreateElement(const QString &factory_name, const QString &name, GstElement *bin, QString &error) const { - QString unique_name = QStringLiteral("pipeline") + "-" + QString::number(id_) + "-" + (name.isEmpty() ? factory_name : name); + QString unique_name = QStringLiteral("pipeline") + QLatin1Char('-') + QString::number(id_) + QLatin1Char('-') + (name.isEmpty() ? factory_name : name); GstElement *element = gst_element_factory_make(factory_name.toUtf8().constData(), unique_name.toUtf8().constData()); if (!element) { @@ -366,7 +366,7 @@ bool GstEnginePipeline::InitFromUrl(const QUrl &media_url, const QUrl &stream_ur } #else if (volume_enabled_ && !volume_) { - if (output_ == GstEngine::kAutoSink) { + if (output_ == QLatin1String(GstEngine::kAutoSink)) { element_added_cb_id_ = CHECKED_GCONNECT(G_OBJECT(audiobin_), "deep-element-added", &ElementAddedCallback, this); element_removed_cb_id_ = CHECKED_GCONNECT(G_OBJECT(audiobin_), "deep-element-removed", &ElementRemovedCallback, this); } @@ -835,7 +835,7 @@ bool GstEnginePipeline::InitAudioBin(QString &error) { const bool link_filtered_result = gst_element_link_filtered(audiosinkconverter, audiosink_, caps); gst_caps_unref(caps); if (!link_filtered_result) { - error = "Failed to link audio sink converter to audio sink with filter for " + output_; + error = QStringLiteral("Failed to link audio sink converter to audio sink with filter for ") + output_; return false; } } @@ -923,7 +923,7 @@ void GstEnginePipeline::ElementAddedCallback(GstBin *bin, GstBin*, GstElement *e GstEnginePipeline *instance = reinterpret_cast(self); gchar *element_name_char = gst_element_get_name(element); - const QString element_name(element_name_char); + const QString element_name = QString::fromUtf8(element_name_char); g_free(element_name_char); if (bin != GST_BIN(instance->audiobin_) || element_name == QStringLiteral("fake-audio-sink") || GST_ELEMENT(gst_element_get_parent(element)) != instance->audiosink_) return; @@ -1488,8 +1488,8 @@ void GstEnginePipeline::TagMessageReceived(GstMessage *msg) { if (engine_metadata.title.contains(QLatin1String(" - "))) { title_splitted = engine_metadata.title.split(QStringLiteral(" - ")); } - else if (engine_metadata.title.contains('~')) { - title_splitted = engine_metadata.title.split('~'); + else if (engine_metadata.title.contains(QLatin1Char('~'))) { + title_splitted = engine_metadata.title.split(QLatin1Char('~')); } if (!title_splitted.isEmpty() && title_splitted.count() >= 2) { int i = 0; diff --git a/src/engine/pulsedevicefinder.cpp b/src/engine/pulsedevicefinder.cpp index 67efe2f427..934879f57c 100644 --- a/src/engine/pulsedevicefinder.cpp +++ b/src/engine/pulsedevicefinder.cpp @@ -33,7 +33,7 @@ #include "pulsedevicefinder.h" #include "enginedevice.h" -PulseDeviceFinder::PulseDeviceFinder() : DeviceFinder(QStringLiteral("pulseaudio"), { "pulseaudio", "pulse", "pulsesink" }), mainloop_(nullptr), context_(nullptr) {} +PulseDeviceFinder::PulseDeviceFinder() : DeviceFinder(QStringLiteral("pulseaudio"), { QStringLiteral("pulseaudio"), QStringLiteral("pulse"), QStringLiteral("pulsesink") }), mainloop_(nullptr), context_(nullptr) {} bool PulseDeviceFinder::Initialize() { diff --git a/src/engine/vlcengine.cpp b/src/engine/vlcengine.cpp index 88f8bd400e..1645cf8781 100644 --- a/src/engine/vlcengine.cpp +++ b/src/engine/vlcengine.cpp @@ -129,7 +129,7 @@ bool VLCEngine::Play(const quint64 offset_nanosec) { if (!Initialized()) return false; // Set audio output - if (!output_.isEmpty() && output_ != "auto") { + if (!output_.isEmpty() && output_ != QStringLiteral("auto")) { int result = libvlc_audio_output_set(player_, output_.toUtf8().constData()); if (result != 0) qLog(Error) << "Failed to set output to" << output_; } @@ -235,11 +235,11 @@ EngineBase::OutputDetailsList VLCEngine::GetOutputsList() const { OutputDetails output; output.name = QString::fromUtf8(audio_output->psz_name); output.description = QString::fromUtf8(audio_output->psz_description); - if (output.name == "auto") output.iconname = QStringLiteral("soundcard"); - else if ((output.name == "alsa")||(output.name == "oss")) output.iconname = QStringLiteral("alsa"); - else if (output.name== "jack") output.iconname = QStringLiteral("jack"); - else if (output.name == "pulse") output.iconname = QStringLiteral("pulseaudio"); - else if (output.name == "afile") output.iconname = QStringLiteral("document-new"); + if (output.name == QStringLiteral("auto")) output.iconname = QStringLiteral("soundcard"); + else if ((output.name == QStringLiteral("alsa"))||(output.name == QStringLiteral("oss"))) output.iconname = QStringLiteral("alsa"); + else if (output.name== QStringLiteral("jack")) output.iconname = QStringLiteral("jack"); + else if (output.name == QStringLiteral("pulse")) output.iconname = QStringLiteral("pulseaudio"); + else if (output.name == QStringLiteral("afile")) output.iconname = QStringLiteral("document-new"); else output.iconname = QStringLiteral("soundcard"); outputs << output; } @@ -257,11 +257,11 @@ bool VLCEngine::ValidOutput(const QString &output) { } bool VLCEngine::CustomDeviceSupport(const QString &output) { - return (output != "auto"); + return (output != QStringLiteral("auto")); } bool VLCEngine::ALSADeviceSupport(const QString &output) { - return (output == "alsa"); + return (output == QStringLiteral("alsa")); } bool VLCEngine::ExclusiveModeSupport(const QString &output) { diff --git a/src/equalizer/equalizer.cpp b/src/equalizer/equalizer.cpp index 1a6ca30d9e..de05ca557a 100644 --- a/src/equalizer/equalizer.cpp +++ b/src/equalizer/equalizer.cpp @@ -44,6 +44,7 @@ #include #include "core/iconloader.h" +#include "core/settings.h" #include "equalizer.h" #include "equalizerslider.h" #include "ui_equalizer.h" @@ -70,7 +71,7 @@ Equalizer::Equalizer(QWidget *parent) line->setFrameShadow(QFrame::Sunken); ui_->slider_container->layout()->addWidget(line); - for (int i = 0; i < kBands; ++i) gain_[i] = AddSlider(kGainText[i]); + for (int i = 0; i < kBands; ++i) gain_[i] = AddSlider(QString::fromUtf8(kGainText[i])); // Must be done before the signals are connected ReloadSettings(); @@ -95,7 +96,7 @@ Equalizer::~Equalizer() { void Equalizer::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); presets_.clear(); @@ -112,7 +113,7 @@ void Equalizer::ReloadSettings() { if (count == 0) LoadDefaultPresets(); // Selected preset - QString selected_preset = s.value("selected_preset", "Custom").toString(); + QString selected_preset = s.value("selected_preset", QStringLiteral("Custom")).toString(); QString selected_preset_display_name = tr(qPrintable(selected_preset)); int selected_index = ui_->preset->findText(selected_preset_display_name); if (selected_index != -1) ui_->preset->setCurrentIndex(selected_index); @@ -135,25 +136,25 @@ void Equalizer::ReloadSettings() { void Equalizer::LoadDefaultPresets() { - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Custom"), Params(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Classical"), Params(0, 0, 0, 0, 0, 0, -40, -40, -40, -50)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Club"), Params(0, 0, 20, 30, 30, 30, 20, 0, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Dance"), Params(50, 35, 10, 0, 0, -30, -40, -40, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Full Bass"), Params(70, 70, 70, 40, 20, -45, -50, -55, -55, -55)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Full Treble"), Params(-50, -50, -50, -25, 15, 55, 80, 80, 80, 85)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Full Bass + Treble"), Params(35, 30, 0, -40, -25, 10, 45, 55, 60, 60)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Laptop/Headphones"), Params(25, 50, 25, -20, 0, -30, -40, -40, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Large Hall"), Params(50, 50, 30, 30, 0, -25, -25, -25, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Live"), Params(-25, 0, 20, 25, 30, 30, 20, 15, 15, 10)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Party"), Params(35, 35, 0, 0, 0, 0, 0, 0, 35, 35)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Pop"), Params(-10, 25, 35, 40, 25, -5, -15, -15, -10, -10)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Reggae"), Params(0, 0, -5, -30, 0, -35, -35, 0, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Rock"), Params(40, 25, -30, -40, -20, 20, 45, 55, 55, 55)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Soft"), Params(25, 10, -5, -15, -5, 20, 45, 50, 55, 60)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Ska"), Params(-15, -25, -25, -5, 20, 30, 45, 50, 55, 50)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Soft Rock"), Params(20, 20, 10, -5, -25, -30, -20, -5, 15, 45)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Techno"), Params(40, 30, 0, -30, -25, 0, 40, 50, 50, 45)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Zero"), Params(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Custom")), Params(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Classical")), Params(0, 0, 0, 0, 0, 0, -40, -40, -40, -50)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Club")), Params(0, 0, 20, 30, 30, 30, 20, 0, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Dance")), Params(50, 35, 10, 0, 0, -30, -40, -40, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Full Bass")), Params(70, 70, 70, 40, 20, -45, -50, -55, -55, -55)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Full Treble")), Params(-50, -50, -50, -25, 15, 55, 80, 80, 80, 85)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Full Bass + Treble")), Params(35, 30, 0, -40, -25, 10, 45, 55, 60, 60)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Laptop/Headphones")), Params(25, 50, 25, -20, 0, -30, -40, -40, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Large Hall")), Params(50, 50, 30, 30, 0, -25, -25, -25, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Live")), Params(-25, 0, 20, 25, 30, 30, 20, 15, 15, 10)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Party")), Params(35, 35, 0, 0, 0, 0, 0, 0, 35, 35)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Pop")), Params(-10, 25, 35, 40, 25, -5, -15, -15, -10, -10)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Reggae")), Params(0, 0, -5, -30, 0, -35, -35, 0, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Rock")), Params(40, 25, -30, -40, -20, 20, 45, 55, 55, 55)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Soft")), Params(25, 10, -5, -15, -5, 20, 45, 50, 55, 60)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Ska")), Params(-15, -25, -25, -5, 20, 30, 45, 50, 55, 50)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Soft Rock")), Params(20, 20, 10, -5, -25, -30, -20, -5, 15, 45)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Techno")), Params(40, 30, 0, -30, -25, 0, 40, 50, 50, 45)); + AddPreset(QT_TRANSLATE_NOOP(QStringLiteral("Equalizer"), QStringLiteral("Zero")), Params(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); } @@ -321,7 +322,7 @@ void Equalizer::EqualizerParametersChangedSlot() { void Equalizer::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); // Presets diff --git a/src/globalshortcuts/globalshortcutgrabber.cpp b/src/globalshortcuts/globalshortcutgrabber.cpp index 3eb2b8101a..25184a758c 100644 --- a/src/globalshortcuts/globalshortcutgrabber.cpp +++ b/src/globalshortcuts/globalshortcutgrabber.cpp @@ -110,7 +110,7 @@ bool GlobalShortcutGrabber::event(QEvent *e) { } void GlobalShortcutGrabber::UpdateText() { - ui_->label_key->setText("" + ret_.toString(QKeySequence::NativeText) + ""); + ui_->label_key->setText(QStringLiteral("") + ret_.toString(QKeySequence::NativeText) + QStringLiteral("")); } void GlobalShortcutGrabber::Accepted() { diff --git a/src/globalshortcuts/globalshortcutsbackend-gnome.cpp b/src/globalshortcuts/globalshortcutsbackend-gnome.cpp index fd3f807334..c9a29c7481 100644 --- a/src/globalshortcuts/globalshortcutsbackend-gnome.cpp +++ b/src/globalshortcuts/globalshortcutsbackend-gnome.cpp @@ -37,9 +37,11 @@ #include "gnomesettingsdaemon.h" -const char *GlobalShortcutsBackendGnome::kService1 = "org.gnome.SettingsDaemon.MediaKeys"; -const char *GlobalShortcutsBackendGnome::kService2 = "org.gnome.SettingsDaemon"; -const char *GlobalShortcutsBackendGnome::kPath = "/org/gnome/SettingsDaemon/MediaKeys"; +namespace { +constexpr char kService1[] = "org.gnome.SettingsDaemon.MediaKeys"; +constexpr char kService2[] = "org.gnome.SettingsDaemon"; +constexpr char kPath[] = "/org/gnome/SettingsDaemon/MediaKeys"; +} // namespace GlobalShortcutsBackendGnome::GlobalShortcutsBackendGnome(GlobalShortcutsManager *manager, QObject *parent) : GlobalShortcutsBackend(manager, GlobalShortcutsBackend::Type::Gnome, parent), @@ -52,7 +54,7 @@ bool GlobalShortcutsBackendGnome::IsAvailable() const { bool GlobalShortcutsBackendGnome::IsGnomeAvailable() { - return QDBusConnection::sessionBus().interface()->isServiceRegistered(kService1) || QDBusConnection::sessionBus().interface()->isServiceRegistered(kService2); + return QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kService1)) || QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kService2)); } @@ -61,11 +63,11 @@ bool GlobalShortcutsBackendGnome::DoRegister() { qLog(Debug) << "Registering"; if (!interface_) { - if (QDBusConnection::sessionBus().interface()->isServiceRegistered(kService1)) { - interface_ = new OrgGnomeSettingsDaemonMediaKeysInterface(kService1, kPath, QDBusConnection::sessionBus(), this); + if (QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kService1))) { + interface_ = new OrgGnomeSettingsDaemonMediaKeysInterface(QLatin1String(kService1), QLatin1String(kPath), QDBusConnection::sessionBus(), this); } - else if (QDBusConnection::sessionBus().interface()->isServiceRegistered(kService2)) { - interface_ = new OrgGnomeSettingsDaemonMediaKeysInterface(kService2, kPath, QDBusConnection::sessionBus(), this); + else if (QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kService2))) { + interface_ = new OrgGnomeSettingsDaemonMediaKeysInterface(QLatin1String(kService2), QLatin1String(kPath), QDBusConnection::sessionBus(), this); } } @@ -116,9 +118,9 @@ void GlobalShortcutsBackendGnome::DoUnregister() { void GlobalShortcutsBackendGnome::GnomeMediaKeyPressed(const QString&, const QString &key) { auto shortcuts = manager_->shortcuts(); - if (key == "Play") shortcuts[QStringLiteral("play_pause")].action->trigger(); - if (key == "Stop") shortcuts[QStringLiteral("stop")].action->trigger(); - if (key == "Next") shortcuts[QStringLiteral("next_track")].action->trigger(); - if (key == "Previous") shortcuts[QStringLiteral("prev_track")].action->trigger(); + if (key == QStringLiteral("Play")) shortcuts[QStringLiteral("play_pause")].action->trigger(); + if (key == QStringLiteral("Stop")) shortcuts[QStringLiteral("stop")].action->trigger(); + if (key == QStringLiteral("Next")) shortcuts[QStringLiteral("next_track")].action->trigger(); + if (key == QStringLiteral("Previous")) shortcuts[QStringLiteral("prev_track")].action->trigger(); } diff --git a/src/globalshortcuts/globalshortcutsbackend-gnome.h b/src/globalshortcuts/globalshortcutsbackend-gnome.h index b66e9a1140..1d22d8beab 100644 --- a/src/globalshortcuts/globalshortcutsbackend-gnome.h +++ b/src/globalshortcuts/globalshortcutsbackend-gnome.h @@ -52,10 +52,6 @@ class GlobalShortcutsBackendGnome : public GlobalShortcutsBackend { void GnomeMediaKeyPressed(const QString &application, const QString &key); private: - static const char *kService1; - static const char *kService2; - static const char *kPath; - OrgGnomeSettingsDaemonMediaKeysInterface *interface_; bool is_connected_; }; diff --git a/src/globalshortcuts/globalshortcutsbackend-kde.cpp b/src/globalshortcuts/globalshortcutsbackend-kde.cpp index b445647f25..ff76f5f2eb 100644 --- a/src/globalshortcuts/globalshortcutsbackend-kde.cpp +++ b/src/globalshortcuts/globalshortcutsbackend-kde.cpp @@ -38,8 +38,10 @@ #include "kglobalaccel.h" #include "kglobalaccelcomponent.h" -const char *GlobalShortcutsBackendKDE::kKdeService = "org.kde.kglobalaccel"; -const char *GlobalShortcutsBackendKDE::kKdePath = "/kglobalaccel"; +namespace { +constexpr char kKdeService[] = "org.kde.kglobalaccel"; +constexpr char kKdePath[] = "/kglobalaccel"; +} GlobalShortcutsBackendKDE::GlobalShortcutsBackendKDE(GlobalShortcutsManager *manager, QObject *parent) : GlobalShortcutsBackend(manager, GlobalShortcutsBackend::Type::KDE, parent), @@ -48,7 +50,7 @@ GlobalShortcutsBackendKDE::GlobalShortcutsBackendKDE(GlobalShortcutsManager *man bool GlobalShortcutsBackendKDE::IsKDEAvailable() { - return QDBusConnection::sessionBus().interface()->isServiceRegistered(kKdeService); + return QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kKdeService)); } @@ -72,13 +74,13 @@ bool GlobalShortcutsBackendKDE::DoRegister() { qLog(Debug) << "Registering"; - if (!QDBusConnection::sessionBus().interface()->isServiceRegistered(kKdeService)) { + if (!QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kKdeService))) { qLog(Warning) << "KGlobalAccel is not registered"; return false; } if (!interface_) { - interface_ = new OrgKdeKGlobalAccelInterface(kKdeService, kKdePath, QDBusConnection::sessionBus(), this); + interface_ = new OrgKdeKGlobalAccelInterface(QLatin1String(kKdeService), QLatin1String(kKdePath), QDBusConnection::sessionBus(), this); } QList shortcuts = manager_->shortcuts().values(); @@ -100,14 +102,14 @@ void GlobalShortcutsBackendKDE::RegisterFinished(QDBusPendingCallWatcher *watche watcher->deleteLater(); if (!reply.isValid()) { - if (reply.error().name() != "org.kde.kglobalaccel.NoSuchComponent") { + if (reply.error().name() != QStringLiteral("org.kde.kglobalaccel.NoSuchComponent")) { qLog(Error) << "Failed to register:" << reply.error().name() << reply.error().message(); } return; } if (!component_) { - component_ = new org::kde::kglobalaccel::Component(kKdeService, reply.value().path(), QDBusConnection::sessionBus(), interface_); + component_ = new org::kde::kglobalaccel::Component(QLatin1String(kKdeService), reply.value().path(), QDBusConnection::sessionBus(), interface_); } if (!component_->isValid()) { @@ -174,7 +176,7 @@ QStringList GlobalShortcutsBackendKDE::GetActionId(const QString &id, const QAct ret << QCoreApplication::applicationName(); ret << id; ret << QCoreApplication::applicationName(); - ret << action->text().remove('&'); + ret << action->text().remove(QLatin1Char('&')); if (ret.back().isEmpty()) ret.back() = id; return ret; diff --git a/src/globalshortcuts/globalshortcutsbackend-kde.h b/src/globalshortcuts/globalshortcutsbackend-kde.h index 6b98b24013..defa2604aa 100644 --- a/src/globalshortcuts/globalshortcutsbackend-kde.h +++ b/src/globalshortcuts/globalshortcutsbackend-kde.h @@ -62,9 +62,6 @@ class GlobalShortcutsBackendKDE : public GlobalShortcutsBackend { void GlobalShortcutPressed(const QString &component_unique, const QString &shortcut_unique, qint64); private: - static const char *kKdeService; - static const char *kKdePath; - OrgKdeKGlobalAccelInterface *interface_; OrgKdeKglobalaccelComponentInterface *component_; QMultiHash actions_; diff --git a/src/globalshortcuts/globalshortcutsbackend-mate.cpp b/src/globalshortcuts/globalshortcutsbackend-mate.cpp index 76c4156003..e73eda263c 100644 --- a/src/globalshortcuts/globalshortcutsbackend-mate.cpp +++ b/src/globalshortcuts/globalshortcutsbackend-mate.cpp @@ -35,9 +35,11 @@ #include "matesettingsdaemon.h" -const char *GlobalShortcutsBackendMate::kService1 = "org.mate.SettingsDaemon.MediaKeys"; -const char *GlobalShortcutsBackendMate::kService2 = "org.mate.SettingsDaemon"; -const char *GlobalShortcutsBackendMate::kPath = "/org/mate/SettingsDaemon/MediaKeys"; +namespace { +constexpr char kService1[] = "org.mate.SettingsDaemon.MediaKeys"; +constexpr char kService2[] = "org.mate.SettingsDaemon"; +constexpr char kPath[] = "/org/mate/SettingsDaemon/MediaKeys"; +} GlobalShortcutsBackendMate::GlobalShortcutsBackendMate(GlobalShortcutsManager *manager, QObject *parent) : GlobalShortcutsBackend(manager, GlobalShortcutsBackend::Type::Mate, parent), @@ -52,7 +54,7 @@ bool GlobalShortcutsBackendMate::IsAvailable() const { bool GlobalShortcutsBackendMate::IsMateAvailable() { - return QDBusConnection::sessionBus().interface()->isServiceRegistered(kService1) || QDBusConnection::sessionBus().interface()->isServiceRegistered(kService2); + return QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kService1)) || QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kService2)); } @@ -61,11 +63,11 @@ bool GlobalShortcutsBackendMate::DoRegister() { qLog(Debug) << "Registering"; if (!interface_) { - if (QDBusConnection::sessionBus().interface()->isServiceRegistered(kService1)) { - interface_ = new OrgMateSettingsDaemonMediaKeysInterface(kService1, kPath, QDBusConnection::sessionBus(), this); + if (QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kService1))) { + interface_ = new OrgMateSettingsDaemonMediaKeysInterface(QLatin1String(kService1), QLatin1String(kPath), QDBusConnection::sessionBus(), this); } - else if (QDBusConnection::sessionBus().interface()->isServiceRegistered(kService2)) { - interface_ = new OrgMateSettingsDaemonMediaKeysInterface(kService2, kPath, QDBusConnection::sessionBus(), this); + else if (QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String(kService2))) { + interface_ = new OrgMateSettingsDaemonMediaKeysInterface(QLatin1String(kService2), QLatin1String(kPath), QDBusConnection::sessionBus(), this); } } @@ -116,9 +118,9 @@ void GlobalShortcutsBackendMate::DoUnregister() { void GlobalShortcutsBackendMate::MateMediaKeyPressed(const QString&, const QString &key) { auto shortcuts = manager_->shortcuts(); - if (key == "Play") shortcuts[QStringLiteral("play_pause")].action->trigger(); - if (key == "Stop") shortcuts[QStringLiteral("stop")].action->trigger(); - if (key == "Next") shortcuts[QStringLiteral("next_track")].action->trigger(); - if (key == "Previous") shortcuts[QStringLiteral("prev_track")].action->trigger(); + if (key == QStringLiteral("Play")) shortcuts[QStringLiteral("play_pause")].action->trigger(); + if (key == QStringLiteral("Stop")) shortcuts[QStringLiteral("stop")].action->trigger(); + if (key == QStringLiteral("Next")) shortcuts[QStringLiteral("next_track")].action->trigger(); + if (key == QStringLiteral("Previous")) shortcuts[QStringLiteral("prev_track")].action->trigger(); } diff --git a/src/globalshortcuts/globalshortcutsbackend-mate.h b/src/globalshortcuts/globalshortcutsbackend-mate.h index 3e88c12f94..434778c7d8 100644 --- a/src/globalshortcuts/globalshortcutsbackend-mate.h +++ b/src/globalshortcuts/globalshortcutsbackend-mate.h @@ -50,10 +50,6 @@ class GlobalShortcutsBackendMate : public GlobalShortcutsBackend { void MateMediaKeyPressed(const QString &application, const QString &key); private: - static const char *kService1; - static const char *kService2; - static const char *kPath; - OrgMateSettingsDaemonMediaKeysInterface *interface_; bool is_connected_; }; diff --git a/src/globalshortcuts/globalshortcutsbackend-x11.cpp b/src/globalshortcuts/globalshortcutsbackend-x11.cpp index 27ae2d8d34..32906d6174 100644 --- a/src/globalshortcuts/globalshortcutsbackend-x11.cpp +++ b/src/globalshortcuts/globalshortcutsbackend-x11.cpp @@ -45,7 +45,7 @@ bool GlobalShortcutsBackendX11::IsAvailable() const { bool GlobalShortcutsBackendX11::IsX11Available() { - return QApplication::platformName() == "xcb"; + return QApplication::platformName() == QStringLiteral("xcb"); } diff --git a/src/globalshortcuts/globalshortcutsmanager.h b/src/globalshortcuts/globalshortcutsmanager.h index 2787f8a094..6f2c24e689 100644 --- a/src/globalshortcuts/globalshortcutsmanager.h +++ b/src/globalshortcuts/globalshortcutsmanager.h @@ -36,6 +36,8 @@ #include "globalshortcutsbackend.h" +#include "core/settings.h" + class QShortcut; class QAction; @@ -103,7 +105,7 @@ class GlobalShortcutsManager : public QWidget { private: QList backends_; - QSettings settings_; + Settings settings_; QList backends_enabled_; QMap shortcuts_; }; diff --git a/src/internet/internetsearchmodel.cpp b/src/internet/internetsearchmodel.cpp index eb9ab1d4c8..7e2b00d90b 100644 --- a/src/internet/internetsearchmodel.cpp +++ b/src/internet/internetsearchmodel.cpp @@ -175,14 +175,14 @@ QStandardItem *InternetSearchModel::BuildContainers(const Song &s, QStandardItem case CollectionModel::GroupBy::Year:{ const int year = qMax(0, s.year()); display_text = QString::number(year); - sort_text = CollectionModel::SortTextForNumber(year) + " "; + sort_text = CollectionModel::SortTextForNumber(year) + QStringLiteral(" "); break; } case CollectionModel::GroupBy::OriginalYear:{ const int year = qMax(0, s.effective_originalyear()); display_text = QString::number(year); - sort_text = CollectionModel::SortTextForNumber(year) + " "; + sort_text = CollectionModel::SortTextForNumber(year) + QStringLiteral(" "); break; } diff --git a/src/internet/internetsearchview.cpp b/src/internet/internetsearchview.cpp index efa5978692..cd0a2843a5 100644 --- a/src/internet/internetsearchview.cpp +++ b/src/internet/internetsearchview.cpp @@ -68,6 +68,7 @@ #include "core/mimedata.h" #include "core/iconloader.h" #include "core/song.h" +#include "core/settings.h" #include "collection/collectionfilterwidget.h" #include "collection/collectionmodel.h" #include "collection/groupbydialog.h" @@ -209,7 +210,7 @@ void InternetSearchView::Init(Application *app, InternetServicePtr service) { void InternetSearchView::ReloadSettings() { - QSettings s; + Settings s; // Collection settings @@ -436,11 +437,11 @@ QStringList InternetSearchView::TokenizeQuery(const QString &query) { QStringList tokens(query.split(QRegularExpression(QStringLiteral("\\s+")))); for (QStringList::iterator it = tokens.begin(); it != tokens.end(); ++it) { - (*it).remove('('); - (*it).remove(')'); - (*it).remove('"'); + (*it).remove(QLatin1Char('(')); + (*it).remove(QLatin1Char(')')); + (*it).remove(QLatin1Char('"')); - const qint64 colon = (*it).indexOf(QLatin1String(":")); + const qint64 colon = (*it).indexOf(QLatin1Char(':')); if (colon != -1) { (*it).remove(0, colon + 1); } @@ -705,7 +706,7 @@ void InternetSearchView::SetGroupBy(const CollectionModel::Grouping g) { back_model_->SetGroupBy(g, false); // Save the setting - QSettings s; + Settings s; s.beginGroup(service_->settings_group()); s.setValue("search_group_by_version", 1); s.setValue("search_group_by1", static_cast(g.first)); @@ -745,7 +746,7 @@ void InternetSearchView::SetSearchType(const InternetSearchView::SearchType type search_type_ = type; - QSettings s; + Settings s; s.beginGroup(service_->settings_group()); s.setValue("type", static_cast(search_type_)); s.endGroup(); @@ -787,13 +788,13 @@ void InternetSearchView::AddSongs() { QString InternetSearchView::PixmapCacheKey(const InternetSearchView::Result &result) const { if (result.metadata_.art_automatic_is_valid()) { - return Song::TextForSource(service_->source()) + "/" + result.metadata_.art_automatic().toString(); + return Song::TextForSource(service_->source()) + QLatin1Char('/') + result.metadata_.art_automatic().toString(); } else if (!result.metadata_.effective_albumartist().isEmpty() && !result.metadata_.album().isEmpty()) { - return Song::TextForSource(service_->source()) + "/" + result.metadata_.effective_albumartist() + "/" + result.metadata_.album(); + return Song::TextForSource(service_->source()) + QLatin1Char('/') + result.metadata_.effective_albumartist() + QLatin1Char('/') + result.metadata_.album(); } else { - return Song::TextForSource(service_->source()) + "/" + result.metadata_.url().toString(); + return Song::TextForSource(service_->source()) + QLatin1Char('/') + result.metadata_.url().toString(); } } diff --git a/src/internet/internettabsview.cpp b/src/internet/internettabsview.cpp index 657604fa78..0825c166b8 100644 --- a/src/internet/internettabsview.cpp +++ b/src/internet/internettabsview.cpp @@ -35,6 +35,7 @@ #include "core/application.h" #include "core/iconloader.h" +#include "core/settings.h" #include "collection/collectionbackend.h" #include "collection/collectionmodel.h" #include "collection/collectionfilterwidget.h" @@ -158,21 +159,21 @@ InternetTabsView::InternetTabsView(Application *app, InternetServicePtr service, ui_->tabs->removeTab(ui_->tabs->indexOf(ui_->songs)); } - QSettings s; + Settings s; s.beginGroup(settings_group_); - QString tab = s.value("tab", "artists").toString().toLower(); + QString tab = s.value("tab", QStringLiteral("artists")).toString().toLower(); s.endGroup(); - if (tab == "artists") { + if (tab == QStringLiteral("artists")) { ui_->tabs->setCurrentWidget(ui_->artists); } - else if (tab == "albums") { + else if (tab == QStringLiteral("albums")) { ui_->tabs->setCurrentWidget(ui_->albums); } - else if (tab == "songs") { + else if (tab == QStringLiteral("songs")) { ui_->tabs->setCurrentWidget(ui_->songs); } - else if (tab == "search") { + else if (tab == QStringLiteral("search")) { ui_->tabs->setCurrentWidget(ui_->search); } @@ -182,7 +183,7 @@ InternetTabsView::InternetTabsView(Application *app, InternetServicePtr service, InternetTabsView::~InternetTabsView() { - QSettings s; + Settings s; s.beginGroup(settings_group_); s.setValue("tab", ui_->tabs->currentWidget()->objectName().toLower()); s.endGroup(); diff --git a/src/internet/localredirectserver.cpp b/src/internet/localredirectserver.cpp index 6b52315ed2..7c4911b3a6 100644 --- a/src/internet/localredirectserver.cpp +++ b/src/internet/localredirectserver.cpp @@ -151,7 +151,7 @@ void LocalRedirectServer::WriteTemplate() const { .pixmap(16) .toImage() .save(&image_buffer, "PNG"); - page_data.replace(QLatin1String("@IMAGE_DATA@"), image_buffer.data().toBase64()); + page_data.replace(QLatin1String("@IMAGE_DATA@"), QString::fromUtf8(image_buffer.data().toBase64())); image_buffer.close(); } @@ -169,7 +169,8 @@ QUrl LocalRedirectServer::ParseUrlFromRequest(const QByteArray &request) const { const QByteArray &request_line = lines[0]; QByteArray path = request_line.split(' ')[1]; QUrl base_url = url_; - QUrl request_url(base_url.toString() + path.mid(1), QUrl::StrictMode); + QUrl request_url(base_url.toString() + QString::fromLatin1(path.mid(1)), QUrl::StrictMode); + return request_url; } diff --git a/src/lyrics/azlyricscomlyricsprovider.cpp b/src/lyrics/azlyricscomlyricsprovider.cpp index 7f2d7d0ced..257f7ea4e2 100644 --- a/src/lyrics/azlyricscomlyricsprovider.cpp +++ b/src/lyrics/azlyricscomlyricsprovider.cpp @@ -28,17 +28,19 @@ #include "lyricssearchrequest.h" #include "azlyricscomlyricsprovider.h" -const char AzLyricsComLyricsProvider::kUrl[] = "https://www.azlyrics.com/lyrics/"; -const char AzLyricsComLyricsProvider::kStartTag[] = "
"; -const char AzLyricsComLyricsProvider::kEndTag[] = "
"; -const char AzLyricsComLyricsProvider::kLyricsStart[] = ""; +namespace { +constexpr char kUrl[] = "https://www.azlyrics.com/lyrics/"; +constexpr char kStartTag[] = "
"; +constexpr char kEndTag[] = "
"; +constexpr char kLyricsStart[] = ""; +} AzLyricsComLyricsProvider::AzLyricsComLyricsProvider(SharedPtr network, QObject *parent) - : HtmlLyricsProvider(QStringLiteral("azlyrics.com"), true, kStartTag, kEndTag, kLyricsStart, false, network, parent) {} + : HtmlLyricsProvider(QStringLiteral("azlyrics.com"), true, QLatin1String(kStartTag), QLatin1String(kEndTag), QLatin1String(kLyricsStart), false, network, parent) {} QUrl AzLyricsComLyricsProvider::Url(const LyricsSearchRequest &request) { - return QUrl(kUrl + StringFixup(request.artist) + "/" + StringFixup(request.title) + ".html"); + return QUrl(QLatin1String(kUrl) + StringFixup(request.artist) + QStringLiteral("/") + StringFixup(request.title) + QStringLiteral(".html")); } diff --git a/src/lyrics/azlyricscomlyricsprovider.h b/src/lyrics/azlyricscomlyricsprovider.h index f3dd8e5af9..147b8b3be9 100644 --- a/src/lyrics/azlyricscomlyricsprovider.h +++ b/src/lyrics/azlyricscomlyricsprovider.h @@ -41,12 +41,6 @@ class AzLyricsComLyricsProvider : public HtmlLyricsProvider { private: QString StringFixup(const QString &text); - - private: - static const char kUrl[]; - static const char kStartTag[]; - static const char kEndTag[]; - static const char kLyricsStart[]; }; #endif // AZLYRICSCOMLYRICSPROVIDER_H diff --git a/src/lyrics/chartlyricsprovider.cpp b/src/lyrics/chartlyricsprovider.cpp index 45b7c75ab8..6dec707526 100644 --- a/src/lyrics/chartlyricsprovider.cpp +++ b/src/lyrics/chartlyricsprovider.cpp @@ -37,7 +37,9 @@ #include "lyricssearchresult.h" #include "chartlyricsprovider.h" -const char *ChartLyricsProvider::kUrlSearch = "http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect"; +namespace { +static constexpr char kUrlSearch[] = "http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect"; +} ChartLyricsProvider::ChartLyricsProvider(SharedPtr network, QObject *parent) : LyricsProvider(QStringLiteral("ChartLyrics"), false, false, network, parent) {} @@ -55,10 +57,10 @@ ChartLyricsProvider::~ChartLyricsProvider() { bool ChartLyricsProvider::StartSearch(const int id, const LyricsSearchRequest &request) { QUrlQuery url_query; - url_query.addQueryItem(QStringLiteral("artist"), QUrl::toPercentEncoding(request.artist)); - url_query.addQueryItem(QStringLiteral("song"), QUrl::toPercentEncoding(request.title)); + url_query.addQueryItem(QStringLiteral("artist"), QString::fromUtf8(QUrl::toPercentEncoding(request.artist))); + url_query.addQueryItem(QStringLiteral("song"), QString::fromUtf8(QUrl::toPercentEncoding(request.title))); - QUrl url(kUrlSearch); + QUrl url(QString::fromUtf8(kUrlSearch)); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); @@ -99,21 +101,21 @@ void ChartLyricsProvider::HandleSearchReply(QNetworkReply *reply, const int id, QXmlStreamReader::TokenType type = reader.readNext(); QString name = reader.name().toString(); if (type == QXmlStreamReader::StartElement) { - if (name == "GetLyricResult") { + if (name == QStringLiteral("GetLyricResult")) { result = LyricsSearchResult(); } - if (name == "LyricArtist") { + if (name == QStringLiteral("LyricArtist")) { result.artist = reader.readElementText(); } - else if (name == "LyricSong") { + else if (name == QStringLiteral("LyricSong")) { result.title = reader.readElementText(); } - else if (name == "Lyric") { + else if (name == QStringLiteral("Lyric")) { result.lyrics = reader.readElementText(); } } else if (type == QXmlStreamReader::EndElement) { - if (name == "GetLyricResult") { + if (name == QStringLiteral("GetLyricResult")) { if (!result.artist.isEmpty() && !result.title.isEmpty() && !result.lyrics.isEmpty() && (result.artist.compare(request.albumartist, Qt::CaseInsensitive) == 0 || result.artist.compare(request.artist, Qt::CaseInsensitive) == 0 || diff --git a/src/lyrics/chartlyricsprovider.h b/src/lyrics/chartlyricsprovider.h index 984b563e1e..111f1299f5 100644 --- a/src/lyrics/chartlyricsprovider.h +++ b/src/lyrics/chartlyricsprovider.h @@ -51,7 +51,6 @@ class ChartLyricsProvider : public LyricsProvider { void HandleSearchReply(QNetworkReply *reply, const int id, const LyricsSearchRequest &request); private: - static const char *kUrlSearch; QList replies_; }; diff --git a/src/lyrics/elyricsnetlyricsprovider.cpp b/src/lyrics/elyricsnetlyricsprovider.cpp index 824cfcd90d..65c541da6c 100644 --- a/src/lyrics/elyricsnetlyricsprovider.cpp +++ b/src/lyrics/elyricsnetlyricsprovider.cpp @@ -28,17 +28,19 @@ #include "lyricssearchrequest.h" #include "elyricsnetlyricsprovider.h" -const char ElyricsNetLyricsProvider::kUrl[] = "https://www.elyrics.net/read/"; -const char ElyricsNetLyricsProvider::kStartTag[] = "]*>"; -const char ElyricsNetLyricsProvider::kEndTag[] = "<\\/div>"; -const char ElyricsNetLyricsProvider::kLyricsStart[] = "
"; +namespace { +constexpr char kUrl[] = "https://www.elyrics.net/read/"; +constexpr char kStartTag[] = "]*>"; +constexpr char kEndTag[] = "<\\/div>"; +constexpr char kLyricsStart[] = "
"; +} // namespace ElyricsNetLyricsProvider::ElyricsNetLyricsProvider(SharedPtr network, QObject *parent) - : HtmlLyricsProvider(QStringLiteral("elyrics.net"), true, kStartTag, kEndTag, kLyricsStart, false, network, parent) {} + : HtmlLyricsProvider(QStringLiteral("elyrics.net"), true, QLatin1String(kStartTag), QLatin1String(kEndTag), QLatin1String(kLyricsStart), false, network, parent) {} QUrl ElyricsNetLyricsProvider::Url(const LyricsSearchRequest &request) { - return QUrl(kUrl + request.artist[0].toLower() + "/" + StringFixup(request.artist) + "-lyrics/" + StringFixup(request.title) + "-lyrics.html"); + return QUrl(QLatin1String(kUrl) + request.artist[0].toLower() + QLatin1Char('/') + StringFixup(request.artist) + QStringLiteral("-lyrics/") + StringFixup(request.title) + QStringLiteral("-lyrics.html")); } @@ -48,7 +50,7 @@ QString ElyricsNetLyricsProvider::StringFixup(const QString &text) { .replace(QRegularExpression(QStringLiteral("[^\\w0-9_,&\\-\\(\\) ]")), QStringLiteral("_")) .replace(QRegularExpression(QStringLiteral(" {2,}")), QStringLiteral(" ")) .simplified() - .replace(' ', '-') + .replace(QLatin1Char(' '), QLatin1Char('-')) .toLower(); } diff --git a/src/lyrics/elyricsnetlyricsprovider.h b/src/lyrics/elyricsnetlyricsprovider.h index abdb148fe3..4fa4fb2ccc 100644 --- a/src/lyrics/elyricsnetlyricsprovider.h +++ b/src/lyrics/elyricsnetlyricsprovider.h @@ -41,12 +41,6 @@ class ElyricsNetLyricsProvider : public HtmlLyricsProvider { private: QString StringFixup(const QString &text); - - private: - static const char kUrl[]; - static const char kStartTag[]; - static const char kEndTag[]; - static const char kLyricsStart[]; }; #endif // ELYRICSNETLYRICSPROVIDER_H diff --git a/src/lyrics/geniuslyricsprovider.cpp b/src/lyrics/geniuslyricsprovider.cpp index a35a4fd11f..68b7561f2a 100644 --- a/src/lyrics/geniuslyricsprovider.cpp +++ b/src/lyrics/geniuslyricsprovider.cpp @@ -45,6 +45,7 @@ #include "core/logging.h" #include "core/shared_ptr.h" #include "core/networkaccessmanager.h" +#include "core/settings.h" #include "utilities/randutils.h" #include "internet/localredirectserver.h" #include "jsonlyricsprovider.h" @@ -53,17 +54,19 @@ using std::make_shared; -const char *GeniusLyricsProvider::kSettingsGroup = "GeniusLyrics"; -const char *GeniusLyricsProvider::kOAuthAuthorizeUrl = "https://api.genius.com/oauth/authorize"; -const char *GeniusLyricsProvider::kOAuthAccessTokenUrl = "https://api.genius.com/oauth/token"; -const char *GeniusLyricsProvider::kOAuthRedirectUrl = "http://localhost:63111/"; // Genius does not accept a random port number. This port must match the URL of the ClientID. -const char *GeniusLyricsProvider::kUrlSearch = "https://api.genius.com/search/"; -const char *GeniusLyricsProvider::kClientIDB64 = "RUNTNXU4U1VyMU1KUU5hdTZySEZteUxXY2hkanFiY3lfc2JjdXBpNG5WMU9SNUg4dTBZelEtZTZCdFg2dl91SQ=="; -const char *GeniusLyricsProvider::kClientSecretB64 = "VE9pMU9vUjNtTXZ3eFR3YVN0QVRyUjVoUlhVWDI1Ylp5X240eEt1M0ZkYlNwRG5JUnd0LXFFbHdGZkZkRWY2VzJ1S011UnQzM3c2Y3hqY0tVZ3NGN2c="; +namespace { +static constexpr char kSettingsGroup[] = "GeniusLyrics"; +static constexpr char kOAuthAuthorizeUrl[] = "https://api.genius.com/oauth/authorize"; +static constexpr char kOAuthAccessTokenUrl[] = "https://api.genius.com/oauth/token"; +static constexpr char kOAuthRedirectUrl[] = "http://localhost:63111/"; // Genius does not accept a random port number. This port must match the URL of the ClientID. +static constexpr char kUrlSearch[] = "https://api.genius.com/search/"; +static constexpr char kClientIDB64[] = "RUNTNXU4U1VyMU1KUU5hdTZySEZteUxXY2hkanFiY3lfc2JjdXBpNG5WMU9SNUg4dTBZelEtZTZCdFg2dl91SQ=="; +static constexpr char kClientSecretB64[] = "VE9pMU9vUjNtTXZ3eFR3YVN0QVRyUjVoUlhVWDI1Ylp5X240eEt1M0ZkYlNwRG5JUnd0LXFFbHdGZkZkRWY2VzJ1S011UnQzM3c2Y3hqY0tVZ3NGN2c="; +} // namespace GeniusLyricsProvider::GeniusLyricsProvider(SharedPtr network, QObject *parent) : JsonLyricsProvider(QStringLiteral("Genius"), true, true, network, parent), server_(nullptr) { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); if (s.contains("access_token")) { access_token_ = s.value("access_token").toString(); @@ -85,7 +88,7 @@ GeniusLyricsProvider::~GeniusLyricsProvider() { void GeniusLyricsProvider::Authenticate() { - QUrl redirect_url(kOAuthRedirectUrl); + QUrl redirect_url(QString::fromUtf8(kOAuthRedirectUrl)); if (!server_) { server_ = new LocalRedirectServer(this); @@ -100,19 +103,19 @@ void GeniusLyricsProvider::Authenticate() { } code_verifier_ = Utilities::CryptographicRandomString(44); - code_challenge_ = QString(QCryptographicHash::hash(code_verifier_.toUtf8(), QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding)); - if (code_challenge_.lastIndexOf(QChar('=')) == code_challenge_.length() - 1) { + code_challenge_ = QString::fromUtf8(QCryptographicHash::hash(code_verifier_.toUtf8(), QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding)); + if (code_challenge_.lastIndexOf(QLatin1Char('=')) == code_challenge_.length() - 1) { code_challenge_.chop(1); } QUrlQuery url_query; - url_query.addQueryItem(QStringLiteral("client_id"), QUrl::toPercentEncoding(QByteArray::fromBase64(kClientIDB64))); - url_query.addQueryItem(QStringLiteral("redirect_uri"), QUrl::toPercentEncoding(redirect_url.toString())); + url_query.addQueryItem(QStringLiteral("client_id"), QString::fromUtf8(QUrl::toPercentEncoding(QLatin1String(kClientIDB64)))); + url_query.addQueryItem(QStringLiteral("redirect_uri"), QString::fromUtf8(QUrl::toPercentEncoding(redirect_url.toString()))); url_query.addQueryItem(QStringLiteral("scope"), QStringLiteral("me")); - url_query.addQueryItem(QStringLiteral("state"), QUrl::toPercentEncoding(code_challenge_)); + url_query.addQueryItem(QStringLiteral("state"), QString::fromUtf8(QUrl::toPercentEncoding(code_challenge_))); url_query.addQueryItem(QStringLiteral("response_type"), QStringLiteral("code")); - QUrl url(kOAuthAuthorizeUrl); + QUrl url(QString::fromUtf8(kOAuthAuthorizeUrl)); url.setQuery(url_query); const bool result = QDesktopServices::openUrl(url); @@ -136,7 +139,7 @@ void GeniusLyricsProvider::RedirectArrived() { AuthError(QUrlQuery(url).queryItemValue(QStringLiteral("error"))); } else if (url_query.hasQueryItem(QStringLiteral("code"))) { - QUrl redirect_url(kOAuthRedirectUrl); + QUrl redirect_url(QString::fromUtf8(kOAuthRedirectUrl)); redirect_url.setPort(server_->url().port()); RequestAccessToken(url, redirect_url); } @@ -169,14 +172,14 @@ void GeniusLyricsProvider::RequestAccessToken(const QUrl &url, const QUrl &redir const QString code = url_query.queryItemValue(QStringLiteral("code")); QUrlQuery new_url_query; - new_url_query.addQueryItem(QStringLiteral("code"), QUrl::toPercentEncoding(code)); - new_url_query.addQueryItem(QStringLiteral("client_id"), QUrl::toPercentEncoding(QByteArray::fromBase64(kClientIDB64))); - new_url_query.addQueryItem(QStringLiteral("client_secret"), QUrl::toPercentEncoding(QByteArray::fromBase64(kClientSecretB64))); - new_url_query.addQueryItem(QStringLiteral("redirect_uri"), QUrl::toPercentEncoding(redirect_url.toString())); + new_url_query.addQueryItem(QStringLiteral("code"), QString::fromUtf8(QUrl::toPercentEncoding(code))); + new_url_query.addQueryItem(QStringLiteral("client_id"), QString::fromUtf8(QUrl::toPercentEncoding(QLatin1String(kClientIDB64)))); + new_url_query.addQueryItem(QStringLiteral("client_secret"), QString::fromUtf8(QUrl::toPercentEncoding(QLatin1String(kClientSecretB64)))); + new_url_query.addQueryItem(QStringLiteral("redirect_uri"), QString::fromUtf8(QUrl::toPercentEncoding(redirect_url.toString()))); new_url_query.addQueryItem(QStringLiteral("grant_type"), QStringLiteral("authorization_code")); new_url_query.addQueryItem(QStringLiteral("response_type"), QStringLiteral("code")); - QUrl new_url(kOAuthAccessTokenUrl); + QUrl new_url(QString::fromUtf8(kOAuthAccessTokenUrl)); QNetworkRequest req(new_url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); QByteArray query = new_url_query.toString(QUrl::FullyEncoded).toUtf8(); @@ -218,7 +221,7 @@ void GeniusLyricsProvider::AccessTokenRequestFinished(QNetworkReply *reply) { } else { // See if there is Json data containing "status" and "userMessage" then use that instead. - QByteArray data = reply->readAll(); + const QByteArray data = reply->readAll(); QJsonParseError json_error; QJsonDocument json_doc = QJsonDocument::fromJson(data, &json_error); if (json_error.error == QJsonParseError::NoError && !json_doc.isEmpty() && json_doc.isObject()) { @@ -242,7 +245,7 @@ void GeniusLyricsProvider::AccessTokenRequestFinished(QNetworkReply *reply) { } } - QByteArray data = reply->readAll(); + const QByteArray data = reply->readAll(); QJsonParseError json_error; QJsonDocument json_doc = QJsonDocument::fromJson(data, &json_error); @@ -275,7 +278,7 @@ void GeniusLyricsProvider::AccessTokenRequestFinished(QNetworkReply *reply) { access_token_ = json_obj[QStringLiteral("access_token")].toString(); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("access_token", access_token_); s.endGroup(); @@ -297,9 +300,9 @@ bool GeniusLyricsProvider::StartSearch(const int id, const LyricsSearchRequest & requests_search_.insert(id, search); QUrlQuery url_query; - url_query.addQueryItem(QStringLiteral("q"), QUrl::toPercentEncoding(QStringLiteral("%1 %2").arg(request.artist, request.title))); + url_query.addQueryItem(QStringLiteral("q"), QString::fromUtf8(QUrl::toPercentEncoding(QStringLiteral("%1 %2").arg(request.artist, request.title)))); - QUrl url(kUrlSearch); + QUrl url(QString::fromUtf8(kUrlSearch)); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); @@ -460,14 +463,14 @@ void GeniusLyricsProvider::HandleLyricReply(QNetworkReply *reply, const int sear return; } - QByteArray data = reply->readAll(); + const QByteArray data = reply->readAll(); if (data.isEmpty()) { Error(QStringLiteral("Empty reply received from server.")); EndSearch(search, lyric); return; } - QString content = QString::fromUtf8(data); + const QString content = QString::fromUtf8(data); QString lyrics = HtmlLyricsProvider::ParseLyricsFromHTML(content, QRegularExpression(QStringLiteral("]*>")), QRegularExpression(QStringLiteral("<\\/div>")), QRegularExpression(QStringLiteral("
]+>")), true); if (lyrics.isEmpty()) { lyrics = HtmlLyricsProvider::ParseLyricsFromHTML(content, QRegularExpression(QStringLiteral("]*>")), QRegularExpression(QStringLiteral("<\\/div>")), QRegularExpression(QStringLiteral("
")), true); diff --git a/src/lyrics/geniuslyricsprovider.h b/src/lyrics/geniuslyricsprovider.h index 1baf924e0d..040c74f6a5 100644 --- a/src/lyrics/geniuslyricsprovider.h +++ b/src/lyrics/geniuslyricsprovider.h @@ -86,15 +86,6 @@ class GeniusLyricsProvider : public JsonLyricsProvider { void HandleSearchReply(QNetworkReply *reply, const int id); void HandleLyricReply(QNetworkReply *reply, const int search_id, const QUrl &url); - private: - static const char *kSettingsGroup; - static const char *kClientIDB64; - static const char *kClientSecretB64; - static const char *kOAuthAuthorizeUrl; - static const char *kOAuthAccessTokenUrl; - static const char *kOAuthRedirectUrl; - static const char *kUrlSearch; - private: LocalRedirectServer *server_; QString code_verifier_; diff --git a/src/lyrics/htmllyricsprovider.cpp b/src/lyrics/htmllyricsprovider.cpp index f989c87af3..7abc102c94 100644 --- a/src/lyrics/htmllyricsprovider.cpp +++ b/src/lyrics/htmllyricsprovider.cpp @@ -56,7 +56,7 @@ bool HtmlLyricsProvider::StartSearch(const int id, const LyricsSearchRequest &re QUrl url(Url(request)); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (X11; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0"); + req.setHeader(QNetworkRequest::UserAgentHeader, QStringLiteral("Mozilla/5.0 (X11; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0")); QNetworkReply *reply = network_->get(req); replies_ << reply; QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, id, request]() { HandleLyricsReply(reply, id, request); }); @@ -154,11 +154,11 @@ QString HtmlLyricsProvider::ParseLyricsFromHTML(const QString &content, const QR if (end_lyrics_idx != -1 && start_lyrics_idx < end_lyrics_idx) { if (!lyrics.isEmpty()) { - lyrics.append("\n"); + lyrics.append(QLatin1Char('\n')); } lyrics.append(content.mid(start_lyrics_idx, end_lyrics_idx - start_lyrics_idx) - .remove('\r') - .remove('\n') + .remove(QLatin1Char('\r')) + .remove(QLatin1Char('\n')) .remove(QRegularExpression(QStringLiteral("]*>[^<]*"))) .remove(QRegularExpression(QStringLiteral(""))) .remove(QRegularExpression(QStringLiteral("
]*>×
"))) diff --git a/src/lyrics/letraslyricsprovider.cpp b/src/lyrics/letraslyricsprovider.cpp index db04688426..5312dff4be 100644 --- a/src/lyrics/letraslyricsprovider.cpp +++ b/src/lyrics/letraslyricsprovider.cpp @@ -35,22 +35,22 @@ const char LetrasLyricsProvider::kEndTag[] = "<\\/div>"; const char LetrasLyricsProvider::kLyricsStart[] = "
"; LetrasLyricsProvider::LetrasLyricsProvider(SharedPtr network, QObject *parent) - : HtmlLyricsProvider(QStringLiteral("letras.mus.br"), true, kStartTag, kEndTag, kLyricsStart, false, network, parent) {} + : HtmlLyricsProvider(QStringLiteral("letras.mus.br"), true, QString::fromUtf8(kStartTag), QString::fromUtf8(kEndTag), QString::fromUtf8(kLyricsStart), false, network, parent) {} QUrl LetrasLyricsProvider::Url(const LyricsSearchRequest &request) { - return QUrl(QString(kUrl) + QStringLiteral("?musica=") + StringFixup(request.artist) + "&artista=" + StringFixup(request.title)); + return QUrl(QLatin1String(kUrl) + QStringLiteral("?musica=") + StringFixup(request.artist) + QStringLiteral("&artista=") + StringFixup(request.title)); } QString LetrasLyricsProvider::StringFixup(const QString &text) { - return QUrl::toPercentEncoding(Utilities::Transliterate(text) + return QString::fromUtf8(QUrl::toPercentEncoding(Utilities::Transliterate(text) .replace(QRegularExpression(QStringLiteral("[^\\w0-9_,&\\-\\(\\) ]")), QStringLiteral("_")) .replace(QRegularExpression(QStringLiteral(" {2,}")), QStringLiteral(" ")) .simplified() - .replace(' ', '-') + .replace(QLatin1Char(' '), QLatin1Char('-')) .toLower() - ); + )); } diff --git a/src/lyrics/lololyricsprovider.cpp b/src/lyrics/lololyricsprovider.cpp index bb9df97c1a..82c6c60791 100644 --- a/src/lyrics/lololyricsprovider.cpp +++ b/src/lyrics/lololyricsprovider.cpp @@ -37,7 +37,9 @@ #include "lyricssearchresult.h" #include "lololyricsprovider.h" -const char *LoloLyricsProvider::kUrlSearch = "http://api.lololyrics.com/0.5/getLyric"; +namespace { +constexpr char kUrlSearch[] = "http://api.lololyrics.com/0.5/getLyric"; +} LoloLyricsProvider::LoloLyricsProvider(SharedPtr network, QObject *parent) : LyricsProvider(QStringLiteral("LoloLyrics"), true, false, network, parent) {} @@ -55,10 +57,10 @@ LoloLyricsProvider::~LoloLyricsProvider() { bool LoloLyricsProvider::StartSearch(const int id, const LyricsSearchRequest &request) { QUrlQuery url_query; - url_query.addQueryItem(QStringLiteral("artist"), QUrl::toPercentEncoding(request.artist)); - url_query.addQueryItem(QStringLiteral("track"), QUrl::toPercentEncoding(request.title)); + url_query.addQueryItem(QStringLiteral("artist"), QString::fromUtf8(QUrl::toPercentEncoding(request.artist))); + url_query.addQueryItem(QStringLiteral("track"), QString::fromUtf8(QUrl::toPercentEncoding(request.title))); - QUrl url(kUrlSearch); + QUrl url(QString::fromUtf8(kUrlSearch)); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); @@ -103,15 +105,15 @@ void LoloLyricsProvider::HandleSearchReply(QNetworkReply *reply, const int id, c QXmlStreamReader::TokenType type = reader.readNext(); QString name = reader.name().toString(); if (type == QXmlStreamReader::StartElement) { - if (name == "result") { + if (name == QStringLiteral("result")) { status.clear(); result = LyricsSearchResult(); } - else if (name == "status") { + else if (name == QStringLiteral("status")) { status = reader.readElementText(); } - else if (name == "response") { - if (status == "OK") { + else if (name == QStringLiteral("response")) { + if (status == QStringLiteral("OK")) { result.lyrics = reader.readElementText(); } else { @@ -121,7 +123,7 @@ void LoloLyricsProvider::HandleSearchReply(QNetworkReply *reply, const int id, c } } else if (type == QXmlStreamReader::EndElement) { - if (name == "result") { + if (name == QStringLiteral("result")) { if (!result.lyrics.isEmpty()) { result.lyrics = Utilities::DecodeHtmlEntities(result.lyrics); results << result; diff --git a/src/lyrics/lololyricsprovider.h b/src/lyrics/lololyricsprovider.h index be1d330645..0aded88ded 100644 --- a/src/lyrics/lololyricsprovider.h +++ b/src/lyrics/lololyricsprovider.h @@ -52,7 +52,6 @@ class LoloLyricsProvider : public LyricsProvider { void HandleSearchReply(QNetworkReply *reply, const int id, const LyricsSearchRequest &request); private: - static const char *kUrlSearch; QList replies_; }; diff --git a/src/lyrics/lyricsproviders.cpp b/src/lyrics/lyricsproviders.cpp index d5ebc113b8..6fa9962bc9 100644 --- a/src/lyrics/lyricsproviders.cpp +++ b/src/lyrics/lyricsproviders.cpp @@ -28,6 +28,7 @@ #include #include "core/logging.h" +#include "core/settings.h" #include "lyricsprovider.h" #include "lyricsproviders.h" @@ -55,7 +56,7 @@ void LyricsProviders::ReloadSettings() { all_providers.insert(provider->order(), provider->name()); } - QSettings s; + Settings s; s.beginGroup(LyricsSettingsPage::kSettingsGroup); QStringList providers_enabled = s.value("providers", QStringList() << all_providers.values()).toStringList(); s.endGroup(); diff --git a/src/lyrics/musixmatchlyricsprovider.cpp b/src/lyrics/musixmatchlyricsprovider.cpp index 0d9a18aebe..1be41f0e26 100644 --- a/src/lyrics/musixmatchlyricsprovider.cpp +++ b/src/lyrics/musixmatchlyricsprovider.cpp @@ -79,12 +79,12 @@ void MusixmatchLyricsProvider::CancelSearch(const int id) { Q_UNUSED(id); } bool MusixmatchLyricsProvider::SendSearchRequest(LyricsSearchContextPtr search) { QUrlQuery url_query; - url_query.addQueryItem(QStringLiteral("apikey"), QByteArray::fromBase64(kApiKey)); - url_query.addQueryItem(QStringLiteral("q_artist"), QUrl::toPercentEncoding(search->request.artist)); - url_query.addQueryItem(QStringLiteral("q_track"), QUrl::toPercentEncoding(search->request.title)); + url_query.addQueryItem(QStringLiteral("apikey"), QString::fromUtf8(QByteArray::fromBase64(kApiKey))); + url_query.addQueryItem(QStringLiteral("q_artist"), QString::fromUtf8(QUrl::toPercentEncoding(search->request.artist))); + url_query.addQueryItem(QStringLiteral("q_track"), QString::fromUtf8(QUrl::toPercentEncoding(search->request.title))); url_query.addQueryItem(QStringLiteral("f_has_lyrics"), QStringLiteral("1")); - QUrl url(QString(kApiUrl) + QStringLiteral("/track.search")); + QUrl url(QString::fromUtf8(kApiUrl) + QStringLiteral("/track.search")); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); @@ -290,16 +290,16 @@ void MusixmatchLyricsProvider::HandleLyricsReply(QNetworkReply *reply, LyricsSea return; } - QByteArray data = reply->readAll(); + const QByteArray data = reply->readAll(); if (data.isEmpty()) { Error(QStringLiteral("Empty reply received from server.")); EndSearch(search, url); return; } - QString content = data; - QString data_begin = QStringLiteral(""); + const QString content = QString::fromUtf8(data); + const QString data_begin = QStringLiteral(""); qint64 begin_idx = content.indexOf(data_begin); QString content_json; if (begin_idx > 0) { diff --git a/src/lyrics/ovhlyricsprovider.cpp b/src/lyrics/ovhlyricsprovider.cpp index 6cde42d984..9c06e893eb 100644 --- a/src/lyrics/ovhlyricsprovider.cpp +++ b/src/lyrics/ovhlyricsprovider.cpp @@ -53,7 +53,7 @@ OVHLyricsProvider::~OVHLyricsProvider() { bool OVHLyricsProvider::StartSearch(const int id, const LyricsSearchRequest &request) { - QUrl url(kUrlSearch + QString(QUrl::toPercentEncoding(request.artist)) + "/" + QString(QUrl::toPercentEncoding(request.title))); + QUrl url(QString::fromUtf8(kUrlSearch) + QString::fromUtf8(QUrl::toPercentEncoding(request.artist)) + QStringLiteral("/") + QString::fromUtf8(QUrl::toPercentEncoding(request.title))); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); QNetworkReply *reply = network_->get(req); diff --git a/src/lyrics/songlyricscomlyricsprovider.cpp b/src/lyrics/songlyricscomlyricsprovider.cpp index b2f1e79a61..ef606abaa5 100644 --- a/src/lyrics/songlyricscomlyricsprovider.cpp +++ b/src/lyrics/songlyricscomlyricsprovider.cpp @@ -27,28 +27,30 @@ #include "lyricssearchrequest.h" #include "songlyricscomlyricsprovider.h" -const char SongLyricsComLyricsProvider::kUrl[] = "https://www.songlyrics.com/"; -const char SongLyricsComLyricsProvider::kStartTag[] = "]*>"; -const char SongLyricsComLyricsProvider::kEndTag[] = "<\\/p>"; -const char SongLyricsComLyricsProvider::kLyricsStart[] = "

]+>"; +namespace { +constexpr char kUrl[] = "https://www.songlyrics.com/"; +constexpr char kStartTag[] = "]*>"; +constexpr char kEndTag[] = "<\\/p>"; +constexpr char kLyricsStart[] = "

]+>"; +} // namespace SongLyricsComLyricsProvider::SongLyricsComLyricsProvider(SharedPtr network, QObject *parent) - : HtmlLyricsProvider(QStringLiteral("songlyrics.com"), true, kStartTag, kEndTag, kLyricsStart, false, network, parent) {} + : HtmlLyricsProvider(QStringLiteral("songlyrics.com"), true, QLatin1String(kStartTag), QLatin1String(kEndTag), QLatin1String(kLyricsStart), false, network, parent) {} QUrl SongLyricsComLyricsProvider::Url(const LyricsSearchRequest &request) { - return QUrl(kUrl + StringFixup(request.artist) + "/" + StringFixup(request.title) + "-lyrics/"); + return QUrl(QLatin1String(kUrl) + StringFixup(request.artist) + QLatin1Char('/') + StringFixup(request.title) + QStringLiteral("-lyrics/")); } QString SongLyricsComLyricsProvider::StringFixup(QString text) { - return text.replace('/', '-') - .replace('\'', '-') + return text.replace(QLatin1Char('/'), QLatin1Char('-')) + .replace(QLatin1Char('\''), QLatin1Char('-')) .remove(QRegularExpression(QStringLiteral("[^\\w0-9\\- ]"))) .replace(QRegularExpression(QStringLiteral(" {2,}")), QStringLiteral(" ")) .simplified() - .replace(' ', '-') + .replace(QLatin1Char(' '), QLatin1Char('-')) .replace(QRegularExpression(QStringLiteral("(-)\\1+")), QStringLiteral("-")) .toLower(); diff --git a/src/lyrics/songlyricscomlyricsprovider.h b/src/lyrics/songlyricscomlyricsprovider.h index 7a1580d389..1b62c2ed2b 100644 --- a/src/lyrics/songlyricscomlyricsprovider.h +++ b/src/lyrics/songlyricscomlyricsprovider.h @@ -41,12 +41,6 @@ class SongLyricsComLyricsProvider : public HtmlLyricsProvider { private: QString StringFixup(QString text); - - private: - static const char kUrl[]; - static const char kStartTag[]; - static const char kEndTag[]; - static const char kLyricsStart[]; }; #endif // SONGLYRICSCOMLYRICSPROVIDER_H diff --git a/src/main.cpp b/src/main.cpp index 82f9f40616..43b14ae0ed 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -69,6 +69,7 @@ #include "core/scoped_ptr.h" #include "core/shared_ptr.h" +#include "core/settings.h" #include "utilities/envutils.h" @@ -216,7 +217,7 @@ int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, false); { - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); QString style = s.value(AppearanceSettingsPage::kStyle).toString(); if (style.isEmpty()) { @@ -224,7 +225,7 @@ int main(int argc, char *argv[]) { s.setValue(AppearanceSettingsPage::kStyle, style); } s.endGroup(); - if (style != "default") { + if (style != QStringLiteral("default")) { QApplication::setStyle(style); } if (QApplication::style()) qLog(Debug) << "Style:" << QApplication::style()->objectName(); @@ -234,7 +235,7 @@ int main(int argc, char *argv[]) { // On Windows these are stored in the registry instead. #ifdef Q_OS_UNIX { - QSettings s; + Settings s; if (QFile::exists(s.fileName())) { if (!QFile::setPermissions(s.fileName(), QFile::ReadOwner | QFile::WriteOwner)) { qLog(Error) << "Could not set permissions for settingsfile" << s.fileName(); @@ -258,7 +259,7 @@ int main(int argc, char *argv[]) { #ifdef HAVE_TRANSLATIONS QString override_language = options.language(); if (override_language.isEmpty()) { - QSettings s; + Settings s; s.beginGroup(BehaviourSettingsPage::kSettingsGroup); override_language = s.value("language").toString(); s.endGroup(); @@ -266,21 +267,21 @@ int main(int argc, char *argv[]) { QString system_language = QLocale::system().uiLanguages().empty() ? QLocale::system().name() : QLocale::system().uiLanguages().first(); // uiLanguages returns strings with "-" as separators for language/region; however QTranslator needs "_" separators - system_language.replace("-", "_"); + system_language.replace(QLatin1Char('-'), QLatin1Char('_')); const QString language = override_language.isEmpty() ? system_language : override_language; ScopedPtr translations(new Translations); # if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - translations->LoadTranslation("qt", QLibraryInfo::path(QLibraryInfo::TranslationsPath), language); + translations->LoadTranslation(QStringLiteral("qt"), QLibraryInfo::path(QLibraryInfo::TranslationsPath), language); # else - translations->LoadTranslation("qt", QLibraryInfo::location(QLibraryInfo::TranslationsPath), language); + translations->LoadTranslation(QStringLiteral("qt"), QLibraryInfo::location(QLibraryInfo::TranslationsPath), language); # endif - translations->LoadTranslation("strawberry", ":/translations", language); - translations->LoadTranslation("strawberry", TRANSLATIONS_DIR, language); - translations->LoadTranslation("strawberry", QCoreApplication::applicationDirPath(), language); - translations->LoadTranslation("strawberry", QDir::currentPath(), language); + translations->LoadTranslation(QStringLiteral("strawberry"), QStringLiteral(":/translations"), language); + translations->LoadTranslation(QStringLiteral("strawberry"), QLatin1String(TRANSLATIONS_DIR), language); + translations->LoadTranslation(QStringLiteral("strawberry"), QCoreApplication::applicationDirPath(), language); + translations->LoadTranslation(QStringLiteral("strawberry"), QDir::currentPath(), language); # ifdef HAVE_QTSPARKLE //qtsparkle::LoadTranslations(language); diff --git a/src/moodbar/moodbarcontroller.cpp b/src/moodbar/moodbarcontroller.cpp index 2251346528..1b0fd1cc2f 100644 --- a/src/moodbar/moodbarcontroller.cpp +++ b/src/moodbar/moodbarcontroller.cpp @@ -44,7 +44,7 @@ MoodbarController::MoodbarController(Application *app, QObject *parent) void MoodbarController::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(MoodbarSettingsPage::kSettingsGroup); enabled_ = s.value("enabled", false).toBool(); s.endGroup(); diff --git a/src/moodbar/moodbaritemdelegate.cpp b/src/moodbar/moodbaritemdelegate.cpp index 92b1c1ba42..353665a465 100644 --- a/src/moodbar/moodbaritemdelegate.cpp +++ b/src/moodbar/moodbaritemdelegate.cpp @@ -32,6 +32,7 @@ #include #include "core/application.h" +#include "core/settings.h" #include "playlist/playlist.h" #include "playlist/playlistview.h" #include "playlist/playlistfilter.h" @@ -59,7 +60,7 @@ MoodbarItemDelegate::MoodbarItemDelegate(Application *app, PlaylistView *view, Q void MoodbarItemDelegate::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(MoodbarSettingsPage::kSettingsGroup); enabled_ = s.value("enabled", false).toBool(); const MoodbarRenderer::MoodbarStyle new_style = static_cast(s.value("style", static_cast(MoodbarRenderer::MoodbarStyle::Normal)).toInt()); diff --git a/src/moodbar/moodbarloader.cpp b/src/moodbar/moodbarloader.cpp index 2d239318bd..b6980cde8e 100644 --- a/src/moodbar/moodbarloader.cpp +++ b/src/moodbar/moodbarloader.cpp @@ -40,6 +40,7 @@ #include "core/logging.h" #include "core/scoped_ptr.h" #include "core/application.h" +#include "core/settings.h" #include "moodbarpipeline.h" @@ -58,7 +59,7 @@ MoodbarLoader::MoodbarLoader(Application *app, QObject *parent) kMaxActiveRequests(qMax(1, QThread::idealThreadCount() / 2)), save_(false) { - cache_->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/moodbar"); + cache_->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/moodbar")); cache_->setMaximumCacheSize(60 * 1024 * 1024); // 60MB - enough for 20,000 moodbars QObject::connect(app, &Application::SettingsChanged, this, &MoodbarLoader::ReloadSettings); @@ -73,7 +74,7 @@ MoodbarLoader::~MoodbarLoader() { void MoodbarLoader::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(MoodbarSettingsPage::kSettingsGroup); save_ = s.value("save", false).toBool(); s.endGroup(); @@ -86,15 +87,15 @@ QStringList MoodbarLoader::MoodFilenames(const QString &song_filename) { const QFileInfo file_info(song_filename); const QString dir_path(file_info.dir().path()); - const QString mood_filename = file_info.completeBaseName() + ".mood"; + const QString mood_filename = file_info.completeBaseName() + QStringLiteral(".mood"); - return QStringList() << dir_path + "/." + mood_filename << dir_path + "/" + mood_filename; + return QStringList() << dir_path + QStringLiteral("/.") + mood_filename << dir_path + QLatin1Char('/') + mood_filename; } QUrl MoodbarLoader::CacheUrlEntry(const QString &filename) { - return QUrl(QUrl::toPercentEncoding(filename)); + return QUrl(QString::fromUtf8(QUrl::toPercentEncoding(filename))); } diff --git a/src/moodbar/moodbarpipeline.cpp b/src/moodbar/moodbarpipeline.cpp index d73330a464..56516eb598 100644 --- a/src/moodbar/moodbarpipeline.cpp +++ b/src/moodbar/moodbarpipeline.cpp @@ -71,7 +71,7 @@ GstElement *MoodbarPipeline::CreateElement(const QString &factory_name) { QByteArray MoodbarPipeline::ToGstUrl(const QUrl &url) { if (url.isLocalFile() && !url.host().isEmpty()) { - QString str = "file:////" + url.host() + url.path(); + QString str = QStringLiteral("file:////") + url.host() + url.path(); return str.toUtf8(); } diff --git a/src/moodbar/moodbarproxystyle.cpp b/src/moodbar/moodbarproxystyle.cpp index f16a47974e..35c01a6545 100644 --- a/src/moodbar/moodbarproxystyle.cpp +++ b/src/moodbar/moodbarproxystyle.cpp @@ -37,6 +37,7 @@ #include #include "core/application.h" +#include "core/settings.h" #include "moodbarproxystyle.h" #include "moodbarrenderer.h" @@ -74,7 +75,7 @@ MoodbarProxyStyle::MoodbarProxyStyle(Application *app, QSlider *slider, QObject* void MoodbarProxyStyle::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(MoodbarSettingsPage::kSettingsGroup); // Get the enabled/disabled setting, and start the timelines if there's a change. enabled_ = s.value("show", false).toBool(); @@ -107,7 +108,7 @@ void MoodbarProxyStyle::SetMoodbarEnabled(const bool enabled) { enabled_ = enabled; // Save the enabled setting. - QSettings s; + Settings s; s.beginGroup(MoodbarSettingsPage::kSettingsGroup); s.setValue("show", enabled); s.endGroup(); @@ -403,7 +404,7 @@ void MoodbarProxyStyle::ShowContextMenu(const QPoint pos) { void MoodbarProxyStyle::ChangeStyle(QAction *action) { - QSettings s; + Settings s; s.beginGroup(MoodbarSettingsPage::kSettingsGroup); s.setValue("style", action->data().toInt()); s.endGroup(); diff --git a/src/musicbrainz/acoustidclient.cpp b/src/musicbrainz/acoustidclient.cpp index c83ecf0fc9..15285c3422 100644 --- a/src/musicbrainz/acoustidclient.cpp +++ b/src/musicbrainz/acoustidclient.cpp @@ -48,9 +48,11 @@ #include "acoustidclient.h" -const char *AcoustidClient::kClientId = "0qjUoxbowg"; -const char *AcoustidClient::kUrl = "https://api.acoustid.org/v2/lookup"; -const int AcoustidClient::kDefaultTimeout = 5000; // msec +namespace { +constexpr char kClientId[] = "0qjUoxbowg"; +constexpr char kUrl[] = "https://api.acoustid.org/v2/lookup"; +constexpr int kDefaultTimeout = 5000; // msec +} // namespace AcoustidClient::AcoustidClient(SharedPtr network, QObject *parent) : QObject(parent), @@ -70,15 +72,15 @@ void AcoustidClient::Start(const int id, const QString &fingerprint, int duratio using Param = QPair; using ParamList = QList; - const ParamList params = ParamList() << Param("format", "json") - << Param("client", kClientId) - << Param("duration", QString::number(duration_msec / kMsecPerSec)) - << Param("meta", "recordingids+sources") - << Param("fingerprint", fingerprint); + const ParamList params = ParamList() << Param(QStringLiteral("format"), QStringLiteral("json")) + << Param(QStringLiteral("client"), QLatin1String(kClientId)) + << Param(QStringLiteral("duration"), QString::number(duration_msec / kMsecPerSec)) + << Param(QStringLiteral("meta"), QStringLiteral("recordingids+sources")) + << Param(QStringLiteral("fingerprint"), fingerprint); QUrlQuery url_query; url_query.setQueryItems(params); - QUrl url(kUrl); + QUrl url(QString::fromLatin1(kUrl)); url.setQuery(url_query); QNetworkRequest req(url); @@ -149,7 +151,7 @@ void AcoustidClient::RequestFinished(QNetworkReply *reply, const int request_id) QJsonObject json_object = json_document.object(); QString status = json_object[QStringLiteral("status")].toString(); - if (status != "ok") { + if (status != QStringLiteral("ok")) { emit Finished(request_id, QStringList(), status); return; } diff --git a/src/musicbrainz/acoustidclient.h b/src/musicbrainz/acoustidclient.h index a0374b5349..06e39286f5 100644 --- a/src/musicbrainz/acoustidclient.h +++ b/src/musicbrainz/acoustidclient.h @@ -67,10 +67,6 @@ class AcoustidClient : public QObject { void RequestFinished(QNetworkReply *reply, const int id); private: - static const char *kClientId; - static const char *kUrl; - static const int kDefaultTimeout; - SharedPtr network_; NetworkTimeouts *timeouts_; QMap requests_; diff --git a/src/musicbrainz/musicbrainzclient.cpp b/src/musicbrainz/musicbrainzclient.cpp index e62502964a..fb63eb9a4d 100644 --- a/src/musicbrainz/musicbrainzclient.cpp +++ b/src/musicbrainz/musicbrainzclient.cpp @@ -49,12 +49,14 @@ #include "utilities/xmlutils.h" #include "musicbrainzclient.h" -const char *MusicBrainzClient::kTrackUrl = "https://musicbrainz.org/ws/2/recording/"; -const char *MusicBrainzClient::kDiscUrl = "https://musicbrainz.org/ws/2/discid/"; -const char *MusicBrainzClient::kDateRegex = "^[12]\\d{3}"; -const int MusicBrainzClient::kRequestsDelay = 1200; -const int MusicBrainzClient::kDefaultTimeout = 8000; -const int MusicBrainzClient::kMaxRequestPerTrack = 3; +namespace { +constexpr char kTrackUrl[] = "https://musicbrainz.org/ws/2/recording/"; +constexpr char kDiscUrl[] = "https://musicbrainz.org/ws/2/discid/"; +constexpr char kDateRegex[] = "^[12]\\d{3}"; +constexpr int kRequestsDelay = 1200; +constexpr int kDefaultTimeout = 8000; +constexpr int kMaxRequestPerTrack = 3; +} // namespace MusicBrainzClient::MusicBrainzClient(SharedPtr network, QObject *parent) : QObject(parent), @@ -151,11 +153,11 @@ void MusicBrainzClient::Start(const int id, const QStringList &mbid_list) { void MusicBrainzClient::StartDiscIdRequest(const QString &discid) { - const ParamList params = ParamList() << Param("inc", "artists+recordings"); + const ParamList params = ParamList() << Param(QStringLiteral("inc"), QStringLiteral("artists+recordings")); QUrlQuery url_query; url_query.setQueryItems(params); - QUrl url(kDiscUrl + discid); + QUrl url(QString::fromLatin1(kDiscUrl) + discid); url.setQuery(url_query); QNetworkRequest req(url); @@ -173,11 +175,11 @@ void MusicBrainzClient::FlushRequests() { Request request = requests_pending_.take(requests_pending_.firstKey()); - const ParamList params = ParamList() << Param("inc", "artists+releases+media"); + const ParamList params = ParamList() << Param(QStringLiteral("inc"), QStringLiteral("artists+releases+media")); QUrlQuery url_query; url_query.setQueryItems(params); - QUrl url(kTrackUrl + request.mbid); + QUrl url(QString::fromLatin1(kTrackUrl) + request.mbid); url.setQuery(url_query); QNetworkRequest req(url); @@ -210,7 +212,7 @@ void MusicBrainzClient::RequestFinished(QNetworkReply *reply, const int id, cons QXmlStreamReader reader(data); ResultList res; while (!reader.atEnd()) { - if (reader.readNext() == QXmlStreamReader::StartElement && reader.name().toString() == "recording") { + if (reader.readNext() == QXmlStreamReader::StartElement && reader.name().toString() == QStringLiteral("recording")) { ResultList tracks = ParseTrack(&reader); for (const Result &track : tracks) { if (!track.title_.isEmpty()) { @@ -265,20 +267,20 @@ void MusicBrainzClient::DiscIdRequestFinished(const QString &discid, QNetworkRep QXmlStreamReader::TokenType type = reader.readNext(); if (type == QXmlStreamReader::StartElement) { QString name = reader.name().toString(); - if (name == "title") { + if (name == QStringLiteral("title")) { album = reader.readElementText(); } - else if (name == "date") { - QRegularExpression regex(kDateRegex); + else if (name == QStringLiteral("date")) { + QRegularExpression regex(QString::fromLatin1(kDateRegex)); QRegularExpressionMatch re_match = regex.match(reader.readElementText()); if (re_match.capturedStart() == 0) { year = re_match.captured(0).toInt(); } } - else if (name == "artist-credit") { + else if (name == QStringLiteral("artist-credit")) { ParseArtist(&reader, &artist); } - else if (name == "medium-list") { + else if (name == QStringLiteral("medium-list")) { break; } } @@ -287,7 +289,7 @@ void MusicBrainzClient::DiscIdRequestFinished(const QString &discid, QNetworkRep while (!reader.atEnd()) { QXmlStreamReader::TokenType token = reader.readNext(); QString name = reader.name().toString(); - if (token == QXmlStreamReader::StartElement && name == "medium") { + if (token == QXmlStreamReader::StartElement && name == QStringLiteral("medium")) { // Get the medium with a matching discid. if (MediumHasDiscid(discid, &reader)) { ResultList tracks = ParseMedium(&reader); @@ -301,7 +303,7 @@ void MusicBrainzClient::DiscIdRequestFinished(const QString &discid, QNetworkRep Utilities::ConsumeCurrentElement(&reader); } } - else if (token == QXmlStreamReader::EndElement && name == "medium-list") { + else if (token == QXmlStreamReader::EndElement && name == QStringLiteral("medium-list")) { break; } } @@ -323,10 +325,10 @@ bool MusicBrainzClient::MediumHasDiscid(const QString &discid, QXmlStreamReader QXmlStreamReader::TokenType type = reader->readNext(); QString name = reader->name().toString(); - if (type == QXmlStreamReader::StartElement && name == "disc" && reader->attributes().value("id").toString() == discid) { + if (type == QXmlStreamReader::StartElement && name == QStringLiteral("disc") && reader->attributes().value(QStringLiteral("id")).toString() == discid) { return true; } - else if (type == QXmlStreamReader::EndElement && name == "disc-list") { + else if (type == QXmlStreamReader::EndElement && name == QStringLiteral("disc-list")) { return false; } } @@ -343,14 +345,14 @@ MusicBrainzClient::ResultList MusicBrainzClient::ParseMedium(QXmlStreamReader *r QString name = reader->name().toString(); if (type == QXmlStreamReader::StartElement) { - if (name == "track") { + if (name == QStringLiteral("track")) { Result result; result = ParseTrackFromDisc(reader); ret << result; } } - if (type == QXmlStreamReader::EndElement && name == "track-list") { + if (type == QXmlStreamReader::EndElement && name == QStringLiteral("track-list")) { break; } } @@ -368,18 +370,18 @@ MusicBrainzClient::Result MusicBrainzClient::ParseTrackFromDisc(QXmlStreamReader QString name = reader->name().toString(); if (type == QXmlStreamReader::StartElement) { - if (name == "position") { + if (name == QStringLiteral("position")) { result.track_ = reader->readElementText().toInt(); } - else if (name == "length") { + else if (name == QStringLiteral("length")) { result.duration_msec_ = reader->readElementText().toInt(); } - else if (name == "title") { + else if (name == QStringLiteral("title")) { result.title_ = reader->readElementText(); } } - if (type == QXmlStreamReader::EndElement && name == "track") { + if (type == QXmlStreamReader::EndElement && name == QStringLiteral("track")) { break; } } @@ -398,21 +400,21 @@ MusicBrainzClient::ResultList MusicBrainzClient::ParseTrack(QXmlStreamReader *re if (type == QXmlStreamReader::StartElement) { - if (name == "title") { + if (name == QStringLiteral("title")) { result.title_ = reader->readElementText(); } - else if (name == "length") { + else if (name == QStringLiteral("length")) { result.duration_msec_ = reader->readElementText().toInt(); } - else if (name == "artist-credit") { + else if (name == QStringLiteral("artist-credit")) { ParseArtist(reader, &result.artist_); } - else if (name == "release") { + else if (name == QStringLiteral("release")) { releases << ParseRelease(reader); } } - if (type == QXmlStreamReader::EndElement && name == "recording") { + if (type == QXmlStreamReader::EndElement && name == QStringLiteral("recording")) { break; } } @@ -439,15 +441,15 @@ void MusicBrainzClient::ParseArtist(QXmlStreamReader *reader, QString *artist) { while (!reader->atEnd()) { QXmlStreamReader::TokenType type = reader->readNext(); QString name = reader->name().toString(); - if (type == QXmlStreamReader::StartElement && name == "name-credit") { - join_phrase = reader->attributes().value("joinphrase").toString(); + if (type == QXmlStreamReader::StartElement && name == QStringLiteral("name-credit")) { + join_phrase = reader->attributes().value(QStringLiteral("joinphrase")).toString(); } - if (type == QXmlStreamReader::StartElement && name == "name") { + if (type == QXmlStreamReader::StartElement && name == QStringLiteral("name")) { *artist += reader->readElementText() + join_phrase; } - if (type == QXmlStreamReader::EndElement && name == "artist-credit") { + if (type == QXmlStreamReader::EndElement && name == QStringLiteral("artist-credit")) { return; } } @@ -462,26 +464,26 @@ MusicBrainzClient::Release MusicBrainzClient::ParseRelease(QXmlStreamReader *rea QString name = reader->name().toString(); if (type == QXmlStreamReader::StartElement) { - if (name == "title") { + if (name == QStringLiteral("title")) { ret.album_ = reader->readElementText(); } - else if (name == "status") { + else if (name == QStringLiteral("status")) { ret.SetStatusFromString(reader->readElementText()); } - else if (name == "date") { - QRegularExpression regex(kDateRegex); + else if (name == QStringLiteral("date")) { + QRegularExpression regex(QString::fromLatin1(kDateRegex)); QRegularExpressionMatch re_match = regex.match(reader->readElementText()); if (re_match.capturedStart() == 0) { ret.year_ = re_match.captured(0).toInt(); } } - else if (name == "track-list") { - ret.track_ = reader->attributes().value("offset").toString().toInt() + 1; + else if (name == QStringLiteral("track-list")) { + ret.track_ = reader->attributes().value(QStringLiteral("offset")).toString().toInt() + 1; Utilities::ConsumeCurrentElement(reader); } } - if (type == QXmlStreamReader::EndElement && name == "release") { + if (type == QXmlStreamReader::EndElement && name == QStringLiteral("release")) { break; } } diff --git a/src/musicbrainz/musicbrainzclient.h b/src/musicbrainz/musicbrainzclient.h index b37f6589a1..608276bc88 100644 --- a/src/musicbrainz/musicbrainzclient.h +++ b/src/musicbrainz/musicbrainzclient.h @@ -202,14 +202,6 @@ class MusicBrainzClient : public QObject { static void Error(const QString &error, const QVariant &debug = QVariant()); private: - - static const char *kTrackUrl; - static const char *kDiscUrl; - static const char *kDateRegex; - static const int kRequestsDelay; - static const int kDefaultTimeout; - static const int kMaxRequestPerTrack; - SharedPtr network_; NetworkTimeouts *timeouts_; QMultiMap requests_pending_; diff --git a/src/organize/organize.cpp b/src/organize/organize.cpp index 5c88ccb8f0..cd6799ec1d 100644 --- a/src/organize/organize.cpp +++ b/src/organize/organize.cpp @@ -248,7 +248,7 @@ void Organize::ProcessSomeFiles() { } if (!job.cover_source_.isEmpty()) { - job.cover_dest_ = QFileInfo(job.destination_).path() + "/" + QFileInfo(job.cover_source_).fileName(); + job.cover_dest_ = QFileInfo(job.destination_).path() + QLatin1Char('/') + QFileInfo(job.cover_source_).fileName(); } job.progress_ = std::bind(&Organize::SetSongProgress, this, std::placeholders::_1, !task.transcoded_filename_.isEmpty()); @@ -258,7 +258,7 @@ void Organize::ProcessSomeFiles() { if (job.remove_original_ && song.is_collection_song() && destination_->source() == Song::Source::Collection) { // Notify other aspects of system that song has been invalidated QString root = destination_->LocalPath(); - QFileInfo new_file = QFileInfo(root + "/" + task.song_info_.new_filename_); + QFileInfo new_file = QFileInfo(root + QLatin1Char('/') + task.song_info_.new_filename_); emit SongPathChanged(song, new_file, destination_->collection_directory_id()); } } diff --git a/src/organize/organizedialog.cpp b/src/organize/organizedialog.cpp index a02caeb83c..bf3af266bb 100644 --- a/src/organize/organizedialog.cpp +++ b/src/organize/organizedialog.cpp @@ -59,6 +59,7 @@ #include "core/iconloader.h" #include "core/musicstorage.h" #include "core/tagreaderclient.h" +#include "core/settings.h" #include "utilities/strutils.h" #include "utilities/screenutils.h" #include "widgets/freespacebar.h" @@ -75,8 +76,10 @@ using std::make_unique; -constexpr char OrganizeDialog::kSettingsGroup[] = "OrganizeDialog"; -constexpr char OrganizeDialog::kDefaultFormat[] = "%albumartist/%album{ (Disc %disc)}/{%track - }{%albumartist - }%album{ (Disc %disc)} - %title.%extension"; +namespace { +constexpr char kSettingsGroup[] = "OrganizeDialog"; +constexpr char kDefaultFormat[] = "%albumartist/%album{ (Disc %disc)}/{%track - }{%albumartist - }%album{ (Disc %disc)} - %title.%extension"; +} OrganizeDialog::OrganizeDialog(SharedPtr task_manager, SharedPtr collection_backend, QWidget *parentwindow, QWidget *parent) : QDialog(parent), @@ -213,7 +216,7 @@ void OrganizeDialog::LoadGeometry() { AdjustSize(); } else { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); if (s.contains("geometry")) { restoreGeometry(s.value("geometry").toByteArray()); @@ -231,7 +234,7 @@ void OrganizeDialog::LoadGeometry() { void OrganizeDialog::SaveGeometry() { if (parentwindow_) { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("geometry", saveGeometry()); s.endGroup(); @@ -270,7 +273,7 @@ void OrganizeDialog::AdjustSize() { void OrganizeDialog::RestoreDefaults() { - ui_->naming->setPlainText(kDefaultFormat); + ui_->naming->setPlainText(QLatin1String(kDefaultFormat)); ui_->remove_problematic->setChecked(true); ui_->remove_non_fat->setChecked(false); ui_->remove_non_ascii->setChecked(false); @@ -284,9 +287,9 @@ void OrganizeDialog::RestoreDefaults() { void OrganizeDialog::LoadSettings() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); - ui_->naming->setPlainText(s.value("format", kDefaultFormat).toString()); + ui_->naming->setPlainText(s.value("format", QLatin1String(kDefaultFormat)).toString()); ui_->remove_problematic->setChecked(s.value("remove_problematic", true).toBool()); ui_->remove_non_fat->setChecked(s.value("remove_non_fat", false).toBool()); ui_->remove_non_ascii->setChecked(s.value("remove_non_ascii", false).toBool()); @@ -310,7 +313,7 @@ void OrganizeDialog::LoadSettings() { void OrganizeDialog::SaveSettings() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("format", ui_->naming->toPlainText()); s.setValue("remove_problematic", ui_->remove_problematic->isChecked()); @@ -430,7 +433,7 @@ void OrganizeDialog::SetPlaylist(const QString &playlist) { } void OrganizeDialog::InsertTag(const QString &tag) { - ui_->naming->insertPlainText("%" + tag); + ui_->naming->insertPlainText(QLatin1Char('%') + tag); } Organize::NewSongInfoList OrganizeDialog::ComputeNewSongsFilenames(const SongList &songs, const OrganizeFormat &format, const QString &extension) { @@ -449,7 +452,7 @@ Organize::NewSongInfoList OrganizeDialog::ComputeNewSongsFilenames(const SongLis if (result.unique_filename) { if (filenames.contains(result.filename)) { QString song_number = QString::number(++filenames[result.filename]); - result.filename = Utilities::PathWithoutFilenameExtension(result.filename) + "(" + song_number + ")." + QFileInfo(result.filename).suffix(); + result.filename = Utilities::PathWithoutFilenameExtension(result.filename) + QStringLiteral("(") + song_number + QStringLiteral(").") + QFileInfo(result.filename).suffix(); } else { filenames.insert(result.filename, 1); @@ -529,7 +532,7 @@ void OrganizeDialog::UpdatePreviews() { ui_->groupbox_naming->setVisible(has_local_destination); if (has_local_destination) { for (const Organize::NewSongInfo &song_info : new_songs_info_) { - QString filename = storage->LocalPath() + "/" + song_info.new_filename_; + QString filename = storage->LocalPath() + QLatin1Char('/') + song_info.new_filename_; QListWidgetItem *item = new QListWidgetItem(song_info.unique_filename_ ? IconLoader::Load(QStringLiteral("dialog-ok-apply")) : IconLoader::Load(QStringLiteral("dialog-warning")), QDir::toNativeSeparators(filename), ui_->preview); ui_->preview->addItem(item); if (!song_info.unique_filename_) { diff --git a/src/organize/organizedialog.h b/src/organize/organizedialog.h index 92d06a2d9b..d53185171f 100644 --- a/src/organize/organizedialog.h +++ b/src/organize/organizedialog.h @@ -105,9 +105,6 @@ class OrganizeDialog : public QDialog { void AllowExtASCII(const bool checked); private: - static const char kSettingsGroup[]; - static const char kDefaultFormat[]; - QWidget *parentwindow_; Ui_OrganizeDialog *ui_; SharedPtr task_manager_; diff --git a/src/organize/organizeformat.cpp b/src/organize/organizeformat.cpp index 76837ae671..01a14762d3 100644 --- a/src/organize/organizeformat.cpp +++ b/src/organize/organizeformat.cpp @@ -43,8 +43,10 @@ #include "organizeformat.h" -constexpr char OrganizeFormat::kBlockPattern[] = "\\{([^{}]+)\\}"; -constexpr char OrganizeFormat::kTagPattern[] = "\\%([a-zA-Z]*)"; +namespace { +static constexpr char kBlockPattern[] = "\\{([^{}]+)\\}"; +static constexpr char kTagPattern[] = "\\%([a-zA-Z]*)"; +} const QStringList OrganizeFormat::kKnownTags = QStringList() << QStringLiteral("title") << QStringLiteral("album") @@ -88,7 +90,7 @@ OrganizeFormat::OrganizeFormat(const QString &format) void OrganizeFormat::set_format(const QString &v) { format_ = v; - format_.replace('\\', '/'); + format_.replace(QLatin1Char('\\'), QLatin1Char('/')); } bool OrganizeFormat::IsValid() const { @@ -119,21 +121,21 @@ OrganizeFormat::GetFilenameForSongResult OrganizeFormat::GetFilenameForSong(cons filepath.clear(); if (!path.isEmpty()) { filepath.append(path); - if (path.right(1) != '/') { - filepath.append('/'); + if (path.right(1) != QLatin1Char('/')) { + filepath.append(QLatin1Char('/')); } } filepath.append(song.basefilename()); } } - if (filepath.isEmpty() || (filepath.contains('/') && (filepath.section('/', 0, -2).isEmpty() || filepath.section('/', 0, -2).isEmpty()))) { + if (filepath.isEmpty() || (filepath.contains(QLatin1Char('/')) && (filepath.section(QLatin1Char('/'), 0, -2).isEmpty() || filepath.section(QLatin1Char('/'), 0, -2).isEmpty()))) { return GetFilenameForSongResult(); } - if (remove_problematic_) filepath = filepath.remove(QRegularExpression(QString(kProblematicCharactersRegex), QRegularExpression::PatternOption::CaseInsensitiveOption)); + if (remove_problematic_) filepath = filepath.remove(QRegularExpression(QLatin1String(kProblematicCharactersRegex), QRegularExpression::PatternOption::CaseInsensitiveOption)); if (remove_non_fat_ || (remove_non_ascii_ && !allow_ascii_ext_)) filepath = Utilities::Transliterate(filepath); - if (remove_non_fat_) filepath = filepath.remove(QRegularExpression(QString(kInvalidFatCharactersRegex), QRegularExpression::PatternOption::CaseInsensitiveOption)); + if (remove_non_fat_) filepath = filepath.remove(QRegularExpression(QLatin1String(kInvalidFatCharactersRegex), QRegularExpression::PatternOption::CaseInsensitiveOption)); if (remove_non_ascii_) { int ascii = 128; @@ -168,9 +170,9 @@ OrganizeFormat::GetFilenameForSongResult OrganizeFormat::GetFilenameForSong(cons extension = info.suffix(); } } - if (!info.path().isEmpty() && info.path() != ".") { + if (!info.path().isEmpty() && info.path() != QStringLiteral(".")) { filepath.append(info.path()); - filepath.append("/"); + filepath.append(QLatin1Char('/')); } filepath.append(info.completeBaseName()); @@ -180,7 +182,7 @@ OrganizeFormat::GetFilenameForSongResult OrganizeFormat::GetFilenameForSong(cons for (int i = 0; i < parts_old.count(); ++i) { QString part = parts_old[i]; for (int j = 0; j < kInvalidPrefixCharactersCount; ++j) { - if (part.startsWith(kInvalidPrefixCharacters[j])) { + if (part.startsWith(QLatin1Char(kInvalidPrefixCharacters[j]))) { part = part.remove(0, 1); break; } @@ -204,7 +206,7 @@ QString OrganizeFormat::ParseBlock(QString block, const Song &song, bool *have_t // Find any blocks first qint64 pos = 0; - const QRegularExpression block_regexp(kBlockPattern); + const QRegularExpression block_regexp(QString::fromUtf8(kBlockPattern)); QRegularExpressionMatch re_match; for (re_match = block_regexp.match(block, pos); re_match.hasMatch(); re_match = block_regexp.match(block, pos)) { pos = re_match.capturedStart(); @@ -221,7 +223,7 @@ QString OrganizeFormat::ParseBlock(QString block, const Song &song, bool *have_t // Now look for tags bool empty = false; pos = 0; - const QRegularExpression tag_regexp(kTagPattern); + const QRegularExpression tag_regexp(QString::fromUtf8(kTagPattern)); for (re_match = tag_regexp.match(block, pos); re_match.hasMatch(); re_match = tag_regexp.match(block, pos)) { pos = re_match.capturedStart(); const QString tag = re_match.captured(1); @@ -249,79 +251,79 @@ QString OrganizeFormat::TagValue(const QString &tag, const Song &song) const { QString value; - if (tag == "title") { + if (tag == QStringLiteral("title")) { value = song.title(); } - else if (tag == "album") { + else if (tag == QStringLiteral("album")) { value = song.album(); } - else if (tag == "artist") { + else if (tag == QStringLiteral("artist")) { value = song.artist(); } - else if (tag == "composer") { + else if (tag == QStringLiteral("composer")) { value = song.composer(); } - else if (tag == "performer") { + else if (tag == QStringLiteral("performer")) { value = song.performer(); } - else if (tag == "grouping") { + else if (tag == QStringLiteral("grouping")) { value = song.grouping(); } - else if (tag == "lyrics") { + else if (tag == QStringLiteral("lyrics")) { value = song.lyrics(); } - else if (tag == "genre") { + else if (tag == QStringLiteral("genre")) { value = song.genre(); } - else if (tag == "comment") { + else if (tag == QStringLiteral("comment")) { value = song.comment(); } - else if (tag == "year") { + else if (tag == QStringLiteral("year")) { value = QString::number(song.year()); } - else if (tag == "originalyear") { + else if (tag == QStringLiteral("originalyear")) { value = QString::number(song.effective_originalyear()); } - else if (tag == "track") { + else if (tag == QStringLiteral("track")) { value = QString::number(song.track()); } - else if (tag == "disc") { + else if (tag == QStringLiteral("disc")) { value = QString::number(song.disc()); } - else if (tag == "length") { + else if (tag == QStringLiteral("length")) { value = QString::number(song.length_nanosec() / kNsecPerSec); } - else if (tag == "bitrate") { + else if (tag == QStringLiteral("bitrate")) { value = QString::number(song.bitrate()); } - else if (tag == "samplerate") { + else if (tag == QStringLiteral("samplerate")) { value = QString::number(song.samplerate()); } - else if (tag == "bitdepth") { + else if (tag == QStringLiteral("bitdepth")) { value = QString::number(song.bitdepth()); } - else if (tag == "extension") { + else if (tag == QStringLiteral("extension")) { value = QFileInfo(song.url().toLocalFile()).suffix(); } - else if (tag == "artistinitial") { + else if (tag == QStringLiteral("artistinitial")) { value = song.effective_albumartist().trimmed(); if (!value.isEmpty()) { value.replace(QRegularExpression(QStringLiteral("^the\\s+"), QRegularExpression::CaseInsensitiveOption), QLatin1String("")); value = value[0].toUpper(); } } - else if (tag == "albumartist") { + else if (tag == QStringLiteral("albumartist")) { value = song.is_compilation() ? QStringLiteral("Various Artists") : song.effective_albumartist(); } - if (value == "0" || value == "-1") value = QLatin1String(""); + if (value == QStringLiteral("0") || value == QStringLiteral("-1")) value = QLatin1String(""); // Prepend a 0 to single-digit track numbers - if (tag == "track" && value.length() == 1) value.prepend('0'); + if (tag == QStringLiteral("track") && value.length() == 1) value.prepend(QLatin1Char('0')); // Replace characters that really shouldn't be in paths - value = value.remove(QRegularExpression(QString(kInvalidDirCharactersRegex), QRegularExpression::PatternOption::CaseInsensitiveOption)); - if (remove_problematic_) value = value.remove('.'); + value = value.remove(QRegularExpression(QString::fromLatin1(kInvalidDirCharactersRegex), QRegularExpression::PatternOption::CaseInsensitiveOption)); + if (remove_problematic_) value = value.remove(QLatin1Char('.')); value = value.trimmed(); return value; @@ -335,10 +337,10 @@ QValidator::State OrganizeFormat::Validator::validate(QString &input, int&) cons // Make sure all the blocks match up int block_level = 0; for (int i = 0; i < input.length(); ++i) { - if (input[i] == '{') { + if (input[i] == QLatin1Char('{')) { ++block_level; } - else if (input[i] == '}') { + else if (input[i] == QLatin1Char('}')) { --block_level; } @@ -348,7 +350,7 @@ QValidator::State OrganizeFormat::Validator::validate(QString &input, int&) cons if (block_level != 0) return QValidator::Invalid; // Make sure the tags are valid - const QRegularExpression tag_regexp(kTagPattern); + const QRegularExpression tag_regexp(QString::fromLatin1(kTagPattern)); QRegularExpressionMatch re_match; qint64 pos = 0; for (re_match = tag_regexp.match(input, pos); re_match.hasMatch(); re_match = tag_regexp.match(input, pos)) { @@ -384,7 +386,7 @@ void OrganizeFormat::SyntaxHighlighter::highlightBlock(const QString &text) { setFormat(0, static_cast(text.length()), QTextCharFormat()); // Blocks - const QRegularExpression block_regexp(kBlockPattern); + const QRegularExpression block_regexp(QString::fromLatin1(kBlockPattern)); QRegularExpressionMatch re_match; qint64 pos = 0; for (re_match = block_regexp.match(text, pos); re_match.hasMatch(); re_match = block_regexp.match(text, pos)) { @@ -394,7 +396,7 @@ void OrganizeFormat::SyntaxHighlighter::highlightBlock(const QString &text) { } // Tags - const QRegularExpression tag_regexp(kTagPattern); + const QRegularExpression tag_regexp(QString::fromLatin1(kTagPattern)); pos = 0; for (re_match = tag_regexp.match(text, pos); re_match.hasMatch(); re_match = tag_regexp.match(text, pos)) { pos = re_match.capturedStart(); diff --git a/src/organize/organizeformat.h b/src/organize/organizeformat.h index 39712bcce1..d61f601043 100644 --- a/src/organize/organizeformat.h +++ b/src/organize/organizeformat.h @@ -85,8 +85,6 @@ class OrganizeFormat { }; private: - static const char kBlockPattern[]; - static const char kTagPattern[]; static const QStringList kKnownTags; static const QStringList kUniqueTags; diff --git a/src/osd/osdbase.cpp b/src/osd/osdbase.cpp index 7f5719386b..1e503cff3b 100644 --- a/src/osd/osdbase.cpp +++ b/src/osd/osdbase.cpp @@ -34,6 +34,7 @@ #include "core/shared_ptr.h" #include "core/application.h" #include "core/logging.h" +#include "core/settings.h" #ifdef Q_OS_MACOS # include "core/macsystemtrayicon.h" #else @@ -74,7 +75,7 @@ OSDBase::~OSDBase() { void OSDBase::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); behaviour_ = static_cast(s.value("Behaviour", static_cast(Behaviour::Native)).toInt()); timeout_msec_ = s.value("Timeout", 5000).toInt(); @@ -200,7 +201,7 @@ void OSDBase::Paused() { else { summary = last_song_.PrettyTitle(); if (!last_song_.artist().isEmpty()) { - summary.prepend(" - "); + summary.prepend(QStringLiteral(" - ")); summary.prepend(last_song_.artist()); } if (behaviour_ == Behaviour::Pretty) { @@ -245,7 +246,7 @@ void OSDBase::Stopped() { else { summary = last_song_.PrettyTitle(); if (!last_song_.artist().isEmpty()) { - summary.prepend(" - "); + summary.prepend(QStringLiteral(" - ")); summary.prepend(last_song_.artist()); } if (behaviour_ == Behaviour::Pretty) { diff --git a/src/osd/osddbus.cpp b/src/osd/osddbus.cpp index de125875cb..842c476846 100644 --- a/src/osd/osddbus.cpp +++ b/src/osd/osddbus.cpp @@ -117,7 +117,7 @@ OSDDBus::~OSDDBus() = default; void OSDDBus::Init() { - interface_ = make_unique(OrgFreedesktopNotificationsInterface::staticInterfaceName(), "/org/freedesktop/Notifications", QDBusConnection::sessionBus()); + interface_ = make_unique(QString::fromUtf8(OrgFreedesktopNotificationsInterface::staticInterfaceName()), QStringLiteral("/org/freedesktop/Notifications"), QDBusConnection::sessionBus()); if (!interface_->isValid()) { qLog(Warning) << "Error connecting to notifications service."; } diff --git a/src/osd/osdpretty.cpp b/src/osd/osdpretty.cpp index 8e8b894cb9..9973bc85bf 100644 --- a/src/osd/osdpretty.cpp +++ b/src/osd/osdpretty.cpp @@ -51,6 +51,8 @@ #include #include +#include "core/settings.h" + #ifdef HAVE_X11EXTRAS # include #elif defined(HAVE_X11) && defined(HAVE_QPA_QPLATFORMNATIVEINTERFACE_H) @@ -232,12 +234,12 @@ bool OSDPretty::IsTransparencyAvailable() { void OSDPretty::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); foreground_color_ = QColor(s.value("foreground_color", 0).toInt()); background_color_ = QColor(s.value("background_color", kPresetBlue).toInt()); background_opacity_ = s.value("background_opacity", 0.85).toFloat(); - font_.fromString(s.value("font", "Verdana,9,-1,5,50,0,0,0,0,0").toString()); + font_.fromString(s.value("font", QStringLiteral("Verdana,9,-1,5,50,0,0,0,0,0")).toString()); disable_duration_ = s.value("disable_duration", false).toBool(); #ifdef Q_OS_WIN fading_enabled_ = s.value("fading", true).toBool(); @@ -245,7 +247,7 @@ void OSDPretty::Load() { fading_enabled_ = s.value("fading", false).toBool(); #endif - if (s.contains("popup_screen")) { + if (s.contains(QStringLiteral("popup_screen"))) { popup_screen_name_ = s.value("popup_screen").toString(); if (screens_.contains(popup_screen_name_)) { popup_screen_ = screens_[popup_screen_name_]; @@ -261,7 +263,7 @@ void OSDPretty::Load() { if (current_screen()) popup_screen_name_ = current_screen()->name(); } - if (s.contains("popup_pos")) { + if (s.contains(QStringLiteral("popup_pos"))) { popup_pos_ = s.value("popup_pos").toPoint(); } else { diff --git a/src/osd/osdpretty.h b/src/osd/osdpretty.h index ba1f8f0e35..87a9cac6f0 100644 --- a/src/osd/osdpretty.h +++ b/src/osd/osdpretty.h @@ -142,7 +142,7 @@ class OSDPretty : public QWidget { Mode mode_; - // Settings loaded from QSettings + // Settings loaded from Settings QColor foreground_color_; QColor background_color_; qreal background_opacity_; diff --git a/src/playlist/playlist.cpp b/src/playlist/playlist.cpp index 45aba524d3..bea2e91839 100644 --- a/src/playlist/playlist.cpp +++ b/src/playlist/playlist.cpp @@ -64,6 +64,7 @@ #include "core/mimedata.h" #include "core/tagreaderclient.h" #include "core/song.h" +#include "core/settings.h" #include "utilities/timeconstants.h" #include "collection/collection.h" #include "collection/collectionbackend.h" @@ -772,7 +773,7 @@ Qt::ItemFlags Playlist::flags(const QModelIndex &idx) const { QStringList Playlist::mimeTypes() const { - return QStringList() << QStringLiteral("text/uri-list") << kRowsMimetype; + return QStringList() << QStringLiteral("text/uri-list") << QString::fromUtf8(kRowsMimetype); } @@ -800,7 +801,7 @@ bool Playlist::dropMimeData(const QMimeData *data, Qt::DropAction action, int ro if (const SongMimeData *song_data = qobject_cast(data)) { // Dragged from a collection // We want to check if these songs are from the actual local file backend, if they are we treat them differently. - if (song_data->backend && song_data->backend->songs_table() == SCollection::kSongsTable) { + if (song_data->backend && song_data->backend->songs_table() == QLatin1String(SCollection::kSongsTable)) { InsertSongItems(song_data->songs, row, play_now, enqueue_now, enqueue_next_now); } else { @@ -819,7 +820,7 @@ bool Playlist::dropMimeData(const QMimeData *data, Qt::DropAction action, int ro else if (const RadioMimeData *radio_data = qobject_cast(data)) { InsertRadioItems(radio_data->songs, row, play_now, enqueue_now, enqueue_next_now); } - else if (data->hasFormat(kRowsMimetype)) { + else if (data->hasFormat(QString::fromUtf8(kRowsMimetype))) { // Dragged from the playlist // Rearranging it is tricky... @@ -829,7 +830,7 @@ bool Playlist::dropMimeData(const QMimeData *data, Qt::DropAction action, int ro qint64 pid = 0; qint64 own_pid = QCoreApplication::applicationPid(); - QDataStream stream(data->data(kRowsMimetype)); + QDataStream stream(data->data(QString::fromUtf8(kRowsMimetype))); stream.readRawData(reinterpret_cast(&source_playlist), sizeof(source_playlist)); // NOLINT(bugprone-sizeof-expression) stream >> source_rows; if (!stream.atEnd()) { @@ -868,7 +869,7 @@ bool Playlist::dropMimeData(const QMimeData *data, Qt::DropAction action, int ro } } } - else if (data->hasFormat(kCddaMimeType)) { + else if (data->hasFormat(QLatin1String(kCddaMimeType))) { SongLoaderInserter *inserter = new SongLoaderInserter(task_manager_, collection_backend_, backend_->app()->player()); QObject::connect(inserter, &SongLoaderInserter::Error, this, &Playlist::Error); inserter->LoadAudioCD(this, row, play_now, enqueue_now, enqueue_next_now); @@ -1291,7 +1292,7 @@ QMimeData *Playlist::mimeData(const QModelIndexList &indexes) const { buf.close(); mimedata->setUrls(urls); - mimedata->setData(kRowsMimetype, buf.data()); + mimedata->setData(QLatin1String(kRowsMimetype), buf.data()); return mimedata; @@ -1361,8 +1362,8 @@ bool Playlist::ComparePathDepths(const Qt::SortOrder order, PlaylistItemPtr _a, PlaylistItemPtr a = order == Qt::AscendingOrder ? _a : _b; PlaylistItemPtr b = order == Qt::AscendingOrder ? _b : _a; - qint64 a_dir_level = a->Url().path().count('/'); - qint64 b_dir_level = b->Url().path().count('/'); + qint64 a_dir_level = a->Url().path().count(QLatin1Char('/')); + qint64 b_dir_level = b->Url().path().count(QLatin1Char('/')); return a_dir_level < b_dir_level; @@ -1615,7 +1616,7 @@ void Playlist::ItemsLoaded() { emit RestoreFinished(); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); bool greyout = s.value("greyout_songs_startup", true).toBool(); s.endGroup(); diff --git a/src/playlist/playlistbackend.cpp b/src/playlist/playlistbackend.cpp index 5ecd12ea74..662fe3c16e 100644 --- a/src/playlist/playlistbackend.cpp +++ b/src/playlist/playlistbackend.cpp @@ -116,11 +116,11 @@ PlaylistBackend::PlaylistList PlaylistBackend::GetPlaylists(const GetPlaylistsFl } QString condition; if (!condition_list.isEmpty()) { - condition = " WHERE " + condition_list.join(QStringLiteral(" OR ")); + condition = QStringLiteral(" WHERE ") + condition_list.join(QStringLiteral(" OR ")); } SqlQuery q(db); - q.prepare("SELECT ROWID, name, last_played, special_type, ui_path, is_favorite, dynamic_playlist_type, dynamic_playlist_data, dynamic_playlist_backend FROM playlists " + condition + " ORDER BY ui_order"); + q.prepare(QStringLiteral("SELECT ROWID, name, last_played, special_type, ui_path, is_favorite, dynamic_playlist_type, dynamic_playlist_data, dynamic_playlist_backend FROM playlists ") + condition + QStringLiteral(" ORDER BY ui_order")); if (!q.Exec()) { db_->ReportErrors(q); return ret; @@ -184,7 +184,7 @@ PlaylistItemPtrList PlaylistBackend::GetPlaylistItems(const int playlist) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QString query = "SELECT songs.ROWID, " + Song::JoinSpec(QStringLiteral("songs")) + ", p.ROWID, " + Song::JoinSpec(QStringLiteral("p")) + ", p.type FROM playlist_items AS p LEFT JOIN songs ON p.collection_id = songs.ROWID WHERE p.playlist = :playlist"; + QString query = QStringLiteral("SELECT songs.ROWID, ") + Song::JoinSpec(QStringLiteral("songs")) + QStringLiteral(", p.ROWID, ") + Song::JoinSpec(QStringLiteral("p")) + QStringLiteral(", p.type FROM playlist_items AS p LEFT JOIN songs ON p.collection_id = songs.ROWID WHERE p.playlist = :playlist"); SqlQuery q(db); // Forward iterations only may be faster q.setForwardOnly(true); @@ -219,7 +219,7 @@ SongList PlaylistBackend::GetPlaylistSongs(const int playlist) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QString query = "SELECT songs.ROWID, " + Song::JoinSpec(QStringLiteral("songs")) + ", p.ROWID, " + Song::JoinSpec(QStringLiteral("p")) + ", p.type FROM playlist_items AS p LEFT JOIN songs ON p.collection_id = songs.ROWID WHERE p.playlist = :playlist"; + QString query = QStringLiteral("SELECT songs.ROWID, ") + Song::JoinSpec(QStringLiteral("songs")) + QStringLiteral(", p.ROWID, ") + Song::JoinSpec(QStringLiteral("p")) + QStringLiteral(", p.type FROM playlist_items AS p LEFT JOIN songs ON p.collection_id = songs.ROWID WHERE p.playlist = :playlist"); SqlQuery q(db); // Forward iterations only may be faster q.setForwardOnly(true); @@ -296,7 +296,7 @@ PlaylistItemPtr PlaylistBackend::RestoreCueData(PlaylistItemPtr item, SharedPtr< QFile cue_file(cue_path); if (!cue_file.open(QIODevice::ReadOnly)) return item; - song_list = cue_parser.Load(&cue_file, cue_path, QDir(cue_path.section('/', 0, -2))); + song_list = cue_parser.Load(&cue_file, cue_path, QDir(cue_path.section(QLatin1Char('/'), 0, -2))); cue_file.close(); state->cached_cues_[cue_path] = song_list; } @@ -348,7 +348,7 @@ void PlaylistBackend::SavePlaylist(int playlist, const PlaylistItemPtrList &item // Save the new ones for (PlaylistItemPtr item : items) { // clazy:exclude=range-loop-reference SqlQuery q(db); - q.prepare("INSERT INTO playlist_items (playlist, type, collection_id, " + Song::kColumnSpec + ") VALUES (:playlist, :type, :collection_id, " + Song::kBindSpec + ")"); + q.prepare(QStringLiteral("INSERT INTO playlist_items (playlist, type, collection_id, ") + Song::kColumnSpec + QStringLiteral(") VALUES (:playlist, :type, :collection_id, ") + Song::kBindSpec + QStringLiteral(")")); q.BindValue(QStringLiteral(":playlist"), playlist); item->BindToQuery(&q); diff --git a/src/playlist/playlistcontainer.cpp b/src/playlist/playlistcontainer.cpp index 8eb217acb0..10a1b36c29 100644 --- a/src/playlist/playlistcontainer.cpp +++ b/src/playlist/playlistcontainer.cpp @@ -48,6 +48,7 @@ #include "core/shared_ptr.h" #include "core/iconloader.h" +#include "core/settings.h" #include "playlist.h" #include "playlisttabbar.h" #include "playlistview.h" @@ -135,7 +136,7 @@ PlaylistContainer::PlaylistContainer(QWidget *parent) QStringLiteral("

") + tr("Search terms for numerical fields can be prefixed with %1 or %2 to refine the search, e.g.: ") - .arg(" =, !=, <, >, <=", ">=") + + .arg(QStringLiteral(" =, !=, <, >, <="), QStringLiteral(">=")) + QStringLiteral("") + tr("rating") + QStringLiteral("") + @@ -144,7 +145,7 @@ PlaylistContainer::PlaylistContainer(QWidget *parent) QStringLiteral("

") + tr("Multiple search terms can also be combined with \"%1\" (default) and \"%2\", as well as grouped with parentheses. ") - .arg("AND", "OR") + + .arg(QStringLiteral("AND"), QStringLiteral("OR")) + QStringLiteral("

") + tr("Available fields") + @@ -268,7 +269,7 @@ void PlaylistContainer::SetViewModel(Playlist *playlist, const int scroll_positi void PlaylistContainer::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); int iconsize = s.value(AppearanceSettingsPage::kIconSizePlaylistButtons, 20).toInt(); s.endGroup(); @@ -305,11 +306,11 @@ void PlaylistContainer::FocusSearchField() { } void PlaylistContainer::ActivePlaying() { - UpdateActiveIcon(QIcon(":/pictures/tiny-play.png")); + UpdateActiveIcon(QIcon(QStringLiteral(":/pictures/tiny-play.png"))); } void PlaylistContainer::ActivePaused() { - UpdateActiveIcon(QIcon(":/pictures/tiny-pause.png")); + UpdateActiveIcon(QIcon(QStringLiteral(":/pictures/tiny-pause.png"))); } void PlaylistContainer::ActiveStopped() { UpdateActiveIcon(QIcon()); } diff --git a/src/playlist/playlistcontainer.h b/src/playlist/playlistcontainer.h index 5e4030495d..d993d96091 100644 --- a/src/playlist/playlistcontainer.h +++ b/src/playlist/playlistcontainer.h @@ -45,6 +45,7 @@ class PlaylistView; class Ui_PlaylistContainer; #include "core/shared_ptr.h" +#include "core/settings.h" class PlaylistContainer : public QWidget { Q_OBJECT @@ -122,7 +123,7 @@ class PlaylistContainer : public QWidget { QAction *redo_; Playlist *playlist_; - QSettings settings_; + Settings settings_; bool starting_up_; bool tab_bar_visible_; diff --git a/src/playlist/playlistdelegates.cpp b/src/playlist/playlistdelegates.cpp index 633b0b522d..bfeef19a7b 100644 --- a/src/playlist/playlistdelegates.cpp +++ b/src/playlist/playlistdelegates.cpp @@ -110,7 +110,7 @@ void QueuedItemDelegate::DrawBox(QPainter *painter, const QRect line_rect, const smaller.setBold(true); if (width == -1) { - width = QFontMetrics(font).horizontalAdvance(text + " "); + width = QFontMetrics(font).horizontalAdvance(text + QStringLiteral(" ")); } QRect rect(line_rect); @@ -197,7 +197,7 @@ QString PlaylistDelegateBase::displayText(const QVariant &value, const QLocale&) break; } - if (!text.isNull() && !suffix_.isNull()) text += " " + suffix_; + if (!text.isNull() && !suffix_.isNull()) text += QStringLiteral(" ") + suffix_; return text; } diff --git a/src/playlist/playlistfilterparser.cpp b/src/playlist/playlistfilterparser.cpp index b97f5e1d94..95786eda46 100644 --- a/src/playlist/playlistfilterparser.cpp +++ b/src/playlist/playlistfilterparser.cpp @@ -358,7 +358,7 @@ FilterTree *FilterParser::parseAndGroup() { do { group->add(parseSearchExpression()); advance(); - if (iter_ != end_ && *iter_ == QChar(')')) break; + if (iter_ != end_ && *iter_ == QLatin1Char(')')) break; if (checkOr(false)) { break; } @@ -372,16 +372,16 @@ FilterTree *FilterParser::parseAndGroup() { bool FilterParser::checkAnd() { if (iter_ != end_) { - if (*iter_ == QChar('A')) { + if (*iter_ == QLatin1Char('A')) { buf_ += *iter_; ++iter_; - if (iter_ != end_ && *iter_ == QChar('N')) { + if (iter_ != end_ && *iter_ == QLatin1Char('N')) { buf_ += *iter_; ++iter_; - if (iter_ != end_ && *iter_ == QChar('D')) { + if (iter_ != end_ && *iter_ == QLatin1Char('D')) { buf_ += *iter_; ++iter_; - if (iter_ != end_ && (iter_->isSpace() || *iter_ == QChar('-') || *iter_ == '(')) { + if (iter_ != end_ && (iter_->isSpace() || *iter_ == QLatin1Char('-') || *iter_ == QLatin1Char('('))) { advance(); buf_.clear(); return true; @@ -397,7 +397,7 @@ bool FilterParser::checkAnd() { bool FilterParser::checkOr(const bool step_over) { if (!buf_.isEmpty()) { - if (buf_ == "OR") { + if (buf_ == QLatin1String("OR")) { if (step_over) { buf_.clear(); advance(); @@ -407,13 +407,13 @@ bool FilterParser::checkOr(const bool step_over) { } else { if (iter_ != end_) { - if (*iter_ == 'O') { + if (*iter_ == QLatin1Char('O')) { buf_ += *iter_; ++iter_; - if (iter_ != end_ && *iter_ == 'R') { + if (iter_ != end_ && *iter_ == QLatin1Char('R')) { buf_ += *iter_; ++iter_; - if (iter_ != end_ && (iter_->isSpace() || *iter_ == '-' || *iter_ == '(')) { + if (iter_ != end_ && (iter_->isSpace() || *iter_ == QLatin1Char('-') || *iter_ == QLatin1Char('('))) { if (step_over) { buf_.clear(); advance(); @@ -432,19 +432,19 @@ FilterTree *FilterParser::parseSearchExpression() { advance(); if (iter_ == end_) return new NopFilter; - if (*iter_ == '(') { + if (*iter_ == QLatin1Char('(')) { ++iter_; advance(); FilterTree *tree = parseOrGroup(); advance(); if (iter_ != end_) { - if (*iter_ == ')') { + if (*iter_ == QLatin1Char(')')) { ++iter_; } } return tree; } - else if (*iter_ == '-') { + else if (*iter_ == QLatin1Char('-')) { ++iter_; FilterTree *tree = parseSearchExpression(); if (tree->type() != FilterTree::FilterType::Nop) return new NotFilter(tree); @@ -464,7 +464,7 @@ FilterTree *FilterParser::parseSearchTerm() { bool inQuotes = false; for (; iter_ != end_; ++iter_) { if (inQuotes) { - if (*iter_ == '"') { + if (*iter_ == QLatin1Char('"')) { inQuotes = false; } else { @@ -472,23 +472,23 @@ FilterTree *FilterParser::parseSearchTerm() { } } else { - if (*iter_ == '"') { + if (*iter_ == QLatin1Char('"')) { inQuotes = true; } - else if (col.isEmpty() && *iter_ == ':') { + else if (col.isEmpty() && *iter_ == QLatin1Char(':')) { col = buf_.toLower(); buf_.clear(); prefix.clear(); // prefix isn't allowed here - let's ignore it } - else if (iter_->isSpace() || *iter_ == '(' || *iter_ == ')' || *iter_ == '-') { + else if (iter_->isSpace() || *iter_ == QLatin1Char('(') || *iter_ == QLatin1Char(')') || *iter_ == QLatin1Char('-')) { break; } else if (buf_.isEmpty()) { // we don't know whether there is a column part in this search term thus we assume the latter and just try and read a prefix - if (prefix.isEmpty() && (*iter_ == '>' || *iter_ == '<' || *iter_ == '=' || *iter_ == '!')) { + if (prefix.isEmpty() && (*iter_ == QLatin1Char('>') || *iter_ == QLatin1Char('<') || *iter_ == QLatin1Char('=') || *iter_ == QLatin1Char('!'))) { prefix += *iter_; } - else if (prefix != "=" && *iter_ == '=') { + else if (prefix != QLatin1String("=") && *iter_ == QLatin1Char('=')) { prefix += *iter_; } else { @@ -510,7 +510,7 @@ FilterTree *FilterParser::parseSearchTerm() { FilterTree *FilterParser::createSearchTermTreeNode(const QString &col, const QString &prefix, const QString &search) const { - if (search.isEmpty() && prefix != "=") { + if (search.isEmpty() && prefix != QLatin1String("=")) { return new NopFilter; } // here comes a mess :/ @@ -521,29 +521,29 @@ FilterTree *FilterParser::createSearchTermTreeNode(const QString &col, const QSt if (columns_[col] == Playlist::Column_Rating) { float parsed_search = Utilities::ParseSearchRating(search); - if (prefix == "=") { + if (prefix == QStringLiteral("=")) { cmp = new FloatEqComparator(parsed_search); } - else if (prefix == "!=" || prefix == "<>") { + else if (prefix == QStringLiteral("!=") || prefix == QStringLiteral("<>")) { cmp = new FloatNeComparator(parsed_search); } - else if (prefix == ">") { + else if (prefix == QStringLiteral(">")) { cmp = new FloatGtComparator(parsed_search); } - else if (prefix == ">=") { + else if (prefix == QStringLiteral(">=")) { cmp = new FloatGeComparator(parsed_search); } - else if (prefix == "<") { + else if (prefix == QStringLiteral("<")) { cmp = new FloatLtComparator(parsed_search); } - else if (prefix == "<=") { + else if (prefix == QStringLiteral("<=")) { cmp = new FloatLeComparator(parsed_search); } else { cmp = new FloatEqComparator(parsed_search); } } - else if (prefix == "!=" || prefix == "<>") { + else if (prefix == QStringLiteral("!=") || prefix == QStringLiteral("<>")) { cmp = new NeComparator(search); } else if (!col.isEmpty() && columns_.contains(col) && numerical_columns_.contains(columns_[col])) { @@ -556,16 +556,16 @@ FilterTree *FilterParser::createSearchTermTreeNode(const QString &col, const QSt search_value = search.toInt(); } // alright, back to deciding which comparator we'll use - if (prefix == ">") { + if (prefix == QLatin1String(">")) { cmp = new GtComparator(search_value); } - else if (prefix == ">=") { + else if (prefix == QLatin1String(">=")) { cmp = new GeComparator(search_value); } - else if (prefix == "<") { + else if (prefix == QLatin1String("<")) { cmp = new LtComparator(search_value); } - else if (prefix == "<=") { + else if (prefix == QLatin1String("<=")) { cmp = new LeComparator(search_value); } else { @@ -574,19 +574,19 @@ FilterTree *FilterParser::createSearchTermTreeNode(const QString &col, const QSt } } else { - if (prefix == "=") { + if (prefix == QStringLiteral("=")) { cmp = new EqComparator(search); } - else if (prefix == ">") { + else if (prefix == QStringLiteral(">")) { cmp = new LexicalGtComparator(search); } - else if (prefix == ">=") { + else if (prefix == QStringLiteral(">=")) { cmp = new LexicalGeComparator(search); } - else if (prefix == "<") { + else if (prefix == QStringLiteral("<")) { cmp = new LexicalLtComparator(search); } - else if (prefix == "<=") { + else if (prefix == QStringLiteral("<=")) { cmp = new LexicalLeComparator(search); } else { diff --git a/src/playlist/playlistheader.cpp b/src/playlist/playlistheader.cpp index d75f65e0b2..ea7d123088 100644 --- a/src/playlist/playlistheader.cpp +++ b/src/playlist/playlistheader.cpp @@ -37,6 +37,7 @@ #include "playlistheader.h" #include "playlistview.h" +#include "core/settings.h" #include "widgets/stretchheaderview.h" #include "settings/playlistsettingspage.h" @@ -81,7 +82,7 @@ PlaylistHeader::PlaylistHeader(Qt::Orientation orientation, PlaylistView *view, QObject::connect(this, &PlaylistHeader::StretchEnabledChanged, action_stretch_, &QAction::setChecked); - QSettings s; + Settings s; s.beginGroup(PlaylistSettingsPage::kSettingsGroup); action_rating_lock_->setChecked(s.value("rating_locked", false).toBool()); s.endGroup(); diff --git a/src/playlist/playlistlistcontainer.cpp b/src/playlist/playlistlistcontainer.cpp index cbcf8251b6..533373ae0c 100644 --- a/src/playlist/playlistlistcontainer.cpp +++ b/src/playlist/playlistlistcontainer.cpp @@ -49,6 +49,7 @@ #include "core/application.h" #include "core/iconloader.h" #include "core/player.h" +#include "core/settings.h" #include "playlist.h" #include "playlistbackend.h" #include "playlistlistview.h" @@ -150,7 +151,7 @@ void PlaylistListContainer::SetApplication(Application *app) { void PlaylistListContainer::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); int iconsize = s.value(AppearanceSettingsPage::kIconSizeLeftPanelButtons, 22).toInt(); s.endGroup(); @@ -213,7 +214,7 @@ void PlaylistListContainer::NewFolderClicked() { return; } - name.replace(QLatin1String("/"), QLatin1String(" ")); + name.replace(QLatin1Char('/'), QLatin1Char(' ')); model_->invisibleRootItem()->appendRow(model_->NewFolder(name)); @@ -504,7 +505,7 @@ void PlaylistListContainer::ActivePlaying() { } void PlaylistListContainer::ActivePaused() { - UpdateActiveIcon(active_playlist_id_, QIcon(":/pictures/tiny-pause.png")); + UpdateActiveIcon(active_playlist_id_, QIcon(QStringLiteral(":/pictures/tiny-pause.png"))); } void PlaylistListContainer::ActiveStopped() { diff --git a/src/playlist/playlistlistmodel.cpp b/src/playlist/playlistlistmodel.cpp index b571cb3546..cab6a8aeb5 100644 --- a/src/playlist/playlistlistmodel.cpp +++ b/src/playlist/playlistlistmodel.cpp @@ -159,9 +159,9 @@ QStandardItem *PlaylistListModel::FolderByPath(const QString &path) { QStandardItem *parent = invisibleRootItem(); #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - const QStringList parts = path.split('/', Qt::SkipEmptyParts); + const QStringList parts = path.split(QLatin1Char('/'), Qt::SkipEmptyParts); #else - const QStringList parts = path.split('/', QString::SkipEmptyParts); + const QStringList parts = path.split(QLatin1Char('/'), QString::SkipEmptyParts); #endif for (const QString &part : parts) { diff --git a/src/playlist/playlistlistview.cpp b/src/playlist/playlistlistview.cpp index 95eb01c4fa..11cbc49a9f 100644 --- a/src/playlist/playlistlistview.cpp +++ b/src/playlist/playlistlistview.cpp @@ -69,7 +69,7 @@ void PlaylistListView::selectionChanged(const QItemSelection&, const QItemSelect void PlaylistListView::dragEnterEvent(QDragEnterEvent *e) { - if (e->mimeData()->hasFormat(Playlist::kRowsMimetype)) { + if (e->mimeData()->hasFormat(QString::fromUtf8(Playlist::kRowsMimetype))) { e->acceptProposedAction(); } else { @@ -86,7 +86,7 @@ void PlaylistListView::dragMoveEvent(QDragMoveEvent *e) { QModelIndex drag_hover_tab_ = indexAt(e->pos()); #endif - if (e->mimeData()->hasFormat(Playlist::kRowsMimetype)) { + if (e->mimeData()->hasFormat(QString::fromUtf8(Playlist::kRowsMimetype))) { if (drag_hover_tab_ != currentIndex()) { e->setDropAction(Qt::CopyAction); e->accept(visualRect(drag_hover_tab_)); @@ -124,7 +124,7 @@ void PlaylistListView::timerEvent(QTimerEvent *e) { void PlaylistListView::dropEvent(QDropEvent *e) { - if (e->mimeData()->hasFormat(Playlist::kRowsMimetype)) { + if (e->mimeData()->hasFormat(QLatin1String(Playlist::kRowsMimetype))) { if (drag_hover_timer_.isActive()) { drag_hover_timer_.stop(); } diff --git a/src/playlist/playlistmanager.cpp b/src/playlist/playlistmanager.cpp index 9fa8232d69..09f865feef 100644 --- a/src/playlist/playlistmanager.cpp +++ b/src/playlist/playlistmanager.cpp @@ -45,6 +45,7 @@ #include "core/shared_ptr.h" #include "core/application.h" #include "core/player.h" +#include "core/settings.h" #include "utilities/filenameconstants.h" #include "utilities/timeutils.h" #include "collection/collectionbackend.h" @@ -241,7 +242,7 @@ void PlaylistManager::ItemsLoadedForSavePlaylist(const SongList &songs, const QS void PlaylistManager::SaveWithUI(const int id, const QString &playlist_name) { - QSettings s; + Settings s; s.beginGroup(Playlist::kSettingsGroup); QString last_save_filter = s.value("last_save_filter", parser()->default_filter()).toString(); QString last_save_path = s.value("last_save_path", QDir::homePath()).toString(); @@ -249,7 +250,7 @@ void PlaylistManager::SaveWithUI(const int id, const QString &playlist_name) { s.endGroup(); QString suggested_filename = playlist_name; - QString filename = last_save_path + "/" + suggested_filename.remove(QRegularExpression(QString(kProblematicCharactersRegex), QRegularExpression::CaseInsensitiveOption)) + "." + last_save_extension; + QString filename = last_save_path + QStringLiteral("/") + suggested_filename.remove(QRegularExpression(QLatin1String(kProblematicCharactersRegex), QRegularExpression::CaseInsensitiveOption)) + QStringLiteral(".") + last_save_extension; QFileInfo fileinfo; forever { @@ -441,7 +442,7 @@ void PlaylistManager::UpdateSummaryText() { QString summary; if (selected > 1) { - summary += tr("%1 selected of").arg(selected) + " "; + summary += tr("%1 selected of").arg(selected) + QStringLiteral(" "); } else { nanoseconds = current()->GetTotalLength(); @@ -450,7 +451,7 @@ void PlaylistManager::UpdateSummaryText() { summary += tr("%n track(s)", "", tracks); if (nanoseconds > 0) { - summary += " - [ " + Utilities::WordyTimeNanosec(nanoseconds) + " ]"; + summary += QStringLiteral(" - [ ") + Utilities::WordyTimeNanosec(nanoseconds) + QStringLiteral(" ]"); } emit SummaryTextChanged(summary); @@ -565,7 +566,7 @@ QString PlaylistManager::GetNameForNewPlaylist(const SongList &songs) { if (!various_artists && albums.size() == 1) { QStringList album_names = albums.values(); - result += " - " + album_names.first(); + result += QStringLiteral(" - ") + album_names.first(); } return result; @@ -633,7 +634,7 @@ void PlaylistManager::SaveAllPlaylists() { QString extension = dialog.extension(); if (extension.isEmpty()) extension = parser()->default_extension(); - QSettings s; + Settings s; s.beginGroup(PlaylistSettingsPage::kSettingsGroup); PlaylistSettingsPage::PathType path_type = static_cast(s.value("path_type", static_cast(PlaylistSettingsPage::PathType::Automatic)).toInt()); s.endGroup(); @@ -646,7 +647,7 @@ void PlaylistManager::SaveAllPlaylists() { for (QMap::const_iterator it = playlists_.constBegin(); it != playlists_.constEnd(); ++it) { const Data &data = *it; - const QString filepath = path + "/" + data.name + "." + extension; + const QString filepath = path + QStringLiteral("/") + data.name + QStringLiteral(".") + extension; Save(it.key(), filepath, path_type); } diff --git a/src/playlist/playlistproxystyle.cpp b/src/playlist/playlistproxystyle.cpp index fbfc2d6e28..ca041dc32b 100644 --- a/src/playlist/playlistproxystyle.cpp +++ b/src/playlist/playlistproxystyle.cpp @@ -41,7 +41,7 @@ void PlaylistProxyStyle::drawControl(ControlElement element, const QStyleOption const QFontMetrics &font_metrics = header_option->fontMetrics; // Spaces added to make transition less abrupt - if (rect.width() < font_metrics.horizontalAdvance(text + " ")) { + if (rect.width() < font_metrics.horizontalAdvance(text + QStringLiteral(" "))) { const Playlist::Column column = static_cast(header_option->section); QStyleOptionHeader new_option(*header_option); new_option.text = Playlist::abbreviated_column_name(column); diff --git a/src/playlist/playlistsaveoptionsdialog.cpp b/src/playlist/playlistsaveoptionsdialog.cpp index 8e8ebfe122..c38774b018 100644 --- a/src/playlist/playlistsaveoptionsdialog.cpp +++ b/src/playlist/playlistsaveoptionsdialog.cpp @@ -27,6 +27,7 @@ #include #include +#include "core/settings.h" #include "settings/playlistsettingspage.h" #include "playlistsaveoptionsdialog.h" #include "ui_playlistsaveoptionsdialog.h" @@ -48,7 +49,7 @@ PlaylistSaveOptionsDialog::~PlaylistSaveOptionsDialog() { delete ui; } void PlaylistSaveOptionsDialog::accept() { if (ui->remember_user_choice->isChecked()) { - QSettings s; + Settings s; s.beginGroup(PlaylistSettingsPage::kSettingsGroup); s.setValue("path_type", ui->filePaths->itemData(ui->filePaths->currentIndex()).toInt()); s.endGroup(); diff --git a/src/playlist/playlisttabbar.cpp b/src/playlist/playlisttabbar.cpp index 92c836cebb..84462cfe51 100644 --- a/src/playlist/playlisttabbar.cpp +++ b/src/playlist/playlisttabbar.cpp @@ -47,6 +47,7 @@ #include "core/shared_ptr.h" #include "core/iconloader.h" #include "core/mimedata.h" +#include "core/settings.h" #include "widgets/favoritewidget.h" #include "widgets/renametablineedit.h" #include "playlist.h" @@ -217,14 +218,14 @@ void PlaylistTabBar::CloseSlot() { const int playlist_id = tabData(menu_index_).toInt(); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); const bool ask_for_delete = s.value("warn_close_playlist", true).toBool(); if (ask_for_delete && !manager_->IsPlaylistFavorite(playlist_id) && !manager_->playlist(playlist_id)->GetAllSongs().empty()) { QMessageBox confirmation_box; - confirmation_box.setWindowIcon(QIcon(":/icons/64x64/strawberry.png")); + confirmation_box.setWindowIcon(QIcon(QStringLiteral(":/icons/64x64/strawberry.png"))); confirmation_box.setWindowTitle(tr("Remove playlist")); confirmation_box.setIcon(QMessageBox::Question); confirmation_box.setText( @@ -345,8 +346,8 @@ void PlaylistTabBar::CurrentIndexChanged(const int index) { void PlaylistTabBar::InsertTab(const int id, const int index, const QString &text, const bool favorite) { QString new_text = text; - if (new_text.contains('&')) { - new_text = new_text.replace('&', QLatin1String("&&")); + if (new_text.contains(QLatin1Char('&'))) { + new_text = new_text.replace(QLatin1Char('&'), QLatin1String("&&")); } suppress_current_changed_ = true; @@ -381,7 +382,7 @@ void PlaylistTabBar::TabMoved() { } void PlaylistTabBar::dragEnterEvent(QDragEnterEvent *e) { - if (e->mimeData()->hasUrls() || e->mimeData()->hasFormat(Playlist::kRowsMimetype) || qobject_cast(e->mimeData())) { + if (e->mimeData()->hasUrls() || e->mimeData()->hasFormat(QString::fromUtf8(Playlist::kRowsMimetype)) || qobject_cast(e->mimeData())) { e->acceptProposedAction(); } } diff --git a/src/playlist/playlistview.cpp b/src/playlist/playlistview.cpp index cf432c5f33..004cf0d5c7 100644 --- a/src/playlist/playlistview.cpp +++ b/src/playlist/playlistview.cpp @@ -63,6 +63,7 @@ #include "core/player.h" #include "core/qt_blurimage.h" #include "core/song.h" +#include "core/settings.h" #include "playlistmanager.h" #include "playlist.h" #include "playlistdelegates.h" @@ -291,7 +292,7 @@ void PlaylistView::SetPlaylist(Playlist *playlist) { void PlaylistView::LoadHeaderState() { - QSettings s; + Settings s; s.beginGroup(Playlist::kSettingsGroup); if (s.contains("state")) { header_state_version_ = s.value("state_version", 0).toInt(); @@ -1171,7 +1172,7 @@ void PlaylistView::PlaylistDestroyed() { void PlaylistView::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(PlaylistSettingsPage::kSettingsGroup); bars_enabled_ = s.value("show_bars", true).toBool(); @@ -1286,7 +1287,7 @@ void PlaylistView::SaveSettings() { if (!header_state_loaded_ || read_only_settings_) return; - QSettings s; + Settings s; s.beginGroup(Playlist::kSettingsGroup); s.setValue("state_version", header_state_version_); s.setValue("state", header_->SaveState()); diff --git a/src/playlistparsers/asxiniparser.cpp b/src/playlistparsers/asxiniparser.cpp index d82d8f2490..6a94adf334 100644 --- a/src/playlistparsers/asxiniparser.cpp +++ b/src/playlistparsers/asxiniparser.cpp @@ -54,7 +54,7 @@ SongList AsxIniParser::Load(QIODevice *device, const QString &playlist_path, con while (!device->atEnd()) { QString line = QString::fromUtf8(device->readLine()).trimmed(); - qint64 equals = line.indexOf('='); + qint64 equals = line.indexOf(QLatin1Char('=')); QString key = line.left(equals).toLower(); QString value = line.mid(equals + 1); diff --git a/src/playlistparsers/asxparser.cpp b/src/playlistparsers/asxparser.cpp index acde4214b9..2dc01eb062 100644 --- a/src/playlistparsers/asxparser.cpp +++ b/src/playlistparsers/asxparser.cpp @@ -50,7 +50,7 @@ SongList ASXParser::Load(QIODevice *device, const QString &playlist_path, const // Some playlists have unescaped & characters in URLs :( QRegularExpression ex(QStringLiteral("(href\\s*=\\s*\")([^\"]+)\""), QRegularExpression::CaseInsensitiveOption); qint64 index = 0; - for (QRegularExpressionMatch re_match = ex.match(data, index); re_match.hasMatch(); re_match = ex.match(data, index)) { + for (QRegularExpressionMatch re_match = ex.match(QString::fromUtf8(data), index); re_match.hasMatch(); re_match = ex.match(QString::fromUtf8(data), index)) { index = re_match.capturedStart(); QString url = re_match.captured(2); url.replace(QRegularExpression(QStringLiteral("&(?!amp;|quot;|apos;|lt;|gt;)")), QStringLiteral("&")); @@ -92,21 +92,21 @@ Song ASXParser::ParseTrack(QXmlStreamReader *reader, const QDir &dir, const bool switch (type) { case QXmlStreamReader::StartElement: { - QString name = reader->name().toString().toLower(); - if (name == "ref") { - ref = reader->attributes().value("href").toString(); + const QString name = reader->name().toString().toLower(); + if (name == QStringLiteral("ref")) { + ref = reader->attributes().value(QStringLiteral("href")).toString(); } - else if (name == "title") { + else if (name == QStringLiteral("title")) { title = reader->readElementText(); } - else if (name == "author") { + else if (name == QStringLiteral("author")) { artist = reader->readElementText(); } break; } case QXmlStreamReader::EndElement: { - QString name = reader->name().toString().toLower(); - if (name == "entry") { + const QString name = reader->name().toString().toLower(); + if (name == QStringLiteral("entry")) { goto return_song; } break; @@ -138,16 +138,16 @@ void ASXParser::Save(const SongList &songs, QIODevice *device, const QDir&, cons writer.writeStartDocument(); { StreamElement asx(QStringLiteral("asx"), &writer); - writer.writeAttribute("version", "3.0"); + writer.writeAttribute(QStringLiteral("version"), QStringLiteral("3.0")); for (const Song &song : songs) { StreamElement entry(QStringLiteral("entry"), &writer); - writer.writeTextElement("title", song.title()); + writer.writeTextElement(QStringLiteral("title"), song.title()); { StreamElement ref(QStringLiteral("ref"), &writer); - writer.writeAttribute("href", song.url().toString()); + writer.writeAttribute(QStringLiteral("href"), song.url().toString()); } if (!song.artist().isEmpty()) { - writer.writeTextElement("author", song.artist()); + writer.writeTextElement(QStringLiteral("author"), song.artist()); } } } diff --git a/src/playlistparsers/cueparser.cpp b/src/playlistparsers/cueparser.cpp index 2c71ce3582..5f62721401 100644 --- a/src/playlistparsers/cueparser.cpp +++ b/src/playlistparsers/cueparser.cpp @@ -43,22 +43,24 @@ class CollectionBackendInterface; -const char *CueParser::kFileLineRegExp = "(\\S+)\\s+(?:\"([^\"]+)\"|(\\S+))\\s*(?:\"([^\"]+)\"|(\\S+))?"; -const char *CueParser::kIndexRegExp = "(\\d{1,3}):(\\d{2}):(\\d{2})"; +namespace { +static constexpr char kFileLineRegExp[] = "(\\S+)\\s+(?:\"([^\"]+)\"|(\\S+))\\s*(?:\"([^\"]+)\"|(\\S+))?"; +static constexpr char kIndexRegExp[] = "(\\d{1,3}):(\\d{2}):(\\d{2})"; -const char *CueParser::kPerformer = "performer"; -const char *CueParser::kTitle = "title"; -const char *CueParser::kSongWriter = "songwriter"; +static constexpr char kPerformer[] = "performer"; +static constexpr char kTitle[] = "title"; +static constexpr char kSongWriter[] = "songwriter"; // composer may be in cue file and is synonym for songwriter -const char *CueParser::kComposer = "composer"; -const char *CueParser::kFile = "file"; -const char *CueParser::kTrack = "track"; -const char *CueParser::kIndex = "index"; -const char *CueParser::kAudioTrackType = "audio"; -const char *CueParser::kRem = "rem"; -const char *CueParser::kGenre = "genre"; -const char *CueParser::kDate = "date"; -const char *CueParser::kDisc = "discnumber"; +static constexpr char kComposer[] = "composer"; +static constexpr char kFile[] = "file"; +static constexpr char kTrack[] = "track"; +static constexpr char kIndex[] = "index"; +static constexpr char kAudioTrackType[] = "audio"; +static constexpr char kRem[] = "rem"; +static constexpr char kGenre[] = "genre"; +static constexpr char kDate[] = "date"; +static constexpr char kDisc[] = "discnumber"; +} CueParser::CueParser(SharedPtr collection_backend, QObject *parent) : ParserBase(collection_backend, parent) {} @@ -106,40 +108,40 @@ SongList CueParser::Load(QIODevice *device, const QString &playlist_path, const const QString &line_name = splitted[0]; const QString &line_value = splitted[1]; - if (line_name.compare(kPerformer, Qt::CaseInsensitive) == 0) { + if (line_name.compare(QString::fromUtf8(kPerformer), Qt::CaseInsensitive) == 0) { album_artist = line_value; } - else if (line_name.compare(kTitle, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QString::fromUtf8(kTitle), Qt::CaseInsensitive) == 0) { album = line_value; } - else if (line_name.compare(kSongWriter, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QString::fromUtf8(kSongWriter), Qt::CaseInsensitive) == 0) { album_composer = line_value; } - else if (line_name.compare(kComposer, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QString::fromUtf8(kComposer), Qt::CaseInsensitive) == 0) { album_composer = line_value; } - else if (line_name.compare(kFile, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QString::fromUtf8(kFile), Qt::CaseInsensitive) == 0) { file = QDir::isAbsolutePath(line_value) ? line_value : dir.absoluteFilePath(line_value); if (splitted.size() > 2) { file_type = splitted[2]; } } - else if (line_name.compare(kRem, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QString::fromUtf8(kRem), Qt::CaseInsensitive) == 0) { if (splitted.size() < 3) { break; } - if (line_value.compare(kGenre, Qt::CaseInsensitive) == 0) { + if (line_value.compare(QString::fromUtf8(kGenre), Qt::CaseInsensitive) == 0) { album_genre = splitted[2]; } - else if (line_value.compare(kDate, Qt::CaseInsensitive) == 0) { + else if (line_value.compare(QString::fromUtf8(kDate), Qt::CaseInsensitive) == 0) { album_date = splitted[2]; } - else if (line_value.compare(kDisc, Qt::CaseInsensitive) == 0) { + else if (line_value.compare(QString::fromUtf8(kDisc), Qt::CaseInsensitive) == 0) { disc = splitted[2]; } } // end of the header -> go into the track mode - else if (line_name.compare(kTrack, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QString::fromUtf8(kTrack), Qt::CaseInsensitive) == 0) { files++; break; } @@ -175,11 +177,11 @@ SongList CueParser::Load(QIODevice *device, const QString &playlist_path, const const QString &line_value = splitted[1]; QString line_additional = splitted.size() > 2 ? splitted[2].toLower() : QLatin1String(""); - if (line_name.compare(kTrack, Qt::CaseInsensitive) == 0) { + if (line_name.compare(QString::fromUtf8(kTrack), Qt::CaseInsensitive) == 0) { // the beginning of another track's definition - we're saving the current one for later (if it's valid of course) // please note that the same code is repeated just after this 'do-while' loop - if (valid_file && !index.isEmpty() && (track_type.isEmpty() || track_type.compare(kAudioTrackType, Qt::CaseInsensitive) == 0)) { + if (valid_file && !index.isEmpty() && (track_type.isEmpty() || track_type.compare(QLatin1String(kAudioTrackType), Qt::CaseInsensitive) == 0)) { entries.append(CueEntry(file, index, title, artist, album_artist, album, composer, album_composer, (genre.isEmpty() ? album_genre : genre), (date.isEmpty() ? album_date : date), disc)); } @@ -191,43 +193,43 @@ SongList CueParser::Load(QIODevice *device, const QString &playlist_path, const } } - else if (line_name.compare(kIndex, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QLatin1String(kIndex), Qt::CaseInsensitive) == 0) { // We need the index's position field if (!line_additional.isEmpty()) { // If there's none "01" index, we'll just take the first one also, we'll take the "01" index even if it's the last one - if (line_value == "01" || index.isEmpty()) { + if (line_value == QStringLiteral("01") || index.isEmpty()) { index = line_additional; } } } - else if (line_name.compare(kTitle, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QLatin1String(kTitle), Qt::CaseInsensitive) == 0) { title = line_value; } - else if (line_name.compare(kDate, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QLatin1String(kDate), Qt::CaseInsensitive) == 0) { date = line_value; } - else if (line_name.compare(kPerformer, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QLatin1String(kPerformer), Qt::CaseInsensitive) == 0) { artist = line_value; } - else if (line_name.compare(kSongWriter, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QLatin1String(kSongWriter), Qt::CaseInsensitive) == 0) { composer = line_value; } - else if (line_name.compare(kComposer, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QLatin1String(kComposer), Qt::CaseInsensitive) == 0) { composer = line_value; } // End of tracks for the current file -> parse next one - else if (line_name.compare(kRem, Qt::CaseInsensitive) == 0 && splitted.size() >= 3) { - if (line_value.compare(kGenre, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QLatin1String(kRem), Qt::CaseInsensitive) == 0 && splitted.size() >= 3) { + if (line_value.compare(QLatin1String(kGenre), Qt::CaseInsensitive) == 0) { genre = splitted[2]; } - else if (line_value.compare(kDate, Qt::CaseInsensitive) == 0) { + else if (line_value.compare(QLatin1String(kDate), Qt::CaseInsensitive) == 0) { date = splitted[2]; } } - else if (line_name.compare(kFile, Qt::CaseInsensitive) == 0) { + else if (line_name.compare(QLatin1String(kFile), Qt::CaseInsensitive) == 0) { break; } @@ -235,7 +237,7 @@ SongList CueParser::Load(QIODevice *device, const QString &playlist_path, const } while (!(line = text_stream.readLine()).isNull()); // We didn't add the last song yet... - if (valid_file && !index.isEmpty() && (track_type.isEmpty() || track_type.compare(kAudioTrackType, Qt::CaseInsensitive) == 0)) { + if (valid_file && !index.isEmpty() && (track_type.isEmpty() || track_type.compare(QLatin1String(kAudioTrackType), Qt::CaseInsensitive) == 0)) { entries.append(CueEntry(file, index, title, artist, album_artist, album, composer, album_composer, (genre.isEmpty() ? album_genre : genre), (date.isEmpty() ? album_date : date), disc)); } } @@ -285,7 +287,7 @@ SongList CueParser::Load(QIODevice *device, const QString &playlist_path, const // line into logical parts and getting rid of all the unnecessary whitespaces and quoting. QStringList CueParser::SplitCueLine(const QString &line) { - QRegularExpression line_regexp(kFileLineRegExp); + QRegularExpression line_regexp(QString::fromUtf8(kFileLineRegExp)); QRegularExpressionMatch re_match = line_regexp.match(line.trimmed()); if (!re_match.hasMatch()) { return QStringList(); @@ -356,7 +358,7 @@ bool CueParser::UpdateLastSong(const CueEntry &entry, Song *song) { qint64 CueParser::IndexToMarker(const QString &index) { - QRegularExpression index_regexp(kIndexRegExp); + QRegularExpression index_regexp(QString::fromUtf8(kIndexRegExp)); QRegularExpressionMatch re_match = index_regexp.match(index); if (!re_match.hasMatch()) { return -1; @@ -382,14 +384,14 @@ void CueParser::Save(const SongList &songs, QIODevice *device, const QDir &dir, // Looks for a track starting with one of the .cue's keywords. bool CueParser::TryMagic(const QByteArray &data) const { - QStringList splitted = QString::fromUtf8(data.constData()).split('\n'); + QStringList splitted = QString::fromUtf8(data.constData()).split(QLatin1Char('\n')); for (int i = 0; i < splitted.length(); i++) { QString line = splitted.at(i).trimmed(); - if (line.startsWith(kPerformer, Qt::CaseInsensitive) || - line.startsWith(kTitle, Qt::CaseInsensitive) || - line.startsWith(kFile, Qt::CaseInsensitive) || - line.startsWith(kTrack, Qt::CaseInsensitive)) { + if (line.startsWith(QLatin1String(kPerformer), Qt::CaseInsensitive) || + line.startsWith(QLatin1String(kTitle), Qt::CaseInsensitive) || + line.startsWith(QLatin1String(kFile), Qt::CaseInsensitive) || + line.startsWith(QLatin1String(kTrack), Qt::CaseInsensitive)) { return true; } } @@ -400,8 +402,8 @@ bool CueParser::TryMagic(const QByteArray &data) const { QString CueParser::FindCueFilename(const QString &filename) { - QStringList cue_files = QStringList() << filename + ".cue" - << filename.section('.', 0, -2) + ".cue"; + QStringList cue_files = QStringList() << filename + QStringLiteral(".cue") + << filename.section(QLatin1Char('.'), 0, -2) + QStringLiteral(".cue"); for (const QString &cuefile : cue_files) { if (QFileInfo::exists(cuefile)) return cuefile; diff --git a/src/playlistparsers/cueparser.h b/src/playlistparsers/cueparser.h index eb04d74a82..0b42226637 100644 --- a/src/playlistparsers/cueparser.h +++ b/src/playlistparsers/cueparser.h @@ -45,22 +45,6 @@ class CueParser : public ParserBase { Q_OBJECT public: - static const char *kFileLineRegExp; - static const char *kIndexRegExp; - - static const char *kPerformer; - static const char *kTitle; - static const char *kSongWriter; - static const char *kComposer; - static const char *kFile; - static const char *kTrack; - static const char *kIndex; - static const char *kAudioTrackType; - static const char *kRem; - static const char *kGenre; - static const char *kDate; - static const char *kDisc; - explicit CueParser(SharedPtr collection_backend, QObject *parent = nullptr); QString name() const override { return QStringLiteral("CUE"); } diff --git a/src/playlistparsers/m3uparser.cpp b/src/playlistparsers/m3uparser.cpp index 88c1a00546..7240b9fa20 100644 --- a/src/playlistparsers/m3uparser.cpp +++ b/src/playlistparsers/m3uparser.cpp @@ -29,6 +29,7 @@ #include "core/shared_ptr.h" #include "core/logging.h" +#include "core/settings.h" #include "utilities/timeconstants.h" #include "settings/playlistsettingspage.h" #include "parserbase.h" @@ -47,7 +48,7 @@ SongList M3UParser::Load(QIODevice *device, const QString &playlist_path, const Metadata current_metadata; QString data = QString::fromUtf8(device->readAll()); - data.replace('\r', '\n'); + data.replace(QLatin1Char('\r'), QLatin1Char('\n')); data.replace(QLatin1String("\n\n"), QLatin1String("\n")); QByteArray bytes = data.toUtf8(); QBuffer buffer(&bytes); @@ -62,7 +63,7 @@ SongList M3UParser::Load(QIODevice *device, const QString &playlist_path, const SongList ret; forever { - if (line.startsWith('#')) { + if (line.startsWith(QLatin1Char('#'))) { // Extended info or comment. if (type == M3UType::EXTENDED && line.startsWith(QLatin1String("#EXT"))) { if (!ParseMetadata(line, ¤t_metadata)) { @@ -101,8 +102,8 @@ bool M3UParser::ParseMetadata(const QString &line, M3UParser::Metadata *metadata // Extended info, eg. // #EXTINF:123,Sample Artist - Sample title - QString info = line.section(':', 1); - QString l = info.section(',', 0, 0); + QString info = line.section(QLatin1Char(':'), 1); + QString l = info.section(QLatin1Char(','), 0, 0); bool ok = false; int length = l.toInt(&ok); if (!ok) { @@ -110,7 +111,7 @@ bool M3UParser::ParseMetadata(const QString &line, M3UParser::Metadata *metadata } metadata->length = length * kNsecPerSec; - QString track_info = info.section(',', 1); + QString track_info = info.section(QLatin1Char(','), 1); QStringList list = track_info.split(QStringLiteral(" - ")); if (list.size() <= 1) { metadata->title = track_info; @@ -126,7 +127,7 @@ void M3UParser::Save(const SongList &songs, QIODevice *device, const QDir &dir, device->write("#EXTM3U\n"); - QSettings s; + Settings s; s.beginGroup(PlaylistSettingsPage::kSettingsGroup); bool write_metadata = s.value("write_metadata", true).toBool(); s.endGroup(); diff --git a/src/playlistparsers/parserbase.cpp b/src/playlistparsers/parserbase.cpp index ec7cb570b9..1e065a1a7a 100644 --- a/src/playlistparsers/parserbase.cpp +++ b/src/playlistparsers/parserbase.cpp @@ -65,7 +65,7 @@ void ParserBase::LoadSong(const QString &filename_or_url, const qint64 beginning // Strawberry always wants / separators internally. // Using QDir::fromNativeSeparators() only works on the same platform the playlist was created on/for, using replace() lets playlists work on any platform. - filename = filename.replace('\\', '/'); + filename = filename.replace(QLatin1Char('\\'), QLatin1Char('/')); // Make the path absolute if (!QDir::isAbsolutePath(filename)) { diff --git a/src/playlistparsers/playlistparser.cpp b/src/playlistparsers/playlistparser.cpp index ef5136ac9c..597e9d0733 100644 --- a/src/playlistparsers/playlistparser.cpp +++ b/src/playlistparsers/playlistparser.cpp @@ -113,7 +113,7 @@ QString PlaylistParser::FilterForParser(const ParserBase *parser, QStringList *a QStringList extensions; extensions.reserve(file_extensions.count()); for (const QString &extension : file_extensions) { - extensions << "*." + extension; + extensions << QStringLiteral("*.") + extension; } if (all_extensions) *all_extensions << extensions; diff --git a/src/playlistparsers/plsparser.cpp b/src/playlistparsers/plsparser.cpp index 0e8e421b51..591b2f546a 100644 --- a/src/playlistparsers/plsparser.cpp +++ b/src/playlistparsers/plsparser.cpp @@ -54,7 +54,7 @@ SongList PLSParser::Load(QIODevice *device, const QString &playlist_path, const while (!device->atEnd()) { QString line = QString::fromUtf8(device->readLine()).trimmed(); - qint64 equals = line.indexOf('='); + qint64 equals = line.indexOf(QLatin1Char('=')); QString key = line.left(equals).toLower(); QString value = line.mid(equals + 1); diff --git a/src/playlistparsers/wplparser.cpp b/src/playlistparsers/wplparser.cpp index 459faf448e..2246769ef2 100644 --- a/src/playlistparsers/wplparser.cpp +++ b/src/playlistparsers/wplparser.cpp @@ -68,9 +68,9 @@ void WplParser::ParseSeq(const QDir &dir, QXmlStreamReader *reader, SongList *so QXmlStreamReader::TokenType type = reader->readNext(); QString name = reader->name().toString(); switch (type) { - case QXmlStreamReader::StartElement: { - if (name == "media") { - QString src = reader->attributes().value("src").toString(); + case QXmlStreamReader::StartElement:{ + if (name == QStringLiteral("media")) { + QString src = reader->attributes().value(QStringLiteral("src")).toString(); if (!src.isEmpty()) { Song song = LoadSong(src, 0, 0, dir, collection_search); if (song.is_valid()) { @@ -83,8 +83,8 @@ void WplParser::ParseSeq(const QDir &dir, QXmlStreamReader *reader, SongList *so } break; } - case QXmlStreamReader::EndElement: { - if (name == "seq") { + case QXmlStreamReader::EndElement:{ + if (name == QStringLiteral("seq")) { return; } break; @@ -101,13 +101,13 @@ void WplParser::Save(const SongList &songs, QIODevice *device, const QDir &dir, QXmlStreamWriter writer(device); writer.setAutoFormatting(true); writer.setAutoFormattingIndent(2); - writer.writeProcessingInstruction("wpl", "version=\"1.0\""); + writer.writeProcessingInstruction(QStringLiteral("wpl"), QStringLiteral("version=\"1.0\"")); StreamElement smil(QStringLiteral("smil"), &writer); { StreamElement head(QStringLiteral("head"), &writer); - WriteMeta(QStringLiteral("Generator"), "Strawberry -- " STRAWBERRY_VERSION_DISPLAY, &writer); + WriteMeta(QStringLiteral("Generator"), QStringLiteral("Strawberry -- ") + QLatin1String(STRAWBERRY_VERSION_DISPLAY), &writer); WriteMeta(QStringLiteral("ItemCount"), QString::number(songs.count()), &writer); } @@ -116,8 +116,8 @@ void WplParser::Save(const SongList &songs, QIODevice *device, const QDir &dir, { StreamElement seq(QStringLiteral("seq"), &writer); for (const Song &song : songs) { - writer.writeStartElement("media"); - writer.writeAttribute("src", URLOrFilename(song.url(), dir, path_type)); + writer.writeStartElement(QStringLiteral("media")); + writer.writeAttribute(QStringLiteral("src"), URLOrFilename(song.url(), dir, path_type)); writer.writeEndElement(); } } @@ -126,9 +126,9 @@ void WplParser::Save(const SongList &songs, QIODevice *device, const QDir &dir, void WplParser::WriteMeta(const QString &name, const QString &content, QXmlStreamWriter *writer) { - writer->writeStartElement("meta"); - writer->writeAttribute("name", name); - writer->writeAttribute("content", content); + writer->writeStartElement(QStringLiteral("meta")); + writer->writeAttribute(QStringLiteral("name"), name); + writer->writeAttribute(QStringLiteral("content"), content); writer->writeEndElement(); } diff --git a/src/playlistparsers/xspfparser.cpp b/src/playlistparsers/xspfparser.cpp index 783bef4586..76aa0ee115 100644 --- a/src/playlistparsers/xspfparser.cpp +++ b/src/playlistparsers/xspfparser.cpp @@ -30,6 +30,7 @@ #include #include "core/shared_ptr.h" +#include "core/settings.h" #include "utilities/xmlutils.h" #include "utilities/timeconstants.h" #include "settings/playlistsettingspage.h" @@ -73,22 +74,22 @@ Song XSPFParser::ParseTrack(QXmlStreamReader *reader, const QDir &dir, const boo QString name = reader->name().toString(); switch (type) { case QXmlStreamReader::StartElement: { - if (name == "location") { + if (name == QStringLiteral("location")) { location = QUrl::fromPercentEncoding(reader->readElementText().toUtf8()); } - else if (name == "title") { + else if (name == QStringLiteral("title")) { title = reader->readElementText(); } - else if (name == "creator") { + else if (name == QStringLiteral("creator")) { artist = reader->readElementText(); } - else if (name == "album") { + else if (name == QStringLiteral("album")) { album = reader->readElementText(); } - else if (name == "image") { + else if (name == QStringLiteral("image")) { art = QUrl::fromPercentEncoding(reader->readElementText().toUtf8()); } - else if (name == "duration") { // in milliseconds. + else if (name == QStringLiteral("duration")) { // in milliseconds. const QString duration = reader->readElementText(); bool ok = false; nanosec = duration.toInt(&ok) * kNsecPerMsec; @@ -96,7 +97,7 @@ Song XSPFParser::ParseTrack(QXmlStreamReader *reader, const QDir &dir, const boo nanosec = -1; } } - else if (name == "trackNum") { + else if (name == QStringLiteral("trackNum")) { const QString track_num_str = reader->readElementText(); bool ok = false; track_num = track_num_str.toInt(&ok); @@ -104,13 +105,13 @@ Song XSPFParser::ParseTrack(QXmlStreamReader *reader, const QDir &dir, const boo track_num = -1; } } - else if (name == "info") { + else if (name == QStringLiteral("info")) { // TODO: Do something with extra info? } break; } case QXmlStreamReader::EndElement: { - if (name == "track") { + if (name == QStringLiteral("track")) { goto return_song; } } @@ -143,44 +144,44 @@ void XSPFParser::Save(const SongList &songs, QIODevice *device, const QDir &dir, writer.setAutoFormattingIndent(2); writer.writeStartDocument(); StreamElement playlist(QStringLiteral("playlist"), &writer); - writer.writeAttribute("version", "1"); - writer.writeDefaultNamespace("http://xspf.org/ns/0/"); + writer.writeAttribute(QStringLiteral("version"), QStringLiteral("1")); + writer.writeDefaultNamespace(QStringLiteral("http://xspf.org/ns/0/")); - QSettings s; + Settings s; s.beginGroup(PlaylistSettingsPage::kSettingsGroup); bool write_metadata = s.value("write_metadata", true).toBool(); s.endGroup(); StreamElement tracklist(QStringLiteral("trackList"), &writer); for (const Song &song : songs) { - QString filename_or_url = QUrl::toPercentEncoding(URLOrFilename(song.url(), dir, path_type), "/ "); + QString filename_or_url = QString::fromLatin1(QUrl::toPercentEncoding(URLOrFilename(song.url(), dir, path_type), "/ ")); StreamElement track(QStringLiteral("track"), &writer); - writer.writeTextElement("location", filename_or_url); + writer.writeTextElement(QStringLiteral("location"), filename_or_url); if (write_metadata || (song.is_stream() && !song.is_radio())) { - writer.writeTextElement("title", song.title()); + writer.writeTextElement(QStringLiteral("title"), song.title()); if (!song.artist().isEmpty()) { - writer.writeTextElement("creator", song.artist()); + writer.writeTextElement(QStringLiteral("creator"), song.artist()); } if (!song.album().isEmpty()) { - writer.writeTextElement("album", song.album()); + writer.writeTextElement(QStringLiteral("album"), song.album()); } if (song.length_nanosec() != -1) { - writer.writeTextElement("duration", QString::number(song.length_nanosec() / kNsecPerMsec)); + writer.writeTextElement(QStringLiteral("duration"), QString::number(song.length_nanosec() / kNsecPerMsec)); } } if ((write_metadata || song.has_cue() || (song.is_stream() && !song.is_radio())) && song.track() > 0) { - writer.writeTextElement("trackNum", QString::number(song.track())); + writer.writeTextElement(QStringLiteral("trackNum"), QString::number(song.track())); } if (write_metadata || (song.is_stream() && !song.is_radio())) { const QUrl cover_url = song.art_manual().isEmpty() || !song.art_manual().isValid() ? song.art_automatic() : song.art_manual(); // Ignore images that are in our resource bundle. if (!cover_url.isEmpty() && cover_url.isValid()) { - const QString cover_filename = QUrl::toPercentEncoding(URLOrFilename(cover_url, dir, path_type), "/ "); - writer.writeTextElement("image", cover_filename); + const QString cover_filename = QString::fromLatin1(QUrl::toPercentEncoding(URLOrFilename(cover_url, dir, path_type), "/ ")); + writer.writeTextElement(QStringLiteral("image"), cover_filename); } } } diff --git a/src/providers/musixmatchprovider.cpp b/src/providers/musixmatchprovider.cpp index 69a9aac81a..78e4a2f7ed 100644 --- a/src/providers/musixmatchprovider.cpp +++ b/src/providers/musixmatchprovider.cpp @@ -27,12 +27,12 @@ const char *MusixmatchProvider::kApiKey = "Y2FhMDRlN2Y4OWE5OTIxYmZlOGMzOWQzOGI3Z QString MusixmatchProvider::StringFixup(QString text) { - return text.replace('/', '-') - .replace('\'', '-') + return text.replace(QLatin1Char('/'), QLatin1Char('-')) + .replace(QLatin1Char('\''), QLatin1Char('-')) .remove(QRegularExpression(QStringLiteral("[^\\w0-9\\- ]"), QRegularExpression::UseUnicodePropertiesOption)) .replace(QRegularExpression(QStringLiteral(" {2,}")), QStringLiteral(" ")) .simplified() - .replace(' ', '-') + .replace(QLatin1Char(' '), QLatin1Char('-')) .replace(QRegularExpression(QStringLiteral("(-)\\1+")), QStringLiteral("-")) .toLower(); diff --git a/src/qobuz/qobuzbaserequest.cpp b/src/qobuz/qobuzbaserequest.cpp index b546833979..3004498e14 100644 --- a/src/qobuz/qobuzbaserequest.cpp +++ b/src/qobuz/qobuzbaserequest.cpp @@ -52,20 +52,20 @@ QobuzBaseRequest::~QobuzBaseRequest() = default; QNetworkReply *QobuzBaseRequest::CreateRequest(const QString &ressource_name, const ParamList ¶ms_provided) { ParamList params = ParamList() << params_provided - << Param("app_id", app_id()); + << Param(QStringLiteral("app_id"), app_id()); std::sort(params.begin(), params.end()); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } - QUrl url(QString(QobuzService::kApiUrl) + QStringLiteral("/") + ressource_name); + QUrl url(QString::fromLatin1(QobuzService::kApiUrl) + QStringLiteral("/") + ressource_name); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); req.setRawHeader("X-App-Id", app_id().toUtf8()); if (authenticated()) req.setRawHeader("X-User-Auth-Token", user_auth_token().toUtf8()); @@ -182,7 +182,7 @@ QString QobuzBaseRequest::ErrorsToHTML(const QStringList &errors) { QString error_html; for (const QString &error : errors) { - error_html += error + "
"; + error_html += error + QStringLiteral("
"); } return error_html; diff --git a/src/qobuz/qobuzfavoriterequest.cpp b/src/qobuz/qobuzfavoriterequest.cpp index 545c8c4e5f..fc3d02bc25 100644 --- a/src/qobuz/qobuzfavoriterequest.cpp +++ b/src/qobuz/qobuzfavoriterequest.cpp @@ -132,13 +132,13 @@ void QobuzFavoriteRequest::AddFavorites(const FavoriteType type, const SongList void QobuzFavoriteRequest::AddFavoritesRequest(const FavoriteType type, const QStringList &ids_list, const SongList &songs) { - ParamList params = ParamList() << Param("app_id", app_id()) - << Param("user_auth_token", user_auth_token()) - << Param(FavoriteMethod(type), ids_list.join(',')); + ParamList params = ParamList() << Param(QStringLiteral("app_id"), app_id()) + << Param(QStringLiteral("user_auth_token"), user_auth_token()) + << Param(FavoriteMethod(type), ids_list.join(QLatin1Char(','))); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } QNetworkReply *reply = CreateRequest(QStringLiteral("favorite/create"), params); @@ -227,13 +227,13 @@ void QobuzFavoriteRequest::RemoveFavorites(const FavoriteType type, const SongLi void QobuzFavoriteRequest::RemoveFavoritesRequest(const FavoriteType type, const QStringList &ids_list, const SongList &songs) { - ParamList params = ParamList() << Param("app_id", app_id()) - << Param("user_auth_token", user_auth_token()) - << Param(FavoriteMethod(type), ids_list.join(',')); + ParamList params = ParamList() << Param(QStringLiteral("app_id"), app_id()) + << Param(QStringLiteral("user_auth_token"), user_auth_token()) + << Param(FavoriteMethod(type), ids_list.join(QLatin1Char(','))); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } QNetworkReply *reply = CreateRequest(QStringLiteral("favorite/delete"), params); diff --git a/src/qobuz/qobuzrequest.cpp b/src/qobuz/qobuzrequest.cpp index d911b42b2c..556c15ee4b 100644 --- a/src/qobuz/qobuzrequest.cpp +++ b/src/qobuz/qobuzrequest.cpp @@ -225,12 +225,12 @@ void QobuzRequest::FlushArtistsRequests() { ParamList params; if (query_type_ == QueryType::Artists) { - params << Param("type", "artists"); - params << Param("user_auth_token", user_auth_token()); + params << Param(QStringLiteral("type"), QStringLiteral("artists")); + params << Param(QStringLiteral("user_auth_token"), user_auth_token()); } - else if (query_type_ == QueryType::SearchArtists) params << Param("query", search_text_); - if (request.limit > 0) params << Param("limit", QString::number(request.limit)); - if (request.offset > 0) params << Param("offset", QString::number(request.offset)); + else if (query_type_ == QueryType::SearchArtists) params << Param(QStringLiteral("query"), search_text_); + if (request.limit > 0) params << Param(QStringLiteral("limit"), QString::number(request.limit)); + if (request.offset > 0) params << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = nullptr; if (query_type_ == QueryType::Artists) { reply = CreateRequest(QStringLiteral("favorite/getUserFavorites"), params); @@ -277,12 +277,12 @@ void QobuzRequest::FlushAlbumsRequests() { ParamList params; if (query_type_ == QueryType::Albums) { - params << Param("type", "albums"); - params << Param("user_auth_token", user_auth_token()); + params << Param(QStringLiteral("type"), QStringLiteral("albums")); + params << Param(QStringLiteral("user_auth_token"), user_auth_token()); } - else if (query_type_ == QueryType::SearchAlbums) params << Param("query", search_text_); - if (request.limit > 0) params << Param("limit", QString::number(request.limit)); - if (request.offset > 0) params << Param("offset", QString::number(request.offset)); + else if (query_type_ == QueryType::SearchAlbums) params << Param(QStringLiteral("query"), search_text_); + if (request.limit > 0) params << Param(QStringLiteral("limit"), QString::number(request.limit)); + if (request.offset > 0) params << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = nullptr; if (query_type_ == QueryType::Albums) { reply = CreateRequest(QStringLiteral("favorite/getUserFavorites"), params); @@ -329,12 +329,12 @@ void QobuzRequest::FlushSongsRequests() { ParamList params; if (query_type_ == QueryType::Songs) { - params << Param("type", "tracks"); - params << Param("user_auth_token", user_auth_token()); + params << Param(QStringLiteral("type"), QStringLiteral("tracks")); + params << Param(QStringLiteral("user_auth_token"), user_auth_token()); } - else if (query_type_ == QueryType::SearchSongs) params << Param("query", search_text_); - if (request.limit > 0) params << Param("limit", QString::number(request.limit)); - if (request.offset > 0) params << Param("offset", QString::number(request.offset)); + else if (query_type_ == QueryType::SearchSongs) params << Param(QStringLiteral("query"), search_text_); + if (request.limit > 0) params << Param(QStringLiteral("limit"), QString::number(request.limit)); + if (request.offset > 0) params << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = nullptr; if (query_type_ == QueryType::Songs) { reply = CreateRequest(QStringLiteral("favorite/getUserFavorites"), params); @@ -585,10 +585,10 @@ void QobuzRequest::FlushArtistAlbumsRequests() { const ArtistAlbumsRequest request = artist_albums_requests_queue_.dequeue(); - ParamList params = ParamList() << Param("artist_id", request.artist.artist_id) - << Param("extra", "albums"); + ParamList params = ParamList() << Param(QStringLiteral("artist_id"), request.artist.artist_id) + << Param(QStringLiteral("extra"), QStringLiteral("albums")); - if (request.offset > 0) params << Param("offset", QString::number(request.offset)); + if (request.offset > 0) params << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = CreateRequest(QStringLiteral("artist/get"), params); QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, request]() { ArtistAlbumsReplyReceived(reply, request.artist, request.offset); }); replies_ << reply; @@ -842,8 +842,8 @@ void QobuzRequest::FlushAlbumSongsRequests() { while (!album_songs_requests_queue_.isEmpty() && album_songs_requests_active_ < kMaxConcurrentAlbumSongsRequests) { AlbumSongsRequest request = album_songs_requests_queue_.dequeue(); - ParamList params = ParamList() << Param("album_id", request.album.album_id); - if (request.offset > 0) params << Param("offset", QString::number(request.offset)); + ParamList params = ParamList() << Param(QStringLiteral("album_id"), request.album.album_id); + if (request.offset > 0) params << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = CreateRequest(QStringLiteral("album/get"), params); replies_ << reply; QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, request]() { AlbumSongsReplyReceived(reply, request.artist, request.album, request.offset); }); @@ -1341,8 +1341,8 @@ void QobuzRequest::AlbumCoverReceived(QNetworkReply *reply, const QUrl &cover_ur } QString mimetype = reply->header(QNetworkRequest::ContentTypeHeader).toString(); - if (mimetype.contains(';')) { - mimetype = mimetype.left(mimetype.indexOf(';')); + if (mimetype.contains(QLatin1Char(';'))) { + mimetype = mimetype.left(mimetype.indexOf(QLatin1Char(';'))); } if (!ImageUtils::SupportedImageMimeTypes().contains(mimetype, Qt::CaseInsensitive) && !ImageUtils::SupportedImageFormats().contains(mimetype, Qt::CaseInsensitive)) { Error(QStringLiteral("Unsupported mimetype for image reader %1 for %2").arg(mimetype, cover_url.toString())); @@ -1351,7 +1351,7 @@ void QobuzRequest::AlbumCoverReceived(QNetworkReply *reply, const QUrl &cover_ur return; } - QByteArray data = reply->readAll(); + const QByteArray data = reply->readAll(); if (data.isEmpty()) { Error(QStringLiteral("Received empty image data for %1").arg(cover_url.toString())); if (album_covers_requests_sent_.contains(cover_url)) album_covers_requests_sent_.remove(cover_url); diff --git a/src/qobuz/qobuzservice.cpp b/src/qobuz/qobuzservice.cpp index 0ab02c588e..a8e4a7fb2c 100644 --- a/src/qobuz/qobuzservice.cpp +++ b/src/qobuz/qobuzservice.cpp @@ -45,6 +45,7 @@ #include "core/networkaccessmanager.h" #include "core/database.h" #include "core/song.h" +#include "core/settings.h" #include "utilities/macaddrutils.h" #include "internet/internetsearchview.h" #include "collection/collectionbackend.h" @@ -62,22 +63,26 @@ using std::make_shared; const Song::Source QobuzService::kSource = Song::Source::Qobuz; const char QobuzService::kApiUrl[] = "https://www.qobuz.com/api.json/0.2"; +const int QobuzService::kLoginAttempts = 2; -constexpr char QobuzService::kAuthUrl[] = "https://www.qobuz.com/api.json/0.2/user/login"; +namespace { -const int QobuzService::kLoginAttempts = 2; -constexpr int QobuzService::kTimeResetLoginAttempts = 60000; +constexpr char kAuthUrl[] = "https://www.qobuz.com/api.json/0.2/user/login"; + +constexpr int kTimeResetLoginAttempts = 60000; + +constexpr char kArtistsSongsTable[] = "qobuz_artists_songs"; +constexpr char kAlbumsSongsTable[] = "qobuz_albums_songs"; +constexpr char kSongsTable[] = "qobuz_songs"; -constexpr char QobuzService::kArtistsSongsTable[] = "qobuz_artists_songs"; -constexpr char QobuzService::kAlbumsSongsTable[] = "qobuz_albums_songs"; -constexpr char QobuzService::kSongsTable[] = "qobuz_songs"; +constexpr char kArtistsSongsFtsTable[] = "qobuz_artists_songs_fts"; +constexpr char kAlbumsSongsFtsTable[] = "qobuz_albums_songs_fts"; +constexpr char kSongsFtsTable[] = "qobuz_songs_fts"; -constexpr char QobuzService::kArtistsSongsFtsTable[] = "qobuz_artists_songs_fts"; -constexpr char QobuzService::kAlbumsSongsFtsTable[] = "qobuz_albums_songs_fts"; -constexpr char QobuzService::kSongsFtsTable[] = "qobuz_songs_fts"; +} // namespace QobuzService::QobuzService(Application *app, QObject *parent) - : InternetService(Song::Source::Qobuz, QStringLiteral("Qobuz"), QStringLiteral("qobuz"), QobuzSettingsPage::kSettingsGroup, SettingsDialog::Page::Qobuz, app, parent), + : InternetService(Song::Source::Qobuz, QStringLiteral("Qobuz"), QStringLiteral("qobuz"), QLatin1String(QobuzSettingsPage::kSettingsGroup), SettingsDialog::Page::Qobuz, app, parent), app_(app), network_(app->network()), url_handler_(new QobuzUrlHandler(app, this)), @@ -115,15 +120,15 @@ QobuzService::QobuzService(Application *app, QObject *parent) artists_collection_backend_ = make_shared(); artists_collection_backend_->moveToThread(app_->database()->thread()); - artists_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Qobuz, kArtistsSongsTable, kArtistsSongsFtsTable); + artists_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Qobuz, QLatin1String(kArtistsSongsTable), QLatin1String(kArtistsSongsFtsTable)); albums_collection_backend_ = make_shared(); albums_collection_backend_->moveToThread(app_->database()->thread()); - albums_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Qobuz, kAlbumsSongsTable, kAlbumsSongsFtsTable); + albums_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Qobuz, QLatin1String(kAlbumsSongsTable), QLatin1String(kAlbumsSongsFtsTable)); songs_collection_backend_ = make_shared(); songs_collection_backend_->moveToThread(app_->database()->thread()); - songs_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Qobuz, kSongsTable, kSongsFtsTable); + songs_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Qobuz, QLatin1String(kSongsTable), QLatin1String(kSongsFtsTable)); artists_collection_model_ = new CollectionModel(artists_collection_backend_, app_, this); albums_collection_model_ = new CollectionModel(albums_collection_backend_, app_, this); @@ -229,7 +234,7 @@ void QobuzService::ShowConfig() { void QobuzService::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(QobuzSettingsPage::kSettingsGroup); app_id_ = s.value("app_id").toString(); @@ -295,21 +300,21 @@ void QobuzService::SendLoginWithCredentials(const QString &app_id, const QString timer_login_attempt_->setInterval(kTimeResetLoginAttempts); timer_login_attempt_->start(); - const ParamList params = ParamList() << Param("app_id", app_id) - << Param("username", username) - << Param("password", password) - << Param("device_manufacturer_id", Utilities::MacAddress()); + const ParamList params = ParamList() << Param(QStringLiteral("app_id"), app_id) + << Param(QStringLiteral("username"), username) + << Param(QStringLiteral("password"), password) + << Param(QStringLiteral("device_manufacturer_id"), Utilities::MacAddress()); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromUtf8(QUrl::toPercentEncoding(param.first)), QString::fromUtf8(QUrl::toPercentEncoding(param.second))); } - QUrl url(kAuthUrl); + QUrl url(QString::fromUtf8(kAuthUrl)); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8(); QNetworkReply *reply = network_->post(req, query); @@ -369,7 +374,7 @@ void QobuzService::HandleAuthReply(QNetworkReply *reply) { login_errors_.clear(); - QByteArray data = reply->readAll(); + const QByteArray data = reply->readAll(); QJsonParseError json_error; QJsonDocument json_doc = QJsonDocument::fromJson(data, &json_error); @@ -451,7 +456,7 @@ void QobuzService::HandleAuthReply(QNetworkReply *reply) { } credential_id_ = obj_credential[QStringLiteral("id")].toInt(); - QSettings s; + Settings s; s.beginGroup(QobuzSettingsPage::kSettingsGroup); s.setValue("user_auth_token", user_auth_token_); s.setValue("user_id", user_id_); @@ -476,7 +481,7 @@ void QobuzService::Logout() { user_id_ = -1; credential_id_ = -1; - QSettings s; + Settings s; s.beginGroup(QobuzSettingsPage::kSettingsGroup); s.remove("user_id"); s.remove("credential_id"); @@ -784,7 +789,7 @@ void QobuzService::LoginError(const QString &error, const QVariant &debug) { QString error_html; for (const QString &e : login_errors_) { qLog(Error) << "Qobuz:" << e; - error_html += e + "
"; + error_html += e + QStringLiteral("
"); } if (debug.isValid()) qLog(Debug) << debug; diff --git a/src/qobuz/qobuzservice.h b/src/qobuz/qobuzservice.h index edfb76e200..5fffc62880 100644 --- a/src/qobuz/qobuzservice.h +++ b/src/qobuz/qobuzservice.h @@ -63,6 +63,7 @@ class QobuzService : public InternetService { static const Song::Source kSource; static const char kApiUrl[]; + static const int kLoginAttempts; void Exit() override; void ReloadSettings() override; @@ -147,19 +148,6 @@ class QobuzService : public InternetService { void SendSearch(); void LoginError(const QString &error = QString(), const QVariant &debug = QVariant()); - static const char kAuthUrl[]; - - static const int kLoginAttempts; - static const int kTimeResetLoginAttempts; - - static const char kArtistsSongsTable[]; - static const char kAlbumsSongsTable[]; - static const char kSongsTable[]; - - static const char kArtistsSongsFtsTable[]; - static const char kAlbumsSongsFtsTable[]; - static const char kSongsFtsTable[]; - Application *app_; SharedPtr network_; QobuzUrlHandler *url_handler_; diff --git a/src/qobuz/qobuzstreamurlrequest.cpp b/src/qobuz/qobuzstreamurlrequest.cpp index dd410dc633..8a6284900f 100644 --- a/src/qobuz/qobuzstreamurlrequest.cpp +++ b/src/qobuz/qobuzstreamurlrequest.cpp @@ -115,26 +115,26 @@ void QobuzStreamURLRequest::GetStreamURL() { quint64 timestamp = QDateTime::currentDateTime().toSecsSinceEpoch(); - ParamList params_to_sign = ParamList() << Param("format_id", QString::number(format())) - << Param("track_id", QString::number(song_id_)); + ParamList params_to_sign = ParamList() << Param(QStringLiteral("format_id"), QString::number(format())) + << Param(QStringLiteral("track_id"), QString::number(song_id_)); std::sort(params_to_sign.begin(), params_to_sign.end()); QString data_to_sign; - data_to_sign += QLatin1String("trackgetFileUrl"); + data_to_sign += QStringLiteral("trackgetFileUrl"); for (const Param ¶m : params_to_sign) { data_to_sign += param.first + param.second; } data_to_sign += QString::number(timestamp); - data_to_sign += app_secret().toUtf8(); + data_to_sign += app_secret(); QByteArray const digest = QCryptographicHash::hash(data_to_sign.toUtf8(), QCryptographicHash::Md5); - QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, '0').toLower(); + const QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, QLatin1Char('0')).toLower(); ParamList params = params_to_sign; - params << Param("request_ts", QString::number(timestamp)); - params << Param("request_sig", signature); - params << Param("user_auth_token", user_auth_token()); + params << Param(QStringLiteral("request_ts"), QString::number(timestamp)); + params << Param(QStringLiteral("request_sig"), signature); + params << Param(QStringLiteral("user_auth_token"), user_auth_token()); std::sort(params.begin(), params.end()); @@ -192,7 +192,7 @@ void QobuzStreamURLRequest::StreamURLReceived() { Song::FileType filetype(Song::FileType::Unknown); QMimeDatabase mimedb; - QStringList suffixes = mimedb.mimeTypeForName(mimetype.toUtf8()).suffixes(); + QStringList suffixes = mimedb.mimeTypeForName(mimetype).suffixes(); for (const QString &suffix : suffixes) { filetype = Song::FiletypeByExtension(suffix); if (filetype != Song::FileType::Unknown) break; diff --git a/src/queue/queue.cpp b/src/queue/queue.cpp index 5f93f2813a..fc931a44c9 100644 --- a/src/queue/queue.cpp +++ b/src/queue/queue.cpp @@ -39,7 +39,9 @@ #include "playlist/playlist.h" #include "queue.h" -const char *Queue::kRowsMimetype = "application/x-strawberry-queue-rows"; +namespace { +static constexpr char kRowsMimetype[] = "application/x-strawberry-queue-rows"; +} Queue::Queue(Playlist *playlist, QObject *parent) : QAbstractProxyModel(parent), playlist_(playlist), total_length_ns_(0) { @@ -252,7 +254,7 @@ void Queue::UpdateSummaryText() { summary += tr("%n track(s)", "", tracks); if (nanoseconds > 0) { - summary += " - [ " + Utilities::WordyTimeNanosec(nanoseconds) + " ]"; + summary += QStringLiteral(" - [ ") + Utilities::WordyTimeNanosec(nanoseconds) + QStringLiteral(" ]"); } emit SummaryTextChanged(summary); @@ -320,7 +322,7 @@ void Queue::MoveDown(int row) { } QStringList Queue::mimeTypes() const { - return QStringList() << kRowsMimetype << Playlist::kRowsMimetype; + return QStringList() << QLatin1String(kRowsMimetype) << QLatin1String(Playlist::kRowsMimetype); } Qt::DropActions Queue::supportedDropActions() const { @@ -343,7 +345,7 @@ QMimeData *Queue::mimeData(const QModelIndexList &indexes) const { QDataStream stream(&buf); stream << rows; buf.close(); - data->setData(kRowsMimetype, buf.data()); + data->setData(QLatin1String(kRowsMimetype), buf.data()); } return data; @@ -355,11 +357,11 @@ bool Queue::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, if (action == Qt::IgnoreAction) return false; - if (data->hasFormat(kRowsMimetype)) { + if (data->hasFormat(QLatin1String(kRowsMimetype))) { // Dragged from the queue QList proxy_rows; - QDataStream stream(data->data(kRowsMimetype)); + QDataStream stream(data->data(QLatin1String(kRowsMimetype))); stream >> proxy_rows; // Make sure we take them in order @@ -367,12 +369,12 @@ bool Queue::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, Move(proxy_rows, row); } - else if (data->hasFormat(Playlist::kRowsMimetype)) { + else if (data->hasFormat(QLatin1String(Playlist::kRowsMimetype))) { // Dragged from the playlist Playlist *playlist = nullptr; QList source_rows; - QDataStream stream(data->data(Playlist::kRowsMimetype)); + QDataStream stream(data->data(QLatin1String(Playlist::kRowsMimetype))); stream.readRawData(reinterpret_cast(&playlist), sizeof(Playlist)); stream >> source_rows; diff --git a/src/queue/queue.h b/src/queue/queue.h index 4a4321b15b..e96ae9afe6 100644 --- a/src/queue/queue.h +++ b/src/queue/queue.h @@ -41,8 +41,6 @@ class Queue : public QAbstractProxyModel { public: explicit Queue(Playlist *playlist, QObject *parent = nullptr); - static const char *kRowsMimetype; - // Query the queue bool is_empty() const; int PositionOf(const QModelIndex &source_index) const; diff --git a/src/queue/queueview.cpp b/src/queue/queueview.cpp index d5ec1c07ba..95b3849233 100644 --- a/src/queue/queueview.cpp +++ b/src/queue/queueview.cpp @@ -35,6 +35,7 @@ #include "core/shared_ptr.h" #include "core/iconloader.h" +#include "core/settings.h" #include "playlist/playlist.h" #include "playlist/playlistdelegates.h" #include "playlist/playlistmanager.h" @@ -86,7 +87,7 @@ void QueueView::SetPlaylistManager(SharedPtr playlist_manager) void QueueView::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); int iconsize = s.value(AppearanceSettingsPage::kIconSizeLeftPanelButtons, 22).toInt(); s.endGroup(); diff --git a/src/radios/radiochannel.cpp b/src/radios/radiochannel.cpp index 98dce5d9d6..a0ab582dc3 100644 --- a/src/radios/radiochannel.cpp +++ b/src/radios/radiochannel.cpp @@ -28,7 +28,7 @@ Song RadioChannel::ToSong() const { Song song(source); song.set_valid(true); song.set_filetype(Song::FileType::Stream); - song.set_title(Song::DescriptionForSource(source) + " " + name); + song.set_title(Song::DescriptionForSource(source) + QStringLiteral(" ") + name); song.set_url(url); return song; diff --git a/src/radios/radiomodel.cpp b/src/radios/radiomodel.cpp index 16b4195608..fa15e626c7 100644 --- a/src/radios/radiomodel.cpp +++ b/src/radios/radiomodel.cpp @@ -181,7 +181,7 @@ void RadioModel::AddChannels(const RadioChannelList &channels) { RadioItem *item = new RadioItem(RadioItem::Type_Channel, container); item->source = channel.source; item->display_text = channel.name; - item->sort_text = SortText(Song::TextForSource(channel.source) + " - " + channel.name); + item->sort_text = SortText(Song::TextForSource(channel.source) + QStringLiteral(" - ") + channel.name); item->channel = channel; item->lazy_loaded = true; items_ << item; @@ -258,7 +258,7 @@ QString RadioModel::ChannelIconPixmapCacheKey(const QModelIndex &idx) const { idx_copy = idx_copy.parent(); } - return path.join('/'); + return path.join(QLatin1Char('/')); } diff --git a/src/radios/radioparadiseservice.cpp b/src/radios/radioparadiseservice.cpp index 2afa717425..71c9c880a9 100644 --- a/src/radios/radioparadiseservice.cpp +++ b/src/radios/radioparadiseservice.cpp @@ -32,7 +32,9 @@ #include "radioparadiseservice.h" #include "radiochannel.h" -const char *RadioParadiseService::kApiChannelsUrl = "https://api.radioparadise.com/api/list_streams"; +namespace { +constexpr char kApiChannelsUrl[] = "https://api.radioparadise.com/api/list_streams"; +} RadioParadiseService::RadioParadiseService(Application *app, SharedPtr network, QObject *parent) : RadioService(Song::Source::RadioParadise, QStringLiteral("Radio Paradise"), IconLoader::Load(QStringLiteral("radioparadise")), app, network, parent) {} @@ -57,7 +59,7 @@ void RadioParadiseService::GetChannels() { Abort(); - QUrl url(kApiChannelsUrl); + QUrl url(QString::fromLatin1(kApiChannelsUrl)); QNetworkRequest req(url); QNetworkReply *reply = network_->get(req); replies_ << reply; @@ -108,11 +110,11 @@ void RadioParadiseService::GetChannelsReply(QNetworkReply *reply, const int task QString label = obj_stream[QStringLiteral("label")].toString(); QString url = obj_stream[QStringLiteral("url")].toString(); if (!url.contains(QRegularExpression(QStringLiteral("^[0-9a-zA-Z]*:\\/\\/"), QRegularExpression::CaseInsensitiveOption))) { - url.prepend("https://"); + url.prepend(QStringLiteral("https://")); } RadioChannel channel; channel.source = source_; - channel.name = name + " - " + label; + channel.name = name + QStringLiteral(" - ") + label; channel.url.setUrl(url); channels << channel; } diff --git a/src/radios/radioparadiseservice.h b/src/radios/radioparadiseservice.h index 2341ad826a..ec51533da4 100644 --- a/src/radios/radioparadiseservice.h +++ b/src/radios/radioparadiseservice.h @@ -48,7 +48,6 @@ class RadioParadiseService : public RadioService { void GetChannelsReply(QNetworkReply *reply, const int task_id); private: - static const char *kApiChannelsUrl; QList replies_; RadioChannelList channels_; }; diff --git a/src/radios/radioviewcontainer.cpp b/src/radios/radioviewcontainer.cpp index f721530935..db41b6ded3 100644 --- a/src/radios/radioviewcontainer.cpp +++ b/src/radios/radioviewcontainer.cpp @@ -22,6 +22,7 @@ #include #include "core/iconloader.h" +#include "core/settings.h" #include "settings/appearancesettingspage.h" #include "radioviewcontainer.h" #include "ui_radioviewcontainer.h" @@ -44,7 +45,7 @@ RadioViewContainer::~RadioViewContainer() { delete ui_; } void RadioViewContainer::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); int iconsize = s.value(AppearanceSettingsPage::kIconSizeLeftPanelButtons, 22).toInt(); s.endGroup(); diff --git a/src/radios/somafmservice.cpp b/src/radios/somafmservice.cpp index e29f495a11..d676c70389 100644 --- a/src/radios/somafmservice.cpp +++ b/src/radios/somafmservice.cpp @@ -34,7 +34,9 @@ #include "somafmservice.h" #include "radiochannel.h" -const char *SomaFMService::kApiChannelsUrl = "https://somafm.com/channels.json"; +namespace { +constexpr char kApiChannelsUrl[] = "https://somafm.com/channels.json"; +} SomaFMService::SomaFMService(Application *app, SharedPtr network, QObject *parent) : RadioService(Song::Source::SomaFM, QStringLiteral("SomaFM"), IconLoader::Load(QStringLiteral("somafm")), app, network, parent) {} @@ -63,7 +65,7 @@ void SomaFMService::GetChannels() { Abort(); - QUrl url(kApiChannelsUrl); + QUrl url(QString::fromUtf8(kApiChannelsUrl)); QNetworkRequest req(url); QNetworkReply *reply = network_->get(req); replies_ << reply; @@ -110,13 +112,13 @@ void SomaFMService::GetChannelsReply(QNetworkReply *reply, const int task_id) { } RadioChannel channel; QString quality = obj_playlist[QStringLiteral("quality")].toString(); - if (quality != "highest") continue; + if (quality != QStringLiteral("highest")) continue; channel.source = source_; channel.name = name; channel.url.setUrl(obj_playlist[QStringLiteral("url")].toString()); channel.thumbnail_url.setUrl(image); if (obj_playlist.contains(QStringLiteral("format"))) { - channel.name.append(" " + obj_playlist[QStringLiteral("format")].toString().toUpper()); + channel.name.append(QLatin1Char(' ') + obj_playlist[QStringLiteral("format")].toString().toUpper()); } channels << channel; } diff --git a/src/radios/somafmservice.h b/src/radios/somafmservice.h index da8e649200..df23a7b31c 100644 --- a/src/radios/somafmservice.h +++ b/src/radios/somafmservice.h @@ -53,7 +53,6 @@ class SomaFMService : public RadioService { void GetStreamUrlsReply(QNetworkReply *reply, const int task_id, RadioChannel channel); private: - static const char *kApiChannelsUrl; QList replies_; RadioChannelList channels_; }; diff --git a/src/scrobbler/audioscrobbler.h b/src/scrobbler/audioscrobbler.h index 4e853b3c24..3e5de2e609 100644 --- a/src/scrobbler/audioscrobbler.h +++ b/src/scrobbler/audioscrobbler.h @@ -55,7 +55,7 @@ class AudioScrobbler : public QObject { SharedPtr ServiceByName(const QString &name); template SharedPtr Service() { - return std::static_pointer_cast(ServiceByName(T::kName)); + return std::static_pointer_cast(ServiceByName(QLatin1String(T::kName))); } void ReloadSettings(); diff --git a/src/scrobbler/lastfmimport.cpp b/src/scrobbler/lastfmimport.cpp index 264efa5f38..f939a57905 100644 --- a/src/scrobbler/lastfmimport.cpp +++ b/src/scrobbler/lastfmimport.cpp @@ -41,6 +41,7 @@ #include "core/logging.h" #include "core/shared_ptr.h" #include "core/networkaccessmanager.h" +#include "core/settings.h" #include "lastfmimport.h" @@ -94,7 +95,7 @@ void LastFMImport::AbortAll() { void LastFMImport::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(LastFMScrobbler::kSettingsGroup); username_ = s.value("username").toString(); s.endGroup(); @@ -104,24 +105,24 @@ void LastFMImport::ReloadSettings() { QNetworkReply *LastFMImport::CreateRequest(const ParamList &request_params) { ParamList params = ParamList() - << Param("api_key", ScrobblingAPI20::kApiKey) - << Param("user", username_) - << Param("lang", QLocale().name().left(2).toLower()) - << Param("format", "json") + << Param(QStringLiteral("api_key"), QLatin1String(ScrobblingAPI20::kApiKey)) + << Param(QStringLiteral("user"), username_) + << Param(QStringLiteral("lang"), QLocale().name().left(2).toLower()) + << Param(QStringLiteral("format"), QStringLiteral("json")) << request_params; std::sort(params.begin(), params.end()); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } - QUrl url(LastFMScrobbler::kApiUrl); + QUrl url(QLatin1String(LastFMScrobbler::kApiUrl)); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); QNetworkReply *reply = network_->get(req); replies_ << reply; @@ -251,15 +252,15 @@ void LastFMImport::AddGetRecentTracksRequest(const int page) { void LastFMImport::SendGetRecentTracksRequest(GetRecentTracksRequest request) { - ParamList params = ParamList() << Param("method", "user.getRecentTracks"); + ParamList params = ParamList() << Param(QStringLiteral("method"), QStringLiteral("user.getRecentTracks")); if (request.page == 0) { - params << Param("page", "1"); - params << Param("limit", "1"); + params << Param(QStringLiteral("page"), QStringLiteral("1")); + params << Param(QStringLiteral("limit"), QStringLiteral("1")); } else { - params << Param("page", QString::number(request.page)); - params << Param("limit", "500"); + params << Param(QStringLiteral("page"), QString::number(request.page)); + params << Param(QStringLiteral("limit"), QStringLiteral("500")); } QNetworkReply *reply = CreateRequest(params); @@ -414,15 +415,15 @@ void LastFMImport::AddGetTopTracksRequest(const int page) { void LastFMImport::SendGetTopTracksRequest(GetTopTracksRequest request) { - ParamList params = ParamList() << Param("method", "user.getTopTracks"); + ParamList params = ParamList() << Param(QStringLiteral("method"), QStringLiteral("user.getTopTracks")); if (request.page == 0) { - params << Param("page", "1"); - params << Param("limit", "1"); + params << Param(QStringLiteral("page"), QStringLiteral("1")); + params << Param(QStringLiteral("limit"), QStringLiteral("1")); } else { - params << Param("page", QString::number(request.page)); - params << Param("limit", "500"); + params << Param(QStringLiteral("page"), QString::number(request.page)); + params << Param(QStringLiteral("limit"), QStringLiteral("500")); } QNetworkReply *reply = CreateRequest(params); diff --git a/src/scrobbler/lastfmscrobbler.cpp b/src/scrobbler/lastfmscrobbler.cpp index a8de1b8d35..44ae692734 100644 --- a/src/scrobbler/lastfmscrobbler.cpp +++ b/src/scrobbler/lastfmscrobbler.cpp @@ -34,4 +34,4 @@ const char *LastFMScrobbler::kApiUrl = "https://ws.audioscrobbler.com/2.0/"; const char *LastFMScrobbler::kCacheFile = "lastfmscrobbler.cache"; LastFMScrobbler::LastFMScrobbler(SharedPtr settings, SharedPtr network, QObject *parent) - : ScrobblingAPI20(kName, kSettingsGroup, kAuthUrl, kApiUrl, true, kCacheFile, settings, network, parent) {} + : ScrobblingAPI20(QLatin1String(kName), QLatin1String(kSettingsGroup), QLatin1String(kAuthUrl), QLatin1String(kApiUrl), true, QLatin1String(kCacheFile), settings, network, parent) {} diff --git a/src/scrobbler/librefmscrobbler.cpp b/src/scrobbler/librefmscrobbler.cpp index 1d8a11b2df..08cdbc1234 100644 --- a/src/scrobbler/librefmscrobbler.cpp +++ b/src/scrobbler/librefmscrobbler.cpp @@ -35,4 +35,4 @@ const char *LibreFMScrobbler::kApiUrl = "https://libre.fm/2.0/"; const char *LibreFMScrobbler::kCacheFile = "librefmscrobbler.cache"; LibreFMScrobbler::LibreFMScrobbler(SharedPtr settings, SharedPtr network, QObject *parent) - : ScrobblingAPI20(kName, kSettingsGroup, kAuthUrl, kApiUrl, false, kCacheFile, settings, network, parent) {} + : ScrobblingAPI20(QLatin1String(kName), QLatin1String(kSettingsGroup), QLatin1String(kAuthUrl), QLatin1String(kApiUrl), false, QLatin1String(kCacheFile), settings, network, parent) {} diff --git a/src/scrobbler/listenbrainzscrobbler.cpp b/src/scrobbler/listenbrainzscrobbler.cpp index 19110cfcb4..8dbc7a349e 100644 --- a/src/scrobbler/listenbrainzscrobbler.cpp +++ b/src/scrobbler/listenbrainzscrobbler.cpp @@ -44,6 +44,7 @@ #include "core/networkaccessmanager.h" #include "core/song.h" #include "core/logging.h" +#include "core/settings.h" #include "utilities/timeconstants.h" #include "internet/localredirectserver.h" #include "settings/scrobblersettingspage.h" @@ -57,19 +58,22 @@ const char *ListenBrainzScrobbler::kName = "ListenBrainz"; const char *ListenBrainzScrobbler::kSettingsGroup = "ListenBrainz"; -const char *ListenBrainzScrobbler::kOAuthAuthorizeUrl = "https://musicbrainz.org/oauth2/authorize"; -const char *ListenBrainzScrobbler::kOAuthAccessTokenUrl = "https://musicbrainz.org/oauth2/token"; -const char *ListenBrainzScrobbler::kOAuthRedirectUrl = "http://localhost"; -const char *ListenBrainzScrobbler::kApiUrl = "https://api.listenbrainz.org"; -const char *ListenBrainzScrobbler::kClientIDB64 = "b2VBVU53cVNRZXIwZXIwOUZpcWkwUQ=="; -const char *ListenBrainzScrobbler::kClientSecretB64 = "Uk9GZ2hrZVEzRjNvUHlFaHFpeVdQQQ=="; -const char *ListenBrainzScrobbler::kCacheFile = "listenbrainzscrobbler.cache"; -const int ListenBrainzScrobbler::kScrobblesPerRequest = 10; + +namespace { +constexpr char kOAuthAuthorizeUrl[] = "https://musicbrainz.org/oauth2/authorize"; +constexpr char kOAuthAccessTokenUrl[] = "https://musicbrainz.org/oauth2/token"; +constexpr char kOAuthRedirectUrl[] = "http://localhost"; +constexpr char kApiUrl[] = "https://api.listenbrainz.org"; +constexpr char kClientIDB64[] = "b2VBVU53cVNRZXIwZXIwOUZpcWkwUQ=="; +constexpr char kClientSecretB64[] = "Uk9GZ2hrZVEzRjNvUHlFaHFpeVdQQQ=="; +constexpr char kCacheFile[] = "listenbrainzscrobbler.cache"; +constexpr int kScrobblesPerRequest = 10; +} // namespace ListenBrainzScrobbler::ListenBrainzScrobbler(SharedPtr settings, SharedPtr network, QObject *parent) - : ScrobblerService(kName, settings, parent), + : ScrobblerService(QLatin1String(kName), settings, parent), network_(network), - cache_(new ScrobblerCache(kCacheFile, this)), + cache_(new ScrobblerCache(QLatin1String(kCacheFile), this)), server_(nullptr), enabled_(false), expires_in_(-1), @@ -110,7 +114,7 @@ ListenBrainzScrobbler::~ListenBrainzScrobbler() { void ListenBrainzScrobbler::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); enabled_ = s.value("enabled", false).toBool(); user_token_ = s.value("user_token").toString(); @@ -124,7 +128,7 @@ void ListenBrainzScrobbler::ReloadSettings() { void ListenBrainzScrobbler::LoadSession() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); access_token_ = s.value("access_token").toString(); expires_in_ = s.value("expires_in", -1).toInt(); @@ -150,13 +154,13 @@ void ListenBrainzScrobbler::Logout() { expires_in_ = -1; login_time_ = 0; - QSettings settings; - settings.beginGroup(kSettingsGroup); - settings.remove("access_token"); - settings.remove("expires_in"); - settings.remove("token_type"); - settings.remove("refresh_token"); - settings.endGroup(); + Settings s; + s.beginGroup(kSettingsGroup); + s.remove("access_token"); + s.remove("expires_in"); + s.remove("token_type"); + s.remove("refresh_token"); + s.endGroup(); } @@ -173,15 +177,15 @@ void ListenBrainzScrobbler::Authenticate() { QObject::connect(server_, &LocalRedirectServer::Finished, this, &ListenBrainzScrobbler::RedirectArrived); } - QUrl redirect_url(kOAuthRedirectUrl); + QUrl redirect_url(QString::fromLatin1(kOAuthRedirectUrl)); redirect_url.setPort(server_->url().port()); QUrlQuery url_query; url_query.addQueryItem(QStringLiteral("response_type"), QStringLiteral("code")); - url_query.addQueryItem(QStringLiteral("client_id"), QByteArray::fromBase64(kClientIDB64)); + url_query.addQueryItem(QStringLiteral("client_id"), QString::fromLatin1(QByteArray::fromBase64(kClientIDB64))); url_query.addQueryItem(QStringLiteral("redirect_uri"), redirect_url.toString()); url_query.addQueryItem(QStringLiteral("scope"), QStringLiteral("profile;email;tag;rating;collection;submit_isrc;submit_barcode")); - QUrl url(kOAuthAuthorizeUrl); + QUrl url(QString::fromLatin1(kOAuthAuthorizeUrl)); url.setQuery(url_query); bool result = QDesktopServices::openUrl(url); @@ -268,17 +272,17 @@ void ListenBrainzScrobbler::RequestAccessToken(const QUrl &redirect_url, const Q refresh_login_timer_.stop(); - ParamList params = ParamList() << Param("client_id", QByteArray::fromBase64(kClientIDB64)) - << Param("client_secret", QByteArray::fromBase64(kClientSecretB64)); + ParamList params = ParamList() << Param(QStringLiteral("client_id"), QString::fromLatin1(QByteArray::fromBase64(kClientIDB64))) + << Param(QStringLiteral("client_secret"), QString::fromLatin1(QByteArray::fromBase64(kClientSecretB64))); if (!code.isEmpty() && !redirect_url.isEmpty()) { - params << Param("grant_type", "authorization_code"); - params << Param("code", code); - params << Param("redirect_uri", redirect_url.toString()); + params << Param(QStringLiteral("grant_type"), QStringLiteral("authorization_code")); + params << Param(QStringLiteral("code"), code); + params << Param(QStringLiteral("redirect_uri"), redirect_url.toString()); } else if (!refresh_token_.isEmpty() && enabled_) { - params << Param("grant_type", "refresh_token"); - params << Param("refresh_token", refresh_token_); + params << Param(QStringLiteral("grant_type"), QStringLiteral("refresh_token")); + params << Param(QStringLiteral("refresh_token"), refresh_token_); } else { return; @@ -286,14 +290,14 @@ void ListenBrainzScrobbler::RequestAccessToken(const QUrl &redirect_url, const Q QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } - QUrl session_url(kOAuthAccessTokenUrl); + QUrl session_url(QString::fromLatin1(kOAuthAccessTokenUrl)); QNetworkRequest req(session_url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8(); QNetworkReply *reply = network_->post(req, query); replies_ << reply; @@ -328,7 +332,7 @@ void ListenBrainzScrobbler::AuthenticateReplyFinished(QNetworkReply *reply) { } login_time_ = QDateTime::currentDateTime().toSecsSinceEpoch(); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("access_token", access_token_); s.setValue("expires_in", expires_in_); @@ -354,7 +358,7 @@ QNetworkReply *ListenBrainzScrobbler::CreateRequest(const QUrl &url, const QJson QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json")); req.setRawHeader("Authorization", QStringLiteral("Token %1").arg(user_token_).toUtf8()); QNetworkReply *reply = network_->post(req, json_doc.toJson()); replies_ << reply; @@ -398,13 +402,13 @@ QJsonObject ListenBrainzScrobbler::JsonTrackMetadata(const ScrobbleMetadata &met QStringList artist_mbids_list; if (!metadata.musicbrainz_album_artist_id.isEmpty()) { - artist_mbids_list << metadata.musicbrainz_album_artist_id.split('/'); + artist_mbids_list << metadata.musicbrainz_album_artist_id.split(QLatin1Char('/')); } if (!metadata.musicbrainz_artist_id.isEmpty()) { - artist_mbids_list << metadata.musicbrainz_artist_id.split('/'); + artist_mbids_list << metadata.musicbrainz_artist_id.split(QLatin1Char('/')); } if (!metadata.musicbrainz_original_artist_id.isEmpty()) { - artist_mbids_list << metadata.musicbrainz_original_artist_id.split('/'); + artist_mbids_list << metadata.musicbrainz_original_artist_id.split(QLatin1Char('/')); } if (!artist_mbids_list.isEmpty()) { QJsonArray artist_mbids_array; @@ -456,11 +460,11 @@ void ListenBrainzScrobbler::UpdateNowPlaying(const Song &song) { QJsonArray array_payload; array_payload.append(object_listen); QJsonObject object; - object.insert(QStringLiteral("listen_type"), "playing_now"); + object.insert(QStringLiteral("listen_type"), QStringLiteral("playing_now")); object.insert(QStringLiteral("payload"), array_payload); QJsonDocument doc(object); - QUrl url(QStringLiteral("%1/1/submit-listens").arg(kApiUrl)); + QUrl url(QStringLiteral("%1/1/submit-listens").arg(QLatin1String(kApiUrl))); QNetworkReply *reply = CreateRequest(url, doc); QObject::connect(reply, &QNetworkReply::finished, this, [this, reply]() { UpdateNowPlayingRequestFinished(reply); }); @@ -559,11 +563,11 @@ void ListenBrainzScrobbler::Submit() { submitted_ = true; QJsonObject object; - object.insert(QStringLiteral("listen_type"), "import"); + object.insert(QStringLiteral("listen_type"), QStringLiteral("import")); object.insert(QStringLiteral("payload"), array); QJsonDocument doc(object); - QUrl url(QStringLiteral("%1/1/submit-listens").arg(kApiUrl)); + QUrl url(QStringLiteral("%1/1/submit-listens").arg(QLatin1String(kApiUrl))); QNetworkReply *reply = CreateRequest(url, doc); QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, cache_items_sent]() { ScrobbleRequestFinished(reply, cache_items_sent); }); @@ -633,7 +637,7 @@ void ListenBrainzScrobbler::Love() { object.insert(QStringLiteral("recording_mbid"), song_playing_.musicbrainz_recording_id()); object.insert(QStringLiteral("score"), 1); - QUrl url(QStringLiteral("%1/1/feedback/recording-feedback").arg(kApiUrl)); + QUrl url(QStringLiteral("%1/1/feedback/recording-feedback").arg(QLatin1String(kApiUrl))); QNetworkReply *reply = CreateRequest(url, QJsonDocument(object)); QObject::connect(reply, &QNetworkReply::finished, this, [this, reply]() { LoveRequestFinished(reply); }); diff --git a/src/scrobbler/listenbrainzscrobbler.h b/src/scrobbler/listenbrainzscrobbler.h index 476e0175d3..12773075e0 100644 --- a/src/scrobbler/listenbrainzscrobbler.h +++ b/src/scrobbler/listenbrainzscrobbler.h @@ -101,15 +101,6 @@ class ListenBrainzScrobbler : public ScrobblerService { void StartSubmit(const bool initial = false) override; void CheckScrobblePrevSong(); - static const char *kOAuthAuthorizeUrl; - static const char *kOAuthAccessTokenUrl; - static const char *kOAuthRedirectUrl; - static const char *kApiUrl; - static const char *kClientIDB64; - static const char *kClientSecretB64; - static const char *kCacheFile; - static const int kScrobblesPerRequest; - SharedPtr network_; ScrobblerCache *cache_; LocalRedirectServer *server_; diff --git a/src/scrobbler/scrobblercache.cpp b/src/scrobbler/scrobblercache.cpp index f66d64e937..6057328c81 100644 --- a/src/scrobbler/scrobblercache.cpp +++ b/src/scrobbler/scrobblercache.cpp @@ -47,7 +47,7 @@ using namespace std::chrono_literals; ScrobblerCache::ScrobblerCache(const QString &filename, QObject *parent) : QObject(parent), timer_flush_(new QTimer(this)), - filename_(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/" + filename), + filename_(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/") + filename), loaded_(false) { ReadCache(); diff --git a/src/scrobbler/scrobblersettings.cpp b/src/scrobbler/scrobblersettings.cpp index 835fbf62b4..5a373a4a43 100644 --- a/src/scrobbler/scrobblersettings.cpp +++ b/src/scrobbler/scrobblersettings.cpp @@ -25,6 +25,7 @@ #include "core/application.h" #include "core/song.h" +#include "core/settings.h" #include "settings/settingsdialog.h" #include "settings/scrobblersettingspage.h" #include "scrobblersettings.h" @@ -47,7 +48,7 @@ ScrobblerSettings::ScrobblerSettings(Application *app, QObject *parent) void ScrobblerSettings::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(ScrobblerSettingsPage::kSettingsGroup); enabled_ = s.value("enabled", false).toBool(); offline_ = s.value("offline", false).toBool(); @@ -92,7 +93,7 @@ void ScrobblerSettings::ToggleScrobbling() { bool enabled_old_ = enabled_; enabled_ = !enabled_; - QSettings s; + Settings s; s.beginGroup(ScrobblerSettingsPage::kSettingsGroup); s.setValue("enabled", enabled_); s.endGroup(); @@ -106,7 +107,7 @@ void ScrobblerSettings::ToggleOffline() { bool offline_old_ = offline_; offline_ = !offline_; - QSettings s; + Settings s; s.beginGroup(ScrobblerSettingsPage::kSettingsGroup); s.setValue("offline", offline_); s.endGroup(); diff --git a/src/scrobbler/scrobblingapi20.cpp b/src/scrobbler/scrobblingapi20.cpp index ba959221fe..2c6af2dcd2 100644 --- a/src/scrobbler/scrobblingapi20.cpp +++ b/src/scrobbler/scrobblingapi20.cpp @@ -48,6 +48,7 @@ #include "core/networkaccessmanager.h" #include "core/song.h" #include "core/logging.h" +#include "core/settings.h" #include "utilities/timeconstants.h" #include "internet/localredirectserver.h" #include "settings/scrobblersettingspage.h" @@ -60,8 +61,10 @@ #include "scrobblemetadata.h" const char *ScrobblingAPI20::kApiKey = "211990b4c96782c05d1536e7219eb56e"; -const char *ScrobblingAPI20::kSecret = "80fd738f49596e9709b1bf9319c444a8"; -const int ScrobblingAPI20::kScrobblesPerRequest = 50; +namespace { +constexpr char kSecret[] = "80fd738f49596e9709b1bf9319c444a8"; +constexpr int kScrobblesPerRequest = 50; +} ScrobblingAPI20::ScrobblingAPI20(const QString &name, const QString &settings_group, const QString &auth_url, const QString &api_url, const bool batch, const QString &cache_file, SharedPtr settings, SharedPtr network, QObject *parent) : ScrobblerService(name, settings, parent), @@ -108,7 +111,7 @@ ScrobblingAPI20::~ScrobblingAPI20() { void ScrobblingAPI20::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(settings_group_); enabled_ = s.value("enabled", false).toBool(); @@ -122,7 +125,7 @@ void ScrobblingAPI20::ReloadSettings() { void ScrobblingAPI20::LoadSession() { - QSettings s; + Settings s; s.beginGroup(settings_group_); subscriber_ = s.value("subscriber", false).toBool(); username_ = s.value("username").toString(); @@ -137,7 +140,7 @@ void ScrobblingAPI20::Logout() { username_.clear(); session_key_.clear(); - QSettings settings; + Settings settings; settings.beginGroup(settings_group_); settings.remove("subscriber"); settings.remove("username"); @@ -202,7 +205,7 @@ void ScrobblingAPI20::Authenticate() { } QUrlQuery url_query; - url_query.addQueryItem(QStringLiteral("api_key"), kApiKey); + url_query.addQueryItem(QStringLiteral("api_key"), QLatin1String(kApiKey)); url_query.addQueryItem(QStringLiteral("cb"), server_->url().toString()); QUrl url(auth_url_); url.setQuery(url_query); @@ -246,7 +249,7 @@ void ScrobblingAPI20::RedirectArrived() { if (url.isValid()) { QUrlQuery url_query(url); if (url_query.hasQueryItem(QStringLiteral("token"))) { - QString token = url_query.queryItemValue(QStringLiteral("token")).toUtf8(); + QString token = url_query.queryItemValue(QStringLiteral("token")); RequestSession(token); } else { @@ -271,18 +274,18 @@ void ScrobblingAPI20::RequestSession(const QString &token) { QUrl session_url(api_url_); QUrlQuery session_url_query; - session_url_query.addQueryItem(QStringLiteral("api_key"), kApiKey); + session_url_query.addQueryItem(QStringLiteral("api_key"), QLatin1String(kApiKey)); session_url_query.addQueryItem(QStringLiteral("method"), QStringLiteral("auth.getSession")); session_url_query.addQueryItem(QStringLiteral("token"), token); QString data_to_sign; for (const Param ¶m : session_url_query.queryItems()) { data_to_sign += param.first + param.second; } - data_to_sign += kSecret; + data_to_sign += QString::fromUtf8(kSecret); QByteArray const digest = QCryptographicHash::hash(data_to_sign.toUtf8(), QCryptographicHash::Md5); - QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, '0').toLower(); + const QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, QLatin1Char('0')).toLower(); session_url_query.addQueryItem(QStringLiteral("api_sig"), signature); - session_url_query.addQueryItem(QUrl::toPercentEncoding(QStringLiteral("format")), QUrl::toPercentEncoding(QStringLiteral("json"))); + session_url_query.addQueryItem(QString::fromUtf8(QUrl::toPercentEncoding(QStringLiteral("format"))), QString::fromUtf8(QUrl::toPercentEncoding(QStringLiteral("json")))); session_url.setQuery(session_url_query); QNetworkRequest req(session_url); @@ -331,7 +334,7 @@ void ScrobblingAPI20::AuthenticateReplyFinished(QNetworkReply *reply) { username_ = json_obj[QStringLiteral("name")].toString(); session_key_ = json_obj[QStringLiteral("key")].toString(); - QSettings s; + Settings s; s.beginGroup(settings_group_); s.setValue("subscriber", subscriber_); s.setValue("username", username_); @@ -347,9 +350,9 @@ void ScrobblingAPI20::AuthenticateReplyFinished(QNetworkReply *reply) { QNetworkReply *ScrobblingAPI20::CreateRequest(const ParamList &request_params) { ParamList params = ParamList() - << Param("api_key", kApiKey) - << Param("sk", session_key_) - << Param("lang", QLocale().name().left(2).toLower()) + << Param(QStringLiteral("api_key"), QLatin1String(kApiKey)) + << Param(QStringLiteral("sk"), session_key_) + << Param(QStringLiteral("lang"), QLocale().name().left(2).toLower()) << request_params; std::sort(params.begin(), params.end()); @@ -358,21 +361,21 @@ QNetworkReply *ScrobblingAPI20::CreateRequest(const ParamList &request_params) { QString data_to_sign; for (const Param ¶m : params) { EncodedParam encoded_param(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); - url_query.addQueryItem(encoded_param.first, encoded_param.second); + url_query.addQueryItem(QString::fromUtf8(encoded_param.first), QString::fromUtf8(encoded_param.second)); data_to_sign += param.first + param.second; } - data_to_sign += kSecret; + data_to_sign += QString::fromUtf8(kSecret); QByteArray const digest = QCryptographicHash::hash(data_to_sign.toUtf8(), QCryptographicHash::Md5); - QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, '0').toLower(); + const QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, QLatin1Char('0')).toLower(); - url_query.addQueryItem(QStringLiteral("api_sig"), QUrl::toPercentEncoding(signature)); - url_query.addQueryItem(QStringLiteral("format"), QUrl::toPercentEncoding(QStringLiteral("json"))); + url_query.addQueryItem(QStringLiteral("api_sig"), QString::fromUtf8(QUrl::toPercentEncoding(signature))); + url_query.addQueryItem(QStringLiteral("format"), QStringLiteral("json")); QUrl url(api_url_); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8(); QNetworkReply *reply = network_->post(req, query); replies_ << reply; @@ -394,16 +397,16 @@ void ScrobblingAPI20::UpdateNowPlaying(const Song &song) { if (!authenticated() || !song.is_metadata_good() || settings_->offline()) return; ParamList params = ParamList() - << Param("method", "track.updateNowPlaying") - << Param("artist", prefer_albumartist_ ? song.effective_albumartist() : song.artist()) - << Param("track", StripTitle(song.title())); + << Param(QStringLiteral("method"), QStringLiteral("track.updateNowPlaying")) + << Param(QStringLiteral("artist"), prefer_albumartist_ ? song.effective_albumartist() : song.artist()) + << Param(QStringLiteral("track"), StripTitle(song.title())); if (!song.album().isEmpty()) { - params << Param("album", StripAlbum(song.album())); + params << Param(QStringLiteral("album"), StripAlbum(song.album())); } if (!prefer_albumartist_ && !song.albumartist().isEmpty()) { - params << Param("albumArtist", song.albumartist()); + params << Param(QStringLiteral("albumArtist"), song.albumartist()); } QNetworkReply *reply = CreateRequest(params); @@ -486,7 +489,7 @@ void ScrobblingAPI20::Submit() { qLog(Debug) << name_ << "Submitting scrobbles."; - ParamList params = ParamList() << Param("method", "track.scrobble"); + ParamList params = ParamList() << Param(QStringLiteral("method"), QStringLiteral("track.scrobble")); int i = 0; ScrobblerCacheItemPtrList all_cache_items = cache_->List(); @@ -688,20 +691,20 @@ void ScrobblingAPI20::ScrobbleRequestFinished(QNetworkReply *reply, ScrobblerCac void ScrobblingAPI20::SendSingleScrobble(ScrobblerCacheItemPtr item) { ParamList params = ParamList() - << Param("method", "track.scrobble") - << Param("artist", prefer_albumartist_ ? item->metadata.effective_albumartist() : item->metadata.artist) - << Param("track", StripTitle(item->metadata.title)) - << Param("timestamp", QString::number(item->timestamp)) - << Param("duration", QString::number(item->metadata.length_nanosec / kNsecPerSec)); + << Param(QStringLiteral("method"), QStringLiteral("track.scrobble")) + << Param(QStringLiteral("artist"), prefer_albumartist_ ? item->metadata.effective_albumartist() : item->metadata.artist) + << Param(QStringLiteral("track"), StripTitle(item->metadata.title)) + << Param(QStringLiteral("timestamp"), QString::number(item->timestamp)) + << Param(QStringLiteral("duration"), QString::number(item->metadata.length_nanosec / kNsecPerSec)); if (!item->metadata.album.isEmpty()) { - params << Param("album", StripAlbum(item->metadata.album)); + params << Param(QStringLiteral("album"), StripAlbum(item->metadata.album)); } if (!prefer_albumartist_ && !item->metadata.albumartist.isEmpty()) { - params << Param("albumArtist", item->metadata.albumartist); + params << Param(QStringLiteral("albumArtist"), item->metadata.albumartist); } if (item->metadata.track > 0) { - params << Param("trackNumber", QString::number(item->metadata.track)); + params << Param(QStringLiteral("trackNumber"), QString::number(item->metadata.track)); } QNetworkReply *reply = CreateRequest(params); @@ -825,16 +828,16 @@ void ScrobblingAPI20::Love() { qLog(Debug) << name_ << "Sending love for song" << song_playing_.artist() << song_playing_.album() << song_playing_.title(); ParamList params = ParamList() - << Param("method", "track.love") - << Param("artist", prefer_albumartist_ ? song_playing_.effective_albumartist() : song_playing_.artist()) - << Param("track", song_playing_.title()); + << Param(QStringLiteral("method"), QStringLiteral("track.love")) + << Param(QStringLiteral("artist"), prefer_albumartist_ ? song_playing_.effective_albumartist() : song_playing_.artist()) + << Param(QStringLiteral("track"), song_playing_.title()); if (!song_playing_.album().isEmpty()) { - params << Param("album", song_playing_.album()); + params << Param(QStringLiteral("album"), song_playing_.album()); } if (!prefer_albumartist_ && !song_playing_.albumartist().isEmpty()) { - params << Param("albumArtist", song_playing_.albumartist()); + params << Param(QStringLiteral("albumArtist"), song_playing_.albumartist()); } QNetworkReply *reply = CreateRequest(params); diff --git a/src/scrobbler/scrobblingapi20.h b/src/scrobbler/scrobblingapi20.h index a09d85f7e8..a993c82f2e 100644 --- a/src/scrobbler/scrobblingapi20.h +++ b/src/scrobbler/scrobblingapi20.h @@ -120,9 +120,6 @@ class ScrobblingAPI20 : public ScrobblerService { RateLimitExceeded = 29, }; - static const char *kSecret; - static const int kScrobblesPerRequest; - QNetworkReply *CreateRequest(const ParamList &request_params); ReplyResult GetJsonObject(QNetworkReply *reply, QJsonObject &json_obj, QString &error_description); diff --git a/src/scrobbler/subsonicscrobbler.cpp b/src/scrobbler/subsonicscrobbler.cpp index 89b5218d6d..cca5b3f1f9 100644 --- a/src/scrobbler/subsonicscrobbler.cpp +++ b/src/scrobbler/subsonicscrobbler.cpp @@ -43,7 +43,7 @@ const char *SubsonicScrobbler::kName = "Subsonic"; SubsonicScrobbler::SubsonicScrobbler(SharedPtr settings, Application *app, QObject *parent) - : ScrobblerService(kName, settings, parent), + : ScrobblerService(QLatin1String(kName), settings, parent), app_(app), service_(nullptr), enabled_(false), @@ -58,7 +58,7 @@ SubsonicScrobbler::SubsonicScrobbler(SharedPtr settings, Appl void SubsonicScrobbler::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(SubsonicSettingsPage::kSettingsGroup); enabled_ = s.value("serversidescrobbling", false).toBool(); s.endGroup(); diff --git a/src/settings/appearancesettingspage.cpp b/src/settings/appearancesettingspage.cpp index 960c3af0d4..156645b84d 100644 --- a/src/settings/appearancesettingspage.cpp +++ b/src/settings/appearancesettingspage.cpp @@ -44,6 +44,7 @@ #include "utilities/colorutils.h" #include "core/iconloader.h" #include "core/stylehelper.h" +#include "core/settings.h" #include "covermanager/albumcoverchoicecontroller.h" #include "settingspage.h" #include "settingsdialog.h" @@ -89,7 +90,7 @@ AppearanceSettingsPage::AppearanceSettingsPage(SettingsDialog *dialog, QWidget * ui_->setupUi(this); setWindowIcon(IconLoader::Load(QStringLiteral("view-media-visualization"), true, 0, 32)); - ui_->combobox_style->addItem(QStringLiteral("default"), "default"); + ui_->combobox_style->addItem(QStringLiteral("default"), QStringLiteral("default")); for (const QString &style : QStyleFactory::keys()) { ui_->combobox_style->addItem(style, style); } @@ -139,10 +140,10 @@ AppearanceSettingsPage::~AppearanceSettingsPage() { void AppearanceSettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); - ComboBoxLoadFromSettings(s, ui_->combobox_style, kStyle, QStringLiteral("default")); + ComboBoxLoadFromSettings(s, ui_->combobox_style, QLatin1String(kStyle), QStringLiteral("default")); #if !defined(Q_OS_MACOS) && !defined(Q_OS_WIN) ui_->checkbox_system_icons->setChecked(s.value(kSystemThemeIcons, false).toBool()); @@ -215,13 +216,13 @@ void AppearanceSettingsPage::Load() { Init(ui_->layout_appearancesettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void AppearanceSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("style", ui_->combobox_style->currentText()); @@ -297,7 +298,7 @@ void AppearanceSettingsPage::UpdateColorSelectorColor(QWidget *color_selector, c void AppearanceSettingsPage::SelectBackgroundImage() { - QString selected_filename = QFileDialog::getOpenFileName(this, tr("Select background image"), background_image_filename_, tr(AlbumCoverChoiceController::kLoadImageFileFilter) + ";;" + tr(AlbumCoverChoiceController::kAllFilesFilter)); + QString selected_filename = QFileDialog::getOpenFileName(this, tr("Select background image"), background_image_filename_, tr(AlbumCoverChoiceController::kLoadImageFileFilter) + QStringLiteral(";;") + tr(AlbumCoverChoiceController::kAllFilesFilter)); if (selected_filename.isEmpty()) return; background_image_filename_ = selected_filename; ui_->background_image_filename->setText(background_image_filename_); diff --git a/src/settings/backendsettingspage.cpp b/src/settings/backendsettingspage.cpp index 3197fff7ac..f113443134 100644 --- a/src/settings/backendsettingspage.cpp +++ b/src/settings/backendsettingspage.cpp @@ -43,6 +43,7 @@ #include "core/iconloader.h" #include "core/player.h" #include "core/logging.h" +#include "core/settings.h" #include "engine/enginebase.h" #include "engine/enginedevice.h" #include "engine/devicefinders.h" @@ -55,12 +56,15 @@ #include "ui_backendsettingspage.h" const char *BackendSettingsPage::kSettingsGroup = "Backend"; -const char *BackendSettingsPage::kOutputAutomaticallySelect = "Automatically select"; -const char *BackendSettingsPage::kOutputCustom = "Custom"; const qint64 BackendSettingsPage::kDefaultBufferDuration = 4000; const double BackendSettingsPage::kDefaultBufferLowWatermark = 0.33; const double BackendSettingsPage::kDefaultBufferHighWatermark = 0.99; +namespace { +static constexpr char kOutputAutomaticallySelect[] = "Automatically select"; +static constexpr char kOutputCustom[] = "Custom"; +} // namespace + BackendSettingsPage::BackendSettingsPage(SettingsDialog *dialog, QWidget *parent) : SettingsPage(dialog, parent), ui_(new Ui_BackendSettingsPage), @@ -115,7 +119,7 @@ void BackendSettingsPage::Load() { configloaded_ = false; engineloaded_ = false; - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); EngineBase::Type enginetype = EngineBase::TypeFromName(s.value("engine", EngineBase::Name(EngineBase::Type::None)).toString()); @@ -226,7 +230,7 @@ void BackendSettingsPage::Load() { #endif Init(ui_->layout_backendsettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); // Check if engine, output or device is set to a different setting than the configured to force saving settings. @@ -241,7 +245,7 @@ void BackendSettingsPage::Load() { } QVariant device_value; if (ui_->combobox_device->currentText().isEmpty()) device_value = QVariant(); - else if (ui_->combobox_device->currentText() == kOutputCustom) device_value = ui_->lineedit_device->text(); + else if (ui_->combobox_device->currentText() == QLatin1String(kOutputCustom)) device_value = ui_->lineedit_device->text(); else device_value = ui_->combobox_device->itemData(ui_->combobox_device->currentIndex()).value(); if (enginetype_current_ != enginetype || output_name != output_current_ || device_value != device_current_) { @@ -364,7 +368,7 @@ void BackendSettingsPage::Load_Device(const QString &output, const QVariant &dev #ifdef Q_OS_WIN if (engine()->type() != EngineBase::Type::GStreamer) #endif - ui_->combobox_device->addItem(IconLoader::Load(QStringLiteral("soundcard")), kOutputAutomaticallySelect, QVariant()); + ui_->combobox_device->addItem(IconLoader::Load(QStringLiteral("soundcard")), QLatin1String(kOutputAutomaticallySelect), QVariant()); for (DeviceFinder *f : dialog()->app()->device_finders()->ListFinders()) { if (!f->outputs().contains(output)) continue; @@ -376,7 +380,7 @@ void BackendSettingsPage::Load_Device(const QString &output, const QVariant &dev } if (engine()->CustomDeviceSupport(output)) { - ui_->combobox_device->addItem(IconLoader::Load(QStringLiteral("soundcard")), kOutputCustom, QVariant()); + ui_->combobox_device->addItem(IconLoader::Load(QStringLiteral("soundcard")), QLatin1String(kOutputCustom), QVariant()); ui_->lineedit_device->setEnabled(true); } else { @@ -446,8 +450,8 @@ void BackendSettingsPage::Load_Device(const QString &output, const QVariant &dev ui_->lineedit_device->setText(device.toString()); if (!found) { for (int i = 0; i < ui_->combobox_device->count(); ++i) { - if (ui_->combobox_device->itemText(i) == kOutputCustom) { - if (ui_->combobox_device->currentText() != kOutputCustom) ui_->combobox_device->setCurrentIndex(i); + if (ui_->combobox_device->itemText(i) == QLatin1String(kOutputCustom)) { + if (ui_->combobox_device->currentText() != QLatin1String(kOutputCustom)) ui_->combobox_device->setCurrentIndex(i); break; } } @@ -478,10 +482,10 @@ void BackendSettingsPage::Save() { } if (ui_->combobox_device->currentText().isEmpty()) device_value = QVariant(); - else if (ui_->combobox_device->currentText() == kOutputCustom) device_value = ui_->lineedit_device->text(); + else if (ui_->combobox_device->currentText() == QLatin1String(kOutputCustom)) device_value = ui_->lineedit_device->text(); else device_value = ui_->combobox_device->itemData(ui_->combobox_device->currentIndex()).value(); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("engine", EngineBase::Name(enginetype)); @@ -586,7 +590,7 @@ void BackendSettingsPage::DeviceSelectionChanged(int index) { if (engine()->CustomDeviceSupport(output.name)) { ui_->lineedit_device->setEnabled(true); - if (ui_->combobox_device->currentText() != kOutputCustom) { + if (ui_->combobox_device->currentText() != QLatin1String(kOutputCustom)) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) if (device.metaType().id() == QMetaType::QString) #else @@ -638,7 +642,7 @@ void BackendSettingsPage::DeviceStringChanged() { #endif QString device_str = device.toString(); if (device_str.isEmpty()) continue; - if (ui_->combobox_device->itemText(i) == kOutputCustom) continue; + if (ui_->combobox_device->itemText(i) == QLatin1String(kOutputCustom)) continue; if (device_str == ui_->lineedit_device->text()) { if (ui_->combobox_device->currentIndex() != i) ui_->combobox_device->setCurrentIndex(i); found = true; @@ -647,15 +651,15 @@ void BackendSettingsPage::DeviceStringChanged() { if (engine()->CustomDeviceSupport(output.name)) { ui_->lineedit_device->setEnabled(true); - if ((!found) && (ui_->combobox_device->currentText() != kOutputCustom)) { + if ((!found) && (ui_->combobox_device->currentText() != QLatin1String(kOutputCustom))) { for (int i = 0; i < ui_->combobox_device->count(); ++i) { - if (ui_->combobox_device->itemText(i) == kOutputCustom) { + if (ui_->combobox_device->itemText(i) == QLatin1String(kOutputCustom)) { ui_->combobox_device->setCurrentIndex(i); break; } } } - if (ui_->combobox_device->currentText() == kOutputCustom) { + if (ui_->combobox_device->currentText() == QLatin1String(kOutputCustom)) { if ((ui_->lineedit_device->text().isEmpty()) && (ui_->combobox_device->count() > 0) && (ui_->combobox_device->currentIndex() != 0)) ui_->combobox_device->setCurrentIndex(0); } } @@ -806,7 +810,7 @@ void BackendSettingsPage::SelectDevice(const QString &device_new) { if (device_new.isEmpty()) { for (int i = 0; i < ui_->combobox_device->count(); ++i) { - if (ui_->combobox_device->itemText(i) == kOutputAutomaticallySelect && ui_->combobox_device->currentIndex() != i) { + if (ui_->combobox_device->itemText(i) == QLatin1String(kOutputAutomaticallySelect) && ui_->combobox_device->currentIndex() != i) { ui_->combobox_device->setCurrentIndex(i); break; } @@ -833,7 +837,7 @@ void BackendSettingsPage::SelectDevice(const QString &device_new) { if (!found) { ui_->lineedit_device->setText(device_new); for (int i = 0; i < ui_->combobox_device->count(); ++i) { - if (ui_->combobox_device->itemText(i) == kOutputCustom && ui_->combobox_device->currentIndex() != i) { + if (ui_->combobox_device->itemText(i) == QLatin1String(kOutputCustom) && ui_->combobox_device->currentIndex() != i) { ui_->combobox_device->setCurrentIndex(i); break; } diff --git a/src/settings/backendsettingspage.h b/src/settings/backendsettingspage.h index a04580f99a..12ff152c4a 100644 --- a/src/settings/backendsettingspage.h +++ b/src/settings/backendsettingspage.h @@ -91,9 +91,6 @@ class BackendSettingsPage : public SettingsPage { void SelectDevice(const QString &device_new); private: - static const char *kOutputAutomaticallySelect; - static const char *kOutputCustom; - Ui_BackendSettingsPage *ui_; bool configloaded_; bool engineloaded_; diff --git a/src/settings/behavioursettingspage.cpp b/src/settings/behavioursettingspage.cpp index 8256adcb5e..dc56e2a867 100644 --- a/src/settings/behavioursettingspage.cpp +++ b/src/settings/behavioursettingspage.cpp @@ -40,6 +40,7 @@ #include "core/iconloader.h" #include "core/mainwindow.h" +#include "core/settings.h" #include "settings/settingspage.h" #include "behavioursettingspage.h" #include "ui_behavioursettingspage.h" @@ -77,13 +78,13 @@ BehaviourSettingsPage::BehaviourSettingsPage(SettingsDialog *dialog, QWidget *pa #ifdef HAVE_TRANSLATIONS // Populate the language combo box. We do this by looking at all the compiled in translations. - QDir dir1(":/translations/"); - QDir dir2(TRANSLATIONS_DIR); - QStringList codes(dir1.entryList(QStringList() << "*.qm")); + QDir dir1(QStringLiteral(":/translations/")); + QDir dir2(QStringLiteral(TRANSLATIONS_DIR)); + QStringList codes(dir1.entryList(QStringList() << QStringLiteral("*.qm"))); if (dir2.exists()) { - codes << dir2.entryList(QStringList() << "*.qm"); + codes << dir2.entryList(QStringList() << QStringLiteral("*.qm")); } - QRegularExpression lang_re("^strawberry_(.*).qm$"); + QRegularExpression lang_re(QStringLiteral("^strawberry_(.*).qm$")); for (const QString &filename : codes) { QRegularExpressionMatch re_match = lang_re.match(filename); @@ -93,21 +94,21 @@ BehaviourSettingsPage::BehaviourSettingsPage(SettingsDialog *dialog, QWidget *pa QString code = re_match.captured(1); QString lookup_code = QString(code) - .replace("@latin", "_Latn") - .replace("_CN", "_Hans_CN") - .replace("_TW", "_Hant_TW"); + .replace(QStringLiteral("@latin"), QStringLiteral("_Latn")) + .replace(QStringLiteral("_CN"), QStringLiteral("_Hans_CN")) + .replace(QStringLiteral("_TW"), QStringLiteral("_Hant_TW")); QString language_name = QLocale::languageToString(QLocale(lookup_code).language()); QString native_name = QLocale(lookup_code).nativeLanguageName(); if (!native_name.isEmpty()) { language_name = native_name; } - QString name = QString("%1 (%2)").arg(language_name, code); + QString name = QStringLiteral("%1 (%2)").arg(language_name, code); language_map_[name] = code; } - language_map_["English (en)"] = "en"; + language_map_[QStringLiteral("English (en)")] = QStringLiteral("en"); // Sort the names and show them in the UI QStringList names = language_map_.keys(); @@ -145,7 +146,7 @@ BehaviourSettingsPage::~BehaviourSettingsPage() { void BehaviourSettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); #ifdef Q_OS_MACOS @@ -217,13 +218,13 @@ void BehaviourSettingsPage::Load() { Init(ui_->layout_behavioursettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void BehaviourSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("showtrayicon", ui_->checkbox_showtrayicon->isChecked()); diff --git a/src/settings/collectionsettingspage.cpp b/src/settings/collectionsettingspage.cpp index 24bfca50e1..42ce7dcc9b 100644 --- a/src/settings/collectionsettingspage.cpp +++ b/src/settings/collectionsettingspage.cpp @@ -43,6 +43,7 @@ #include "core/application.h" #include "core/iconloader.h" +#include "core/settings.h" #include "utilities/strutils.h" #include "utilities/timeutils.h" #include "collection/collection.h" @@ -112,7 +113,7 @@ CollectionSettingsPage::~CollectionSettingsPage() { delete ui_; } void CollectionSettingsPage::Add() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); QString path(s.value("last_path", QStandardPaths::writableLocation(QStandardPaths::MusicLocation)).toString()); @@ -173,7 +174,7 @@ void CollectionSettingsPage::Load() { QObject::connect(ui_->list->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &CollectionSettingsPage::CurrentRowChanged); } - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); ui_->auto_open->setChecked(s.value("auto_open", true).toBool()); @@ -215,13 +216,13 @@ void CollectionSettingsPage::Load() { ui_->disk_cache_in_use->setText((dialog()->app()->collection_model()->icon_cache_disk_size() == 0 ? QStringLiteral("empty") : Utilities::PrettySize(dialog()->app()->collection_model()->icon_cache_disk_size()))); Init(ui_->layout_collectionsettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void CollectionSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("auto_open", ui_->auto_open->isChecked()); @@ -238,9 +239,9 @@ void CollectionSettingsPage::Save() { QString filter_text = ui_->cover_art_patterns->text(); #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QStringList filters = filter_text.split(',', Qt::SkipEmptyParts); + QStringList filters = filter_text.split(QLatin1Char(','), Qt::SkipEmptyParts); #else - QStringList filters = filter_text.split(',', QString::SkipEmptyParts); + QStringList filters = filter_text.split(QLatin1Char(','), QString::SkipEmptyParts); #endif s.setValue("cover_art_patterns", filters); diff --git a/src/settings/contextsettingspage.cpp b/src/settings/contextsettingspage.cpp index 35156eca9f..622426144f 100644 --- a/src/settings/contextsettingspage.cpp +++ b/src/settings/contextsettingspage.cpp @@ -38,6 +38,7 @@ #include "core/iconloader.h" #include "core/mainwindow.h" +#include "core/settings.h" #include "settingspage.h" #include "settingsdialog.h" #include "contextsettingspage.h" @@ -113,7 +114,7 @@ ContextSettingsPage::ContextSettingsPage(SettingsDialog *dialog, QWidget *parent QFile file(QStringLiteral(":/text/ghosts.txt")); if (file.open(QIODevice::ReadOnly)) { - QString text = file.readAll(); + QString text = QString::fromUtf8(file.readAll()); ui_->preview_headline->setText(text); ui_->preview_normal->setText(text); file.close(); @@ -128,11 +129,11 @@ ContextSettingsPage::~ContextSettingsPage() { delete ui_; } void ContextSettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); - ui_->context_custom_text1->setText(s.value(kSettingsTitleFmt, "%title% - %artist%").toString()); - ui_->context_custom_text2->setText(s.value(kSettingsSummaryFmt, "%album%").toString()); + ui_->context_custom_text1->setText(s.value(kSettingsTitleFmt, QStringLiteral("%title% - %artist%")).toString()); + ui_->context_custom_text2->setText(s.value(kSettingsSummaryFmt, QStringLiteral("%album%")).toString()); for (int i = 0; i < static_cast(ContextSettingsOrder::NELEMS); ++i) { checkboxes_[i]->setChecked(s.value(kSettingsGroupEnable[i], checkboxes_[i]->isChecked()).toBool()); @@ -140,9 +141,9 @@ void ContextSettingsPage::Load() { // Fonts QString default_font; - int i = ui_->font_headline->findText(kDefaultFontFamily); + int i = ui_->font_headline->findText(QLatin1String(kDefaultFontFamily)); if (i >= 0) { - default_font = kDefaultFontFamily; + default_font = QLatin1String(kDefaultFontFamily); } else { default_font = font().family(); @@ -160,13 +161,13 @@ void ContextSettingsPage::Load() { Init(ui_->layout_contextsettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void ContextSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue(kSettingsTitleFmt, ui_->context_custom_text1->text()); diff --git a/src/settings/coverssettingspage.cpp b/src/settings/coverssettingspage.cpp index ab4442c92d..ae68a4c256 100644 --- a/src/settings/coverssettingspage.cpp +++ b/src/settings/coverssettingspage.cpp @@ -39,6 +39,7 @@ #include "ui_coverssettingspage.h" #include "core/application.h" #include "core/iconloader.h" +#include "core/settings.h" #include "utilities/coveroptions.h" #include "covermanager/coverproviders.h" #include "covermanager/coverprovider.h" @@ -107,7 +108,7 @@ void CoversSettingsPage::Load() { item->setForeground(provider->is_enabled() ? palette().color(QPalette::Active, QPalette::Text) : palette().color(QPalette::Disabled, QPalette::Text)); } - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); const QStringList all_types = QStringList() << QStringLiteral("art_unset") @@ -160,13 +161,13 @@ void CoversSettingsPage::Load() { Init(ui_->layout_coverssettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void CoversSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); QStringList providers; @@ -220,11 +221,11 @@ void CoversSettingsPage::ProvidersCurrentItemChanged(QListWidgetItem *item_curre CoverProvider *provider = dialog()->app()->cover_providers()->ProviderByName(item_current->text()); if (provider) { if (provider->AuthenticationRequired()) { - if (provider->name() == "Tidal" && !provider->IsAuthenticated()) { + if (provider->name() == QStringLiteral("Tidal") && !provider->IsAuthenticated()) { DisableAuthentication(); ui_->label_auth_info->setText(tr("Use Tidal settings to authenticate.")); } - else if (provider->name() == "Qobuz" && !provider->IsAuthenticated()) { + else if (provider->name() == QStringLiteral("Qobuz") && !provider->IsAuthenticated()) { DisableAuthentication(); ui_->label_auth_info->setText(tr("Use Qobuz settings to authenticate.")); } @@ -333,11 +334,11 @@ void CoversSettingsPage::LogoutClicked() { if (!provider) return; provider->Deauthenticate(); - if (provider->name() == "Tidal") { + if (provider->name() == QStringLiteral("Tidal")) { DisableAuthentication(); ui_->label_auth_info->setText(tr("Use Tidal settings to authenticate.")); } - else if (provider->name() == "Qobuz") { + else if (provider->name() == QStringLiteral("Qobuz")) { DisableAuthentication(); ui_->label_auth_info->setText(tr("Use Qobuz settings to authenticate.")); } @@ -419,16 +420,16 @@ void CoversSettingsPage::AddAlbumCoverArtType(const QString &name, const QString QString CoversSettingsPage::AlbumCoverArtTypeDescription(const QString &type) const { - if (type == "art_unset") { + if (type == QStringLiteral("art_unset")) { return tr("Manually unset (%1)").arg(type); } - if (type == "art_manual") { + if (type == QStringLiteral("art_manual")) { return tr("Set through album cover search (%1)").arg(type); } - if (type == "art_automatic") { + if (type == QStringLiteral("art_automatic")) { return tr("Automatically picked up from album directory (%1)").arg(type); } - if (type == "art_embedded") { + if (type == QStringLiteral("art_embedded")) { return tr("Embedded album cover art (%1)").arg(type); } diff --git a/src/settings/globalshortcutssettingspage.cpp b/src/settings/globalshortcutssettingspage.cpp index e660b57516..a5a12eb16e 100644 --- a/src/settings/globalshortcutssettingspage.cpp +++ b/src/settings/globalshortcutssettingspage.cpp @@ -40,6 +40,7 @@ #include "core/iconloader.h" #include "core/logging.h" +#include "core/settings.h" #include "utilities/envutils.h" #include "globalshortcuts/globalshortcutgrabber.h" #include "globalshortcuts/globalshortcutsmanager.h" @@ -95,7 +96,7 @@ GlobalShortcutsSettingsPage::~GlobalShortcutsSettingsPage() { delete ui_; } void GlobalShortcutsSettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); GlobalShortcutsManager *manager = dialog()->global_shortcuts_manager(); @@ -205,13 +206,13 @@ void GlobalShortcutsSettingsPage::Load() { Init(ui_->layout_globalshortcutssettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void GlobalShortcutsSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); QList shortcuts = shortcuts_.values(); @@ -344,18 +345,18 @@ void GlobalShortcutsSettingsPage::ChangeClicked() { void GlobalShortcutsSettingsPage::X11Warning() { QString de = de_.toLower(); - if (de == "kde" || de == "gnome" || de == "x-cinnamon" || de == "mate") { + if (de == QStringLiteral("kde") || de == QStringLiteral("gnome") || de == QStringLiteral("x-cinnamon") || de == QStringLiteral("mate")) { QString text(tr("Using X11 shortcuts on %1 is not recommended and can cause keyboard to become unresponsive!").arg(de_)); - if (de == "kde") { + if (de == QStringLiteral("kde")) { text += tr(" Shortcuts on %1 are usually used through MPRIS and KGlobalAccel.").arg(de_); } - else if (de == "gnome") { + else if (de == QStringLiteral("gnome")) { text += tr(" Shortcuts on %1 are usually used through Gnome Settings Daemon and should be configured in gnome-settings-daemon instead.").arg(de_); } - else if (de == "x-cinnamon") { + else if (de == QStringLiteral("x-cinnamon")) { text += tr(" Shortcuts on %1 are usually used through Gnome Settings Daemon and should be configured in cinnamon-settings-daemon instead.").arg(de_); } - else if (de == "mate") { + else if (de == QStringLiteral("mate")) { text += tr(" Shortcuts on %1 are usually used through MATE Settings Daemon and should be configured there instead.").arg(de_); } ui_->label_warn_text->setText(text); diff --git a/src/settings/globalshortcutssettingspage.h b/src/settings/globalshortcutssettingspage.h index 749efcfb36..620ae22525 100644 --- a/src/settings/globalshortcutssettingspage.h +++ b/src/settings/globalshortcutssettingspage.h @@ -25,7 +25,6 @@ #include "config.h" #include -#include #include #include #include diff --git a/src/settings/lyricssettingspage.cpp b/src/settings/lyricssettingspage.cpp index 78dfc2a2b8..b19669bdc4 100644 --- a/src/settings/lyricssettingspage.cpp +++ b/src/settings/lyricssettingspage.cpp @@ -39,6 +39,7 @@ #include "ui_lyricssettingspage.h" #include "core/application.h" #include "core/iconloader.h" +#include "core/settings.h" #include "lyrics/lyricsproviders.h" #include "lyrics/lyricsprovider.h" #include "widgets/loginstatewidget.h" @@ -89,7 +90,7 @@ void LyricsSettingsPage::Load() { Init(ui_->layout_lyricssettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } @@ -101,7 +102,7 @@ void LyricsSettingsPage::Save() { if (item->checkState() == Qt::Checked) providers << item->text(); // clazy:exclude=reserve-candidates } - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("providers", providers); s.endGroup(); diff --git a/src/settings/moodbarsettingspage.cpp b/src/settings/moodbarsettingspage.cpp index ad7f275ea4..3712e00919 100644 --- a/src/settings/moodbarsettingspage.cpp +++ b/src/settings/moodbarsettingspage.cpp @@ -33,6 +33,7 @@ #include "core/iconloader.h" #include "core/logging.h" +#include "core/settings.h" #include "settingsdialog.h" #include "settingspage.h" @@ -64,7 +65,7 @@ MoodbarSettingsPage::~MoodbarSettingsPage() { delete ui_; } void MoodbarSettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); ui_->moodbar_enabled->setChecked(s.value("enabled", false).toBool()); ui_->moodbar_show->setChecked(s.value("show", false).toBool()); @@ -76,13 +77,13 @@ void MoodbarSettingsPage::Load() { Init(ui_->layout_moodbarsettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void MoodbarSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("enabled", ui_->moodbar_enabled->isChecked()); s.setValue("show", ui_->moodbar_show->isChecked()); diff --git a/src/settings/networkproxysettingspage.cpp b/src/settings/networkproxysettingspage.cpp index b0e32b79e9..a648732dad 100644 --- a/src/settings/networkproxysettingspage.cpp +++ b/src/settings/networkproxysettingspage.cpp @@ -32,6 +32,7 @@ #include "core/iconloader.h" #include "core/networkproxyfactory.h" +#include "core/settings.h" #include "networkproxysettingspage.h" #include "settings/settingspage.h" #include "ui_networkproxysettingspage.h" @@ -53,7 +54,7 @@ NetworkProxySettingsPage::~NetworkProxySettingsPage() { delete ui_; } void NetworkProxySettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(NetworkProxyFactory::kSettingsGroup); const NetworkProxyFactory::Mode mode = static_cast(s.value("mode", static_cast(NetworkProxyFactory::Mode::System)).toInt()); @@ -82,13 +83,13 @@ void NetworkProxySettingsPage::Load() { Init(ui_->layout_networkproxysettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void NetworkProxySettingsPage::Save() { - QSettings s; + Settings s; NetworkProxyFactory::Mode mode = NetworkProxyFactory::Mode::System; if (ui_->proxy_direct->isChecked()) mode = NetworkProxyFactory::Mode::Direct; diff --git a/src/settings/notificationssettingspage.cpp b/src/settings/notificationssettingspage.cpp index 6762f617d3..0ef9dd3bf0 100644 --- a/src/settings/notificationssettingspage.cpp +++ b/src/settings/notificationssettingspage.cpp @@ -46,6 +46,7 @@ #include #include "core/iconloader.h" +#include "core/settings.h" #include "osd/osdbase.h" #include "osd/osdpretty.h" #include "settingspage.h" @@ -151,7 +152,7 @@ void NotificationsSettingsPage::hideEvent(QHideEvent*) { void NotificationsSettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(OSDBase::kSettingsGroup); const OSDBase::Behaviour osd_behaviour = static_cast(s.value("Behaviour", static_cast(OSDBase::Behaviour::Native)).toInt()); @@ -221,13 +222,13 @@ void NotificationsSettingsPage::Load() { Init(ui_->layout_notificationssettingspage->parentWidget()); - if (!QSettings().childGroups().contains(OSDBase::kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(OSDBase::kSettingsGroup))) set_changed(); } void NotificationsSettingsPage::Save() { - QSettings s; + Settings s; OSDBase::Behaviour osd_behaviour = OSDBase::Behaviour::Disabled; if (ui_->notifications_none->isChecked()) osd_behaviour = OSDBase::Behaviour::Disabled; diff --git a/src/settings/playlistsettingspage.cpp b/src/settings/playlistsettingspage.cpp index df8389d457..80c27dc814 100644 --- a/src/settings/playlistsettingspage.cpp +++ b/src/settings/playlistsettingspage.cpp @@ -27,6 +27,7 @@ #include #include "core/iconloader.h" +#include "core/settings.h" #include "playlist/playlist.h" #include "settingspage.h" #include "playlistsettingspage.h" @@ -51,7 +52,7 @@ PlaylistSettingsPage::~PlaylistSettingsPage() { void PlaylistSettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); ui_->checkbox_alternating_row_colors->setChecked(s.value("alternating_row_colors", true).toBool()); @@ -105,7 +106,7 @@ void PlaylistSettingsPage::Load() { Init(ui_->layout_playlistsettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } @@ -125,7 +126,7 @@ void PlaylistSettingsPage::Save() { path_type = PathType::Ask_User; } - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("alternating_row_colors", ui_->checkbox_alternating_row_colors->isChecked()); s.setValue("show_bars", ui_->checkbox_barscurrenttrack->isChecked()); diff --git a/src/settings/qobuzsettingspage.cpp b/src/settings/qobuzsettingspage.cpp index 060c7235a3..5a712f8886 100644 --- a/src/settings/qobuzsettingspage.cpp +++ b/src/settings/qobuzsettingspage.cpp @@ -36,6 +36,7 @@ #include "ui_qobuzsettingspage.h" #include "core/application.h" #include "core/iconloader.h" +#include "core/settings.h" #include "widgets/loginstatewidget.h" #include "internet/internetservices.h" #include "qobuz/qobuzservice.h" @@ -71,7 +72,7 @@ QobuzSettingsPage::~QobuzSettingsPage() { delete ui_; } void QobuzSettingsPage::Load() { - QSettings s; + Settings s; if (!s.contains(kSettingsGroup)) set_changed(); s.beginGroup(kSettingsGroup); @@ -98,13 +99,13 @@ void QobuzSettingsPage::Load() { Init(ui_->layout_qobuzsettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void QobuzSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("enabled", ui_->enable->isChecked()); s.setValue("app_id", ui_->app_id->text()); diff --git a/src/settings/scrobblersettingspage.cpp b/src/settings/scrobblersettingspage.cpp index af15d8ac27..d882936654 100644 --- a/src/settings/scrobblersettingspage.cpp +++ b/src/settings/scrobblersettingspage.cpp @@ -34,6 +34,7 @@ #include "core/application.h" #include "core/iconloader.h" #include "core/song.h" +#include "core/settings.h" #include "widgets/loginstatewidget.h" #include "scrobbler/audioscrobbler.h" @@ -78,7 +79,7 @@ ScrobblerSettingsPage::ScrobblerSettingsPage(SettingsDialog *dialog, QWidget *pa QObject::connect(ui_->widget_listenbrainz_login_state, &LoginStateWidget::LogoutClicked, this, &ScrobblerSettingsPage::ListenBrainz_Logout); ui_->widget_listenbrainz_login_state->AddCredentialGroup(ui_->widget_listenbrainz_login); - ui_->label_listenbrainz_token->setText("

" + tr("Enter your user token from") + " " + "https://listenbrainz.org/profile/

"); + ui_->label_listenbrainz_token->setText(QStringLiteral("

") + tr("Enter your user token from") + QStringLiteral(" ") + QStringLiteral("https://listenbrainz.org/profile/

")); resize(sizeHint()); @@ -88,7 +89,7 @@ ScrobblerSettingsPage::~ScrobblerSettingsPage() { delete ui_; } void ScrobblerSettingsPage::Load() { - QSettings s; + Settings s; if (!s.contains(kSettingsGroup)) set_changed(); ui_->checkbox_enable->setChecked(scrobbler_->enabled()); @@ -124,13 +125,13 @@ void ScrobblerSettingsPage::Load() { Init(ui_->layout_scrobblersettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void ScrobblerSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("enabled", ui_->checkbox_enable->isChecked()); diff --git a/src/settings/settingsdialog.cpp b/src/settings/settingsdialog.cpp index b87a88fb36..165106d3cc 100644 --- a/src/settings/settingsdialog.cpp +++ b/src/settings/settingsdialog.cpp @@ -49,6 +49,7 @@ #include "core/application.h" #include "core/player.h" +#include "core/settings.h" #include "utilities/screenutils.h" #include "widgets/groupediconview.h" #include "collection/collectionmodel.h" @@ -237,8 +238,8 @@ void SettingsDialog::reject() { void SettingsDialog::LoadGeometry() { - QSettings s; - s.beginGroup(kSettingsGroup); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup)); if (s.contains("geometry")) { restoreGeometry(s.value("geometry").toByteArray()); } @@ -251,8 +252,8 @@ void SettingsDialog::LoadGeometry() { void SettingsDialog::SaveGeometry() { - QSettings s; - s.beginGroup(kSettingsGroup); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup)); s.setValue("geometry", saveGeometry()); s.endGroup(); @@ -353,7 +354,7 @@ void SettingsDialog::CurrentItemChanged(QTreeWidgetItem *item) { } // Set the title - ui_->title->setText("" + item->text(0) + ""); + ui_->title->setText(QStringLiteral("") + item->text(0) + QStringLiteral("")); // Display the right page QList pages = pages_.values(); diff --git a/src/settings/settingsdialog.h b/src/settings/settingsdialog.h index 013890dd52..cbdb23e4c7 100644 --- a/src/settings/settingsdialog.h +++ b/src/settings/settingsdialog.h @@ -32,7 +32,6 @@ #include #include #include -#include #include "core/shared_ptr.h" #include "engine/enginebase.h" diff --git a/src/settings/settingspage.cpp b/src/settings/settingspage.cpp index e1bf5b3ea9..69b463d71c 100644 --- a/src/settings/settingspage.cpp +++ b/src/settings/settingspage.cpp @@ -31,6 +31,7 @@ #include #include "core/logging.h" +#include "core/settings.h" #include "settingsdialog.h" #include "settingspage.h" @@ -151,7 +152,7 @@ void SettingsPage::Apply() { } -void SettingsPage::ComboBoxLoadFromSettings(const QSettings &s, QComboBox *combobox, const QString &setting, const QString &default_value) { +void SettingsPage::ComboBoxLoadFromSettings(const Settings &s, QComboBox *combobox, const QString &setting, const QString &default_value) { QString value = s.value(setting, default_value).toString(); int i = combobox->findData(value); @@ -160,7 +161,7 @@ void SettingsPage::ComboBoxLoadFromSettings(const QSettings &s, QComboBox *combo } -void SettingsPage::ComboBoxLoadFromSettings(const QSettings &s, QComboBox *combobox, const QString &setting, const int default_value) { +void SettingsPage::ComboBoxLoadFromSettings(const Settings &s, QComboBox *combobox, const QString &setting, const int default_value) { int value = s.value(setting, default_value).toInt(); int i = combobox->findData(value); @@ -169,7 +170,7 @@ void SettingsPage::ComboBoxLoadFromSettings(const QSettings &s, QComboBox *combo } -void SettingsPage::ComboBoxLoadFromSettingsByIndex(const QSettings &s, QComboBox *combobox, const QString &setting, const int default_value) { +void SettingsPage::ComboBoxLoadFromSettingsByIndex(const Settings &s, QComboBox *combobox, const QString &setting, const int default_value) { if (combobox->count() == 0) return; int i = s.value(setting, default_value).toInt(); diff --git a/src/settings/settingspage.h b/src/settings/settingspage.h index 98b7d73489..88fd081b48 100644 --- a/src/settings/settingspage.h +++ b/src/settings/settingspage.h @@ -34,6 +34,7 @@ #include "osd/osdbase.h" #include "core/logging.h" +#include "core/settings.h" class QCheckBox; class QComboBox; @@ -68,9 +69,9 @@ class SettingsPage : public QWidget { void set_changed() { changed_ = true; } - static void ComboBoxLoadFromSettings(const QSettings &s, QComboBox *combobox, const QString &setting, const QString &default_value); - static void ComboBoxLoadFromSettings(const QSettings &s, QComboBox *combobox, const QString &setting, const int default_value); - static void ComboBoxLoadFromSettingsByIndex(const QSettings &s, QComboBox *combobox, const QString &setting, const int default_value); + static void ComboBoxLoadFromSettings(const Settings &s, QComboBox *combobox, const QString &setting, const QString &default_value); + static void ComboBoxLoadFromSettings(const Settings &s, QComboBox *combobox, const QString &setting, const int default_value); + static void ComboBoxLoadFromSettingsByIndex(const Settings &s, QComboBox *combobox, const QString &setting, const int default_value); private: virtual void Save() = 0; diff --git a/src/settings/subsonicsettingspage.cpp b/src/settings/subsonicsettingspage.cpp index bac7a7ffdd..d0634f3f88 100644 --- a/src/settings/subsonicsettingspage.cpp +++ b/src/settings/subsonicsettingspage.cpp @@ -36,6 +36,7 @@ #include "ui_subsonicsettingspage.h" #include "core/application.h" #include "core/iconloader.h" +#include "core/settings.h" #include "internet/internetservices.h" #include "subsonic/subsonicservice.h" @@ -71,7 +72,7 @@ SubsonicSettingsPage::~SubsonicSettingsPage() { delete ui_; } void SubsonicSettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); ui_->enable->setChecked(s.value("enabled", false).toBool()); ui_->server_url->setText(s.value("url").toString()); @@ -98,13 +99,13 @@ void SubsonicSettingsPage::Load() { Init(ui_->layout_subsonicsettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void SubsonicSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("enabled", ui_->enable->isChecked()); s.setValue("url", QUrl(ui_->server_url->text())); diff --git a/src/settings/tidalsettingspage.cpp b/src/settings/tidalsettingspage.cpp index 66428c2ecc..45e0683676 100644 --- a/src/settings/tidalsettingspage.cpp +++ b/src/settings/tidalsettingspage.cpp @@ -36,6 +36,7 @@ #include "ui_tidalsettingspage.h" #include "core/application.h" #include "core/iconloader.h" +#include "core/settings.h" #include "internet/internetservices.h" #include "tidal/tidalservice.h" #include "widgets/loginstatewidget.h" @@ -62,16 +63,16 @@ TidalSettingsPage::TidalSettingsPage(SettingsDialog *dialog, QWidget *parent) dialog->installEventFilter(this); - ui_->quality->addItem(QStringLiteral("Low"), "LOW"); - ui_->quality->addItem(QStringLiteral("High"), "HIGH"); - ui_->quality->addItem(QStringLiteral("Lossless"), "LOSSLESS"); - ui_->quality->addItem(QStringLiteral("Hi resolution"), "HI_RES"); + ui_->quality->addItem(QStringLiteral("Low"), QStringLiteral("LOW")); + ui_->quality->addItem(QStringLiteral("High"), QStringLiteral("HIGH")); + ui_->quality->addItem(QStringLiteral("Lossless"), QStringLiteral("LOSSLESS")); + ui_->quality->addItem(QStringLiteral("Hi resolution"), QStringLiteral("HI_RES")); - ui_->coversize->addItem(QStringLiteral("160x160"), "160x160"); - ui_->coversize->addItem(QStringLiteral("320x320"), "320x320"); - ui_->coversize->addItem(QStringLiteral("640x640"), "640x640"); - ui_->coversize->addItem(QStringLiteral("750x750"), "750x750"); - ui_->coversize->addItem(QStringLiteral("1280x1280"), "1280x1280"); + ui_->coversize->addItem(QStringLiteral("160x160"), QStringLiteral("160x160")); + ui_->coversize->addItem(QStringLiteral("320x320"), QStringLiteral("320x320")); + ui_->coversize->addItem(QStringLiteral("640x640"), QStringLiteral("640x640")); + ui_->coversize->addItem(QStringLiteral("750x750"), QStringLiteral("750x750")); + ui_->coversize->addItem(QStringLiteral("1280x1280"), QStringLiteral("1280x1280")); ui_->streamurl->addItem(QStringLiteral("streamurl"), static_cast(StreamUrlMethod::StreamUrl)); ui_->streamurl->addItem(QStringLiteral("urlpostpaywall"), static_cast(StreamUrlMethod::UrlPostPaywall)); @@ -83,7 +84,7 @@ TidalSettingsPage::~TidalSettingsPage() { delete ui_; } void TidalSettingsPage::Load() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); ui_->enable->setChecked(s.value("enabled", false).toBool()); ui_->oauth->setChecked(s.value("oauth", true).toBool()); @@ -114,13 +115,13 @@ void TidalSettingsPage::Load() { Init(ui_->layout_tidalsettingspage->parentWidget()); - if (!QSettings().childGroups().contains(kSettingsGroup)) set_changed(); + if (!Settings().childGroups().contains(QLatin1String(kSettingsGroup))) set_changed(); } void TidalSettingsPage::Save() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("enabled", ui_->enable->isChecked()); s.setValue("oauth", ui_->oauth->isChecked()); diff --git a/src/smartplaylists/smartplaylistsearch.cpp b/src/smartplaylists/smartplaylistsearch.cpp index 37dd999804..fe6bf14aa6 100644 --- a/src/smartplaylists/smartplaylistsearch.cpp +++ b/src/smartplaylists/smartplaylistsearch.cpp @@ -51,7 +51,7 @@ void SmartPlaylistSearch::Reset() { QString SmartPlaylistSearch::ToSql(const QString &songs_table) const { - QString sql = "SELECT ROWID," + Song::kColumnSpec + " FROM " + songs_table; + QString sql = QStringLiteral("SELECT ROWID,") + Song::kColumnSpec + QStringLiteral(" FROM ") + songs_table; // Add search terms QStringList where_clauses; @@ -63,16 +63,16 @@ QString SmartPlaylistSearch::ToSql(const QString &songs_table) const { if (!terms_.isEmpty() && search_type_ != SearchType::All) { QString boolean_op = search_type_ == SearchType::And ? QStringLiteral(" AND ") : QStringLiteral(" OR "); - where_clauses << "(" + term_where_clauses.join(boolean_op) + ")"; + where_clauses << QStringLiteral("(") + term_where_clauses.join(boolean_op) + QStringLiteral(")"); } // Restrict the IDs of songs if we're making a dynamic playlist if (!id_not_in_.isEmpty()) { QString numbers; for (int id : id_not_in_) { - numbers += (numbers.isEmpty() ? "" : ",") + QString::number(id); + numbers += (numbers.isEmpty() ? QLatin1String("") : QStringLiteral(",")) + QString::number(id); } - where_clauses << "(ROWID NOT IN (" + numbers + "))"; + where_clauses << QStringLiteral("(ROWID NOT IN (") + numbers + QStringLiteral("))"); } // We never want to include songs that have been deleted, @@ -80,7 +80,7 @@ QString SmartPlaylistSearch::ToSql(const QString &songs_table) const { where_clauses << QStringLiteral("unavailable = 0"); if (!where_clauses.isEmpty()) { - sql += " WHERE " + where_clauses.join(QStringLiteral(" AND ")); + sql += QStringLiteral(" WHERE ") + where_clauses.join(QStringLiteral(" AND ")); } // Add sort by @@ -88,7 +88,7 @@ QString SmartPlaylistSearch::ToSql(const QString &songs_table) const { sql += QLatin1String(" ORDER BY random()"); } else { - sql += " ORDER BY " + SmartPlaylistSearchTerm::FieldColumnName(sort_field_) + (sort_type_ == SortType::FieldAsc ? " ASC" : " DESC"); + sql += QStringLiteral(" ORDER BY ") + SmartPlaylistSearchTerm::FieldColumnName(sort_field_) + (sort_type_ == SortType::FieldAsc ? QStringLiteral(" ASC") : QStringLiteral(" DESC")); } // Add limit @@ -96,7 +96,7 @@ QString SmartPlaylistSearch::ToSql(const QString &songs_table) const { sql += QStringLiteral(" LIMIT %1 OFFSET %2").arg(limit_).arg(first_item_); } else if (limit_ != -1) { - sql += " LIMIT " + QString::number(limit_); + sql += QStringLiteral(" LIMIT ") + QString::number(limit_); } //qLog(Debug) << sql; diff --git a/src/smartplaylists/smartplaylistsearchterm.cpp b/src/smartplaylists/smartplaylistsearchterm.cpp index 27f539ea5f..e17feadb6e 100644 --- a/src/smartplaylists/smartplaylistsearchterm.cpp +++ b/src/smartplaylists/smartplaylistsearchterm.cpp @@ -39,7 +39,7 @@ QString SmartPlaylistSearchTerm::ToSql() const { QString col = FieldColumnName(field_); QString date = DateName(datetype_, true); QString value = value_.toString(); - value.replace('\'', QLatin1String("''")); + value.replace(QLatin1Char('\''), QLatin1String("''")); if (field_ == Field::Filetype) { Song::FileType filetype = Song::FiletypeByExtension(value); @@ -62,10 +62,10 @@ QString SmartPlaylistSearchTerm::ToSql() const { if (TypeOf(field_) == Type::Date) { if (special_date_query) { // We have a numeric date, consider also the time for more precision - col = "DATETIME(" + col + ", 'unixepoch', 'localtime')"; + col = QStringLiteral("DATETIME(") + col + QStringLiteral(", 'unixepoch', 'localtime')"); second_value = second_value_.toString(); - second_value.replace('\'', QLatin1String("''")); - if (date == "weeks") { + second_value.replace(QLatin1Char('\''), QLatin1String("''")); + if (date == QStringLiteral("weeks")) { // Sqlite doesn't know weeks, transform them to days date = QStringLiteral("days"); value = QString::number(value_.toInt() * 7); @@ -76,80 +76,80 @@ QString SmartPlaylistSearchTerm::ToSql() const { // We have the exact date // The calendar widget specifies no time so ditch the possible time part // from integers representing the dates. - col = "DATE(" + col + ", 'unixepoch', 'localtime')"; - value = "DATE(" + value + ", 'unixepoch', 'localtime')"; + col = QStringLiteral("DATE(") + col + QStringLiteral(", 'unixepoch', 'localtime')"); + value = QStringLiteral("DATE(") + value + QStringLiteral(", 'unixepoch', 'localtime')"); } } else if (TypeOf(field_) == Type::Time) { // Convert seconds to nanoseconds - value = "CAST (" + value + " *1000000000 AS INTEGER)"; + value = QStringLiteral("CAST (") + value + QStringLiteral(" *1000000000 AS INTEGER)"); } // File paths need some extra processing since they are stored as encoded urls in the database. if (field_ == Field::Filepath) { if (operator_ == Operator::StartsWith || operator_ == Operator::Equals) { - value = QUrl::fromLocalFile(value).toEncoded(); + value = QString::fromUtf8(QUrl::fromLocalFile(value).toEncoded()); } else { - value = QUrl(value).toEncoded(); + value = QString::fromUtf8(QUrl(value).toEncoded()); } } else if (TypeOf(field_) == Type::Rating) { - col = "CAST ((replace(" + col + ", -1, 0) + 0.05) * 10 AS INTEGER)"; - value = "CAST ((" + value + " + 0.05) * 10 AS INTEGER)"; + col = QStringLiteral("CAST ((replace(") + col + QStringLiteral(", -1, 0) + 0.05) * 10 AS INTEGER)"); + value = QStringLiteral("CAST ((") + value + QStringLiteral(" + 0.05) * 10 AS INTEGER)"); } switch (operator_) { case Operator::Contains: - return col + " LIKE '%" + value + "%'"; + return col + QStringLiteral(" LIKE '%") + value + QStringLiteral("%'"); case Operator::NotContains: - return col + " NOT LIKE '%" + value + "%'"; + return col + QStringLiteral(" NOT LIKE '%") + value + QStringLiteral("%'"); case Operator::StartsWith: - return col + " LIKE '" + value + "%'"; + return col + QStringLiteral(" LIKE '") + value + QStringLiteral("%'"); case Operator::EndsWith: - return col + " LIKE '%" + value + "'"; + return col + QStringLiteral(" LIKE '%") + value + QStringLiteral("'"); case Operator::Equals: if (TypeOf(field_) == Type::Text) { - return col + " LIKE '" + value + "'"; + return col + QStringLiteral(" LIKE '") + value + QStringLiteral("'"); } else if (TypeOf(field_) == Type::Date || TypeOf(field_) == Type::Time || TypeOf(field_) == Type::Rating) { - return col + " = " + value; + return col + QStringLiteral(" = ") + value; } else { - return col + " = '" + value + "'"; + return col + QStringLiteral(" = '") + value + QStringLiteral("'"); } case Operator::GreaterThan: if (TypeOf(field_) == Type::Date || TypeOf(field_) == Type::Time || TypeOf(field_) == Type::Rating) { - return col + " > " + value; + return col + QStringLiteral(" > ") + value; } else { - return col + " > '" + value + "'"; + return col + QStringLiteral(" > '") + value + QLatin1Char('\''); } case Operator::LessThan: if (TypeOf(field_) == Type::Date || TypeOf(field_) == Type::Time || TypeOf(field_) == Type::Rating) { - return col + " < " + value; + return col + QStringLiteral(" < ") + value; } else { - return col + " < '" + value + "'"; + return col + QStringLiteral(" < '") + value + QStringLiteral("'"); } case Operator::NumericDate: - return col + " > " + "DATETIME('now', '-" + value + " " + date + "', 'localtime')"; + return col + QStringLiteral(" > ") + QStringLiteral("DATETIME('now', '-") + value + QStringLiteral(" ") + date + QStringLiteral("', 'localtime')"); case Operator::NumericDateNot: - return col + " < " + "DATETIME('now', '-" + value + " " + date + "', 'localtime')"; + return col + QStringLiteral(" < ") + QStringLiteral("DATETIME('now', '-") + value + QStringLiteral(" ") + date + QStringLiteral("', 'localtime')"); case Operator::RelativeDate: // Consider the time range before the first date but after the second one - return "(" + col + " < " + "DATETIME('now', '-" + value + " " + date + "', 'localtime') AND " + col + " > " + "DATETIME('now', '-" + second_value + " " + date + "', 'localtime'))"; + return QStringLiteral("(") + col + QStringLiteral(" < ") + QStringLiteral("DATETIME('now', '-") + value + QStringLiteral(" ") + date + QStringLiteral("', 'localtime') AND ") + col + QStringLiteral(" > ") + QStringLiteral("DATETIME('now', '-") + second_value + QStringLiteral(" ") + date + QStringLiteral("', 'localtime'))"); case Operator::NotEquals: if (TypeOf(field_) == Type::Text) { - return col + " <> '" + value + "'"; + return col + QStringLiteral(" <> '") + value + QStringLiteral("'"); } else { - return col + " <> " + value; + return col + QStringLiteral(" <> ") + value; } case Operator::Empty: - return col + " = ''"; + return col + QStringLiteral(" = ''"); case Operator::NotEmpty: - return col + " <> ''"; + return col + QStringLiteral(" <> ''"); } return QString(); diff --git a/src/smartplaylists/smartplaylistsearchtermwidget.cpp b/src/smartplaylists/smartplaylistsearchtermwidget.cpp index 7fe847e31b..730cbfaebd 100644 --- a/src/smartplaylists/smartplaylistsearchtermwidget.cpp +++ b/src/smartplaylists/smartplaylistsearchtermwidget.cpp @@ -381,7 +381,7 @@ SmartPlaylistSearchTerm SmartPlaylistSearchTermWidget::Term() const { ret.value_ = ui_->value_text->text(); } else if (value_page == ui_->page_empty) { - ret.value_ = ""; + ret.value_ = QLatin1String(""); } else if (value_page == ui_->page_number) { ret.value_ = ui_->value_number->value(); diff --git a/src/smartplaylists/smartplaylistsmodel.cpp b/src/smartplaylists/smartplaylistsmodel.cpp index 089b5c51e9..d0ad5d4e6b 100644 --- a/src/smartplaylists/smartplaylistsmodel.cpp +++ b/src/smartplaylists/smartplaylistsmodel.cpp @@ -32,6 +32,7 @@ #include "core/application.h" #include "core/iconloader.h" #include "core/simpletreemodel.h" +#include "core/settings.h" #include "collection/collectionbackend.h" #include "smartplaylistsitem.h" @@ -63,62 +64,62 @@ void SmartPlaylistsModel::Init() { << (SmartPlaylistsModel::GeneratorList() << PlaylistGeneratorPtr( new PlaylistQueryGenerator( - QT_TRANSLATE_NOOP("SmartPlaylists", "Newest tracks"), + QT_TRANSLATE_NOOP(QStringLiteral("SmartPlaylists"), QStringLiteral("Newest tracks")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::All, SmartPlaylistSearch::TermList(), SmartPlaylistSearch::SortType::FieldDesc, SmartPlaylistSearchTerm::Field::DateCreated) ) ) << PlaylistGeneratorPtr(new PlaylistQueryGenerator( - QT_TRANSLATE_NOOP("SmartPlaylists", "50 random tracks"), + QT_TRANSLATE_NOOP(QStringLiteral("SmartPlaylists"), QStringLiteral("50 random tracks")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::All, SmartPlaylistSearch::TermList(), SmartPlaylistSearch::SortType::Random, SmartPlaylistSearchTerm::Field::Title, 50) ) ) << PlaylistGeneratorPtr( new PlaylistQueryGenerator( - QT_TRANSLATE_NOOP("SmartPlaylists", "Ever played"), + QT_TRANSLATE_NOOP(QStringLiteral("SmartPlaylists"), QStringLiteral("Ever played")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::And, SmartPlaylistSearch::TermList() << SmartPlaylistSearchTerm( SmartPlaylistSearchTerm::Field::PlayCount, SmartPlaylistSearchTerm::Operator::GreaterThan, 0), SmartPlaylistSearch::SortType::Random, SmartPlaylistSearchTerm::Field::Title) ) ) << PlaylistGeneratorPtr( new PlaylistQueryGenerator( - QT_TRANSLATE_NOOP("SmartPlaylists", "Never played"), + QT_TRANSLATE_NOOP(QStringLiteral("SmartPlaylists"), QStringLiteral("Never played")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::And, SmartPlaylistSearch::TermList() << SmartPlaylistSearchTerm(SmartPlaylistSearchTerm::Field::PlayCount, SmartPlaylistSearchTerm::Operator::Equals, 0), SmartPlaylistSearch::SortType::Random, SmartPlaylistSearchTerm::Field::Title) ) ) << PlaylistGeneratorPtr( new PlaylistQueryGenerator( - QT_TRANSLATE_NOOP("SmartPlaylists", "Last played"), + QT_TRANSLATE_NOOP(QStringLiteral("SmartPlaylists"), QStringLiteral("Last played")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::All, SmartPlaylistSearch::TermList(), SmartPlaylistSearch::SortType::FieldDesc, SmartPlaylistSearchTerm::Field::LastPlayed) ) ) << PlaylistGeneratorPtr( new PlaylistQueryGenerator( - QT_TRANSLATE_NOOP("SmartPlaylists", "Most played"), + QT_TRANSLATE_NOOP(QStringLiteral("SmartPlaylists"), QStringLiteral("Most played")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::All, SmartPlaylistSearch::TermList(), SmartPlaylistSearch::SortType::FieldDesc, SmartPlaylistSearchTerm::Field::PlayCount) ) ) << PlaylistGeneratorPtr( new PlaylistQueryGenerator( - QT_TRANSLATE_NOOP("SmartPlaylists", "Favourite tracks"), + QT_TRANSLATE_NOOP(QStringLiteral("SmartPlaylists"), QStringLiteral("Favourite tracks")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::All, SmartPlaylistSearch::TermList(), SmartPlaylistSearch::SortType::FieldDesc, SmartPlaylistSearchTerm::Field::Rating) ) ) << PlaylistGeneratorPtr( new PlaylistQueryGenerator( - QT_TRANSLATE_NOOP("Library", "Least favourite tracks"), + QT_TRANSLATE_NOOP(QStringLiteral("Library"), QStringLiteral("Least favourite tracks")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::Or, SmartPlaylistSearch::TermList() << SmartPlaylistSearchTerm(SmartPlaylistSearchTerm::Field::Rating, SmartPlaylistSearchTerm::Operator::LessThan, 0.5) << SmartPlaylistSearchTerm(SmartPlaylistSearchTerm::Field::SkipCount, SmartPlaylistSearchTerm::Operator::GreaterThan, 4), SmartPlaylistSearch::SortType::FieldDesc, SmartPlaylistSearchTerm::Field::SkipCount) ) ) ) - << (SmartPlaylistsModel::GeneratorList() << PlaylistGeneratorPtr(new PlaylistQueryGenerator(QT_TRANSLATE_NOOP("SmartPlaylists", "All tracks"), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::All, SmartPlaylistSearch::TermList(), SmartPlaylistSearch::SortType::FieldAsc, SmartPlaylistSearchTerm::Field::Artist, -1)))) - << (SmartPlaylistsModel::GeneratorList() << PlaylistGeneratorPtr(new PlaylistQueryGenerator( QT_TRANSLATE_NOOP("SmartPlaylists", "Dynamic random mix"), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::All, SmartPlaylistSearch::TermList(), SmartPlaylistSearch::SortType::Random, SmartPlaylistSearchTerm::Field::Title), true))); + << (SmartPlaylistsModel::GeneratorList() << PlaylistGeneratorPtr(new PlaylistQueryGenerator(QT_TRANSLATE_NOOP(QStringLiteral("SmartPlaylists"), QStringLiteral("All tracks")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::All, SmartPlaylistSearch::TermList(), SmartPlaylistSearch::SortType::FieldAsc, SmartPlaylistSearchTerm::Field::Artist, -1)))) + << (SmartPlaylistsModel::GeneratorList() << PlaylistGeneratorPtr(new PlaylistQueryGenerator( QT_TRANSLATE_NOOP(QStringLiteral("SmartPlaylists"), QStringLiteral("Dynamic random mix")), SmartPlaylistSearch(SmartPlaylistSearch::SearchType::All, SmartPlaylistSearch::TermList(), SmartPlaylistSearch::SortType::Random, SmartPlaylistSearchTerm::Field::Title), true))); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); - int version = s.value(collection_backend_->songs_table() + "_version", 0).toInt(); + int version = s.value(collection_backend_->songs_table() + QStringLiteral("_version"), 0).toInt(); // How many defaults do we have to write? int unwritten_defaults = 0; @@ -142,7 +143,7 @@ void SmartPlaylistsModel::Init() { s.endArray(); } - s.setValue(collection_backend_->songs_table() + "_version", version); + s.setValue(collection_backend_->songs_table() + QStringLiteral("_version"), version); const int count = s.beginReadArray(collection_backend_->songs_table()); for (int i = 0; i < count; ++i) { @@ -154,7 +155,7 @@ void SmartPlaylistsModel::Init() { } -void SmartPlaylistsModel::ItemFromSmartPlaylist(const QSettings &s, const bool notify) { +void SmartPlaylistsModel::ItemFromSmartPlaylist(const Settings &s, const bool notify) { SmartPlaylistsItem *item = new SmartPlaylistsItem(SmartPlaylistsItem::Type_SmartPlaylist, notify ? nullptr : root_); item->display_text = tr(qPrintable(s.value("name").toString())); @@ -169,7 +170,7 @@ void SmartPlaylistsModel::ItemFromSmartPlaylist(const QSettings &s, const bool n void SmartPlaylistsModel::AddGenerator(PlaylistGeneratorPtr gen) { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); // Count the existing items @@ -195,7 +196,7 @@ void SmartPlaylistsModel::UpdateGenerator(const QModelIndex &idx, PlaylistGenera if (!item) return; // Update the config - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); // Count the existing items @@ -224,7 +225,7 @@ void SmartPlaylistsModel::DeleteGenerator(const QModelIndex &idx) { // Remove the item from the tree root_->DeleteNotify(idx.row()); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); // Rewrite all the items to the settings @@ -241,7 +242,7 @@ void SmartPlaylistsModel::DeleteGenerator(const QModelIndex &idx) { } -void SmartPlaylistsModel::SaveGenerator(QSettings *s, const int i, PlaylistGeneratorPtr generator) { +void SmartPlaylistsModel::SaveGenerator(Settings *s, const int i, PlaylistGeneratorPtr generator) { s->setArrayIndex(i); s->setValue("name", generator->name()); @@ -300,7 +301,7 @@ QMimeData *SmartPlaylistsModel::mimeData(const QModelIndexList &indexes) const { if (!generator) return nullptr; PlaylistGeneratorMimeData *mimedata = new PlaylistGeneratorMimeData(generator); - mimedata->setData(kSmartPlaylistsMimeType, QByteArray()); + mimedata->setData(QLatin1String(kSmartPlaylistsMimeType), QByteArray()); mimedata->name_for_new_playlist_ = data(indexes.first()).toString(); return mimedata; diff --git a/src/smartplaylists/smartplaylistsmodel.h b/src/smartplaylists/smartplaylistsmodel.h index 898426a1fd..98cddfd555 100644 --- a/src/smartplaylists/smartplaylistsmodel.h +++ b/src/smartplaylists/smartplaylistsmodel.h @@ -33,6 +33,7 @@ #include "core/shared_ptr.h" #include "core/simpletreemodel.h" +#include "core/settings.h" #include "smartplaylistsitem.h" #include "playlistgenerator_fwd.h" @@ -77,8 +78,8 @@ class SmartPlaylistsModel : public SimpleTreeModel { static const char *kSmartPlaylistsMimeType; static const int kSmartPlaylistsVersion; - static void SaveGenerator(QSettings *s, const int i, PlaylistGeneratorPtr generator); - void ItemFromSmartPlaylist(const QSettings &s, const bool notify); + static void SaveGenerator(Settings *s, const int i, PlaylistGeneratorPtr generator); + void ItemFromSmartPlaylist(const Settings &s, const bool notify); private: SharedPtr collection_backend_; diff --git a/src/smartplaylists/smartplaylistsviewcontainer.cpp b/src/smartplaylists/smartplaylistsviewcontainer.cpp index abd42f31fc..f4634b4a15 100644 --- a/src/smartplaylists/smartplaylistsviewcontainer.cpp +++ b/src/smartplaylists/smartplaylistsviewcontainer.cpp @@ -27,6 +27,7 @@ #include "core/application.h" #include "core/iconloader.h" #include "core/mimedata.h" +#include "core/settings.h" #include "collection/collectionbackend.h" #include "settings/appearancesettingspage.h" @@ -109,7 +110,7 @@ void SmartPlaylistsViewContainer::showEvent(QShowEvent *e) { void SmartPlaylistsViewContainer::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); int iconsize = s.value(AppearanceSettingsPage::kIconSizeLeftPanelButtons, 22).toInt(); s.endGroup(); diff --git a/src/smartplaylists/smartplaylistwizard.cpp b/src/smartplaylists/smartplaylistwizard.cpp index a66d624037..bc70df1e24 100644 --- a/src/smartplaylists/smartplaylistwizard.cpp +++ b/src/smartplaylists/smartplaylistwizard.cpp @@ -124,7 +124,7 @@ void SmartPlaylistWizard::SetGenerator(PlaylistGeneratorPtr gen) { // Set the name if (!gen->name().isEmpty()) { - setWindowTitle(windowTitle() + " - " + gen->name()); + setWindowTitle(windowTitle() + QStringLiteral(" - ") + gen->name()); } finish_page_->ui_->name->setText(gen->name()); finish_page_->ui_->dynamic->setChecked(gen->is_dynamic()); diff --git a/src/subsonic/subsonicbaserequest.cpp b/src/subsonic/subsonicbaserequest.cpp index bcfa9d2290..c9e0d99204 100644 --- a/src/subsonic/subsonicbaserequest.cpp +++ b/src/subsonic/subsonicbaserequest.cpp @@ -55,31 +55,31 @@ SubsonicBaseRequest::SubsonicBaseRequest(SubsonicService *service, QObject *pare QUrl SubsonicBaseRequest::CreateUrl(const QUrl &server_url, const SubsonicSettingsPage::AuthMethod auth_method, const QString &username, const QString &password, const QString &ressource_name, const ParamList ¶ms_provided) { ParamList params = ParamList() << params_provided - << Param("c", SubsonicService::kClientName) - << Param("v", SubsonicService::kApiVersion) - << Param("f", "json") - << Param("u", username); + << Param(QStringLiteral("c"), QLatin1String(SubsonicService::kClientName)) + << Param(QStringLiteral("v"), QLatin1String(SubsonicService::kApiVersion)) + << Param(QStringLiteral("f"), QStringLiteral("json")) + << Param(QStringLiteral("u"), username); if (auth_method == SubsonicSettingsPage::AuthMethod::Hex) { - params << Param("p", QString("enc:" + password.toUtf8().toHex())); + params << Param(QStringLiteral("p"), QStringLiteral("enc:") + QString::fromUtf8(password.toUtf8().toHex())); } else { const QString salt = Utilities::CryptographicRandomString(20); QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(password.toUtf8()); md5.addData(salt.toUtf8()); - params << Param("s", salt); - params << Param("t", md5.result().toHex()); + params << Param(QStringLiteral("s"), salt); + params << Param(QStringLiteral("t"), QString::fromUtf8(md5.result().toHex())); } QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } QUrl url(server_url); - if (!url.path().isEmpty() && url.path().right(1) == "/") { + if (!url.path().isEmpty() && url.path().right(1) == QStringLiteral("/")) { url.setPath(url.path() + QStringLiteral("rest/") + ressource_name + QStringLiteral(".view")); } else { @@ -97,13 +97,13 @@ QNetworkReply *SubsonicBaseRequest::CreateGetRequest(const QString &ressource_na QUrl url = CreateUrl(server_url(), auth_method(), username(), password(), ressource_name, params_provided); QNetworkRequest req(url); - if (url.scheme() == "https" && !verify_certificate()) { + if (url.scheme() == QStringLiteral("https") && !verify_certificate()) { QSslConfiguration sslconfig = QSslConfiguration::defaultConfiguration(); sslconfig.setPeerVerifyMode(QSslSocket::VerifyNone); req.setSslConfiguration(sslconfig); } - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) @@ -222,7 +222,7 @@ QString SubsonicBaseRequest::ErrorsToHTML(const QStringList &errors) { QString error_html; for (const QString &error : errors) { - error_html += error + "
"; + error_html += error + QStringLiteral("
"); } return error_html; diff --git a/src/subsonic/subsonicrequest.cpp b/src/subsonic/subsonicrequest.cpp index bed47beb57..2217db89d1 100644 --- a/src/subsonic/subsonicrequest.cpp +++ b/src/subsonic/subsonicrequest.cpp @@ -145,9 +145,9 @@ void SubsonicRequest::FlushAlbumsRequests() { Request request = albums_requests_queue_.dequeue(); ++albums_requests_active_; - ParamList params = ParamList() << Param("type", "alphabeticalByName"); - if (request.size > 0) params << Param("size", QString::number(request.size)); - if (request.offset > 0) params << Param("offset", QString::number(request.offset)); + ParamList params = ParamList() << Param(QStringLiteral("type"), QStringLiteral("alphabeticalByName")); + if (request.size > 0) params << Param(QStringLiteral("size"), QString::number(request.size)); + if (request.offset > 0) params << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = CreateGetRequest(QStringLiteral("getAlbumList2"), params); replies_ << reply; @@ -341,7 +341,7 @@ void SubsonicRequest::FlushAlbumSongsRequests() { Request request = album_songs_requests_queue_.dequeue(); ++album_songs_requests_active_; - QNetworkReply *reply = CreateGetRequest(QStringLiteral("getAlbum"), ParamList() << Param("id", request.album_id)); + QNetworkReply *reply = CreateGetRequest(QStringLiteral("getAlbum"), ParamList() << Param(QStringLiteral("id"), request.album_id)); replies_ << reply; QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, request]() { AlbumSongsReplyReceived(reply, request.artist_id, request.album_id, request.album_artist); }); timeouts_->AddReply(reply); @@ -631,7 +631,7 @@ QString SubsonicRequest::ParseSong(Song &song, const QJsonObject &json_obj, cons cover_url = cover_urls_[cover_id]; } else { - cover_url = CreateUrl(server_url(), auth_method(), username(), password(), QStringLiteral("getCoverArt"), ParamList() << Param("id", cover_id)); + cover_url = CreateUrl(server_url(), auth_method(), username(), password(), QStringLiteral("getCoverArt"), ParamList() << Param(QStringLiteral("id"), cover_id)); cover_urls_.insert(cover_id, cover_url); } } @@ -639,7 +639,7 @@ QString SubsonicRequest::ParseSong(Song &song, const QJsonObject &json_obj, cons Song::FileType filetype(Song::FileType::Stream); if (!mimetype.isEmpty()) { QMimeDatabase mimedb; - QStringList suffixes = mimedb.mimeTypeForName(mimetype.toUtf8()).suffixes(); + QStringList suffixes = mimedb.mimeTypeForName(mimetype).suffixes(); for (const QString &suffix : suffixes) { filetype = Song::FiletypeByExtension(suffix); if (filetype != Song::FileType::Unknown) break; @@ -721,7 +721,7 @@ void SubsonicRequest::AddAlbumCoverRequest(const Song &song) { request.album_id = song.album_id(); request.cover_id = cover_id; request.url = cover_url; - request.filename = cover_path + "/" + cover_id + ".jpg"; + request.filename = cover_path + QLatin1Char('/') + cover_id + QStringLiteral(".jpg"); if (request.filename.isEmpty()) return; album_covers_requests_sent_.insert(cover_id, song.song_id()); @@ -799,8 +799,8 @@ void SubsonicRequest::AlbumCoverReceived(QNetworkReply *reply, const AlbumCoverR } QString mimetype = reply->header(QNetworkRequest::ContentTypeHeader).toString(); - if (mimetype.contains(';')) { - mimetype = mimetype.left(mimetype.indexOf(';')); + if (mimetype.contains(QLatin1Char(';'))) { + mimetype = mimetype.left(mimetype.indexOf(QLatin1Char(';'))); } if (!ImageUtils::SupportedImageMimeTypes().contains(mimetype, Qt::CaseInsensitive) && !ImageUtils::SupportedImageFormats().contains(mimetype, Qt::CaseInsensitive)) { Error(QStringLiteral("Unsupported mimetype for image reader %1 for %2").arg(mimetype, request.url.toString())); diff --git a/src/subsonic/subsonicscrobblerequest.cpp b/src/subsonic/subsonicscrobblerequest.cpp index 1c65a8aeb2..314b24a3a1 100644 --- a/src/subsonic/subsonicscrobblerequest.cpp +++ b/src/subsonic/subsonicscrobblerequest.cpp @@ -73,9 +73,9 @@ void SubsonicScrobbleRequest::FlushScrobbleRequests() { Request request = scrobble_requests_queue_.dequeue(); ++scrobble_requests_active_; - ParamList params = ParamList() << Param("id", request.song_id) - << Param("submission", QVariant(request.submission).toString()) - << Param("time", QVariant(request.time_ms).toString()); + ParamList params = ParamList() << Param(QStringLiteral("id"), request.song_id) + << Param(QStringLiteral("submission"), QVariant(request.submission).toString()) + << Param(QStringLiteral("time"), QVariant(request.time_ms).toString()); QNetworkReply *reply = CreateGetRequest(QStringLiteral("scrobble"), params); replies_ << reply; diff --git a/src/subsonic/subsonicservice.cpp b/src/subsonic/subsonicservice.cpp index 71f643f871..0c52d41c04 100644 --- a/src/subsonic/subsonicservice.cpp +++ b/src/subsonic/subsonicservice.cpp @@ -48,6 +48,7 @@ #include "core/player.h" #include "core/database.h" #include "core/song.h" +#include "core/settings.h" #include "utilities/randutils.h" #include "collection/collectionbackend.h" #include "collection/collectionmodel.h" @@ -64,12 +65,15 @@ using std::make_shared; const Song::Source SubsonicService::kSource = Song::Source::Subsonic; const char *SubsonicService::kClientName = "Strawberry"; const char *SubsonicService::kApiVersion = "1.11.0"; -const char *SubsonicService::kSongsTable = "subsonic_songs"; -const char *SubsonicService::kSongsFtsTable = "subsonic_songs_fts"; -const int SubsonicService::kMaxRedirects = 3; + +namespace { +constexpr char kSongsTable[] = "subsonic_songs"; +constexpr char kSongsFtsTable[] = "subsonic_songs_fts"; +constexpr int kMaxRedirects = 3; +} // namespace SubsonicService::SubsonicService(Application *app, QObject *parent) - : InternetService(Song::Source::Subsonic, QStringLiteral("Subsonic"), QStringLiteral("subsonic"), SubsonicSettingsPage::kSettingsGroup, SettingsDialog::Page::Subsonic, app, parent), + : InternetService(Song::Source::Subsonic, QStringLiteral("Subsonic"), QStringLiteral("subsonic"), QLatin1String(SubsonicSettingsPage::kSettingsGroup), SettingsDialog::Page::Subsonic, app, parent), app_(app), url_handler_(new SubsonicUrlHandler(app, this)), collection_backend_(nullptr), @@ -85,9 +89,10 @@ SubsonicService::SubsonicService(Application *app, QObject *parent) // Backend + collection_backend_ = make_shared(); collection_backend_->moveToThread(app_->database()->thread()); - collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Subsonic, kSongsTable, kSongsFtsTable); + collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Subsonic, QLatin1String(kSongsTable), QLatin1String(kSongsFtsTable)); // Model @@ -126,7 +131,7 @@ void SubsonicService::ShowConfig() { void SubsonicService::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(SubsonicSettingsPage::kSettingsGroup); server_url_ = s.value("url").toUrl(); @@ -159,30 +164,30 @@ void SubsonicService::SendPingWithCredentials(QUrl url, const QString &username, using Param = QPair; using ParamList = QList; - ParamList params = ParamList() << Param("c", kClientName) - << Param("v", kApiVersion) - << Param("f", "json") - << Param("u", username); + ParamList params = ParamList() << Param(QStringLiteral("c"), QLatin1String(kClientName)) + << Param(QStringLiteral("v"), QLatin1String(kApiVersion)) + << Param(QStringLiteral("f"), QStringLiteral("json")) + << Param(QStringLiteral("u"), username); if (auth_method == SubsonicSettingsPage::AuthMethod::Hex) { - params << Param("p", QString("enc:" + password.toUtf8().toHex())); + params << Param(QStringLiteral("p"), QStringLiteral("enc:") + QString::fromLatin1(password.toUtf8().toHex())); } else { const QString salt = Utilities::CryptographicRandomString(20); QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(password.toUtf8()); md5.addData(salt.toUtf8()); - params << Param("s", salt); - params << Param("t", md5.result().toHex()); + params << Param(QStringLiteral("s"), salt); + params << Param(QStringLiteral("t"), QString::fromLatin1(md5.result().toHex())); } QUrlQuery url_query(url.query()); for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } if (!redirect) { - if (!url.path().isEmpty() && url.path().right(1) == "/") { + if (!url.path().isEmpty() && url.path().right(1) == QStringLiteral("/")) { url.setPath(url.path() + QStringLiteral("rest/ping.view")); } else { @@ -194,14 +199,14 @@ void SubsonicService::SendPingWithCredentials(QUrl url, const QString &username, QNetworkRequest req(url); - if (url.scheme() == "https" && !verify_certificate_) { + if (url.scheme() == QStringLiteral("https") && !verify_certificate_) { QSslConfiguration sslconfig = QSslConfiguration::defaultConfiguration(); sslconfig.setPeerVerifyMode(QSslSocket::VerifyNone); req.setSslConfiguration(sslconfig); } req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) req.setAttribute(QNetworkRequest::Http2AllowedAttribute, http2_); @@ -263,7 +268,7 @@ void SubsonicService::HandlePingReply(QNetworkReply *reply, const QUrl &url, con } // See if there is Json data containing "error" - then use that instead. - QByteArray data = reply->readAll(); + const QByteArray data = reply->readAll(); QJsonParseError parse_error; QJsonDocument json_doc = QJsonDocument::fromJson(data, &parse_error); if (parse_error.error == QJsonParseError::NoError && !json_doc.isEmpty() && json_doc.isObject()) { @@ -358,12 +363,12 @@ void SubsonicService::HandlePingReply(QNetworkReply *reply, const QUrl &url, con QString status = obj_response[QStringLiteral("status")].toString().toLower(); QString message = obj_response[QStringLiteral("message")].toString(); - if (status == "failed") { + if (status == QStringLiteral("failed")) { emit TestComplete(false, message); emit TestFailure(message); return; } - else if (status == "ok") { + else if (status == QStringLiteral("ok")) { emit TestComplete(true); emit TestSuccess(); return; @@ -461,7 +466,7 @@ void SubsonicService::PingError(const QString &error, const QVariant &debug) { QString error_html; for (const QString &e : errors_) { qLog(Error) << "Subsonic:" << e; - error_html += e + "
"; + error_html += e + QStringLiteral("
"); } if (debug.isValid()) qLog(Debug) << debug; diff --git a/src/subsonic/subsonicservice.h b/src/subsonic/subsonicservice.h index 42ebb21a5b..4128105760 100644 --- a/src/subsonic/subsonicservice.h +++ b/src/subsonic/subsonicservice.h @@ -103,10 +103,6 @@ class SubsonicService : public InternetService { private: void PingError(const QString &error = QString(), const QVariant &debug = QVariant()); - static const char *kSongsTable; - static const char *kSongsFtsTable; - static const int kMaxRedirects; - Application *app_; ScopedPtr network_; SubsonicUrlHandler *url_handler_; diff --git a/src/subsonic/subsonicurlhandler.cpp b/src/subsonic/subsonicurlhandler.cpp index a68548260e..8c18ea11eb 100644 --- a/src/subsonic/subsonicurlhandler.cpp +++ b/src/subsonic/subsonicurlhandler.cpp @@ -45,7 +45,7 @@ UrlHandler::LoadResult SubsonicUrlHandler::StartLoading(const QUrl &url) { using Param = QPair; using ParamList = QList; - const QUrl stream_url = SubsonicBaseRequest::CreateUrl(server_url(), auth_method(), username(), password(), QStringLiteral("stream"), ParamList() << Param("id", url.path())); + const QUrl stream_url = SubsonicBaseRequest::CreateUrl(server_url(), auth_method(), username(), password(), QStringLiteral("stream"), ParamList() << Param(QStringLiteral("id"), url.path())); return LoadResult(url, LoadResult::Type::TrackAvailable, stream_url); diff --git a/src/tidal/tidalbaserequest.cpp b/src/tidal/tidalbaserequest.cpp index fd25774832..81076b0f29 100644 --- a/src/tidal/tidalbaserequest.cpp +++ b/src/tidal/tidalbaserequest.cpp @@ -48,18 +48,18 @@ TidalBaseRequest::TidalBaseRequest(TidalService *service, SharedPtr"; + error_html += error + QStringLiteral("
"); } return error_html; diff --git a/src/tidal/tidalfavoriterequest.cpp b/src/tidal/tidalfavoriterequest.cpp index fd6b20fd89..66ec0de3a1 100644 --- a/src/tidal/tidalfavoriterequest.cpp +++ b/src/tidal/tidalfavoriterequest.cpp @@ -134,18 +134,18 @@ void TidalFavoriteRequest::AddFavorites(const FavoriteType type, const SongList void TidalFavoriteRequest::AddFavoritesRequest(const FavoriteType type, const QStringList &id_list, const SongList &songs) { - ParamList params = ParamList() << Param("countryCode", country_code()) - << Param(FavoriteMethod(type), id_list.join(',')); + ParamList params = ParamList() << Param(QStringLiteral("countryCode"), country_code()) + << Param(FavoriteMethod(type), id_list.join(QLatin1Char(','))); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } - QUrl url(QString(TidalService::kApiUrl) + QStringLiteral("/") + "users/" + QString::number(service_->user_id()) + "/favorites/" + FavoriteText(type)); + QUrl url(QString::fromLatin1(TidalService::kApiUrl) + QStringLiteral("/") + QStringLiteral("users/") + QString::number(service_->user_id()) + QStringLiteral("/favorites/") + FavoriteText(type)); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); if (oauth() && !access_token().isEmpty()) req.setRawHeader("authorization", "Bearer " + access_token().toUtf8()); else if (!session_id().isEmpty()) req.setRawHeader("X-Tidal-SessionId", session_id().toUtf8()); QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8(); @@ -244,18 +244,18 @@ void TidalFavoriteRequest::RemoveFavorites(const FavoriteType type, const SongLi void TidalFavoriteRequest::RemoveFavoritesRequest(const FavoriteType type, const QString &id, const SongList &songs) { - ParamList params = ParamList() << Param("countryCode", country_code()); + ParamList params = ParamList() << Param(QStringLiteral("countryCode"), country_code()); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } - QUrl url(QString(TidalService::kApiUrl) + QStringLiteral("/") + "users/" + QString::number(service_->user_id()) + "/favorites/" + FavoriteText(type) + QStringLiteral("/") + id); + QUrl url(QString::fromLatin1(TidalService::kApiUrl) + QStringLiteral("/users/") + QString::number(service_->user_id()) + QStringLiteral("/favorites/") + FavoriteText(type) + QStringLiteral("/") + id); url.setQuery(url_query); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); if (oauth() && !access_token().isEmpty()) req.setRawHeader("authorization", "Bearer " + access_token().toUtf8()); else if (!session_id().isEmpty()) req.setRawHeader("X-Tidal-SessionId", session_id().toUtf8()); QNetworkReply *reply = network_->deleteResource(req); diff --git a/src/tidal/tidalrequest.cpp b/src/tidal/tidalrequest.cpp index cbb13b66fa..f242e2cdbf 100644 --- a/src/tidal/tidalrequest.cpp +++ b/src/tidal/tidalrequest.cpp @@ -248,9 +248,9 @@ void TidalRequest::FlushArtistsRequests() { Request request = artists_requests_queue_.dequeue(); ParamList parameters; - if (query_type_ == QueryType::SearchArtists) parameters << Param("query", search_text_); - if (request.limit > 0) parameters << Param("limit", QString::number(request.limit)); - if (request.offset > 0) parameters << Param("offset", QString::number(request.offset)); + if (query_type_ == QueryType::SearchArtists) parameters << Param(QStringLiteral("query"), search_text_); + if (request.limit > 0) parameters << Param(QStringLiteral("limit"), QString::number(request.limit)); + if (request.offset > 0) parameters << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = nullptr; if (query_type_ == QueryType::Artists) { reply = CreateRequest(QStringLiteral("users/%1/favorites/artists").arg(service_->user_id()), parameters); @@ -296,9 +296,9 @@ void TidalRequest::FlushAlbumsRequests() { Request request = albums_requests_queue_.dequeue(); ParamList parameters; - if (query_type_ == QueryType::SearchAlbums) parameters << Param("query", search_text_); - if (request.limit > 0) parameters << Param("limit", QString::number(request.limit)); - if (request.offset > 0) parameters << Param("offset", QString::number(request.offset)); + if (query_type_ == QueryType::SearchAlbums) parameters << Param(QStringLiteral("query"), search_text_); + if (request.limit > 0) parameters << Param(QStringLiteral("limit"), QString::number(request.limit)); + if (request.offset > 0) parameters << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = nullptr; if (query_type_ == QueryType::Albums) { reply = CreateRequest(QStringLiteral("users/%1/favorites/albums").arg(service_->user_id()), parameters); @@ -344,9 +344,9 @@ void TidalRequest::FlushSongsRequests() { Request request = songs_requests_queue_.dequeue(); ParamList parameters; - if (query_type_ == QueryType::SearchSongs) parameters << Param("query", search_text_); - if (request.limit > 0) parameters << Param("limit", QString::number(request.limit)); - if (request.offset > 0) parameters << Param("offset", QString::number(request.offset)); + if (query_type_ == QueryType::SearchSongs) parameters << Param(QStringLiteral("query"), search_text_); + if (request.limit > 0) parameters << Param(QStringLiteral("limit"), QString::number(request.limit)); + if (request.offset > 0) parameters << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = nullptr; if (query_type_ == QueryType::Songs) { reply = CreateRequest(QStringLiteral("users/%1/favorites/tracks").arg(service_->user_id()), parameters); @@ -584,7 +584,7 @@ void TidalRequest::FlushArtistAlbumsRequests() { const ArtistAlbumsRequest request = artist_albums_requests_queue_.dequeue(); ParamList parameters; - if (request.offset > 0) parameters << Param("offset", QString::number(request.offset)); + if (request.offset > 0) parameters << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = CreateRequest(QStringLiteral("artists/%1/albums").arg(request.artist.artist_id), parameters); QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, request]() { ArtistAlbumsReplyReceived(reply, request.artist, request.offset); }); replies_ << reply; @@ -692,7 +692,7 @@ void TidalRequest::AlbumsReceived(QNetworkReply *reply, const Artist &artist_req if (service_->album_explicit() && obj_item.contains(QStringLiteral("explicit"))) { album.album_explicit = obj_item[QStringLiteral("explicit")].toVariant().toBool(); if (album.album_explicit && !album.album.isEmpty()) { - album.album.append(" (Explicit)"); + album.album.append(QStringLiteral(" (Explicit)")); } } } @@ -717,7 +717,7 @@ void TidalRequest::AlbumsReceived(QNetworkReply *reply, const Artist &artist_req if (service_->album_explicit() && obj_album.contains(QStringLiteral("explicit"))) { album.album_explicit = obj_album[QStringLiteral("explicit")].toVariant().toBool(); if (album.album_explicit && !album.album.isEmpty()) { - album.album.append(" (Explicit)"); + album.album.append(QStringLiteral(" (Explicit)")); } } } @@ -859,7 +859,7 @@ void TidalRequest::FlushAlbumSongsRequests() { AlbumSongsRequest request = album_songs_requests_queue_.dequeue(); ParamList parameters; - if (request.offset > 0) parameters << Param("offset", QString::number(request.offset)); + if (request.offset > 0) parameters << Param(QStringLiteral("offset"), QString::number(request.offset)); QNetworkReply *reply = CreateRequest(QStringLiteral("albums/%1/tracks").arg(request.album.album_id), parameters); replies_ << reply; QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, request]() { AlbumSongsReplyReceived(reply, request.artist, request.album, request.offset); }); @@ -1095,7 +1095,7 @@ void TidalRequest::ParseSong(Song &song, const QJsonObject &json_obj, const Arti return; } QString album_title = obj_album[QStringLiteral("title")].toString(); - if (album.album_explicit) album_title.append(" (Explicit)"); + if (album.album_explicit) album_title.append(QStringLiteral(" (Explicit)")); if (!allow_streaming) { Warn(QStringLiteral("Song %1 %2 %3 is not allowStreaming").arg(artist, album_title, title)); @@ -1125,7 +1125,7 @@ void TidalRequest::ParseSong(Song &song, const QJsonObject &json_obj, const Arti if (obj_album.contains(QStringLiteral("cover"))) { const QString cover = obj_album[QStringLiteral("cover")].toString().replace(QLatin1String("-"), QLatin1String("/")); if (!cover.isEmpty()) { - cover_url.setUrl(QStringLiteral("%1/images/%2/%3.jpg").arg(kResourcesUrl, cover, coversize_)); + cover_url.setUrl(QStringLiteral("%1/images/%2/%3.jpg").arg(QLatin1String(kResourcesUrl), cover, coversize_)); } } @@ -1277,8 +1277,8 @@ void TidalRequest::AlbumCoverReceived(QNetworkReply *reply, const QString &album } QString mimetype = reply->header(QNetworkRequest::ContentTypeHeader).toString(); - if (mimetype.contains(';')) { - mimetype = mimetype.left(mimetype.indexOf(';')); + if (mimetype.contains(QLatin1Char(';'))) { + mimetype = mimetype.left(mimetype.indexOf(QLatin1Char(';'))); } if (!ImageUtils::SupportedImageMimeTypes().contains(mimetype, Qt::CaseInsensitive) && !ImageUtils::SupportedImageFormats().contains(mimetype, Qt::CaseInsensitive)) { Error(QStringLiteral("Unsupported mimetype for image reader %1 for %2").arg(mimetype, url.toString())); @@ -1287,7 +1287,7 @@ void TidalRequest::AlbumCoverReceived(QNetworkReply *reply, const QString &album return; } - QByteArray data = reply->readAll(); + const QByteArray data = reply->readAll(); if (data.isEmpty()) { Error(QStringLiteral("Received empty image data for %1").arg(url.toString())); if (album_covers_requests_sent_.contains(album_id)) album_covers_requests_sent_.remove(album_id); diff --git a/src/tidal/tidalservice.cpp b/src/tidal/tidalservice.cpp index f0218c15f1..9a9d6281a7 100644 --- a/src/tidal/tidalservice.cpp +++ b/src/tidal/tidalservice.cpp @@ -48,6 +48,7 @@ #include "core/networkaccessmanager.h" #include "core/database.h" #include "core/song.h" +#include "core/settings.h" #include "utilities/randutils.h" #include "utilities/timeconstants.h" #include "internet/internetsearchview.h" @@ -69,25 +70,29 @@ const Song::Source TidalService::kSource = Song::Source::Tidal; const char TidalService::kApiUrl[] = "https://api.tidalhifi.com/v1"; const char TidalService::kResourcesUrl[] = "https://resources.tidal.com"; +const int TidalService::kLoginAttempts = 2; -constexpr char TidalService::kOAuthUrl[] = "https://login.tidal.com/authorize"; -constexpr char TidalService::kOAuthAccessTokenUrl[] = "https://login.tidal.com/oauth2/token"; -constexpr char TidalService::kOAuthRedirectUrl[] = "tidal://login/auth"; -constexpr char TidalService::kAuthUrl[] = "https://api.tidalhifi.com/v1/login/username"; +namespace { -const int TidalService::kLoginAttempts = 2; -constexpr int TidalService::kTimeResetLoginAttempts = 60000; +constexpr char kOAuthUrl[] = "https://login.tidal.com/authorize"; +constexpr char kOAuthAccessTokenUrl[] = "https://login.tidal.com/oauth2/token"; +constexpr char kOAuthRedirectUrl[] = "tidal://login/auth"; +constexpr char kAuthUrl[] = "https://api.tidalhifi.com/v1/login/username"; + +constexpr int kTimeResetLoginAttempts = 60000; -constexpr char TidalService::kArtistsSongsTable[] = "tidal_artists_songs"; -constexpr char TidalService::kAlbumsSongsTable[] = "tidal_albums_songs"; -constexpr char TidalService::kSongsTable[] = "tidal_songs"; +constexpr char kArtistsSongsTable[] = "tidal_artists_songs"; +constexpr char kAlbumsSongsTable[] = "tidal_albums_songs"; +constexpr char kSongsTable[] = "tidal_songs"; -constexpr char TidalService::kArtistsSongsFtsTable[] = "tidal_artists_songs_fts"; -constexpr char TidalService::kAlbumsSongsFtsTable[] = "tidal_albums_songs_fts"; -constexpr char TidalService::kSongsFtsTable[] = "tidal_songs_fts"; +constexpr char kArtistsSongsFtsTable[] = "tidal_artists_songs_fts"; +constexpr char kAlbumsSongsFtsTable[] = "tidal_albums_songs_fts"; +constexpr char kSongsFtsTable[] = "tidal_songs_fts"; + +} // namespace TidalService::TidalService(Application *app, QObject *parent) - : InternetService(Song::Source::Tidal, QStringLiteral("Tidal"), QStringLiteral("tidal"), TidalSettingsPage::kSettingsGroup, SettingsDialog::Page::Tidal, app, parent), + : InternetService(Song::Source::Tidal, QStringLiteral("Tidal"), QStringLiteral("tidal"), QLatin1String(TidalSettingsPage::kSettingsGroup), SettingsDialog::Page::Tidal, app, parent), app_(app), network_(app->network()), url_handler_(new TidalUrlHandler(app, this)), @@ -130,15 +135,15 @@ TidalService::TidalService(Application *app, QObject *parent) artists_collection_backend_ = make_shared(); artists_collection_backend_->moveToThread(app_->database()->thread()); - artists_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Tidal, kArtistsSongsTable, kArtistsSongsFtsTable); + artists_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Tidal, QLatin1String(kArtistsSongsTable), QLatin1String(kArtistsSongsFtsTable)); albums_collection_backend_ = make_shared(); albums_collection_backend_->moveToThread(app_->database()->thread()); - albums_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Tidal, kAlbumsSongsTable, kAlbumsSongsFtsTable); + albums_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Tidal, QLatin1String(kAlbumsSongsTable), QLatin1String(kAlbumsSongsFtsTable)); songs_collection_backend_ = make_shared(); songs_collection_backend_->moveToThread(app_->database()->thread()); - songs_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Tidal, kSongsTable, kSongsFtsTable); + songs_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Tidal, QLatin1String(kSongsTable), QLatin1String(kSongsFtsTable)); artists_collection_model_ = new CollectionModel(artists_collection_backend_, app_, this); albums_collection_model_ = new CollectionModel(albums_collection_backend_, app_, this); @@ -247,10 +252,10 @@ void TidalService::ShowConfig() { void TidalService::LoadSession() { - QSettings s; + Settings s; s.beginGroup(TidalSettingsPage::kSettingsGroup); user_id_ = s.value("user_id").toInt(); - country_code_ = s.value("country_code", "US").toString(); + country_code_ = s.value("country_code", QStringLiteral("US")).toString(); access_token_ = s.value("access_token").toString(); refresh_token_ = s.value("refresh_token").toString(); session_id_ = s.value("session_id").toString(); @@ -273,7 +278,7 @@ void TidalService::LoadSession() { void TidalService::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(TidalSettingsPage::kSettingsGroup); enabled_ = s.value("enabled", false).toBool(); @@ -286,13 +291,13 @@ void TidalService::ReloadSettings() { if (password.isEmpty()) password_.clear(); else password_ = QString::fromUtf8(QByteArray::fromBase64(password)); - quality_ = s.value("quality", "LOSSLESS").toString(); + quality_ = s.value("quality", QStringLiteral("LOSSLESS")).toString(); quint64 search_delay = s.value("searchdelay", 1500).toInt(); artistssearchlimit_ = s.value("artistssearchlimit", 4).toInt(); albumssearchlimit_ = s.value("albumssearchlimit", 10).toInt(); songssearchlimit_ = s.value("songssearchlimit", 10).toInt(); fetchalbums_ = s.value("fetchalbums", false).toBool(); - coversize_ = s.value("coversize", "640x640").toString(); + coversize_ = s.value("coversize", QStringLiteral("640x640")).toString(); download_album_covers_ = s.value("downloadalbumcovers", true).toBool(); stream_url_method_ = static_cast(s.value("streamurl", static_cast(TidalSettingsPage::StreamUrlMethod::StreamUrl)).toInt()); album_explicit_ = s.value("album_explicit").toBool(); @@ -307,25 +312,25 @@ void TidalService::StartAuthorization(const QString &client_id) { client_id_ = client_id; code_verifier_ = Utilities::CryptographicRandomString(44); - code_challenge_ = QString(QCryptographicHash::hash(code_verifier_.toUtf8(), QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding)); + code_challenge_ = QString::fromUtf8(QCryptographicHash::hash(code_verifier_.toUtf8(), QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding)); - if (code_challenge_.lastIndexOf(QChar('=')) == code_challenge_.length() - 1) { + if (code_challenge_.lastIndexOf(QLatin1Char('=')) == code_challenge_.length() - 1) { code_challenge_.chop(1); } - const ParamList params = ParamList() << Param("response_type", "code") - << Param("code_challenge", code_challenge_) - << Param("code_challenge_method", "S256") - << Param("redirect_uri", kOAuthRedirectUrl) - << Param("client_id", client_id_) - << Param("scope", "r_usr w_usr"); + const ParamList params = ParamList() << Param(QStringLiteral("response_type"), QStringLiteral("code")) + << Param(QStringLiteral("code_challenge"), code_challenge_) + << Param(QStringLiteral("code_challenge_method"), QStringLiteral("S256")) + << Param(QStringLiteral("redirect_uri"), QLatin1String(kOAuthRedirectUrl)) + << Param(QStringLiteral("client_id"), client_id_) + << Param(QStringLiteral("scope"), QStringLiteral("r_usr w_usr")); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } - QUrl url = QUrl(kOAuthUrl); + QUrl url = QUrl(QString::fromLatin1(kOAuthUrl)); url.setQuery(url_query); QDesktopServices::openUrl(url); @@ -339,15 +344,15 @@ void TidalService::AuthorizationUrlReceived(const QUrl &url) { if (url_query.hasQueryItem(QStringLiteral("token_type")) && url_query.hasQueryItem(QStringLiteral("expires_in")) && url_query.hasQueryItem(QStringLiteral("access_token"))) { - access_token_ = url_query.queryItemValue(QStringLiteral("access_token")).toUtf8(); + access_token_ = url_query.queryItemValue(QStringLiteral("access_token")); if (url_query.hasQueryItem(QStringLiteral("refresh_token"))) { - refresh_token_ = url_query.queryItemValue(QStringLiteral("refresh_token")).toUtf8(); + refresh_token_ = url_query.queryItemValue(QStringLiteral("refresh_token")); } expires_in_ = url_query.queryItemValue(QStringLiteral("expires_in")).toInt(); login_time_ = QDateTime::currentDateTime().toSecsSinceEpoch(); session_id_.clear(); - QSettings s; + Settings s; s.beginGroup(TidalSettingsPage::kSettingsGroup); s.setValue("access_token", access_token_); s.setValue("refresh_token", refresh_token_); @@ -379,18 +384,18 @@ void TidalService::RequestAccessToken(const QString &code) { timer_refresh_login_->stop(); - ParamList params = ParamList() << Param("client_id", client_id_); + ParamList params = ParamList() << Param(QStringLiteral("client_id"), client_id_); if (!code.isEmpty()) { - params << Param("grant_type", "authorization_code"); - params << Param("code", code); - params << Param("code_verifier", code_verifier_); - params << Param("redirect_uri", kOAuthRedirectUrl); - params << Param("scope", "r_usr w_usr"); + params << Param(QStringLiteral("grant_type"), QStringLiteral("authorization_code")); + params << Param(QStringLiteral("code"), code); + params << Param(QStringLiteral("code_verifier"), code_verifier_); + params << Param(QStringLiteral("redirect_uri"), QLatin1String(kOAuthRedirectUrl)); + params << Param(QStringLiteral("scope"), QStringLiteral("r_usr w_usr")); } else if (!refresh_token_.isEmpty() && enabled_ && oauth_) { - params << Param("grant_type", "refresh_token"); - params << Param("refresh_token", refresh_token_); + params << Param(QStringLiteral("grant_type"), QStringLiteral("refresh_token")); + params << Param(QStringLiteral("refresh_token"), refresh_token_); } else { return; @@ -398,13 +403,13 @@ void TidalService::RequestAccessToken(const QString &code) { QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } - QUrl url(kOAuthAccessTokenUrl); + QUrl url(QString::fromLatin1(kOAuthAccessTokenUrl)); QNetworkRequest req(url); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8(); + const QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8(); login_errors_.clear(); QNetworkReply *reply = network_->post(req, query); @@ -462,7 +467,7 @@ void TidalService::AccessTokenRequestFinished(QNetworkReply *reply) { } } - QByteArray data(reply->readAll()); + const QByteArray data = reply->readAll(); QJsonParseError json_error; QJsonDocument json_doc = QJsonDocument::fromJson(data, &json_error); @@ -509,7 +514,7 @@ void TidalService::AccessTokenRequestFinished(QNetworkReply *reply) { session_id_.clear(); - QSettings s; + Settings s; s.beginGroup(TidalSettingsPage::kSettingsGroup); s.setValue("access_token", access_token_); s.setValue("refresh_token", refresh_token_); @@ -543,20 +548,20 @@ void TidalService::SendLoginWithCredentials(const QString &api_token, const QStr timer_login_attempt_->start(); timer_refresh_login_->stop(); - const ParamList params = ParamList() << Param("token", (api_token.isEmpty() ? api_token_ : api_token)) - << Param("username", username) - << Param("password", password) - << Param("clientVersion", "2.2.1--7"); + const ParamList params = ParamList() << Param(QStringLiteral("token"), (api_token.isEmpty() ? api_token_ : api_token)) + << Param(QStringLiteral("username"), username) + << Param(QStringLiteral("password"), password) + << Param(QStringLiteral("clientVersion"), QStringLiteral("2.2.1--7")); QUrlQuery url_query; for (const Param ¶m : params) { - url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); + url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(param.first)), QString::fromLatin1(QUrl::toPercentEncoding(param.second))); } - QUrl url(kAuthUrl); + QUrl url(QString::fromLatin1(kAuthUrl)); QNetworkRequest req(url); - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded")); req.setRawHeader("X-Tidal-Token", (api_token.isEmpty() ? api_token_.toUtf8() : api_token.toUtf8())); QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8(); @@ -615,7 +620,7 @@ void TidalService::HandleAuthReply(QNetworkReply *reply) { login_errors_.clear(); - QByteArray data(reply->readAll()); + const QByteArray data = reply->readAll(); QJsonParseError json_error; QJsonDocument json_doc = QJsonDocument::fromJson(data, &json_error); @@ -651,7 +656,7 @@ void TidalService::HandleAuthReply(QNetworkReply *reply) { access_token_.clear(); refresh_token_.clear(); - QSettings s; + Settings s; s.beginGroup(TidalSettingsPage::kSettingsGroup); s.remove("access_token"); s.remove("refresh_token"); @@ -681,7 +686,7 @@ void TidalService::Logout() { expires_in_ = 0; login_time_ = 0; - QSettings s; + Settings s; s.beginGroup(TidalSettingsPage::kSettingsGroup); s.remove("user_id"); s.remove("country_code"); @@ -1026,7 +1031,7 @@ void TidalService::LoginError(const QString &error, const QVariant &debug) { QString error_html; for (const QString &e : login_errors_) { qLog(Error) << "Tidal:" << e; - error_html += e + "
"; + error_html += e + QStringLiteral("
"); } if (debug.isValid()) qLog(Debug) << debug; diff --git a/src/tidal/tidalservice.h b/src/tidal/tidalservice.h index bd02302e4e..11210086fd 100644 --- a/src/tidal/tidalservice.h +++ b/src/tidal/tidalservice.h @@ -65,6 +65,7 @@ class TidalService : public InternetService { static const Song::Source kSource; static const char kApiUrl[]; static const char kResourcesUrl[]; + static const int kLoginAttempts; void Exit() override; void ReloadSettings() override; @@ -159,22 +160,6 @@ class TidalService : public InternetService { void SendSearch(); void LoginError(const QString &error = QString(), const QVariant &debug = QVariant()); - static const char kOAuthUrl[]; - static const char kOAuthAccessTokenUrl[]; - static const char kOAuthRedirectUrl[]; - static const char kAuthUrl[]; - - static const int kLoginAttempts; - static const int kTimeResetLoginAttempts; - - static const char kArtistsSongsTable[]; - static const char kAlbumsSongsTable[]; - static const char kSongsTable[]; - - static const char kArtistsSongsFtsTable[]; - static const char kAlbumsSongsFtsTable[]; - static const char kSongsFtsTable[]; - Application *app_; SharedPtr network_; TidalUrlHandler *url_handler_; diff --git a/src/tidal/tidalstreamurlrequest.cpp b/src/tidal/tidalstreamurlrequest.cpp index 9dd53a579e..e2c1bc3b02 100644 --- a/src/tidal/tidalstreamurlrequest.cpp +++ b/src/tidal/tidalstreamurlrequest.cpp @@ -121,22 +121,22 @@ void TidalStreamURLRequest::GetStreamURL() { switch (stream_url_method()) { case TidalSettingsPage::StreamUrlMethod::StreamUrl: - params << Param("soundQuality", quality()); + params << Param(QStringLiteral("soundQuality"), quality()); reply_ = CreateRequest(QStringLiteral("tracks/%1/streamUrl").arg(song_id_), params); QObject::connect(reply_, &QNetworkReply::finished, this, &TidalStreamURLRequest::StreamURLReceived); break; case TidalSettingsPage::StreamUrlMethod::UrlPostPaywall: - params << Param("audioquality", quality()); - params << Param("playbackmode", "STREAM"); - params << Param("assetpresentation", "FULL"); - params << Param("urlusagemode", "STREAM"); + params << Param(QStringLiteral("audioquality"), quality()); + params << Param(QStringLiteral("playbackmode"), QStringLiteral("STREAM")); + params << Param(QStringLiteral("assetpresentation"), QStringLiteral("FULL")); + params << Param(QStringLiteral("urlusagemode"), QStringLiteral("STREAM")); reply_ = CreateRequest(QStringLiteral("tracks/%1/urlpostpaywall").arg(song_id_), params); QObject::connect(reply_, &QNetworkReply::finished, this, &TidalStreamURLRequest::StreamURLReceived); break; case TidalSettingsPage::StreamUrlMethod::PlaybackInfoPostPaywall: - params << Param("audioquality", quality()); - params << Param("playbackmode", "STREAM"); - params << Param("assetpresentation", "FULL"); + params << Param(QStringLiteral("audioquality"), quality()); + params << Param(QStringLiteral("playbackmode"), QStringLiteral("STREAM")); + params << Param(QStringLiteral("assetpresentation"), QStringLiteral("FULL")); reply_ = CreateRequest(QStringLiteral("tracks/%1/playbackinfopostpaywall").arg(song_id_), params); QObject::connect(reply_, &QNetworkReply::finished, this, &TidalStreamURLRequest::StreamURLReceived); break; @@ -233,7 +233,7 @@ void TidalStreamURLRequest::StreamURLReceived() { QString mimetype = json_obj[QStringLiteral("mimeType")].toString(); QMimeDatabase mimedb; - QStringList suffixes = mimedb.mimeTypeForName(mimetype.toUtf8()).suffixes(); + QStringList suffixes = mimedb.mimeTypeForName(mimetype).suffixes(); for (const QString &suffix : suffixes) { filetype = Song::FiletypeByExtension(suffix); if (filetype != Song::FileType::Unknown) break; diff --git a/src/transcoder/transcodedialog.cpp b/src/transcoder/transcodedialog.cpp index be20554ac7..914c6f821d 100644 --- a/src/transcoder/transcodedialog.cpp +++ b/src/transcoder/transcodedialog.cpp @@ -57,6 +57,7 @@ #include "core/iconloader.h" #include "core/mainwindow.h" +#include "core/settings.h" #include "utilities/screenutils.h" #include "widgets/fileview.h" #include "transcodedialog.h" @@ -71,8 +72,11 @@ #endif const char *TranscodeDialog::kSettingsGroup = "Transcoder"; -const int TranscodeDialog::kProgressInterval = 500; -const int TranscodeDialog::kMaxDestinationItems = 10; + +namespace { +constexpr int kProgressInterval = 500; +constexpr int kMaxDestinationItems = 10; +} static bool ComparePresetsByName(const TranscoderPreset &left, const TranscoderPreset &right) { return left.name_ < right.name_; @@ -107,11 +111,11 @@ TranscodeDialog::TranscodeDialog(QMainWindow *mainwindow, QWidget *parent) } // Load settings - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); last_add_dir_ = s.value("last_add_dir", QDir::homePath()).toString(); last_import_dir_ = s.value("last_import_dir", QDir::homePath()).toString(); - QString last_output_format = s.value("last_output_format", "audio/x-vorbis").toString(); + QString last_output_format = s.value("last_output_format", QStringLiteral("audio/x-vorbis")).toString(); s.endGroup(); for (int i = 0; i < ui_->format->count(); ++i) { @@ -186,7 +190,7 @@ void TranscodeDialog::reject() { void TranscodeDialog::LoadGeometry() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); if (s.contains("geometry")) { restoreGeometry(s.value("geometry").toByteArray()); @@ -200,7 +204,7 @@ void TranscodeDialog::LoadGeometry() { void TranscodeDialog::SaveGeometry() { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("geometry", saveGeometry()); s.endGroup(); @@ -253,7 +257,7 @@ void TranscodeDialog::Start() { transcoder_->Start(); // Save the last output format - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("last_output_format", preset.codec_mimetype_); s.endGroup(); @@ -299,15 +303,15 @@ void TranscodeDialog::UpdateStatusText() { QStringList sections; if (queued_) { - sections << "" + tr("%n remaining", "", queued_) + ""; + sections << QStringLiteral("") + tr("%n remaining", "", queued_) + QStringLiteral(""); } if (finished_success_) { - sections << "" + tr("%n finished", "", finished_success_) + ""; + sections << QStringLiteral("") + tr("%n finished", "", finished_success_) + QStringLiteral(""); } if (finished_failed_) { - sections << "" + tr("%n failed", "", finished_failed_) + ""; + sections << QStringLiteral("") + tr("%n failed", "", finished_failed_) + QStringLiteral(""); } ui_->progress_text->setText(sections.join(QStringLiteral(", "))); @@ -322,14 +326,14 @@ void TranscodeDialog::Add() { QStringList filenames = QFileDialog::getOpenFileNames( this, tr("Add files to transcode"), last_add_dir_, - QStringLiteral("%1 (%2);;%3").arg(tr("Music"), FileView::kFileFilter, tr(MainWindow::kAllFilesFilterSpec))); + QStringLiteral("%1 (%2);;%3").arg(tr("Music"), QLatin1String(FileView::kFileFilter), tr(MainWindow::kAllFilesFilterSpec))); if (filenames.isEmpty()) return; SetFilenames(filenames); last_add_dir_ = filenames[0]; - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("last_add_dir", last_add_dir_); s.endGroup(); @@ -345,9 +349,9 @@ void TranscodeDialog::Import() { QStringList filenames; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QStringList audioTypes = QString(FileView::kFileFilter).split(QStringLiteral(" "), Qt::SkipEmptyParts); + QStringList audioTypes = QString::fromLatin1(FileView::kFileFilter).split(QLatin1Char(' '), Qt::SkipEmptyParts); #else - QStringList audioTypes = QString(FileView::kFileFilter).split(" ", QString::SkipEmptyParts); + QStringList audioTypes = QString::fromLatin1(FileView::kFileFilter).split(QLatin1Char(' '), QString::SkipEmptyParts); #endif QDirIterator files(path, audioTypes, QDir::Files | QDir::Readable, QDirIterator::Subdirectories); @@ -359,7 +363,7 @@ void TranscodeDialog::Import() { SetFilenames(filenames); last_import_dir_ = path; - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("last_import_dir", last_import_dir_); s.endGroup(); @@ -369,8 +373,8 @@ void TranscodeDialog::Import() { void TranscodeDialog::SetFilenames(const QStringList &filenames) { for (const QString &filename : filenames) { - QString name = filename.section('/', -1, -1); - QString path = filename.section('/', 0, -2); + QString name = filename.section(QLatin1Char('/'), -1, -1); + QString path = filename.section(QLatin1Char('/'), 0, -2); QTreeWidgetItem *item = new QTreeWidgetItem(ui_->files, QStringList() << name << path); item->setData(0, Qt::UserRole, filename); @@ -438,7 +442,7 @@ void TranscodeDialog::AddDestination() { // Returns the rightmost non-empty part of 'path'. QString TranscodeDialog::TrimPath(const QString &path) { - return path.section('/', -1, -1, QString::SectionSkipEmpty); + return path.section(QLatin1Char('/'), -1, -1, QString::SectionSkipEmpty); } QString TranscodeDialog::GetOutputFileName(const QString &input_filepath, const TranscoderPreset &preset) const { @@ -447,12 +451,12 @@ QString TranscodeDialog::GetOutputFileName(const QString &input_filepath, const QString output_filepath; if (destination_path.isEmpty()) { // Keep the original path. - output_filepath = input_filepath.section('.', 0, -2) + '.' + preset.extension_; + output_filepath = input_filepath.section(QLatin1Char('.'), 0, -2) + QLatin1Char('.') + preset.extension_; } else { QString filename = TrimPath(input_filepath); - filename = filename.section('.', 0, -2); - output_filepath = destination_path + '/' + filename + '.' + preset.extension_; + filename = filename.section(QLatin1Char('.'), 0, -2); + output_filepath = destination_path + QLatin1Char('/') + filename + QLatin1Char('.') + preset.extension_; } if (output_filepath.isEmpty()) return QString(); diff --git a/src/transcoder/transcodedialog.h b/src/transcoder/transcodedialog.h index 0eee9eec87..ff7f2f6e98 100644 --- a/src/transcoder/transcodedialog.h +++ b/src/transcoder/transcodedialog.h @@ -49,8 +49,6 @@ class TranscodeDialog : public QDialog { ~TranscodeDialog() override; static const char *kSettingsGroup; - static const int kProgressInterval; - static const int kMaxDestinationItems; void SetFilenames(const QStringList &filenames); diff --git a/src/transcoder/transcoder.cpp b/src/transcoder/transcoder.cpp index 3eac9b9277..cbc213034e 100644 --- a/src/transcoder/transcoder.cpp +++ b/src/transcoder/transcoder.cpp @@ -45,6 +45,7 @@ #include "core/logging.h" #include "core/shared_ptr.h" #include "core/signalchecker.h" +#include "core/settings.h" #include "transcoder.h" using std::make_shared; @@ -94,7 +95,7 @@ GstElement *Transcoder::CreateElementForMimeType(const QString &element_type, co if (mime_type.isEmpty()) return nullptr; // HACK: Force mp4mux because it doesn't set any useful src caps - if (mime_type == "audio/mp4") { + if (mime_type == QStringLiteral("audio/mp4")) { emit LogLine(QStringLiteral("Using '%1' (rank %2)").arg(QStringLiteral("mp4mux")).arg(-1)); return CreateElement(QStringLiteral("mp4mux"), bin); } @@ -127,7 +128,7 @@ GstElement *Transcoder::CreateElementForMimeType(const QString &element_type, co if (intersection) { if (!gst_caps_is_empty(intersection)) { int rank = static_cast(gst_plugin_feature_get_rank(GST_PLUGIN_FEATURE(factory))); - QString name = GST_OBJECT_NAME(factory); + const QString name = QString::fromUtf8(GST_OBJECT_NAME(factory)); if (name.startsWith(QLatin1String("ffmux")) || name.startsWith(QLatin1String("ffenc"))) { rank = -1; // ffmpeg usually sucks @@ -152,7 +153,7 @@ GstElement *Transcoder::CreateElementForMimeType(const QString &element_type, co emit LogLine(QStringLiteral("Using '%1' (rank %2)").arg(best.name_).arg(best.rank_)); - if (best.name_ == "lamemp3enc") { + if (best.name_ == QStringLiteral("lamemp3enc")) { // Special case: we need to add xingmux and id3v2mux to the pipeline when using lamemp3enc because it doesn't write the VBR or ID3v2 headers itself. emit LogLine(QStringLiteral("Adding xingmux and id3v2mux to the pipeline")); @@ -212,8 +213,8 @@ Transcoder::Transcoder(QObject *parent, const QString &settings_postfix) JobFinishedEvent::sEventType = QEvent::registerEventType(); // Initialize some settings for the lamemp3enc element. - QSettings s; - s.beginGroup("Transcoder/lamemp3enc" + settings_postfix_); + Settings s; + s.beginGroup(QStringLiteral("Transcoder/lamemp3enc") + settings_postfix_); if (s.value("target").isNull()) { s.setValue("target", 1); // 1 == bitrate @@ -301,10 +302,10 @@ QString Transcoder::GetFile(const QString &input, const TranscoderPreset &preset if (!fileinfo_output.isFile() || fileinfo_output.filePath().isEmpty() || fileinfo_output.path().isEmpty() || fileinfo_output.fileName().isEmpty() || fileinfo_output.suffix().isEmpty()) { QFileInfo fileinfo_input(input); - QString temp_dir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/transcoder"; + QString temp_dir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/transcoder"); if (!QDir(temp_dir).exists()) QDir().mkpath(temp_dir); - QString filename = fileinfo_input.completeBaseName() + "." + preset.extension_; - fileinfo_output.setFile(temp_dir + "/" + filename); + QString filename = fileinfo_input.completeBaseName() + QLatin1Char('.') + preset.extension_; + fileinfo_output.setFile(temp_dir + QLatin1Char('/') + filename); } // Never overwrite existing files @@ -571,8 +572,8 @@ QMap Transcoder::GetProgress() const { void Transcoder::SetElementProperties(const QString &name, GObject *object) { - QSettings s; - s.beginGroup("Transcoder/" + name + settings_postfix_); + Settings s; + s.beginGroup(QStringLiteral("Transcoder/") + name + settings_postfix_); guint properties_count = 0; GParamSpec **properties = g_object_class_list_properties(G_OBJECT_GET_CLASS(object), &properties_count); @@ -580,16 +581,16 @@ void Transcoder::SetElementProperties(const QString &name, GObject *object) { for (uint i = 0; i < properties_count; ++i) { GParamSpec *property = properties[i]; - if (!s.contains(property->name)) { + if (!s.contains(QString::fromUtf8(property->name))) { continue; } - const QVariant value = s.value(property->name); + const QVariant value = s.value(QString::fromUtf8(property->name)); if (value.isNull()) { continue; } - emit LogLine(QStringLiteral("Setting %1 property: %2 = %3").arg(name, property->name, value.toString())); + emit LogLine(QStringLiteral("Setting %1 property: %2 = %3").arg(name, QString::fromUtf8(property->name), value.toString())); switch (property->value_type) { case G_TYPE_FLOAT:{ diff --git a/src/transcoder/transcoderoptionsaac.cpp b/src/transcoder/transcoderoptionsaac.cpp index a2646f3c4d..85fd4c06be 100644 --- a/src/transcoder/transcoderoptionsaac.cpp +++ b/src/transcoder/transcoderoptionsaac.cpp @@ -30,7 +30,11 @@ #include "transcoderoptionsaac.h" #include "ui_transcoderoptionsaac.h" -const char *TranscoderOptionsAAC::kSettingsGroup = "Transcoder/faac"; +#include "core/settings.h" + +namespace { +constexpr char kSettingsGroup[] = "Transcoder/faac"; +} TranscoderOptionsAAC::TranscoderOptionsAAC(QWidget *parent) : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsAAC) { ui_->setupUi(this); @@ -42,8 +46,8 @@ TranscoderOptionsAAC::~TranscoderOptionsAAC() { void TranscoderOptionsAAC::Load() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); ui_->bitrate_slider->setValue(s.value("bitrate", 320000).toInt() / 1000); ui_->profile->setCurrentIndex(s.value("profile", 2).toInt() - 1); ui_->tns->setChecked(s.value("tns", false).toBool()); @@ -55,8 +59,8 @@ void TranscoderOptionsAAC::Load() { void TranscoderOptionsAAC::Save() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); s.setValue("bitrate", ui_->bitrate_slider->value() * 1000); s.setValue("profile", ui_->profile->currentIndex() + 1); s.setValue("tns", ui_->tns->isChecked()); diff --git a/src/transcoder/transcoderoptionsaac.h b/src/transcoder/transcoderoptionsaac.h index e880166194..e367fee0c7 100644 --- a/src/transcoder/transcoderoptionsaac.h +++ b/src/transcoder/transcoderoptionsaac.h @@ -40,8 +40,6 @@ class TranscoderOptionsAAC : public TranscoderOptionsInterface { void Save() override; private: - static const char *kSettingsGroup; - Ui_TranscoderOptionsAAC *ui_; }; diff --git a/src/transcoder/transcoderoptionsasf.cpp b/src/transcoder/transcoderoptionsasf.cpp index 51a5fd4f6d..bd7b014089 100644 --- a/src/transcoder/transcoderoptionsasf.cpp +++ b/src/transcoder/transcoderoptionsasf.cpp @@ -25,11 +25,15 @@ #include #include -#include "transcoder/transcoderoptionsinterface.h" +#include "transcoderoptionsinterface.h" #include "transcoderoptionsasf.h" #include "ui_transcoderoptionsasf.h" -const char *TranscoderOptionsASF::kSettingsGroup = "Transcoder/ffenc_wmav2"; +#include "core/settings.h" + +namespace { +constexpr char kSettingsGroup[] = "Transcoder/ffenc_wmav2"; +} TranscoderOptionsASF::TranscoderOptionsASF(QWidget *parent) : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsASF) { ui_->setupUi(this); @@ -41,8 +45,8 @@ TranscoderOptionsASF::~TranscoderOptionsASF() { void TranscoderOptionsASF::Load() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); ui_->bitrate_slider->setValue(s.value("bitrate", 320000).toInt() / 1000); s.endGroup(); @@ -50,8 +54,8 @@ void TranscoderOptionsASF::Load() { void TranscoderOptionsASF::Save() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); s.setValue("bitrate", ui_->bitrate_slider->value() * 1000); s.endGroup(); diff --git a/src/transcoder/transcoderoptionsasf.h b/src/transcoder/transcoderoptionsasf.h index 4e297ba9bf..4a1e0a7111 100644 --- a/src/transcoder/transcoderoptionsasf.h +++ b/src/transcoder/transcoderoptionsasf.h @@ -40,8 +40,6 @@ class TranscoderOptionsASF : public TranscoderOptionsInterface { void Save() override; private: - static const char *kSettingsGroup; - Ui_TranscoderOptionsASF *ui_; }; diff --git a/src/transcoder/transcoderoptionsdialog.cpp b/src/transcoder/transcoderoptionsdialog.cpp index ebbb59c39f..b9691e766b 100644 --- a/src/transcoder/transcoderoptionsdialog.cpp +++ b/src/transcoder/transcoderoptionsdialog.cpp @@ -61,7 +61,7 @@ TranscoderOptionsDialog::TranscoderOptionsDialog(Song::FileType type, QWidget *p } if (options_) { - setWindowTitle(windowTitle() + " - " + Song::TextForFiletype(type)); + setWindowTitle(windowTitle() + QStringLiteral(" - ") + Song::TextForFiletype(type)); options_->layout()->setContentsMargins(0, 0, 0, 0); ui_->verticalLayout->insertWidget(0, options_); resize(width(), minimumHeight()); diff --git a/src/transcoder/transcoderoptionsflac.cpp b/src/transcoder/transcoderoptionsflac.cpp index 5c6e5f2b70..fc6293f61f 100644 --- a/src/transcoder/transcoderoptionsflac.cpp +++ b/src/transcoder/transcoderoptionsflac.cpp @@ -29,7 +29,11 @@ #include "transcoderoptionsflac.h" #include "ui_transcoderoptionsflac.h" -const char *TranscoderOptionsFLAC::kSettingsGroup = "Transcoder/flacenc"; +#include "core/settings.h" + +namespace { +constexpr char kSettingsGroup[] = "Transcoder/flacenc"; +} TranscoderOptionsFLAC::TranscoderOptionsFLAC(QWidget *parent) : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsFLAC) { ui_->setupUi(this); @@ -41,8 +45,8 @@ TranscoderOptionsFLAC::~TranscoderOptionsFLAC() { void TranscoderOptionsFLAC::Load() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); ui_->quality->setValue(s.value("quality", 5).toInt()); s.endGroup(); @@ -50,8 +54,8 @@ void TranscoderOptionsFLAC::Load() { void TranscoderOptionsFLAC::Save() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); s.setValue("quality", ui_->quality->value()); s.endGroup(); diff --git a/src/transcoder/transcoderoptionsflac.h b/src/transcoder/transcoderoptionsflac.h index 3f77ec65c3..98f1097581 100644 --- a/src/transcoder/transcoderoptionsflac.h +++ b/src/transcoder/transcoderoptionsflac.h @@ -40,8 +40,6 @@ class TranscoderOptionsFLAC : public TranscoderOptionsInterface { void Save() override; private: - static const char *kSettingsGroup; - Ui_TranscoderOptionsFLAC *ui_; }; diff --git a/src/transcoder/transcoderoptionsmp3.cpp b/src/transcoder/transcoderoptionsmp3.cpp index 4cee0893f9..398d6e6503 100644 --- a/src/transcoder/transcoderoptionsmp3.cpp +++ b/src/transcoder/transcoderoptionsmp3.cpp @@ -33,7 +33,11 @@ #include "transcoderoptionsmp3.h" #include "ui_transcoderoptionsmp3.h" -const char *TranscoderOptionsMP3::kSettingsGroup = "Transcoder/lamemp3enc"; +#include "core/settings.h" + +namespace { +constexpr char kSettingsGroup[] = "Transcoder/lamemp3enc"; +} TranscoderOptionsMP3::TranscoderOptionsMP3(QWidget *parent) : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsMP3) { @@ -50,8 +54,8 @@ TranscoderOptionsMP3::~TranscoderOptionsMP3() { void TranscoderOptionsMP3::Load() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); if (s.value("target", 1).toInt() == 0) { ui_->target_quality->setChecked(true); @@ -72,8 +76,8 @@ void TranscoderOptionsMP3::Load() { void TranscoderOptionsMP3::Save() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); s.setValue("target", ui_->target_quality->isChecked() ? 0 : 1); s.setValue("quality", ui_->quality_spinbox->value()); diff --git a/src/transcoder/transcoderoptionsmp3.h b/src/transcoder/transcoderoptionsmp3.h index b36604372e..be233f4bac 100644 --- a/src/transcoder/transcoderoptionsmp3.h +++ b/src/transcoder/transcoderoptionsmp3.h @@ -46,8 +46,6 @@ class TranscoderOptionsMP3 : public TranscoderOptionsInterface { void QualitySpinboxChanged(const double value); private: - static const char *kSettingsGroup; - Ui_TranscoderOptionsMP3 *ui_; }; diff --git a/src/transcoder/transcoderoptionsopus.cpp b/src/transcoder/transcoderoptionsopus.cpp index ae9c397351..4e35ad59cd 100644 --- a/src/transcoder/transcoderoptionsopus.cpp +++ b/src/transcoder/transcoderoptionsopus.cpp @@ -29,9 +29,13 @@ #include "transcoderoptionsopus.h" #include "ui_transcoderoptionsopus.h" +#include "core/settings.h" + // TODO: Add more options than only bitrate as soon as gst doesn't crash anymore while using the cbr parameter (like cbr=false) -const char *TranscoderOptionsOpus::kSettingsGroup = "Transcoder/opusenc"; +namespace { +constexpr char kSettingsGroup[] = "Transcoder/opusenc"; +} TranscoderOptionsOpus::TranscoderOptionsOpus(QWidget *parent) : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsOpus) { ui_->setupUi(this); @@ -43,8 +47,8 @@ TranscoderOptionsOpus::~TranscoderOptionsOpus() { void TranscoderOptionsOpus::Load() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); ui_->bitrate_slider->setValue(s.value("bitrate", 320000).toInt() / 1000); s.endGroup(); @@ -52,8 +56,8 @@ void TranscoderOptionsOpus::Load() { void TranscoderOptionsOpus::Save() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); s.setValue("bitrate", ui_->bitrate_slider->value() * 1000); s.endGroup(); diff --git a/src/transcoder/transcoderoptionsopus.h b/src/transcoder/transcoderoptionsopus.h index b85137eefc..3f9ab3761a 100644 --- a/src/transcoder/transcoderoptionsopus.h +++ b/src/transcoder/transcoderoptionsopus.h @@ -40,8 +40,6 @@ class TranscoderOptionsOpus : public TranscoderOptionsInterface { void Save() override; private: - static const char *kSettingsGroup; - Ui_TranscoderOptionsOpus *ui_; }; diff --git a/src/transcoder/transcoderoptionsspeex.cpp b/src/transcoder/transcoderoptionsspeex.cpp index 2c15fbb85f..2aee551010 100644 --- a/src/transcoder/transcoderoptionsspeex.cpp +++ b/src/transcoder/transcoderoptionsspeex.cpp @@ -32,7 +32,11 @@ #include "transcoderoptionsspeex.h" #include "ui_transcoderoptionsspeex.h" -const char *TranscoderOptionsSpeex::kSettingsGroup = "Transcoder/speexenc"; +#include "core/settings.h" + +namespace { +constexpr char kSettingsGroup[] = "Transcoder/speexenc"; +} TranscoderOptionsSpeex::TranscoderOptionsSpeex(QWidget *parent) : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsSpeex) { ui_->setupUi(this); @@ -44,8 +48,8 @@ TranscoderOptionsSpeex::~TranscoderOptionsSpeex() { void TranscoderOptionsSpeex::Load() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); ui_->quality_slider->setValue(s.value("quality", 10).toInt()); ui_->bitrate_slider->setValue(s.value("bitrate", 0).toInt() / 1000); @@ -63,8 +67,8 @@ void TranscoderOptionsSpeex::Load() { void TranscoderOptionsSpeex::Save() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); s.setValue("quality", ui_->quality_slider->value()); s.setValue("bitrate", ui_->bitrate_slider->value() * 1000); diff --git a/src/transcoder/transcoderoptionsspeex.h b/src/transcoder/transcoderoptionsspeex.h index 3e2bd907e3..64ccf0bf34 100644 --- a/src/transcoder/transcoderoptionsspeex.h +++ b/src/transcoder/transcoderoptionsspeex.h @@ -40,8 +40,6 @@ class TranscoderOptionsSpeex : public TranscoderOptionsInterface { void Save() override; private: - static const char *kSettingsGroup; - Ui_TranscoderOptionsSpeex *ui_; }; diff --git a/src/transcoder/transcoderoptionsvorbis.cpp b/src/transcoder/transcoderoptionsvorbis.cpp index 0c7e0d7505..5f081d42b6 100644 --- a/src/transcoder/transcoderoptionsvorbis.cpp +++ b/src/transcoder/transcoderoptionsvorbis.cpp @@ -30,7 +30,11 @@ #include "transcoderoptionsvorbis.h" #include "ui_transcoderoptionsvorbis.h" -const char *TranscoderOptionsVorbis::kSettingsGroup = "Transcoder/vorbisenc"; +#include "core/settings.h" + +namespace { +constexpr char kSettingsGroup[] = "Transcoder/vorbisenc"; +} TranscoderOptionsVorbis::TranscoderOptionsVorbis(QWidget *parent) : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsVorbis) { ui_->setupUi(this); @@ -42,8 +46,8 @@ TranscoderOptionsVorbis::~TranscoderOptionsVorbis() { void TranscoderOptionsVorbis::Load() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); int bitrate = s.value("bitrate", -1).toInt(); bitrate = bitrate == -1 ? 0 : bitrate / 1000; @@ -66,8 +70,8 @@ void TranscoderOptionsVorbis::Load() { void TranscoderOptionsVorbis::Save() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); int bitrate = ui_->bitrate_slider->value(); bitrate = bitrate == 0 ? -1 : bitrate * 1000; diff --git a/src/transcoder/transcoderoptionsvorbis.h b/src/transcoder/transcoderoptionsvorbis.h index 44a436a8f9..c4bacc6130 100644 --- a/src/transcoder/transcoderoptionsvorbis.h +++ b/src/transcoder/transcoderoptionsvorbis.h @@ -40,8 +40,6 @@ class TranscoderOptionsVorbis : public TranscoderOptionsInterface { void Save() override; private: - static const char *kSettingsGroup; - Ui_TranscoderOptionsVorbis *ui_; }; diff --git a/src/transcoder/transcoderoptionswavpack.cpp b/src/transcoder/transcoderoptionswavpack.cpp index 00a882979b..c3c4d25eb7 100644 --- a/src/transcoder/transcoderoptionswavpack.cpp +++ b/src/transcoder/transcoderoptionswavpack.cpp @@ -27,7 +27,11 @@ #include "transcoderoptionswavpack.h" #include "ui_transcoderoptionswavpack.h" -const char *TranscoderOptionsWavPack::kSettingsGroup = "Transcoder/wavpackenc"; +#include "core/settings.h" + +namespace { +constexpr char kSettingsGroup[] = "Transcoder/wavpackenc"; +} TranscoderOptionsWavPack::TranscoderOptionsWavPack(QWidget *parent) : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsWavPack) { ui_->setupUi(this); @@ -39,16 +43,16 @@ TranscoderOptionsWavPack::~TranscoderOptionsWavPack() { void TranscoderOptionsWavPack::Load() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); s.endGroup(); } void TranscoderOptionsWavPack::Save() { - QSettings s; - s.beginGroup(kSettingsGroup + settings_postfix_); + Settings s; + s.beginGroup(QLatin1String(kSettingsGroup) + settings_postfix_); s.endGroup(); } diff --git a/src/transcoder/transcoderoptionswavpack.h b/src/transcoder/transcoderoptionswavpack.h index d361a23fea..75eaedc4fe 100644 --- a/src/transcoder/transcoderoptionswavpack.h +++ b/src/transcoder/transcoderoptionswavpack.h @@ -39,8 +39,6 @@ class TranscoderOptionsWavPack : public TranscoderOptionsInterface { void Save() override; private: - static const char *kSettingsGroup; - Ui_TranscoderOptionsWavPack *ui_; }; diff --git a/src/utilities/coverutils.cpp b/src/utilities/coverutils.cpp index 5b1bffa6cb..1ce21e48f3 100644 --- a/src/utilities/coverutils.cpp +++ b/src/utilities/coverutils.cpp @@ -43,18 +43,18 @@ QByteArray CoverUtils::Sha1CoverHash(const QString &artist, const QString &album QString CoverUtils::AlbumCoverFilename(QString artist, QString album, const QString &extension) { - artist.remove('/').remove('\\'); - album.remove('/').remove('\\'); + artist.remove(QLatin1Char('/')).remove(QLatin1Char('\\')); + album.remove(QLatin1Char('/')).remove(QLatin1Char('\\')); - QString filename = artist + "-" + album; + QString filename = artist + QStringLiteral("-") + album; filename = Utilities::Transliterate(filename.toLower()); - filename = filename.replace(' ', '-') + filename = filename.replace(QLatin1Char(' '), QLatin1Char('-')) .replace(QLatin1String("--"), QLatin1String("-")) - .remove(QRegularExpression(QString(kInvalidFatCharactersRegex), QRegularExpression::CaseInsensitiveOption)) + .remove(QRegularExpression(QLatin1String(kInvalidFatCharactersRegex), QRegularExpression::CaseInsensitiveOption)) .simplified(); if (!extension.isEmpty()) { - filename.append('.'); + filename.append(QLatin1Char('.')); filename.append(extension); } @@ -76,7 +76,7 @@ QString CoverUtils::CoverFilePath(const CoverOptions &options, const Song::Sourc path = Song::ImageCacheDir(source); } - if (path.right(1) == QDir::separator() || path.right(1) == "/") { + if (path.right(1) == QDir::separator() || path.right(1) == QLatin1String("/")) { path.chop(1); } @@ -92,11 +92,11 @@ QString CoverUtils::CoverFilePath(const CoverOptions &options, const Song::Sourc options.cover_filename == CoverOptions::CoverFilename::Pattern && !options.cover_pattern.isEmpty()) { filename = CoverFilenameFromVariable(options, artist, album); - filename.remove(QRegularExpression(QString(kInvalidFatCharactersRegex), QRegularExpression::CaseInsensitiveOption)).remove('/').remove('\\'); + filename.remove(QRegularExpression(QLatin1String(kInvalidFatCharactersRegex), QRegularExpression::CaseInsensitiveOption)).remove(QLatin1Char('/')).remove(QLatin1Char('\\')); if (options.cover_lowercase) filename = filename.toLower(); if (options.cover_replace_spaces) filename.replace(QRegularExpression(QStringLiteral("\\s")), QStringLiteral("-")); if (!extension.isEmpty()) { - filename.append('.'); + filename.append(QLatin1Char('.')); filename.append(extension); } } @@ -105,7 +105,7 @@ QString CoverUtils::CoverFilePath(const CoverOptions &options, const Song::Sourc filename = CoverFilenameFromSource(source, cover_url, artist, album, album_id, extension); } - QString filepath(path + "/" + filename); + QString filepath(path + QStringLiteral("/") + filename); return filepath; @@ -118,7 +118,7 @@ QString CoverUtils::CoverFilenameFromSource(const Song::Source source, const QUr switch (source) { case Song::Source::Tidal: if (!album_id.isEmpty()) { - filename = album_id + "-" + cover_url.fileName(); + filename = album_id + QStringLiteral("-") + cover_url.fileName(); break; } [[fallthrough]]; @@ -137,12 +137,12 @@ QString CoverUtils::CoverFilenameFromSource(const Song::Source source, const QUr case Song::Source::SomaFM: case Song::Source::RadioParadise: case Song::Source::Unknown: - filename = Sha1CoverHash(artist, album).toHex(); + filename = QString::fromUtf8(Sha1CoverHash(artist, album).toHex()); break; } if (!extension.isEmpty()) { - filename.append('.'); + filename.append(QLatin1Char('.')); filename.append(extension); } @@ -159,7 +159,7 @@ QString CoverUtils::CoverFilenameFromVariable(const CoverOptions &options, const filename.replace(QLatin1String("%artist"), artist); filename.replace(QLatin1String("%album"), album); if (!extension.isEmpty()) { - filename.append('.'); + filename.append(QLatin1Char('.')); filename.append(extension); } return filename; diff --git a/src/utilities/envutils.cpp b/src/utilities/envutils.cpp index f93173cf06..3f84075bc1 100644 --- a/src/utilities/envutils.cpp +++ b/src/utilities/envutils.cpp @@ -52,19 +52,19 @@ QString DesktopEnvironment() { if (!qEnvironmentVariableIsEmpty("GNOME_DESKTOP_SESSION_ID")) return QStringLiteral("Gnome"); QString session = GetEnv(QStringLiteral("DESKTOP_SESSION")); - qint64 slash = session.lastIndexOf('/'); + qint64 slash = session.lastIndexOf(QLatin1Char('/')); if (slash != -1) { QSettings desktop_file(QStringLiteral("%1.desktop").arg(session), QSettings::IniFormat); - desktop_file.beginGroup("Desktop Entry"); - QString name = desktop_file.value("DesktopNames").toString(); + desktop_file.beginGroup(QStringLiteral("Desktop Entry")); + QString name = desktop_file.value(QStringLiteral("DesktopNames")).toString(); desktop_file.endGroup(); if (!name.isEmpty()) return name; session = session.mid(slash + 1); } - if (session == "kde") return QStringLiteral("KDE"); - else if (session == "gnome") return QStringLiteral("Gnome"); - else if (session == "xfce") return QStringLiteral("XFCE"); + if (session == QStringLiteral("kde")) return QStringLiteral("KDE"); + else if (session == QStringLiteral("gnome")) return QStringLiteral("Gnome"); + else if (session == QStringLiteral("xfce")) return QStringLiteral("XFCE"); return QStringLiteral("Unknown"); diff --git a/src/utilities/filemanagerutils.cpp b/src/utilities/filemanagerutils.cpp index 2ea60ab9b9..679a8a92a0 100644 --- a/src/utilities/filemanagerutils.cpp +++ b/src/utilities/filemanagerutils.cpp @@ -46,11 +46,11 @@ void OpenInFileManager(const QString &path, const QUrl &url) { #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) proc.startCommand(QStringLiteral("xdg-mime query default inode/directory")); #else - proc.start("xdg-mime", QStringList() << "query" << "default" << "inode/directory"); + proc.start(QStringLiteral("xdg-mime"), QStringList() << QStringLiteral("query") << QStringLiteral("default") << QStringLiteral("inode/directory")); #endif proc.waitForFinished(); - QString desktop_file = proc.readLine().simplified(); - QString xdg_data_dirs = QString(qgetenv("XDG_DATA_DIRS")); + QString desktop_file = QString::fromUtf8(proc.readLine()).simplified(); + QString xdg_data_dirs = QString::fromUtf8(qgetenv("XDG_DATA_DIRS")); if (xdg_data_dirs.isEmpty()) { xdg_data_dirs = QStringLiteral("/usr/local/share/:/usr/share/"); } @@ -62,15 +62,15 @@ void OpenInFileManager(const QString &path, const QUrl &url) { QString desktop_file_path = QStringLiteral("%1/applications/%2").arg(data_dir, desktop_file); if (!QFile::exists(desktop_file_path)) continue; QSettings setting(desktop_file_path, QSettings::IniFormat); - setting.beginGroup("Desktop Entry"); - if (setting.contains("Exec")) { - QString cmd = setting.value("Exec").toString(); + setting.beginGroup(QStringLiteral("Desktop Entry")); + if (setting.contains(QStringLiteral("Exec"))) { + QString cmd = setting.value(QStringLiteral("Exec")).toString(); if (cmd.isEmpty()) break; cmd = cmd.remove(QRegularExpression(QStringLiteral("[%][a-zA-Z]*( |$)"), QRegularExpression::CaseInsensitiveOption)); # if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - command_params = cmd.split(' ', Qt::SkipEmptyParts); + command_params = cmd.split(QLatin1Char(' '), Qt::SkipEmptyParts); # else - command_params = cmd.split(' ', QString::SkipEmptyParts); + command_params = cmd.split(QLatin1Char(' '), QString::SkipEmptyParts); # endif command = command_params.first(); command_params.removeFirst(); @@ -83,7 +83,7 @@ void OpenInFileManager(const QString &path, const QUrl &url) { command = command.split(QStringLiteral("/")).last(); } - if (command.isEmpty() || command == "exo-open") { + if (command.isEmpty() || command == QStringLiteral("exo-open")) { QDesktopServices::openUrl(QUrl::fromLocalFile(path)); } else if (command.startsWith(QLatin1String("nautilus"))) { diff --git a/src/utilities/fileutils.cpp b/src/utilities/fileutils.cpp index af044be0c0..a159210ec5 100644 --- a/src/utilities/fileutils.cpp +++ b/src/utilities/fileutils.cpp @@ -86,21 +86,21 @@ bool Copy(QIODevice *source, QIODevice *destination) { bool CopyRecursive(const QString &source, const QString &destination) { // Make the destination directory - QString dir_name = source.section('/', -1, -1); - QString dest_path = destination + "/" + dir_name; + QString dir_name = source.section(QLatin1Char('/'), -1, -1); + QString dest_path = destination + QLatin1Char('/') + dir_name; QDir().mkpath(dest_path); QDir dir(source); for (const QString &child : dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs)) { - if (!CopyRecursive(source + "/" + child, dest_path)) { - qLog(Warning) << "Failed to copy dir" << source + "/" + child << "to" << dest_path; + if (!CopyRecursive(source + QLatin1Char('/') + child, dest_path)) { + qLog(Warning) << "Failed to copy dir" << source + QLatin1Char('/') + child << "to" << dest_path; return false; } } for (const QString &child : dir.entryList(QDir::NoDotAndDotDot | QDir::Files)) { - if (!QFile::copy(source + "/" + child, dest_path + "/" + child)) { - qLog(Warning) << "Failed to copy file" << source + "/" + child << "to" << dest_path; + if (!QFile::copy(source + QLatin1Char('/') + child, dest_path + QLatin1Char('/') + child)) { + qLog(Warning) << "Failed to copy file" << source + QLatin1Char('/') + child << "to" << dest_path; return false; } } @@ -112,13 +112,13 @@ bool RemoveRecursive(const QString &path) { QDir dir(path); for (const QString &child : dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden)) { - if (!RemoveRecursive(path + "/" + child)) { + if (!RemoveRecursive(path + QLatin1Char('/') + child)) { return false; } } for (const QString &child : dir.entryList(QDir::NoDotAndDotDot | QDir::Files | QDir::Hidden)) { - if (!QFile::remove(path + "/" + child)) { + if (!QFile::remove(path + QLatin1Char('/') + child)) { return false; } } diff --git a/src/utilities/imageutils.cpp b/src/utilities/imageutils.cpp index 7763a40cf6..992dbdb4e2 100644 --- a/src/utilities/imageutils.cpp +++ b/src/utilities/imageutils.cpp @@ -38,7 +38,7 @@ QStringList ImageUtils::SupportedImageMimeTypes() { if (kSupportedImageMimeTypes.isEmpty()) { for (const QByteArray &mimetype : QImageReader::supportedMimeTypes()) { - kSupportedImageMimeTypes << mimetype; + kSupportedImageMimeTypes << QString::fromUtf8(mimetype); } } @@ -50,7 +50,7 @@ QStringList ImageUtils::SupportedImageFormats() { if (kSupportedImageFormats.isEmpty()) { for (const QByteArray &filetype : QImageReader::supportedImageFormats()) { - kSupportedImageFormats << filetype; + kSupportedImageFormats << QString::fromUtf8(filetype); } } @@ -78,7 +78,7 @@ QByteArray ImageUtils::FileToJpegData(const QString &filename) { if (filename.isEmpty()) return QByteArray(); QByteArray image_data = Utilities::ReadDataFromFile(filename); - if (Utilities::MimeTypeFromData(image_data) == "image/jpeg") return image_data; + if (Utilities::MimeTypeFromData(image_data) == QStringLiteral("image/jpeg")) return image_data; else { QImage image; if (image.loadFromData(image_data)) { diff --git a/src/utilities/macaddrutils.cpp b/src/utilities/macaddrutils.cpp index 4f380614a4..e19dde3932 100644 --- a/src/utilities/macaddrutils.cpp +++ b/src/utilities/macaddrutils.cpp @@ -31,7 +31,7 @@ QString MacAddress() { for (QNetworkInterface &netif : QNetworkInterface::allInterfaces()) { if ( - (netif.hardwareAddress() == "00:00:00:00:00:00") || + (netif.hardwareAddress() == QStringLiteral("00:00:00:00:00:00")) || (netif.flags() & QNetworkInterface::IsLoopBack) || !(netif.flags() & QNetworkInterface::IsUp) || !(netif.flags() & QNetworkInterface::IsRunning) diff --git a/src/utilities/searchparserutils.cpp b/src/utilities/searchparserutils.cpp index 1380ac9a47..813f7cc9d0 100644 --- a/src/utilities/searchparserutils.cpp +++ b/src/utilities/searchparserutils.cpp @@ -49,7 +49,7 @@ int ParseSearchTime(const QString &time_str) { if (c.isDigit()) { accum = accum * 10 + c.digitValue(); } - else if (c == ':') { + else if (c == QLatin1Char(':')) { seconds = seconds * 60 + accum; accum = 0; ++colon_count; @@ -89,7 +89,7 @@ float ParseSearchRating(const QString &rating_str) { } // check if the search is a float - else if (rating_str.at(0) == 'f') { + else if (rating_str.at(0) == QLatin1Char('f')) { QString rating_float = rating_str; rating_float = rating_float.remove(0, 1); diff --git a/src/utilities/strutils.cpp b/src/utilities/strutils.cpp index 9d03a6c920..6bdc774398 100644 --- a/src/utilities/strutils.cpp +++ b/src/utilities/strutils.cpp @@ -35,7 +35,7 @@ QString PrettySize(const quint64 bytes) { if (bytes > 0) { if (bytes <= 1000) { - ret = QString::number(bytes) + " bytes"; + ret = QString::number(bytes) + QStringLiteral(" bytes"); } else if (bytes <= 1000 * 1000) { ret = QString::asprintf("%.1f KB", static_cast(bytes) / 1000.0F); @@ -52,16 +52,16 @@ QString PrettySize(const quint64 bytes) { } QString PrettySize(const QSize size) { - return QString::number(size.width()) + "x" + QString::number(size.height()); + return QString::number(size.width()) + QLatin1Char('x') + QString::number(size.height()); } QString PathWithoutFilenameExtension(const QString &filename) { - if (filename.section('/', -1, -1).contains('.')) return filename.section('.', 0, -2); + if (filename.section(QLatin1Char('/'), -1, -1).contains(QLatin1Char('.'))) return filename.section(QLatin1Char('.'), 0, -2); return filename; } QString FiddleFileExtension(const QString &filename, const QString &new_extension) { - return PathWithoutFilenameExtension(filename) + "." + new_extension; + return PathWithoutFilenameExtension(filename) + QLatin1Char('.') + new_extension; } const char *EnumToString(const QMetaObject &meta, const char *name, const int value) { @@ -86,7 +86,7 @@ QStringList Prepend(const QString &text, const QStringList &list) { QStringList Updateify(const QStringList &list) { QStringList ret(list); - for (int i = 0; i < ret.count(); ++i) ret[i].prepend(ret[i] + " = :"); + for (int i = 0; i < ret.count(); ++i) ret[i].prepend(ret[i] + QStringLiteral(" = :")); return ret; } @@ -136,61 +136,61 @@ QString ReplaceVariable(const QString &variable, const Song &song, const QString QString value = variable; - if (variable == "%title%") { + if (variable == QStringLiteral("%title%")) { value = song.PrettyTitle(); } - else if (variable == "%album%") { + else if (variable == QStringLiteral("%album%")) { value = song.album(); } - else if (variable == "%artist%") { + else if (variable == QStringLiteral("%artist%")) { value = song.artist(); } - else if (variable == "%albumartist%") { + else if (variable == QStringLiteral("%albumartist%")) { value = song.effective_albumartist(); } - else if (variable == "%track%") { + else if (variable == QStringLiteral("%track%")) { value.setNum(song.track()); } - else if (variable == "%disc%") { + else if (variable == QStringLiteral("%disc%")) { value.setNum(song.disc()); } - else if (variable == "%year%") { + else if (variable == QStringLiteral("%year%")) { value = song.PrettyYear(); } - else if (variable == "%originalyear%") { + else if (variable == QStringLiteral("%originalyear%")) { value = song.PrettyOriginalYear(); } - else if (variable == "%genre%") { + else if (variable == QStringLiteral("%genre%")) { value = song.genre(); } - else if (variable == "%composer%") { + else if (variable == QStringLiteral("%composer%")) { value = song.composer(); } - else if (variable == "%performer%") { + else if (variable == QStringLiteral("%performer%")) { value = song.performer(); } - else if (variable == "%grouping%") { + else if (variable == QStringLiteral("%grouping%")) { value = song.grouping(); } - else if (variable == "%length%") { + else if (variable == QStringLiteral("%length%")) { value = song.PrettyLength(); } - else if (variable == "%filename%") { + else if (variable == QStringLiteral("%filename%")) { value = song.basefilename(); } - else if (variable == "%url%") { + else if (variable == QStringLiteral("%url%")) { value = song.url().toString(); } - else if (variable == "%playcount%") { + else if (variable == QStringLiteral("%playcount%")) { value.setNum(song.playcount()); } - else if (variable == "%skipcount%") { + else if (variable == QStringLiteral("%skipcount%")) { value.setNum(song.skipcount()); } - else if (variable == "%rating%") { + else if (variable == QStringLiteral("%rating%")) { value = song.PrettyRating(); } - else if (variable == "%newline%") { + else if (variable == QStringLiteral("%newline%")) { return QString(newline); // No HTML escaping, return immediately. } diff --git a/src/utilities/timeutils.cpp b/src/utilities/timeutils.cpp index 16d8403bd3..44ec84bb02 100644 --- a/src/utilities/timeutils.cpp +++ b/src/utilities/timeutils.cpp @@ -50,7 +50,7 @@ QString PrettyTime(int seconds) { } QString PrettyTimeDelta(const int seconds) { - return (seconds >= 0 ? "+" : "-") + PrettyTime(seconds); + return (seconds >= 0 ? QStringLiteral("+") : QStringLiteral("-")) + PrettyTime(seconds); } QString PrettyTimeNanosec(const qint64 nanoseconds) { @@ -67,7 +67,7 @@ QString WordyTime(const quint64 seconds) { if (days > 0) parts << (days == 1 ? QObject::tr("1 day") : QObject::tr("%1 days").arg(days)); parts << PrettyTime(static_cast(seconds - days * 60 * 60 * 24)); - return parts.join(QStringLiteral(" ")); + return parts.join(QLatin1Char(' ')); } @@ -82,8 +82,8 @@ QString Ago(const qint64 seconds_since_epoch, const QLocale &locale) { const qint64 days_ago = then.date().daysTo(now.date()); const QString time = then.time().toString(locale.timeFormat(QLocale::ShortFormat)); - if (days_ago == 0) return QObject::tr("Today") + " " + time; - if (days_ago == 1) return QObject::tr("Yesterday") + " " + time; + if (days_ago == 0) return QObject::tr("Today") + QLatin1Char(' ') + time; + if (days_ago == 1) return QObject::tr("Yesterday") + QLatin1Char(' ') + time; if (days_ago <= 7) return QObject::tr("%1 days ago").arg(days_ago); return then.date().toString(locale.dateFormat(QLocale::ShortFormat)); diff --git a/src/widgets/fancytabwidget.cpp b/src/widgets/fancytabwidget.cpp index 70c9fc19ba..373bfaf0fe 100644 --- a/src/widgets/fancytabwidget.cpp +++ b/src/widgets/fancytabwidget.cpp @@ -61,6 +61,7 @@ #include "fancytabwidget.h" #include "core/stylehelper.h" +#include "core/settings.h" #include "settings/appearancesettingspage.h" using namespace std::chrono_literals; @@ -480,11 +481,11 @@ FancyTabWidget::~FancyTabWidget() { void FancyTabWidget::Load(const QString &kSettingsGroup) { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); QMultiMap tabs; for (TabData *tab : std::as_const(tabs_)) { - int idx = s.value("tab_" + tab->name(), tab->index()).toInt(); + int idx = s.value(QStringLiteral("tab_") + tab->name(), tab->index()).toInt(); while (tabs.contains(idx)) { ++idx; } tabs.insert(idx, tab); } @@ -505,14 +506,14 @@ int FancyTabWidget::insertTab(const int idx, QWidget *page, const QIcon &icon, c void FancyTabWidget::SaveSettings(const QString &kSettingsGroup) { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("tab_mode", static_cast(mode_)); s.setValue("current_tab", currentIndex()); for (TabData *tab : std::as_const(tabs_)) { - QString k = "tab_" + tab->name(); + QString k = QStringLiteral("tab_") + tab->name(); int idx = QTabWidget::indexOf(tab->page()); if (idx < 0) { if (s.contains(k)) s.remove(k); @@ -528,7 +529,7 @@ void FancyTabWidget::SaveSettings(const QString &kSettingsGroup) { void FancyTabWidget::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); bg_color_system_ = s.value(AppearanceSettingsPage::kTabBarSystemColor, false).toBool(); bg_gradient_ = s.value(AppearanceSettingsPage::kTabBarGradient, true).toBool(); diff --git a/src/widgets/fileview.cpp b/src/widgets/fileview.cpp index 5e80a9e410..624b64e3ec 100644 --- a/src/widgets/fileview.cpp +++ b/src/widgets/fileview.cpp @@ -41,6 +41,7 @@ #include "core/filesystemmusicstorage.h" #include "core/iconloader.h" #include "core/mimedata.h" +#include "core/settings.h" #include "dialogs/deleteconfirmationdialog.h" #include "fileview.h" #include "fileviewlist.h" @@ -93,7 +94,7 @@ FileView::FileView(QWidget *parent) QObject::connect(ui_->list, &FileViewList::Delete, this, &FileView::Delete); QObject::connect(ui_->list, &FileViewList::EditTags, this, &FileView::EditTags); - QString filter(FileView::kFileFilter); + QString filter(QLatin1String(FileView::kFileFilter)); filter_list_ << filter.split(QStringLiteral(" ")); ReloadSettings(); @@ -106,7 +107,7 @@ FileView::~FileView() { void FileView::ReloadSettings() { - QSettings s; + Settings s; s.beginGroup(AppearanceSettingsPage::kSettingsGroup); int iconsize = s.value(AppearanceSettingsPage::kIconSizeLeftPanelButtons, 22).toInt(); s.endGroup(); diff --git a/src/widgets/freespacebar.cpp b/src/widgets/freespacebar.cpp index 1cf0137b19..10168a51f9 100644 --- a/src/widgets/freespacebar.cpp +++ b/src/widgets/freespacebar.cpp @@ -229,7 +229,7 @@ QString FreeSpaceBar::TextForSize(const QString &prefix, const quint64 size) { ret = QStringLiteral("0 MB"); } - if (!prefix.isEmpty()) ret.prepend(prefix + " "); + if (!prefix.isEmpty()) ret.prepend(prefix + QStringLiteral(" ")); return ret; diff --git a/src/widgets/lineedit.h b/src/widgets/lineedit.h index 056cc34ab1..12751164f0 100644 --- a/src/widgets/lineedit.h +++ b/src/widgets/lineedit.h @@ -188,7 +188,7 @@ class SpinBox : public QSpinBox, public ExtendedEditor { QVariant value() const override { return QSpinBox::value(); } void set_value(const QVariant &value) override { QSpinBox::setValue(value.toInt()); } - bool is_empty() const override { return text().isEmpty() || text() == "0"; } + bool is_empty() const override { return text().isEmpty() || text() == QStringLiteral("0"); } public slots: void set_focus() override { QSpinBox::setFocus(); } @@ -214,7 +214,7 @@ class CheckBox : public QCheckBox, public ExtendedEditor { // ExtendedEditor void set_enabled(bool enabled) override { QCheckBox::setEnabled(enabled); } - bool is_empty() const override { return text().isEmpty() || text() == "0"; } + bool is_empty() const override { return text().isEmpty() || text() == QStringLiteral("0"); } QVariant value() const override { return QCheckBox::isChecked(); } void set_value(const QVariant &value) override { QCheckBox::setCheckState(value.toBool() ? Qt::Checked : Qt::Unchecked); } void set_partially() override { QCheckBox::setCheckState(Qt::PartiallyChecked); } diff --git a/src/widgets/loginstatewidget.cpp b/src/widgets/loginstatewidget.cpp index f17f624d2b..31e9ec6769 100644 --- a/src/widgets/loginstatewidget.cpp +++ b/src/widgets/loginstatewidget.cpp @@ -79,8 +79,8 @@ void LoginStateWidget::SetLoggedIn(const State state, const QString &account_nam ui_->signed_out->setVisible(state != State::LoggedIn); ui_->busy->setVisible(state == State::LoginInProgress); - if (account_name.isEmpty()) ui_->signed_in_label->setText("" + tr("You are signed in.") + ""); - else ui_->signed_in_label->setText(tr("You are signed in as %1.").arg("" + account_name + "")); + if (account_name.isEmpty()) ui_->signed_in_label->setText(QStringLiteral("") + tr("You are signed in.") + QStringLiteral("")); + else ui_->signed_in_label->setText(tr("You are signed in as %1.").arg(QStringLiteral("") + account_name + QStringLiteral(""))); for (QWidget *widget : credential_groups_) { widget->setVisible(state != State::LoggedIn); @@ -151,7 +151,7 @@ void LoginStateWidget::SetExpires(const QDate expires) { if (expires.isValid()) { const QString expires_text = QLocale().toString(expires, QLocale::LongFormat); - ui_->expires_label->setText(tr("Expires on %1").arg("" + expires_text + "")); + ui_->expires_label->setText(tr("Expires on %1").arg(QStringLiteral("") + expires_text + QStringLiteral(""))); } } diff --git a/src/widgets/playingwidget.cpp b/src/widgets/playingwidget.cpp index 599149eff8..70c2f31b9a 100644 --- a/src/widgets/playingwidget.cpp +++ b/src/widgets/playingwidget.cpp @@ -40,6 +40,7 @@ #include #include "core/application.h" +#include "core/settings.h" #include "utilities/imageutils.h" #include "covermanager/albumcoverchoicecontroller.h" #include "playingwidget.h" @@ -87,7 +88,7 @@ PlayingWidget::PlayingWidget(QWidget *parent) SetHeight(0); // Load settings - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); mode_ = static_cast(s.value("mode", static_cast(Mode::LargeSongDetails)).toInt()); fit_width_ = s.value("fit_cover_width", false).toBool(); @@ -139,7 +140,7 @@ void PlayingWidget::Init(Application *app, AlbumCoverChoiceController *album_cov above_statusbar_action_ = menu_->addAction(tr("Show above status bar")); above_statusbar_action_->setCheckable(true); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); above_statusbar_action_->setChecked(s.value("above_status_bar", false).toBool()); s.endGroup(); @@ -229,7 +230,7 @@ void PlayingWidget::SetMode(const Mode mode) { UpdateDetailsText(); update(); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("mode", static_cast(mode_)); s.endGroup(); @@ -242,7 +243,7 @@ void PlayingWidget::FitCoverWidth(const bool fit) { UpdateHeight(); update(); - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("fit_cover_width", fit_width_); s.endGroup(); @@ -251,7 +252,7 @@ void PlayingWidget::FitCoverWidth(const bool fit) { void PlayingWidget::ShowAboveStatusBar(const bool above) { - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("above_status_bar", above); s.endGroup(); @@ -547,7 +548,7 @@ void PlayingWidget::SearchCoverInProgress() { downloading_covers_ = true; // Show a spinner animation - spinner_animation_ = make_unique(":/pictures/spinner.gif", QByteArray(), this); + spinner_animation_ = make_unique(QStringLiteral(":/pictures/spinner.gif"), QByteArray(), this); QObject::connect(&*spinner_animation_, &QMovie::updated, this, &PlayingWidget::Update); spinner_animation_->start(); update(); diff --git a/src/widgets/ratingwidget.cpp b/src/widgets/ratingwidget.cpp index ac26fc2f7d..fde714628e 100644 --- a/src/widgets/ratingwidget.cpp +++ b/src/widgets/ratingwidget.cpp @@ -29,16 +29,13 @@ #include #include -const int RatingPainter::kStarCount; -const int RatingPainter::kStarSize; - RatingPainter::RatingPainter() { // Load the base pixmaps - QIcon star_on(":/pictures/star-on.png"); + QIcon star_on(QStringLiteral(":/pictures/star-on.png")); QList star_on_sizes = star_on.availableSizes(); QPixmap on(star_on.pixmap(star_on_sizes.last())); - QIcon star_off(":/pictures/star-off.png"); + QIcon star_off(QStringLiteral(":/pictures/star-off.png")); QList star_off_sizes = star_off.availableSizes(); QPixmap off(star_off.pixmap(star_off_sizes.last())); diff --git a/src/widgets/ratingwidget.h b/src/widgets/ratingwidget.h index e63bcb9a19..0a8bb7a3eb 100644 --- a/src/widgets/ratingwidget.h +++ b/src/widgets/ratingwidget.h @@ -30,8 +30,9 @@ class RatingPainter { public: RatingPainter(); - static const int kStarCount = 5; - static const int kStarSize = 16; + static constexpr int kStarCount = 5; + static constexpr int kStarSize = 16; + static QRect Contents(const QRect rect); static float RatingForPos(const QPoint pos, const QRect rect); diff --git a/src/widgets/trackslider.cpp b/src/widgets/trackslider.cpp index b4991b1028..e03ec63753 100644 --- a/src/widgets/trackslider.cpp +++ b/src/widgets/trackslider.cpp @@ -29,6 +29,7 @@ #include #include +#include "core/settings.h" #include "utilities/timeutils.h" #include "utilities/timeconstants.h" #include "trackslider.h" @@ -57,7 +58,7 @@ TrackSlider::TrackSlider(QWidget *parent) UpdateLabelWidth(); // Load settings - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); show_remaining_time_ = s.value("show_remaining_time").toBool(); s.endGroup(); @@ -142,7 +143,7 @@ void TrackSlider::UpdateTimes(const int elapsed) { ui_->elapsed->setText(Utilities::PrettyTime(elapsed)); // Update normally if showing remaining time if (show_remaining_time_) { - ui_->remaining->setText("-" + Utilities::PrettyTime(static_cast(ui_->slider->maximum() / kMsecPerSec) - elapsed)); + ui_->remaining->setText(QLatin1Char('-') + Utilities::PrettyTime(static_cast(ui_->slider->maximum() / kMsecPerSec) - elapsed)); } else { // Check if slider maximum value is changed before updating @@ -214,7 +215,7 @@ void TrackSlider::ToggleTimeDisplay() { UpdateTimes(static_cast(ui_->slider->value() / kMsecPerSec)); // Save this setting - QSettings s; + Settings s; s.beginGroup(kSettingsGroup); s.setValue("show_remaining_time", show_remaining_time_); diff --git a/src/widgets/volumeslider.cpp b/src/widgets/volumeslider.cpp index 201768d1a9..d1e464046b 100644 --- a/src/widgets/volumeslider.cpp +++ b/src/widgets/volumeslider.cpp @@ -109,7 +109,7 @@ void VolumeSlider::paintEvent(QPaintEvent*) { vol_font.setPixelSize(9); p.setFont(vol_font); const QRect rect(0, 0, 34, 15); - p.drawText(rect, Qt::AlignRight | Qt::AlignVCenter, QString::number(value()) + '%'); + p.drawText(rect, Qt::AlignRight | Qt::AlignVCenter, QString::number(value()) + QLatin1Char('%')); }