Disable automatic conversions from 8-bit strings

This commit is contained in:
Jonas Kvinge 2024-04-11 02:56:01 +02:00
parent 58944993b8
commit 0c6872b352
310 changed files with 2501 additions and 2332 deletions

View File

@ -508,6 +508,8 @@ add_definitions(
-DQT_NO_CAST_TO_ASCII -DQT_NO_CAST_TO_ASCII
-DQT_NO_NARROWING_CONVERSIONS_IN_CONNECT -DQT_NO_NARROWING_CONVERSIONS_IN_CONNECT
-DQT_NO_FOREACH -DQT_NO_FOREACH
-DQT_ASCII_CAST_WARNINGS
-DQT_NO_CAST_FROM_ASCII
) )
if(WIN32) if(WIN32)

View File

@ -67,8 +67,8 @@ static QIODevice *sNullDevice = nullptr;
const char *kDefaultLogLevels = "*:3"; const char *kDefaultLogLevels = "*:3";
static const char *kMessageHandlerMagic = "__logging_message__"; static constexpr char kMessageHandlerMagic[] = "__logging_message__";
static const size_t kMessageHandlerMagicLength = strlen(kMessageHandlerMagic); static const size_t kMessageHandlerMagicLen = strlen(kMessageHandlerMagic);
static QtMessageHandler sOriginalMessageHandler = nullptr; static QtMessageHandler sOriginalMessageHandler = nullptr;
template<class T> template<class T>
@ -135,9 +135,9 @@ class LoggedDebug : public DebugBase<LoggedDebug> {
static void MessageHandler(QtMsgType type, const QMessageLogContext&, const QString &message) { static void MessageHandler(QtMsgType type, const QMessageLogContext&, const QString &message) {
if (message.startsWith(kMessageHandlerMagic)) { if (message.startsWith(QLatin1String(kMessageHandlerMagic))) {
QByteArray message_data = message.toUtf8(); 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); fflush(type == QtCriticalMsg || type == QtFatalMsg ? stderr : stdout);
return; return;
} }
@ -157,7 +157,7 @@ static void MessageHandler(QtMsgType type, const QMessageLogContext&, const QStr
break; break;
} }
for (const QString &line : message.split('\n')) { for (const QString &line : message.split(QLatin1Char('\n'))) {
BufferedDebug d = CreateLogger<BufferedDebug>(level, QStringLiteral("unknown"), -1, nullptr); BufferedDebug d = CreateLogger<BufferedDebug>(level, QStringLiteral("unknown"), -1, nullptr);
d << line.toLocal8Bit().constData(); d << line.toLocal8Bit().constData();
if (d.buf_) { if (d.buf_) {
@ -193,8 +193,8 @@ void SetLevels(const QString &levels) {
if (!sClassLevels) return; if (!sClassLevels) return;
for (const QString &item : levels.split(',')) { for (const QString &item : levels.split(QLatin1Char(','))) {
const QStringList class_level = item.split(':'); const QStringList class_level = item.split(QLatin1Char(':'));
QString class_name; QString class_name;
bool ok = false; bool ok = false;
@ -212,7 +212,7 @@ void SetLevels(const QString &levels) {
continue; continue;
} }
if (class_name.isEmpty() || class_name == "*") { if (class_name.isEmpty() || class_name == QStringLiteral("*")) {
sDefaultLevel = static_cast<Level>(level); sDefaultLevel = static_cast<Level>(level);
} }
else { else {
@ -225,8 +225,8 @@ void SetLevels(const QString &levels) {
static QString ParsePrettyFunction(const char *pretty_function) { static QString ParsePrettyFunction(const char *pretty_function) {
// Get the class name out of the function name. // Get the class name out of the function name.
QString class_name = pretty_function; QString class_name = QLatin1String(pretty_function);
const qint64 paren = class_name.indexOf('('); const qint64 paren = class_name.indexOf(QLatin1Char('('));
if (paren != -1) { if (paren != -1) {
const qint64 colons = class_name.lastIndexOf(QLatin1String("::"), paren); const qint64 colons = class_name.lastIndexOf(QLatin1String("::"), paren);
if (colons != -1) { 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) { if (space != -1) {
class_name = class_name.mid(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; 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. // Check the settings to see if we're meant to show or hide this message.
Level threshold_level = sDefaultLevel; Level threshold_level = sDefaultLevel;
if (sClassLevels && sClassLevels->contains(filter_category)) { 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; QString function_line = class_name;
if (line != -1) { if (line != -1) {
function_line += ":" + QString::number(line); function_line += QStringLiteral(":") + QString::number(line);
} }
if (category) { if (category) {
function_line += "(" + QString(category) + ")"; function_line += QStringLiteral("(") + QLatin1String(category) + QStringLiteral(")");
} }
QtMsgType type = QtDebugMsg; QtMsgType type = QtDebugMsg;
@ -326,9 +326,9 @@ QString DarwinDemangle(const QString &symbol);
QString DarwinDemangle(const QString &symbol) { QString DarwinDemangle(const QString &symbol) {
# if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) # if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
QStringList split = symbol.split(' ', Qt::SkipEmptyParts); QStringList split = symbol.split(QLatin1Char(' '), Qt::SkipEmptyParts);
# else # else
QStringList split = symbol.split(' ', QString::SkipEmptyParts); QStringList split = symbol.split(QLatin1Char(' '), QString::SkipEmptyParts);
# endif # endif
QString mangled_function = split[3]; QString mangled_function = split[3];
return CXXDemangle(mangled_function); return CXXDemangle(mangled_function);
@ -392,7 +392,7 @@ namespace {
template<typename T> template<typename T>
QString print_duration(T duration, const std::string &unit) { 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 } // namespace

View File

@ -247,11 +247,11 @@ void WorkerPool<HandlerType>::DoStart() {
search_path << QStringLiteral("/usr/local/libexec"); search_path << QStringLiteral("/usr/local/libexec");
#endif #endif
#if defined(Q_OS_MACOS) #if defined(Q_OS_MACOS)
search_path << QDir::cleanPath(QCoreApplication::applicationDirPath() + "/../PlugIns"); search_path << QDir::cleanPath(QCoreApplication::applicationDirPath() + QStringLiteral("/../PlugIns"));
#endif #endif
for (const QString &path_prefix : search_path) { 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)) { if (QFile::exists(executable_path)) {
executable_path_ = executable_path; executable_path_ = executable_path;
qLog(Debug) << "Using worker" << executable_name_ << "from" << path_prefix; qLog(Debug) << "Using worker" << executable_name_ << "from" << path_prefix;

View File

@ -74,7 +74,7 @@ TagReaderBase::Cover TagReaderBase::LoadCoverFromRequest(const spb::tagreader::S
} }
QString cover_mime_type; QString cover_mime_type;
if (request.has_cover_mime_type()) { if (request.has_cover_mime_type()) {
cover_mime_type = QByteArray(request.cover_mime_type().data(), static_cast<qint64>(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); 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; QString cover_mime_type;
if (request.has_cover_mime_type()) { if (request.has_cover_mime_type()) {
cover_mime_type = QByteArray(request.cover_mime_type().data(), static_cast<qint64>(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); 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()) { if (cover_mime_type.isEmpty()) {
cover_mime_type = QMimeDatabase().mimeTypeForData(cover_data).name(); 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; qLog(Debug) << "Using cover from JPEG data for" << song_filename;
return Cover(cover_data, cover_mime_type); 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; qLog(Debug) << "Using cover from PNG data for" << song_filename;
return Cover(cover_data, cover_mime_type); return Cover(cover_data, cover_mime_type);
} }
// Convert image to JPEG. // Convert image to JPEG.
qLog(Debug) << "Converting cover to JPEG data for" << song_filename; 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(); cover_data.clear();
QBuffer buffer(&cover_data); QBuffer buffer(&cover_data);
if (buffer.open(QIODevice::WriteOnly)) { if (buffer.open(QIODevice::WriteOnly)) {

View File

@ -226,7 +226,7 @@ void GME::VGM::Read(const QFileInfo &file_info, spb::tagreader::SongMetadata *so
#else #else
fileTagStream.setCodec("UTF-16"); fileTagStream.setCodec("UTF-16");
#endif #endif
QStringList strings = fileTagStream.readLine(0).split(QChar('\0')); QStringList strings = fileTagStream.readLine(0).split(QLatin1Char('\0'));
if (strings.count() < 10) return; if (strings.count() < 10) return;
// VGM standard dictates string tag data exist in specific order. // VGM standard dictates string tag data exist in specific order.

View File

@ -368,7 +368,7 @@ bool TagReaderTagLib::ReadFile(const QString &filename, spb::tagreader::SongMeta
for (uint i = 0; i < map["COMM"].size(); ++i) { for (uint i = 0; i < map["COMM"].size(); ++i) {
const TagLib::ID3v2::CommentsFrame *frame = dynamic_cast<const TagLib::ID3v2::CommentsFrame*>(map["COMM"][i]); const TagLib::ID3v2::CommentsFrame *frame = dynamic_cast<const TagLib::ID3v2::CommentsFrame*>(map["COMM"][i]);
if (frame && TStringToQString(frame->description()) != "iTunNORM") { if (frame && TStringToQString(frame->description()) != QStringLiteral("iTunNORM")) {
TStringToStdString(frame->text(), song->mutable_comment()); TStringToStdString(frame->text(), song->mutable_comment());
break; break;
} }
@ -663,7 +663,7 @@ bool TagReaderTagLib::ReadFile(const QString &filename, spb::tagreader::SongMeta
} }
if (!disc.isEmpty()) { if (!disc.isEmpty()) {
const qint64 i = disc.indexOf('/'); const qint64 i = disc.indexOf(QLatin1Char('/'));
if (i != -1) { if (i != -1) {
// disc.right( i ).toInt() is total number of discs, we don't use this at the moment // disc.right( i ).toInt() is total number of discs, we don't use this at the moment
song->set_disc(disc.left(i).toInt()); song->set_disc(disc.left(i).toInt());
@ -1311,10 +1311,10 @@ void TagReaderTagLib::SetEmbeddedArt(TagLib::MP4::File *aac_file, TagLib::MP4::T
} }
else { else {
TagLib::MP4::CoverArt::Format cover_format = TagLib::MP4::CoverArt::Format::JPEG; 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; 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; cover_format = TagLib::MP4::CoverArt::Format::PNG;
} }
else { else {

View File

@ -24,6 +24,7 @@ set(SOURCES
core/networktimeouts.cpp core/networktimeouts.cpp
core/networkproxyfactory.cpp core/networkproxyfactory.cpp
core/qtfslistener.cpp core/qtfslistener.cpp
core/settings.cpp
core/settingsprovider.cpp core/settingsprovider.cpp
core/signalchecker.cpp core/signalchecker.cpp
core/song.cpp core/song.cpp
@ -307,6 +308,7 @@ set(HEADERS
core/threadsafenetworkdiskcache.h core/threadsafenetworkdiskcache.h
core/networktimeouts.h core/networktimeouts.h
core/qtfslistener.h core/qtfslistener.h
core/settings.h
core/songloader.h core/songloader.h
core/tagreaderclient.h core/tagreaderclient.h
core/taskmanager.h core/taskmanager.h

View File

@ -108,7 +108,7 @@ void AnalyzerBase::paintEvent(QPaintEvent *e) {
p.fillRect(e->rect(), palette().color(QPalette::Window)); p.fillRect(e->rect(), palette().color(QPalette::Window));
switch (engine_->state()) { switch (engine_->state()) {
case EngineBase::State::Playing: { case EngineBase::State::Playing:{
const EngineBase::Scope &thescope = engine_->scope(timeout_); const EngineBase::Scope &thescope = engine_->scope(timeout_);
int i = 0; int i = 0;

View File

@ -44,6 +44,7 @@
#include "core/logging.h" #include "core/logging.h"
#include "core/shared_ptr.h" #include "core/shared_ptr.h"
#include "core/settings.h"
#include "engine/enginebase.h" #include "engine/enginebase.h"
using namespace std::chrono_literals; using namespace std::chrono_literals;
@ -178,9 +179,9 @@ void AnalyzerContainer::ChangeFramerate(int new_framerate) {
void AnalyzerContainer::Load() { void AnalyzerContainer::Load() {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); 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(); current_framerate_ = s.value(kSettingsFramerate, kMediumFramerate).toInt();
s.endGroup(); s.endGroup();
@ -191,7 +192,7 @@ void AnalyzerContainer::Load() {
} }
else { else {
for (int i = 0; i < analyzer_types_.count(); ++i) { for (int i = 0; i < analyzer_types_.count(); ++i) {
if (type == analyzer_types_[i]->className()) { if (type == QString::fromLatin1(analyzer_types_[i]->className())) {
ChangeAnalyzer(i); ChangeAnalyzer(i);
actions_[i]->setChecked(true); actions_[i]->setChecked(true);
break; 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? // For now, framerate is common for all analyzers. Maybe each analyzer should have its own framerate?
current_framerate_ = framerate; current_framerate_ = framerate;
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
s.setValue(kSettingsFramerate, current_framerate_); s.setValue(kSettingsFramerate, current_framerate_);
s.endGroup(); s.endGroup();
@ -224,9 +225,9 @@ void AnalyzerContainer::SaveFramerate(const int framerate) {
void AnalyzerContainer::Save() { void AnalyzerContainer::Save() {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
s.setValue("type", current_analyzer_ ? current_analyzer_->metaObject()->className() : QVariant()); s.setValue("type", current_analyzer_ ? QString::fromLatin1(current_analyzer_->metaObject()->className()) : QVariant());
s.endGroup(); s.endGroup();
} }

View File

@ -37,6 +37,7 @@
#include "core/thread.h" #include "core/thread.h"
#include "core/song.h" #include "core/song.h"
#include "core/logging.h" #include "core/logging.h"
#include "core/settings.h"
#include "utilities/threadutils.h" #include "utilities/threadutils.h"
#include "collection.h" #include "collection.h"
#include "collectionwatcher.h" #include "collectionwatcher.h"
@ -69,7 +70,7 @@ SCollection::SCollection(Application *app, QObject *parent)
backend()->moveToThread(app->database()->thread()); backend()->moveToThread(app->database()->thread());
qLog(Debug) << &*backend_ << "moved to thread" << 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); model_ = new CollectionModel(backend_, app_, this);
@ -179,7 +180,7 @@ void SCollection::ReloadSettings() {
watcher_->ReloadSettingsAsync(); watcher_->ReloadSettingsAsync();
model_->ReloadSettings(); model_->ReloadSettings();
QSettings s; Settings s;
s.beginGroup(CollectionSettingsPage::kSettingsGroup); s.beginGroup(CollectionSettingsPage::kSettingsGroup);
save_playcounts_to_files_ = s.value("save_playcounts", false).toBool(); save_playcounts_to_files_ = s.value("save_playcounts", false).toBool();
save_ratings_to_files_ = s.value("save_ratings", false).toBool(); save_ratings_to_files_ = s.value("save_ratings", false).toBool();

View File

@ -939,7 +939,7 @@ QStringList CollectionBackend::GetAll(const QString &column, const CollectionFil
QSqlDatabase db(db_->Connect()); QSqlDatabase db(db_->Connect());
CollectionQuery query(db, songs_table_, fts_table_, filter_options); CollectionQuery query(db, songs_table_, fts_table_, filter_options);
query.SetColumnSpec("DISTINCT " + column); query.SetColumnSpec(QStringLiteral("DISTINCT ") + column);
query.AddCompilationRequirement(false); query.AddCompilationRequirement(false);
if (!query.Exec()) { if (!query.Exec()) {
@ -969,14 +969,14 @@ QStringList CollectionBackend::GetAllArtistsWithAlbums(const CollectionFilterOpt
CollectionQuery query(db, songs_table_, fts_table_, opt); CollectionQuery query(db, songs_table_, fts_table_, opt);
query.SetColumnSpec(QStringLiteral("DISTINCT albumartist")); query.SetColumnSpec(QStringLiteral("DISTINCT albumartist"));
query.AddCompilationRequirement(false); query.AddCompilationRequirement(false);
query.AddWhere(QStringLiteral("album"), "", QStringLiteral("!=")); query.AddWhere(QStringLiteral("album"), QLatin1String(""), QStringLiteral("!="));
// Albums with no 'albumartist' (extract 'artist'): // Albums with no 'albumartist' (extract 'artist'):
CollectionQuery query2(db, songs_table_, fts_table_, opt); CollectionQuery query2(db, songs_table_, fts_table_, opt);
query2.SetColumnSpec(QStringLiteral("DISTINCT artist")); query2.SetColumnSpec(QStringLiteral("DISTINCT artist"));
query2.AddCompilationRequirement(false); query2.AddCompilationRequirement(false);
query2.AddWhere(QStringLiteral("album"), "", QStringLiteral("!=")); query2.AddWhere(QStringLiteral("album"), QLatin1String(""), QStringLiteral("!="));
query2.AddWhere(QStringLiteral("albumartist"), "", QStringLiteral("=")); query2.AddWhere(QStringLiteral("albumartist"), QLatin1String(""), QStringLiteral("="));
if (!query.Exec()) { if (!query.Exec()) {
ReportErrors(query); ReportErrors(query);
@ -1065,7 +1065,7 @@ SongList CollectionBackend::GetSongsByAlbum(const QString &album, const Collecti
bool CollectionBackend::ExecCollectionQuery(CollectionQuery *query, SongList &songs) { 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; if (!query->Exec()) return false;
@ -1080,7 +1080,7 @@ bool CollectionBackend::ExecCollectionQuery(CollectionQuery *query, SongList &so
bool CollectionBackend::ExecCollectionQuery(CollectionQuery *query, SongMap &songs) { 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; if (!query->Exec()) return false;
@ -1301,9 +1301,9 @@ SongList CollectionBackend::GetSongsBySongId(const QStringList &song_ids, QSqlDa
QStringList song_ids2; QStringList song_ids2;
song_ids2.reserve(song_ids.count()); song_ids2.reserve(song_ids.count());
for (const QString &song_id : song_ids) { 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); SqlQuery q(db);
q.prepare(QStringLiteral("SELECT ROWID, %1 FROM %2 WHERE SONG_ID IN (%3)").arg(Song::kColumnSpec, songs_table_, in)); 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()); QSqlDatabase db(db_->Connect());
CollectionQuery query(db, songs_table_, fts_table_, opt); 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.AddCompilationRequirement(true);
query.AddWhere(QStringLiteral("album"), album); query.AddWhere(QStringLiteral("album"), album);
@ -1553,7 +1553,7 @@ CollectionBackend::AlbumList CollectionBackend::GetAlbums(const QString &artist,
key.append(album_info.album_artist); key.append(album_info.album_artist);
} }
if (!album_info.album.isEmpty()) { if (!album_info.album.isEmpty()) {
if (!key.isEmpty()) key.append("-"); if (!key.isEmpty()) key.append(QLatin1Char('-'));
key.append(album_info.album); key.append(album_info.album);
} }
if (!filetype.isEmpty()) { if (!filetype.isEmpty()) {
@ -1622,7 +1622,7 @@ void CollectionBackend::UpdateEmbeddedAlbumArt(const QString &effective_albumart
// Get the songs before they're updated // Get the songs before they're updated
CollectionQuery query(db, songs_table_, fts_table_); 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("effective_albumartist"), effective_albumartist);
query.AddWhere(QStringLiteral("album"), album); query.AddWhere(QStringLiteral("album"), album);
@ -1684,7 +1684,7 @@ void CollectionBackend::UpdateManualAlbumArt(const QString &effective_albumartis
QSqlDatabase db(db_->Connect()); QSqlDatabase db(db_->Connect());
CollectionQuery query(db, songs_table_, fts_table_); 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("effective_albumartist"), effective_albumartist);
query.AddWhere(QStringLiteral("album"), album); query.AddWhere(QStringLiteral("album"), album);
@ -1742,7 +1742,7 @@ void CollectionBackend::UnsetAlbumArt(const QString &effective_albumartist, cons
QSqlDatabase db(db_->Connect()); QSqlDatabase db(db_->Connect());
CollectionQuery query(db, songs_table_, fts_table_); 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("effective_albumartist"), effective_albumartist);
query.AddWhere(QStringLiteral("album"), album); query.AddWhere(QStringLiteral("album"), album);
@ -1799,7 +1799,7 @@ void CollectionBackend::ClearAlbumArt(const QString &effective_albumartist, cons
QSqlDatabase db(db_->Connect()); QSqlDatabase db(db_->Connect());
CollectionQuery query(db, songs_table_, fts_table_); 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("effective_albumartist"), effective_albumartist);
query.AddWhere(QStringLiteral("album"), album); query.AddWhere(QStringLiteral("album"), album);
@ -1854,7 +1854,7 @@ void CollectionBackend::ForceCompilation(const QString &album, const QList<QStri
for (const QString &artist : artists) { for (const QString &artist : artists) {
// Get the songs before they're updated // Get the songs before they're updated
CollectionQuery query(db, songs_table_, fts_table_); CollectionQuery query(db, songs_table_, fts_table_);
query.SetColumnSpec("ROWID, " + Song::kColumnSpec); query.SetColumnSpec(QStringLiteral("ROWID, ") + Song::kColumnSpec);
query.AddWhere(QStringLiteral("album"), album); query.AddWhere(QStringLiteral("album"), album);
if (!artist.isEmpty()) query.AddWhere(QStringLiteral("artist"), artist); if (!artist.isEmpty()) query.AddWhere(QStringLiteral("artist"), artist);
@ -2008,7 +2008,7 @@ void CollectionBackend::DeleteAll() {
{ {
SqlQuery q(db); SqlQuery q(db);
q.prepare("DELETE FROM " + songs_table_); q.prepare(QStringLiteral("DELETE FROM ") + songs_table_);
if (!q.Exec()) { if (!q.Exec()) {
db_->ReportErrors(q); db_->ReportErrors(q);
return; return;
@ -2017,7 +2017,7 @@ void CollectionBackend::DeleteAll() {
{ {
SqlQuery q(db); SqlQuery q(db);
q.prepare("DELETE FROM " + fts_table_); q.prepare(QStringLiteral("DELETE FROM ") + fts_table_);
if (!q.Exec()) { if (!q.Exec()) {
db_->ReportErrors(q); db_->ReportErrors(q);
return; return;
@ -2220,7 +2220,7 @@ void CollectionBackend::ExpireSongs(const int directory_id, const int expire_una
QMutexLocker l(db_->Mutex()); QMutexLocker l(db_->Mutex());
QSqlDatabase db(db_->Connect()); QSqlDatabase db(db_->Connect());
SqlQuery q(db); 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(":directory_id"), directory_id);
q.BindValue(QStringLiteral(":time"), QDateTime::currentDateTime().toSecsSinceEpoch() - (expire_unavailable_songs_days * 86400)); q.BindValue(QStringLiteral(":time"), QDateTime::currentDateTime().toSecsSinceEpoch() - (expire_unavailable_songs_days * 86400));
if (!q.Exec()) { if (!q.Exec()) {

View File

@ -46,6 +46,7 @@
#include "core/iconloader.h" #include "core/iconloader.h"
#include "core/song.h" #include "core/song.h"
#include "core/logging.h" #include "core/logging.h"
#include "core/settings.h"
#include "collectionfilteroptions.h" #include "collectionfilteroptions.h"
#include "collectionmodel.h" #include "collectionmodel.h"
#include "savedgroupingmanager.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")) + tr("searches the collection for all artists that contain the word %1. ").arg(QStringLiteral("Strawbs")) +
QStringLiteral("</p><p>") + QStringLiteral("</p><p>") +
tr("Search terms for numerical fields can be prefixed with %1 or %2 to refine the search, e.g.: ") tr("Search terms for numerical fields can be prefixed with %1 or %2 to refine the search, e.g.: ")
.arg(" =, !=, &lt;, &gt;, &lt;=", "&gt;=") + .arg(QStringLiteral(" =, !=, &lt;, &gt;, &lt;="), QStringLiteral("&gt;=")) +
QStringLiteral("<span style=\"font-weight:600;\">") + QStringLiteral("<span style=\"font-weight:600;\">") +
tr("rating") + tr("rating") +
QStringLiteral("</span>") + QStringLiteral("</span>") +
@ -181,7 +182,7 @@ void CollectionFilterWidget::Init(CollectionModel *model) {
// Load settings // Load settings
if (!settings_group_.isEmpty()) { if (!settings_group_.isEmpty()) {
QSettings s; Settings s;
s.beginGroup(settings_group_); s.beginGroup(settings_group_);
int version = 0; int version = 0;
if (s.contains(group_by_version())) version = s.value(group_by_version(), 0).toInt(); 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() { void CollectionFilterWidget::ReloadSettings() {
QSettings s; Settings s;
s.beginGroup(AppearanceSettingsPage::kSettingsGroup); s.beginGroup(AppearanceSettingsPage::kSettingsGroup);
int iconsize = s.value(AppearanceSettingsPage::kIconSizeConfigureButtons, 20).toInt(); int iconsize = s.value(AppearanceSettingsPage::kIconSizeConfigureButtons, 20).toInt();
s.endGroup(); s.endGroup();
@ -306,13 +307,13 @@ QActionGroup *CollectionFilterWidget::CreateGroupByActions(const QString &saved_
ret->addAction(sep1); ret->addAction(sep1);
// Read saved groupings // Read saved groupings
QSettings s; Settings s;
s.beginGroup(saved_groupings_settings_group); s.beginGroup(saved_groupings_settings_group);
int version = s.value("version").toInt(); int version = s.value("version").toInt();
if (version == 1) { if (version == 1) {
QStringList saved = s.childKeys(); QStringList saved = s.childKeys();
for (int i = 0; i < saved.size(); ++i) { 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(); QByteArray bytes = s.value(saved.at(i)).toByteArray();
QDataStream ds(&bytes, QIODevice::ReadOnly); QDataStream ds(&bytes, QIODevice::ReadOnly);
CollectionModel::Grouping g; CollectionModel::Grouping g;
@ -323,7 +324,7 @@ QActionGroup *CollectionFilterWidget::CreateGroupByActions(const QString &saved_
else { else {
QStringList saved = s.childKeys(); QStringList saved = s.childKeys();
for (int i = 0; i < saved.size(); ++i) { 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)); s.remove(saved.at(i));
} }
} }
@ -361,17 +362,17 @@ void CollectionFilterWidget::SaveGroupBy() {
qLog(Debug) << "Saving current grouping to" << name; qLog(Debug) << "Saving current grouping to" << name;
QSettings s; Settings s;
if (settings_group_.isEmpty() || settings_group_ == CollectionSettingsPage::kSettingsGroup) { if (settings_group_.isEmpty() || settings_group_ == QLatin1String(CollectionSettingsPage::kSettingsGroup)) {
s.beginGroup(SavedGroupingManager::kSavedGroupingsSettingsGroup); s.beginGroup(SavedGroupingManager::kSavedGroupingsSettingsGroup);
} }
else { else {
s.beginGroup(QString(SavedGroupingManager::kSavedGroupingsSettingsGroup) + "_" + settings_group_); s.beginGroup(QLatin1String(SavedGroupingManager::kSavedGroupingsSettingsGroup) + QLatin1Char('_') + settings_group_);
} }
QByteArray buffer; QByteArray buffer;
QDataStream datastream(&buffer, QIODevice::WriteOnly); QDataStream datastream(&buffer, QIODevice::WriteOnly);
datastream << model_->GetGroupBy(); datastream << model_->GetGroupBy();
s.setValue("version", "1"); s.setValue("version", QStringLiteral("1"));
s.setValue(name, buffer); s.setValue(name, buffer);
s.endGroup(); s.endGroup();
@ -425,7 +426,7 @@ void CollectionFilterWidget::GroupByClicked(QAction *action) {
void CollectionFilterWidget::GroupingChanged(const CollectionModel::Grouping g, const bool separate_albums_by_grouping) { void CollectionFilterWidget::GroupingChanged(const CollectionModel::Grouping g, const bool separate_albums_by_grouping) {
if (!settings_group_.isEmpty()) { if (!settings_group_.isEmpty()) {
QSettings s; Settings s;
s.beginGroup(settings_group_); s.beginGroup(settings_group_);
s.setValue(group_by_version(), 1); s.setValue(group_by_version(), 1);
s.setValue(group_by_key(1), static_cast<int>(g[0])); s.setValue(group_by_key(1), static_cast<int>(g[0]));

View File

@ -130,7 +130,7 @@ bool CollectionItemDelegate::helpEvent(QHelpEvent *event, QAbstractItemView *vie
if (text.isEmpty()) return false; if (text.isEmpty()) return false;
switch (event->type()) { switch (event->type()) {
case QEvent::ToolTip: { case QEvent::ToolTip:{
QSize real_text = sizeHint(option, idx); QSize real_text = sizeHint(option, idx);
QRect displayed_text = view->visualRect(idx); QRect displayed_text = view->visualRect(idx);

View File

@ -61,6 +61,7 @@
#include "core/logging.h" #include "core/logging.h"
#include "core/taskmanager.h" #include "core/taskmanager.h"
#include "core/sqlrow.h" #include "core/sqlrow.h"
#include "core/settings.h"
#include "collectionfilteroptions.h" #include "collectionfilteroptions.h"
#include "collectionquery.h" #include "collectionquery.h"
#include "collectionqueryoptions.h" #include "collectionqueryoptions.h"
@ -117,7 +118,7 @@ CollectionModel::CollectionModel(SharedPtr<CollectionBackend> backend, Applicati
if (app_ && !sIconCache) { if (app_ && !sIconCache) {
sIconCache = new QNetworkDiskCache(this); sIconCache = new QNetworkDiskCache(this);
sIconCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/" + kPixmapDiskCacheDir); sIconCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1Char('/') + QLatin1String(kPixmapDiskCacheDir));
QObject::connect(app_, &Application::ClearPixmapDiskCache, this, &CollectionModel::ClearDiskCache); 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() { void CollectionModel::ReloadSettings() {
QSettings s; Settings s;
s.beginGroup(CollectionSettingsPage::kSettingsGroup); s.beginGroup(CollectionSettingsPage::kSettingsGroup);
@ -247,7 +248,7 @@ void CollectionModel::SongsDiscovered(const SongList &songs) {
GroupBy group_by = group_by_[i]; GroupBy group_by = group_by_[i];
if (group_by == GroupBy::None) break; 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 :( // 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()) { if (IsArtistGroupBy(group_by) && song.is_compilation()) {
@ -329,33 +330,33 @@ QString CollectionModel::ContainerKey(const GroupBy group_by, const bool separat
break; break;
case GroupBy::Album: case GroupBy::Album:
key = TextOrUnknown(song.album()); key = TextOrUnknown(song.album());
if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id());
if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping());
break; break;
case GroupBy::AlbumDisc: case GroupBy::AlbumDisc:
key = PrettyAlbumDisc(song.album(), song.disc()); key = PrettyAlbumDisc(song.album(), song.disc());
if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id());
if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping());
break; break;
case GroupBy::YearAlbum: case GroupBy::YearAlbum:
key = PrettyYearAlbum(song.year(), song.album()); key = PrettyYearAlbum(song.year(), song.album());
if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id());
if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping());
break; break;
case GroupBy::YearAlbumDisc: case GroupBy::YearAlbumDisc:
key = PrettyYearAlbumDisc(song.year(), song.album(), song.disc()); key = PrettyYearAlbumDisc(song.year(), song.album(), song.disc());
if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id());
if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping());
break; break;
case GroupBy::OriginalYearAlbum: case GroupBy::OriginalYearAlbum:
key = PrettyYearAlbum(song.effective_originalyear(), song.album()); key = PrettyYearAlbum(song.effective_originalyear(), song.album());
if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id());
if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping());
break; break;
case GroupBy::OriginalYearAlbumDisc: case GroupBy::OriginalYearAlbumDisc:
key = PrettyYearAlbumDisc(song.effective_originalyear(), song.album(), song.disc()); key = PrettyYearAlbumDisc(song.effective_originalyear(), song.album(), song.disc());
if (!song.album_id().isEmpty()) key.append("-" + song.album_id()); if (!song.album_id().isEmpty()) key.append(QLatin1Char('-') + song.album_id());
if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append("-" + song.grouping()); if (separate_albums_by_grouping && !song.grouping().isEmpty()) key.append(QLatin1Char('-') + song.grouping());
break; break;
case GroupBy::Disc: case GroupBy::Disc:
key = PrettyDisc(song.disc()); key = PrettyDisc(song.disc());
@ -430,10 +431,10 @@ QString CollectionModel::DividerKey(const GroupBy group_by, CollectionItem *item
case GroupBy::Disc: case GroupBy::Disc:
case GroupBy::Genre: case GroupBy::Genre:
case GroupBy::Format: case GroupBy::Format:
case GroupBy::FileType: { case GroupBy::FileType:{
QChar c = item->sort_text[0]; QChar c = item->sort_text[0];
if (c.isDigit()) return QStringLiteral("0"); if (c.isDigit()) return QStringLiteral("0");
if (c == ' ') return QString(); if (c == QLatin1Char(' ')) return QString();
if (c.decompositionTag() != QChar::NoDecomposition) { if (c.decompositionTag() != QChar::NoDecomposition) {
QString decomposition = c.decomposition(); QString decomposition = c.decomposition();
return QChar(decomposition[0]); return QChar(decomposition[0]);
@ -487,31 +488,31 @@ QString CollectionModel::DividerDisplayText(const GroupBy group_by, const QStrin
case GroupBy::Genre: case GroupBy::Genre:
case GroupBy::FileType: case GroupBy::FileType:
case GroupBy::Format: case GroupBy::Format:
if (key == "0") return QStringLiteral("0-9"); if (key == QLatin1String("0")) return QStringLiteral("0-9");
return key.toUpper(); return key.toUpper();
case GroupBy::YearAlbum: case GroupBy::YearAlbum:
case GroupBy::YearAlbumDisc: case GroupBy::YearAlbumDisc:
case GroupBy::OriginalYearAlbum: case GroupBy::OriginalYearAlbum:
case GroupBy::OriginalYearAlbumDisc: case GroupBy::OriginalYearAlbumDisc:
if (key == "0000") return tr("Unknown"); if (key == QStringLiteral("0000")) return tr("Unknown");
return key.toUpper(); return key.toUpper();
case GroupBy::Year: case GroupBy::Year:
case GroupBy::OriginalYear: 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 return QString::number(key.toInt()); // To remove leading 0s
case GroupBy::Samplerate: 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 return QString::number(key.toInt()); // To remove leading 0s
case GroupBy::Bitdepth: 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 return QString::number(key.toInt()); // To remove leading 0s
case GroupBy::Bitrate: 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 return QString::number(key.toInt()); // To remove leading 0s
case GroupBy::None: case GroupBy::None:
@ -631,13 +632,13 @@ QString CollectionModel::AlbumIconPixmapCacheKey(const QModelIndex &idx) const {
idx_copy = idx_copy.parent(); idx_copy = idx_copy.parent();
} }
return Song::TextForSource(backend_->source()) + "/" + path.join(QStringLiteral("/")); return Song::TextForSource(backend_->source()) + QLatin1Char('/') + path.join(QLatin1Char('/'));
} }
QUrl CollectionModel::AlbumIconPixmapDiskCacheKey(const QString &cache_key) const { 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; break;
case GroupBy::Album:{ case GroupBy::Album:{
QString query(QStringLiteral("DISTINCT album, album_id")); 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); query_options->set_column_spec(query);
break; break;
} }
case GroupBy::AlbumDisc:{ case GroupBy::AlbumDisc:{
QString query(QStringLiteral("DISTINCT album, album_id, disc")); 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); query_options->set_column_spec(query);
break; break;
} }
case GroupBy::YearAlbum:{ case GroupBy::YearAlbum:{
QString query(QStringLiteral("DISTINCT year, album, album_id")); 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); query_options->set_column_spec(query);
break; break;
} }
case GroupBy::YearAlbumDisc:{ case GroupBy::YearAlbumDisc:{
QString query(QStringLiteral("DISTINCT year, album, album_id, disc")); 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); query_options->set_column_spec(query);
break; break;
} }
case GroupBy::OriginalYearAlbum:{ case GroupBy::OriginalYearAlbum:{
QString query(QStringLiteral("DISTINCT year, originalyear, album, album_id")); 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); query_options->set_column_spec(query);
break; break;
} }
case GroupBy::OriginalYearAlbumDisc:{ case GroupBy::OriginalYearAlbumDisc:{
QString query(QStringLiteral("DISTINCT year, originalyear, album, album_id, disc")); 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); query_options->set_column_spec(query);
break; break;
} }
@ -1133,7 +1134,7 @@ void CollectionModel::SetQueryColumnSpec(const GroupBy group_by, const bool sepa
break; break;
case GroupBy::None: case GroupBy::None:
case GroupBy::GroupByCount: 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; break;
} }
@ -1269,7 +1270,7 @@ CollectionItem *CollectionModel::ItemFromQuery(const GroupBy group_by, const boo
CollectionItem *item = InitItem(group_by, signal, parent, container_level); CollectionItem *item = InitItem(group_by, signal, parent, container_level);
if (parent != root_ && !parent->key.isEmpty()) { if (parent != root_ && !parent->key.isEmpty()) {
item->key = parent->key + "-"; item->key = parent->key + QLatin1Char('-');
} }
switch (group_by) { 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata));
const int year = std::max(0, item->metadata.year()); const int year = std::max(0, item->metadata.year());
item->display_text = QString::number(year); item->display_text = QString::number(year);
item->sort_text = SortTextForNumber(year) + " "; item->sort_text = SortTextForNumber(year) + QLatin1Char(' ');
break; break;
} }
case GroupBy::OriginalYear:{ 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata));
const int year = std::max(0, item->metadata.originalyear()); const int year = std::max(0, item->metadata.originalyear());
item->display_text = QString::number(year); item->display_text = QString::number(year);
item->sort_text = SortTextForNumber(year) + " "; item->sort_text = SortTextForNumber(year) + QLatin1Char(' ');
break; break;
} }
case GroupBy::Genre:{ 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata));
const int samplerate = std::max(0, item->metadata.samplerate()); const int samplerate = std::max(0, item->metadata.samplerate());
item->display_text = QString::number(samplerate); item->display_text = QString::number(samplerate);
item->sort_text = SortTextForNumber(samplerate) + " "; item->sort_text = SortTextForNumber(samplerate) + QLatin1Char(' ');
break; break;
} }
case GroupBy::Bitdepth:{ 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata));
const int bitdepth = std::max(0, item->metadata.bitdepth()); const int bitdepth = std::max(0, item->metadata.bitdepth());
item->display_text = QString::number(bitdepth); item->display_text = QString::number(bitdepth);
item->sort_text = SortTextForNumber(bitdepth) + " "; item->sort_text = SortTextForNumber(bitdepth) + QLatin1Char(' ');
break; break;
} }
case GroupBy::Bitrate:{ 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, item->metadata));
const int bitrate = std::max(0, item->metadata.bitrate()); const int bitrate = std::max(0, item->metadata.bitrate());
item->display_text = QString::number(bitrate); item->display_text = QString::number(bitrate);
item->sort_text = SortTextForNumber(bitrate) + " "; item->sort_text = SortTextForNumber(bitrate) + QLatin1Char(' ');
break; break;
} }
case GroupBy::None: 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); CollectionItem *item = InitItem(group_by, signal, parent, container_level);
if (parent != root_ && !parent->key.isEmpty()) { if (parent != root_ && !parent->key.isEmpty()) {
item->key = parent->key + "-"; item->key = parent->key + QLatin1Char('-');
} }
switch (group_by) { 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s));
const int year = std::max(0, s.year()); const int year = std::max(0, s.year());
item->display_text = QString::number(year); item->display_text = QString::number(year);
item->sort_text = SortTextForNumber(year) + " "; item->sort_text = SortTextForNumber(year) + QLatin1Char(' ');
break; break;
} }
case GroupBy::OriginalYear:{ 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s));
const int year = std::max(0, s.effective_originalyear()); const int year = std::max(0, s.effective_originalyear());
item->display_text = QString::number(year); item->display_text = QString::number(year);
item->sort_text = SortTextForNumber(year) + " "; item->sort_text = SortTextForNumber(year) + QLatin1Char(' ');
break; break;
} }
case GroupBy::Genre:{ 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s));
const int samplerate = std::max(0, s.samplerate()); const int samplerate = std::max(0, s.samplerate());
item->display_text = QString::number(samplerate); item->display_text = QString::number(samplerate);
item->sort_text = SortTextForNumber(samplerate) + " "; item->sort_text = SortTextForNumber(samplerate) + QLatin1Char(' ');
break; break;
} }
case GroupBy::Bitdepth:{ 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s));
const int bitdepth = std::max(0, s.bitdepth()); const int bitdepth = std::max(0, s.bitdepth());
item->display_text = QString::number(bitdepth); item->display_text = QString::number(bitdepth);
item->sort_text = SortTextForNumber(bitdepth) + " "; item->sort_text = SortTextForNumber(bitdepth) + QLatin1Char(' ');
break; break;
} }
case GroupBy::Bitrate:{ 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)); item->key.append(ContainerKey(group_by, separate_albums_by_grouping, s));
const int bitrate = std::max(0, s.bitrate()); const int bitrate = std::max(0, s.bitrate());
item->display_text = QString::number(bitrate); item->display_text = QString::number(bitrate);
item->sort_text = SortTextForNumber(bitrate) + " "; item->sort_text = SortTextForNumber(bitrate) + QLatin1Char(' ');
break; break;
} }
case GroupBy::None: case GroupBy::None:
@ -1658,7 +1659,7 @@ CollectionItem *CollectionModel::ItemFromSong(const GroupBy group_by, const bool
} }
FinishItem(group_by, signal, create_divider, parent, item); 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; return item;
@ -1678,7 +1679,7 @@ void CollectionModel::FinishItem(const GroupBy group_by, const bool signal, cons
if (create_divider && show_dividers_) { if (create_divider && show_dividers_) {
QString divider_key = DividerKey(group_by, item); QString divider_key = DividerKey(group_by, item);
if (!divider_key.isEmpty()) { 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)) { 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_); CollectionItem *divider = new CollectionItem(CollectionItem::Type_Divider, root_);
divider->key = divider_key; divider->key = divider_key;
divider->display_text = DividerDisplayText(group_by, 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->lazy_loaded = true;
divider_nodes_[divider_key] = divider; divider_nodes_[divider_key] = divider;
@ -1712,14 +1713,14 @@ QString CollectionModel::TextOrUnknown(const QString &text) {
QString CollectionModel::PrettyYearAlbum(const int year, const QString &album) { QString CollectionModel::PrettyYearAlbum(const int year, const QString &album) {
if (year <= 0) return TextOrUnknown(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) { QString CollectionModel::PrettyAlbumDisc(const QString &album, const int disc) {
if (disc <= 0 || Song::AlbumContainsDisc(album)) return TextOrUnknown(album); 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; QString str;
if (year <= 0) str = TextOrUnknown(album); 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; return str;
@ -1738,7 +1739,7 @@ QString CollectionModel::PrettyYearAlbumDisc(const int year, const QString &albu
QString CollectionModel::PrettyDisc(const int disc) { 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) { for (const auto &i : Song::kArticles) {
if (artist.startsWith(i)) { if (artist.startsWith(i)) {
qint64 ilen = i.length(); 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; break;
} }
} }
@ -1776,7 +1777,7 @@ QString CollectionModel::SortTextForArtist(QString artist, const bool skip_artic
QString CollectionModel::SortTextForNumber(const int number) { 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) { 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(); qint64 size = s->value(QLatin1String(size_id), cache_size_default).toInt();
int unit = s->value(size_unit_id, static_cast<int>(CollectionSettingsPage::CacheSizeUnit::MB)).toInt() + 1; int unit = s->value(QLatin1String(size_unit_id), static_cast<int>(CollectionSettingsPage::CacheSizeUnit::MB)).toInt() + 1;
do { do {
size *= 1024; size *= 1024;
@ -1875,7 +1876,7 @@ qint64 CollectionModel::MaximumCacheSize(QSettings *s, const char *size_id, cons
void CollectionModel::GetChildSongs(CollectionItem *item, QList<QUrl> *urls, SongList *songs, QSet<int> *song_ids) const { void CollectionModel::GetChildSongs(CollectionItem *item, QList<QUrl> *urls, SongList *songs, QSet<int> *song_ids) const {
switch (item->type) { switch (item->type) {
case CollectionItem::Type_Container: { case CollectionItem::Type_Container:{
const_cast<CollectionModel*>(this)->LazyPopulate(item); const_cast<CollectionModel*>(this)->LazyPopulate(item);
QList<CollectionItem*> children = item->children; QList<CollectionItem*> children = item->children;

View File

@ -55,7 +55,7 @@
#include "collectionqueryoptions.h" #include "collectionqueryoptions.h"
#include "collectionitem.h" #include "collectionitem.h"
class QSettings; class Settings;
class Application; class Application;
class CollectionBackend; class CollectionBackend;
@ -82,7 +82,7 @@ class CollectionModel : public SimpleTreeModel<CollectionItem> {
LastRole LastRole
}; };
// These values get saved in QSettings - don't change them // These values get saved in Settings - don't change them
enum class GroupBy { enum class GroupBy {
None = 0, None = 0,
AlbumArtist = 1, AlbumArtist = 1,
@ -275,7 +275,7 @@ class CollectionModel : public SimpleTreeModel<CollectionItem> {
QVariant AlbumIcon(const QModelIndex &idx); QVariant AlbumIcon(const QModelIndex &idx);
QVariant data(const CollectionItem *item, const int role) const; QVariant data(const CollectionItem *item, const int role) const;
bool CompareItems(const CollectionItem *a, const CollectionItem *b) 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: private:
SharedPtr<CollectionBackend> backend_; SharedPtr<CollectionBackend> backend_;

View File

@ -58,22 +58,22 @@ CollectionQuery::CollectionQuery(const QSqlDatabase &db, const QString &songs_ta
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
QStringList tokens(filter_text.split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts)); QStringList tokens(filter_text.split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts));
#else #else
QStringList tokens(filter_text.split(QRegularExpression("\\s+"), QString::SkipEmptyParts)); QStringList tokens(filter_text.split(QRegularExpression(QStringLiteral("\\s+")), QString::SkipEmptyParts));
#endif #endif
QString query; QString query;
for (QString token : tokens) { for (QString token : tokens) {
token.remove('(') token.remove(QLatin1Char('('))
.remove(')') .remove(QLatin1Char(')'))
.remove('"') .remove(QLatin1Char('"'))
.replace('-', ' '); .replace(QLatin1Char('-'), QLatin1Char(' '));
if (token.contains(':')) { if (token.contains(QLatin1Char(':'))) {
const QString columntoken = token.section(':', 0, 0); const QString columntoken = token.section(QLatin1Char(':'), 0, 0);
QString subtoken = token.section(':', 1, -1).replace(QLatin1String(":"), QLatin1String(" ")).trimmed(); QString subtoken = token.section(QLatin1Char(':'), 1, -1).replace(QLatin1String(":"), QLatin1String(" ")).trimmed();
if (subtoken.isEmpty()) continue; if (subtoken.isEmpty()) continue;
if (Song::kFtsColumns.contains("fts" + columntoken, Qt::CaseInsensitive)) { if (Song::kFtsColumns.contains(QLatin1String("fts") + columntoken, Qt::CaseInsensitive)) {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1String(" "));
query += "fts" + columntoken + ":\"" + subtoken + "\"*"; query += QStringLiteral("fts") + columntoken + QStringLiteral(":\"") + subtoken + QStringLiteral("\"*");
} }
else if (Song::kNumericalColumns.contains(columntoken, Qt::CaseInsensitive)) { else if (Song::kNumericalColumns.contains(columntoken, Qt::CaseInsensitive)) {
QString comparator = RemoveSqlOperator(subtoken); 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) { else if (columntoken.compare(QLatin1String("length"), Qt::CaseInsensitive) == 0) {
// Time is saved in nanoseconds, so add 9 0's // 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); AddWhere(columntoken, parsedTime, comparator);
} }
else { else {
@ -93,14 +93,14 @@ CollectionQuery::CollectionQuery(const QSqlDatabase &db, const QString &songs_ta
else { else {
token = token.replace(QLatin1String(":"), QLatin1String(" ")).trimmed(); token = token.replace(QLatin1String(":"), QLatin1String(" ")).trimmed();
if (!token.isEmpty()) { if (!token.isEmpty()) {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query += "\"" + token + "\"*"; query += QLatin1Char('\"') + token + QStringLiteral("\"*");
} }
} }
} }
else { else {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query += "\"" + token + "\"*"; query += QLatin1Char('\"') + token + QStringLiteral("\"*");
} }
} }
if (!query.isEmpty()) { if (!query.isEmpty()) {
@ -141,7 +141,7 @@ QString CollectionQuery::RemoveSqlOperator(QString &token) {
} }
token.remove(rxOp); token.remove(rxOp);
if (op == "!=") { if (op == QStringLiteral("!=")) {
op = QStringLiteral("<>"); op = QStringLiteral("<>");
} }
@ -161,7 +161,7 @@ void CollectionQuery::AddWhere(const QString &column, const QVariant &value, con
bound_values_ << single_value; 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 { else {
// Do integers inline - sqlite seems to get confused when you pass integers to bound parameters // 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, // 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. // So we have to use a certain tolerance, so that the searched value is definetly included.
const float tolerance = 0.001F; const float tolerance = 0.001F;
if (op == "<") { if (op == QStringLiteral("<")) {
AddWhere(QStringLiteral("rating"), parsed_rating-tolerance, QStringLiteral("<")); AddWhere(QStringLiteral("rating"), parsed_rating-tolerance, QStringLiteral("<"));
} }
else if (op == ">") { else if (op == QStringLiteral(">")) {
AddWhere(QStringLiteral("rating"), parsed_rating+tolerance, QStringLiteral(">")); AddWhere(QStringLiteral("rating"), parsed_rating+tolerance, QStringLiteral(">"));
} }
else if (op == "<=") { else if (op == QStringLiteral("<=")) {
AddWhere(QStringLiteral("rating"), parsed_rating+tolerance, QStringLiteral("<=")); AddWhere(QStringLiteral("rating"), parsed_rating+tolerance, QStringLiteral("<="));
} }
else if (op == ">=") { else if (op == QStringLiteral(">=")) {
AddWhere(QStringLiteral("rating"), parsed_rating-tolerance, QStringLiteral(">=")); AddWhere(QStringLiteral("rating"), parsed_rating-tolerance, QStringLiteral(">="));
} }
else if (op == "<>") { else if (op == QStringLiteral("<>")) {
where_clauses_ << QStringLiteral("(rating<? OR rating>?)"); where_clauses_ << QStringLiteral("(rating<? OR rating>?)");
bound_values_ << parsed_rating - tolerance; bound_values_ << parsed_rating - tolerance;
bound_values_ << parsed_rating + tolerance; bound_values_ << parsed_rating + tolerance;
@ -239,7 +239,7 @@ void CollectionQuery::AddCompilationRequirement(const bool compilation) {
QString CollectionQuery::GetInnerQuery() const { QString CollectionQuery::GetInnerQuery() const {
return duplicates_only_ 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 " "ON (%songs_table.artist = dsongs.dup_artist "
"AND %songs_table.album = dsongs.dup_album " "AND %songs_table.album = dsongs.dup_album "
"AND %songs_table.title = dsongs.dup_title) ") "AND %songs_table.title = dsongs.dup_title) ")
@ -262,14 +262,14 @@ bool CollectionQuery::Exec() {
where_clauses << QStringLiteral("unavailable = 0"); 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("%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_); sql.replace(QLatin1String("%fts_table"), fts_table_);
if (!QSqlQuery::prepare(sql)) return false; if (!QSqlQuery::prepare(sql)) return false;

View File

@ -52,6 +52,7 @@
#include "core/mimedata.h" #include "core/mimedata.h"
#include "core/musicstorage.h" #include "core/musicstorage.h"
#include "core/deletefiles.h" #include "core/deletefiles.h"
#include "core/settings.h"
#include "utilities/filemanagerutils.h" #include "utilities/filemanagerutils.h"
#include "collection.h" #include "collection.h"
#include "collectionbackend.h" #include "collectionbackend.h"
@ -128,7 +129,7 @@ void CollectionView::SaveFocus() {
last_selected_container_ = QString(); last_selected_container_ = QString();
switch (type.toInt()) { switch (type.toInt()) {
case CollectionItem::Type_Song: { case CollectionItem::Type_Song:{
QModelIndex index = qobject_cast<QSortFilterProxyModel*>(model())->mapToSource(current); QModelIndex index = qobject_cast<QSortFilterProxyModel*>(model())->mapToSource(current);
SongList songs = app_->collection_model()->GetChildSongs(index); SongList songs = app_->collection_model()->GetChildSongs(index);
if (!songs.isEmpty()) { if (!songs.isEmpty()) {
@ -138,7 +139,7 @@ void CollectionView::SaveFocus() {
} }
case CollectionItem::Type_Container: case CollectionItem::Type_Container:
case CollectionItem::Type_Divider: { case CollectionItem::Type_Divider:{
QString text = model()->data(current, CollectionModel::Role_SortText).toString(); QString text = model()->data(current, CollectionModel::Role_SortText).toString();
last_selected_container_ = text; last_selected_container_ = text;
break; break;
@ -197,7 +198,7 @@ bool CollectionView::RestoreLevelFocus(const QModelIndex &parent) {
break; break;
case CollectionItem::Type_Container: case CollectionItem::Type_Container:
case CollectionItem::Type_Divider: { case CollectionItem::Type_Divider:{
QString text = model()->data(current, CollectionModel::Role_SortText).toString(); QString text = model()->data(current, CollectionModel::Role_SortText).toString();
if (!last_selected_container_.isEmpty() && last_selected_container_ == text) { if (!last_selected_container_.isEmpty() && last_selected_container_ == text) {
expand(current); expand(current);
@ -224,7 +225,7 @@ bool CollectionView::RestoreLevelFocus(const QModelIndex &parent) {
void CollectionView::ReloadSettings() { void CollectionView::ReloadSettings() {
QSettings settings; Settings settings;
settings.beginGroup(CollectionSettingsPage::kSettingsGroup); settings.beginGroup(CollectionSettingsPage::kSettingsGroup);
SetAutoOpen(settings.value("auto_open", false).toBool()); SetAutoOpen(settings.value("auto_open", false).toBool());

View File

@ -48,6 +48,7 @@
#include "core/logging.h" #include "core/logging.h"
#include "core/tagreaderclient.h" #include "core/tagreaderclient.h"
#include "core/taskmanager.h" #include "core/taskmanager.h"
#include "core/settings.h"
#include "utilities/imageutils.h" #include "utilities/imageutils.h"
#include "utilities/timeconstants.h" #include "utilities/timeconstants.h"
#include "collectiondirectory.h" #include "collectiondirectory.h"
@ -150,7 +151,7 @@ void CollectionWatcher::ReloadSettingsAsync() {
void CollectionWatcher::ReloadSettings() { void CollectionWatcher::ReloadSettings() {
const bool was_monitoring_before = monitor_; const bool was_monitoring_before = monitor_;
QSettings s; Settings s;
s.beginGroup(CollectionSettingsPage::kSettingsGroup); s.beginGroup(CollectionSettingsPage::kSettingsGroup);
scan_on_startup_ = s.value("startup_scan", true).toBool(); scan_on_startup_ = s.value("startup_scan", true).toBool();
monitor_ = s.value("monitor", true).toBool(); monitor_ = s.value("monitor", true).toBool();
@ -316,7 +317,7 @@ SongList CollectionWatcher::ScanTransaction::FindSongsInSubdirectory(const QStri
if (cached_songs_dirty_) { if (cached_songs_dirty_) {
const SongList songs = watcher_->backend_->FindSongsInDirectory(dir_); const SongList songs = watcher_->backend_->FindSongsInDirectory(dir_);
for (const Song &song : songs) { 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_.insert(p, song);
} }
cached_songs_dirty_ = false; cached_songs_dirty_ = false;
@ -334,7 +335,7 @@ bool CollectionWatcher::ScanTransaction::HasSongsWithMissingFingerprint(const QS
if (cached_songs_missing_fingerprint_dirty_) { if (cached_songs_missing_fingerprint_dirty_) {
const SongList songs = watcher_->backend_->SongsWithMissingFingerprint(dir_); const SongList songs = watcher_->backend_->SongsWithMissingFingerprint(dir_);
for (const Song &song : songs) { 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_.insert(p, song);
} }
cached_songs_missing_fingerprint_dirty_ = false; cached_songs_missing_fingerprint_dirty_ = false;
@ -349,7 +350,7 @@ bool CollectionWatcher::ScanTransaction::HasSongsWithMissingLoudnessCharacterist
if (cached_songs_missing_loudness_characteristics_dirty_) { if (cached_songs_missing_loudness_characteristics_dirty_) {
const SongList songs = watcher_->backend_->SongsWithMissingLoudnessCharacteristics(dir_); const SongList songs = watcher_->backend_->SongsWithMissingLoudnessCharacteristics(dir_);
for (const Song &song : songs) { 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_.insert(p, song);
} }
cached_songs_missing_loudness_characteristics_dirty_ = false; cached_songs_missing_loudness_characteristics_dirty_ = false;
@ -510,7 +511,7 @@ void CollectionWatcher::ScanSubdirectory(const QString &path, const CollectionSu
else { else {
QString ext_part(ExtensionPart(child)); QString ext_part(ExtensionPart(child));
QString dir_part(DirectoryPart(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); t->AddToProgress(1);
} }
else if (sValidImages.contains(ext_part)) { else if (sValidImages.contains(ext_part)) {
@ -643,7 +644,7 @@ void CollectionWatcher::ScanSubdirectory(const QString &path, const CollectionSu
} }
} }
#endif #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. // The song is in the database and still on disk.
// Check the mtime to see if it's been changed since it was added. // 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; QStringList scanned_paths;
for (const Song &song : songs) { for (const Song &song : songs) {
if (stop_requested_ || abort_requested_) break; 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; if (scanned_paths.contains(song_path)) continue;
ScanTransaction transaction(this, song.directory_id(), false, true, mark_songs_unavailable_); ScanTransaction transaction(this, song.directory_id(), false, true, mark_songs_unavailable_);
CollectionSubdirectoryList subdirs(transaction.GetAllSubdirs()); CollectionSubdirectoryList subdirs(transaction.GetAllSubdirs());

View File

@ -252,14 +252,14 @@ class CollectionWatcher : public QObject {
}; };
inline QString CollectionWatcher::NoExtensionPart(const QString &fileName) { 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 // Thanks Amarok
inline QString CollectionWatcher::ExtensionPart(const QString &fileName) { 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) { inline QString CollectionWatcher::DirectoryPart(const QString &fileName) {
return fileName.section('/', 0, -2); return fileName.section(QLatin1Char('/'), 0, -2);
} }
#endif // COLLECTIONWATCHER_H #endif // COLLECTIONWATCHER_H

View File

@ -36,6 +36,7 @@
#include "core/logging.h" #include "core/logging.h"
#include "core/iconloader.h" #include "core/iconloader.h"
#include "core/settings.h"
#include "settings/collectionsettingspage.h" #include "settings/collectionsettingspage.h"
#include "collectionmodel.h" #include "collectionmodel.h"
#include "savedgroupingmanager.h" #include "savedgroupingmanager.h"
@ -72,11 +73,11 @@ SavedGroupingManager::~SavedGroupingManager() {
QString SavedGroupingManager::GetSavedGroupingsSettingsGroup(const QString &settings_group) { QString SavedGroupingManager::GetSavedGroupingsSettingsGroup(const QString &settings_group) {
if (settings_group.isEmpty() || settings_group == CollectionSettingsPage::kSettingsGroup) { if (settings_group.isEmpty() || settings_group == QLatin1String(CollectionSettingsPage::kSettingsGroup)) {
return kSavedGroupingsSettingsGroup; return QLatin1String(kSavedGroupingsSettingsGroup);
} }
else { else {
return QString(kSavedGroupingsSettingsGroup) + "_" + settings_group; return QLatin1String(kSavedGroupingsSettingsGroup) + QLatin1Char('_') + settings_group;
} }
} }
@ -85,67 +86,67 @@ QString SavedGroupingManager::GroupByToString(const CollectionModel::GroupBy g)
switch (g) { switch (g) {
case CollectionModel::GroupBy::None: case CollectionModel::GroupBy::None:
case CollectionModel::GroupBy::GroupByCount: { case CollectionModel::GroupBy::GroupByCount:{
return tr("None"); return tr("None");
} }
case CollectionModel::GroupBy::AlbumArtist: { case CollectionModel::GroupBy::AlbumArtist:{
return tr("Album artist"); return tr("Album artist");
} }
case CollectionModel::GroupBy::Artist: { case CollectionModel::GroupBy::Artist:{
return tr("Artist"); return tr("Artist");
} }
case CollectionModel::GroupBy::Album: { case CollectionModel::GroupBy::Album:{
return tr("Album"); return tr("Album");
} }
case CollectionModel::GroupBy::AlbumDisc: { case CollectionModel::GroupBy::AlbumDisc:{
return tr("Album - Disc"); return tr("Album - Disc");
} }
case CollectionModel::GroupBy::YearAlbum: { case CollectionModel::GroupBy::YearAlbum:{
return tr("Year - Album"); return tr("Year - Album");
} }
case CollectionModel::GroupBy::YearAlbumDisc: { case CollectionModel::GroupBy::YearAlbumDisc:{
return tr("Year - Album - Disc"); return tr("Year - Album - Disc");
} }
case CollectionModel::GroupBy::OriginalYearAlbum: { case CollectionModel::GroupBy::OriginalYearAlbum:{
return tr("Original year - Album"); return tr("Original year - Album");
} }
case CollectionModel::GroupBy::OriginalYearAlbumDisc: { case CollectionModel::GroupBy::OriginalYearAlbumDisc:{
return tr("Original year - Album - Disc"); return tr("Original year - Album - Disc");
} }
case CollectionModel::GroupBy::Disc: { case CollectionModel::GroupBy::Disc:{
return tr("Disc"); return tr("Disc");
} }
case CollectionModel::GroupBy::Year: { case CollectionModel::GroupBy::Year:{
return tr("Year"); return tr("Year");
} }
case CollectionModel::GroupBy::OriginalYear: { case CollectionModel::GroupBy::OriginalYear:{
return tr("Original year"); return tr("Original year");
} }
case CollectionModel::GroupBy::Genre: { case CollectionModel::GroupBy::Genre:{
return tr("Genre"); return tr("Genre");
} }
case CollectionModel::GroupBy::Composer: { case CollectionModel::GroupBy::Composer:{
return tr("Composer"); return tr("Composer");
} }
case CollectionModel::GroupBy::Performer: { case CollectionModel::GroupBy::Performer:{
return tr("Performer"); return tr("Performer");
} }
case CollectionModel::GroupBy::Grouping: { case CollectionModel::GroupBy::Grouping:{
return tr("Grouping"); return tr("Grouping");
} }
case CollectionModel::GroupBy::FileType: { case CollectionModel::GroupBy::FileType:{
return tr("File type"); return tr("File type");
} }
case CollectionModel::GroupBy::Format: { case CollectionModel::GroupBy::Format:{
return tr("Format"); return tr("Format");
} }
case CollectionModel::GroupBy::Samplerate: { case CollectionModel::GroupBy::Samplerate:{
return tr("Sample rate"); return tr("Sample rate");
} }
case CollectionModel::GroupBy::Bitdepth: { case CollectionModel::GroupBy::Bitdepth:{
return tr("Bit depth"); return tr("Bit depth");
} }
case CollectionModel::GroupBy::Bitrate: { case CollectionModel::GroupBy::Bitrate:{
return tr("Bitrate"); return tr("Bitrate");
} }
} }
@ -157,13 +158,13 @@ QString SavedGroupingManager::GroupByToString(const CollectionModel::GroupBy g)
void SavedGroupingManager::UpdateModel() { void SavedGroupingManager::UpdateModel() {
model_->setRowCount(0); // don't use clear, it deletes headers model_->setRowCount(0); // don't use clear, it deletes headers
QSettings s; Settings s;
s.beginGroup(saved_groupings_settings_group_); s.beginGroup(saved_groupings_settings_group_);
int version = s.value("version").toInt(); int version = s.value("version").toInt();
if (version == 1) { if (version == 1) {
QStringList saved = s.childKeys(); QStringList saved = s.childKeys();
for (int i = 0; i < saved.size(); ++i) { 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(); QByteArray bytes = s.value(saved.at(i)).toByteArray();
QDataStream ds(&bytes, QIODevice::ReadOnly); QDataStream ds(&bytes, QIODevice::ReadOnly);
CollectionModel::Grouping g; CollectionModel::Grouping g;
@ -181,7 +182,7 @@ void SavedGroupingManager::UpdateModel() {
else { else {
QStringList saved = s.childKeys(); QStringList saved = s.childKeys();
for (int i = 0; i < saved.size(); ++i) { 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)); s.remove(saved.at(i));
} }
} }
@ -192,7 +193,7 @@ void SavedGroupingManager::UpdateModel() {
void SavedGroupingManager::Remove() { void SavedGroupingManager::Remove() {
if (ui_->list->selectionModel()->hasSelection()) { if (ui_->list->selectionModel()->hasSelection()) {
QSettings s; Settings s;
s.beginGroup(saved_groupings_settings_group_); s.beginGroup(saved_groupings_settings_group_);
for (const QModelIndex &idx : ui_->list->selectionModel()->selectedRows()) { for (const QModelIndex &idx : ui_->list->selectionModel()->selectedRows()) {
if (idx.isValid()) { if (idx.isValid()) {

View File

@ -61,7 +61,7 @@ ContextAlbum::ContextAlbum(QWidget *parent)
pixmap_current_opacity_(1.0), pixmap_current_opacity_(1.0),
desired_height_(width()) { desired_height_(width()) {
setObjectName("context-widget-album"); setObjectName(QStringLiteral("context-widget-album"));
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
@ -266,7 +266,7 @@ void ContextAlbum::SearchCoverInProgress() {
downloading_covers_ = true; downloading_covers_ = true;
// Show a spinner animation // Show a spinner animation
spinner_animation_ = make_unique<QMovie>(":/pictures/spinner.gif", QByteArray(), this); spinner_animation_ = make_unique<QMovie>(QStringLiteral(":/pictures/spinner.gif"), QByteArray(), this);
QObject::connect(&*spinner_animation_, &QMovie::updated, this, &ContextAlbum::Update); QObject::connect(&*spinner_animation_, &QMovie::updated, this, &ContextAlbum::Update);
spinner_animation_->start(); spinner_animation_->start();
update(); update();

View File

@ -51,6 +51,7 @@
#include "core/application.h" #include "core/application.h"
#include "core/player.h" #include "core/player.h"
#include "core/song.h" #include "core/song.h"
#include "core/settings.h"
#include "utilities/strutils.h" #include "utilities/strutils.h"
#include "utilities/timeutils.h" #include "utilities/timeutils.h"
#include "widgets/resizabletextedit.h" #include "widgets/resizabletextedit.h"
@ -112,25 +113,25 @@ ContextView::ContextView(QWidget *parent)
setLayout(layout_container_); 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_->setContentsMargins(0, 0, 0, 0);
layout_container_->addWidget(scrollarea_); layout_container_->addWidget(scrollarea_);
scrollarea_->setObjectName("context-scrollarea"); scrollarea_->setObjectName(QStringLiteral("context-scrollarea"));
scrollarea_->setWidgetResizable(true); scrollarea_->setWidgetResizable(true);
scrollarea_->setWidget(widget_scrollarea_); scrollarea_->setWidget(widget_scrollarea_);
scrollarea_->setContentsMargins(0, 0, 0, 0); scrollarea_->setContentsMargins(0, 0, 0, 0);
scrollarea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollarea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollarea_->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollarea_->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
widget_scrollarea_->setObjectName("context-widget-scrollarea"); widget_scrollarea_->setObjectName(QStringLiteral("context-widget-scrollarea"));
widget_scrollarea_->setLayout(layout_scrollarea_); widget_scrollarea_->setLayout(layout_scrollarea_);
widget_scrollarea_->setContentsMargins(0, 0, 0, 0); widget_scrollarea_->setContentsMargins(0, 0, 0, 0);
textedit_top_->setReadOnly(true); textedit_top_->setReadOnly(true);
textedit_top_->setFrameShape(QFrame::NoFrame); 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_->setContentsMargins(15, 15, 15, 15);
layout_scrollarea_->addWidget(textedit_top_); layout_scrollarea_->addWidget(textedit_top_);
layout_scrollarea_->addWidget(widget_album_); layout_scrollarea_->addWidget(widget_album_);
@ -291,20 +292,20 @@ void ContextView::ReloadSettings() {
QString default_font; QString default_font;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
if (QFontDatabase::families().contains(ContextSettingsPage::kDefaultFontFamily)) { if (QFontDatabase::families().contains(QLatin1String(ContextSettingsPage::kDefaultFontFamily))) {
#else #else
if (QFontDatabase().families().contains(ContextSettingsPage::kDefaultFontFamily)) { if (QFontDatabase().families().contains(QLatin1String(ContextSettingsPage::kDefaultFontFamily))) {
#endif #endif
default_font = ContextSettingsPage::kDefaultFontFamily; default_font = QLatin1String(ContextSettingsPage::kDefaultFontFamily);
} }
else { else {
default_font = font().family(); default_font = font().family();
} }
QSettings s; Settings s;
s.beginGroup(ContextSettingsPage::kSettingsGroup); s.beginGroup(ContextSettingsPage::kSettingsGroup);
title_fmt_ = s.value(ContextSettingsPage::kSettingsTitleFmt, "%title% - %artist%").toString(); title_fmt_ = s.value(ContextSettingsPage::kSettingsTitleFmt, QStringLiteral("%title% - %artist%")).toString();
summary_fmt_ = s.value(ContextSettingsPage::kSettingsSummaryFmt, "%album%").toString(); summary_fmt_ = s.value(ContextSettingsPage::kSettingsSummaryFmt, QStringLiteral("%album%")).toString();
action_show_album_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::ALBUM)], true).toBool()); action_show_album_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::ALBUM)], true).toBool());
action_show_data_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::TECHNICAL_DATA)], false).toBool()); action_show_data_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::TECHNICAL_DATA)], false).toBool());
action_show_lyrics_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::SONG_LYRICS)], true).toBool()); action_show_lyrics_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(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) { 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) + QLatin1Char(' ') + suffix));
} }
void ContextView::UpdateNoSong() { void ContextView::UpdateNoSong() {
@ -635,7 +636,7 @@ void ContextView::UpdateLyrics(const quint64 id, const QString &provider, const
lyrics_ = QStringLiteral("No lyrics found.\n"); lyrics_ = QStringLiteral("No lyrics found.\n");
} }
else { else {
lyrics_ = lyrics + "\n\n(Lyrics from " + provider + ")\n"; lyrics_ = lyrics + QStringLiteral("\n\n(Lyrics from ") + provider + QStringLiteral(")\n");
} }
lyrics_id_ = -1; lyrics_id_ = -1;
@ -692,7 +693,7 @@ void ContextView::AlbumCoverLoaded(const Song &song, const QImage &image) {
void ContextView::ActionShowAlbum() { void ContextView::ActionShowAlbum() {
QSettings s; Settings s;
s.beginGroup(ContextSettingsPage::kSettingsGroup); s.beginGroup(ContextSettingsPage::kSettingsGroup);
s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::ALBUM)], action_show_album_->isChecked()); s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::ALBUM)], action_show_album_->isChecked());
s.endGroup(); s.endGroup();
@ -702,7 +703,7 @@ void ContextView::ActionShowAlbum() {
void ContextView::ActionShowData() { void ContextView::ActionShowData() {
QSettings s; Settings s;
s.beginGroup(ContextSettingsPage::kSettingsGroup); s.beginGroup(ContextSettingsPage::kSettingsGroup);
s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::TECHNICAL_DATA)], action_show_data_->isChecked()); s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::TECHNICAL_DATA)], action_show_data_->isChecked());
s.endGroup(); s.endGroup();
@ -712,7 +713,7 @@ void ContextView::ActionShowData() {
void ContextView::ActionShowLyrics() { void ContextView::ActionShowLyrics() {
QSettings s; Settings s;
s.beginGroup(ContextSettingsPage::kSettingsGroup); s.beginGroup(ContextSettingsPage::kSettingsGroup);
s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::SONG_LYRICS)], action_show_lyrics_->isChecked()); s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::SONG_LYRICS)], action_show_lyrics_->isChecked());
s.endGroup(); s.endGroup();
@ -725,7 +726,7 @@ void ContextView::ActionShowLyrics() {
void ContextView::ActionSearchLyrics() { void ContextView::ActionSearchLyrics() {
QSettings s; Settings s;
s.beginGroup(ContextSettingsPage::kSettingsGroup); s.beginGroup(ContextSettingsPage::kSettingsGroup);
s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::SEARCH_LYRICS)], action_search_lyrics_->isChecked()); s.setValue(ContextSettingsPage::kSettingsGroupEnable[static_cast<int>(ContextSettingsPage::ContextSettingsOrder::SEARCH_LYRICS)], action_search_lyrics_->isChecked());
s.endGroup(); s.endGroup();

View File

@ -100,7 +100,7 @@ CommandlineOptions::CommandlineOptions(int argc, char **argv)
play_track_at_(-1), play_track_at_(-1),
show_osd_(false), show_osd_(false),
toggle_pretty_osd_(false), toggle_pretty_osd_(false),
log_levels_(logging::kDefaultLogLevels) { log_levels_(QLatin1String(logging::kDefaultLogLevels)) {
#ifdef Q_OS_WIN32 #ifdef Q_OS_WIN32
Q_UNUSED(argv); Q_UNUSED(argv);
@ -108,7 +108,7 @@ CommandlineOptions::CommandlineOptions(int argc, char **argv)
#ifdef Q_OS_MACOS #ifdef Q_OS_MACOS
// Remove -psn_xxx option that Mac passes when opened from Finder. // Remove -psn_xxx option that Mac passes when opened from Finder.
RemoveArg("-psn", 1); RemoveArg(QStringLiteral("-psn"), 1);
#endif #endif
// Remove the -session option that KDE passes // Remove the -session option that KDE passes
@ -212,9 +212,9 @@ bool CommandlineOptions::Parse() {
if (c == -1) break; if (c == -1) break;
switch (c) { switch (c) {
case 'h': { case 'h':{
QString translated_help_text = QString translated_help_text =
QString(kHelpText) QString::fromUtf8(kHelpText)
.arg(QObject::tr("Usage"), QObject::tr("options"), QObject::tr("URL(s)"), .arg(QObject::tr("Usage"), QObject::tr("options"), QObject::tr("URL(s)"),
QObject::tr("Player options"), QObject::tr("Player options"),
QObject::tr("Start the playlist currently playing"), QObject::tr("Start the playlist currently playing"),
@ -309,7 +309,7 @@ bool CommandlineOptions::Parse() {
case LongOptions::LogLevels: case LongOptions::LogLevels:
log_levels_ = OptArgToString(optarg); log_levels_ = OptArgToString(optarg);
break; break;
case LongOptions::Version: { case LongOptions::Version:{
QString version_text = QString::fromUtf8(kVersionText).arg(QStringLiteral(STRAWBERRY_VERSION_DISPLAY)); QString version_text = QString::fromUtf8(kVersionText).arg(QStringLiteral(STRAWBERRY_VERSION_DISPLAY));
std::cout << version_text.toLocal8Bit().constData() << std::endl; std::cout << version_text.toLocal8Bit().constData() << std::endl;
std::exit(0); std::exit(0);
@ -429,7 +429,7 @@ QString CommandlineOptions::DecodeName(wchar_t *opt) {
#else #else
QString CommandlineOptions::OptArgToString(char *opt) { QString CommandlineOptions::OptArgToString(char *opt) {
return QString(opt); return QString::fromUtf8(opt);
} }
QString CommandlineOptions::DecodeName(char *opt) { QString CommandlineOptions::DecodeName(char *opt) {

View File

@ -47,10 +47,13 @@
#include "sqlquery.h" #include "sqlquery.h"
#include "scopedtransaction.h" #include "scopedtransaction.h"
const char *Database::kDatabaseFilename = "strawberry.db";
const int Database::kSchemaVersion = 18; const int Database::kSchemaVersion = 18;
const int Database::kMinSupportedSchemaVersion = 10;
const char *Database::kMagicAllSongsTables = "%allsongstables"; namespace {
constexpr char kDatabaseFilename[] = "strawberry.db";
constexpr int kMinSupportedSchemaVersion = 10;
constexpr char kMagicAllSongsTables[] = "%allsongstables";
} // namespace
int Database::sNextConnectionId = 1; int Database::sNextConnectionId = 1;
QMutex Database::sNextConnectionIdMutex; QMutex Database::sNextConnectionIdMutex;
@ -131,14 +134,14 @@ QSqlDatabase Database::Connect() {
//qLog(Debug) << "Opened database with connection id" << connection_id; //qLog(Debug) << "Opened database with connection id" << connection_id;
if (injected_database_name_.isNull()) { if (injected_database_name_.isNull()) {
db.setDatabaseName(directory_ + "/" + kDatabaseFilename); db.setDatabaseName(directory_ + QLatin1Char('/') + QLatin1String(kDatabaseFilename));
} }
else { else {
db.setDatabaseName(injected_database_name_); db.setDatabaseName(injected_database_name_);
} }
if (!db.open()) { if (!db.open()) {
app_->AddError("Database: " + db.lastError().text()); app_->AddError(QStringLiteral("Database: ") + db.lastError().text());
return db; return db;
} }
@ -405,16 +408,16 @@ void Database::ExecSongTablesCommands(QSqlDatabase &db, const QStringList &song_
for (const QString &command : commands) { for (const QString &command : commands) {
// There are now lots of "songs" tables that need to have the same schema: songs and device_*_songs. // 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. // 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) { 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. // 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; continue;
} }
qLog(Info) << "Updating" << table << "for" << kMagicAllSongsTables; qLog(Info) << "Updating" << table << "for" << kMagicAllSongsTables;
QString new_command(command); QString new_command(command);
new_command.replace(kMagicAllSongsTables, table); new_command.replace(QLatin1String(kMagicAllSongsTables), table);
SqlQuery query(db); SqlQuery query(db);
query.prepare(new_command); query.prepare(new_command);
if (!query.Exec()) { if (!query.Exec()) {
@ -443,7 +446,7 @@ QStringList Database::SongsTables(QSqlDatabase &db, const int schema_version) {
// look for the tables in the main db // look for the tables in the main db
for (const QString &table : db.tables()) { 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 // look for the tables in attached dbs
@ -453,7 +456,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)); q.prepare(QStringLiteral("SELECT NAME FROM %1.sqlite_master WHERE type='table' AND name='songs' OR name LIKE '%songs'").arg(key));
if (q.Exec()) { if (q.Exec()) {
while (q.next()) { while (q.next()) {
QString tab_name = key + "." + q.value(0).toString(); QString tab_name = key + QStringLiteral(".") + q.value(0).toString();
ret << tab_name; ret << tab_name;
} }
} }
@ -495,13 +498,13 @@ bool Database::IntegrityCheck(const QSqlDatabase &db) {
QString message = q.value(0).toString(); QString message = q.value(0).toString();
// If no errors are found, a single row with the value "ok" is returned // If no errors are found, a single row with the value "ok" is returned
if (message == "ok") { if (message == QStringLiteral("ok")) {
ok = true; ok = true;
break; break;
} }
else { else {
if (!error_reported) { app_->AddError(tr("Database corruption detected.")); } if (!error_reported) { app_->AddError(tr("Database corruption detected.")); }
app_->AddError("Database: " + message); app_->AddError(QStringLiteral("Database: ") + message);
error_reported = true; error_reported = true;
} }
} }

View File

@ -50,6 +50,8 @@ class Database : public QObject {
explicit Database(Application *app, QObject *parent = nullptr, const QString &database_name = QString()); explicit Database(Application *app, QObject *parent = nullptr, const QString &database_name = QString());
~Database() override; ~Database() override;
static const int kSchemaVersion;
struct AttachedDatabase { struct AttachedDatabase {
AttachedDatabase() {} AttachedDatabase() {}
AttachedDatabase(const QString &filename, const QString &schema, bool is_temporary) AttachedDatabase(const QString &filename, const QString &schema, bool is_temporary)
@ -60,11 +62,6 @@ class Database : public QObject {
bool is_temporary_; bool is_temporary_;
}; };
static const int kSchemaVersion;
static const int kMinSupportedSchemaVersion;
static const char *kDatabaseFilename;
static const char *kMagicAllSongsTables;
void ExitAsync(); void ExitAsync();
QSqlDatabase Connect(); QSqlDatabase Connect();
void Close(); void Close();

View File

@ -39,13 +39,13 @@ FilesystemMusicStorage::FilesystemMusicStorage(const Song::Source source, const
bool FilesystemMusicStorage::CopyToStorage(const CopyJob &job, QString &error_text) { bool FilesystemMusicStorage::CopyToStorage(const CopyJob &job, QString &error_text) {
const QFileInfo src = QFileInfo(job.source_); const QFileInfo src = QFileInfo(job.source_);
const QFileInfo dest = QFileInfo(root_ + "/" + job.destination_); const QFileInfo dest = QFileInfo(root_ + QLatin1Char('/') + job.destination_);
QFileInfo cover_src; QFileInfo cover_src;
QFileInfo cover_dest; QFileInfo cover_dest;
if (job.albumcover_ && !job.cover_source_.isEmpty() && !job.cover_dest_.isEmpty()) { if (job.albumcover_ && !job.cover_source_.isEmpty() && !job.cover_dest_.isEmpty()) {
cover_src = QFileInfo(job.cover_source_); cover_src = QFileInfo(job.cover_source_);
cover_dest = QFileInfo(root_ + "/" + job.cover_dest_); cover_dest = QFileInfo(root_ + QLatin1Char('/') + job.cover_dest_);
} }
// Don't do anything if the destination is the same as the source // Don't do anything if the destination is the same as the source

View File

@ -29,6 +29,7 @@
#include <QSettings> #include <QSettings>
#include "core/logging.h" #include "core/logging.h"
#include "settings.h"
#include "iconmapper.h" #include "iconmapper.h"
#include "settings/appearancesettingspage.h" #include "settings/appearancesettingspage.h"
#include "iconloader.h" #include "iconloader.h"
@ -39,14 +40,14 @@ bool IconLoader::custom_icons_ = false;
void IconLoader::Init() { void IconLoader::Init() {
#if !defined(Q_OS_MACOS) && !defined(Q_OS_WIN) #if !defined(Q_OS_MACOS) && !defined(Q_OS_WIN)
QSettings s; Settings s;
s.beginGroup(AppearanceSettingsPage::kSettingsGroup); s.beginGroup(AppearanceSettingsPage::kSettingsGroup);
system_icons_ = s.value("system_icons", false).toBool(); system_icons_ = s.value("system_icons", false).toBool();
s.endGroup(); s.endGroup();
#endif #endif
QDir dir; QDir dir;
if (dir.exists(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/icons")) { if (dir.exists(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/icons"))) {
custom_icons_ = true; custom_icons_ = true;
} }
@ -118,7 +119,7 @@ QIcon IconLoader::Load(const QString &name, const bool system_icon, const int fi
} }
if (custom_icons_) { 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) { for (int s : sizes) {
QString filename(custom_icon_path.arg(s).arg(s).arg(name)); QString filename(custom_icon_path.arg(s).arg(s).arg(name));
if (QFile::exists(filename)) ret.addFile(filename, QSize(s, s)); if (QFile::exists(filename)) ret.addFile(filename, QSize(s, s));

View File

@ -38,100 +38,100 @@ struct IconProperties {
static const QMap<QString, IconProperties> iconmapper_ = { // clazy:exclude=non-pod-global-static static const QMap<QString, IconProperties> iconmapper_ = { // clazy:exclude=non-pod-global-static
{ "albums", { {"media-optical"}} }, { QStringLiteral("albums"), { {QStringLiteral("media-optical")}} },
{ "alsa", { {}} }, { QStringLiteral("alsa"), { {}} },
{ "application-exit", { {}} }, { QStringLiteral("application-exit"), { {}} },
{ "applications-internet", { {}} }, { QStringLiteral("applications-internet"), { {}} },
{ "bluetooth", { {"preferences-system-bluetooth", "bluetooth-active"}} }, { QStringLiteral("bluetooth"), { {QStringLiteral("preferences-system-bluetooth"), QStringLiteral("bluetooth-active")}} },
{ "cdcase", { {"cdcover", "media-optical"}} }, { QStringLiteral("cdcase"), { {QStringLiteral("cdcover"), QStringLiteral("media-optical")}} },
{ "media-optical", { {"cd"}} }, { QStringLiteral("media-optical"), { {QStringLiteral("cd")}} },
{ "configure", { {}} }, { QStringLiteral("configure"), { {}} },
{ "device-ipod-nano", { {}} }, { QStringLiteral("device-ipod-nano"), { {}} },
{ "device-ipod", { {}} }, { QStringLiteral("device-ipod"), { {}} },
{ "device-phone", { {}} }, { QStringLiteral("device-phone"), { {}} },
{ "device", { {"drive-removable-media-usb-pendrive"}} }, { QStringLiteral("device"), { {QStringLiteral("drive-removable-media-usb-pendrive")}} },
{ "device-usb-drive", { {}} }, { QStringLiteral("device-usb-drive"), { {}} },
{ "device-usb-flash", { {}} }, { QStringLiteral("device-usb-flash"), { {}} },
{ "dialog-error", { {}} }, { QStringLiteral("dialog-error"), { {}} },
{ "dialog-information", { {}} }, { QStringLiteral("dialog-information"), { {}} },
{ "dialog-ok-apply", { {}} }, { QStringLiteral("dialog-ok-apply"), { {}} },
{ "dialog-password", { {}} }, { QStringLiteral("dialog-password"), { {}} },
{ "dialog-warning", { {}} }, { QStringLiteral("dialog-warning"), { {}} },
{ "document-download", { {"download"}} }, { QStringLiteral("document-download"), { {QStringLiteral("download")}} },
{ "document-new", { {}} }, { QStringLiteral("document-new"), { {}} },
{ "document-open-folder", { {}} }, { QStringLiteral("document-open-folder"), { {}} },
{ "document-open", { {}} }, { QStringLiteral("document-open"), { {}} },
{ "document-save", { {}} }, { QStringLiteral("document-save"), { {}} },
{ "document-search", { {}} }, { QStringLiteral("document-search"), { {}} },
{ "document-open-remote", { {}} }, { QStringLiteral("document-open-remote"), { {}} },
{ "download", { {"applications-internet", "network-workgroup"}} }, { QStringLiteral("download"), { {QStringLiteral("applications-internet"), QStringLiteral("network-workgroup")}} },
{ "edit-clear-list", { {"edit-clear-list","edit-clear-all"}} }, { QStringLiteral("edit-clear-list"), { {QStringLiteral("edit-clear-list"), QStringLiteral("edit-clear-all")}} },
{ "edit-clear-locationbar-ltr", { {"edit-clear-locationbar-ltr"}} }, { QStringLiteral("edit-clear-locationbar-ltr"), { {QStringLiteral("edit-clear-locationbar-ltr")}} },
{ "edit-copy", { {}} }, { QStringLiteral("edit-copy"), { {}} },
{ "edit-delete", { {}} }, { QStringLiteral("edit-delete"), { {}} },
{ "edit-find", { {}} }, { QStringLiteral("edit-find"), { {}} },
{ "edit-redo", { {}} }, { QStringLiteral("edit-redo"), { {}} },
{ "edit-rename", { {}} }, { QStringLiteral("edit-rename"), { {}} },
{ "edit-undo", { {}} }, { QStringLiteral("edit-undo"), { {}} },
{ "electrocompaniet", { {}} }, { QStringLiteral("electrocompaniet"), { {}} },
{ "equalizer", { {"view-media-equalizer"}} }, { QStringLiteral("equalizer"), { {QStringLiteral("view-media-equalizer")}} },
{ "folder-new", { {}} }, { QStringLiteral("folder-new"), { {}} },
{ "folder", { {}} }, { QStringLiteral("folder"), { {}} },
{ "folder-sound", { {"folder-music"}} }, { QStringLiteral("folder-sound"), { {QStringLiteral("folder-music")}} },
{ "footsteps", { {"go-jump"}} }, { QStringLiteral("footsteps"), { {QStringLiteral("go-jump")}} },
{ "go-down", { {}} }, { QStringLiteral("go-down"), { {}} },
{ "go-home", { {}} }, { QStringLiteral("go-home"), { {}} },
{ "go-jump", { {}} }, { QStringLiteral("go-jump"), { {}} },
{ "go-next", { {}} }, { QStringLiteral("go-next"), { {}} },
{ "go-previous", { {}} }, { QStringLiteral("go-previous"), { {}} },
{ "go-up", { {}} }, { QStringLiteral("go-up"), { {}} },
{ "gstreamer", { {"phonon-gstreamer"}} }, { QStringLiteral("gstreamer"), { {QStringLiteral("phonon-gstreamer")}} },
{ "headset", { {"audio-headset"}} }, { QStringLiteral("headset"), { {QStringLiteral("audio-headset")}} },
{ "help-hint", { {}} }, { QStringLiteral("help-hint"), { {}} },
{ "intel", { {}} }, { QStringLiteral("intel"), { {}} },
{ "jack", { {"audio-input-line"}} }, { QStringLiteral("jack"), { {QStringLiteral("audio-input-line")}} },
{ "keyboard", { {"input-keyboard"}} }, { QStringLiteral("keyboard"), { {QStringLiteral("input-keyboard")}} },
{ "list-add", { {}} }, { QStringLiteral("list-add"), { {}} },
{ "list-remove", { {}} }, { QStringLiteral("list-remove"), { {}} },
{ "love", { {"heart", "emblem-favorite"}} }, { QStringLiteral("love"), { {QStringLiteral("heart"), QStringLiteral("emblem-favorite")}} },
{ "mcintosh-player", { {}} }, { QStringLiteral("mcintosh-player"), { {}} },
{ "mcintosh", { {}} }, { QStringLiteral("mcintosh"), { {}} },
{ "mcintosh-text", { {}} }, { QStringLiteral("mcintosh-text"), { {}} },
{ "media-eject", { {}} }, { QStringLiteral("media-eject"), { {}} },
{ "media-playback-pause", { {"media-pause"}} }, { QStringLiteral("media-playback-pause"), { {QStringLiteral("media-pause")}} },
{ "media-playlist-repeat", { {}} }, { QStringLiteral("media-playlist-repeat"), { {}} },
{ "media-playlist-shuffle", { {""}} }, { QStringLiteral("media-playlist-shuffle"), { {QLatin1String("")}} },
{ "media-playback-start", { {"media-play", "media-playback-playing"}} }, { QStringLiteral("media-playback-start"), { {QStringLiteral("media-play"), QStringLiteral("media-playback-playing")}} },
{ "media-seek-backward", { {}} }, { QStringLiteral("media-seek-backward"), { {}} },
{ "media-seek-forward", { {}} }, { QStringLiteral("media-seek-forward"), { {}} },
{ "media-skip-backward", { {}} }, { QStringLiteral("media-skip-backward"), { {}} },
{ "media-skip-forward", { {}} }, { QStringLiteral("media-skip-forward"), { {}} },
{ "media-playback-stop", { {"media-stop"}} }, { QStringLiteral("media-playback-stop"), { {QStringLiteral("media-stop")}} },
{ "moodbar", { {"preferences-desktop-icons"}} }, { QStringLiteral("moodbar"), { {QStringLiteral("preferences-desktop-icons")}} },
{ "nvidia", { {}} }, { QStringLiteral("nvidia"), { {}} },
{ "pulseaudio", { {}} }, { QStringLiteral("pulseaudio"), { {}} },
{ "realtek", { {}} }, { QStringLiteral("realtek"), { {}} },
{ "scrobble-disabled", { {}} }, { QStringLiteral("scrobble-disabled"), { {}} },
{ "scrobble", { {"love"}} }, { QStringLiteral("scrobble"), { {QStringLiteral("love")}} },
{ "search", { {}} }, { QStringLiteral("search"), { {}} },
{ "soundcard", { {"audiocard", "audio-card"}} }, { QStringLiteral("soundcard"), { {QStringLiteral("audiocard"), QStringLiteral("audio-card")}} },
{ "speaker", { {}} }, { QStringLiteral("speaker"), { {}} },
{ "star-grey", { {}} }, { QStringLiteral("star-grey"), { {}} },
{ "star", { {}} }, { QStringLiteral("star"), { {}} },
{ "strawberry", { {}} }, { QStringLiteral("strawberry"), { {}} },
{ "subsonic", { {}} }, { QStringLiteral("subsonic"), { {}} },
{ "tidal", { {}} }, { QStringLiteral("tidal"), { {}} },
{ "tools-wizard", { {}} }, { QStringLiteral("tools-wizard"), { {}} },
{ "view-choose", { {}} }, { QStringLiteral("view-choose"), { {}} },
{ "view-fullscreen", { {}} }, { QStringLiteral("view-fullscreen"), { {}} },
{ "view-media-lyrics", { {}} }, { QStringLiteral("view-media-lyrics"), { {}} },
{ "view-media-playlist", { {}} }, { QStringLiteral("view-media-playlist"), { {}} },
{ "view-media-visualization", { {"preferences-desktop-theme"}} }, { QStringLiteral("view-media-visualization"), { {QStringLiteral("preferences-desktop-theme")}} },
{ "view-refresh", { {}} }, { QStringLiteral("view-refresh"), { {}} },
{ "library-music", { {"vinyl"}} }, { QStringLiteral("library-music"), { {QStringLiteral("vinyl")}} },
{ "vlc", { {}} }, { QStringLiteral("vlc"), { {}} },
{ "zoom-in", { {}} }, { QStringLiteral("zoom-in"), { {}} },
{ "zoom-out", { {}, 0, 0 } } { QStringLiteral("zoom-out"), { {}, 0, 0 } }
}; };

View File

@ -60,13 +60,12 @@
#include <QDir> #include <QDir>
#include <QEvent> #include <QEvent>
#include <QFile> #include <QFile>
#include <QSettings>
#include <QtDebug> #include <QtDebug>
QDebug operator<<(QDebug dbg, NSObject *object) { QDebug operator<<(QDebug dbg, NSObject *object) {
QString ns_format = [[NSString stringWithFormat:@"%@", object] UTF8String]; const QString ns_format = QString::fromUtf8([[NSString stringWithFormat:@"%@", object] UTF8String]);
dbg.nospace() << ns_format; dbg.nospace() << ns_format;
return dbg.space(); return dbg.space();

View File

@ -57,7 +57,7 @@ void MacFSListener::EventStreamCallback(ConstFSEventStreamRef stream, void *user
for (size_t i = 0; i < num_events; ++i) { for (size_t i = 0; i < num_events; ++i) {
QString path = QString::fromUtf8(paths[i]); QString path = QString::fromUtf8(paths[i]);
qLog(Debug) << "Something changed at:" << path; qLog(Debug) << "Something changed at:" << path;
while (path.endsWith('/')) { while (path.endsWith(QLatin1Char('/'))) {
path.chop(1); path.chop(1);
} }
emit me->PathChanged(path); emit me->PathChanged(path);

View File

@ -70,7 +70,7 @@ class MacSystemTrayIconPrivate {
MacSystemTrayIconPrivate() { MacSystemTrayIconPrivate() {
dock_menu_ = [[NSMenu alloc] initWithTitle:@"DockMenu"]; dock_menu_ = [[NSMenu alloc] initWithTitle:@"DockMenu"];
QString title = QT_TR_NOOP("Now Playing"); QString title = QT_TR_NOOP(QStringLiteral("Now Playing"));
NSString *t = [[NSString alloc] initWithUTF8String:title.toUtf8().constData()]; NSString *t = [[NSString alloc] initWithUTF8String:title.toUtf8().constData()];
now_playing_ = [[NSMenuItem alloc] initWithTitle:t action:nullptr keyEquivalent:@""]; now_playing_ = [[NSMenuItem alloc] initWithTitle:t action:nullptr keyEquivalent:@""];
now_playing_artist_ = [[NSMenuItem alloc] initWithTitle:@"Nothing to see here" action:nullptr keyEquivalent:@""]; now_playing_artist_ = [[NSMenuItem alloc] initWithTitle:@"Nothing to see here" action:nullptr keyEquivalent:@""];
@ -89,7 +89,7 @@ class MacSystemTrayIconPrivate {
void AddMenuItem(QAction *action) { void AddMenuItem(QAction *action) {
// Strip accelarators from name. // Strip accelarators from name.
QString text = action->text().remove("&"); QString text = action->text().remove(QLatin1Char('&'));
NSString *title = [[NSString alloc] initWithUTF8String: text.toUtf8().constData()]; NSString *title = [[NSString alloc] initWithUTF8String: text.toUtf8().constData()];
// Create an object that can receive user clicks and pass them on to the QAction. // Create an object that can receive user clicks and pass them on to the QAction.
Target *target = [[Target alloc] initWithQAction:action]; Target *target = [[Target alloc] initWithQAction:action];
@ -152,10 +152,10 @@ class MacSystemTrayIconPrivate {
SystemTrayIcon::SystemTrayIcon(QObject *parent) SystemTrayIcon::SystemTrayIcon(QObject *parent)
: QObject(parent), : QObject(parent),
normal_icon_(QPixmap(":/pictures/strawberry.png").scaled(128, 128, Qt::KeepAspectRatio, Qt::SmoothTransformation)), normal_icon_(QPixmap(QStringLiteral(":/pictures/strawberry.png")).scaled(128, 128, Qt::KeepAspectRatio, Qt::SmoothTransformation)),
grey_icon_(QPixmap(":/pictures/strawberry-grey.png").scaled(128, 128, Qt::KeepAspectRatio, Qt::SmoothTransformation)), grey_icon_(QPixmap(QStringLiteral(":/pictures/strawberry-grey.png")).scaled(128, 128, Qt::KeepAspectRatio, Qt::SmoothTransformation)),
playing_icon_(":/pictures/tiny-play.png"), playing_icon_(QStringLiteral(":/pictures/tiny-play.png")),
paused_icon_(":/pictures/tiny-pause.png"), paused_icon_(QStringLiteral(":/pictures/tiny-pause.png")),
trayicon_progress_(false), trayicon_progress_(false),
song_progress_(0) { song_progress_(0) {

View File

@ -104,6 +104,7 @@
# include "qtsystemtrayicon.h" # include "qtsystemtrayicon.h"
#endif #endif
#include "networkaccessmanager.h" #include "networkaccessmanager.h"
#include "settings.h"
#include "utilities/envutils.h" #include "utilities/envutils.h"
#include "utilities/filemanagerutils.h" #include "utilities/filemanagerutils.h"
#include "utilities/timeconstants.h" #include "utilities/timeconstants.h"
@ -301,13 +302,13 @@ MainWindow::MainWindow(Application *app, SharedPtr<SystemTrayIcon> tray_icon, OS
}), }),
smartplaylists_view_(new SmartPlaylistsViewContainer(app, this)), smartplaylists_view_(new SmartPlaylistsViewContainer(app, this)),
#ifdef HAVE_SUBSONIC #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), QLatin1String(SubsonicSettingsPage::kSettingsGroup), SettingsDialog::Page::Subsonic, this)),
#endif #endif
#ifdef HAVE_TIDAL #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), QLatin1String(TidalSettingsPage::kSettingsGroup), SettingsDialog::Page::Tidal, this)),
#endif #endif
#ifdef HAVE_QOBUZ #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), QLatin1String(QobuzSettingsPage::kSettingsGroup), SettingsDialog::Page::Qobuz, this)),
#endif #endif
radio_view_(new RadioViewContainer(this)), radio_view_(new RadioViewContainer(this)),
lastfm_import_dialog_(new LastFMImportDialog(app_->lastfm_import(), this)), lastfm_import_dialog_(new LastFMImportDialog(app_->lastfm_import(), this)),
@ -398,7 +399,7 @@ MainWindow::MainWindow(Application *app, SharedPtr<SystemTrayIcon> tray_icon, OS
// Add the playing widget to the fancy tab widget // Add the playing widget to the fancy tab widget
ui_->tabs->addBottomWidget(ui_->widget_playing); ui_->tabs->addBottomWidget(ui_->widget_playing);
//ui_->tabs->SetBackgroundPixmap(QPixmap(":/pictures/strawberry-background.png")); //ui_->tabs->SetBackgroundPixmap(QPixmap(":/pictures/strawberry-background.png"));
ui_->tabs->Load(kSettingsGroup); ui_->tabs->Load(QLatin1String(kSettingsGroup));
track_position_timer_->setInterval(kTrackPositionUpdateTimeMs); track_position_timer_->setInterval(kTrackPositionUpdateTimeMs);
QObject::connect(track_position_timer_, &QTimer::timeout, this, &MainWindow::UpdateTrackPosition); QObject::connect(track_position_timer_, &QTimer::timeout, this, &MainWindow::UpdateTrackPosition);
@ -448,7 +449,7 @@ MainWindow::MainWindow(Application *app, SharedPtr<SystemTrayIcon> tray_icon, OS
// Help menu // Help menu
ui_->action_about_strawberry->setIcon(IconLoader::Load(QStringLiteral("strawberry"))); 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 // Music menu
@ -690,7 +691,7 @@ MainWindow::MainWindow(Application *app, SharedPtr<SystemTrayIcon> tray_icon, OS
QAction *collection_config_action = new QAction(IconLoader::Load(QStringLiteral("configure")), tr("Configure collection..."), this); QAction *collection_config_action = new QAction(IconLoader::Load(QStringLiteral("configure")), tr("Configure collection..."), this);
QObject::connect(collection_config_action, &QAction::triggered, this, &MainWindow::ShowCollectionConfig); 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()); collection_view_->filter_widget()->Init(app_->collection()->model());
QAction *separator = new QAction(this); QAction *separator = new QAction(this);
@ -952,7 +953,7 @@ MainWindow::MainWindow(Application *app, SharedPtr<SystemTrayIcon> tray_icon, OS
#else #else
BehaviourSettingsPage::StartupBehaviour startupbehaviour = BehaviourSettingsPage::StartupBehaviour::Remember; BehaviourSettingsPage::StartupBehaviour startupbehaviour = BehaviourSettingsPage::StartupBehaviour::Remember;
{ {
QSettings s; Settings s;
s.beginGroup(BehaviourSettingsPage::kSettingsGroup); s.beginGroup(BehaviourSettingsPage::kSettingsGroup);
startupbehaviour = static_cast<BehaviourSettingsPage::StartupBehaviour>(s.value("startupbehaviour", static_cast<int>(BehaviourSettingsPage::StartupBehaviour::Remember)).toInt()); startupbehaviour = static_cast<BehaviourSettingsPage::StartupBehaviour>(s.value("startupbehaviour", static_cast<int>(BehaviourSettingsPage::StartupBehaviour::Remember)).toInt());
s.endGroup(); s.endGroup();
@ -975,7 +976,7 @@ MainWindow::MainWindow(Application *app, SharedPtr<SystemTrayIcon> tray_icon, OS
} }
[[fallthrough]]; [[fallthrough]];
case BehaviourSettingsPage::StartupBehaviour::Remember: case BehaviourSettingsPage::StartupBehaviour::Remember:
default: { default:{
was_maximized_ = settings_.value("maximized", true).toBool(); was_maximized_ = settings_.value("maximized", true).toBool();
if (was_maximized_) setWindowState(windowState() | Qt::WindowMaximized); if (was_maximized_) setWindowState(windowState() | Qt::WindowMaximized);
@ -1024,18 +1025,18 @@ MainWindow::MainWindow(Application *app, SharedPtr<SystemTrayIcon> tray_icon, OS
} }
#ifdef HAVE_QTSPARKLE #ifdef HAVE_QTSPARKLE
QUrl sparkle_url(QTSPARKLE_URL); QUrl sparkle_url(QString::fromLatin1(QTSPARKLE_URL));
if (!sparkle_url.isEmpty()) { if (!sparkle_url.isEmpty()) {
qLog(Debug) << "Creating Qt Sparkle updater"; qLog(Debug) << "Creating Qt Sparkle updater";
qtsparkle::Updater *updater = new qtsparkle::Updater(sparkle_url, this); 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); QObject::connect(check_updates, &QAction::triggered, updater, &qtsparkle::Updater::CheckNow);
} }
#endif #endif
#ifdef Q_OS_LINUX #ifdef Q_OS_LINUX
if (!Utilities::GetEnv(QStringLiteral("SNAP")).isEmpty() && !Utilities::GetEnv(QStringLiteral("SNAP_NAME")).isEmpty()) { if (!Utilities::GetEnv(QStringLiteral("SNAP")).isEmpty() && !Utilities::GetEnv(QStringLiteral("SNAP_NAME")).isEmpty()) {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
const bool ignore_snap = s.value("ignore_snap", false).toBool(); const bool ignore_snap = s.value("ignore_snap", false).toBool();
s.endGroup(); s.endGroup();
@ -1049,30 +1050,30 @@ MainWindow::MainWindow(Application *app, SharedPtr<SystemTrayIcon> tray_icon, OS
#if defined(Q_OS_MACOS) #if defined(Q_OS_MACOS)
if (Utilities::ProcessTranslated()) { if (Utilities::ProcessTranslated()) {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
const bool ignore_rosetta = s.value("ignore_rosetta", false).toBool(); const bool ignore_rosetta = s.value("ignore_rosetta", false).toBool();
s.endGroup(); s.endGroup();
if (!ignore_rosetta) { if (!ignore_rosetta) {
MessageDialog *rosetta_message = new MessageDialog(this); MessageDialog *rosetta_message = new MessageDialog(this);
rosetta_message->set_settings_group(kSettingsGroup); rosetta_message->set_settings_group(QLatin1String(kSettingsGroup));
rosetta_message->set_do_not_show_message_again("ignore_rosetta"); rosetta_message->set_do_not_show_message_again(QStringLiteral("ignore_rosetta"));
rosetta_message->setAttribute(Qt::WA_DeleteOnClose); 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("<a href=\"https://downloads.strawberrymusicplayer.org/\">downloads.strawberrymusicplayer.org</a>"), 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("<a href=\"https://downloads.strawberrymusicplayer.org/\">downloads.strawberrymusicplayer.org</a>")), IconLoader::Load(QStringLiteral("dialog-warning")));
} }
} }
#endif #endif
{ {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); 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(); const bool do_not_show_sponsor_message = s.value(do_not_show_sponsor_message_key, false).toBool();
s.endGroup(); s.endGroup();
if (!do_not_show_sponsor_message) { if (!do_not_show_sponsor_message) {
MessageDialog *sponsor_message = new MessageDialog(this); MessageDialog *sponsor_message = new MessageDialog(this);
sponsor_message->set_settings_group(kSettingsGroup); sponsor_message->set_settings_group(QLatin1String(kSettingsGroup));
sponsor_message->set_do_not_show_message_again(do_not_show_sponsor_message_key); sponsor_message->set_do_not_show_message_again(QLatin1String(do_not_show_sponsor_message_key));
sponsor_message->setAttribute(Qt::WA_DeleteOnClose); 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("<a href= \"https://www.strawberrymusicplayer.org/\">www.strawberrymusicplayer.org</a>")), IconLoader::Load(QStringLiteral("dialog-information"))); 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("<a href= \"https://www.strawberrymusicplayer.org/\">www.strawberrymusicplayer.org</a>")), IconLoader::Load(QStringLiteral("dialog-information")));
} }
@ -1089,7 +1090,7 @@ MainWindow::~MainWindow() {
void MainWindow::ReloadSettings() { void MainWindow::ReloadSettings() {
QSettings s; Settings s;
#ifdef Q_OS_MACOS #ifdef Q_OS_MACOS
constexpr bool keeprunning_available = true; constexpr bool keeprunning_available = true;
@ -1252,7 +1253,7 @@ void MainWindow::SaveSettings() {
SaveGeometry(); SaveGeometry();
SavePlaybackStatus(); SavePlaybackStatus();
app_->player()->SaveVolume(); app_->player()->SaveVolume();
ui_->tabs->SaveSettings(kSettingsGroup); ui_->tabs->SaveSettings(QLatin1String(kSettingsGroup));
ui_->playlist->view()->SaveSettings(); ui_->playlist->view()->SaveSettings();
app_->scrobbler()->WriteCache(); app_->scrobbler()->WriteCache();
@ -1507,7 +1508,7 @@ void MainWindow::SaveGeometry() {
void MainWindow::SavePlaybackStatus() { void MainWindow::SavePlaybackStatus() {
QSettings s; Settings s;
s.beginGroup(Player::kSettingsGroup); s.beginGroup(Player::kSettingsGroup);
s.setValue("playback_state", static_cast<int>(app_->player()->GetState())); s.setValue("playback_state", static_cast<int>(app_->player()->GetState()));
@ -1526,7 +1527,7 @@ void MainWindow::SavePlaybackStatus() {
void MainWindow::LoadPlaybackStatus() { void MainWindow::LoadPlaybackStatus() {
QSettings s; Settings s;
s.beginGroup(BehaviourSettingsPage::kSettingsGroup); s.beginGroup(BehaviourSettingsPage::kSettingsGroup);
const bool resume_playback = s.value("resumeplayback", false).toBool(); const bool resume_playback = s.value("resumeplayback", false).toBool();
@ -1550,7 +1551,7 @@ void MainWindow::ResumePlayback() {
qLog(Debug) << "Resuming playback"; qLog(Debug) << "Resuming playback";
QSettings s; Settings s;
s.beginGroup(Player::kSettingsGroup); s.beginGroup(Player::kSettingsGroup);
const EngineBase::State playback_state = static_cast<EngineBase::State>(s.value("playback_state", static_cast<int>(EngineBase::State::Empty)).toInt()); const EngineBase::State playback_state = static_cast<EngineBase::State>(s.value("playback_state", static_cast<int>(EngineBase::State::Empty)).toInt());
int playback_playlist = s.value("playback_playlist", -1).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_name = Playlist::column_name(column);
QString column_value = app_->playlist_manager()->current()->data(source_index).toString(); 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_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)); ui_->action_edit_value->setText(tr("Edit tag \"%1\"...").arg(column_name));
@ -2297,7 +2298,7 @@ void MainWindow::AddFile() {
PlaylistParser parser(app_->collection_backend()); PlaylistParser parser(app_->collection_backend());
// Show dialog // 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; if (file_names.isEmpty()) return;
@ -2341,7 +2342,7 @@ void MainWindow::AddCDTracks() {
MimeData *mimedata = new MimeData; MimeData *mimedata = new MimeData;
// We are putting empty data, but we specify cdda mimetype to indicate that we want to load audio cd tracks // 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->open_in_new_playlist_ = true;
mimedata->setData(Playlist::kCddaMimeType, QByteArray()); mimedata->setData(QLatin1String(Playlist::kCddaMimeType), QByteArray());
AddToPlaylist(mimedata); AddToPlaylist(mimedata);
} }
@ -2375,7 +2376,7 @@ void MainWindow::ShowInCollection() {
} }
QString search; QString search;
if (!songs.isEmpty()) { 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); collection_view_->filter_widget()->ShowInCollection(search);
@ -2468,9 +2469,9 @@ void MainWindow::CommandlineOptionsReceived(const CommandlineOptions &options) {
break; break;
case CommandlineOptions::PlayerAction::ResizeWindow:{ case CommandlineOptions::PlayerAction::ResizeWindow:{
if (options.window_size().contains('x') && options.window_size().length() >= 4) { if (options.window_size().contains(QLatin1Char('x')) && options.window_size().length() >= 4) {
QString str_w = options.window_size().left(options.window_size().indexOf('x')); 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('x') - 1); QString str_h = options.window_size().right(options.window_size().length() - options.window_size().indexOf(QLatin1Char('x')) - 1);
bool w_ok = false; bool w_ok = false;
bool h_ok = false; bool h_ok = false;
int w = str_w.toInt(&w_ok); int w = str_w.toInt(&w_ok);
@ -2509,7 +2510,7 @@ void MainWindow::CommandlineOptionsReceived(const CommandlineOptions &options) {
#ifdef HAVE_TIDAL #ifdef HAVE_TIDAL
for (const QUrl &url : options.urls()) { 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); emit AuthorizationUrlReceived(url);
return; return;
} }
@ -2951,11 +2952,11 @@ void MainWindow::CheckFullRescanRevisions() {
// if we have any... // if we have any...
if (!reasons.isEmpty()) { 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:") + "<ul>"; 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("<ul>");
for (const QString &reason : reasons) { for (const QString &reason : reasons) {
message += ("<li>" + reason + "</li>"); message += QStringLiteral("<li>") + reason + QStringLiteral("</li>");
} }
message += "</ul>" + tr("Would you like to run a full rescan right now?"); message += QStringLiteral("</ul>") + 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) { if (QMessageBox::question(this, tr("Collection rescan notice"), message, QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) {
app_->collection()->FullScan(); app_->collection()->FullScan();
} }
@ -3262,7 +3263,7 @@ void MainWindow::PlaylistDelete() {
app_->player()->Next(); app_->player()->Next();
} }
SharedPtr<MusicStorage> storage = make_shared<FilesystemMusicStorage>(Song::Source::LocalFile, "/"); SharedPtr<MusicStorage> storage = make_shared<FilesystemMusicStorage>(Song::Source::LocalFile, QStringLiteral("/"));
DeleteFiles *delete_files = new DeleteFiles(app_->task_manager(), storage, true); DeleteFiles *delete_files = new DeleteFiles(app_->task_manager(), storage, true);
QObject::connect(delete_files, &DeleteFiles::Finished, this, &MainWindow::DeleteFilesFinished); QObject::connect(delete_files, &DeleteFiles::Finished, this, &MainWindow::DeleteFilesFinished);
delete_files->Start(selected_songs); delete_files->Start(selected_songs);

View File

@ -52,6 +52,7 @@
#include "platforminterface.h" #include "platforminterface.h"
#include "song.h" #include "song.h"
#include "tagreaderclient.h" #include "tagreaderclient.h"
#include "settings.h"
#include "engine/enginebase.h" #include "engine/enginebase.h"
#include "osd/osdbase.h" #include "osd/osdbase.h"
#include "playlist/playlist.h" #include "playlist/playlist.h"
@ -379,7 +380,7 @@ class MainWindow : public QMainWindow, public PlatformInterface {
QTimer *track_position_timer_; QTimer *track_position_timer_;
QTimer *track_slider_timer_; QTimer *track_slider_timer_;
QSettings settings_; Settings settings_;
bool keep_running_; bool keep_running_;
bool playing_widget_; bool playing_widget_;

View File

@ -94,9 +94,9 @@ const QDBusArgument &operator>>(const QDBusArgument &arg, MaybePlaylist &playlis
namespace mpris { namespace mpris {
const char *Mpris2::kMprisObjectPath = "/org/mpris/MediaPlayer2"; constexpr char kMprisObjectPath[] = "/org/mpris/MediaPlayer2";
const char *Mpris2::kServiceName = "org.mpris.MediaPlayer2.strawberry"; constexpr char kServiceName[] = "org.mpris.MediaPlayer2.strawberry";
const char *Mpris2::kFreedesktopPath = "org.freedesktop.DBus.Properties"; constexpr char kFreedesktopPath[] = "org.freedesktop.DBus.Properties";
Mpris2::Mpris2(Application *app, QObject *parent) Mpris2::Mpris2(Application *app, QObject *parent)
: QObject(parent), : QObject(parent),
@ -108,13 +108,13 @@ Mpris2::Mpris2(Application *app, QObject *parent)
new Mpris2Player(this); new Mpris2Player(this);
new Mpris2Playlists(this); new Mpris2Playlists(this);
if (!QDBusConnection::sessionBus().registerService(kServiceName)) { if (!QDBusConnection::sessionBus().registerService(QLatin1String(kServiceName))) {
qLog(Warning) << "Failed to register" << QString(kServiceName) << "on the session bus"; qLog(Warning) << "Failed to register" << kServiceName << "on the session bus";
return; return;
} }
if (!QDBusConnection::sessionBus().registerObject(kMprisObjectPath, this)) { if (!QDBusConnection::sessionBus().registerObject(QLatin1String(kMprisObjectPath), this)) {
qLog(Warning) << "Failed to register" << QString(kMprisObjectPath) << "on the session bus"; qLog(Warning) << "Failed to register" << kMprisObjectPath << "on the session bus";
return; return;
} }
@ -131,13 +131,13 @@ Mpris2::Mpris2(Application *app, QObject *parent)
app_name_[0] = app_name_[0].toUpper(); 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")); 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")); data_dirs.append(QStringLiteral("/usr/share"));
} }
@ -150,7 +150,7 @@ Mpris2::Mpris2(Application *app, QObject *parent)
} }
if (desktopfilepath_.isEmpty()) { 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) { 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; QVariantMap map;
map.insert(name, value); map.insert(name, value);
QVariantList args = QVariantList() << mprisEntity << map << QStringList(); 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) { void Mpris2::EmitNotification(const QString &name) {
QVariant value; QVariant value;
if (name == "PlaybackStatus") value = PlaybackStatus(); if (name == QStringLiteral("PlaybackStatus")) value = PlaybackStatus();
else if (name == "LoopStatus") value = LoopStatus(); else if (name == QStringLiteral("LoopStatus")) value = LoopStatus();
else if (name == "Shuffle") value = Shuffle(); else if (name == QStringLiteral("Shuffle")) value = Shuffle();
else if (name == "Metadata") value = Metadata(); else if (name == QStringLiteral("Metadata")) value = Metadata();
else if (name == "Rating") value = Rating(); else if (name == QStringLiteral("Rating")) value = Rating();
else if (name == "Volume") value = Volume(); else if (name == QStringLiteral("Volume")) value = Volume();
else if (name == "Position") value = Position(); else if (name == QStringLiteral("Position")) value = Position();
else if (name == "CanPlay") value = CanPlay(); else if (name == QStringLiteral("CanPlay")) value = CanPlay();
else if (name == "CanPause") value = CanPause(); else if (name == QStringLiteral("CanPause")) value = CanPause();
else if (name == "CanSeek") value = CanSeek(); else if (name == QStringLiteral("CanSeek")) value = CanSeek();
else if (name == "CanGoNext") value = CanGoNext(); else if (name == QStringLiteral("CanGoNext")) value = CanGoNext();
else if (name == "CanGoPrevious") value = CanGoPrevious(); else if (name == QStringLiteral("CanGoPrevious")) value = CanGoPrevious();
if (value.isValid()) EmitNotification(name, value); 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 { QStringList Mpris2::SupportedUriSchemes() const {
@ -325,13 +325,13 @@ void Mpris2::SetLoopStatus(const QString &value) {
PlaylistSequence::RepeatMode mode = PlaylistSequence::RepeatMode::Off; PlaylistSequence::RepeatMode mode = PlaylistSequence::RepeatMode::Off;
if (value == "None") { if (value == QStringLiteral("None")) {
mode = PlaylistSequence::RepeatMode::Off; mode = PlaylistSequence::RepeatMode::Off;
} }
else if (value == "Track") { else if (value == QStringLiteral("Track")) {
mode = PlaylistSequence::RepeatMode::Track; mode = PlaylistSequence::RepeatMode::Track;
} }
else if (value == "Playlist") { else if (value == QStringLiteral("Playlist")) {
mode = PlaylistSequence::RepeatMode::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. // 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 { 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()); } bool Mpris2::CanSeek() const { return CanSeek(app_->player()->GetState()); }
@ -594,7 +594,7 @@ MaybePlaylist Mpris2::ActivePlaylist() const {
void Mpris2::ActivatePlaylist(const QDBusObjectPath &playlist_id) { 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; qLog(Debug) << Q_FUNC_INFO << playlist_id.path() << split_path;
if (split_path.isEmpty()) { if (split_path.isEmpty()) {
return; return;
@ -648,7 +648,7 @@ void Mpris2::PlaylistChangedSlot(Playlist *playlist) {
void Mpris2::PlaylistCollectionChanged(Playlist *playlist) { void Mpris2::PlaylistCollectionChanged(Playlist *playlist) {
Q_UNUSED(playlist); Q_UNUSED(playlist);
EmitNotification(QStringLiteral("PlaylistCount"), "", QStringLiteral("org.mpris.MediaPlayer2.Playlists")); EmitNotification(QStringLiteral("PlaylistCount"), QLatin1String(""), QStringLiteral("org.mpris.MediaPlayer2.Playlists"));
} }
} // namespace mpris } // namespace mpris

View File

@ -232,10 +232,6 @@ class Mpris2 : public QObject {
QString DesktopEntryAbsolutePath() const; QString DesktopEntryAbsolutePath() const;
private: private:
static const char *kMprisObjectPath;
static const char *kServiceName;
static const char *kFreedesktopPath;
Application *app_; Application *app_;
QString app_name_; QString app_name_;

View File

@ -57,7 +57,7 @@ QNetworkReply *NetworkAccessManager::createRequest(Operation op, const QNetworkR
new_request.setHeader(QNetworkRequest::UserAgentHeader, user_agent); new_request.setHeader(QNetworkRequest::UserAgentHeader, user_agent);
if (op == QNetworkAccessManager::PostOperation && !new_request.header(QNetworkRequest::ContentTypeHeader).isValid()) { 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 // Prefer the cache unless the caller has changed the setting already

View File

@ -29,6 +29,7 @@
#include <QSettings> #include <QSettings>
#include "core/logging.h" #include "core/logging.h"
#include "core/settings.h"
#include "networkproxyfactory.h" #include "networkproxyfactory.h"
NetworkProxyFactory *NetworkProxyFactory::sInstance = nullptr; NetworkProxyFactory *NetworkProxyFactory::sInstance = nullptr;
@ -78,7 +79,7 @@ void NetworkProxyFactory::ReloadSettings() {
QMutexLocker l(&mutex_); QMutexLocker l(&mutex_);
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
mode_ = static_cast<Mode>(s.value("mode", static_cast<int>(Mode::System)).toInt()); mode_ = static_cast<Mode>(s.value("mode", static_cast<int>(Mode::System)).toInt());

View File

@ -36,6 +36,7 @@
#include <QSettings> #include <QSettings>
#include "core/logging.h" #include "core/logging.h"
#include "core/settings.h"
#include "utilities/timeconstants.h" #include "utilities/timeconstants.h"
#include "scoped_ptr.h" #include "scoped_ptr.h"
@ -94,7 +95,7 @@ Player::Player(Application *app, QObject *parent)
seek_step_sec_(10), seek_step_sec_(10),
play_offset_nanosec_(0) { play_offset_nanosec_(0) {
QSettings s; Settings s;
s.beginGroup(BackendSettingsPage::kSettingsGroup); s.beginGroup(BackendSettingsPage::kSettingsGroup);
EngineBase::Type enginetype = EngineBase::TypeFromName(s.value("engine", EngineBase::Name(EngineBase::Type::GStreamer)).toString().toLower()); EngineBase::Type enginetype = EngineBase::TypeFromName(s.value("engine", EngineBase::Name(EngineBase::Type::GStreamer)).toString().toLower());
s.endGroup(); 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. if (use_enginetype != enginetype) { // Engine was set to something else. Reset output and device.
QSettings s; Settings s;
s.beginGroup(BackendSettingsPage::kSettingsGroup); s.beginGroup(BackendSettingsPage::kSettingsGroup);
s.setValue("engine", EngineBase::Name(use_enginetype)); s.setValue("engine", EngineBase::Name(use_enginetype));
s.setValue("output", engine_->DefaultOutput()); s.setValue("output", engine_->DefaultOutput());
@ -159,7 +160,7 @@ EngineBase::Type Player::CreateEngine(EngineBase::Type enginetype) {
void Player::Init() { void Player::Init() {
QSettings s; Settings s;
if (!engine_) { if (!engine_) {
s.beginGroup(BackendSettingsPage::kSettingsGroup); s.beginGroup(BackendSettingsPage::kSettingsGroup);
@ -203,7 +204,7 @@ void Player::Init() {
void Player::ReloadSettings() { void Player::ReloadSettings() {
QSettings s; Settings s;
s.beginGroup(PlaylistSettingsPage::kSettingsGroup); s.beginGroup(PlaylistSettingsPage::kSettingsGroup);
continue_on_error_ = s.value("continue_on_error", false).toBool(); continue_on_error_ = s.value("continue_on_error", false).toBool();
@ -221,7 +222,7 @@ void Player::ReloadSettings() {
void Player::LoadVolume() { void Player::LoadVolume() {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
const uint volume = s.value("volume", 100).toInt(); const uint volume = s.value("volume", 100).toInt();
s.endGroup(); s.endGroup();
@ -232,7 +233,7 @@ void Player::LoadVolume() {
void Player::SaveVolume() { void Player::SaveVolume() {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
s.setValue("volume", volume_); s.setValue("volume", volume_);
s.endGroup(); s.endGroup();
@ -283,7 +284,7 @@ void Player::HandleLoadResult(const UrlHandler::LoadResult &result) {
if (is_current) NextItem(stream_change_type_, autoscroll_); if (is_current) NextItem(stream_change_type_, autoscroll_);
break; break;
case UrlHandler::LoadResult::Type::TrackAvailable: { case UrlHandler::LoadResult::Type::TrackAvailable:{
qLog(Debug) << "URL handler for" << result.media_url_ << "returned" << result.stream_url_; qLog(Debug) << "URL handler for" << result.media_url_ << "returned" << result.stream_url_;
@ -497,7 +498,7 @@ void Player::PlayPause(const quint64 offset_nanosec, const Playlist::AutoScroll
emit Resumed(); emit Resumed();
break; break;
case EngineBase::State::Playing: { case EngineBase::State::Playing:{
if (current_item_->options() & PlaylistItem::Option::PauseDisabled) { if (current_item_->options() & PlaylistItem::Option::PauseDisabled) {
Stop(); Stop();
} }
@ -511,7 +512,7 @@ void Player::PlayPause(const quint64 offset_nanosec, const Playlist::AutoScroll
case EngineBase::State::Empty: case EngineBase::State::Empty:
case EngineBase::State::Error: case EngineBase::State::Error:
case EngineBase::State::Idle: { case EngineBase::State::Idle:{
pause_time_ = QDateTime(); pause_time_ = QDateTime();
play_offset_nanosec_ = offset_nanosec; play_offset_nanosec_ = offset_nanosec;
app_->playlist_manager()->SetActivePlaylist(app_->playlist_manager()->current_id()); app_->playlist_manager()->SetActivePlaylist(app_->playlist_manager()->current_id());

120
src/core/settings.cpp Normal file
View File

@ -0,0 +1,120 @@
/*
* Strawberry Music Player
* Copyright 2024, Jonas Kvinge <jonas@jkvinge.net>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
#include <QSettings>
#include <QVariant>
#include <QString>
#include "settings.h"
Settings::Settings(QObject *parent)
: QSettings(parent) {}
Settings::Settings(const QString &filename, const Format format, QObject *parent)
: QSettings(filename, format, parent) {}
// Compatibility with older Qt versions
#if QT_VERSION < QT_VERSION_CHECK(6, 4, 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

51
src/core/settings.h Normal file
View File

@ -0,0 +1,51 @@
/*
* Strawberry Music Player
* Copyright 2024, Jonas Kvinge <jonas@jkvinge.net>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
#ifndef SETTINGS_H
#define SETTINGS_H
#include <QSettings>
#include <QObject>
#include <QVariant>
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, 4, 0) // Compatibility with older Qt versions
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

View File

@ -30,7 +30,7 @@ DefaultSettingsProvider::DefaultSettingsProvider() = default;
void DefaultSettingsProvider::set_group(const char *group) { void DefaultSettingsProvider::set_group(const char *group) {
while (!backend_.group().isEmpty()) backend_.endGroup(); while (!backend_.group().isEmpty()) backend_.endGroup();
backend_.beginGroup(group); backend_.beginGroup(QLatin1String(group));
} }
QVariant DefaultSettingsProvider::value(const QString &key, const QVariant &default_value) const { QVariant DefaultSettingsProvider::value(const QString &key, const QVariant &default_value) const {

View File

@ -659,7 +659,7 @@ QString Song::sortable(const QString &v) {
for (const auto &i : kArticles) { for (const auto &i : kArticles) {
if (copy.startsWith(i)) { if (copy.startsWith(i)) {
qint64 ilen = i.length(); 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) { 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 { QString Song::PrettyTitle() const {
@ -686,7 +686,7 @@ QString Song::PrettyTitleWithArtist() const {
QString title(PrettyTitle()); QString title(PrettyTitle());
if (!d->artist_.isEmpty()) title = d->artist_ + " - " + title; if (!d->artist_.isEmpty()) title = d->artist_ + QStringLiteral(" - ") + title;
return title; return title;
@ -722,7 +722,7 @@ QString Song::TitleWithCompilationArtist() const {
if (title.isEmpty()) title = d->basefilename_; 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; return title;
@ -894,11 +894,11 @@ bool Song::IsSimilar(const Song &other) const {
Song::Source Song::SourceFromURL(const QUrl &url) { Song::Source Song::SourceFromURL(const QUrl &url) {
if (url.isLocalFile()) return Source::LocalFile; if (url.isLocalFile()) return Source::LocalFile;
else if (url.scheme() == "cdda") return Source::CDDA; else if (url.scheme() == QStringLiteral("cdda")) return Source::CDDA;
else if (url.scheme() == "tidal") return Source::Tidal; else if (url.scheme() == QStringLiteral("tidal")) return Source::Tidal;
else if (url.scheme() == "subsonic") return Source::Subsonic; else if (url.scheme() == QStringLiteral("subsonic")) return Source::Subsonic;
else if (url.scheme() == "qobuz") return Source::Qobuz; else if (url.scheme() == QStringLiteral("qobuz")) return Source::Qobuz;
else if (url.scheme() == "http" || url.scheme() == "https" || url.scheme() == "rtsp") { 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("tidal.com"), Qt::CaseInsensitive)) { return Source::Tidal; }
if (url.host().endsWith(QLatin1String("qobuz.com"), Qt::CaseInsensitive)) { return Source::Qobuz; } if (url.host().endsWith(QLatin1String("qobuz.com"), Qt::CaseInsensitive)) { return Source::Qobuz; }
if (url.host().endsWith(QLatin1String("somafm.com"), Qt::CaseInsensitive)) { return Source::SomaFM; } 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::CDDA: return IconLoader::Load(QStringLiteral("cd"));
case FileType::Stream: return IconLoader::Load(QStringLiteral("applications-internet")); case FileType::Stream: return IconLoader::Load(QStringLiteral("applications-internet"));
case FileType::Unknown: 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) { switch (source) {
case Source::Collection: case Source::Collection:
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/collectionalbumcovers"; return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/collectionalbumcovers");
case Source::Subsonic: case Source::Subsonic:
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/subsonicalbumcovers"; return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/subsonicalbumcovers");
case Source::Tidal: case Source::Tidal:
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/tidalalbumcovers"; return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/tidalalbumcovers");
case Source::Qobuz: case Source::Qobuz:
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/qobuzalbumcovers"; return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/qobuzalbumcovers");
case Source::Device: case Source::Device:
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/devicealbumcovers"; return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/devicealbumcovers");
case Source::LocalFile: case Source::LocalFile:
case Source::CDDA: case Source::CDDA:
case Source::Stream: case Source::Stream:
case Source::SomaFM: case Source::SomaFM:
case Source::RadioParadise: case Source::RadioParadise:
case Source::Unknown: case Source::Unknown:
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/albumcovers"; return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QStringLiteral("/albumcovers");
} }
return QString(); 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 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()) { if (d->art_manual_.isEmpty() && !effective_albumartist().isEmpty() && !effective_album().isEmpty()) {
QString filename(CoverUtils::Sha1CoverHash(effective_albumartist(), effective_album()).toHex() + ".jpg"); QString filename = QString::fromLatin1(CoverUtils::Sha1CoverHash(effective_albumartist(), effective_album()).toHex()) + QStringLiteral(".jpg");
QString path(ImageCacheDir(d->source_) + "/" + filename); QString path(ImageCacheDir(d->source_) + QLatin1Char('/') + filename);
if (QFile::exists(path)) { if (QFile::exists(path)) {
d->art_manual_ = QUrl::fromLocalFile(path); d->art_manual_ = QUrl::fromLocalFile(path);
} }
@ -1509,7 +1509,7 @@ void Song::InitFromItdb(Itdb_Track *track, const QString &prefix) {
d->source_ = Source::Device; d->source_ = Source::Device;
QString filename = QString::fromLocal8Bit(track->ipod_path); QString filename = QString::fromLocal8Bit(track->ipod_path);
filename.replace(':', '/'); filename.replace(QLatin1Char(':'), QLatin1Char('/'));
if (prefix.contains(QLatin1String("://"))) { if (prefix.contains(QLatin1String("://"))) {
set_url(QUrl(prefix + filename)); set_url(QUrl(prefix + filename));
} }
@ -1533,7 +1533,7 @@ void Song::InitFromItdb(Itdb_Track *track, const QString &prefix) {
QString cover_path = ImageCacheDir(Source::Device); QString cover_path = ImageCacheDir(Source::Device);
QDir dir(cover_path); QDir dir(cover_path);
if (!dir.exists()) dir.mkpath(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; GError *error = nullptr;
if (dir.exists() && gdk_pixbuf_save(pixbuf, cover_file.toUtf8().constData(), "jpeg", &error, nullptr)) { if (dir.exists() && gdk_pixbuf_save(pixbuf, cover_file.toUtf8().constData(), "jpeg", &error, nullptr)) {
d->art_manual_ = QUrl::fromLocalFile(cover_file); d->art_manual_ = QUrl::fromLocalFile(cover_file);

View File

@ -237,7 +237,7 @@ SongLoader::Result SongLoader::LoadLocal(const QString &filename) {
QSqlDatabase db(collection_backend_->db()->Connect()); QSqlDatabase db(collection_backend_->db()->Connect());
CollectionQuery query(db, collection_backend_->songs_table(), collection_backend_->fts_table()); 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()); query.AddWhere(QStringLiteral("url"), url.toEncoded());
if (query.Exec() && query.Next()) { if (query.Exec() && query.Next()) {
@ -302,7 +302,7 @@ SongLoader::Result SongLoader::LoadLocalAsync(const QString &filename) {
// It's a CUE - create virtual tracks // It's a CUE - create virtual tracks
QFile cue(matching_cue); QFile cue(matching_cue);
if (cue.open(QIODevice::ReadOnly)) { 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(); cue.close();
for (const Song &song : songs) { for (const Song &song : songs) {
if (song.is_valid()) songs_ << song; 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; if (instance->state_ != State::WaitingForType) return;
// Check the mimetype // 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_; 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 // Yeah it might be a playlist, let's get some data and have a better look
instance->state_ = State::WaitingForMagic; instance->state_ = State::WaitingForMagic;
return; return;
@ -634,12 +634,12 @@ void SongLoader::ErrorMessageReceived(GstMessage *msg) {
qLog(Error) << error->message; qLog(Error) << error->message;
qLog(Error) << debugs; qLog(Error) << debugs;
QString message_str = error->message; QString message_str = QString::fromUtf8(error->message);
g_error_free(error); g_error_free(error);
g_free(debugs); 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. // Don't give up - assume it's a playlist and see if one of our parsers can read it.
state_ = State::WaitingForMagic; state_ = State::WaitingForMagic;
return; return;
@ -697,7 +697,7 @@ void SongLoader::MagicReady() {
qLog(Debug) << "Magic says" << parser_->name(); 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. // This is actually a weird MS-WMSP stream. Changing the protocol to MMS from HTTP makes it playable.
parser_ = nullptr; parser_ = nullptr;
url_.setScheme(QStringLiteral("mms")); url_.setScheme(QStringLiteral("mms"));

View File

@ -115,7 +115,7 @@ void StyleSheetLoader::UpdateStyleSheet(QWidget *widget, SharedPtr<StyleSheetDat
ReplaceColor(&stylesheet, QStringLiteral("LinkVisited"), p, QPalette::LinkVisited); ReplaceColor(&stylesheet, QStringLiteral("LinkVisited"), p, QPalette::LinkVisited);
#ifdef Q_OS_MACOS #ifdef Q_OS_MACOS
stylesheet.replace("macos", "*"); stylesheet.replace(QStringLiteral("macos"), QStringLiteral("*"));
#endif #endif
if (stylesheet != styledata->stylesheet_current_) { if (stylesheet != styledata->stylesheet_current_) {
@ -127,9 +127,9 @@ void StyleSheetLoader::UpdateStyleSheet(QWidget *widget, SharedPtr<StyleSheetDat
void StyleSheetLoader::ReplaceColor(QString *css, const QString &name, const QPalette &palette, const QPalette::ColorRole role) { void StyleSheetLoader::ReplaceColor(QString *css, const QString &name, const QPalette &palette, const QPalette::ColorRole role) {
css->replace("%palette-" + name + "-lighter", palette.color(role).lighter().name(), Qt::CaseInsensitive); css->replace(QStringLiteral("%palette-") + name + QStringLiteral("-lighter"), palette.color(role).lighter().name(), Qt::CaseInsensitive);
css->replace("%palette-" + name + "-darker", palette.color(role).darker().name(), Qt::CaseInsensitive); css->replace(QStringLiteral("%palette-") + name + QStringLiteral("-darker"), palette.color(role).darker().name(), Qt::CaseInsensitive);
css->replace("%palette-" + name, palette.color(role).name(), Qt::CaseInsensitive); css->replace(QStringLiteral("%palette-") + name, palette.color(role).name(), Qt::CaseInsensitive);
} }

View File

@ -29,7 +29,6 @@
#include <QByteArray> #include <QByteArray>
#include <QString> #include <QString>
#include <QImage> #include <QImage>
#include <QSettings>
#include "core/logging.h" #include "core/logging.h"
#include "core/workerpool.h" #include "core/workerpool.h"
@ -37,7 +36,10 @@
#include "song.h" #include "song.h"
#include "tagreaderclient.h" #include "tagreaderclient.h"
const char *TagReaderClient::kWorkerExecutableName = "strawberry-tagreader"; namespace {
constexpr char kWorkerExecutableName[] = "strawberry-tagreader";
}
TagReaderClient *TagReaderClient::sInstance = nullptr; TagReaderClient *TagReaderClient::sInstance = nullptr;
TagReaderClient::TagReaderClient(QObject *parent) : QObject(parent), worker_pool_(new WorkerPool<HandlerType>(this)) { TagReaderClient::TagReaderClient(QObject *parent) : QObject(parent), worker_pool_(new WorkerPool<HandlerType>(this)) {
@ -45,7 +47,7 @@ TagReaderClient::TagReaderClient(QObject *parent) : QObject(parent), worker_pool
sInstance = this; sInstance = this;
original_thread_ = thread(); original_thread_ = thread();
worker_pool_->SetExecutableName(kWorkerExecutableName); worker_pool_->SetExecutableName(QLatin1String(kWorkerExecutableName));
QObject::connect(worker_pool_, &WorkerPool<HandlerType>::WorkerFailedToStart, this, &TagReaderClient::WorkerFailedToStart); QObject::connect(worker_pool_, &WorkerPool<HandlerType>::WorkerFailedToStart, this, &TagReaderClient::WorkerFailedToStart);
} }

View File

@ -48,8 +48,6 @@ class TagReaderClient : public QObject {
using HandlerType = AbstractMessageHandler<spb::tagreader::Message>; using HandlerType = AbstractMessageHandler<spb::tagreader::Message>;
using ReplyType = HandlerType::ReplyType; using ReplyType = HandlerType::ReplyType;
static const char *kWorkerExecutableName;
void Start(); void Start();
void ExitAsync(); void ExitAsync();

View File

@ -46,9 +46,9 @@ ThreadSafeNetworkDiskCache::ThreadSafeNetworkDiskCache(QObject *parent) : QAbstr
if (!sCache) { if (!sCache) {
sCache = new QNetworkDiskCache; sCache = new QNetworkDiskCache;
#ifdef Q_OS_WIN32 #ifdef Q_OS_WIN32
sCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/strawberry/networkcache"); sCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QStringLiteral("/strawberry/networkcache"));
#else #else
sCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/networkcache"); sCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/networkcache"));
#endif #endif
} }

View File

@ -39,7 +39,7 @@ Translations::~Translations() {
void Translations::LoadTranslation(const QString &prefix, const QString &path, const QString &language) { void Translations::LoadTranslation(const QString &prefix, const QString &path, const QString &language) {
QTranslator *t = new PoTranslator; QTranslator *t = new PoTranslator;
if (t->load(prefix + "_" + language, path)) { if (t->load(prefix + QLatin1Char('_') + language, path)) {
QCoreApplication::installTranslator(t); QCoreApplication::installTranslator(t);
translations_ << t; translations_ << t;
} }

View File

@ -62,6 +62,7 @@
#include "core/song.h" #include "core/song.h"
#include "core/iconloader.h" #include "core/iconloader.h"
#include "core/tagreaderclient.h" #include "core/tagreaderclient.h"
#include "core/settings.h"
#include "collection/collectionfilteroptions.h" #include "collection/collectionfilteroptions.h"
#include "collection/collectionbackend.h" #include "collection/collectionbackend.h"
@ -131,7 +132,7 @@ void AlbumCoverChoiceController::Init(Application *app) {
app_ = app; app_ = app;
cover_fetcher_ = new AlbumCoverFetcher(app_->cover_providers(), app->network(), this); 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_); cover_searcher_->Init(cover_fetcher_);
QObject::connect(cover_fetcher_, &AlbumCoverFetcher::AlbumCoverFetched, this, &AlbumCoverChoiceController::AlbumCoverFetched); QObject::connect(cover_fetcher_, &AlbumCoverFetcher::AlbumCoverFetched, this, &AlbumCoverChoiceController::AlbumCoverFetched);
@ -140,11 +141,11 @@ void AlbumCoverChoiceController::Init(Application *app) {
void AlbumCoverChoiceController::ReloadSettings() { void AlbumCoverChoiceController::ReloadSettings() {
QSettings s; Settings s;
s.beginGroup(CoversSettingsPage::kSettingsGroup); s.beginGroup(CoversSettingsPage::kSettingsGroup);
cover_options_.cover_type = static_cast<CoverOptions::CoverType>(s.value(CoversSettingsPage::kSaveType, static_cast<int>(CoverOptions::CoverType::Cache)).toInt()); cover_options_.cover_type = static_cast<CoverOptions::CoverType>(s.value(CoversSettingsPage::kSaveType, static_cast<int>(CoverOptions::CoverType::Cache)).toInt());
cover_options_.cover_filename = static_cast<CoverOptions::CoverFilename>(s.value(CoversSettingsPage::kSaveFilename, static_cast<int>(CoverOptions::CoverFilename::Pattern)).toInt()); cover_options_.cover_filename = static_cast<CoverOptions::CoverFilename>(s.value(CoversSettingsPage::kSaveFilename, static_cast<int>(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_overwrite = s.value(CoversSettingsPage::kSaveOverwrite, false).toBool();
cover_options_.cover_lowercase = s.value(CoversSettingsPage::kSaveLowercase, false).toBool(); cover_options_.cover_lowercase = s.value(CoversSettingsPage::kSaveLowercase, false).toBool();
cover_options_.cover_replace_spaces = s.value(CoversSettingsPage::kSaveReplaceSpaces, false).toBool(); cover_options_.cover_replace_spaces = s.value(CoversSettingsPage::kSaveReplaceSpaces, false).toBool();
@ -175,7 +176,7 @@ AlbumCoverImageResult AlbumCoverChoiceController::LoadImageFromFile(Song *song)
return AlbumCoverImageResult(); 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(); if (cover_file.isEmpty()) return AlbumCoverImageResult();
QFile file(cover_file); 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(); 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(); if (cover_file.isEmpty() || QImage(cover_file).isNull()) return QUrl();
switch (get_save_album_cover_type()) { switch (get_save_album_cover_type()) {
@ -235,23 +236,23 @@ void AlbumCoverChoiceController::SaveCoverToFileManual(const Song &song, const A
if (!song.effective_albumartist().isEmpty()) { if (!song.effective_albumartist().isEmpty()) {
initial_file_name = initial_file_name + song.effective_albumartist(); 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 + QLatin1Char('-') + (song.effective_album().isEmpty() ? tr("unknown") : song.effective_album()) + QStringLiteral(".jpg");
initial_file_name = initial_file_name.toLower(); initial_file_name = initial_file_name.toLower();
initial_file_name.replace(QRegularExpression(QStringLiteral("\\s")), QStringLiteral("-")); 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; if (save_filename.isEmpty()) return;
QFileInfo fileinfo(save_filename); QFileInfo fileinfo(save_filename);
if (fileinfo.suffix().isEmpty()) { if (fileinfo.suffix().isEmpty()) {
save_filename.append(".jpg"); save_filename.append(QStringLiteral(".jpg"));
fileinfo.setFile(save_filename); fileinfo.setFile(save_filename);
} }
if (!QImageWriter::supportedImageFormats().contains(fileinfo.completeSuffix().toUtf8().toLower())) { 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); 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 no automatic art, start in the song's folder
if (!song.url().isEmpty() && song.url().isValid() && song.url().isLocalFile() && song.url().toLocalFile().contains('/')) { if (!song.url().isEmpty() && song.url().isValid() && song.url().isLocalFile() && song.url().toLocalFile().contains(QLatin1Char('/'))) {
return song.url().toLocalFile().section('/', 0, -2) + filename; return song.url().toLocalFile().section(QLatin1Char('/'), 0, -2) + filename;
} }
return QDir::home().absolutePath() + filename; return QDir::home().absolutePath() + filename;
@ -422,7 +423,7 @@ void AlbumCoverChoiceController::ShowCover(const Song &song, const QImage &image
for (const AlbumCoverLoaderOptions::Type type : cover_types_) { for (const AlbumCoverLoaderOptions::Type type : cover_types_) {
switch (type) { switch (type) {
case AlbumCoverLoaderOptions::Type::Unset: { case AlbumCoverLoaderOptions::Type::Unset:{
if (song.art_unset()) { if (song.art_unset()) {
return; return;
} }
@ -472,13 +473,13 @@ void AlbumCoverChoiceController::ShowCover(const Song &song, const QPixmap &pixm
// Use Artist - Album as the window title // Use Artist - Album as the window title
QString title_text(song.effective_albumartist()); 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); QLabel *label = new QLabel(dialog);
label->setPixmap(pixmap); label->setPixmap(pixmap);
// Add (WxHpx) to the title before possibly resizing // 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()) + QLatin1Char('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. // 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); 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()) { 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()) { while (file.exists()) {
QFileInfo fileinfo(file.fileName()); QFileInfo fileinfo(file.fileName());
file.setFileName(fileinfo.path() + "/0" + fileinfo.fileName()); file.setFileName(fileinfo.path() + QStringLiteral("/0") + fileinfo.fileName());
} }
filepath = file.fileName(); filepath = file.fileName();
} }

View File

@ -33,6 +33,8 @@
#include "albumcoverexport.h" #include "albumcoverexport.h"
#include "ui_albumcoverexport.h" #include "ui_albumcoverexport.h"
#include "core/settings.h"
const char *AlbumCoverExport::kSettingsGroup = "AlbumCoverExport"; const char *AlbumCoverExport::kSettingsGroup = "AlbumCoverExport";
AlbumCoverExport::AlbumCoverExport(QWidget *parent) : QDialog(parent), ui_(new Ui_AlbumCoverExport) { AlbumCoverExport::AlbumCoverExport(QWidget *parent) : QDialog(parent), ui_(new Ui_AlbumCoverExport) {
@ -47,17 +49,17 @@ AlbumCoverExport::~AlbumCoverExport() { delete ui_; }
AlbumCoverExport::DialogResult AlbumCoverExport::Exec() { AlbumCoverExport::DialogResult AlbumCoverExport::Exec() {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
// Restore last accepted settings // 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<OverwriteMode>(s.value("overwrite", static_cast<int>(OverwriteMode::None)).toInt()) == OverwriteMode::None); ui_->doNotOverwrite->setChecked(static_cast<OverwriteMode>(s.value("overwrite", static_cast<int>(OverwriteMode::None)).toInt()) == OverwriteMode::None);
ui_->overwriteAll->setChecked(static_cast<OverwriteMode>(s.value("overwrite", static_cast<int>(OverwriteMode::All)).toInt()) == OverwriteMode::All); ui_->overwriteAll->setChecked(static_cast<OverwriteMode>(s.value("overwrite", static_cast<int>(OverwriteMode::All)).toInt()) == OverwriteMode::All);
ui_->overwriteSmaller->setChecked(static_cast<OverwriteMode>(s.value("overwrite", static_cast<int>(OverwriteMode::Smaller)).toInt()) == OverwriteMode::Smaller); ui_->overwriteSmaller->setChecked(static_cast<OverwriteMode>(s.value("overwrite", static_cast<int>(OverwriteMode::Smaller)).toInt()) == OverwriteMode::Smaller);
ui_->forceSize->setChecked(s.value("forceSize", false).toBool()); ui_->forceSize->setChecked(s.value("forceSize", false).toBool());
ui_->width->setText(s.value("width", "").toString()); ui_->width->setText(s.value("width", QLatin1String("")).toString());
ui_->height->setText(s.value("height", "").toString()); ui_->height->setText(s.value("height", QLatin1String("")).toString());
ui_->export_downloaded->setChecked(s.value("export_downloaded", true).toBool()); ui_->export_downloaded->setChecked(s.value("export_downloaded", true).toBool());
ui_->export_embedded->setChecked(s.value("export_embedded", false).toBool()); ui_->export_embedded->setChecked(s.value("export_embedded", false).toBool());

View File

@ -320,8 +320,8 @@ void AlbumCoverFetcherSearch::ProviderCoverFetchFinished(QNetworkReply *reply) {
} }
else { else {
QString mimetype = reply->header(QNetworkRequest::ContentTypeHeader).toString(); QString mimetype = reply->header(QNetworkRequest::ContentTypeHeader).toString();
if (mimetype.contains(';')) { if (mimetype.contains(QLatin1Char(';'))) {
mimetype = mimetype.left(mimetype.indexOf(';')); mimetype = mimetype.left(mimetype.indexOf(QLatin1Char(';')));
} }
if (ImageUtils::SupportedImageMimeTypes().contains(mimetype, Qt::CaseInsensitive) || ImageUtils::SupportedImageFormats().contains(mimetype, Qt::CaseInsensitive)) { if (ImageUtils::SupportedImageMimeTypes().contains(mimetype, Qt::CaseInsensitive) || ImageUtils::SupportedImageFormats().contains(mimetype, Qt::CaseInsensitive)) {
QByteArray image_data = reply->readAll(); QByteArray image_data = reply->readAll();

View File

@ -41,7 +41,7 @@ class AlbumCoverImageResult {
QImage image; QImage image;
bool is_valid() const { return !image_data.isNull() || !image.isNull(); } 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) Q_DECLARE_METATYPE(AlbumCoverImageResult)

View File

@ -21,6 +21,7 @@
#include <QSettings> #include <QSettings>
#include "core/settings.h"
#include "settings/coverssettingspage.h" #include "settings/coverssettingspage.h"
AlbumCoverLoaderOptions::AlbumCoverLoaderOptions(const Options _options, const QSize _desired_scaled_size, const qreal _device_pixel_ratio, const Types &_types) 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; Types cover_types;
QSettings s; Settings s;
s.beginGroup(CoversSettingsPage::kSettingsGroup); s.beginGroup(CoversSettingsPage::kSettingsGroup);
const QStringList all_cover_types = QStringList() << QStringLiteral("art_unset") << QStringLiteral("art_embedded") << QStringLiteral("art_manual") << QStringLiteral("art_automatic"); 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(); const QStringList cover_types_strlist = s.value(CoversSettingsPage::kTypes, all_cover_types).toStringList();
for (const QString &cover_type_str : cover_types_strlist) { 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; 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; 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; 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; cover_types << AlbumCoverLoaderOptions::Type::Automatic;
} }
} }

View File

@ -70,6 +70,7 @@
#include "core/tagreaderclient.h" #include "core/tagreaderclient.h"
#include "core/database.h" #include "core/database.h"
#include "core/sqlrow.h" #include "core/sqlrow.h"
#include "core/settings.h"
#include "utilities/strutils.h" #include "utilities/strutils.h"
#include "utilities/fileutils.h" #include "utilities/fileutils.h"
#include "utilities/imageutils.h" #include "utilities/imageutils.h"
@ -218,7 +219,7 @@ void AlbumCoverManager::Init() {
QObject::connect(ui_->action_load, &QAction::triggered, this, &AlbumCoverManager::LoadSelectedToPlaylist); QObject::connect(ui_->action_load, &QAction::triggered, this, &AlbumCoverManager::LoadSelectedToPlaylist);
// Restore settings // Restore settings
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
if (s.contains("geometry")) { if (s.contains("geometry")) {
@ -279,12 +280,12 @@ void AlbumCoverManager::closeEvent(QCloseEvent *e) {
void AlbumCoverManager::LoadGeometry() { void AlbumCoverManager::LoadGeometry() {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
if (s.contains("geometry")) { if (s.contains(QStringLiteral("geometry"))) {
restoreGeometry(s.value("geometry").toByteArray()); restoreGeometry(s.value("geometry").toByteArray());
} }
if (s.contains("splitter_state")) { if (s.contains(QStringLiteral("splitter_state"))) {
ui_->splitter->restoreState(s.value("splitter_state").toByteArray()); ui_->splitter->restoreState(s.value("splitter_state").toByteArray());
} }
else { else {
@ -300,7 +301,7 @@ void AlbumCoverManager::LoadGeometry() {
void AlbumCoverManager::SaveSettings() { void AlbumCoverManager::SaveSettings() {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
s.setValue("geometry", saveGeometry()); s.setValue("geometry", saveGeometry());
s.setValue("splitter_state", ui_->splitter->saveState()); s.setValue("splitter_state", ui_->splitter->saveState());
@ -397,7 +398,7 @@ void AlbumCoverManager::ArtistChanged(QListWidgetItem *current) {
display_text = album_info.album; display_text = album_info.album;
} }
else { 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); 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); album_item->setToolTip(album_info.album);
} }
else { 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); 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; return false;
} }
QStringList query = filter.split(' '); QStringList query = filter.split(QLatin1Char(' '));
for (const QString &s : query) { for (const QString &s : query) {
bool in_text = album_item.text().contains(s, Qt::CaseInsensitive); bool in_text = album_item.text().contains(s, Qt::CaseInsensitive);
bool in_albumartist = album_item.data(Role_AlbumArtist).toString().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_); .arg(fetch_statistics_.missing_images_);
if (fetch_statistics_.bytes_transferred_ > 0) { 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); statusBar()->showMessage(message);
@ -632,7 +633,7 @@ Song AlbumCoverManager::AlbumItemAsSong(AlbumItem *album_item) {
QString title = album_item->data(Role_Album).toString(); QString title = album_item->data(Role_Album).toString();
QString artist_name = album_item->data(Role_AlbumArtist).toString(); QString artist_name = album_item->data(Role_AlbumArtist).toString();
if (!artist_name.isEmpty()) { if (!artist_name.isEmpty()) {
result.set_title(artist_name + " - " + title); result.set_title(artist_name + QStringLiteral(" - ") + title);
} }
else { else {
result.set_title(title); result.set_title(title);
@ -876,7 +877,7 @@ SongList AlbumCoverManager::GetSongsInAlbum(const QModelIndex &idx) const {
QSqlDatabase db(collection_backend_->db()->Connect()); QSqlDatabase db(collection_backend_->db()->Connect());
CollectionQuery q(db, collection_backend_->songs_table(), collection_backend_->fts_table()); 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.AddWhere(QStringLiteral("album"), idx.data(Role_Album).toString());
q.SetOrderBy(QStringLiteral("disc, track, title")); q.SetOrderBy(QStringLiteral("disc, track, title"));

View File

@ -220,7 +220,7 @@ void AlbumCoverSearcher::SearchFinished(const quint64 id, const CoverProviderSea
QStandardItem *item = new QStandardItem; QStandardItem *item = new QStandardItem;
item->setIcon(no_cover_icon_); 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(result.image_url, Role_ImageURL);
item->setData(new_id, Role_ImageRequestId); item->setData(new_id, Role_ImageRequestId);
item->setData(false, Role_ImageFetchFinished); item->setData(false, Role_ImageFetchFinished);

View File

@ -84,7 +84,7 @@ void CoverExportRunnable::ProcessAndExportCover() {
if (dialog_result_.export_downloaded_ && song_.art_manual_is_valid()) { if (dialog_result_.export_downloaded_ && song_.art_manual_is_valid()) {
const QString cover_path = song_.art_manual().toLocalFile(); const QString cover_path = song_.art_manual().toLocalFile();
if (image.load(cover_path)) { if (image.load(cover_path)) {
extension = cover_path.section('.', -1); extension = cover_path.section(QLatin1Char('.'), -1);
} }
} }
break; break;
@ -92,7 +92,7 @@ void CoverExportRunnable::ProcessAndExportCover() {
if (dialog_result_.export_downloaded_ && song_.art_automatic_is_valid()) { if (dialog_result_.export_downloaded_ && song_.art_automatic_is_valid()) {
const QString cover_path = song_.art_automatic().toLocalFile(); const QString cover_path = song_.art_automatic().toLocalFile();
if (image.load(cover_path)) { if (image.load(cover_path)) {
extension = cover_path.section('.', -1); extension = cover_path.section(QLatin1Char('.'), -1);
} }
} }
break; break;
@ -110,8 +110,8 @@ void CoverExportRunnable::ProcessAndExportCover() {
image = image.scaled(QSize(dialog_result_.width_, dialog_result_.height_), Qt::IgnoreAspectRatio); image = image.scaled(QSize(dialog_result_.width_, dialog_result_.height_), Qt::IgnoreAspectRatio);
} }
QString cover_dir = song_.url().toLocalFile().section('/', 0, -2); QString cover_dir = song_.url().toLocalFile().section(QLatin1Char('/'), 0, -2);
QString new_file = cover_dir + '/' + dialog_result_.filename_ + '.' + (song_.art_embedded() ? QStringLiteral("jpg") : extension); QString new_file = cover_dir + QLatin1Char('/') + dialog_result_.filename_ + QLatin1Char('.') + (song_.art_embedded() ? QStringLiteral("jpg") : extension);
// If the file exists, do not override! // If the file exists, do not override!
if (dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode::None && QFile::exists(new_file)) { 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()) { if (dialog_result_.export_downloaded_ && song_.art_manual_is_valid()) {
cover_path = song_.art_manual().toLocalFile(); cover_path = song_.art_manual().toLocalFile();
if (image.load(cover_path)) { if (image.load(cover_path)) {
extension = cover_path.section('.', -1); extension = cover_path.section(QLatin1Char('.'), -1);
} }
} }
break; break;
@ -185,7 +185,7 @@ void CoverExportRunnable::ExportCover() {
if (dialog_result_.export_downloaded_ && song_.art_automatic_is_valid()) { if (dialog_result_.export_downloaded_ && song_.art_automatic_is_valid()) {
cover_path = song_.art_automatic().toLocalFile(); cover_path = song_.art_automatic().toLocalFile();
if (image.load(cover_path)) { if (image.load(cover_path)) {
extension = cover_path.section('.', -1); extension = cover_path.section(QLatin1Char('.'), -1);
} }
} }
break; break;
@ -198,8 +198,8 @@ void CoverExportRunnable::ExportCover() {
return; return;
} }
QString cover_dir = song_.url().toLocalFile().section('/', 0, -2); QString cover_dir = song_.url().toLocalFile().section(QLatin1Char('/'), 0, -2);
QString new_file = cover_dir + '/' + dialog_result_.filename_ + '.' + extension; QString new_file = cover_dir + QLatin1Char('/') + dialog_result_.filename_ + QLatin1Char('.') + extension;
// If the file exists, do not override! // If the file exists, do not override!
if (dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode::None && QFile::exists(new_file)) { if (dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode::None && QFile::exists(new_file)) {

View File

@ -30,6 +30,7 @@
#include <QSettings> #include <QSettings>
#include "core/logging.h" #include "core/logging.h"
#include "core/settings.h"
#include "coverprovider.h" #include "coverprovider.h"
#include "coverproviders.h" #include "coverproviders.h"
@ -56,7 +57,7 @@ void CoverProviders::ReloadSettings() {
all_providers.insert(provider->order(), provider->name()); all_providers.insert(provider->order(), provider->name());
} }
QSettings s; Settings s;
s.beginGroup(CoversSettingsPage::kSettingsGroup); s.beginGroup(CoversSettingsPage::kSettingsGroup);
QStringList providers_enabled = s.value(CoversSettingsPage::kProviders, QStringList() << all_providers.values()).toStringList(); QStringList providers_enabled = s.value(CoversSettingsPage::kProviders, QStringList() << all_providers.values()).toStringList();
s.endGroup(); s.endGroup();

View File

@ -63,6 +63,6 @@ QString CoverSearchStatistics::AverageDimensions() const {
return QStringLiteral("0x0"); return QStringLiteral("0x0");
} }
return QString::number(chosen_width_ / chosen_images_) + "x" + QString::number(chosen_height_ / chosen_images_); return QString::number(chosen_width_ / chosen_images_) + QLatin1Char('x') + QString::number(chosen_height_ / chosen_images_);
} }

View File

@ -43,7 +43,7 @@ CoverSearchStatisticsDialog::CoverSearchStatisticsDialog(QWidget *parent)
details_layout_->setSpacing(0); details_layout_->setSpacing(0);
setStyleSheet( setStyleSheet(
"#details {" QStringLiteral("#details {"
" background-color: palette(base);" " background-color: palette(base);"
"}" "}"
"#details QLabel[type=\"label\"] {" "#details QLabel[type=\"label\"] {"
@ -54,7 +54,7 @@ CoverSearchStatisticsDialog::CoverSearchStatisticsDialog(QWidget *parent)
"#details QLabel[type=\"value\"] {" "#details QLabel[type=\"value\"] {"
" font-weight: bold;" " font-weight: bold;"
" max-width: 100px;" " max-width: 100px;"
"}"); "}"));
} }
CoverSearchStatisticsDialog::~CoverSearchStatisticsDialog() { delete ui_; } CoverSearchStatisticsDialog::~CoverSearchStatisticsDialog() { delete ui_; }
@ -92,8 +92,8 @@ void CoverSearchStatisticsDialog::AddLine(const QString &label, const QString &v
QLabel *label1 = new QLabel(label); QLabel *label1 = new QLabel(label);
QLabel *label2 = new QLabel(value); QLabel *label2 = new QLabel(value);
label1->setProperty("type", "label"); label1->setProperty("type", QStringLiteral("label"));
label2->setProperty("type", "value"); label2->setProperty("type", QStringLiteral("value"));
QHBoxLayout *layout = new QHBoxLayout; QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(label1); layout->addWidget(label1);

View File

@ -41,7 +41,7 @@ using std::make_unique;
CurrentAlbumCoverLoader::CurrentAlbumCoverLoader(Application *app, QObject *parent) CurrentAlbumCoverLoader::CurrentAlbumCoverLoader(Application *app, QObject *parent)
: QObject(parent), : QObject(parent),
app_(app), app_(app),
temp_file_pattern_(QDir::tempPath() + "/strawberry-cover-XXXXXX.jpg"), temp_file_pattern_(QDir::tempPath() + QStringLiteral("/strawberry-cover-XXXXXX.jpg")),
id_(0) { id_(0) {
options_.options = AlbumCoverLoaderOptions::Option::RawImageData | AlbumCoverLoaderOptions::Option::OriginalImage | AlbumCoverLoaderOptions::Option::ScaledImage; options_.options = AlbumCoverLoaderOptions::Option::RawImageData | AlbumCoverLoaderOptions::Option::OriginalImage | AlbumCoverLoaderOptions::Option::ScaledImage;

View File

@ -47,8 +47,10 @@
#include "jsoncoverprovider.h" #include "jsoncoverprovider.h"
#include "deezercoverprovider.h" #include "deezercoverprovider.h"
const char *DeezerCoverProvider::kApiUrl = "https://api.deezer.com"; namespace {
const int DeezerCoverProvider::kLimit = 10; constexpr char kApiUrl[] = "https://api.deezer.com";
constexpr int kLimit = 10;
}
DeezerCoverProvider::DeezerCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent) DeezerCoverProvider::DeezerCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent)
: JsonCoverProvider(QStringLiteral("Deezer"), true, false, 2.0, true, true, app, network, parent) {} : JsonCoverProvider(QStringLiteral("Deezer"), true, false, 2.0, true, true, app, network, parent) {}
@ -72,27 +74,27 @@ bool DeezerCoverProvider::StartSearch(const QString &artist, const QString &albu
QString query = artist; QString query = artist;
if (album.isEmpty() && !title.isEmpty()) { if (album.isEmpty() && !title.isEmpty()) {
resource = QStringLiteral("search/track"); resource = QStringLiteral("search/track");
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(title); query.append(title);
} }
else { else {
resource = QStringLiteral("search/album"); resource = QStringLiteral("search/album");
if (!album.isEmpty()) { if (!album.isEmpty()) {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(album); query.append(album);
} }
} }
const ParamList params = ParamList() << Param("output", "json") const ParamList params = ParamList() << Param(QStringLiteral("output"), QStringLiteral("json"))
<< Param("q", query) << Param(QStringLiteral("q"), query)
<< Param("limit", QString::number(kLimit)); << Param(QStringLiteral("limit"), QString::number(kLimit));
QUrlQuery url_query; QUrlQuery url_query;
for (const Param &param : params) { for (const Param &param : 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(kApiUrl + QStringLiteral("/") + resource); QUrl url(QLatin1String(kApiUrl) + QLatin1Char('/') + resource);
url.setQuery(url_query); url.setQuery(url_query);
QNetworkRequest req(url); QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
@ -237,7 +239,7 @@ void DeezerCoverProvider::HandleSearchReply(QNetworkReply *reply, const int id)
continue; continue;
} }
QString type = obj_album[QStringLiteral("type")].toString(); 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); Error(QStringLiteral("Invalid Json reply, data array value album object has incorrect type returned"), obj_album);
continue; continue;
} }

View File

@ -55,9 +55,6 @@ class DeezerCoverProvider : public JsonCoverProvider {
void Error(const QString &error, const QVariant &debug = QVariant()) override; void Error(const QString &error, const QVariant &debug = QVariant()) override;
private: private:
static const char *kApiUrl;
static const int kLimit;
QList<QNetworkReply*> replies_; QList<QNetworkReply*> replies_;
}; };

View File

@ -126,28 +126,28 @@ void DiscogsCoverProvider::FlushRequests() {
void DiscogsCoverProvider::SendSearchRequest(SharedPtr<DiscogsCoverSearchContext> search) { void DiscogsCoverProvider::SendSearchRequest(SharedPtr<DiscogsCoverSearchContext> search) {
ParamList params = ParamList() << Param("format", "album") ParamList params = ParamList() << Param(QStringLiteral("format"), QStringLiteral("album"))
<< Param("artist", search->artist.toLower()) << Param(QStringLiteral("artist"), search->artist.toLower())
<< Param("release_title", search->album.toLower()); << Param(QStringLiteral("release_title"), search->album.toLower());
switch (search->type) { switch (search->type) {
case DiscogsCoverType::Master: case DiscogsCoverType::Master:
params << Param("type", "master"); params << Param(QStringLiteral("type"), QStringLiteral("master"));
break; break;
case DiscogsCoverType::Release: case DiscogsCoverType::Release:
params << Param("type", "release"); params << Param(QStringLiteral("type"), QStringLiteral("release"));
break; 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); }); QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, search]() { HandleSearchReply(reply, search->id); });
} }
QNetworkReply *DiscogsCoverProvider::CreateRequest(QUrl url, const ParamList &params_provided) { QNetworkReply *DiscogsCoverProvider::CreateRequest(QUrl url, const ParamList &params_provided) {
ParamList params = ParamList() << Param("key", QByteArray::fromBase64(kAccessKeyB64)) ParamList params = ParamList() << Param(QStringLiteral("key"), QString::fromLatin1(QByteArray::fromBase64(kAccessKeyB64)))
<< Param("secret", QByteArray::fromBase64(kSecretKeyB64)) << Param(QStringLiteral("secret"), QString::fromLatin1(QByteArray::fromBase64(kSecretKeyB64)))
<< params_provided; << params_provided;
QUrlQuery url_query; QUrlQuery url_query;
@ -157,8 +157,8 @@ QNetworkReply *DiscogsCoverProvider::CreateRequest(QUrl url, const ParamList &pa
using EncodedParam = QPair<QByteArray, QByteArray>; using EncodedParam = QPair<QByteArray, QByteArray>;
for (const Param &param : params) { for (const Param &param : params) {
EncodedParam encoded_param(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second)); EncodedParam encoded_param(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second));
query_items << QString(encoded_param.first + "=" + encoded_param.second); query_items << QString::fromLatin1(encoded_param.first) + QLatin1Char('=') + QString::fromLatin1(encoded_param.second);
url_query.addQueryItem(encoded_param.first, encoded_param.second); url_query.addQueryItem(QString::fromLatin1(encoded_param.first), QString::fromLatin1(encoded_param.second));
} }
url.setQuery(url_query); 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)); const QByteArray signature(Utilities::HmacSha256(QByteArray::fromBase64(kSecretKeyB64), data_to_sign));
// Add the signature to the request // Add the signature to the request
url_query.addQueryItem(QStringLiteral("Signature"), QUrl::toPercentEncoding(signature.toBase64())); url_query.addQueryItem(QStringLiteral("Signature"), QString::fromLatin1(QUrl::toPercentEncoding(QString::fromLatin1(signature.toBase64()))));
QNetworkRequest req(url); QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
@ -427,7 +427,7 @@ void DiscogsCoverProvider::HandleReleaseReply(QNetworkReply *reply, const int se
continue; continue;
} }
QString type = obj_image[QStringLiteral("type")].toString(); QString type = obj_image[QStringLiteral("type")].toString();
if (type != "primary") { if (type != QStringLiteral("primary")) {
continue; continue;
} }
int width = obj_image[QStringLiteral("width")].toInt(); int width = obj_image[QStringLiteral("width")].toInt();

View File

@ -46,9 +46,11 @@
#include "albumcoverfetcher.h" #include "albumcoverfetcher.h"
#include "lastfmcoverprovider.h" #include "lastfmcoverprovider.h"
const char *LastFmCoverProvider::kUrl = "https://ws.audioscrobbler.com/2.0/"; namespace {
const char *LastFmCoverProvider::kApiKey = "211990b4c96782c05d1536e7219eb56e"; constexpr char kUrl[] = "https://ws.audioscrobbler.com/2.0/";
const char *LastFmCoverProvider::kSecret = "80fd738f49596e9709b1bf9319c444a8"; constexpr char kApiKey[] = "211990b4c96782c05d1536e7219eb56e";
constexpr char kSecret[] = "80fd738f49596e9709b1bf9319c444a8";
} // namespace
LastFmCoverProvider::LastFmCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent) LastFmCoverProvider::LastFmCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent)
: JsonCoverProvider(QStringLiteral("Last.fm"), true, false, 1.0, true, false, app, network, 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()) { if (album.isEmpty() && !title.isEmpty()) {
method = QStringLiteral("track.search"); method = QStringLiteral("track.search");
type = QStringLiteral("track"); type = QStringLiteral("track");
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(title); query.append(title);
} }
else { else {
method = QStringLiteral("album.search"); method = QStringLiteral("album.search");
type = QStringLiteral("album"); type = QStringLiteral("album");
if (!album.isEmpty()) { if (!album.isEmpty()) {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(album); query.append(album);
} }
} }
ParamList params = ParamList() << Param("api_key", kApiKey) ParamList params = ParamList() << Param(QStringLiteral("api_key"), QLatin1String(kApiKey))
<< Param("lang", QLocale().name().left(2).toLower()) << Param(QStringLiteral("lang"), QLocale().name().left(2).toLower())
<< Param("method", method) << Param(QStringLiteral("method"), method)
<< Param(type, query); << Param(type, query);
std::sort(params.begin(), params.end()); std::sort(params.begin(), params.end());
@ -96,21 +98,21 @@ bool LastFmCoverProvider::StartSearch(const QString &artist, const QString &albu
QUrlQuery url_query; QUrlQuery url_query;
QString data_to_sign; QString data_to_sign;
for (const Param &param : params) { for (const Param &param : 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)));
data_to_sign += param.first + 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); 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(QString::fromLatin1(QUrl::toPercentEncoding(QStringLiteral("api_sig"))), QString::fromLatin1(QUrl::toPercentEncoding(signature)));
url_query.addQueryItem(QUrl::toPercentEncoding(QStringLiteral("format")), QUrl::toPercentEncoding(QStringLiteral("json"))); url_query.addQueryItem(QString::fromLatin1(QUrl::toPercentEncoding(QStringLiteral("format"))), QString::fromLatin1(QUrl::toPercentEncoding(QStringLiteral("json"))));
QUrl url(kUrl); QUrl url(QString::fromLatin1(kUrl));
QNetworkRequest req(url); QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); 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()); QNetworkReply *reply = network_->post(req, url_query.toString(QUrl::FullyEncoded).toUtf8());
replies_ << reply; replies_ << reply;
QObject::connect(reply, &QNetworkReply::finished, this, [this, reply, id, type]() { QueryFinished(reply, id, type); }); 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; QJsonValue value_matches;
if (type == "album") { if (type == QStringLiteral("album")) {
if (obj_results.contains(QStringLiteral("albummatches"))) { if (obj_results.contains(QStringLiteral("albummatches"))) {
value_matches = obj_results[QStringLiteral("albummatches")]; value_matches = obj_results[QStringLiteral("albummatches")];
} }
@ -182,7 +184,7 @@ void LastFmCoverProvider::QueryFinished(QNetworkReply *reply, const int id, cons
return; return;
} }
} }
else if (type == "track") { else if (type == QStringLiteral("track")) {
if (obj_results.contains(QStringLiteral("trackmatches"))) { if (obj_results.contains(QStringLiteral("trackmatches"))) {
value_matches = obj_results[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 artist = obj[QStringLiteral("artist")].toString();
QString album; QString album;
if (type == "album") { if (type == QStringLiteral("album")) {
album = obj[QStringLiteral("name")].toString(); 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"))) { if (json_obj.contains(QStringLiteral("error")) && json_obj.contains(QStringLiteral("message"))) {
int code = json_obj[QStringLiteral("error")].toInt(); int code = json_obj[QStringLiteral("error")].toInt();
QString message = json_obj[QStringLiteral("message")].toString(); QString message = json_obj[QStringLiteral("message")].toString();
error = "Error: " + QString::number(code) + ": " + message; error = QStringLiteral("Error: ") + QString::number(code) + QStringLiteral(": ") + message;
} }
} }
if (error.isEmpty()) { if (error.isEmpty()) {
@ -337,10 +339,10 @@ void LastFmCoverProvider::Error(const QString &error, const QVariant &debug) {
LastFmCoverProvider::LastFmImageSize LastFmCoverProvider::ImageSizeFromString(const QString &size) { LastFmCoverProvider::LastFmImageSize LastFmCoverProvider::ImageSizeFromString(const QString &size) {
if (size == "small") return LastFmImageSize::Small; if (size == QStringLiteral("small")) return LastFmImageSize::Small;
else if (size == "medium") return LastFmImageSize::Medium; else if (size == QStringLiteral("medium")) return LastFmImageSize::Medium;
else if (size == "large") return LastFmImageSize::Large; else if (size == QStringLiteral("large")) return LastFmImageSize::Large;
else if (size == "extralarge") return LastFmImageSize::ExtraLarge; else if (size == QStringLiteral("extralarge")) return LastFmImageSize::ExtraLarge;
else return LastFmImageSize::Unknown; else return LastFmImageSize::Unknown;
} }

View File

@ -62,10 +62,6 @@ class LastFmCoverProvider : public JsonCoverProvider {
void Error(const QString &error, const QVariant &debug = QVariant()) override; void Error(const QString &error, const QVariant &debug = QVariant()) override;
private: private:
static const char *kUrl;
static const char *kApiKey;
static const char *kSecret;
QList<QNetworkReply*> replies_; QList<QNetworkReply*> replies_;
}; };

View File

@ -44,10 +44,12 @@
#include "jsoncoverprovider.h" #include "jsoncoverprovider.h"
#include "musicbrainzcoverprovider.h" #include "musicbrainzcoverprovider.h"
const char *MusicbrainzCoverProvider::kReleaseSearchUrl = "https://musicbrainz.org/ws/2/release/"; namespace {
const char *MusicbrainzCoverProvider::kAlbumCoverUrl = "https://coverartarchive.org/release/%1/front"; constexpr char kReleaseSearchUrl[] = "https://musicbrainz.org/ws/2/release/";
const int MusicbrainzCoverProvider::kLimit = 8; constexpr char kAlbumCoverUrl[] = "https://coverartarchive.org/release/%1/front";
const int MusicbrainzCoverProvider::kRequestsDelay = 1000; constexpr int kLimit = 8;
constexpr int kRequestsDelay = 1000;
} // namespace
MusicbrainzCoverProvider::MusicbrainzCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent) MusicbrainzCoverProvider::MusicbrainzCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent)
: JsonCoverProvider(QStringLiteral("MusicBrainz"), true, false, 1.5, true, false, app, network, 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) { 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; QUrlQuery url_query;
url_query.addQueryItem(QStringLiteral("query"), query); url_query.addQueryItem(QStringLiteral("query"), query);
url_query.addQueryItem(QStringLiteral("limit"), QString::number(kLimit)); url_query.addQueryItem(QStringLiteral("limit"), QString::number(kLimit));
url_query.addQueryItem(QStringLiteral("fmt"), QStringLiteral("json")); url_query.addQueryItem(QStringLiteral("fmt"), QStringLiteral("json"));
QUrl url(kReleaseSearchUrl); QUrl url(QString::fromLatin1(kReleaseSearchUrl));
url.setQuery(url_query); url.setQuery(url_query);
QNetworkRequest req(url); QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
@ -214,7 +216,7 @@ void MusicbrainzCoverProvider::HandleSearchReply(QNetworkReply *reply, const int
QString album = obj_release[QStringLiteral("title")].toString(); QString album = obj_release[QStringLiteral("title")].toString();
CoverProviderSearchResult cover_result; CoverProviderSearchResult cover_result;
QUrl url(QString(kAlbumCoverUrl).arg(id)); QUrl url(QString::fromLatin1(kAlbumCoverUrl).arg(id));
cover_result.artist = artist; cover_result.artist = artist;
cover_result.album = album; cover_result.album = album;
cover_result.image_url = url; cover_result.image_url = url;

View File

@ -64,11 +64,6 @@ class MusicbrainzCoverProvider : public JsonCoverProvider {
void Error(const QString &error, const QVariant &debug = QVariant()) override; void Error(const QString &error, const QVariant &debug = QVariant()) override;
private: private:
static const char *kReleaseSearchUrl;
static const char *kAlbumCoverUrl;
static const int kLimit;
static const int kRequestsDelay;
QTimer *timer_flush_requests_; QTimer *timer_flush_requests_;
QQueue<SearchRequest> queue_search_requests_; QQueue<SearchRequest> queue_search_requests_;
QList<QNetworkReply*> replies_; QList<QNetworkReply*> replies_;

View File

@ -100,13 +100,13 @@ void MusixmatchCoverProvider::HandleSearchReply(QNetworkReply *reply, const int
return; return;
} }
QByteArray data = reply->readAll(); const QByteArray data = reply->readAll();
if (data.isEmpty()) { if (data.isEmpty()) {
Error(QStringLiteral("Empty reply received from server.")); Error(QStringLiteral("Empty reply received from server."));
emit SearchFinished(id, results); emit SearchFinished(id, results);
return; return;
} }
QString content = data; const QString content = QString::fromUtf8(data);
const QString data_begin = QStringLiteral("<script id=\"__NEXT_DATA__\" type=\"application/json\">"); const QString data_begin = QStringLiteral("<script id=\"__NEXT_DATA__\" type=\"application/json\">");
const QString data_end = QStringLiteral("</script>"); const QString data_end = QStringLiteral("</script>");
if (!content.contains(data_begin) || !content.contains(data_end)) { if (!content.contains(data_begin) || !content.contains(data_end)) {

View File

@ -39,6 +39,7 @@
#include "core/application.h" #include "core/application.h"
#include "core/networkaccessmanager.h" #include "core/networkaccessmanager.h"
#include "core/logging.h" #include "core/logging.h"
#include "core/settings.h"
#include "utilities/timeconstants.h" #include "utilities/timeconstants.h"
#include "albumcoverfetcher.h" #include "albumcoverfetcher.h"
#include "jsoncoverprovider.h" #include "jsoncoverprovider.h"
@ -112,7 +113,7 @@ void OpenTidalCoverProvider::CancelSearch(const int id) {
void OpenTidalCoverProvider::LoadSession() { void OpenTidalCoverProvider::LoadSession() {
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
token_type_ = s.value("token_type").toString(); token_type_ = s.value("token_type").toString();
access_token_ = s.value("access_token").toString(); access_token_ = s.value("access_token").toString();
@ -155,7 +156,7 @@ void OpenTidalCoverProvider::Login() {
login_in_progress_ = true; login_in_progress_ = true;
last_login_attempt_ = QDateTime::currentDateTime(); last_login_attempt_ = QDateTime::currentDateTime();
QUrl url(kAuthUrl); QUrl url(QString::fromLatin1(kAuthUrl));
QNetworkRequest req(url); QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
req.setRawHeader("Authorization", "Basic " + QByteArray(QByteArray::fromBase64(kApiClientIdB64) + ":" + QByteArray::fromBase64(kApiClientSecretB64)).toBase64()); 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(); login_time_ = QDateTime::currentDateTime().toSecsSinceEpoch();
expires_in_ = json_obj[QStringLiteral("expires_in")].toInt(); expires_in_ = json_obj[QStringLiteral("expires_in")].toInt();
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
s.setValue("token_type", token_type_); s.setValue("token_type", token_type_);
s.setValue("access_token", access_token_); s.setValue("access_token", access_token_);
@ -293,23 +294,23 @@ void OpenTidalCoverProvider::SendSearchRequest(SearchRequestPtr search_request)
QString query = search_request->artist; QString query = search_request->artist;
if (!search_request->album.isEmpty()) { if (!search_request->album.isEmpty()) {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(search_request->album); query.append(search_request->album);
} }
else if (!search_request->title.isEmpty()) { else if (!search_request->title.isEmpty()) {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(search_request->title); query.append(search_request->title);
} }
QUrlQuery url_query; 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("limit"), QString::number(kLimit));
url_query.addQueryItem(QStringLiteral("countryCode"), QStringLiteral("US")); url_query.addQueryItem(QStringLiteral("countryCode"), QStringLiteral("US"));
QUrl url(QString(kApiUrl) + QStringLiteral("/search")); QUrl url(QLatin1String(kApiUrl) + QStringLiteral("/search"));
url.setQuery(url_query); url.setQuery(url_query);
QNetworkRequest req(url); QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); 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()); req.setRawHeader("Authorization", token_type_.toUtf8() + " " + access_token_.toUtf8());
QNetworkReply *reply = network_->get(req); QNetworkReply *reply = network_->get(req);

View File

@ -46,7 +46,9 @@
#include "jsoncoverprovider.h" #include "jsoncoverprovider.h"
#include "qobuzcoverprovider.h" #include "qobuzcoverprovider.h"
constexpr int QobuzCoverProvider::kLimit = 10; namespace {
constexpr int kLimit = 10;
}
QobuzCoverProvider::QobuzCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent) QobuzCoverProvider::QobuzCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent)
: JsonCoverProvider(QStringLiteral("Qobuz"), true, true, 2.0, true, true, app, network, parent), : JsonCoverProvider(QStringLiteral("Qobuz"), true, true, 2.0, true, true, app, network, parent),
@ -71,34 +73,34 @@ bool QobuzCoverProvider::StartSearch(const QString &artist, const QString &album
QString query = artist; QString query = artist;
if (album.isEmpty() && !title.isEmpty()) { if (album.isEmpty() && !title.isEmpty()) {
resource = QStringLiteral("track/search"); resource = QStringLiteral("track/search");
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(title); query.append(title);
} }
else { else {
resource = QStringLiteral("album/search"); resource = QStringLiteral("album/search");
if (!album.isEmpty()) { if (!album.isEmpty()) {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(album); query.append(album);
} }
} }
ParamList params = ParamList() << Param("query", query) ParamList params = ParamList() << Param(QStringLiteral("query"), query)
<< Param("limit", QString::number(kLimit)) << Param(QStringLiteral("limit"), QString::number(kLimit))
<< Param("app_id", service_->app_id().toUtf8()); << Param(QStringLiteral("app_id"), service_->app_id());
std::sort(params.begin(), params.end()); std::sort(params.begin(), params.end());
QUrlQuery url_query; QUrlQuery url_query;
for (const Param &param : params) { for (const Param &param : 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("/") + resource); QUrl url(QLatin1String(QobuzService::kApiUrl) + QLatin1Char('/') + resource);
url.setQuery(url_query); url.setQuery(url_query);
QNetworkRequest req(url); QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); 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-App-Id", service_->app_id().toUtf8());
req.setRawHeader("X-User-Auth-Token", service_->user_auth_token().toUtf8()); req.setRawHeader("X-User-Auth-Token", service_->user_auth_token().toUtf8());
QNetworkReply *reply = network_->get(req); QNetworkReply *reply = network_->get(req);

View File

@ -59,8 +59,6 @@ class QobuzCoverProvider : public JsonCoverProvider {
void Error(const QString &error, const QVariant &debug = QVariant()) override; void Error(const QString &error, const QVariant &debug = QVariant()) override;
private: private:
static const int kLimit;
QobuzServicePtr service_; QobuzServicePtr service_;
QList<QNetworkReply*> replies_; QList<QNetworkReply*> replies_;
}; };

View File

@ -45,6 +45,7 @@
#include "core/application.h" #include "core/application.h"
#include "core/networkaccessmanager.h" #include "core/networkaccessmanager.h"
#include "core/logging.h" #include "core/logging.h"
#include "core/settings.h"
#include "utilities/randutils.h" #include "utilities/randutils.h"
#include "utilities/timeconstants.h" #include "utilities/timeconstants.h"
#include "internet/localredirectserver.h" #include "internet/localredirectserver.h"
@ -52,14 +53,16 @@
#include "jsoncoverprovider.h" #include "jsoncoverprovider.h"
#include "spotifycoverprovider.h" #include "spotifycoverprovider.h"
const char *SpotifyCoverProvider::kSettingsGroup = "Spotify"; namespace {
const char *SpotifyCoverProvider::kOAuthAuthorizeUrl = "https://accounts.spotify.com/authorize"; constexpr char kSettingsGroup[] = "Spotify";
const char *SpotifyCoverProvider::kOAuthAccessTokenUrl = "https://accounts.spotify.com/api/token"; constexpr char kOAuthAuthorizeUrl[] = "https://accounts.spotify.com/authorize";
const char *SpotifyCoverProvider::kOAuthRedirectUrl = "http://localhost:63111/"; constexpr char kOAuthAccessTokenUrl[] = "https://accounts.spotify.com/api/token";
const char *SpotifyCoverProvider::kClientIDB64 = "ZTZjY2Y2OTQ5NzY1NGE3NThjOTAxNWViYzdiMWQzMTc="; constexpr char kOAuthRedirectUrl[] = "http://localhost:63111/";
const char *SpotifyCoverProvider::kClientSecretB64 = "N2ZlMDMxODk1NTBlNDE3ZGI1ZWQ1MzE3ZGZlZmU2MTE="; constexpr char kClientIDB64[] = "ZTZjY2Y2OTQ5NzY1NGE3NThjOTAxNWViYzdiMWQzMTc=";
const char *SpotifyCoverProvider::kApiUrl = "https://api.spotify.com/v1"; constexpr char kClientSecretB64[] = "N2ZlMDMxODk1NTBlNDE3ZGI1ZWQ1MzE3ZGZlZmU2MTE=";
const int SpotifyCoverProvider::kLimit = 10; constexpr char kApiUrl[] = "https://api.spotify.com/v1";
constexpr int kLimit = 10;
} // namespace
SpotifyCoverProvider::SpotifyCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent) SpotifyCoverProvider::SpotifyCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent)
: JsonCoverProvider(QStringLiteral("Spotify"), true, true, 2.5, true, true, app, network, parent), : JsonCoverProvider(QStringLiteral("Spotify"), true, true, 2.5, true, true, app, network, parent),
@ -70,7 +73,7 @@ SpotifyCoverProvider::SpotifyCoverProvider(Application *app, SharedPtr<NetworkAc
refresh_login_timer_.setSingleShot(true); refresh_login_timer_.setSingleShot(true);
QObject::connect(&refresh_login_timer_, &QTimer::timeout, this, &SpotifyCoverProvider::RequestNewAccessToken); QObject::connect(&refresh_login_timer_, &QTimer::timeout, this, &SpotifyCoverProvider::RequestNewAccessToken);
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
access_token_ = s.value("access_token").toString(); access_token_ = s.value("access_token").toString();
refresh_token_ = s.value("refresh_token").toString(); refresh_token_ = s.value("refresh_token").toString();
@ -100,7 +103,7 @@ SpotifyCoverProvider::~SpotifyCoverProvider() {
void SpotifyCoverProvider::Authenticate() { void SpotifyCoverProvider::Authenticate() {
QUrl redirect_url(kOAuthRedirectUrl); QUrl redirect_url(QString::fromLatin1(kOAuthRedirectUrl));
if (!server_) { if (!server_) {
server_ = new LocalRedirectServer(this); server_ = new LocalRedirectServer(this);
@ -126,22 +129,22 @@ void SpotifyCoverProvider::Authenticate() {
} }
code_verifier_ = Utilities::CryptographicRandomString(44); code_verifier_ = Utilities::CryptographicRandomString(44);
code_challenge_ = QString(QCryptographicHash::hash(code_verifier_.toUtf8(), QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding)); code_challenge_ = QString::fromLatin1(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); code_challenge_.chop(1);
} }
const ParamList params = ParamList() << Param("client_id", QByteArray::fromBase64(kClientIDB64)) const ParamList params = ParamList() << Param(QStringLiteral("client_id"), QString::fromLatin1(QByteArray::fromBase64(kClientIDB64)))
<< Param("response_type", "code") << Param(QStringLiteral("response_type"), QStringLiteral("code"))
<< Param("redirect_uri", redirect_url.toString()) << Param(QStringLiteral("redirect_uri"), redirect_url.toString())
<< Param("state", code_challenge_); << Param(QStringLiteral("state"), code_challenge_);
QUrlQuery url_query; QUrlQuery url_query;
for (const Param &param : params) { for (const Param &param : 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(kOAuthAuthorizeUrl); QUrl url(QString::fromLatin1(kOAuthAuthorizeUrl));
url.setQuery(url_query); url.setQuery(url_query);
const bool result = QDesktopServices::openUrl(url); const bool result = QDesktopServices::openUrl(url);
@ -160,7 +163,7 @@ void SpotifyCoverProvider::Deauthenticate() {
expires_in_ = 0; expires_in_ = 0;
login_time_ = 0; login_time_ = 0;
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
s.remove("access_token"); s.remove("access_token");
s.remove("refresh_token"); s.remove("refresh_token");
@ -186,7 +189,7 @@ void SpotifyCoverProvider::RedirectArrived() {
else if (url_query.hasQueryItem(QStringLiteral("code")) && url_query.hasQueryItem(QStringLiteral("state"))) { else if (url_query.hasQueryItem(QStringLiteral("code")) && url_query.hasQueryItem(QStringLiteral("state"))) {
qLog(Debug) << "Spotify: Authorization URL Received" << url; qLog(Debug) << "Spotify: Authorization URL Received" << url;
QString code = url_query.queryItemValue(QStringLiteral("code")); QString code = url_query.queryItemValue(QStringLiteral("code"));
QUrl redirect_url(kOAuthRedirectUrl); QUrl redirect_url(QString::fromLatin1(kOAuthRedirectUrl));
redirect_url.setPort(server_->url().port()); redirect_url.setPort(server_->url().port());
RequestAccessToken(code, redirect_url); RequestAccessToken(code, redirect_url);
} }
@ -212,17 +215,17 @@ void SpotifyCoverProvider::RequestAccessToken(const QString &code, const QUrl &r
refresh_login_timer_.stop(); refresh_login_timer_.stop();
ParamList params = ParamList() << Param("client_id", QByteArray::fromBase64(kClientIDB64)) ParamList params = ParamList() << Param(QStringLiteral("client_id"), QLatin1String(kClientIDB64))
<< Param("client_secret", QByteArray::fromBase64(kClientSecretB64)); << Param(QStringLiteral("client_secret"), QLatin1String(kClientSecretB64));
if (!code.isEmpty() && !redirect_url.isEmpty()) { if (!code.isEmpty() && !redirect_url.isEmpty()) {
params << Param("grant_type", "authorization_code"); params << Param(QStringLiteral("grant_type"), QStringLiteral("authorization_code"));
params << Param("code", code); params << Param(QStringLiteral("code"), code);
params << Param("redirect_uri", redirect_url.toString()); params << Param(QStringLiteral("redirect_uri"), redirect_url.toString());
} }
else if (!refresh_token_.isEmpty() && is_enabled()) { else if (!refresh_token_.isEmpty() && is_enabled()) {
params << Param("grant_type", "refresh_token"); params << Param(QStringLiteral("grant_type"), QStringLiteral("refresh_token"));
params << Param("refresh_token", refresh_token_); params << Param(QStringLiteral("refresh_token"), refresh_token_);
} }
else { else {
return; return;
@ -230,14 +233,14 @@ void SpotifyCoverProvider::RequestAccessToken(const QString &code, const QUrl &r
QUrlQuery url_query; QUrlQuery url_query;
for (const Param &param : params) { for (const Param &param : 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 new_url(kOAuthAccessTokenUrl); QUrl new_url(QString::fromLatin1(kOAuthAccessTokenUrl));
QNetworkRequest req(new_url); QNetworkRequest req(new_url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); 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"));
QString auth_header_data = QByteArray::fromBase64(kClientIDB64) + QStringLiteral(":") + QByteArray::fromBase64(kClientSecretB64); QString auth_header_data = QString::fromLatin1(QByteArray::fromBase64(kClientIDB64)) + QLatin1Char(':') + QString::fromLatin1(QByteArray::fromBase64(kClientSecretB64));
req.setRawHeader("Authorization", "Basic " + auth_header_data.toUtf8().toBase64()); req.setRawHeader("Authorization", "Basic " + auth_header_data.toUtf8().toBase64());
QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8(); 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(); expires_in_ = json_obj[QStringLiteral("expires_in")].toInt();
login_time_ = QDateTime::currentDateTime().toSecsSinceEpoch(); login_time_ = QDateTime::currentDateTime().toSecsSinceEpoch();
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
s.setValue("access_token", access_token_); s.setValue("access_token", access_token_);
s.setValue("refresh_token", refresh_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()) { if (album.isEmpty() && !title.isEmpty()) {
type = QStringLiteral("track"); type = QStringLiteral("track");
extract = QStringLiteral("tracks"); extract = QStringLiteral("tracks");
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(title); query.append(title);
} }
else { else {
type = QStringLiteral("album"); type = QStringLiteral("album");
extract = QStringLiteral("albums"); extract = QStringLiteral("albums");
if (!album.isEmpty()) { if (!album.isEmpty()) {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(album); query.append(album);
} }
} }
ParamList params = ParamList() << Param("q", query) ParamList params = ParamList() << Param(QStringLiteral("q"), query)
<< Param("type", type) << Param(QStringLiteral("type"), type)
<< Param("limit", QString::number(kLimit)); << Param(QStringLiteral("limit"), QString::number(kLimit));
QUrlQuery url_query; QUrlQuery url_query;
for (const Param &param : params) { for (const Param &param : 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(kApiUrl + QStringLiteral("/search")); QUrl url(QLatin1String(kApiUrl) + QStringLiteral("/search"));
url.setQuery(url_query); url.setQuery(url_query);
QNetworkRequest req(url); QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); 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()); req.setRawHeader("Authorization", "Bearer " + access_token_.toUtf8());
QNetworkReply *reply = network_->get(req); QNetworkReply *reply = network_->get(req);

View File

@ -70,15 +70,6 @@ class SpotifyCoverProvider : public JsonCoverProvider {
void RequestAccessToken(const QString &code = QString(), const QUrl &redirect_url = QUrl()); void RequestAccessToken(const QString &code = QString(), const QUrl &redirect_url = QUrl());
private: 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_; LocalRedirectServer *server_;
QStringList login_errors_; QStringList login_errors_;
QString code_verifier_; QString code_verifier_;

View File

@ -45,7 +45,9 @@
#include "jsoncoverprovider.h" #include "jsoncoverprovider.h"
#include "tidalcoverprovider.h" #include "tidalcoverprovider.h"
constexpr int TidalCoverProvider::kLimit = 10; namespace {
constexpr int kLimit = 10;
}
TidalCoverProvider::TidalCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent) TidalCoverProvider::TidalCoverProvider(Application *app, SharedPtr<NetworkAccessManager> network, QObject *parent)
: JsonCoverProvider(QStringLiteral("Tidal"), true, true, 2.5, true, true, app, network, parent), : JsonCoverProvider(QStringLiteral("Tidal"), true, true, 2.5, true, true, app, network, parent),
@ -72,31 +74,31 @@ bool TidalCoverProvider::StartSearch(const QString &artist, const QString &album
QString query = artist; QString query = artist;
if (album.isEmpty() && !title.isEmpty()) { if (album.isEmpty() && !title.isEmpty()) {
resource = QStringLiteral("search/tracks"); resource = QStringLiteral("search/tracks");
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(title); query.append(title);
} }
else { else {
resource = QStringLiteral("search/albums"); resource = QStringLiteral("search/albums");
if (!album.isEmpty()) { if (!album.isEmpty()) {
if (!query.isEmpty()) query.append(" "); if (!query.isEmpty()) query.append(QLatin1Char(' '));
query.append(album); query.append(album);
} }
} }
ParamList params = ParamList() << Param("query", query) ParamList params = ParamList() << Param(QStringLiteral("query"), query)
<< Param("limit", QString::number(kLimit)) << Param(QStringLiteral("limit"), QString::number(kLimit))
<< Param("countryCode", service_->country_code()); << Param(QStringLiteral("countryCode"), service_->country_code());
QUrlQuery url_query; QUrlQuery url_query;
for (const Param &param : params) { for (const Param &param : 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(QLatin1String(TidalService::kApiUrl) + QLatin1Char('/') + resource);
url.setQuery(url_query); url.setQuery(url_query);
QNetworkRequest req(url); QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); 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()); 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()); else if (!service_->session_id().isEmpty()) req.setRawHeader("X-Tidal-SessionId", service_->session_id().toUtf8());
@ -252,7 +254,7 @@ void TidalCoverProvider::HandleSearchReply(QNetworkReply *reply, const int id) {
<< qMakePair(QStringLiteral("750x750"), QSize(750, 750)) << qMakePair(QStringLiteral("750x750"), QSize(750, 750))
<< qMakePair(QStringLiteral("640x640"), QSize(640, 640)); << qMakePair(QStringLiteral("640x640"), QSize(640, 640));
for (const QPair<QString, QSize> &cover_size : cover_sizes) { for (const QPair<QString, QSize> &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_url = cover_url;
cover_result.image_size = cover_size.second; cover_result.image_size = cover_size.second;
results << cover_result; results << cover_result;

View File

@ -63,8 +63,6 @@ class TidalCoverProvider : public JsonCoverProvider {
void Error(const QString &error, const QVariant &debug = QVariant()) override; void Error(const QString &error, const QVariant &debug = QVariant()) override;
private: private:
static const int kLimit;
TidalServicePtr service_; TidalServicePtr service_;
QList<QNetworkReply*> replies_; QList<QNetworkReply*> replies_;
}; };

View File

@ -51,7 +51,7 @@ QString CddaLister::DeviceManufacturer(const QString &id) {
cdio_hwinfo_t cd_info; cdio_hwinfo_t cd_info;
if (cdio_get_hwinfo(cdio, &cd_info)) { if (cdio_get_hwinfo(cdio, &cd_info)) {
cdio_destroy(cdio); cdio_destroy(cdio);
return QString(cd_info.psz_vendor); return QString::fromUtf8(cd_info.psz_vendor);
} }
cdio_destroy(cdio); cdio_destroy(cdio);
return QString(); return QString();
@ -64,7 +64,7 @@ QString CddaLister::DeviceModel(const QString &id) {
cdio_hwinfo_t cd_info; cdio_hwinfo_t cd_info;
if (cdio_get_hwinfo(cdio, &cd_info)) { if (cdio_get_hwinfo(cdio, &cd_info)) {
cdio_destroy(cdio); cdio_destroy(cdio);
return QString(cd_info.psz_model); return QString::fromUtf8(cd_info.psz_model);
} }
cdio_destroy(cdio); cdio_destroy(cdio);
return QString(); return QString();
@ -85,15 +85,15 @@ QString CddaLister::MakeFriendlyName(const QString &id) {
cdio_hwinfo_t cd_info; cdio_hwinfo_t cd_info;
if (cdio_get_hwinfo(cdio, &cd_info)) { if (cdio_get_hwinfo(cdio, &cd_info)) {
cdio_destroy(cdio); cdio_destroy(cdio);
return QString(cd_info.psz_model); return QString::fromUtf8(cd_info.psz_model);
} }
cdio_destroy(cdio); cdio_destroy(cdio);
return QStringLiteral("CD (") + id + ")"; return QStringLiteral("CD (") + id + QLatin1Char(')');
} }
QList<QUrl> CddaLister::MakeDeviceUrls(const QString &id) { QList<QUrl> CddaLister::MakeDeviceUrls(const QString &id) {
return QList<QUrl>() << QUrl("cdda://" + id); return QList<QUrl>() << QUrl(QStringLiteral("cdda://") + id);
} }
void CddaLister::UnmountDevice(const QString &id) { void CddaLister::UnmountDevice(const QString &id) {
@ -116,14 +116,14 @@ bool CddaLister::Init() {
return false; return false;
} }
for (; *devices != nullptr; ++devices) { for (; *devices != nullptr; ++devices) {
QString device(*devices); QString device = QString::fromUtf8(*devices);
QFileInfo device_info(device); QFileInfo device_info(device);
if (device_info.isSymLink()) { if (device_info.isSymLink()) {
device = device_info.symLinkTarget(); device = device_info.symLinkTarget();
} }
#ifdef Q_OS_MACOS #ifdef Q_OS_MACOS
// Every track is detected as a separate device on Darwin. The raw disk looks like /dev/rdisk1 // Every track is detected as a separate device on Darwin. The raw disk looks like /dev/rdisk1
if (!device.contains(QRegularExpression("^/dev/rdisk[0-9]$"))) { if (!device.contains(QRegularExpression(QStringLiteral("^/dev/rdisk[0-9]$")))) {
continue; continue;
} }
#endif #endif

View File

@ -82,7 +82,7 @@ void CddaSongLoader::LoadSongs() {
GError *error = nullptr; GError *error = nullptr;
cdda_ = gst_element_make_from_uri(GST_URI_SRC, "cdda://", nullptr, &error); cdda_ = gst_element_make_from_uri(GST_URI_SRC, "cdda://", nullptr, &error);
if (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; if (!cdda_) return;
@ -199,7 +199,7 @@ void CddaSongLoader::LoadSongs() {
gst_message_parse_tag(msg_tag, &tags); gst_message_parse_tag(msg_tag, &tags);
char *string_mb = nullptr; char *string_mb = nullptr;
if (gst_tag_list_get_string(tags, GST_TAG_CDDA_MUSICBRAINZ_DISCID, &string_mb)) { 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; qLog(Info) << "MusicBrainz discid: " << musicbrainz_discid;
MusicBrainzClient *musicbrainz_client = new MusicBrainzClient(network_); MusicBrainzClient *musicbrainz_client = new MusicBrainzClient(network_);

View File

@ -60,7 +60,7 @@ ConnectedDevice::ConnectedDevice(const QUrl &url, DeviceLister *lister, const QS
backend_->moveToThread(app_->database()->thread()); backend_->moveToThread(app_->database()->thread());
qLog(Debug) << &*backend_ << "for device" << unique_id_ << "moved to thread" << 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); QObject::connect(&*backend_, &CollectionBackend::TotalSongCountUpdated, this, &ConnectedDevice::BackendTotalSongCountUpdated);
} }

View File

@ -219,13 +219,13 @@ void DeviceDatabaseBackend::SetDeviceOptions(const int id, const QString &friend
QSqlDatabase db(db_->Connect()); QSqlDatabase db(db_->Connect());
SqlQuery q(db); SqlQuery q(db);
q.prepare( q.prepare(QStringLiteral(
"UPDATE devices" "UPDATE devices"
" SET friendly_name=:friendly_name," " SET friendly_name=:friendly_name,"
" icon=:icon_name," " icon=:icon_name,"
" transcode_mode=:transcode_mode," " transcode_mode=:transcode_mode,"
" transcode_format=:transcode_format" " transcode_format=:transcode_format"
" WHERE ROWID=:id"); " WHERE ROWID=:id"));
q.BindValue(QStringLiteral(":friendly_name"), friendly_name); q.BindValue(QStringLiteral(":friendly_name"), friendly_name);
q.BindValue(QStringLiteral(":icon_name"), icon_name); q.BindValue(QStringLiteral(":icon_name"), icon_name);
q.BindValue(QStringLiteral(":transcode_mode"), static_cast<int>(mode)); q.BindValue(QStringLiteral(":transcode_mode"), static_cast<int>(mode));

View File

@ -64,7 +64,7 @@ void DeviceInfo::InitFromDb(const DeviceDatabaseBackend::Device &dev) {
transcode_format_ = dev.transcode_format_; transcode_format_ = dev.transcode_format_;
icon_name_ = dev.icon_name_; 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) { for (const QString &id : unique_ids) {
backends_ << Backend(nullptr, id); backends_ << Backend(nullptr, id);
} }

View File

@ -223,9 +223,9 @@ QUrl DeviceLister::MakeUrlFromLocalPath(const QString &path) const {
} }
bool DeviceLister::IsIpod(const QString &path) const { bool DeviceLister::IsIpod(const QString &path) const {
return QFile::exists(path + "/iTunes_Control") || return QFile::exists(path + QStringLiteral("/iTunes_Control")) ||
QFile::exists(path + "/iPod_Control") || QFile::exists(path + QStringLiteral("/iPod_Control")) ||
QFile::exists(path + "/iTunes/iTunes_Control"); QFile::exists(path + QStringLiteral("/iTunes/iTunes_Control"));
} }
QVariantList DeviceLister::GuessIconForPath(const QString &path) { 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); const Itdb_IpodInfo *info = itdb_device_get_ipod_info(device);
if (info->ipod_model == ITDB_IPOD_MODEL_INVALID) { if (info->ipod_model == ITDB_IPOD_MODEL_INVALID) {
ret << "device-ipod"; ret << QStringLiteral("device-ipod");
} }
else { else {
QString model = GetIpodModel(info->ipod_model); QString model = GetIpodModel(info->ipod_model);
@ -255,7 +255,7 @@ QVariantList DeviceLister::GuessIconForPath(const QString &path) {
} }
if (ret.isEmpty()) { if (ret.isEmpty()) {
ret << "device-ipod"; ret << QStringLiteral("device-ipod");
} }
} }
@ -275,7 +275,7 @@ QVariantList DeviceLister::GuessIconForModel(const QString &vendor, const QStrin
QVariantList ret; QVariantList ret;
if (vendor.startsWith(QLatin1String("Google")) && model.contains(QLatin1String("Nexus"))) { if (vendor.startsWith(QLatin1String("Google")) && model.contains(QLatin1String("Nexus"))) {
ret << "phone-google-nexus-one"; ret << QStringLiteral("phone-google-nexus-one");
} }
return ret; return ret;

View File

@ -245,7 +245,7 @@ void DeviceManager::LoadAllDevices() {
void DeviceManager::AddDeviceFromDB(DeviceInfo *info) { void DeviceManager::AddDeviceFromDB(DeviceInfo *info) {
QStringList icon_names = info->icon_name_.split(','); QStringList icon_names = info->icon_name_.split(QLatin1Char(','));
QVariantList icons; QVariantList icons;
icons.reserve(icon_names.count()); icons.reserve(icon_names.count());
for (const QString &icon_name : icon_names) { for (const QString &icon_name : icon_names) {
@ -279,7 +279,7 @@ QVariant DeviceManager::data(const QModelIndex &idx, int role) const {
if (!info) return QVariant(); if (!info) return QVariant();
switch (role) { switch (role) {
case Qt::DisplayRole: { case Qt::DisplayRole:{
QString text; QString text;
if (!info->friendly_name_.isEmpty()) { if (!info->friendly_name_.isEmpty()) {
text = info->friendly_name_; text = info->friendly_name_;
@ -295,7 +295,7 @@ QVariant DeviceManager::data(const QModelIndex &idx, int role) const {
return text; return text;
} }
case Qt::DecorationRole: { case Qt::DecorationRole:{
QPixmap pixmap = info->icon_.pixmap(kDeviceIconSize); QPixmap pixmap = info->icon_.pixmap(kDeviceIconSize);
if (info->backends_.isEmpty() || !info->BestBackend() || !info->BestBackend()->lister_) { if (info->backends_.isEmpty() || !info->BestBackend() || !info->BestBackend()->lister_) {
@ -360,7 +360,7 @@ QVariant DeviceManager::data(const QModelIndex &idx, int role) const {
if (!info->device_) return QVariant(); if (!info->device_) return QVariant();
return QVariant::fromValue<SharedPtr<MusicStorage>>(info->device_); return QVariant::fromValue<SharedPtr<MusicStorage>>(info->device_);
case Role_MountPath: { case Role_MountPath:{
if (!info->device_) return QVariant(); if (!info->device_) return QVariant();
QString ret = info->device_->url().path(); QString ret = info->device_->url().path();
@ -604,17 +604,17 @@ SharedPtr<ConnectedDevice> DeviceManager::Connect(DeviceInfo *info) {
// If we get here it means that this URL scheme wasn't supported. // 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 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"), 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."), tr("If you continue, this device will work slowly and songs copied to it may not work."),
QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort) QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort)
return ret; return ret;
} }
if (url.scheme() == "ipod") { if (url.scheme() == QStringLiteral("ipod")) {
if (QMessageBox::critical(nullptr, tr("This device will not work properly"), 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."), tr("If you continue, this device will work slowly and songs copied to it may not work."),
QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort) QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort)
return ret; return ret;

View File

@ -139,7 +139,7 @@ void DeviceItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op
status_text = tr("Double click to open"); status_text = tr("Double click to open");
break; break;
case DeviceManager::State_Connected: { case DeviceManager::State_Connected:{
QVariant song_count = idx.data(DeviceManager::Role_SongCount); QVariant song_count = idx.data(DeviceManager::Role_SongCount);
if (song_count.isValid()) { if (song_count.isValid()) {
int count = song_count.toInt(); int count = song_count.toInt();

View File

@ -69,7 +69,7 @@ bool GioLister::DeviceInfo::is_suitable() const {
if (filesystem_type.isEmpty()) return true; 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; if (!devices_.contains(id)) return ret;
const DeviceInfo &info = devices_[id]; const DeviceInfo &info = devices_[id];
ret[QT_TR_NOOP("Mount point")] = info.mount_path; ret[QStringLiteral(QT_TR_NOOP("Mount point"))] = info.mount_path;
ret[QT_TR_NOOP("Device")] = info.volume_unix_device; ret[QStringLiteral(QT_TR_NOOP("Device"))] = info.volume_unix_device;
ret[QT_TR_NOOP("URI")] = info.mount_uri; ret[QStringLiteral(QT_TR_NOOP("URI"))] = info.mount_uri;
return ret; return ret;
} }
@ -503,7 +503,7 @@ void GioLister::DeviceInfo::ReadMountInfo(GMount *mount) {
// Query the file's info for a filesystem ID // Query the file's info for a filesystem ID
// Only afc devices (that I know of) give reliably unique IDs // Only afc devices (that I know of) give reliably unique IDs
if (filesystem_type == "afc") { if (filesystem_type == QStringLiteral("afc")) {
error = nullptr; error = nullptr;
info = g_file_query_info(root, G_FILE_ATTRIBUTE_ID_FILESYSTEM, G_FILE_QUERY_INFO_NONE, nullptr, &error); info = g_file_query_info(root, G_FILE_ATTRIBUTE_ID_FILESYSTEM, G_FILE_QUERY_INFO_NONE, nullptr, &error);
if (error) { if (error) {
@ -528,7 +528,7 @@ void GioLister::DeviceInfo::ReadVolumeInfo(GVolume *volume) {
GFile *root = g_volume_get_activation_root(volume); GFile *root = g_volume_get_activation_root(volume);
if (root) { if (root) {
volume_root_uri = g_file_get_uri(root); volume_root_uri = QString::fromUtf8(g_file_get_uri(root));
g_object_unref(root); g_object_unref(root);
} }

View File

@ -195,12 +195,12 @@ bool GPodDevice::CopyToStorage(const CopyJob &job, QString &error_text) {
bool result = false; bool result = false;
if (!job.cover_image_.isNull()) { if (!job.cover_image_.isNull()) {
#ifdef Q_OS_LINUX #ifdef Q_OS_LINUX
QString temp_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/organize"; QString temp_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/organize");
#else #else
QString temp_path = QStandardPaths::writableLocation(QStandardPaths::TempLocation); QString temp_path = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
#endif #endif
if (!QDir(temp_path).exists()) QDir().mkpath(temp_path); if (!QDir(temp_path).exists()) QDir().mkpath(temp_path);
SharedPtr<QTemporaryFile> cover_file = make_shared<QTemporaryFile>(temp_path + "/track-albumcover-XXXXXX.jpg"); SharedPtr<QTemporaryFile> cover_file = make_shared<QTemporaryFile>(temp_path + QStringLiteral("/track-albumcover-XXXXXX.jpg"));
cover_file->setAutoRemove(true); cover_file->setAutoRemove(true);
if (cover_file->open()) { if (cover_file->open()) {
cover_file->close(); cover_file->close();
@ -281,7 +281,7 @@ bool GPodDevice::WriteDatabase(QString &error_text) {
cover_files_.clear(); cover_files_.clear();
if (!success) { if (!success) {
if (error) { 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); g_error_free(error);
} }
else { else {
@ -327,17 +327,17 @@ bool GPodDevice::RemoveTrackFromITunesDb(const QString &path, const QString &rel
QString ipod_filename = path; QString ipod_filename = path;
if (!relative_to.isEmpty() && path.startsWith(relative_to)) { 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 // Find the track in the itdb, identify it by its filename
Itdb_Track *track = nullptr; Itdb_Track *track = nullptr;
for (GList *tracks = db_->tracks; tracks != nullptr; tracks = tracks->next) { for (GList *tracks = db_->tracks; tracks != nullptr; tracks = tracks->next) {
Itdb_Track *t = static_cast<Itdb_Track*>(tracks->data); Itdb_Track *t = static_cast<Itdb_Track*>(tracks->data);
if (t->ipod_path == ipod_filename) { if (QString::fromUtf8(t->ipod_path) == ipod_filename) {
track = t; track = t;
break; break;
} }

View File

@ -138,9 +138,9 @@ bool MacOsDeviceLister::Init() {
} }
MTPDevice d; MTPDevice d;
d.vendor = "SanDisk"; d.vendor = QStringLiteral("SanDisk");
d.vendor_id = 0x781; d.vendor_id = 0x781;
d.product = "Sansa Clip+"; d.product = QStringLiteral("Sansa Clip+");
d.product_id = 0x74d0; d.product_id = 0x74d0;
d.quirks = 0x2 | 0x4 | 0x40 | 0x4000; d.quirks = 0x2 | 0x4 | 0x40 | 0x4000;
@ -303,7 +303,7 @@ QString GetIconForDevice(io_object_t device) {
scoped_nsobject<NSURL> bundle_url(reinterpret_cast<NSURL*>(KextManagerCreateURLForBundleIdentifier(kCFAllocatorDefault, reinterpret_cast<CFStringRef>(bundle)))); scoped_nsobject<NSURL> bundle_url(reinterpret_cast<NSURL*>(KextManagerCreateURLForBundleIdentifier(kCFAllocatorDefault, reinterpret_cast<CFStringRef>(bundle))));
QString path = QString::fromUtf8([[bundle_url path] UTF8String]); QString path = QString::fromUtf8([[bundle_url path] UTF8String]);
path += "/Contents/Resources/"; path += QStringLiteral("/Contents/Resources/");
path += QString::fromUtf8([file UTF8String]); path += QString::fromUtf8([file UTF8String]);
return path; return path;
} }
@ -314,10 +314,11 @@ QString GetIconForDevice(io_object_t device) {
QString GetSerialForDevice(io_object_t device) { QString GetSerialForDevice(io_object_t device) {
QString serial = GetUSBRegistryEntryString(device, CFSTR(kUSBSerialNumberString)); const QString serial = GetUSBRegistryEntryString(device, CFSTR(kUSBSerialNumberString));
if (!serial.isEmpty()) { if (!serial.isEmpty()) {
return "USB/" + serial; return QStringLiteral("USB/") + serial;
} }
return QString(); return QString();
} }
@ -325,7 +326,7 @@ QString GetSerialForDevice(io_object_t device) {
QString GetSerialForMTPDevice(io_object_t device) { QString GetSerialForMTPDevice(io_object_t device) {
scoped_nsobject<NSString> serial(reinterpret_cast<NSString*>(GetPropertyForDevice(device, CFSTR(kUSBSerialNumberString)))); scoped_nsobject<NSString> serial(reinterpret_cast<NSString*>(GetPropertyForDevice(device, CFSTR(kUSBSerialNumberString))));
return QString(QString("MTP/") + QString::fromUtf8([serial UTF8String])); return QString(QStringLiteral("MTP/") + QString::fromUtf8([serial UTF8String]));
} }
@ -336,6 +337,7 @@ QString FindDeviceProperty(const QString &bsd_name, CFStringRef property) {
ScopedIOObject device(DADiskCopyIOMedia(disk.get())); ScopedIOObject device(DADiskCopyIOMedia(disk.get()));
QString ret = GetUSBRegistryEntryString(device.get(), property); QString ret = GetUSBRegistryEntryString(device.get(), property);
return ret; return ret;
} }
@ -356,6 +358,7 @@ quint64 MacOsDeviceLister::GetFreeSpace(const QUrl &url) {
free_bytes += storage->FreeSpaceInBytes; free_bytes += storage->FreeSpaceInBytes;
storage = storage->next; storage = storage->next;
} }
return free_bytes; return free_bytes;
} }
@ -412,7 +415,7 @@ void MacOsDeviceLister::DiskAddedCallback(DADiskRef disk, void *context) {
if ([[dict objectForKey:@"Removable"] intValue] == 1) { if ([[dict objectForKey:@"Removable"] intValue] == 1) {
QString serial = GetSerialForDevice(device.get()); QString serial = GetSerialForDevice(device.get());
if (!serial.isEmpty()) { if (!serial.isEmpty()) {
me->current_devices_[serial] = QString(DADiskGetBSDName(disk)); me->current_devices_[serial] = QString::fromLatin1(DADiskGetBSDName(disk));
emit me->DeviceAdded(serial); emit me->DeviceAdded(serial);
} }
} }
@ -467,6 +470,7 @@ bool DeviceRequest(IOUSBDeviceInterface **dev,
return false; return false;
} }
data->resize(req.wLenDone); data->resize(req.wLenDone);
return true; return true;
} }
@ -596,14 +600,14 @@ void MacOsDeviceLister::USBDeviceAddedCallback(void *refcon, io_iterator_t it) {
// Because this was designed by MS, the characters are in UTF-16 (LE?). // Because this was designed by MS, the characters are in UTF-16 (LE?).
QString str = QString::fromUtf16(reinterpret_cast<char16_t*>(data.data() + 2), (data.size() / 2) - 2); QString str = QString::fromUtf16(reinterpret_cast<char16_t*>(data.data() + 2), (data.size() / 2) - 2);
if (str.startsWith("MSFT100")) { if (str.startsWith(QStringLiteral("MSFT100"))) {
// We got the OS descriptor! // We got the OS descriptor!
char vendor_code = data[16]; char vendor_code = data[16];
ret = DeviceRequest(dev, kUSBIn, kUSBVendor, kUSBDevice, vendor_code, 0, 4, 256, &data); ret = DeviceRequest(dev, kUSBIn, kUSBVendor, kUSBDevice, vendor_code, 0, 4, 256, &data);
if (!ret || data.at(0) != 0x28) if (!ret || data.at(0) != 0x28)
continue; continue;
if (QString::fromLatin1(data.data() + 0x12, 3) != "MTP") { if (QString::fromLatin1(data.data() + 0x12, 3) != QStringLiteral("MTP")) {
// Not quite. // Not quite.
continue; continue;
} }
@ -613,7 +617,7 @@ void MacOsDeviceLister::USBDeviceAddedCallback(void *refcon, io_iterator_t it) {
continue; continue;
} }
if (QString::fromLatin1(data.data() + 0x12, 3) != "MTP") { if (QString::fromLatin1(data.data() + 0x12, 3) != QStringLiteral("MTP")) {
// Not quite. // Not quite.
continue; continue;
} }
@ -674,7 +678,7 @@ void MacOsDeviceLister::FoundMTPDevice(const MTPDevice &device, const QString &s
} }
bool IsMTPSerial(const QString &serial) { return serial.startsWith("MTP"); } bool IsMTPSerial(const QString &serial) { return serial.startsWith(QStringLiteral("MTP")); }
bool MacOsDeviceLister::IsCDDevice(const QString &serial) const { bool MacOsDeviceLister::IsCDDevice(const QString &serial) const {
return cd_devices_.contains(serial); return cd_devices_.contains(serial);
@ -688,7 +692,7 @@ QString MacOsDeviceLister::MakeFriendlyName(const QString &serial) {
return device.product; return device.product;
} }
else { else {
return device.vendor + " " + device.product; return device.vendor + QLatin1Char(' ') + device.product;
} }
} }
@ -711,7 +715,7 @@ QString MacOsDeviceLister::MakeFriendlyName(const QString &serial) {
if (vendor.isEmpty()) { if (vendor.isEmpty()) {
return product; return product;
} }
return vendor + " " + product; return vendor + QLatin1Char(' ') + product;
} }
@ -721,18 +725,18 @@ QList<QUrl> MacOsDeviceLister::MakeDeviceUrls(const QString &serial) {
const MTPDevice &device = mtp_devices_[serial]; const MTPDevice &device = mtp_devices_[serial];
QString str = QString::asprintf("gphoto2://usb-%d-%d/", device.bus, device.address); QString str = QString::asprintf("gphoto2://usb-%d-%d/", device.bus, device.address);
QUrlQuery url_query; QUrlQuery url_query;
url_query.addQueryItem("vendor", device.vendor); url_query.addQueryItem(QStringLiteral("vendor"), device.vendor);
url_query.addQueryItem("vendor_id", QString::number(device.vendor_id)); url_query.addQueryItem(QStringLiteral("vendor_id"), QString::number(device.vendor_id));
url_query.addQueryItem("product", device.product); url_query.addQueryItem(QStringLiteral("product"), device.product);
url_query.addQueryItem("product_id", QString::number(device.product_id)); url_query.addQueryItem(QStringLiteral("product_id"), QString::number(device.product_id));
url_query.addQueryItem("quirks", QString::number(device.quirks)); url_query.addQueryItem(QStringLiteral("quirks"), QString::number(device.quirks));
QUrl url(str); QUrl url(str);
url.setQuery(url_query); url.setQuery(url_query);
return QList<QUrl>() << url; return QList<QUrl>() << url;
} }
if (IsCDDevice(serial)) { if (IsCDDevice(serial)) {
return QList<QUrl>() << QUrl(QString("cdda:///dev/r" + serial)); return QList<QUrl>() << QUrl(QStringLiteral("cdda:///dev/r") + serial);
} }
QString bsd_name = current_devices_[serial]; QString bsd_name = current_devices_[serial];
@ -760,7 +764,7 @@ QVariantList MacOsDeviceLister::DeviceIcons(const QString &serial) {
} }
if (IsCDDevice(serial)) { if (IsCDDevice(serial)) {
return QVariantList() << "media-optical"; return QVariantList() << QStringLiteral("media-optical");
} }
QString bsd_name = current_devices_[serial]; QString bsd_name = current_devices_[serial];

View File

@ -226,7 +226,7 @@ bool MtpDevice::DeleteFromStorage(const DeleteJob &job) {
// Extract the ID from the song's URL // Extract the ID from the song's URL
QString filename = job.metadata_.url().path(); QString filename = job.metadata_.url().path();
filename.remove('/'); filename.remove(QLatin1Char('/'));
bool ok = false; bool ok = false;
uint32_t id = filename.toUInt(&ok); uint32_t id = filename.toUInt(&ok);

View File

@ -57,6 +57,10 @@
using std::make_unique; using std::make_unique;
using std::make_shared; using std::make_shared;
namespace {
constexpr char kUDisks2Service[] = "org.freedesktop.UDisks2";
}
Udisks2Lister::Udisks2Lister(QObject *parent) : DeviceLister(parent) {} Udisks2Lister::Udisks2Lister(QObject *parent) : DeviceLister(parent) {}
Udisks2Lister::~Udisks2Lister() = default; Udisks2Lister::~Udisks2Lister() = default;
@ -116,11 +120,11 @@ QVariantMap Udisks2Lister::DeviceHardwareInfo(const QString &id) {
QVariantMap result; QVariantMap result;
const PartitionData &data = device_data_[id]; const PartitionData &data = device_data_[id];
result[QT_TR_NOOP("D-Bus path")] = data.dbus_path; result[QStringLiteral(QT_TR_NOOP("D-Bus path"))] = data.dbus_path;
result[QT_TR_NOOP("Serial number")] = data.serial; result[QStringLiteral(QT_TR_NOOP("Serial number"))] = data.serial;
result[QT_TR_NOOP("Mount points")] = data.mount_paths.join(QStringLiteral(", ")); result[QStringLiteral(QT_TR_NOOP("Mount points"))] = data.mount_paths.join(QStringLiteral(", "));
result[QT_TR_NOOP("Partition label")] = data.label; result[QStringLiteral(QT_TR_NOOP("Partition label"))] = data.label;
result[QT_TR_NOOP("UUID")] = data.uuid; result[QStringLiteral(QT_TR_NOOP("UUID"))] = data.uuid;
return result; return result;
@ -149,7 +153,7 @@ void Udisks2Lister::UnmountDevice(const QString &id) {
QReadLocker locker(&device_data_lock_); QReadLocker locker(&device_data_lock_);
if (!device_data_.contains(id)) return; 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()) { if (filesystem.isValid()) {
auto unmount_result = filesystem.Unmount(QVariantMap()); auto unmount_result = filesystem.Unmount(QVariantMap());
@ -160,7 +164,7 @@ void Udisks2Lister::UnmountDevice(const QString &id) {
return; 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()) { if (drive.isValid()) {
auto eject_result = drive.Eject(QVariantMap()); auto eject_result = drive.Eject(QVariantMap());
@ -185,7 +189,7 @@ void Udisks2Lister::UpdateDeviceFreeSpace(const QString &id) {
bool Udisks2Lister::Init() { bool Udisks2Lister::Init() {
udisks2_interface_ = make_unique<OrgFreedesktopDBusObjectManagerInterface>(udisks2_service_, "/org/freedesktop/UDisks2", QDBusConnection::systemBus()); udisks2_interface_ = make_unique<OrgFreedesktopDBusObjectManagerInterface>(QLatin1String(kUDisks2Service), QStringLiteral("/org/freedesktop/UDisks2"), QDBusConnection::systemBus());
QDBusPendingReply<ManagedObjectList> reply = udisks2_interface_->GetManagedObjects(); QDBusPendingReply<ManagedObjectList> reply = udisks2_interface_->GetManagedObjects();
reply.waitForFinished(); reply.waitForFinished();
@ -222,17 +226,17 @@ void Udisks2Lister::DBusInterfaceAdded(const QDBusObjectPath &path, const Interf
for (auto interface = interfaces.constBegin(); interface != interfaces.constEnd(); ++interface) { 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<OrgFreedesktopUDisks2JobInterface> job = make_shared<OrgFreedesktopUDisks2JobInterface>(udisks2_service_, path.path(), QDBusConnection::systemBus()); SharedPtr<OrgFreedesktopUDisks2JobInterface> job = make_shared<OrgFreedesktopUDisks2JobInterface>(QLatin1String(kUDisks2Service), path.path(), QDBusConnection::systemBus());
if (!job->isValid()) continue; if (!job->isValid()) continue;
bool is_mount_job = false; bool is_mount_job = false;
if (job->operation() == "filesystem-mount") { if (job->operation() == QStringLiteral("filesystem-mount")) {
is_mount_job = true; is_mount_job = true;
} }
else if (job->operation() == "filesystem-unmount") { else if (job->operation() == QStringLiteral("filesystem-unmount")) {
is_mount_job = false; is_mount_job = false;
} }
else { else {
@ -365,11 +369,11 @@ void Udisks2Lister::HandleFinishedUnmountJob(const PartitionData &partition_data
Udisks2Lister::PartitionData Udisks2Lister::ReadPartitionData(const QDBusObjectPath &path) { Udisks2Lister::PartitionData Udisks2Lister::ReadPartitionData(const QDBusObjectPath &path) {
PartitionData result; PartitionData result;
OrgFreedesktopUDisks2FilesystemInterface filesystem(udisks2_service_, path.path(), QDBusConnection::systemBus()); OrgFreedesktopUDisks2FilesystemInterface filesystem(QLatin1String(kUDisks2Service), path.path(), QDBusConnection::systemBus());
OrgFreedesktopUDisks2BlockInterface block(udisks2_service_, path.path(), QDBusConnection::systemBus()); OrgFreedesktopUDisks2BlockInterface block(QLatin1String(kUDisks2Service), path.path(), QDBusConnection::systemBus());
if (filesystem.isValid() && block.isValid() && !filesystem.mountPoints().empty()) { 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()) { if (drive.isValid() && drive.mediaRemovable()) {
result.dbus_path = path.path(); result.dbus_path = path.path();
@ -384,18 +388,14 @@ Udisks2Lister::PartitionData Udisks2Lister::ReadPartitionData(const QDBusObjectP
result.capacity = drive.size(); result.capacity = drive.size();
if (result.label.isEmpty()) { if (result.label.isEmpty()) {
result.friendly_name = result.model + " " + result.uuid; result.friendly_name = result.model + QLatin1Char(' ') + result.uuid;
} }
else { else {
result.friendly_name = result.label; result.friendly_name = result.label;
} }
for (const QByteArray &p : filesystem.mountPoints()) { 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 const QString mountpoint = QString::fromUtf8(p.data(), p.size());
QString mountpoint = QByteArray(p.data(), static_cast<qint64>(strlen(p.data())));
#else
QString mountpoint = p;
#endif
result.mount_paths.push_back(mountpoint); result.mount_paths.push_back(mountpoint);
} }

View File

@ -124,8 +124,6 @@ class Udisks2Lister : public DeviceLister {
private: private:
ScopedPtr<OrgFreedesktopDBusObjectManagerInterface> udisks2_interface_; ScopedPtr<OrgFreedesktopDBusObjectManagerInterface> udisks2_interface_;
static constexpr char udisks2_service_[] = "org.freedesktop.UDisks2";
}; };
#endif // UDISKS2LISTER_H #endif // UDISKS2LISTER_H

View File

@ -142,7 +142,7 @@ QString About::ContributorsHtml() const {
ret += tr("Author and maintainer"); ret += tr("Author and maintainer");
ret += QLatin1String("</b>"); ret += QLatin1String("</b>");
for (const Person &person : strawberry_authors_) { for (const Person &person : strawberry_authors_) {
ret += "<br />" + PersonToHtml(person); ret += QStringLiteral("<br />") + PersonToHtml(person);
} }
ret += QStringLiteral("</p>"); ret += QStringLiteral("</p>");
@ -151,7 +151,7 @@ QString About::ContributorsHtml() const {
ret += tr("Contributors"); ret += tr("Contributors");
ret += QLatin1String("</b>"); ret += QLatin1String("</b>");
for (const Person &person : strawberry_contributors_) { for (const Person &person : strawberry_contributors_) {
ret += "<br />" + PersonToHtml(person); ret += QStringLiteral("<br />") + PersonToHtml(person);
} }
ret += QStringLiteral("</p>"); ret += QStringLiteral("</p>");
@ -160,7 +160,7 @@ QString About::ContributorsHtml() const {
ret += tr("Clementine authors"); ret += tr("Clementine authors");
ret += QLatin1String("</b>"); ret += QLatin1String("</b>");
for (const Person &person : clementine_authors_) { for (const Person &person : clementine_authors_) {
ret += "<br />" + PersonToHtml(person); ret += QStringLiteral("<br />") + PersonToHtml(person);
} }
ret += QStringLiteral("</p>"); ret += QStringLiteral("</p>");
@ -169,7 +169,7 @@ QString About::ContributorsHtml() const {
ret += tr("Clementine contributors"); ret += tr("Clementine contributors");
ret += QLatin1String("</b>"); ret += QLatin1String("</b>");
for (const Person &person : clementine_contributors_) { for (const Person &person : clementine_contributors_) {
ret += "<br />" + PersonToHtml(person); ret += QStringLiteral("<br />") + PersonToHtml(person);
} }
ret += QStringLiteral("</p>"); ret += QStringLiteral("</p>");
@ -178,7 +178,7 @@ QString About::ContributorsHtml() const {
ret += tr("Thanks to"); ret += tr("Thanks to");
ret += QLatin1String("</b>"); ret += QLatin1String("</b>");
for (const Person &person : strawberry_thanks_) { for (const Person &person : strawberry_thanks_) {
ret += "<br />" + PersonToHtml(person); ret += QStringLiteral("<br />") + PersonToHtml(person);
} }
ret += QStringLiteral("</p>"); ret += QStringLiteral("</p>");

View File

@ -20,7 +20,6 @@
#include "addstreamdialog.h" #include "addstreamdialog.h"
#include "ui_addstreamdialog.h" #include "ui_addstreamdialog.h"
#include <QSettings>
#include <QUrl> #include <QUrl>
#include <QLabel> #include <QLabel>
#include <QLineEdit> #include <QLineEdit>

View File

@ -69,7 +69,7 @@ void Console::RunQuery() {
return; return;
} }
ui_.output->append("<b>&gt; " + query.executedQuery() + "</b>"); ui_.output->append(QStringLiteral("<b>&gt; ") + query.executedQuery() + QStringLiteral("</b>"));
while (query.next() && query.isValid()) { while (query.next() && query.isValid()) {
QSqlRecord record = query.record(); QSqlRecord record = query.record();

View File

@ -73,6 +73,7 @@
#include "core/iconloader.h" #include "core/iconloader.h"
#include "core/logging.h" #include "core/logging.h"
#include "core/tagreaderclient.h" #include "core/tagreaderclient.h"
#include "core/settings.h"
#include "utilities/strutils.h" #include "utilities/strutils.h"
#include "utilities/timeutils.h" #include "utilities/timeutils.h"
#include "utilities/imageutils.h" #include "utilities/imageutils.h"
@ -99,10 +100,12 @@
#include "ui_edittagdialog.h" #include "ui_edittagdialog.h"
#include "tagreadermessages.pb.h" #include "tagreadermessages.pb.h"
const char EditTagDialog::kTagsDifferentHintText[] = QT_TR_NOOP("(different across multiple songs)"); namespace {
const char EditTagDialog::kArtDifferentHintText[] = QT_TR_NOOP("Different art across multiple songs."); constexpr char kTagsDifferentHintText[] = QT_TR_NOOP("(different across multiple songs)");
const char EditTagDialog::kSettingsGroup[] = "EditTagDialog"; constexpr char kArtDifferentHintText[] = QT_TR_NOOP("Different art across multiple songs.");
const int EditTagDialog::kSmallImageSize = 128; constexpr char kSettingsGroup[] = "EditTagDialog";
constexpr int kSmallImageSize = 128;
} // namespace
EditTagDialog::EditTagDialog(Application *app, QWidget *parent) EditTagDialog::EditTagDialog(Application *app, QWidget *parent)
: QDialog(parent), : QDialog(parent),
@ -140,7 +143,7 @@ EditTagDialog::EditTagDialog(Application *app, QWidget *parent)
ui_->loading_label->hide(); ui_->loading_label->hide();
ui_->label_lyrics->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 #ifdef HAVE_MUSICBRAINZ
ui_->fetch_tag->setEnabled(true); ui_->fetch_tag->setEnabled(true);
#else #else
@ -271,7 +274,7 @@ void EditTagDialog::showEvent(QShowEvent *e) {
resize(width(), sizeHint().height()); resize(width(), sizeHint().height());
// Restore the tab that was current last time. // Restore the tab that was current last time.
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
if (s.contains("geometry")) { if (s.contains("geometry")) {
restoreGeometry(s.value("geometry").toByteArray()); restoreGeometry(s.value("geometry").toByteArray());
@ -292,7 +295,7 @@ void EditTagDialog::showEvent(QShowEvent *e) {
void EditTagDialog::hideEvent(QHideEvent *e) { void EditTagDialog::hideEvent(QHideEvent *e) {
// Save the current tab // Save the current tab
QSettings s; Settings s;
s.beginGroup(kSettingsGroup); s.beginGroup(kSettingsGroup);
s.setValue("geometry", saveGeometry()); s.setValue("geometry", saveGeometry());
s.setValue("current_tab", ui_->tab_widget->currentIndex()); s.setValue("current_tab", ui_->tab_widget->currentIndex());
@ -305,7 +308,7 @@ void EditTagDialog::hideEvent(QHideEvent *e) {
void EditTagDialog::accept() { void EditTagDialog::accept() {
// Show the loading indicator // Show the loading indicator
if (!SetLoading(tr("Saving tracks") + "...")) return; if (!SetLoading(tr("Saving tracks") + QStringLiteral("..."))) return;
SaveData(); SaveData();
@ -410,7 +413,7 @@ QList<EditTagDialog::Data> EditTagDialog::LoadData(const SongList &songs) {
void EditTagDialog::SetSongs(const SongList &s, const PlaylistItemPtrList &items) { void EditTagDialog::SetSongs(const SongList &s, const PlaylistItemPtrList &items) {
// Show the loading indicator // Show the loading indicator
if (!SetLoading(tr("Loading tracks") + "...")) return; if (!SetLoading(tr("Loading tracks") + QStringLiteral("..."))) return;
data_.clear(); data_.clear();
playlist_items_ = items; playlist_items_ = items;
@ -472,21 +475,21 @@ void EditTagDialog::SetSongListVisibility(bool visible) {
QVariant EditTagDialog::Data::value(const Song &song, const QString &id) { QVariant EditTagDialog::Data::value(const Song &song, const QString &id) {
if (id == "title") return song.title(); if (id == QStringLiteral("title")) return song.title();
if (id == "artist") return song.artist(); if (id == QStringLiteral("artist")) return song.artist();
if (id == "album") return song.album(); if (id == QStringLiteral("album")) return song.album();
if (id == "albumartist") return song.albumartist(); if (id == QStringLiteral("albumartist")) return song.albumartist();
if (id == "composer") return song.composer(); if (id == QStringLiteral("composer")) return song.composer();
if (id == "performer") return song.performer(); if (id == QStringLiteral("performer")) return song.performer();
if (id == "grouping") return song.grouping(); if (id == QStringLiteral("grouping")) return song.grouping();
if (id == "genre") return song.genre(); if (id == QStringLiteral("genre")) return song.genre();
if (id == "comment") return song.comment(); if (id == QStringLiteral("comment")) return song.comment();
if (id == "lyrics") return song.lyrics(); if (id == QStringLiteral("lyrics")) return song.lyrics();
if (id == "track") return song.track(); if (id == QStringLiteral("track")) return song.track();
if (id == "disc") return song.disc(); if (id == QStringLiteral("disc")) return song.disc();
if (id == "year") return song.year(); if (id == QStringLiteral("year")) return song.year();
if (id == "compilation") return song.compilation(); if (id == QStringLiteral("compilation")) return song.compilation();
if (id == "rating") { return song.rating(); } if (id == QStringLiteral("rating")) { return song.rating(); }
qLog(Warning) << "Unknown ID" << id; qLog(Warning) << "Unknown ID" << id;
return QVariant(); return QVariant();
@ -494,21 +497,21 @@ QVariant EditTagDialog::Data::value(const Song &song, const QString &id) {
void EditTagDialog::Data::set_value(const QString &id, const QVariant &value) { void EditTagDialog::Data::set_value(const QString &id, const QVariant &value) {
if (id == "title") current_.set_title(value.toString()); if (id == QStringLiteral("title")) current_.set_title(value.toString());
else if (id == "artist") current_.set_artist(value.toString()); else if (id == QStringLiteral("artist")) current_.set_artist(value.toString());
else if (id == "album") current_.set_album(value.toString()); else if (id == QStringLiteral("album")) current_.set_album(value.toString());
else if (id == "albumartist") current_.set_albumartist(value.toString()); else if (id == QStringLiteral("albumartist")) current_.set_albumartist(value.toString());
else if (id == "composer") current_.set_composer(value.toString()); else if (id == QStringLiteral("composer")) current_.set_composer(value.toString());
else if (id == "performer") current_.set_performer(value.toString()); else if (id == QStringLiteral("performer")) current_.set_performer(value.toString());
else if (id == "grouping") current_.set_grouping(value.toString()); else if (id == QStringLiteral("grouping")) current_.set_grouping(value.toString());
else if (id == "genre") current_.set_genre(value.toString()); else if (id == QStringLiteral("genre")) current_.set_genre(value.toString());
else if (id == "comment") current_.set_comment(value.toString()); else if (id == QStringLiteral("comment")) current_.set_comment(value.toString());
else if (id == "lyrics") current_.set_lyrics(value.toString()); else if (id == QStringLiteral("lyrics")) current_.set_lyrics(value.toString());
else if (id == "track") current_.set_track(value.toInt()); else if (id == QStringLiteral("track")) current_.set_track(value.toInt());
else if (id == "disc") current_.set_disc(value.toInt()); else if (id == QStringLiteral("disc")) current_.set_disc(value.toInt());
else if (id == "year") current_.set_year(value.toInt()); else if (id == QStringLiteral("year")) current_.set_year(value.toInt());
else if (id == "compilation") current_.set_compilation(value.toBool()); else if (id == QStringLiteral("compilation")) current_.set_compilation(value.toBool());
else if (id == "rating") { current_.set_rating(value.toFloat()); } else if (id == QStringLiteral("rating")) { current_.set_rating(value.toFloat()); }
else qLog(Warning) << "Unknown ID" << id; else qLog(Warning) << "Unknown ID" << id;
} }
@ -687,7 +690,7 @@ void EditTagDialog::SelectionChanged() {
QString summary; QString summary;
if (indexes.count() == 1) { if (indexes.count() == 1) {
summary += "<p><b>" + first_song.PrettyTitleWithArtist().toHtmlEscaped() + "</b></p>"; summary += QStringLiteral("<p><b>") + first_song.PrettyTitleWithArtist().toHtmlEscaped() + QStringLiteral("</b></p>");
} }
else { else {
summary += QLatin1String("<p><b>"); summary += QLatin1String("<p><b>");
@ -701,7 +704,7 @@ void EditTagDialog::SelectionChanged() {
if ((art_different && first_cover_action != UpdateCoverAction::New) || action_different) { if ((art_different && first_cover_action != UpdateCoverAction::New) || action_different) {
tags_cover_art_id_ = -1; // Cancels any pending art load. tags_cover_art_id_ = -1; // Cancels any pending art load.
ui_->tags_art->clear(); 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_->show_cover_action()->setEnabled(false);
album_cover_choice_controller_->cover_to_file_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); album_cover_choice_controller_->cover_from_file_action()->setEnabled(enable_change_art);
@ -761,7 +764,7 @@ void EditTagDialog::UpdateUI(const QModelIndexList &indexes) {
} }
void EditTagDialog::SetText(QLabel *label, const int value, const QString &suffix, const QString &def) { 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) + QLatin1Char(' ') + suffix));
} }
void EditTagDialog::SetDate(QLabel *label, const uint time) { void EditTagDialog::SetDate(QLabel *label, const uint time) {
@ -783,7 +786,7 @@ void EditTagDialog::UpdateSummaryTab(const Song &song) {
cover_options.device_pixel_ratio = devicePixelRatioF(); cover_options.device_pixel_ratio = devicePixelRatioF();
summary_cover_art_id_ = app_->album_cover_loader()->LoadImageAsync(cover_options, song); summary_cover_art_id_ = app_->album_cover_loader()->LoadImageAsync(cover_options, song);
ui_->summary->setText("<p><b>" + song.PrettyTitleWithArtist().toHtmlEscaped() + "</b></p>"); ui_->summary->setText(QStringLiteral("<p><b>") + song.PrettyTitleWithArtist().toHtmlEscaped() + QStringLiteral("</b></p>"));
ui_->length->setText(Utilities::PrettyTimeNanosec(song.length_nanosec())); ui_->length->setText(Utilities::PrettyTimeNanosec(song.length_nanosec()));
@ -1206,7 +1209,7 @@ void EditTagDialog::SaveData() {
cover_url = ref.cover_result_.cover_url; cover_url = ref.cover_result_.cover_url;
} }
else { else {
QString cover_hash = CoverUtils::Sha1CoverHash(ref.current_.effective_albumartist(), ref.current_.album()).toHex(); QString cover_hash = QString::fromLatin1(CoverUtils::Sha1CoverHash(ref.current_.effective_albumartist(), ref.current_.album()).toHex());
if (cover_urls.contains(cover_hash)) { if (cover_urls.contains(cover_hash)) {
cover_url = cover_urls[cover_hash]; cover_url = cover_urls[cover_hash];
} }

View File

@ -82,11 +82,6 @@ class EditTagDialog : public QDialog {
void hideEvent(QHideEvent *e) override; void hideEvent(QHideEvent *e) override;
private: private:
static const char kSettingsGroup[];
static const char kTagsDifferentHintText[];
static const char kArtDifferentHintText[];
static const int kSmallImageSize;
enum class UpdateCoverAction { enum class UpdateCoverAction {
None = 0, None = 0,
Clear, Clear,

View File

@ -30,6 +30,7 @@
#include <QCheckBox> #include <QCheckBox>
#include <QSettings> #include <QSettings>
#include "core/settings.h"
#include "utilities/screenutils.h" #include "utilities/screenutils.h"
#include "messagedialog.h" #include "messagedialog.h"
#include "ui_messagedialog.h" #include "ui_messagedialog.h"
@ -77,7 +78,7 @@ void MessageDialog::ShowMessage(const QString &title, const QString &message, co
void MessageDialog::DoNotShowMessageAgain() { void MessageDialog::DoNotShowMessageAgain() {
if (!settings_group_.isEmpty() && !do_not_show_message_again_.isEmpty()) { if (!settings_group_.isEmpty() && !do_not_show_message_again_.isEmpty()) {
QSettings s; Settings s;
s.beginGroup(settings_group_); s.beginGroup(settings_group_);
s.setValue(do_not_show_message_again_, ui_->checkbox_do_not_show_message_again->isChecked()); s.setValue(do_not_show_message_again_, ui_->checkbox_do_not_show_message_again->isChecked());
s.endGroup(); s.endGroup();

View File

@ -29,13 +29,14 @@
#include "saveplaylistsdialog.h" #include "saveplaylistsdialog.h"
#include "ui_saveplaylistsdialog.h" #include "ui_saveplaylistsdialog.h"
#include "core/settings.h"
#include "playlist/playlist.h" #include "playlist/playlist.h"
SavePlaylistsDialog::SavePlaylistsDialog(const QStringList &types, const QString &default_extension, QWidget *parent) : QDialog(parent), ui_(new Ui_SavePlaylistsDialog) { SavePlaylistsDialog::SavePlaylistsDialog(const QStringList &types, const QString &default_extension, QWidget *parent) : QDialog(parent), ui_(new Ui_SavePlaylistsDialog) {
ui_->setupUi(this); ui_->setupUi(this);
QSettings s; Settings s;
s.beginGroup(Playlist::kSettingsGroup); s.beginGroup(Playlist::kSettingsGroup);
QString last_save_path = s.value("last_save_all_path", QDir::homePath()).toString(); 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(); QString last_save_extension = s.value("last_save_all_extension", default_extension).toString();
@ -79,7 +80,7 @@ void SavePlaylistsDialog::accept() {
return; return;
} }
QSettings s; Settings s;
s.beginGroup(Playlist::kSettingsGroup); s.beginGroup(Playlist::kSettingsGroup);
s.setValue("last_save_all_path", path); s.setValue("last_save_all_path", path);
s.setValue("last_save_all_extension", ui_->combobox_type->currentText()); s.setValue("last_save_all_extension", ui_->combobox_type->currentText());

View File

@ -86,7 +86,7 @@ SnapDialog::SnapDialog(QWidget *parent) : MessageDialog(parent) {
ui_->label_text->adjustSize(); ui_->label_text->adjustSize();
adjustSize(); adjustSize();
settings_group_ = MainWindow::kSettingsGroup; settings_group_ = QLatin1String(MainWindow::kSettingsGroup);
do_not_show_message_again_ = QStringLiteral("ignore_snap"); do_not_show_message_again_ = QStringLiteral("ignore_snap");
if (parent) { if (parent) {

View File

@ -176,7 +176,7 @@ void TrackSelectionDialog::UpdateStack() {
if (tag_data.pending_) { if (tag_data.pending_) {
ui_->stack->setCurrentWidget(ui_->loading_page); ui_->stack->setCurrentWidget(ui_->loading_page);
ui_->progress->set_text(tag_data.progress_string_ + "..."); ui_->progress->set_text(tag_data.progress_string_ + QStringLiteral("..."));
return; return;
} }
else if (tag_data.results_.isEmpty()) { else if (tag_data.results_.isEmpty()) {
@ -286,7 +286,7 @@ void TrackSelectionDialog::SaveData(const QList<Data> &data) {
void TrackSelectionDialog::accept() { void TrackSelectionDialog::accept() {
if (save_on_close_) { if (save_on_close_) {
SetLoading(tr("Saving tracks") + "..."); SetLoading(tr("Saving tracks") + QStringLiteral("..."));
// Save tags in the background // Save tags in the background
QFuture<void> future = QtConcurrent::run(&TrackSelectionDialog::SaveData, data_); QFuture<void> future = QtConcurrent::run(&TrackSelectionDialog::SaveData, data_);

View File

@ -31,7 +31,7 @@
#include "alsadevicefinder.h" #include "alsadevicefinder.h"
#include "enginedevice.h" #include "enginedevice.h"
AlsaDeviceFinder::AlsaDeviceFinder() : DeviceFinder(QStringLiteral("alsa"), { "alsa", "alsasink" }) {} AlsaDeviceFinder::AlsaDeviceFinder() : DeviceFinder(QStringLiteral("alsa"), { QStringLiteral("alsa"), QStringLiteral("alsasink") }) {}
EngineDeviceList AlsaDeviceFinder::ListDevices() { EngineDeviceList AlsaDeviceFinder::ListDevices() {
@ -91,7 +91,7 @@ EngineDeviceList AlsaDeviceFinder::ListDevices() {
} }
EngineDevice device; 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.iconname = device.GuessIconName();
device.card = card; device.card = card;
device.device = dev; device.device = dev;

View File

@ -28,7 +28,7 @@
#include "alsapcmdevicefinder.h" #include "alsapcmdevicefinder.h"
#include "enginedevice.h" #include "enginedevice.h"
AlsaPCMDeviceFinder::AlsaPCMDeviceFinder() : DeviceFinder(QStringLiteral("alsa"), { "alsa", "alsasink" }) {} AlsaPCMDeviceFinder::AlsaPCMDeviceFinder() : DeviceFinder(QStringLiteral("alsa"), { QStringLiteral("alsa"), QStringLiteral("alsasink") }) {}
EngineDeviceList AlsaPCMDeviceFinder::ListDevices() { EngineDeviceList AlsaPCMDeviceFinder::ListDevices() {
@ -45,22 +45,22 @@ EngineDeviceList AlsaPCMDeviceFinder::ListDevices() {
char *hint_desc = snd_device_name_get_hint(*n, "DESC"); char *hint_desc = snd_device_name_get_hint(*n, "DESC");
if (hint_io && hint_name && hint_desc && strcmp(hint_io, "Output") == 0) { 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; char *desc_last = hint_desc;
QString description; QString description;
for (char *desc_i = hint_desc; desc_i && *desc_i != '\0'; ++desc_i) { for (char *desc_i = hint_desc; desc_i && *desc_i != '\0'; ++desc_i) {
if (*desc_i == '\n') { if (*desc_i == '\n') {
*desc_i = '\0'; *desc_i = '\0';
if (!description.isEmpty()) description.append(' '); if (!description.isEmpty()) description.append(QLatin1Char(' '));
description.append(desc_last); description.append(QString::fromUtf8(desc_last));
desc_last = desc_i + 1; desc_last = desc_i + 1;
} }
} }
if (desc_last) { if (desc_last) {
if (!description.isEmpty()) description.append(' '); if (!description.isEmpty()) description.append(QLatin1Char(' '));
description.append(desc_last); description.append(QString::fromUtf8(desc_last));
} }
EngineDevice device; EngineDevice device;

Some files were not shown because too many files have changed in this diff Show More