Formatting

This commit is contained in:
Jonas Kvinge 2022-03-22 21:09:05 +01:00
parent 8cb4e75f70
commit f6b70fda71
106 changed files with 446 additions and 479 deletions

View File

@ -61,7 +61,7 @@ static const char *kMessageHandlerMagic = "__logging_message__";
static const size_t kMessageHandlerMagicLength = strlen(kMessageHandlerMagic); static const size_t kMessageHandlerMagicLength = strlen(kMessageHandlerMagic);
static QtMessageHandler sOriginalMessageHandler = nullptr; static QtMessageHandler sOriginalMessageHandler = nullptr;
template <class T> template<class T>
static T CreateLogger(Level level, const QString &class_name, int line, const char *category); static T CreateLogger(Level level, const QString &class_name, int line, const char *category);
void GLog(const char *domain, int level, const char *message, void*) { void GLog(const char *domain, int level, const char *message, void*) {
@ -85,10 +85,9 @@ void GLog(const char *domain, int level, const char *message, void*) {
qLogCat(Debug, domain) << message; qLogCat(Debug, domain) << message;
break; break;
} }
} }
template <class T> template<class T>
class DebugBase : public QDebug { class DebugBase : public QDebug {
public: public:
DebugBase() : QDebug(sNullDevice) {} DebugBase() : QDebug(sNullDevice) {}
@ -314,11 +313,11 @@ QString LinuxDemangle(const QString &symbol) {
QString DarwinDemangle(const QString &symbol); 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(' ', Qt::SkipEmptyParts);
#else # else
QStringList split = symbol.split(' ', QString::SkipEmptyParts); QStringList split = symbol.split(' ', QString::SkipEmptyParts);
#endif # endif
QString mangled_function = split[3]; QString mangled_function = split[3];
return CXXDemangle(mangled_function); return CXXDemangle(mangled_function);
@ -379,7 +378,7 @@ QDebug CreateLoggerError(int line, const char *pretty_function, const char *cate
namespace { 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 QString("%1%2").arg(duration.count()).arg(unit.c_str()); return QString("%1%2").arg(duration.count()).arg(unit.c_str());
} }

View File

@ -79,7 +79,7 @@ class _MessageHandlerBase : public QObject {
// Reads and writes uint32 length encoded MessageType messages to a socket. // Reads and writes uint32 length encoded MessageType messages to a socket.
// You should subclass this and implement the MessageArrived(MessageType) method. // You should subclass this and implement the MessageArrived(MessageType) method.
template <typename MT> template<typename MT>
class AbstractMessageHandler : public _MessageHandlerBase { class AbstractMessageHandler : public _MessageHandlerBase {
public: public:
AbstractMessageHandler(QIODevice *device, QObject *parent); AbstractMessageHandler(QIODevice *device, QObject *parent);
@ -115,11 +115,11 @@ class AbstractMessageHandler : public _MessageHandlerBase {
QMap<int, ReplyType*> pending_replies_; QMap<int, ReplyType*> pending_replies_;
}; };
template <typename MT> template<typename MT>
AbstractMessageHandler<MT>::AbstractMessageHandler(QIODevice *device, QObject *parent) AbstractMessageHandler<MT>::AbstractMessageHandler(QIODevice *device, QObject *parent)
: _MessageHandlerBase(device, parent) {} : _MessageHandlerBase(device, parent) {}
template <typename MT> template<typename MT>
void AbstractMessageHandler<MT>::SendMessage(const MessageType &message) { void AbstractMessageHandler<MT>::SendMessage(const MessageType &message) {
Q_ASSERT(QThread::currentThread() == thread()); Q_ASSERT(QThread::currentThread() == thread());
@ -127,7 +127,7 @@ void AbstractMessageHandler<MT>::SendMessage(const MessageType &message) {
WriteMessage(QByteArray(data.data(), data.size())); WriteMessage(QByteArray(data.data(), data.size()));
} }
template <typename MT> template<typename MT>
void AbstractMessageHandler<MT>::SendMessageAsync(const MessageType &message) { void AbstractMessageHandler<MT>::SendMessageAsync(const MessageType &message) {
std::string data = message.SerializeAsString(); std::string data = message.SerializeAsString();
QMetaObject::invokeMethod(this, "WriteMessage", Qt::QueuedConnection, Q_ARG(QByteArray, QByteArray(data.data(), data.size()))); QMetaObject::invokeMethod(this, "WriteMessage", Qt::QueuedConnection, Q_ARG(QByteArray, QByteArray(data.data(), data.size())));

View File

@ -56,7 +56,7 @@ class _MessageReplyBase : public QObject {
}; };
// A reply future class that is returned immediately for requests that will occur in the background. Similar to QNetworkReply. // A reply future class that is returned immediately for requests that will occur in the background. Similar to QNetworkReply.
template <typename MessageType> template<typename MessageType>
class MessageReply : public _MessageReplyBase { class MessageReply : public _MessageReplyBase {
public: public:
explicit MessageReply(const MessageType &request_message, QObject *parent = nullptr); explicit MessageReply(const MessageType &request_message, QObject *parent = nullptr);

View File

@ -70,7 +70,7 @@ class _WorkerPoolBase : public QObject {
// A local socket server is started for each process, and the address is passed to the process as argv[1]. // A local socket server is started for each process, and the address is passed to the process as argv[1].
// The process is expected to connect back to the socket server, and when it does a HandlerType is created for it. // The process is expected to connect back to the socket server, and when it does a HandlerType is created for it.
// Instances of HandlerType are created in the WorkerPool's thread. // Instances of HandlerType are created in the WorkerPool's thread.
template <typename HandlerType> template<typename HandlerType>
class WorkerPool : public _WorkerPoolBase { class WorkerPool : public _WorkerPoolBase {
public: public:
explicit WorkerPool(QObject *parent = nullptr); explicit WorkerPool(QObject *parent = nullptr);
@ -121,9 +121,9 @@ class WorkerPool : public _WorkerPoolBase {
// Must only ever be called on my thread. // Must only ever be called on my thread.
void StartOneWorker(Worker *worker); void StartOneWorker(Worker *worker);
template <typename T> template<typename T>
Worker *FindWorker(T Worker::*member, T value) { Worker *FindWorker(T Worker::*member, T value) {
for (typename QList<Worker>::iterator it = workers_.begin() ; it != workers_.end() ; ++it) { for (typename QList<Worker>::iterator it = workers_.begin(); it != workers_.end(); ++it) {
if ((*it).*member == value) { if ((*it).*member == value) {
return &(*it); return &(*it);
} }
@ -131,7 +131,7 @@ class WorkerPool : public _WorkerPoolBase {
return nullptr; return nullptr;
} }
template <typename T> template<typename T>
void DeleteQObjectPointerLater(T **p) { void DeleteQObjectPointerLater(T **p) {
if (*p) { if (*p) {
(*p)->deleteLater(); (*p)->deleteLater();
@ -158,15 +158,15 @@ class WorkerPool : public _WorkerPoolBase {
QAtomicInt next_id_; QAtomicInt next_id_;
QMutex message_queue_mutex_; QMutex message_queue_mutex_;
QQueue<ReplyType*> message_queue_; QQueue<ReplyType *> message_queue_;
}; };
template <typename HandlerType> template<typename HandlerType>
WorkerPool<HandlerType>::WorkerPool(QObject *parent) WorkerPool<HandlerType>::WorkerPool(QObject *parent)
: _WorkerPoolBase(parent), : _WorkerPoolBase(parent),
next_worker_(0), next_worker_(0),
next_id_(0) { next_id_(0) {
worker_count_ = qBound(1, QThread::idealThreadCount() / 2, 4); worker_count_ = qBound(1, QThread::idealThreadCount() / 2, 4);
local_server_name_ = qApp->applicationName().toLower(); local_server_name_ = qApp->applicationName().toLower();
@ -174,10 +174,9 @@ WorkerPool<HandlerType>::WorkerPool(QObject *parent)
if (local_server_name_.isEmpty()) { if (local_server_name_.isEmpty()) {
local_server_name_ = "workerpool"; local_server_name_ = "workerpool";
} }
} }
template <typename HandlerType> template<typename HandlerType>
WorkerPool<HandlerType>::~WorkerPool() { WorkerPool<HandlerType>::~WorkerPool() {
for (const Worker &worker : workers_) { for (const Worker &worker : workers_) {
@ -205,33 +204,32 @@ WorkerPool<HandlerType>::~WorkerPool() {
for (ReplyType *reply : message_queue_) { for (ReplyType *reply : message_queue_) {
reply->Abort(); reply->Abort();
} }
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::SetWorkerCount(const int count) { void WorkerPool<HandlerType>::SetWorkerCount(const int count) {
Q_ASSERT(workers_.isEmpty()); Q_ASSERT(workers_.isEmpty());
worker_count_ = count; worker_count_ = count;
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::SetLocalServerName(const QString &local_server_name) { void WorkerPool<HandlerType>::SetLocalServerName(const QString &local_server_name) {
Q_ASSERT(workers_.isEmpty()); Q_ASSERT(workers_.isEmpty());
local_server_name_ = local_server_name; local_server_name_ = local_server_name;
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::SetExecutableName(const QString &executable_name) { void WorkerPool<HandlerType>::SetExecutableName(const QString &executable_name) {
Q_ASSERT(workers_.isEmpty()); Q_ASSERT(workers_.isEmpty());
executable_name_ = executable_name; executable_name_ = executable_name;
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::Start() { void WorkerPool<HandlerType>::Start() {
QMetaObject::invokeMethod(this, "DoStart"); QMetaObject::invokeMethod(this, "DoStart");
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::DoStart() { void WorkerPool<HandlerType>::DoStart() {
Q_ASSERT(workers_.isEmpty()); Q_ASSERT(workers_.isEmpty());
@ -267,10 +265,9 @@ void WorkerPool<HandlerType>::DoStart() {
workers_ << worker; workers_ << worker;
} }
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::StartOneWorker(Worker *worker) { void WorkerPool<HandlerType>::StartOneWorker(Worker *worker) {
Q_ASSERT(QThread::currentThread() == thread()); Q_ASSERT(QThread::currentThread() == thread());
@ -311,10 +308,9 @@ void WorkerPool<HandlerType>::StartOneWorker(Worker *worker) {
#endif #endif
worker->process_->start(executable_path_, QStringList() << worker->local_server_->fullServerName()); worker->process_->start(executable_path_, QStringList() << worker->local_server_->fullServerName());
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::NewConnection() { void WorkerPool<HandlerType>::NewConnection() {
Q_ASSERT(QThread::currentThread() == thread()); Q_ASSERT(QThread::currentThread() == thread());
@ -339,10 +335,9 @@ void WorkerPool<HandlerType>::NewConnection() {
worker->handler_ = new HandlerType(worker->local_socket_, this); worker->handler_ = new HandlerType(worker->local_socket_, this);
SendQueuedMessages(); SendQueuedMessages();
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::ProcessError(QProcess::ProcessError error) { void WorkerPool<HandlerType>::ProcessError(QProcess::ProcessError error) {
Q_ASSERT(QThread::currentThread() == thread()); Q_ASSERT(QThread::currentThread() == thread());
@ -367,10 +362,9 @@ void WorkerPool<HandlerType>::ProcessError(QProcess::ProcessError error) {
StartOneWorker(worker); StartOneWorker(worker);
break; break;
} }
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::ProcessReadyReadStandardOutput() { void WorkerPool<HandlerType>::ProcessReadyReadStandardOutput() {
Q_ASSERT(QThread::currentThread() == thread()); Q_ASSERT(QThread::currentThread() == thread());
@ -380,10 +374,9 @@ void WorkerPool<HandlerType>::ProcessReadyReadStandardOutput() {
fprintf(stdout, "%s", data.data()); fprintf(stdout, "%s", data.data());
fflush(stdout); fflush(stdout);
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::ProcessReadyReadStandardError() { void WorkerPool<HandlerType>::ProcessReadyReadStandardError() {
Q_ASSERT(QThread::currentThread() == thread()); Q_ASSERT(QThread::currentThread() == thread());
@ -423,10 +416,9 @@ WorkerPool<HandlerType>::SendMessageWithReply(MessageType *message) {
QMetaObject::invokeMethod(this, "SendQueuedMessages", Qt::QueuedConnection); QMetaObject::invokeMethod(this, "SendQueuedMessages", Qt::QueuedConnection);
return reply; return reply;
} }
template <typename HandlerType> template<typename HandlerType>
void WorkerPool<HandlerType>::SendQueuedMessages() { void WorkerPool<HandlerType>::SendQueuedMessages() {
QMutexLocker l(&message_queue_mutex_); QMutexLocker l(&message_queue_mutex_);
@ -445,10 +437,9 @@ void WorkerPool<HandlerType>::SendQueuedMessages() {
handler->SendRequest(reply); handler->SendRequest(reply);
} }
} }
template <typename HandlerType> template<typename HandlerType>
HandlerType *WorkerPool<HandlerType>::NextHandler() const { HandlerType *WorkerPool<HandlerType>::NextHandler() const {
for (int i = 0; i < workers_.count(); ++i) { for (int i = 0; i < workers_.count(); ++i) {

View File

@ -113,6 +113,7 @@ class TagLibFileRefFactory : public FileRefFactory {
return new TagLib::FileRef(QFile::encodeName(filename).constData()); return new TagLib::FileRef(QFile::encodeName(filename).constData());
#endif #endif
} }
private: private:
Q_DISABLE_COPY(TagLibFileRefFactory) Q_DISABLE_COPY(TagLibFileRefFactory)
}; };
@ -130,11 +131,11 @@ TagLib::String QStringToTaglibString(const QString &s) {
} // namespace } // namespace
namespace { namespace {
const char *kMP4_OriginalYear_ID = "----:com.apple.iTunes:ORIGINAL YEAR"; const char *kMP4_OriginalYear_ID = "----:com.apple.iTunes:ORIGINAL YEAR";
const char *kMP4_FMPS_Playcount_ID = "----:com.apple.iTunes:FMPS_Playcount"; const char *kMP4_FMPS_Playcount_ID = "----:com.apple.iTunes:FMPS_Playcount";
const char *kMP4_FMPS_Rating_ID = "----:com.apple.iTunes:FMPS_Rating"; const char *kMP4_FMPS_Rating_ID = "----:com.apple.iTunes:FMPS_Rating";
const char *kASF_OriginalDate_ID = "WM/OriginalReleaseTime"; const char *kASF_OriginalDate_ID = "WM/OriginalReleaseTime";
const char *kASF_OriginalYear_ID = "WM/OriginalReleaseYear"; const char *kASF_OriginalYear_ID = "WM/OriginalReleaseYear";
} // namespace } // namespace
@ -265,7 +266,7 @@ void TagReaderTagLib::ReadFile(const QString &filename, spb::tagreader::SongMeta
if (tag) Decode(tag->comment(), song->mutable_comment()); if (tag) Decode(tag->comment(), song->mutable_comment());
} }
else if (TagLib::WavPack::File *file_wavpack = dynamic_cast<TagLib::WavPack::File *>(fileref->file())) { else if (TagLib::WavPack::File *file_wavpack = dynamic_cast<TagLib::WavPack::File*>(fileref->file())) {
song->set_bitdepth(file_wavpack->audioProperties()->bitsPerSample()); song->set_bitdepth(file_wavpack->audioProperties()->bitsPerSample());
if (file_wavpack->APETag()) { if (file_wavpack->APETag()) {
ParseAPETag(file_wavpack->APETag()->itemListMap(), &disc, &compilation, song); ParseAPETag(file_wavpack->APETag()->itemListMap(), &disc, &compilation, song);
@ -306,7 +307,9 @@ void TagReaderTagLib::ReadFile(const QString &filename, spb::tagreader::SongMeta
if (!map["TCMP"].isEmpty()) compilation = TStringToQString(map["TCMP"].front()->toString()).trimmed(); if (!map["TCMP"].isEmpty()) compilation = TStringToQString(map["TCMP"].front()->toString()).trimmed();
if (!map["TDOR"].isEmpty()) { song->set_originalyear(map["TDOR"].front()->toString().substr(0, 4).toInt()); } if (!map["TDOR"].isEmpty()) {
song->set_originalyear(map["TDOR"].front()->toString().substr(0, 4).toInt());
}
else if (!map["TORY"].isEmpty()) { else if (!map["TORY"].isEmpty()) {
song->set_originalyear(map["TORY"].front()->toString().substr(0, 4).toInt()); song->set_originalyear(map["TORY"].front()->toString().substr(0, 4).toInt());
} }
@ -321,7 +324,7 @@ void TagReaderTagLib::ReadFile(const QString &filename, spb::tagreader::SongMeta
if (!map["APIC"].isEmpty()) song->set_art_automatic(kEmbeddedCover); if (!map["APIC"].isEmpty()) song->set_art_automatic(kEmbeddedCover);
// Find a suitable comment tag. For now we ignore iTunNORM comments. // Find a suitable comment tag. For now we ignore iTunNORM comments.
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()) != "iTunNORM") {
@ -450,7 +453,7 @@ void TagReaderTagLib::ReadFile(const QString &filename, spb::tagreader::SongMeta
} }
if (attributes_map.contains("FMPS/Rating")) { if (attributes_map.contains("FMPS/Rating")) {
const TagLib::ASF::AttributeList& attributes = attributes_map["FMPS/Rating"]; const TagLib::ASF::AttributeList &attributes = attributes_map["FMPS/Rating"];
if (!attributes.isEmpty()) { if (!attributes.isEmpty()) {
float rating = TStringToQString(attributes.front().toString()).toFloat(); float rating = TStringToQString(attributes.front().toString()).toFloat();
if (song->rating() <= 0 && rating > 0) { if (song->rating() <= 0 && rating > 0) {
@ -679,7 +682,7 @@ bool TagReaderTagLib::SaveFile(const QString &filename, const spb::tagreader::So
else if (TagLib::MP4::File *file_mp4 = dynamic_cast<TagLib::MP4::File*>(fileref->file())) { else if (TagLib::MP4::File *file_mp4 = dynamic_cast<TagLib::MP4::File*>(fileref->file())) {
TagLib::MP4::Tag *tag = file_mp4->tag(); TagLib::MP4::Tag *tag = file_mp4->tag();
if (!tag) return false; if (!tag) return false;
tag->setItem("disk", TagLib::MP4::Item(song.disc() <= 0 -1 ? 0 : song.disc(), 0)); tag->setItem("disk", TagLib::MP4::Item(song.disc() <= 0 - 1 ? 0 : song.disc(), 0));
tag->setItem("\251wrt", TagLib::StringList(TagLib::String(song.composer(), TagLib::String::UTF8))); tag->setItem("\251wrt", TagLib::StringList(TagLib::String(song.composer(), TagLib::String::UTF8)));
tag->setItem("\251grp", TagLib::StringList(TagLib::String(song.grouping(), TagLib::String::UTF8))); tag->setItem("\251grp", TagLib::StringList(TagLib::String(song.grouping(), TagLib::String::UTF8)));
tag->setItem("\251lyr", TagLib::StringList(TagLib::String(song.lyrics(), TagLib::String::UTF8))); tag->setItem("\251lyr", TagLib::StringList(TagLib::String(song.lyrics(), TagLib::String::UTF8)));
@ -743,7 +746,7 @@ void TagReaderTagLib::SetTextFrame(const char *id, const std::string &value, Tag
} }
// Update and add the frames // Update and add the frames
for (int i = 0 ; i < frames_buffer.size() ; ++i) { for (int i = 0; i < frames_buffer.size(); ++i) {
TagLib::ID3v2::TextIdentificationFrame *frame = new TagLib::ID3v2::TextIdentificationFrame(frames_buffer.at(i)); TagLib::ID3v2::TextIdentificationFrame *frame = new TagLib::ID3v2::TextIdentificationFrame(frames_buffer.at(i));
if (i == 0) { if (i == 0) {
frame->setText(StdStringToTaglibString(value)); frame->setText(StdStringToTaglibString(value));
@ -799,7 +802,7 @@ void TagReaderTagLib::SetUnsyncLyricsFrame(const std::string &value, TagLib::ID3
} }
// Update and add the frames // Update and add the frames
for (int i = 0 ; i < frames_buffer.size() ; ++i) { for (int i = 0; i < frames_buffer.size(); ++i) {
TagLib::ID3v2::UnsynchronizedLyricsFrame *frame = new TagLib::ID3v2::UnsynchronizedLyricsFrame(frames_buffer.at(i)); TagLib::ID3v2::UnsynchronizedLyricsFrame *frame = new TagLib::ID3v2::UnsynchronizedLyricsFrame(frames_buffer.at(i));
if (i == 0) { if (i == 0) {
frame->setText(StdStringToTaglibString(value)); frame->setText(StdStringToTaglibString(value));
@ -983,7 +986,7 @@ bool TagReaderTagLib::SaveEmbeddedArt(const QString &filename, const QByteArray
// Remove existing covers // Remove existing covers
TagLib::ID3v2::FrameList apiclist = tag->frameListMap()["APIC"]; TagLib::ID3v2::FrameList apiclist = tag->frameListMap()["APIC"];
for (TagLib::ID3v2::FrameList::ConstIterator it = apiclist.begin() ; it != apiclist.end() ; ++it ) { for (TagLib::ID3v2::FrameList::ConstIterator it = apiclist.begin(); it != apiclist.end(); ++it) {
TagLib::ID3v2::AttachedPictureFrame *frame = dynamic_cast<TagLib::ID3v2::AttachedPictureFrame*>(*it); TagLib::ID3v2::AttachedPictureFrame *frame = dynamic_cast<TagLib::ID3v2::AttachedPictureFrame*>(*it);
tag->removeFrame(frame, false); tag->removeFrame(frame, false);
} }

View File

@ -75,13 +75,13 @@ class TagReaderTagLib : public TagReaderBase {
void SetTextFrame(const char *id, const std::string &value, TagLib::ID3v2::Tag *tag) const; void SetTextFrame(const char *id, const std::string &value, TagLib::ID3v2::Tag *tag) const;
void SetUserTextFrame(const QString &description, const QString &value, TagLib::ID3v2::Tag *tag) const; void SetUserTextFrame(const QString &description, const QString &value, TagLib::ID3v2::Tag *tag) const;
void SetUserTextFrame(const std::string &description, const std::string &value, TagLib::ID3v2::Tag *tag) const; void SetUserTextFrame(const std::string &description, const std::string &value, TagLib::ID3v2::Tag *tag) const;
void SetUnsyncLyricsFrame(const std::string& value, TagLib::ID3v2::Tag* tag) const; void SetUnsyncLyricsFrame(const std::string &value, TagLib::ID3v2::Tag *tag) const;
QByteArray LoadEmbeddedAPEArt(const TagLib::APE::ItemListMap &map) const; QByteArray LoadEmbeddedAPEArt(const TagLib::APE::ItemListMap &map) const;
static float ConvertPOPMRating(const int POPM_rating); static float ConvertPOPMRating(const int POPM_rating);
static int ConvertToPOPMRating(const float rating); static int ConvertToPOPMRating(const float rating);
static TagLib::ID3v2::PopularimeterFrame *GetPOPMFrameFromTag(TagLib::ID3v2::Tag* tag); static TagLib::ID3v2::PopularimeterFrame *GetPOPMFrameFromTag(TagLib::ID3v2::Tag *tag);
private: private:
FileRefFactory *factory_; FileRefFactory *factory_;

View File

@ -151,7 +151,7 @@ void TagReaderTagParser::ReadFile(const QString &filename, spb::tagreader::SongM
const auto tracks = taginfo.tracks(); const auto tracks = taginfo.tracks();
for (const auto track : tracks) { for (const auto track : tracks) {
switch(track->format().general) { switch (track->format().general) {
case TagParser::GeneralMediaFormat::Flac: case TagParser::GeneralMediaFormat::Flac:
song->set_filetype(spb::tagreader::SongMetadata_FileType::SongMetadata_FileType_FLAC); song->set_filetype(spb::tagreader::SongMetadata_FileType::SongMetadata_FileType_FLAC);
break; break;
@ -174,7 +174,7 @@ void TagReaderTagParser::ReadFile(const QString &filename, spb::tagreader::SongM
song->set_filetype(spb::tagreader::SongMetadata_FileType::SongMetadata_FileType_OGGSPEEX); song->set_filetype(spb::tagreader::SongMetadata_FileType::SongMetadata_FileType_OGGSPEEX);
break; break;
case TagParser::GeneralMediaFormat::Mpeg1Audio: case TagParser::GeneralMediaFormat::Mpeg1Audio:
switch(track->format().sub) { switch (track->format().sub) {
case TagParser::SubFormats::Mpeg1Layer3: case TagParser::SubFormats::Mpeg1Layer3:
song->set_filetype(spb::tagreader::SongMetadata_FileType::SongMetadata_FileType_MPEG); song->set_filetype(spb::tagreader::SongMetadata_FileType::SongMetadata_FileType_MPEG);
break; break;

View File

@ -99,7 +99,7 @@ int main(int argc, char **argv) {
QRegularExpressionMatch match = regexp.match(output_line); QRegularExpressionMatch match = regexp.match(output_line);
if (match.hasMatch()) { if (match.hasMatch()) {
QString library = match.captured(1); QString library = match.captured(1);
if (QFileInfo(library).fileName() == QFileInfo(filepath).fileName()) { // It's this. if (QFileInfo(library).fileName() == QFileInfo(filepath).fileName()) { // It's this.
continue; continue;
} }
else if (library.startsWith("@executable_path")) { else if (library.startsWith("@executable_path")) {
@ -113,7 +113,7 @@ int main(int argc, char **argv) {
else if (library.startsWith("@rpath")) { else if (library.startsWith("@rpath")) {
QString real_path = library; QString real_path = library;
real_path = real_path.replace("@rpath", bundle_path + "/Contents/Frameworks"); real_path = real_path.replace("@rpath", bundle_path + "/Contents/Frameworks");
if (!QFile(real_path).exists() && !real_path.endsWith("QtSvg")) { // FIXME: Ignore broken svg image plugin. if (!QFile(real_path).exists() && !real_path.endsWith("QtSvg")) { // FIXME: Ignore broken svg image plugin.
qLog(Error) << real_path << "does not exist for" << filepath; qLog(Error) << real_path << "does not exist for" << filepath;
success = false; success = false;
} }
@ -127,7 +127,7 @@ int main(int argc, char **argv) {
success = false; success = false;
} }
} }
else if (library.startsWith("/System/Library/") || library.startsWith("/usr/lib/")) { // System library else if (library.startsWith("/System/Library/") || library.startsWith("/usr/lib/")) { // System library
continue; continue;
} }
else if (library.endsWith("libgcc_s.1.dylib")) { // fftw points to it for some reason. else if (library.endsWith("libgcc_s.1.dylib")) { // fftw points to it for some reason.

View File

@ -21,7 +21,7 @@
#include <QtGlobal> #include <QtGlobal>
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
#include <sys/time.h> # include <sys/time.h>
#endif #endif
#include <iostream> #include <iostream>

View File

@ -28,7 +28,7 @@
#include "tagreaderworker.h" #include "tagreaderworker.h"
TagReaderWorker::TagReaderWorker(QIODevice *socket, QObject *parent) TagReaderWorker::TagReaderWorker(QIODevice *socket, QObject *parent)
: AbstractMessageHandler<spb::tagreader::Message>(socket, parent) {} : AbstractMessageHandler<spb::tagreader::Message>(socket, parent) {}
void TagReaderWorker::MessageArrived(const spb::tagreader::Message &message) { void TagReaderWorker::MessageArrived(const spb::tagreader::Message &message) {

View File

@ -154,7 +154,7 @@ int Analyzer::Base::resizeForBands(const int bands) {
} }
else { else {
exp = 9; exp = 9;
} }
resizeExponent(exp); resizeExponent(exp);
return fht_->size() / 2; return fht_->size() / 2;

View File

@ -74,7 +74,7 @@ class AnalyzerContainer : public QWidget {
void Load(); void Load();
void Save(); void Save();
void SaveFramerate(const int framerate); void SaveFramerate(const int framerate);
template <typename T> template<typename T>
void AddAnalyzerType(); void AddAnalyzerType();
void AddFramerate(const QString &name, const int framerate); void AddFramerate(const QString &name, const int framerate);
@ -96,10 +96,9 @@ class AnalyzerContainer : public QWidget {
Analyzer::Base *current_analyzer_; Analyzer::Base *current_analyzer_;
EngineBase *engine_; EngineBase *engine_;
}; };
template <typename T> template<typename T>
void AnalyzerContainer::AddAnalyzerType() { void AnalyzerContainer::AddAnalyzerType() {
int id = analyzer_types_.count(); int id = analyzer_types_.count();

View File

@ -63,8 +63,7 @@ BlockAnalyzer::BlockAnalyzer(QWidget *parent)
setMaximumWidth(kMaxColumns * (kWidth + 1) - 1); setMaximumWidth(kMaxColumns * (kWidth + 1) - 1);
// mxcl says null pixmaps cause crashes, so let's play it safe // mxcl says null pixmaps cause crashes, so let's play it safe
std::fill(fade_bars_.begin(), fade_bars_.end(), QPixmap(1, 1)); std::fill(fade_bars_.begin(), fade_bars_.end(), QPixmap(1, 1));
} }
void BlockAnalyzer::resizeEvent(QResizeEvent *e) { void BlockAnalyzer::resizeEvent(QResizeEvent *e) {
@ -89,7 +88,7 @@ void BlockAnalyzer::resizeEvent(QResizeEvent *e) {
if (rows_ != oldRows) { if (rows_ != oldRows) {
barpixmap_ = QPixmap(kWidth, rows_ * (kHeight + 1)); barpixmap_ = QPixmap(kWidth, rows_ * (kHeight + 1));
std::fill(fade_bars_.begin(), fade_bars_.end(), QPixmap(kWidth, rows_ * (kHeight + 1))); std::fill(fade_bars_.begin(), fade_bars_.end(), QPixmap(kWidth, rows_ * (kHeight + 1)));
yscale_.resize(rows_ + 1); yscale_.resize(rows_ + 1);

View File

@ -65,14 +65,14 @@ class BlockAnalyzer : public Analyzer::Base {
private: private:
QPixmap *bar() { return &barpixmap_; } QPixmap *bar() { return &barpixmap_; }
int columns_, rows_; // number of rows and columns of blocks int columns_, rows_; // number of rows and columns of blocks
int y_; // y-offset from top of widget int y_; // y-offset from top of widget
QPixmap barpixmap_; QPixmap barpixmap_;
QPixmap topbarpixmap_; QPixmap topbarpixmap_;
QPixmap background_; QPixmap background_;
QPixmap canvas_; QPixmap canvas_;
Analyzer::Scope scope_; // so we don't create a vector every frame Analyzer::Scope scope_; // so we don't create a vector every frame
QVector<double> store_; // current bar heights QVector<double> store_; // current bar heights
QVector<double> yscale_; QVector<double> yscale_;
QVector<QPixmap> fade_bars_; QVector<QPixmap> fade_bars_;

View File

@ -43,12 +43,12 @@
using Analyzer::Scope; using Analyzer::Scope;
const int Rainbow::RainbowAnalyzer::kHeight[] = {21, 33}; const int Rainbow::RainbowAnalyzer::kHeight[] = { 21, 33 };
const int Rainbow::RainbowAnalyzer::kWidth[] = {34, 53}; const int Rainbow::RainbowAnalyzer::kWidth[] = { 34, 53 };
const int Rainbow::RainbowAnalyzer::kFrameCount[] = {6, 16}; const int Rainbow::RainbowAnalyzer::kFrameCount[] = { 6, 16 };
const int Rainbow::RainbowAnalyzer::kRainbowHeight[] = {21, 16}; const int Rainbow::RainbowAnalyzer::kRainbowHeight[] = { 21, 16 };
const int Rainbow::RainbowAnalyzer::kRainbowOverlap[] = {13, 15}; const int Rainbow::RainbowAnalyzer::kRainbowOverlap[] = { 13, 15 };
const int Rainbow::RainbowAnalyzer::kSleepingHeight[] = {24, 33}; const int Rainbow::RainbowAnalyzer::kSleepingHeight[] = { 24, 33 };
const char *Rainbow::NyanCatAnalyzer::kName = "Nyanalyzer Cat"; const char *Rainbow::NyanCatAnalyzer::kName = "Nyanalyzer Cat";
const char *Rainbow::RainbowDashAnalyzer::kName = "Rainbow Dash"; const char *Rainbow::RainbowDashAnalyzer::kName = "Rainbow Dash";

View File

@ -93,7 +93,7 @@ class RainbowAnalyzer : public Analyzer::Base {
private: private:
// "constants" that get initialized in the constructor // "constants" that get initialized in the constructor
float band_scale_[kRainbowBands]{}; float band_scale_[kRainbowBands] {};
QPen colors_[kRainbowBands]; QPen colors_[kRainbowBands];
// Rainbow Nyancat & Dash // Rainbow Nyancat & Dash
@ -104,7 +104,7 @@ class RainbowAnalyzer : public Analyzer::Base {
int frame_; int frame_;
// The y positions of each point on the rainbow. // The y positions of each point on the rainbow.
float history_[kHistorySize * kRainbowBands]{}; float history_[kHistorySize * kRainbowBands] {};
// A cache of the last frame's rainbow, // A cache of the last frame's rainbow,
// so it can be used in the next frame. // so it can be used in the next frame.
@ -142,6 +142,6 @@ class RainbowDashAnalyzer : public RainbowAnalyzer {
static const char *kName; static const char *kName;
}; };
} } // namespace Rainbow
#endif // RAINBOWANALYZER_H #endif // RAINBOWANALYZER_H

View File

@ -335,8 +335,8 @@ void CollectionBackend::AddDirectory(const QString &path) {
q.prepare(QString("INSERT INTO %1 (path, subdirs) VALUES (:path, 1)").arg(dirs_table_)); q.prepare(QString("INSERT INTO %1 (path, subdirs) VALUES (:path, 1)").arg(dirs_table_));
q.BindValue(":path", db_path); q.BindValue(":path", db_path);
if (!q.Exec()) { if (!q.Exec()) {
db_->ReportErrors(q); db_->ReportErrors(q);
return; return;
} }
Directory dir; Directory dir;
@ -634,15 +634,13 @@ void CollectionBackend::AddOrUpdateSongs(const SongList &songs) {
added_songs << new_song; added_songs << new_song;
continue; continue;
} }
} }
// Create new song // Create new song
int id = -1; int id = -1;
{ // Insert the row and create a new ID { // Insert the row and create a new ID
SqlQuery q(db); SqlQuery q(db);
q.prepare(QString("INSERT INTO %1 (" + Song::kColumnSpec + ") VALUES (" + Song::kBindSpec + ")").arg(songs_table_)); q.prepare(QString("INSERT INTO %1 (" + Song::kColumnSpec + ") VALUES (" + Song::kBindSpec + ")").arg(songs_table_));
song.BindToQuery(&q); song.BindToQuery(&q);
@ -656,7 +654,7 @@ void CollectionBackend::AddOrUpdateSongs(const SongList &songs) {
if (id == -1) return; if (id == -1) return;
{ // Add to the FTS index { // Add to the FTS index
SqlQuery q(db); SqlQuery q(db);
q.prepare(QString("INSERT INTO %1 (ROWID, " + Song::kFtsColumnSpec + ") VALUES (:id, " + Song::kFtsBindSpec + ")").arg(fts_table_)); q.prepare(QString("INSERT INTO %1 (ROWID, " + Song::kFtsColumnSpec + ") VALUES (:id, " + Song::kFtsBindSpec + ")").arg(fts_table_));
q.BindValue(":id", id); q.BindValue(":id", id);
@ -1345,7 +1343,7 @@ void CollectionBackend::CompilationsNeedUpdating() {
if (album.isEmpty()) continue; if (album.isEmpty()) continue;
// Find the directory the song is in // Find the directory the song is in
QString directory = url.toString(QUrl::PreferLocalFile|QUrl::RemoveFilename); QString directory = url.toString(QUrl::PreferLocalFile | QUrl::RemoveFilename);
CompilationInfo &info = compilation_info[directory + album]; CompilationInfo &info = compilation_info[directory + album];
info.urls << url; info.urls << url;

View File

@ -68,24 +68,23 @@ CollectionFilterWidget::CollectionFilterWidget(QWidget *parent)
QString available_fields = Song::kFtsColumns.join(", ").replace(QRegularExpression("\\bfts"), ""); QString available_fields = Song::kFtsColumns.join(", ").replace(QRegularExpression("\\bfts"), "");
ui_->search_field->setToolTip( ui_->search_field->setToolTip(
QString("<html><head/><body><p>") + QString("<html><head/><body><p>") +
tr("Prefix a word with a field name to limit the search to that field, e.g.:") + tr("Prefix a word with a field name to limit the search to that field, e.g.:") +
QString(" ") + QString(" ") +
QString("<span style=\"font-weight:600;\">") + QString("<span style=\"font-weight:600;\">") +
tr("artist") + tr("artist") +
QString(":") + QString(":") +
QString("</span><span style=\"font-style:italic;\">Strawbs</span>") + QString("</span><span style=\"font-style:italic;\">Strawbs</span>") +
QString(" ") + QString(" ") +
tr("searches the collection for all artists that contain the word") + tr("searches the collection for all artists that contain the word") +
QString(" Strawbs.") + QString(" Strawbs.") +
QString("</p><p><span style=\"font-weight:600;\">") + QString("</p><p><span style=\"font-weight:600;\">") +
tr("Available fields") + tr("Available fields") +
QString(": ") + QString(": ") +
"</span><span style=\"font-style:italic;\">" + "</span><span style=\"font-style:italic;\">" +
available_fields + available_fields +
QString("</span>.") + QString("</span>.") +
QString("</p></body></html>") QString("</p></body></html>"));
);
QObject::connect(ui_->search_field, &QSearchField::returnPressed, this, &CollectionFilterWidget::ReturnPressed); QObject::connect(ui_->search_field, &QSearchField::returnPressed, this, &CollectionFilterWidget::ReturnPressed);
QObject::connect(filter_delay_, &QTimer::timeout, this, &CollectionFilterWidget::FilterDelayTimeout); QObject::connect(filter_delay_, &QTimer::timeout, this, &CollectionFilterWidget::FilterDelayTimeout);
@ -177,16 +176,15 @@ void CollectionFilterWidget::Init(CollectionModel *model) {
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();
if (version == 1) { if (version == 1) {
model_->SetGroupBy(CollectionModel::Grouping( model_->SetGroupBy(CollectionModel::Grouping(
CollectionModel::GroupBy(s.value(group_by(1), static_cast<int>(CollectionModel::GroupBy_AlbumArtist)).toInt()), CollectionModel::GroupBy(s.value(group_by(1), static_cast<int>(CollectionModel::GroupBy_AlbumArtist)).toInt()),
CollectionModel::GroupBy(s.value(group_by(2), static_cast<int>(CollectionModel::GroupBy_AlbumDisc)).toInt()), CollectionModel::GroupBy(s.value(group_by(2), static_cast<int>(CollectionModel::GroupBy_AlbumDisc)).toInt()),
CollectionModel::GroupBy(s.value(group_by(3), static_cast<int>(CollectionModel::GroupBy_None)).toInt()))); CollectionModel::GroupBy(s.value(group_by(3), static_cast<int>(CollectionModel::GroupBy_None)).toInt())));
} }
else { else {
model_->SetGroupBy(CollectionModel::Grouping(CollectionModel::GroupBy_AlbumArtist, CollectionModel::GroupBy_AlbumDisc, CollectionModel::GroupBy_None)); model_->SetGroupBy(CollectionModel::Grouping(CollectionModel::GroupBy_AlbumArtist, CollectionModel::GroupBy_AlbumDisc, CollectionModel::GroupBy_None));
} }
s.endGroup(); s.endGroup();
} }
} }
void CollectionFilterWidget::ReloadSettings() { void CollectionFilterWidget::ReloadSettings() {

View File

@ -100,7 +100,7 @@ void CollectionItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem
// Draw the line under the item // Draw the line under the item
QColor line_color = opt.palette.color(QPalette::Text); QColor line_color = opt.palette.color(QPalette::Text);
QLinearGradient grad_color(opt.rect.bottomLeft(), opt.rect.bottomRight()); QLinearGradient grad_color(opt.rect.bottomLeft(), opt.rect.bottomRight());
const double fade_start_end = (opt.rect.width()/3.0)/opt.rect.width(); const double fade_start_end = (opt.rect.width() / 3.0) / opt.rect.width();
line_color.setAlphaF(0.0); line_color.setAlphaF(0.0);
grad_color.setColorAt(0, line_color); grad_color.setColorAt(0, line_color);
line_color.setAlphaF(0.5); line_color.setAlphaF(0.5);

View File

@ -476,7 +476,7 @@ QString CollectionModel::DividerDisplayText(const GroupBy type, const QString &k
case GroupBy_Genre: case GroupBy_Genre:
case GroupBy_FileType: case GroupBy_FileType:
case GroupBy_Format: case GroupBy_Format:
if (key == "0") return "0-9"; if (key == "0") return "0-9";
return key.toUpper(); return key.toUpper();
case GroupBy_YearAlbum: case GroupBy_YearAlbum:

View File

@ -155,11 +155,11 @@ void CollectionQuery::AddWhere(const QString &column, const QVariant &value, con
} }
else if ( else if (
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
value.metaType().id() == QMetaType::QString value.metaType().id() == QMetaType::QString
#else #else
value.type() == QVariant::String value.type() == QVariant::String
#endif #endif
&& value.toString().isNull()) { && value.toString().isNull()) {
where_clauses_ << QString("%1 %2 ?").arg(column, op); where_clauses_ << QString("%1 %2 ?").arg(column, op);
bound_values_ << QString(""); bound_values_ << QString("");
} }

View File

@ -125,4 +125,4 @@ class CollectionQuery : public QSqlQuery {
int limit_; int limit_;
}; };
#endif // COLLECTIONQUERY_H #endif // COLLECTIONQUERY_H

View File

@ -148,7 +148,7 @@ ContextView::ContextView(QWidget *parent)
widget_scrollarea_->setLayout(layout_scrollarea_); widget_scrollarea_->setLayout(layout_scrollarea_);
widget_scrollarea_->setContentsMargins(0, 0, 0, 0); widget_scrollarea_->setContentsMargins(0, 0, 0, 0);
label_top_->setAlignment(Qt::AlignTop|Qt::AlignLeft); label_top_->setAlignment(Qt::AlignTop | Qt::AlignLeft);
label_top_->setWordWrap(true); label_top_->setWordWrap(true);
label_top_->setMinimumHeight(50); label_top_->setMinimumHeight(50);
label_top_->setContentsMargins(0, 0, 32, 0); label_top_->setContentsMargins(0, 0, 32, 0);
@ -262,15 +262,15 @@ ContextView::ContextView(QWidget *parent)
layout_play_->addWidget(label_play_lyrics_); layout_play_->addWidget(label_play_lyrics_);
layout_play_->addSpacerItem(spacer_play_bottom_); layout_play_->addSpacerItem(spacer_play_bottom_);
labels_play_ << label_engine_title_ labels_play_ << label_engine_title_
<< label_device_title_ << label_device_title_
<< label_filetype_title_ << label_filetype_title_
<< label_length_title_ << label_length_title_
<< label_samplerate_title_ << label_samplerate_title_
<< label_bitdepth_title_ << label_bitdepth_title_
<< label_bitrate_title_ << label_bitrate_title_
<< label_play_albums_ << label_play_albums_
<< label_play_lyrics_; << label_play_lyrics_;
labels_play_data_ << label_engine_icon_ labels_play_data_ << label_engine_icon_
<< label_engine_ << label_engine_
@ -379,7 +379,7 @@ void ContextView::ReloadSettings() {
action_search_lyrics_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[ContextSettingsPage::ContextSettingsOrder::SEARCH_LYRICS], true).toBool()); action_search_lyrics_->setChecked(s.value(ContextSettingsPage::kSettingsGroupEnable[ContextSettingsPage::ContextSettingsOrder::SEARCH_LYRICS], true).toBool());
font_headline_ = s.value("font_headline", font().family()).toString(); font_headline_ = s.value("font_headline", font().family()).toString();
font_normal_ = s.value("font_normal", font().family()).toString(); font_normal_ = s.value("font_normal", font().family()).toString();
font_size_headline_ = s.value("font_size_headline", ContextSettingsPage::kDefaultFontSizeHeadline).toReal(); font_size_headline_ = s.value("font_size_headline", ContextSettingsPage::kDefaultFontSizeHeadline).toReal();
font_size_normal_ = s.value("font_size_normal", font().pointSizeF()).toReal(); font_size_normal_ = s.value("font_size_normal", font().pointSizeF()).toReal();
s.endGroup(); s.endGroup();

View File

@ -20,14 +20,14 @@
// This template function declaration is used in defining arraysize. // This template function declaration is used in defining arraysize.
// Note that the function doesn't need an implementation, as we only // Note that the function doesn't need an implementation, as we only
// use its type. // use its type.
template <typename T, size_t N> template<typename T, size_t N>
char (&ArraySizeHelper(T (&array)[N]))[N]; char (&ArraySizeHelper(T (&array)[N]))[N];
// That gcc wants both of these prototypes seems mysterious. VC, for // That gcc wants both of these prototypes seems mysterious. VC, for
// its part, can't decide which to use (another mystery). Matching of // its part, can't decide which to use (another mystery). Matching of
// template overloads: the final frontier. // template overloads: the final frontier.
#ifndef _MSC_VER #ifndef _MSC_VER
template <typename T, size_t N> template<typename T, size_t N>
char (&ArraySizeHelper(const T (&array)[N]))[N]; char (&ArraySizeHelper(const T (&array)[N]))[N];
#endif #endif

View File

@ -109,12 +109,12 @@ bool FilesystemMusicStorage::DeleteFromStorage(const DeleteJob &job) {
if (job.use_trash_) { if (job.use_trash_) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
if (fileInfo.isDir()) { if (fileInfo.isDir()) {
return Utilities::MoveToTrashRecursive(path); return Utilities::MoveToTrashRecursive(path);
} }
else { else {
return QFile::moveToTrash(path); return QFile::moveToTrash(path);
} }
#else #else
return false; return false;
#endif #endif

View File

@ -25,7 +25,7 @@
// Usage: // Usage:
// Lazy<Foo> my_lazy_object([]() { return new Foo; }); // Lazy<Foo> my_lazy_object([]() { return new Foo; });
template <typename T> template<typename T>
class Lazy { class Lazy {
public: public:
explicit Lazy(std::function<T*()> init) : init_(init) {} explicit Lazy(std::function<T*()> init) : init_(init) {}

View File

@ -476,9 +476,9 @@ MainWindow::MainWindow(Application *app, std::shared_ptr<SystemTrayIcon> tray_ic
QObject::connect(file_view_, &FileView::CopyToCollection, this, &MainWindow::CopyFilesToCollection); QObject::connect(file_view_, &FileView::CopyToCollection, this, &MainWindow::CopyFilesToCollection);
QObject::connect(file_view_, &FileView::MoveToCollection, this, &MainWindow::MoveFilesToCollection); QObject::connect(file_view_, &FileView::MoveToCollection, this, &MainWindow::MoveFilesToCollection);
QObject::connect(file_view_, &FileView::EditTags, this, &MainWindow::EditFileTags); QObject::connect(file_view_, &FileView::EditTags, this, &MainWindow::EditFileTags);
#ifndef Q_OS_WIN # ifndef Q_OS_WIN
QObject::connect(file_view_, &FileView::CopyToDevice, this, &MainWindow::CopyFilesToDevice); QObject::connect(file_view_, &FileView::CopyToDevice, this, &MainWindow::CopyFilesToDevice);
#endif # endif
#endif #endif
file_view_->SetTaskManager(app_->task_manager()); file_view_->SetTaskManager(app_->task_manager());
@ -536,8 +536,8 @@ MainWindow::MainWindow(Application *app, std::shared_ptr<SystemTrayIcon> tray_ic
QObject::connect(app_->scrobbler(), &AudioScrobbler::ErrorMessage, this, &MainWindow::ShowErrorDialog); QObject::connect(app_->scrobbler(), &AudioScrobbler::ErrorMessage, this, &MainWindow::ShowErrorDialog);
// Playlist view actions // Playlist view actions
ui_->action_next_playlist->setShortcuts(QList<QKeySequence>() << QKeySequence::fromString("Ctrl+Tab")<< QKeySequence::fromString("Ctrl+PgDown")); ui_->action_next_playlist->setShortcuts(QList<QKeySequence>() << QKeySequence::fromString("Ctrl+Tab") << QKeySequence::fromString("Ctrl+PgDown"));
ui_->action_previous_playlist->setShortcuts(QList<QKeySequence>() << QKeySequence::fromString("Ctrl+Shift+Tab")<< QKeySequence::fromString("Ctrl+PgUp")); ui_->action_previous_playlist->setShortcuts(QList<QKeySequence>() << QKeySequence::fromString("Ctrl+Shift+Tab") << QKeySequence::fromString("Ctrl+PgUp"));
// Actions for switching tabs will be global to the entire window, so adding them here // Actions for switching tabs will be global to the entire window, so adding them here
addAction(ui_->action_next_playlist); addAction(ui_->action_next_playlist);
@ -680,7 +680,7 @@ MainWindow::MainWindow(Application *app, std::shared_ptr<SystemTrayIcon> tray_ic
QObject::connect(tidal_view_->albums_collection_view(), &InternetCollectionView::AddToPlaylistSignal, this, &MainWindow::AddToPlaylist); QObject::connect(tidal_view_->albums_collection_view(), &InternetCollectionView::AddToPlaylistSignal, this, &MainWindow::AddToPlaylist);
QObject::connect(tidal_view_->songs_collection_view(), &InternetCollectionView::AddToPlaylistSignal, this, &MainWindow::AddToPlaylist); QObject::connect(tidal_view_->songs_collection_view(), &InternetCollectionView::AddToPlaylistSignal, this, &MainWindow::AddToPlaylist);
QObject::connect(tidal_view_->search_view(), &InternetSearchView::AddToPlaylist, this, &MainWindow::AddToPlaylist); QObject::connect(tidal_view_->search_view(), &InternetSearchView::AddToPlaylist, this, &MainWindow::AddToPlaylist);
if (TidalService *tidalservice = qobject_cast<TidalService*> (app_->internet_services()->ServiceBySource(Song::Source_Tidal))) { if (TidalService *tidalservice = qobject_cast<TidalService*>(app_->internet_services()->ServiceBySource(Song::Source_Tidal))) {
QObject::connect(this, &MainWindow::AuthorizationUrlReceived, tidalservice, &TidalService::AuthorizationUrlReceived); QObject::connect(this, &MainWindow::AuthorizationUrlReceived, tidalservice, &TidalService::AuthorizationUrlReceived);
} }
#endif #endif
@ -1001,11 +1001,11 @@ MainWindow::MainWindow(Application *app, std::shared_ptr<SystemTrayIcon> tray_ic
#ifdef HAVE_QTSPARKLE #ifdef HAVE_QTSPARKLE
QUrl sparkle_url; QUrl sparkle_url;
#if defined(Q_OS_MACOS) # if defined(Q_OS_MACOS)
sparkle_url.setUrl("https://www.strawberrymusicplayer.org/sparkle-macos"); sparkle_url.setUrl("https://www.strawberrymusicplayer.org/sparkle-macos");
#elif defined(Q_OS_WIN) # elif defined(Q_OS_WIN)
sparkle_url.setUrl("https://www.strawberrymusicplayer.org/sparkle-windows"); sparkle_url.setUrl("https://www.strawberrymusicplayer.org/sparkle-windows");
#endif # endif
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);
@ -2274,7 +2274,7 @@ void MainWindow::PlaylistRemoveCurrent() {
void MainWindow::PlaylistClearCurrent() { void MainWindow::PlaylistClearCurrent() {
if (app_->playlist_manager()->current()->rowCount() > Playlist::kUndoItemLimit) { if (app_->playlist_manager()->current()->rowCount() > Playlist::kUndoItemLimit) {
QMessageBox messagebox(QMessageBox::Warning, tr("Clear playlist"), tr("Playlist has %1 songs, too large to undo, are you sure you want to clear the playlist?").arg(app_->playlist_manager()->current()->rowCount()), QMessageBox::Ok|QMessageBox::Cancel); QMessageBox messagebox(QMessageBox::Warning, tr("Clear playlist"), tr("Playlist has %1 songs, too large to undo, are you sure you want to clear the playlist?").arg(app_->playlist_manager()->current()->rowCount()), QMessageBox::Ok | QMessageBox::Cancel);
messagebox.setTextFormat(Qt::RichText); messagebox.setTextFormat(Qt::RichText);
int result = messagebox.exec(); int result = messagebox.exec();
switch (result) { switch (result) {
@ -2874,22 +2874,20 @@ void MainWindow::Raise() {
show(); show();
activateWindow(); activateWindow();
hidden_ = false; hidden_ = false;
} }
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) # if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, qintptr *result) { bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, qintptr *result) {
#else # else
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) { bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) {
#endif # endif
if (exit_count_ == 0 && message) { if (exit_count_ == 0 && message) {
MSG *msg = static_cast<MSG*>(message); MSG *msg = static_cast<MSG*>(message);
thumbbar_->HandleWinEvent(msg); thumbbar_->HandleWinEvent(msg);
} }
return QMainWindow::nativeEvent(eventType, message, result); return QMainWindow::nativeEvent(eventType, message, result);
} }
#endif // Q_OS_WIN #endif // Q_OS_WIN

View File

@ -120,11 +120,11 @@ class MainWindow : public QMainWindow, public PlatformInterface {
void closeEvent(QCloseEvent *e) override; void closeEvent(QCloseEvent *e) override;
void keyPressEvent(QKeyEvent *e) override; void keyPressEvent(QKeyEvent *e) override;
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) # if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override; bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override;
#else # else
bool nativeEvent(const QByteArray &eventType, void *message, long *result) override; bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
#endif # endif
#endif #endif
// PlatformInterface // PlatformInterface

View File

@ -75,7 +75,7 @@
#include "radios/radiochannel.h" #include "radios/radiochannel.h"
#ifdef HAVE_LIBMTP #ifdef HAVE_LIBMTP
#include "device/mtpconnection.h" # include "device/mtpconnection.h"
#endif #endif
void RegisterMetaTypes() { void RegisterMetaTypes() {

View File

@ -113,7 +113,7 @@ Engine::EngineType Player::CreateEngine(Engine::EngineType enginetype) {
Engine::EngineType use_enginetype(Engine::None); Engine::EngineType use_enginetype(Engine::None);
for (int i = 0; use_enginetype == Engine::None; i++) { for (int i = 0; use_enginetype == Engine::None; i++) {
switch(enginetype) { switch (enginetype) {
case Engine::None: case Engine::None:
#ifdef HAVE_GSTREAMER #ifdef HAVE_GSTREAMER
case Engine::GStreamer:{ case Engine::GStreamer:{
@ -126,18 +126,20 @@ Engine::EngineType Player::CreateEngine(Engine::EngineType enginetype) {
#endif #endif
#ifdef HAVE_VLC #ifdef HAVE_VLC
case Engine::VLC: case Engine::VLC:
use_enginetype=Engine::VLC; use_enginetype = Engine::VLC;
engine_ = std::make_shared<VLCEngine>(app_->task_manager()); engine_ = std::make_shared<VLCEngine>(app_->task_manager());
break; break;
#endif #endif
default: default:
if (i > 0) { qFatal("No engine available!"); } if (i > 0) {
qFatal("No engine available!");
}
enginetype = Engine::None; enginetype = Engine::None;
break; break;
} }
} }
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; QSettings s;
s.beginGroup(BackendSettingsPage::kSettingsGroup); s.beginGroup(BackendSettingsPage::kSettingsGroup);
s.setValue("engine", EngineName(use_enginetype)); s.setValue("engine", EngineName(use_enginetype));
@ -167,7 +169,9 @@ void Player::Init() {
CreateEngine(enginetype); CreateEngine(enginetype);
} }
if (!engine_->Init()) { qFatal("Error initializing audio engine"); } if (!engine_->Init()) {
qFatal("Error initializing audio engine");
}
analyzer_->SetEngine(engine_.get()); analyzer_->SetEngine(engine_.get());
@ -426,7 +430,7 @@ void Player::PlayPlaylistInternal(const Engine::TrackChangeFlags change, const P
if (playlist == nullptr) { if (playlist == nullptr) {
qLog(Warning) << "Playlist '" << playlist_name << "' not found."; qLog(Warning) << "Playlist '" << playlist_name << "' not found.";
return; return;
} }
app_->playlist_manager()->SetActivePlaylist(playlist->id()); app_->playlist_manager()->SetActivePlaylist(playlist->id());
app_->playlist_manager()->SetCurrentPlaylist(playlist->id()); app_->playlist_manager()->SetCurrentPlaylist(playlist->id());
@ -515,7 +519,7 @@ void Player::UnPause() {
const Song &song = current_item_->Metadata(); const Song &song = current_item_->Metadata();
if (url_handlers_.contains(song.url().scheme()) && song.stream_url_can_expire()) { if (url_handlers_.contains(song.url().scheme()) && song.stream_url_can_expire()) {
const quint64 time = QDateTime::currentDateTime().toSecsSinceEpoch() - pause_time_.toSecsSinceEpoch(); const quint64 time = QDateTime::currentDateTime().toSecsSinceEpoch() - pause_time_.toSecsSinceEpoch();
if (time >= 30) { // Stream URL might be expired. if (time >= 30) { // Stream URL might be expired.
qLog(Debug) << "Re-requesting stream URL for" << song.url(); qLog(Debug) << "Re-requesting stream URL for" << song.url();
play_offset_nanosec_ = engine_->position_nanosec(); play_offset_nanosec_ = engine_->position_nanosec();
HandleLoadResult(url_handlers_[song.url().scheme()]->StartLoading(song.url())); HandleLoadResult(url_handlers_[song.url().scheme()]->StartLoading(song.url()));

View File

@ -17,7 +17,7 @@
// caller must own the object it gives to ScopedCFTypeRef<>, and relinquishes // caller must own the object it gives to ScopedCFTypeRef<>, and relinquishes
// an ownership claim to that object. ScopedCFTypeRef<> does not call // an ownership claim to that object. ScopedCFTypeRef<> does not call
// CFRetain(). // CFRetain().
template <typename CFT> template<typename CFT>
class ScopedCFTypeRef { class ScopedCFTypeRef {
public: public:
typedef CFT element_type; typedef CFT element_type;

View File

@ -27,7 +27,7 @@
#include <QtDebug> #include <QtDebug>
template <typename T> template<typename T>
class ScopedGObject { class ScopedGObject {
public: public:
ScopedGObject() : object_(nullptr) {} ScopedGObject() : object_(nullptr) {}

View File

@ -30,7 +30,7 @@
#include "simpletreemodel.h" #include "simpletreemodel.h"
template <typename T> template<typename T>
class SimpleTreeItem { class SimpleTreeItem {
public: public:
explicit SimpleTreeItem(int _type, SimpleTreeModel<T> *_model); // For the root item explicit SimpleTreeItem(int _type, SimpleTreeModel<T> *_model); // For the root item
@ -58,13 +58,13 @@ class SimpleTreeItem {
bool lazy_loaded; bool lazy_loaded;
T *parent; T *parent;
QList<T*> children; QList<T *> children;
QAbstractItemModel *child_model; QAbstractItemModel *child_model;
SimpleTreeModel<T> *model; SimpleTreeModel<T> *model;
}; };
template <typename T> template<typename T>
SimpleTreeItem<T>::SimpleTreeItem(int _type, SimpleTreeModel<T> *_model) SimpleTreeItem<T>::SimpleTreeItem(int _type, SimpleTreeModel<T> *_model)
: type(_type), : type(_type),
row(0), row(0),
@ -73,7 +73,7 @@ SimpleTreeItem<T>::SimpleTreeItem(int _type, SimpleTreeModel<T> *_model)
child_model(nullptr), child_model(nullptr),
model(_model) {} model(_model) {}
template <typename T> template<typename T>
SimpleTreeItem<T>::SimpleTreeItem(int _type, const QString &_key, T *_parent) SimpleTreeItem<T>::SimpleTreeItem(int _type, const QString &_key, T *_parent)
: type(_type), : type(_type),
key(_key), key(_key),
@ -87,7 +87,7 @@ SimpleTreeItem<T>::SimpleTreeItem(int _type, const QString &_key, T *_parent)
} }
} }
template <typename T> template<typename T>
SimpleTreeItem<T>::SimpleTreeItem(int _type, T *_parent) SimpleTreeItem<T>::SimpleTreeItem(int _type, T *_parent)
: type(_type), : type(_type),
lazy_loaded(false), lazy_loaded(false),
@ -100,7 +100,7 @@ SimpleTreeItem<T>::SimpleTreeItem(int _type, T *_parent)
} }
} }
template <typename T> template<typename T>
void SimpleTreeItem<T>::InsertNotify(T *_parent) { void SimpleTreeItem<T>::InsertNotify(T *_parent) {
parent = _parent; parent = _parent;
model = parent->model; model = parent->model;
@ -111,7 +111,7 @@ void SimpleTreeItem<T>::InsertNotify(T *_parent) {
model->EndInsert(); model->EndInsert();
} }
template <typename T> template<typename T>
void SimpleTreeItem<T>::DeleteNotify(int child_row) { void SimpleTreeItem<T>::DeleteNotify(int child_row) {
model->BeginDelete(static_cast<T*>(this), child_row); model->BeginDelete(static_cast<T*>(this), child_row);
delete children.takeAt(child_row); delete children.takeAt(child_row);
@ -121,7 +121,7 @@ void SimpleTreeItem<T>::DeleteNotify(int child_row) {
model->EndDelete(); model->EndDelete();
} }
template <typename T> template<typename T>
void SimpleTreeItem<T>::ClearNotify() { void SimpleTreeItem<T>::ClearNotify() {
if (children.count()) { if (children.count()) {
model->BeginDelete(static_cast<T*>(this), 0, children.count() - 1); model->BeginDelete(static_cast<T*>(this), 0, children.count() - 1);
@ -133,17 +133,17 @@ void SimpleTreeItem<T>::ClearNotify() {
} }
} }
template <typename T> template<typename T>
void SimpleTreeItem<T>::ChangedNotify() { void SimpleTreeItem<T>::ChangedNotify() {
model->EmitDataChanged(static_cast<T*>(this)); model->EmitDataChanged(static_cast<T*>(this));
} }
template <typename T> template<typename T>
SimpleTreeItem<T>::~SimpleTreeItem() { SimpleTreeItem<T>::~SimpleTreeItem() {
qDeleteAll(children); qDeleteAll(children);
} }
template <typename T> template<typename T>
void SimpleTreeItem<T>::Delete(int child_row) { void SimpleTreeItem<T>::Delete(int child_row) {
delete children.takeAt(child_row); delete children.takeAt(child_row);
@ -151,7 +151,7 @@ void SimpleTreeItem<T>::Delete(int child_row) {
for (int i = child_row; i < children.count(); ++i) children[i]->row--; for (int i = child_row; i < children.count(); ++i) children[i]->row--;
} }
template <typename T> template<typename T>
T *SimpleTreeItem<T>::ChildByKey(const QString &_key) const { T *SimpleTreeItem<T>::ChildByKey(const QString &_key) const {
for (T *child : children) { for (T *child : children) {
if (child->key == _key) return child; if (child->key == _key) return child;

View File

@ -27,7 +27,7 @@
#include <QObject> #include <QObject>
#include <QAbstractItemModel> #include <QAbstractItemModel>
template <typename T> template<typename T>
class SimpleTreeModel : public QAbstractItemModel { class SimpleTreeModel : public QAbstractItemModel {
public: public:
explicit SimpleTreeModel(T *root = nullptr, QObject *parent = nullptr); explicit SimpleTreeModel(T *root = nullptr, QObject *parent = nullptr);
@ -59,17 +59,17 @@ class SimpleTreeModel : public QAbstractItemModel {
T *root_; T *root_;
}; };
template <typename T> template<typename T>
SimpleTreeModel<T>::SimpleTreeModel(T *root, QObject *parent) SimpleTreeModel<T>::SimpleTreeModel(T *root, QObject *parent)
: QAbstractItemModel(parent), root_(root) {} : QAbstractItemModel(parent), root_(root) {}
template <typename T> template<typename T>
T *SimpleTreeModel<T>::IndexToItem(const QModelIndex &idx) const { T *SimpleTreeModel<T>::IndexToItem(const QModelIndex &idx) const {
if (!idx.isValid()) return root_; if (!idx.isValid()) return root_;
return reinterpret_cast<T*>(idx.internalPointer()); return reinterpret_cast<T*>(idx.internalPointer());
} }
template <typename T> template<typename T>
QModelIndex SimpleTreeModel<T>::ItemToIndex(T *item) const { QModelIndex SimpleTreeModel<T>::ItemToIndex(T *item) const {
if (!item || !item->parent) return QModelIndex(); if (!item || !item->parent) return QModelIndex();
return createIndex(item->row, 0, item); return createIndex(item->row, 0, item);
@ -80,7 +80,7 @@ int SimpleTreeModel<T>::columnCount(const QModelIndex&) const {
return 1; return 1;
} }
template <typename T> template<typename T>
QModelIndex SimpleTreeModel<T>::index(int row, int, const QModelIndex &parent) const { QModelIndex SimpleTreeModel<T>::index(int row, int, const QModelIndex &parent) const {
T *parent_item = IndexToItem(parent); T *parent_item = IndexToItem(parent);
@ -88,21 +88,20 @@ QModelIndex SimpleTreeModel<T>::index(int row, int, const QModelIndex &parent) c
return QModelIndex(); return QModelIndex();
return ItemToIndex(parent_item->children[row]); return ItemToIndex(parent_item->children[row]);
} }
template <typename T> template<typename T>
QModelIndex SimpleTreeModel<T>::parent(const QModelIndex &idx) const { QModelIndex SimpleTreeModel<T>::parent(const QModelIndex &idx) const {
return ItemToIndex(IndexToItem(idx)->parent); return ItemToIndex(IndexToItem(idx)->parent);
} }
template <typename T> template<typename T>
int SimpleTreeModel<T>::rowCount(const QModelIndex &parent) const { int SimpleTreeModel<T>::rowCount(const QModelIndex &parent) const {
T *item = IndexToItem(parent); T *item = IndexToItem(parent);
return item->children.count(); return item->children.count();
} }
template <typename T> template<typename T>
bool SimpleTreeModel<T>::hasChildren(const QModelIndex &parent) const { bool SimpleTreeModel<T>::hasChildren(const QModelIndex &parent) const {
T *item = IndexToItem(parent); T *item = IndexToItem(parent);
if (item->lazy_loaded) if (item->lazy_loaded)
@ -111,13 +110,13 @@ bool SimpleTreeModel<T>::hasChildren(const QModelIndex &parent) const {
return true; return true;
} }
template <typename T> template<typename T>
bool SimpleTreeModel<T>::canFetchMore(const QModelIndex &parent) const { bool SimpleTreeModel<T>::canFetchMore(const QModelIndex &parent) const {
T *item = IndexToItem(parent); T *item = IndexToItem(parent);
return !item->lazy_loaded; return !item->lazy_loaded;
} }
template <typename T> template<typename T>
void SimpleTreeModel<T>::fetchMore(const QModelIndex &parent) { void SimpleTreeModel<T>::fetchMore(const QModelIndex &parent) {
T *item = IndexToItem(parent); T *item = IndexToItem(parent);
if (!item->lazy_loaded) { if (!item->lazy_loaded) {
@ -125,29 +124,29 @@ void SimpleTreeModel<T>::fetchMore(const QModelIndex &parent) {
} }
} }
template <typename T> template<typename T>
void SimpleTreeModel<T>::BeginInsert(T *parent, int start, int end) { void SimpleTreeModel<T>::BeginInsert(T *parent, int start, int end) {
if (end == -1) end = start; if (end == -1) end = start;
beginInsertRows(ItemToIndex(parent), start, end); beginInsertRows(ItemToIndex(parent), start, end);
} }
template <typename T> template<typename T>
void SimpleTreeModel<T>::EndInsert() { void SimpleTreeModel<T>::EndInsert() {
endInsertRows(); endInsertRows();
} }
template <typename T> template<typename T>
void SimpleTreeModel<T>::BeginDelete(T *parent, int start, int end) { void SimpleTreeModel<T>::BeginDelete(T *parent, int start, int end) {
if (end == -1) end = start; if (end == -1) end = start;
beginRemoveRows(ItemToIndex(parent), start, end); beginRemoveRows(ItemToIndex(parent), start, end);
} }
template <typename T> template<typename T>
void SimpleTreeModel<T>::EndDelete() { void SimpleTreeModel<T>::EndDelete() {
endRemoveRows(); endRemoveRows();
} }
template <typename T> template<typename T>
void SimpleTreeModel<T>::EmitDataChanged(T *item) { void SimpleTreeModel<T>::EmitDataChanged(T *item) {
QModelIndex index(ItemToIndex(item)); QModelIndex index(ItemToIndex(item));
emit dataChanged(index, index); emit dataChanged(index, index);

View File

@ -178,7 +178,7 @@ struct Song::Private : public QSharedData {
int year_; int year_;
int originalyear_; int originalyear_;
QString genre_; QString genre_;
bool compilation_; // From the file tag bool compilation_; // From the file tag
QString composer_; QString composer_;
QString performer_; QString performer_;
QString grouping_; QString grouping_;
@ -1117,7 +1117,7 @@ void Song::ToItdb(Itdb_Track *track) const {
track->type1 = (d->filetype_ == FileType_MPEG ? 1 : 0); track->type1 = (d->filetype_ == FileType_MPEG ? 1 : 0);
track->type2 = (d->filetype_ == FileType_MPEG ? 1 : 0); track->type2 = (d->filetype_ == FileType_MPEG ? 1 : 0);
track->mediatype = 1; // Audio track->mediatype = 1; // Audio
track->size = static_cast<uint>(d->filesize_); track->size = static_cast<uint>(d->filesize_);
track->time_modified = d->mtime_; track->time_modified = d->mtime_;
track->time_added = d->ctime_; track->time_added = d->ctime_;

View File

@ -367,7 +367,7 @@ QPixmap StyleHelper::disabledSideBarIcon(const QPixmap &enabledicon) {
for (int y = 0; y < im.height(); ++y) { for (int y = 0; y < im.height(); ++y) {
auto scanLine = reinterpret_cast<QRgb*>(im.scanLine(y)); auto scanLine = reinterpret_cast<QRgb*>(im.scanLine(y));
for (int x=0; x<im.width(); ++x) { for (int x = 0; x < im.width(); ++x) {
QRgb pixel = *scanLine; QRgb pixel = *scanLine;
char intensity = static_cast<char>(qGray(pixel)); char intensity = static_cast<char>(qGray(pixel));
*scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel)); *scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel));
@ -390,34 +390,33 @@ void StyleHelper::drawCornerImage(const QImage &img, QPainter *painter, const QR
const qreal bottomDIP = bottom * imagePixelRatio; const qreal bottomDIP = bottom * imagePixelRatio;
const QSize size = img.size(); const QSize size = img.size();
if (top > 0) { //top if (top > 0) { //top
painter->drawImage(QRectF(rect.left() + left, rect.top(), rect.width() -right - left, top), img, QRectF(leftDIP, 0, size.width() - rightDIP - leftDIP, topDIP)); painter->drawImage(QRectF(rect.left() + left, rect.top(), rect.width() - right - left, top), img, QRectF(leftDIP, 0, size.width() - rightDIP - leftDIP, topDIP));
if (left > 0) { //top-left if (left > 0) { //top-left
painter->drawImage(QRectF(rect.left(), rect.top(), left, top), img, QRectF(0, 0, leftDIP, topDIP)); painter->drawImage(QRectF(rect.left(), rect.top(), left, top), img, QRectF(0, 0, leftDIP, topDIP));
} }
if (right > 0) { //top-right if (right > 0) { //top-right
painter->drawImage(QRectF(rect.left() + rect.width() - right, rect.top(), right, top), img, QRectF(size.width() - rightDIP, 0, rightDIP, topDIP)); painter->drawImage(QRectF(rect.left() + rect.width() - right, rect.top(), right, top), img, QRectF(size.width() - rightDIP, 0, rightDIP, topDIP));
} }
} }
//left //left
if (left > 0) { if (left > 0) {
painter->drawImage(QRectF(rect.left(), rect.top()+top, left, rect.height() - top - bottom), img, QRectF(0, topDIP, leftDIP, size.height() - bottomDIP - topDIP)); painter->drawImage(QRectF(rect.left(), rect.top() + top, left, rect.height() - top - bottom), img, QRectF(0, topDIP, leftDIP, size.height() - bottomDIP - topDIP));
} }
//center //center
painter->drawImage(QRectF(rect.left() + left, rect.top()+top, rect.width() -right - left, rect.height() - bottom - top), img, QRectF(leftDIP, topDIP, size.width() - rightDIP - leftDIP, size.height() - bottomDIP - topDIP)); painter->drawImage(QRectF(rect.left() + left, rect.top() + top, rect.width() - right - left, rect.height() - bottom - top), img, QRectF(leftDIP, topDIP, size.width() - rightDIP - leftDIP, size.height() - bottomDIP - topDIP));
if (right > 0) { //right if (right > 0) { //right
painter->drawImage(QRectF(rect.left() +rect.width() - right, rect.top()+top, right, rect.height() - top - bottom), img, QRectF(size.width() - rightDIP, topDIP, rightDIP, size.height() - bottomDIP - topDIP)); painter->drawImage(QRectF(rect.left() + rect.width() - right, rect.top() + top, right, rect.height() - top - bottom), img, QRectF(size.width() - rightDIP, topDIP, rightDIP, size.height() - bottomDIP - topDIP));
} }
if (bottom > 0) { //bottom if (bottom > 0) { //bottom
painter->drawImage(QRectF(rect.left() +left, rect.top() + rect.height() - bottom, rect.width() - right - left, bottom), img, QRectF(leftDIP, size.height() - bottomDIP, size.width() - rightDIP - leftDIP, bottomDIP)); painter->drawImage(QRectF(rect.left() + left, rect.top() + rect.height() - bottom, rect.width() - right - left, bottom), img, QRectF(leftDIP, size.height() - bottomDIP, size.width() - rightDIP - leftDIP, bottomDIP));
if (left > 0) { //bottom-left if (left > 0) { //bottom-left
painter->drawImage(QRectF(rect.left(), rect.top() + rect.height() - bottom, left, bottom), img, QRectF(0, size.height() - bottomDIP, leftDIP, bottomDIP)); painter->drawImage(QRectF(rect.left(), rect.top() + rect.height() - bottom, left, bottom), img, QRectF(0, size.height() - bottomDIP, leftDIP, bottomDIP));
} }
if (right > 0) { //bottom-right if (right > 0) { //bottom-right
painter->drawImage(QRectF(rect.left() + rect.width() - right, rect.top() + rect.height() - bottom, right, bottom), img, QRectF(size.width() - rightDIP, size.height() - bottomDIP, rightDIP, bottomDIP)); painter->drawImage(QRectF(rect.left() + rect.width() - right, rect.top() + rect.height() - bottom, right, bottom), img, QRectF(size.width() - rightDIP, size.height() - bottomDIP, rightDIP, bottomDIP));
} }
} }
} }
// Tints an image with tintColor, while preserving alpha and lightness // Tints an image with tintColor, while preserving alpha and lightness
@ -485,7 +484,6 @@ QList<int> StyleHelper::availableImageResolutions(const QString &fileName) {
} }
} }
return result; return result;
} }
} // namespace Utils } // namespace Utils

View File

@ -41,67 +41,66 @@ QT_END_NAMESPACE
// Helper class holding all custom color values // Helper class holding all custom color values
namespace Utils { namespace Utils {
class StyleHelper class StyleHelper {
{ public:
public: static const unsigned int DEFAULT_BASE_COLOR = 0x666666;
static const unsigned int DEFAULT_BASE_COLOR = 0x666666; static const int progressFadeAnimationDuration = 600;
static const int progressFadeAnimationDuration = 600;
// Height of the project explorer navigation bar // Height of the project explorer navigation bar
static int navigationWidgetHeight() { return 24; } static int navigationWidgetHeight() { return 24; }
static qreal sidebarFontSize(); static qreal sidebarFontSize();
static QPalette sidebarFontPalette(const QPalette &original); static QPalette sidebarFontPalette(const QPalette &original);
// This is our color table, all colors derive from baseColor // This is our color table, all colors derive from baseColor
static QColor requestedBaseColor() { return m_requestedBaseColor; } static QColor requestedBaseColor() { return m_requestedBaseColor; }
static QColor baseColor(bool lightColored = false); static QColor baseColor(bool lightColored = false);
static QColor panelTextColor(bool lightColored = false); static QColor panelTextColor(bool lightColored = false);
static QColor highlightColor(bool lightColored = false); static QColor highlightColor(bool lightColored = false);
static QColor shadowColor(bool lightColored = false); static QColor shadowColor(bool lightColored = false);
static QColor borderColor(bool lightColored = false); static QColor borderColor(bool lightColored = false);
static QColor toolBarBorderColor(); static QColor toolBarBorderColor();
static QColor buttonTextColor() { return QColor(0x4c4c4c); } static QColor buttonTextColor() { return QColor(0x4c4c4c); }
static QColor mergedColors(const QColor &colorA, const QColor &colorB, int factor = 50); static QColor mergedColors(const QColor &colorA, const QColor &colorB, int factor = 50);
static QColor alphaBlendedColors(const QColor &colorA, const QColor &colorB); static QColor alphaBlendedColors(const QColor &colorA, const QColor &colorB);
static QColor sidebarHighlight() { return QColor(255, 255, 255, 40); } static QColor sidebarHighlight() { return QColor(255, 255, 255, 40); }
static QColor sidebarShadow() { return QColor(0, 0, 0, 40); } static QColor sidebarShadow() { return QColor(0, 0, 0, 40); }
static QColor toolBarDropShadowColor() { return QColor(0, 0, 0, 70); } static QColor toolBarDropShadowColor() { return QColor(0, 0, 0, 70); }
static QColor notTooBrightHighlightColor(); static QColor notTooBrightHighlightColor();
// Sets the base color and makes sure all top level widgets are updated // Sets the base color and makes sure all top level widgets are updated
static void setBaseColor(const QColor &color); static void setBaseColor(const QColor &color);
// Draws a shaded anti-aliased arrow // Draws a shaded anti-aliased arrow
static void drawArrow(QStyle::PrimitiveElement element, QPainter *painter, const QStyleOption *option); static void drawArrow(QStyle::PrimitiveElement element, QPainter *painter, const QStyleOption *option);
// Gradients used for panels // Gradients used for panels
static void horizontalGradient(QPainter *painter, const QRect spanRect, const QRect clipRect, bool lightColored = false); static void horizontalGradient(QPainter *painter, const QRect spanRect, const QRect clipRect, bool lightColored = false);
static void verticalGradient(QPainter *painter, const QRect spanRect, const QRect clipRect, bool lightColored = false); static void verticalGradient(QPainter *painter, const QRect spanRect, const QRect clipRect, bool lightColored = false);
static void menuGradient(QPainter *painter, const QRect spanRect, const QRect clipRect); static void menuGradient(QPainter *painter, const QRect spanRect, const QRect clipRect);
static bool usePixmapCache() { return true; } static bool usePixmapCache() { return true; }
static QPixmap disabledSideBarIcon(const QPixmap &enabledicon); static QPixmap disabledSideBarIcon(const QPixmap &enabledicon);
static void drawCornerImage(const QImage &img, QPainter *painter, const QRect rect, int left = 0, int top = 0, int right = 0, int bottom = 0); static void drawCornerImage(const QImage &img, QPainter *painter, const QRect rect, int left = 0, int top = 0, int right = 0, int bottom = 0);
static void tintImage(QImage &img, const QColor &tintColor); static void tintImage(QImage &img, const QColor &tintColor);
static QLinearGradient statusBarGradient(const QRect statusBarRect); static QLinearGradient statusBarGradient(const QRect statusBarRect);
static QString dpiSpecificImageFile(const QString &fileName); static QString dpiSpecificImageFile(const QString &fileName);
static QString imageFileWithResolution(const QString &fileName, int dpr); static QString imageFileWithResolution(const QString &fileName, int dpr);
static QList<int> availableImageResolutions(const QString &fileName); static QList<int> availableImageResolutions(const QString &fileName);
private: private:
static QColor m_baseColor; static QColor m_baseColor;
static QColor m_requestedBaseColor; static QColor m_requestedBaseColor;
static QColor m_IconsBaseColor; static QColor m_IconsBaseColor;
static QColor m_IconsDisabledColor; static QColor m_IconsDisabledColor;
static QColor m_ProgressBarTitleColor; static QColor m_ProgressBarTitleColor;
}; };
} // namespace Utils } // namespace Utils
using Utils::StyleHelper; using Utils::StyleHelper;
#endif // STYLEHELPER_H #endif // STYLEHELPER_H

View File

@ -37,7 +37,7 @@
class QThread; class QThread;
class Song; class Song;
template <typename HandlerType> class WorkerPool; template<typename HandlerType> class WorkerPool;
class TagReaderClient : public QObject { class TagReaderClient : public QObject {
Q_OBJECT Q_OBJECT
@ -58,8 +58,8 @@ class TagReaderClient : public QObject {
ReplyType *IsMediaFile(const QString &filename); ReplyType *IsMediaFile(const QString &filename);
ReplyType *LoadEmbeddedArt(const QString &filename); ReplyType *LoadEmbeddedArt(const QString &filename);
ReplyType *SaveEmbeddedArt(const QString &filename, const QByteArray &data); ReplyType *SaveEmbeddedArt(const QString &filename, const QByteArray &data);
ReplyType* UpdateSongPlaycount(const Song &metadata); ReplyType *UpdateSongPlaycount(const Song &metadata);
ReplyType* UpdateSongRating(const Song &metadata); ReplyType *UpdateSongRating(const Song &metadata);
// Convenience functions that call the above functions and wait for a response. // Convenience functions that call the above functions and wait for a response.
// These block the calling thread with a semaphore, and must NOT be called from the TagReaderClient's thread. // These block the calling thread with a semaphore, and must NOT be called from the TagReaderClient's thread.

View File

@ -376,11 +376,11 @@ void OpenInFileManager(const QString &path, const QUrl &url) {
QString cmd = setting.value("Exec").toString(); QString cmd = setting.value("Exec").toString();
if (cmd.isEmpty()) break; if (cmd.isEmpty()) break;
cmd = cmd.remove(QRegularExpression("[%][a-zA-Z]*( |$)", QRegularExpression::CaseInsensitiveOption)); cmd = cmd.remove(QRegularExpression("[%][a-zA-Z]*( |$)", QRegularExpression::CaseInsensitiveOption));
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) # if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
command_params = cmd.split(' ', Qt::SkipEmptyParts); command_params = cmd.split(' ', Qt::SkipEmptyParts);
#else # else
command_params = cmd.split(' ', QString::SkipEmptyParts); command_params = cmd.split(' ', QString::SkipEmptyParts);
#endif # endif
command = command_params.first(); command = command_params.first();
command_params.removeFirst(); command_params.removeFirst();
} }
@ -800,9 +800,9 @@ QString UnicodeToAscii(QString unicode) {
#else #else
#ifdef LC_ALL # ifdef LC_ALL
setlocale(LC_ALL, ""); setlocale(LC_ALL, "");
#endif # endif
iconv_t conv = iconv_open("ASCII//TRANSLIT", "UTF-8"); iconv_t conv = iconv_open("ASCII//TRANSLIT", "UTF-8");
if (conv == reinterpret_cast<iconv_t>(-1)) return unicode; if (conv == reinterpret_cast<iconv_t>(-1)) return unicode;
@ -830,8 +830,7 @@ QString UnicodeToAscii(QString unicode) {
return ret; return ret;
#endif // _MSC_VER #endif // _MSC_VER
} }
QString MacAddress() { QString MacAddress() {
@ -988,9 +987,9 @@ HRGN qt_RectToHRGN(const QRect &rc) {
HRGN toHRGN(const QRegion &region); HRGN toHRGN(const QRegion &region);
HRGN toHRGN(const QRegion &region) { HRGN toHRGN(const QRegion &region) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) # if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
return region.toHRGN(); return region.toHRGN();
#else # else
const int rect_count = region.rectCount(); const int rect_count = region.rectCount();
if (rect_count == 0) { if (rect_count == 0) {
@ -1009,13 +1008,12 @@ HRGN toHRGN(const QRegion &region) {
return resultRgn; return resultRgn;
#endif // Qt 6 # endif // Qt 6
} }
void enableBlurBehindWindow(QWindow *window, const QRegion &region) { void enableBlurBehindWindow(QWindow *window, const QRegion &region) {
DWM_BLURBEHIND dwmbb = {0, 0, nullptr, 0}; DWM_BLURBEHIND dwmbb = { 0, 0, nullptr, 0 };
dwmbb.dwFlags = DWM_BB_ENABLE; dwmbb.dwFlags = DWM_BB_ENABLE;
dwmbb.fEnable = TRUE; dwmbb.fEnable = TRUE;
HRGN rgn = nullptr; HRGN rgn = nullptr;

View File

@ -115,11 +115,11 @@ enum IoPriority {
IOPRIO_CLASS_BE, IOPRIO_CLASS_BE,
IOPRIO_CLASS_IDLE, IOPRIO_CLASS_IDLE,
}; };
enum { enum {
IOPRIO_WHO_PROCESS = 1, IOPRIO_WHO_PROCESS = 1,
IOPRIO_WHO_PGRP, IOPRIO_WHO_PGRP,
IOPRIO_WHO_USER, IOPRIO_WHO_USER,
}; };
static const int IOPRIO_CLASS_SHIFT = 13; static const int IOPRIO_CLASS_SHIFT = 13;
long SetThreadIOPriority(const IoPriority priority); long SetThreadIOPriority(const IoPriority priority);
@ -157,10 +157,10 @@ class ScopedWCharArray {
QString ToString() const { return QString::fromWCharArray(data_.get()); } QString ToString() const { return QString::fromWCharArray(data_.get()); }
wchar_t *get() const { return data_.get(); } wchar_t *get() const { return data_.get(); }
explicit operator wchar_t*() const { return get(); } explicit operator wchar_t *() const { return get(); }
qint64 characters() const { return chars_; } qint64 characters() const { return chars_; }
qint64 bytes() const { return (chars_ + 1) *sizeof(wchar_t); } qint64 bytes() const { return (chars_ + 1) * sizeof(wchar_t); }
private: private:
Q_DISABLE_COPY(ScopedWCharArray) Q_DISABLE_COPY(ScopedWCharArray)

View File

@ -30,7 +30,7 @@
#include <QtDebug> #include <QtDebug>
#ifndef _WIN32_WINNT #ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 # define _WIN32_WINNT 0x0600
#endif #endif
#include <windows.h> #include <windows.h>
@ -77,24 +77,23 @@ ITaskbarList3 *Windows7ThumbBar::CreateTaskbarList() {
ITaskbarList3 *taskbar_list = nullptr; ITaskbarList3 *taskbar_list = nullptr;
// Copied from win7 SDK shobjidl.h // Copied from win7 SDK shobjidl.h
static const GUID CLSID_ITaskbarList = { 0x56FDF344,0xFD6D,0x11d0,{0x95,0x8A,0x00,0x60,0x97,0xC9,0xA0,0x90}}; static const GUID CLSID_ITaskbarList = { 0x56FDF344, 0xFD6D, 0x11d0, { 0x95, 0x8A, 0x00, 0x60, 0x97, 0xC9, 0xA0, 0x90 } };
// Create the taskbar list // Create the taskbar list
HRESULT hr = CoCreateInstance(CLSID_ITaskbarList, nullptr, CLSCTX_ALL, IID_ITaskbarList3, reinterpret_cast<void**>(&taskbar_list)); HRESULT hr = CoCreateInstance(CLSID_ITaskbarList, nullptr, CLSCTX_ALL, IID_ITaskbarList3, reinterpret_cast<void**>(&taskbar_list));
if (hr != S_OK) { if (hr != S_OK) {
qLog(Warning) << "Error creating the ITaskbarList3 interface" << Qt::hex << DWORD (hr); qLog(Warning) << "Error creating the ITaskbarList3 interface" << Qt::hex << DWORD(hr);
return nullptr; return nullptr;
} }
hr = taskbar_list->HrInit(); hr = taskbar_list->HrInit();
if (hr != S_OK) { if (hr != S_OK) {
qLog(Warning) << "Error initializing taskbar list" << Qt::hex << DWORD (hr); qLog(Warning) << "Error initializing taskbar list" << Qt::hex << DWORD(hr);
taskbar_list->Release(); taskbar_list->Release();
return nullptr; return nullptr;
} }
return taskbar_list; return taskbar_list;
} }
void Windows7ThumbBar::SetupButton(const QAction *action, THUMBBUTTON *button) { void Windows7ThumbBar::SetupButton(const QAction *action, THUMBBUTTON *button) {
@ -145,7 +144,7 @@ void Windows7ThumbBar::HandleWinEvent(MSG *msg) {
qLog(Debug) << "Adding" << actions_.count() << "buttons"; qLog(Debug) << "Adding" << actions_.count() << "buttons";
HRESULT hr = taskbar_list->ThumbBarAddButtons(reinterpret_cast<HWND>(widget_->winId()), actions_.count(), buttons); HRESULT hr = taskbar_list->ThumbBarAddButtons(reinterpret_cast<HWND>(widget_->winId()), actions_.count(), buttons);
if (hr != S_OK) { if (hr != S_OK) {
qLog(Debug) << "Failed to add buttons" << Qt::hex << DWORD (hr); qLog(Debug) << "Failed to add buttons" << Qt::hex << DWORD(hr);
} }
for (int i = 0; i < actions_.count(); ++i) { for (int i = 0; i < actions_.count(); ++i) {
@ -188,12 +187,11 @@ void Windows7ThumbBar::ActionChanged() {
button->iId = i; button->iId = i;
SetupButton(action, button); SetupButton(action, button);
} }
HRESULT hr = taskbar_list->ThumbBarUpdateButtons(reinterpret_cast<HWND>(widget_->winId()), actions_.count(), buttons); HRESULT hr = taskbar_list->ThumbBarUpdateButtons(reinterpret_cast<HWND>(widget_->winId()), actions_.count(), buttons);
if (hr != S_OK) { if (hr != S_OK) {
qLog(Debug) << "Failed to update buttons" << Qt::hex << DWORD (hr); qLog(Debug) << "Failed to update buttons" << Qt::hex << DWORD(hr);
} }
for (int i = 0; i < actions_.count(); ++i) { for (int i = 0; i < actions_.count(); ++i) {

View File

@ -211,7 +211,7 @@ QUrl AlbumCoverChoiceController::LoadCoverFromFile(Song *song) {
if (QImage(cover_file).isNull()) return QUrl(); if (QImage(cover_file).isNull()) return QUrl();
switch(get_save_album_cover_type()) { switch (get_save_album_cover_type()) {
case CollectionSettingsPage::SaveCoverType_Embedded: case CollectionSettingsPage::SaveCoverType_Embedded:
if (song->save_embedded_cover_supported()) { if (song->save_embedded_cover_supported()) {
SaveCoverEmbeddedAutomatic(*song, cover_file); SaveCoverEmbeddedAutomatic(*song, cover_file);

View File

@ -673,7 +673,7 @@ void AlbumCoverLoader::SaveEmbeddedCover(const quint64 id, const QList<QUrl> &ur
} }
if (!file.open(QIODevice::ReadOnly)) { if (!file.open(QIODevice::ReadOnly)) {
qLog(Error) << "Failed to open cover file" << cover_filename << "for reading:" << file.errorString(); qLog(Error) << "Failed to open cover file" << cover_filename << "for reading:" << file.errorString();
emit SaveEmbeddedCoverAsyncFinished(id, false, false); emit SaveEmbeddedCoverAsyncFinished(id, false, false);
return; return;
} }

View File

@ -33,7 +33,7 @@ CoverSearchStatistics::CoverSearchStatistics()
chosen_width_(0), chosen_width_(0),
chosen_height_(0) {} chosen_height_(0) {}
CoverSearchStatistics &CoverSearchStatistics::operator +=(const CoverSearchStatistics &other) { CoverSearchStatistics &CoverSearchStatistics::operator+=(const CoverSearchStatistics &other) {
network_requests_made_ += other.network_requests_made_; network_requests_made_ += other.network_requests_made_;
bytes_transferred_ += other.bytes_transferred_; bytes_transferred_ += other.bytes_transferred_;

View File

@ -32,7 +32,7 @@ struct CoverSearchStatistics {
explicit CoverSearchStatistics(); explicit CoverSearchStatistics();
CoverSearchStatistics &operator +=(const CoverSearchStatistics &other); CoverSearchStatistics &operator+=(const CoverSearchStatistics &other);
quint64 network_requests_made_; quint64 network_requests_made_;
quint64 bytes_transferred_; quint64 bytes_transferred_;

View File

@ -383,7 +383,7 @@ void DiscogsCoverProvider::HandleReleaseReply(QNetworkReply *reply, const int se
continue; continue;
} }
QJsonObject obj_artist = value_artist.toObject(); QJsonObject obj_artist = value_artist.toObject();
if (!obj_artist.contains("name") ) { if (!obj_artist.contains("name")) {
Error("Invalid Json reply, artists array value object is missing name.", obj_artist); Error("Invalid Json reply, artists array value object is missing name.", obj_artist);
continue; continue;
} }

View File

@ -111,7 +111,10 @@ void SpotifyCoverProvider::Authenticate() {
bool success = false; bool success = false;
forever { forever {
server_->set_port(port); server_->set_port(port);
if (server_->Listen()) { success = true; break; } if (server_->Listen()) {
success = true;
break;
}
++port; ++port;
if (port > port_max) break; if (port > port_max) break;
} }

View File

@ -50,7 +50,9 @@ class TidalCoverProvider : public JsonCoverProvider {
void CancelSearch(const int id) override; void CancelSearch(const int id) override;
bool IsAuthenticated() const override { return service_ && service_->authenticated(); } bool IsAuthenticated() const override { return service_ && service_->authenticated(); }
void Deauthenticate() override { if (service_) service_->Logout(); } void Deauthenticate() override {
if (service_) service_->Logout();
}
private slots: private slots:
void HandleSearchReply(QNetworkReply *reply, const int id); void HandleSearchReply(QNetworkReply *reply, const int id);

View File

@ -156,7 +156,7 @@ void CddaSongLoader::LoadSongs() {
GstMessage *msg_tag = nullptr; GstMessage *msg_tag = nullptr;
while ((msg = gst_bus_timed_pop_filtered(GST_ELEMENT_BUS(pipeline), GST_SECOND, static_cast<GstMessageType>(GST_MESSAGE_TOC | GST_MESSAGE_TAG)))) { while ((msg = gst_bus_timed_pop_filtered(GST_ELEMENT_BUS(pipeline), GST_SECOND, static_cast<GstMessageType>(GST_MESSAGE_TOC | GST_MESSAGE_TAG)))) {
if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_TOC) { if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_TOC) {
if (msg_toc) gst_message_unref(msg_toc); // Shouldn't happen, but just in case if (msg_toc) gst_message_unref(msg_toc); // Shouldn't happen, but just in case
msg_toc = msg; msg_toc = msg;
} }
else if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_TAG) { else if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_TAG) {

View File

@ -141,7 +141,7 @@ class DeviceManager : public SimpleTreeModel<DeviceInfo> {
private: private:
void AddLister(DeviceLister *lister); void AddLister(DeviceLister *lister);
template <typename T> void AddDeviceClass(); template<typename T> void AddDeviceClass();
DeviceDatabaseBackend::Device InfoToDatabaseDevice(const DeviceInfo &info) const; DeviceDatabaseBackend::Device InfoToDatabaseDevice(const DeviceInfo &info) const;
@ -173,7 +173,7 @@ class DeviceManager : public SimpleTreeModel<DeviceInfo> {
}; };
template <typename T> template<typename T>
void DeviceManager::AddDeviceClass() { void DeviceManager::AddDeviceClass() {
QStringList schemes = T::url_schemes(); QStringList schemes = T::url_schemes();
QMetaObject obj = T::staticMetaObject; QMetaObject obj = T::staticMetaObject;

View File

@ -40,10 +40,10 @@
class DeviceLister; class DeviceLister;
FilesystemDevice::FilesystemDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent) FilesystemDevice::FilesystemDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent)
: FilesystemMusicStorage(url.toLocalFile()), : FilesystemMusicStorage(url.toLocalFile()),
ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time, parent), ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time, parent),
watcher_(new CollectionWatcher(Song::Source_Device)), watcher_(new CollectionWatcher(Song::Source_Device)),
watcher_thread_(new QThread(this)) { watcher_thread_(new QThread(this)) {
watcher_->moveToThread(watcher_thread_); watcher_->moveToThread(watcher_thread_);
watcher_thread_->start(QThread::IdlePriority); watcher_thread_->start(QThread::IdlePriority);

View File

@ -70,10 +70,9 @@ 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 != "udf" && filesystem_type != "smb" && filesystem_type != "cifs" && filesystem_type != "ssh" && filesystem_type != "isofs";
} }
template <typename T, typename F> template<typename T, typename F>
void OperationFinished(F f, GObject *object, GAsyncResult *result) { void OperationFinished(F f, GObject *object, GAsyncResult *result) {
T *obj = reinterpret_cast<T*>(object); T *obj = reinterpret_cast<T*>(object);

View File

@ -137,7 +137,7 @@ class GioLister : public DeviceLister {
QString FindUniqueIdByMount(GMount *mount) const; QString FindUniqueIdByMount(GMount *mount) const;
QString FindUniqueIdByVolume(GVolume *volume) const; QString FindUniqueIdByVolume(GVolume *volume) const;
template <typename T> template<typename T>
T LockAndGetDeviceInfo(const QString &id, T DeviceInfo::*field); T LockAndGetDeviceInfo(const QString &id, T DeviceInfo::*field);
private: private:
@ -148,7 +148,7 @@ class GioLister : public DeviceLister {
QMap<QString, DeviceInfo> devices_; QMap<QString, DeviceInfo> devices_;
}; };
template <typename T> template<typename T>
T GioLister::LockAndGetDeviceInfo(const QString &id, T DeviceInfo::*field) { T GioLister::LockAndGetDeviceInfo(const QString &id, T DeviceInfo::*field) {
QMutexLocker l(&mutex_); QMutexLocker l(&mutex_);
if (!devices_.contains(id)) return T(); if (!devices_.contains(id)) return T();

View File

@ -84,12 +84,12 @@ class MacOsDeviceLister : public DeviceLister {
private: private:
bool Init(); bool Init();
static void DiskAddedCallback(DADiskRef disk, void* context); static void DiskAddedCallback(DADiskRef disk, void *context);
static void DiskRemovedCallback(DADiskRef disk, void* context); static void DiskRemovedCallback(DADiskRef disk, void *context);
static void USBDeviceAddedCallback(void *refcon, io_iterator_t it); static void USBDeviceAddedCallback(void *refcon, io_iterator_t it);
static void USBDeviceRemovedCallback(void *refcon, io_iterator_t it); static void USBDeviceRemovedCallback(void *refcon, io_iterator_t it);
static void DiskUnmountCallback(DADiskRef disk, DADissenterRef dissenter, void* context); static void DiskUnmountCallback(DADiskRef disk, DADissenterRef dissenter, void *context);
void FoundMTPDevice(const MTPDevice &device, const QString &serial); void FoundMTPDevice(const MTPDevice &device, const QString &serial);
void RemovedMTPDevice(const QString &serial); void RemovedMTPDevice(const QString &serial);

View File

@ -44,7 +44,7 @@ Console::Console(Application *app, QWidget *parent) : QDialog(parent), ui_{}, ap
ui_.setupUi(this); ui_.setupUi(this);
setWindowFlags(windowFlags()|Qt::WindowMaximizeButtonHint); setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint);
QObject::connect(ui_.run, &QPushButton::clicked, this, &Console::RunQuery); QObject::connect(ui_.run, &QPushButton::clicked, this, &Console::RunQuery);

View File

@ -34,7 +34,7 @@
#include "devicefinder.h" #include "devicefinder.h"
#include "alsadevicefinder.h" #include "alsadevicefinder.h"
AlsaDeviceFinder::AlsaDeviceFinder() : DeviceFinder("alsa", { "alsa","alsasink" }) {} AlsaDeviceFinder::AlsaDeviceFinder() : DeviceFinder("alsa", { "alsa", "alsasink" }) {}
QList<DeviceFinder::Device> AlsaDeviceFinder::ListDevices() { QList<DeviceFinder::Device> AlsaDeviceFinder::ListDevices() {

View File

@ -33,7 +33,7 @@
#include "devicefinder.h" #include "devicefinder.h"
#include "alsapcmdevicefinder.h" #include "alsapcmdevicefinder.h"
AlsaPCMDeviceFinder::AlsaPCMDeviceFinder() : DeviceFinder("alsa", { "alsa","alsasink" }) {} AlsaPCMDeviceFinder::AlsaPCMDeviceFinder() : DeviceFinder("alsa", { "alsa", "alsasink" }) {}
QList<DeviceFinder::Device> AlsaPCMDeviceFinder::ListDevices() { QList<DeviceFinder::Device> AlsaPCMDeviceFinder::ListDevices() {

View File

@ -94,19 +94,17 @@ bool Engine::Base::Play(const QUrl &stream_url, const QUrl &original_url, const
} }
return Play(offset_nanosec); return Play(offset_nanosec);
} }
void Engine::Base::SetVolume(const uint value) { void Engine::Base::SetVolume(const uint value) {
volume_ = value; volume_ = value;
SetVolumeSW(MakeVolumeLogarithmic(value)); SetVolumeSW(MakeVolumeLogarithmic(value));
} }
uint Engine::Base::MakeVolumeLogarithmic(const uint volume) { uint Engine::Base::MakeVolumeLogarithmic(const uint volume) {
// We're using a logarithmic function to make the volume ramp more natural. // We're using a logarithmic function to make the volume ramp more natural.
return static_cast<uint>( 100 - 100.0 * std::log10( ( 100 - volume ) * 0.09 + 1.0 ) ); return static_cast<uint>(100 - 100.0 * std::log10((100 - volume) * 0.09 + 1.0));
} }
void Engine::Base::ReloadSettings() { void Engine::Base::ReloadSettings() {

View File

@ -865,7 +865,7 @@ void GstEngine::UpdateScope(const int chunk_length) {
// Make sure we don't go beyond the end of the buffer // Make sure we don't go beyond the end of the buffer
if (scope_chunk_ == scope_chunks_ - 1) { if (scope_chunk_ == scope_chunks_ - 1) {
bytes = qMin(static_cast<Engine::Scope::size_type>(map.size - (chunk_size * scope_chunk_)), scope_.size() * sizeof(sample_type)); bytes = qMin(static_cast<Engine::Scope::size_type>(map.size - (chunk_size * scope_chunk_)), scope_.size() * sizeof(sample_type));
} }
else { else {
bytes = qMin(static_cast<Engine::Scope::size_type>(chunk_size), scope_.size() * sizeof(sample_type)); bytes = qMin(static_cast<Engine::Scope::size_type>(chunk_size), scope_.size() * sizeof(sample_type));

View File

@ -564,7 +564,7 @@ bool GstEnginePipeline::InitAudioBin(QString &error) {
// Link all elements // Link all elements
GstElement *next = audioqueue_; // The next element to link from. GstElement *next = audioqueue_; // The next element to link from.
// Link replaygain elements if enabled. // Link replaygain elements if enabled.
if (rg_enabled_ && rgvolume && rglimiter && rgconverter) { if (rg_enabled_ && rgvolume && rglimiter && rgconverter) {
@ -645,7 +645,7 @@ bool GstEnginePipeline::InitAudioBin(QString &error) {
gst_caps_unref(caps); gst_caps_unref(caps);
} }
{ // Add probes and handlers. { // Add probes and handlers.
GstPad *pad = gst_element_get_static_pad(audioqueue_, "src"); GstPad *pad = gst_element_get_static_pad(audioqueue_, "src");
if (pad) { if (pad) {
gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_BUFFER, HandoffCallback, this, nullptr); gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_BUFFER, HandoffCallback, this, nullptr);
@ -894,7 +894,7 @@ GstPadProbeReturn GstEnginePipeline::HandoffCallback(GstPad *pad, GstPadProbeInf
int16_t *s16 = static_cast<int16_t*>(g_malloc(buf16_size)); int16_t *s16 = static_cast<int16_t*>(g_malloc(buf16_size));
memset(s16, 0, buf16_size); memset(s16, 0, buf16_size);
for (int i = 0; i < (samples * channels); ++i) { for (int i = 0; i < (samples * channels); ++i) {
s16[i] = *(reinterpret_cast<int16_t*>(s24+1)); s16[i] = *(reinterpret_cast<int16_t*>(s24 + 1));
s24 += 3; s24 += 3;
if (s24 >= s24e) break; if (s24 >= s24e) break;
} }
@ -919,7 +919,7 @@ GstPadProbeReturn GstEnginePipeline::HandoffCallback(GstPad *pad, GstPadProbeInf
memset(s16, 0, buf16_size); memset(s16, 0, buf16_size);
for (int i = 0; i < (samples * channels); ++i) { for (int i = 0; i < (samples * channels); ++i) {
char *s24 = reinterpret_cast<char*>(s32p); char *s24 = reinterpret_cast<char*>(s32p);
s16[i] = *(reinterpret_cast<int16_t*>(s24+1)); s16[i] = *(reinterpret_cast<int16_t*>(s24 + 1));
++s32p; ++s32p;
if (s32p > s32e) break; if (s32p > s32e) break;
} }

View File

@ -120,17 +120,17 @@ void GstStartup::SetEnvironment() {
QString gst_registry_filename; QString gst_registry_filename;
#ifdef USE_BUNDLE #ifdef USE_BUNDLE
#if defined(Q_OS_WIN32) || defined(Q_OS_MACOS) # if defined(Q_OS_WIN32) || defined(Q_OS_MACOS)
gio_module_path = bundle_path + "/gio-modules"; gio_module_path = bundle_path + "/gio-modules";
#endif # endif
#if defined(Q_OS_LINUX) || defined(Q_OS_MACOS) # if defined(Q_OS_LINUX) || defined(Q_OS_MACOS)
gst_plugin_scanner = bundle_path + "/gst-plugin-scanner"; gst_plugin_scanner = bundle_path + "/gst-plugin-scanner";
gst_plugin_path = bundle_path + "/gstreamer"; gst_plugin_path = bundle_path + "/gstreamer";
#endif # endif
#if defined(Q_OS_WIN32) # if defined(Q_OS_WIN32)
//gst_plugin_scanner = bundle_path + "/gst-plugin-scanner.exe"; //gst_plugin_scanner = bundle_path + "/gst-plugin-scanner.exe";
gst_plugin_path = bundle_path + "/gstreamer-plugins"; gst_plugin_path = bundle_path + "/gstreamer-plugins";
#endif # endif
#endif #endif
#if defined(Q_OS_WIN32) || defined(Q_OS_MACOS) #if defined(Q_OS_WIN32) || defined(Q_OS_MACOS)

View File

@ -34,7 +34,7 @@
namespace { namespace {
template <typename T> template<typename T>
std::unique_ptr<T> GetProperty(const AudioDeviceID &device_id, const AudioObjectPropertyAddress &address, UInt32 *size_bytes_out = nullptr) { std::unique_ptr<T> GetProperty(const AudioDeviceID &device_id, const AudioObjectPropertyAddress &address, UInt32 *size_bytes_out = nullptr) {
UInt32 size_bytes = 0; UInt32 size_bytes = 0;

View File

@ -34,7 +34,7 @@
#include "devicefinder.h" #include "devicefinder.h"
#include "pulsedevicefinder.h" #include "pulsedevicefinder.h"
PulseDeviceFinder::PulseDeviceFinder() : DeviceFinder( "pulseaudio", { "pulseaudio", "pulse", "pulsesink" }), mainloop_(nullptr), context_(nullptr) {} PulseDeviceFinder::PulseDeviceFinder() : DeviceFinder("pulseaudio", { "pulseaudio", "pulse", "pulsesink" }), mainloop_(nullptr), context_(nullptr) {}
bool PulseDeviceFinder::Initialize() { bool PulseDeviceFinder::Initialize() {
@ -97,17 +97,17 @@ retry:
} }
switch (pa_context_get_state(context_)) { switch (pa_context_get_state(context_)) {
case PA_CONTEXT_READY: case PA_CONTEXT_READY:
break; break;
case PA_CONTEXT_FAILED: case PA_CONTEXT_FAILED:
case PA_CONTEXT_TERMINATED: case PA_CONTEXT_TERMINATED:
// Maybe pulseaudio died. Try reconnecting. // Maybe pulseaudio died. Try reconnecting.
if (Reconnect()) { if (Reconnect()) {
goto retry; goto retry;
} }
return state.devices; return state.devices;
default: default:
return state.devices; return state.devices;
} }
pa_mainloop_iterate(mainloop_, true, nullptr); pa_mainloop_iterate(mainloop_, true, nullptr);

View File

@ -25,14 +25,14 @@
#include <vlc/vlc.h> #include <vlc/vlc.h>
template <typename T> template<typename T>
class VlcScopedRef { class VlcScopedRef {
public: public:
explicit VlcScopedRef(T *ptr); explicit VlcScopedRef(T *ptr);
~VlcScopedRef(); ~VlcScopedRef();
operator T*() const { return ptr_; } operator T *() const { return ptr_; }
operator bool () const { return ptr_; } operator bool() const { return ptr_; }
T *operator->() const { return ptr_; } T *operator->() const { return ptr_; }
private: private:
@ -49,23 +49,23 @@ class VlcScopedRef {
} }
#define VLCSCOPEDREF_DEFINE(type) VLCSCOPEDREF_DEFINE2(type, libvlc_##type##_release) #define VLCSCOPEDREF_DEFINE(type) VLCSCOPEDREF_DEFINE2(type, libvlc_##type##_release)
template <typename T> template<typename T>
void VlcScopedRef_Release(T *ptr); void VlcScopedRef_Release(T *ptr);
VLCSCOPEDREF_DEFINE2(instance, libvlc_release) VLCSCOPEDREF_DEFINE2(instance, libvlc_release)
VLCSCOPEDREF_DEFINE(media_player) VLCSCOPEDREF_DEFINE(media_player)
VLCSCOPEDREF_DEFINE(media) VLCSCOPEDREF_DEFINE(media)
template <> void VlcScopedRef_Release<char>(char *ptr) { free(ptr); } template<> void VlcScopedRef_Release<char>(char *ptr) { free(ptr); }
template <typename T> template<typename T>
VlcScopedRef<T>::VlcScopedRef(T *ptr) VlcScopedRef<T>::VlcScopedRef(T *ptr)
: ptr_(ptr) { : ptr_(ptr) {
} }
template <typename T> template<typename T>
VlcScopedRef<T>::~VlcScopedRef() { VlcScopedRef<T>::~VlcScopedRef() {
VlcScopedRef_Release(ptr_); VlcScopedRef_Release(ptr_);
} }
#endif // VLCSCOPEDREF_H #endif // VLCSCOPEDREF_H

View File

@ -384,11 +384,10 @@ bool Equalizer::Params::operator==(const Equalizer::Params &other) const {
if (gain[i] != other.gain[i]) return false; if (gain[i] != other.gain[i]) return false;
} }
return true; return true;
} }
bool Equalizer::Params::operator!=(const Equalizer::Params &other) const { bool Equalizer::Params::operator!=(const Equalizer::Params &other) const {
return ! (*this == other); return !(*this == other);
} }
QDataStream &operator<<(QDataStream &s, const Equalizer::Params &p) { QDataStream &operator<<(QDataStream &s, const Equalizer::Params &p) {

View File

@ -56,7 +56,7 @@ class Equalizer : public QDialog {
bool operator!=(const Params &other) const; bool operator!=(const Params &other) const;
int preamp; int preamp;
int gain[kBands]{}; int gain[kBands] {};
}; };
bool is_equalizer_enabled() const; bool is_equalizer_enabled() const;
@ -100,7 +100,7 @@ class Equalizer : public QDialog {
QString last_preset_; QString last_preset_;
EqualizerSlider *preamp_; EqualizerSlider *preamp_;
EqualizerSlider *gain_[kBands]{}; EqualizerSlider *gain_[kBands] {};
QMap<QString, Params> presets_; QMap<QString, Params> presets_;
}; };

View File

@ -39,11 +39,11 @@
#include <xcb/xproto.h> #include <xcb/xproto.h>
#if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) #if QT_VERSION < QT_VERSION_CHECK(6, 2, 0)
#if defined(HAVE_X11EXTRAS) # if defined(HAVE_X11EXTRAS)
# include <QX11Info> # include <QX11Info>
#elif defined(HAVE_QPA_QPLATFORMNATIVEINTERFACE_H) # elif defined(HAVE_QPA_QPLATFORMNATIVEINTERFACE_H)
# include <qpa/qplatformnativeinterface.h> # include <qpa/qplatformnativeinterface.h>
#endif # endif
#endif #endif
const QVector<quint32> GlobalShortcut::mask_modifiers_ = QVector<quint32>() << 0 << Mod2Mask << LockMask << (Mod2Mask | LockMask); const QVector<quint32> GlobalShortcut::mask_modifiers_ = QVector<quint32>() << 0 << Mod2Mask << LockMask << (Mod2Mask | LockMask);
@ -57,7 +57,7 @@ Display *X11Display() {
if (!qApp) return nullptr; if (!qApp) return nullptr;
if (QNativeInterface::QX11Application *x11_app = qApp->nativeInterface<QNativeInterface::QX11Application>()) { if (QNativeInterface::QX11Application *x11_app = qApp->nativeInterface<QNativeInterface::QX11Application>()) {
return x11_app->display(); return x11_app->display();
} }
return nullptr; return nullptr;

View File

@ -33,7 +33,7 @@ GlobalShortcutsBackend::GlobalShortcutsBackend(GlobalShortcutsManager *manager,
QString GlobalShortcutsBackend::name() const { QString GlobalShortcutsBackend::name() const {
switch(type_) { switch (type_) {
case Type_None: case Type_None:
return "None"; return "None";
case Type_KDE: case Type_KDE:

View File

@ -170,29 +170,25 @@ GlobalShortcutsManager::Shortcut GlobalShortcutsManager::AddShortcut(const QStri
bool GlobalShortcutsManager::IsKdeAvailable() { bool GlobalShortcutsManager::IsKdeAvailable() {
return GlobalShortcutsBackendKDE::IsKDEAvailable(); return GlobalShortcutsBackendKDE::IsKDEAvailable();
} }
bool GlobalShortcutsManager::IsGnomeAvailable() { bool GlobalShortcutsManager::IsGnomeAvailable() {
return GlobalShortcutsBackendGnome::IsGnomeAvailable(); return GlobalShortcutsBackendGnome::IsGnomeAvailable();
} }
bool GlobalShortcutsManager::IsMateAvailable() { bool GlobalShortcutsManager::IsMateAvailable() {
return GlobalShortcutsBackendMate::IsMateAvailable(); return GlobalShortcutsBackendMate::IsMateAvailable();
} }
# endif // defined(Q_OS_UNIX) && !defined(Q_OS_MACOS) && defined(HAVE_DBUS) #endif // defined(Q_OS_UNIX) && !defined(Q_OS_MACOS) && defined(HAVE_DBUS)
#ifdef HAVE_X11_GLOBALSHORTCUTS #ifdef HAVE_X11_GLOBALSHORTCUTS
bool GlobalShortcutsManager::IsX11Available() { bool GlobalShortcutsManager::IsX11Available() {
return GlobalShortcutsBackendX11::IsX11Available(); return GlobalShortcutsBackendX11::IsX11Available();
} }
#endif // HAVE_X11_GLOBALSHORTCUTS #endif // HAVE_X11_GLOBALSHORTCUTS

View File

@ -390,7 +390,7 @@ void InternetCollectionView::AddToPlaylistEnqueueNext() {
void InternetCollectionView::OpenInNewPlaylist() { void InternetCollectionView::OpenInNewPlaylist() {
QMimeData *q_mimedata = model()->mimeData(selectedIndexes()); QMimeData *q_mimedata = model()->mimeData(selectedIndexes());
if (MimeData* mimedata = qobject_cast<MimeData*>(q_mimedata)) { if (MimeData *mimedata = qobject_cast<MimeData*>(q_mimedata)) {
mimedata->open_in_new_playlist_ = true; mimedata->open_in_new_playlist_ = true;
} }
emit AddToPlaylistSignal(q_mimedata); emit AddToPlaylistSignal(q_mimedata);

View File

@ -39,11 +39,11 @@
#endif #endif
#ifdef Q_OS_WIN32 #ifdef Q_OS_WIN32
#ifndef _WIN32_WINNT # ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 # define _WIN32_WINNT 0x0600
#endif # endif
#include <windows.h> # include <windows.h>
#include <iostream> # include <iostream>
#endif // Q_OS_WIN32 #endif // Q_OS_WIN32
#include <QObject> #include <QObject>
@ -265,19 +265,19 @@ int main(int argc, char *argv[]) {
std::unique_ptr<Translations> translations(new Translations); std::unique_ptr<Translations> translations(new Translations);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) # if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
translations->LoadTranslation("qt", QLibraryInfo::path(QLibraryInfo::TranslationsPath), language); translations->LoadTranslation("qt", QLibraryInfo::path(QLibraryInfo::TranslationsPath), language);
#else # else
translations->LoadTranslation("qt", QLibraryInfo::location(QLibraryInfo::TranslationsPath), language); translations->LoadTranslation("qt", QLibraryInfo::location(QLibraryInfo::TranslationsPath), language);
#endif # endif
translations->LoadTranslation("strawberry", ":/translations", language); translations->LoadTranslation("strawberry", ":/translations", language);
translations->LoadTranslation("strawberry", TRANSLATIONS_DIR, language); translations->LoadTranslation("strawberry", TRANSLATIONS_DIR, language);
translations->LoadTranslation("strawberry", QCoreApplication::applicationDirPath(), language); translations->LoadTranslation("strawberry", QCoreApplication::applicationDirPath(), language);
translations->LoadTranslation("strawberry", QDir::currentPath(), language); translations->LoadTranslation("strawberry", QDir::currentPath(), language);
#ifdef HAVE_QTSPARKLE # ifdef HAVE_QTSPARKLE
//qtsparkle::LoadTranslations(language); //qtsparkle::LoadTranslations(language);
#endif # endif
#endif #endif

View File

@ -94,8 +94,8 @@ class Organize : public QObject {
private: private:
struct Task { struct Task {
explicit Task(const NewSongInfo &song_info = NewSongInfo()) explicit Task(const NewSongInfo &song_info = NewSongInfo())
: song_info_(song_info), : song_info_(song_info),
transcode_progress_(0.0) {} transcode_progress_(0.0) {}
NewSongInfo song_info_; NewSongInfo song_info_;
float transcode_progress_; float transcode_progress_;

View File

@ -88,7 +88,7 @@ OrganizeDialog::OrganizeDialog(TaskManager *task_manager, CollectionBackend *bac
ui_->setupUi(this); ui_->setupUi(this);
setWindowFlags(windowFlags()|Qt::WindowMaximizeButtonHint); setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint);
QPushButton *button_save = ui_->button_box->addButton("Save settings", QDialogButtonBox::ApplyRole); QPushButton *button_save = ui_->button_box->addButton("Save settings", QDialogButtonBox::ApplyRole);
QObject::connect(button_save, &QPushButton::clicked, this, &OrganizeDialog::SaveSettings); QObject::connect(button_save, &QPushButton::clicked, this, &OrganizeDialog::SaveSettings);

View File

@ -196,7 +196,7 @@ QString OrganizeFormat::ParseBlock(QString block, const Song &song, bool *any_em
// Find any blocks first // Find any blocks first
qint64 pos = 0; qint64 pos = 0;
QRegularExpressionMatch re_match; QRegularExpressionMatch re_match;
for (re_match = block_regexp.match(block, pos); re_match.hasMatch(); re_match = block_regexp.match(block, pos)) { for (re_match = block_regexp.match(block, pos); re_match.hasMatch(); re_match = block_regexp.match(block, pos)) {
pos = re_match.capturedStart(); pos = re_match.capturedStart();
// Recursively parse the block // Recursively parse the block
bool empty = false; bool empty = false;

View File

@ -305,8 +305,8 @@ void OSDBase::ShowMessage(const QString &summary, const QString &message, const
switch (behaviour_) { switch (behaviour_) {
case Native: case Native:
#ifdef Q_OS_WIN32 #ifdef Q_OS_WIN32
Q_UNUSED(icon) Q_UNUSED(icon)
// fallthrough // fallthrough
#else #else
if (image.isNull()) { if (image.isNull()) {
ShowMessageNative(summary, message, icon, QImage()); ShowMessageNative(summary, message, icon, QImage());
@ -318,7 +318,7 @@ void OSDBase::ShowMessage(const QString &summary, const QString &message, const
#endif #endif
case TrayPopup: case TrayPopup:
#ifdef Q_OS_MACOS #ifdef Q_OS_MACOS
// fallthrough // fallthrough
#else #else
if (tray_icon_) tray_icon_->ShowPopup(summary, message, timeout_msec_); if (tray_icon_) tray_icon_->ShowPopup(summary, message, timeout_msec_);
break; break;
@ -401,7 +401,7 @@ QString OSDBase::ReplaceMessage(const MessageType type, const QString &message,
} }
break; break;
#elif defined(Q_OS_WIN32) #elif defined(Q_OS_WIN32)
// fallthrough // fallthrough
#else #else
// Other OSes doesn't support native notifications. // Other OSes doesn't support native notifications.
qLog(Debug) << "Native notifications are not supported on this OS."; qLog(Debug) << "Native notifications are not supported on this OS.";

View File

@ -108,9 +108,9 @@ OSDPretty::OSDPretty(Mode mode, QWidget *parent)
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
// Don't show the window in the taskbar. Qt::ToolTip does this too, but it adds an extra ugly shadow. // Don't show the window in the taskbar. Qt::ToolTip does this too, but it adds an extra ugly shadow.
int ex_style = GetWindowLong((HWND) winId(), GWL_EXSTYLE); int ex_style = GetWindowLong((HWND)winId(), GWL_EXSTYLE);
ex_style |= WS_EX_NOACTIVATE; ex_style |= WS_EX_NOACTIVATE;
SetWindowLong((HWND) winId(), GWL_EXSTYLE, ex_style); SetWindowLong((HWND)winId(), GWL_EXSTYLE, ex_style);
#endif #endif
// Mode settings // Mode settings
@ -166,7 +166,7 @@ OSDPretty::~OSDPretty() {
void OSDPretty::showEvent(QShowEvent *e) { void OSDPretty::showEvent(QShowEvent *e) {
screens_.clear(); screens_.clear();
for(QScreen *screen : QGuiApplication::screens()) { for (QScreen *screen : QGuiApplication::screens()) {
screens_.insert(screen->name(), screen); screens_.insert(screen->name(), screen);
} }
@ -310,10 +310,10 @@ void OSDPretty::paintEvent(QPaintEvent*) {
p.drawPixmap(0, height() - kShadowCornerSize, shadow_corner_[3]); p.drawPixmap(0, height() - kShadowCornerSize, shadow_corner_[3]);
// Shadow edges // Shadow edges
p.drawTiledPixmap(kShadowCornerSize, 0, width() - kShadowCornerSize*2, kDropShadowSize, shadow_edge_[0]); p.drawTiledPixmap(kShadowCornerSize, 0, width() - kShadowCornerSize * 2, kDropShadowSize, shadow_edge_[0]);
p.drawTiledPixmap(width() - kDropShadowSize, kShadowCornerSize, kDropShadowSize, height() - kShadowCornerSize*2, shadow_edge_[1]); p.drawTiledPixmap(width() - kDropShadowSize, kShadowCornerSize, kDropShadowSize, height() - kShadowCornerSize * 2, shadow_edge_[1]);
p.drawTiledPixmap(kShadowCornerSize, height() - kDropShadowSize, width() - kShadowCornerSize*2, kDropShadowSize, shadow_edge_[2]); p.drawTiledPixmap(kShadowCornerSize, height() - kDropShadowSize, width() - kShadowCornerSize * 2, kDropShadowSize, shadow_edge_[2]);
p.drawTiledPixmap(0, kShadowCornerSize, kDropShadowSize, height() - kShadowCornerSize*2, shadow_edge_[3]); p.drawTiledPixmap(0, kShadowCornerSize, kDropShadowSize, height() - kShadowCornerSize * 2, shadow_edge_[3]);
// Box background // Box background
p.setBrush(background_color_); p.setBrush(background_color_);

View File

@ -177,7 +177,7 @@ Playlist::~Playlist() {
collection_items_by_id_.clear(); collection_items_by_id_.clear();
} }
template <typename T> template<typename T>
void Playlist::InsertSongItems(const SongList &songs, const int pos, const bool play_now, const bool enqueue, const bool enqueue_next) { void Playlist::InsertSongItems(const SongList &songs, const int pos, const bool play_now, const bool enqueue, const bool enqueue_next) {
PlaylistItemList items; PlaylistItemList items;
@ -1189,7 +1189,7 @@ void Playlist::UpdateItems(SongList songs) {
// then we remove song from our list because we will not need to check it again. // then we remove song from our list because we will not need to check it again.
// And we also update undo actions. // And we also update undo actions.
for (int i = 0; i < items_.size(); i++) { for (int i = 0; i < items_.size(); i++) {
// Update current items list // Update current items list
QMutableListIterator<Song> it(songs); QMutableListIterator<Song> it(songs);
while (it.hasNext()) { while (it.hasNext()) {
@ -2168,13 +2168,12 @@ void Playlist::RemoveDeletedSongs() {
} }
removeRows(rows_to_remove); removeRows(rows_to_remove);
} }
namespace { namespace {
struct SongSimilarHash { struct SongSimilarHash {
size_t operator() (const Song &song) const { size_t operator()(const Song &song) const {
return HashSimilar(song); return HashSimilar(song);
} }
}; };

View File

@ -357,7 +357,7 @@ class Playlist : public QAbstractListModel {
int PreviousVirtualIndex(int i, const bool ignore_repeat_track) const; int PreviousVirtualIndex(int i, const bool ignore_repeat_track) const;
bool FilterContainsVirtualIndex(const int i) const; bool FilterContainsVirtualIndex(const int i) const;
template <typename T> template<typename T>
void InsertSongItems(const SongList &songs, const int pos, const bool play_now, const bool enqueue, const bool enqueue_next = false); void InsertSongItems(const SongList &songs, const int pos, const bool play_now, const bool enqueue, const bool enqueue_next = false);
// Modify the playlist without changing the undo stack. These are used by our friends in PlaylistUndoCommands // Modify the playlist without changing the undo stack. These are used by our friends in PlaylistUndoCommands

View File

@ -26,7 +26,7 @@ class PlaylistListSortFilterModel : public QSortFilterProxyModel {
public: public:
explicit PlaylistListSortFilterModel(QObject *parent) explicit PlaylistListSortFilterModel(QObject *parent)
: QSortFilterProxyModel(parent) {} : QSortFilterProxyModel(parent) {}
bool lessThan(const QModelIndex &left, const QModelIndex &right) const override { bool lessThan(const QModelIndex &left, const QModelIndex &right) const override {
// Compare the display text first. // Compare the display text first.

View File

@ -428,7 +428,7 @@ void PlaylistTabBar::dropEvent(QDropEvent *e) {
if (drag_hover_tab_ == -1) { if (drag_hover_tab_ == -1) {
const MimeData *mime_data = qobject_cast<const MimeData*>(e->mimeData()); const MimeData *mime_data = qobject_cast<const MimeData*>(e->mimeData());
if(mime_data && !mime_data->name_for_new_playlist_.isEmpty()) { if (mime_data && !mime_data->name_for_new_playlist_.isEmpty()) {
manager_->New(mime_data->name_for_new_playlist_); manager_->New(mime_data->name_for_new_playlist_);
} }
else { else {

View File

@ -53,7 +53,7 @@ class WplParser : public XMLParser {
SongList Load(QIODevice *device, const QString &playlist_path, const QDir &dir, const bool collection_search = true) const override; SongList Load(QIODevice *device, const QString &playlist_path, const QDir &dir, const bool collection_search = true) const override;
void Save(const SongList &songs, QIODevice *device, const QDir &dir, Playlist::Path path_type = Playlist::Path_Automatic) const override; void Save(const SongList &songs, QIODevice *device, const QDir &dir, Playlist::Path path_type = Playlist::Path_Automatic) const override;
private: private:
void ParseSeq(const QDir &dir, QXmlStreamReader *reader, SongList *songs, const bool collection_search = true) const; void ParseSeq(const QDir &dir, QXmlStreamReader *reader, SongList *songs, const bool collection_search = true) const;
static void WriteMeta(const QString &name, const QString &content, QXmlStreamWriter *writer); static void WriteMeta(const QString &name, const QString &content, QXmlStreamWriter *writer);
}; };

View File

@ -707,7 +707,7 @@ void QobuzRequest::AlbumsFinishCheck(const QString &artist_id, const int limit,
// Get songs for all the albums. // Get songs for all the albums.
QHash<QString, Request> ::iterator it; QHash<QString, Request>::iterator it;
for (it = album_songs_requests_pending_.begin(); it != album_songs_requests_pending_.end(); ++it) { for (it = album_songs_requests_pending_.begin(); it != album_songs_requests_pending_.end(); ++it) {
Request request = it.value(); Request request = it.value();
AddAlbumSongsRequest(request.artist_id, request.album_id, request.album_artist, request.album); AddAlbumSongsRequest(request.artist_id, request.album_id, request.album_artist, request.album);

View File

@ -716,19 +716,17 @@ void QobuzService::SendSearch() {
search_request_->Search(search_id_, search_text_); search_request_->Search(search_id_, search_text_);
search_request_->Process(); search_request_->Process();
} }
void QobuzService::SearchResultsReceived(const int id, const SongMap &songs, const QString &error) { void QobuzService::SearchResultsReceived(const int id, const SongMap &songs, const QString &error) {
search_request_.reset(); search_request_.reset();
emit SearchResults(id, songs, error); emit SearchResults(id, songs, error);
} }
uint QobuzService::GetStreamURL(const QUrl &url, QString &error) { uint QobuzService::GetStreamURL(const QUrl &url, QString &error) {
if (app_id().isEmpty() || app_secret().isEmpty()) { // Don't check for login here, because we allow automatic login. if (app_id().isEmpty() || app_secret().isEmpty()) { // Don't check for login here, because we allow automatic login.
error = tr("Missing Qobuz app ID or secret."); error = tr("Missing Qobuz app ID or secret.");
return 0; return 0;
} }

View File

@ -46,7 +46,7 @@ class RadioServices : public QObject {
RadioService *ServiceBySource(const Song::Source source) const; RadioService *ServiceBySource(const Song::Source source) const;
template <typename T> template<typename T>
T *Service() { T *Service() {
return static_cast<T*>(ServiceBySource(T::source)); return static_cast<T*>(ServiceBySource(T::source));
} }

View File

@ -57,7 +57,7 @@ class AudioScrobbler : public QObject {
ScrobblerService *ServiceByName(const QString &name) const { return scrobbler_services_->ServiceByName(name); } ScrobblerService *ServiceByName(const QString &name) const { return scrobbler_services_->ServiceByName(name); }
template <typename T> template<typename T>
T *Service() { T *Service() {
return qobject_cast<T*>(ServiceByName(T::kName)); return qobject_cast<T*>(ServiceByName(T::kName));
} }

View File

@ -46,7 +46,7 @@ class ScrobblerServices : public QObject {
int NextId(); int NextId();
ScrobblerService *ServiceByName(const QString &name); ScrobblerService *ServiceByName(const QString &name);
template <typename T> template<typename T>
T *Service() { T *Service() {
return qobject_cast<T*>(ServiceByName(T::kName)); return qobject_cast<T*>(ServiceByName(T::kName));
} }

View File

@ -169,7 +169,7 @@ void ScrobblingAPI20::Authenticate(const bool https) {
messagebox.setTextFormat(Qt::RichText); messagebox.setTextFormat(Qt::RichText);
int result = messagebox.exec(); int result = messagebox.exec();
switch (result) { switch (result) {
case QMessageBox::Open:{ case QMessageBox::Open: {
bool openurl_result = QDesktopServices::openUrl(url); bool openurl_result = QDesktopServices::openUrl(url);
if (openurl_result) { if (openurl_result) {
break; break;
@ -178,22 +178,21 @@ void ScrobblingAPI20::Authenticate(const bool https) {
messagebox_error.setTextFormat(Qt::RichText); messagebox_error.setTextFormat(Qt::RichText);
messagebox_error.exec(); messagebox_error.exec();
} }
// fallthrough // fallthrough
case QMessageBox::Save: case QMessageBox::Save:
QApplication::clipboard()->setText(url.toString()); QApplication::clipboard()->setText(url.toString());
break; break;
case QMessageBox::Cancel: case QMessageBox::Cancel:
if (server_) { if (server_) {
server_->close(); server_->close();
server_->deleteLater(); server_->deleteLater();
server_ = nullptr; server_ = nullptr;
} }
emit AuthenticationComplete(false); emit AuthenticationComplete(false);
break; break;
default: default:
break; break;
} }
} }
void ScrobblingAPI20::RedirectArrived() { void ScrobblingAPI20::RedirectArrived() {
@ -533,12 +532,13 @@ void ScrobblingAPI20::Scrobble(const Song &song) {
if (app_->scrobbler()->IsOffline()) return; if (app_->scrobbler()->IsOffline()) return;
if (!IsAuthenticated()) { if (!IsAuthenticated()) {
if (app_->scrobbler()->ShowErrorDialog()) { emit ErrorMessage(tr("Scrobbler %1 is not authenticated!").arg(name_)); } if (app_->scrobbler()->ShowErrorDialog()) {
emit ErrorMessage(tr("Scrobbler %1 is not authenticated!").arg(name_));
}
return; return;
} }
StartSubmit(true); StartSubmit(true);
} }
void ScrobblingAPI20::StartSubmit(const bool initial) { void ScrobblingAPI20::StartSubmit(const bool initial) {
@ -1016,8 +1016,9 @@ void ScrobblingAPI20::Error(const QString &error, const QVariant &debug) {
qLog(Error) << name_ << error; qLog(Error) << name_ << error;
if (debug.isValid()) qLog(Debug) << debug; if (debug.isValid()) qLog(Debug) << debug;
if (app_->scrobbler()->ShowErrorDialog()) { emit ErrorMessage(tr("Scrobbler %1 error: %2").arg(name_, error)); } if (app_->scrobbler()->ShowErrorDialog()) {
emit ErrorMessage(tr("Scrobbler %1 error: %2").arg(name_, error));
}
} }
QString ScrobblingAPI20::ErrorString(const ScrobbleErrorCode error) { QString ScrobblingAPI20::ErrorString(const ScrobbleErrorCode error) {

View File

@ -76,11 +76,11 @@ CollectionSettingsPage::CollectionSettingsPage(SettingsDialog *dialog, QWidget *
setWindowIcon(IconLoader::Load("library-music")); setWindowIcon(IconLoader::Load("library-music"));
ui_->add->setIcon(IconLoader::Load("document-open-folder")); ui_->add->setIcon(IconLoader::Load("document-open-folder"));
ui_->combobox_cache_size->addItems({"KB", "MB"}); ui_->combobox_cache_size->addItems({ "KB", "MB" });
ui_->combobox_disk_cache_size->addItems({"KB", "MB", "GB"}); ui_->combobox_disk_cache_size->addItems({ "KB", "MB", "GB" });
ui_->combobox_iopriority->addItems({"Auto", "Realtime", "Best effort", "Idle"}); ui_->combobox_iopriority->addItems({ "Auto", "Realtime", "Best effort", "Idle" });
ui_->combobox_threadpriority->addItems({"Idle", "Lowest", "Low", "Normal"}); ui_->combobox_threadpriority->addItems({ "Idle", "Lowest", "Low", "Normal" });
QObject::connect(ui_->add, &QPushButton::clicked, this, &CollectionSettingsPage::Add); QObject::connect(ui_->add, &QPushButton::clicked, this, &CollectionSettingsPage::Add);
QObject::connect(ui_->remove, &QPushButton::clicked, this, &CollectionSettingsPage::Remove); QObject::connect(ui_->remove, &QPushButton::clicked, this, &CollectionSettingsPage::Remove);

View File

@ -71,7 +71,7 @@ class ContextSettingsPage : public SettingsPage {
private: private:
Ui_ContextSettingsPage *ui_; Ui_ContextSettingsPage *ui_;
QCheckBox *checkboxes_[ContextSettingsOrder::NELEMS]{}; QCheckBox *checkboxes_[ContextSettingsOrder::NELEMS] {};
}; };
#endif // CONTEXTSETTINGSPAGE_H #endif // CONTEXTSETTINGSPAGE_H

View File

@ -186,7 +186,7 @@ void GlobalShortcutsSettingsPage::Load() {
ui_->checkbox_mate->setChecked(s.value("use_mate", true).toBool()); ui_->checkbox_mate->setChecked(s.value("use_mate", true).toBool());
} }
#endif // defined(Q_OS_UNIX) && !defined(Q_OS_MACOS) && defined(HAVE_DBUS) #endif // defined(Q_OS_UNIX) && !defined(Q_OS_MACOS) && defined(HAVE_DBUS)
#ifdef HAVE_X11_GLOBALSHORTCUTS #ifdef HAVE_X11_GLOBALSHORTCUTS
if (ui_->widget_x11->isVisibleTo(this)) { if (ui_->widget_x11->isVisibleTo(this)) {

View File

@ -185,8 +185,8 @@ void NotificationsSettingsPage::Load() {
break; break;
} }
ui_->notifications_duration->setValue(s.value("Timeout", 5000).toInt() / 1000); ui_->notifications_duration->setValue(s.value("Timeout", 5000).toInt() / 1000);
ui_->notifications_volume->setChecked( s.value("ShowOnVolumeChange", false).toBool()); ui_->notifications_volume->setChecked(s.value("ShowOnVolumeChange", false).toBool());
ui_->notifications_play_mode->setChecked( s.value("ShowOnPlayModeChange", true).toBool()); ui_->notifications_play_mode->setChecked(s.value("ShowOnPlayModeChange", true).toBool());
ui_->notifications_pause->setChecked(s.value("ShowOnPausePlayback", true).toBool()); ui_->notifications_pause->setChecked(s.value("ShowOnPausePlayback", true).toBool());
ui_->notifications_resume->setChecked(s.value("ShowOnResumePlayback", false).toBool()); ui_->notifications_resume->setChecked(s.value("ShowOnResumePlayback", false).toBool());
ui_->notifications_art->setChecked(s.value("ShowArt", true).toBool()); ui_->notifications_art->setChecked(s.value("ShowArt", true).toBool());

View File

@ -85,7 +85,7 @@ void SubsonicSettingsPage::Load() {
ui_->checkbox_server_scrobbling->setChecked(s.value("serversidescrobbling", false).toBool()); ui_->checkbox_server_scrobbling->setChecked(s.value("serversidescrobbling", false).toBool());
AuthMethod auth_method = static_cast<AuthMethod>(s.value("authmethod", AuthMethod_MD5).toInt()); AuthMethod auth_method = static_cast<AuthMethod>(s.value("authmethod", AuthMethod_MD5).toInt());
switch(auth_method) { switch (auth_method) {
case AuthMethod_Hex: case AuthMethod_Hex:
ui_->auth_method_hex->setChecked(true); ui_->auth_method_hex->setChecked(true);
break; break;

View File

@ -247,16 +247,14 @@ void SmartPlaylistsViewContainer::DeleteSmartPlaylistFromButton() {
if (ui_->view->selectionModel()->selectedIndexes().count() == 0) return; if (ui_->view->selectionModel()->selectedIndexes().count() == 0) return;
DeleteSmartPlaylist(ui_->view->selectionModel()->selectedIndexes().first()); DeleteSmartPlaylist(ui_->view->selectionModel()->selectedIndexes().first());
} }
void SmartPlaylistsViewContainer::NewSmartPlaylistFinished() { void SmartPlaylistsViewContainer::NewSmartPlaylistFinished() {
SmartPlaylistWizard *wizard = qobject_cast<SmartPlaylistWizard*>(sender()); SmartPlaylistWizard *wizard = qobject_cast<SmartPlaylistWizard*>(sender());
if (!wizard) return; if (!wizard) return;
QObject::disconnect(wizard, &SmartPlaylistWizard::accepted, this, &SmartPlaylistsViewContainer::NewSmartPlaylistFinished); QObject::disconnect(wizard, &SmartPlaylistWizard::accepted, this, &SmartPlaylistsViewContainer::NewSmartPlaylistFinished);
model_->AddGenerator(wizard->CreateGenerator()); model_->AddGenerator(wizard->CreateGenerator());
} }
void SmartPlaylistsViewContainer::EditSmartPlaylistFinished() { void SmartPlaylistsViewContainer::EditSmartPlaylistFinished() {

View File

@ -59,7 +59,7 @@ class SubsonicRequest : public SubsonicBaseRequest {
void GetAlbums(); void GetAlbums();
void Reset(); void Reset();
private: private:
struct Request { struct Request {
explicit Request() : offset(0), size(0) {} explicit Request() : offset(0), size(0) {}
QString artist_id; QString artist_id;

View File

@ -92,7 +92,7 @@ TranscodeDialog::TranscodeDialog(QMainWindow *mainwindow, QWidget *parent)
ui_->setupUi(this); ui_->setupUi(this);
setWindowFlags(windowFlags()|Qt::WindowMaximizeButtonHint); setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint);
ui_->files->header()->setSectionResizeMode(QHeaderView::ResizeToContents); ui_->files->header()->setSectionResizeMode(QHeaderView::ResizeToContents);

View File

@ -38,16 +38,14 @@ BusyIndicator::BusyIndicator(const QString &text, QWidget *parent)
label_(nullptr) { label_(nullptr) {
Init(text); Init(text);
} }
BusyIndicator::BusyIndicator(QWidget *parent) BusyIndicator::BusyIndicator(QWidget *parent)
: QWidget(parent), : QWidget(parent),
movie_(nullptr), movie_(nullptr),
label_(nullptr) { label_(nullptr) {
Init(QString()); Init(QString());
} }
void BusyIndicator::Init(const QString &text) { void BusyIndicator::Init(const QString &text) {

View File

@ -22,7 +22,7 @@
#include <QWidget> #include <QWidget>
#include <QLabel> #include <QLabel>
ClickableLabel::ClickableLabel(QWidget *parent) : QLabel(parent){} ClickableLabel::ClickableLabel(QWidget *parent) : QLabel(parent) {}
void ClickableLabel::mousePressEvent(QMouseEvent *event) { void ClickableLabel::mousePressEvent(QMouseEvent *event) {
emit Clicked(); emit Clicked();

View File

@ -219,7 +219,7 @@ class FancyTabBar : public QTabBar { // clazy:exclude=missing-qobject-macro
if (tabWidget->mode() != FancyTabWidget::Mode_LargeSidebar && tabWidget->mode() != FancyTabWidget::Mode_SmallSidebar) { if (tabWidget->mode() != FancyTabWidget::Mode_LargeSidebar && tabWidget->mode() != FancyTabWidget::Mode_SmallSidebar) {
// Cache and hide label text for IconOnlyTabs mode // Cache and hide label text for IconOnlyTabs mode
if (tabWidget->mode() == FancyTabWidget::Mode_IconOnlyTabs && labelCache.count() == 0) { if (tabWidget->mode() == FancyTabWidget::Mode_IconOnlyTabs && labelCache.count() == 0) {
for(int i = 0; i < count(); ++i) { for (int i = 0; i < count(); ++i) {
labelCache[tabWidget->widget(i)] = tabText(i); labelCache[tabWidget->widget(i)] = tabText(i);
setTabToolTip(i, tabText(i)); setTabToolTip(i, tabText(i));
setTabText(i, ""); setTabText(i, "");
@ -315,7 +315,7 @@ class FancyTabBar : public QTabBar { // clazy:exclude=missing-qobject-macro
p.setFont(boldFont); p.setFont(boldFont);
// Text drop shadow color // Text drop shadow color
p.setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110) ); p.setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
p.translate(0, 3); p.translate(0, 3);
p.drawText(tabrectText, textFlags, tabText(index)); p.drawText(tabrectText, textFlags, tabText(index));
@ -338,7 +338,7 @@ class FancyTabBar : public QTabBar { // clazy:exclude=missing-qobject-macro
tabrectIcon = tabrectLabel; tabrectIcon = tabrectLabel;
tabrectIcon.setSize(QSize(tabWidget->iconsize_largesidebar(), tabWidget->iconsize_largesidebar())); tabrectIcon.setSize(QSize(tabWidget->iconsize_largesidebar(), tabWidget->iconsize_largesidebar()));
// Center the icon // Center the icon
const int moveRight = (QTabBar::width() - tabWidget->iconsize_largesidebar() -1) / 2; const int moveRight = (QTabBar::width() - tabWidget->iconsize_largesidebar() - 1) / 2;
tabrectIcon.translate(moveRight, 5); tabrectIcon.translate(moveRight, 5);
} }
tabIcon(index).paint(&p, tabrectIcon, iconFlags); tabIcon(index).paint(&p, tabrectIcon, iconFlags);
@ -346,18 +346,17 @@ class FancyTabBar : public QTabBar { // clazy:exclude=missing-qobject-macro
} }
} }
} }
}; };
class TabData : public QObject { // clazy:exclude=missing-qobject-macro class TabData : public QObject { // clazy:exclude=missing-qobject-macro
public: public:
TabData(QWidget *widget_view, const QString &name, const QIcon &icon, const QString &label, const int idx, QWidget *parent) TabData(QWidget *widget_view, const QString &name, const QIcon &icon, const QString &label, const int idx, QWidget *parent)
: QObject(parent), : QObject(parent),
widget_view_(widget_view), widget_view_(widget_view),
name_(name), icon_(icon), name_(name), icon_(icon),
label_(label), label_(label),
index_(idx), index_(idx),
page_(new QWidget()) { page_(new QWidget()) {
// In order to achieve the same effect as the "Bottom Widget" of the old Nokia based FancyTabWidget a VBoxLayout is used on each page // In order to achieve the same effect as the "Bottom Widget" of the old Nokia based FancyTabWidget a VBoxLayout is used on each page
QVBoxLayout *layout = new QVBoxLayout(page_); QVBoxLayout *layout = new QVBoxLayout(page_);
layout->setSpacing(0); layout->setSpacing(0);

View File

@ -72,7 +72,7 @@ class FancyTabWidget : public QTabWidget {
Mode_Tabs, Mode_Tabs,
Mode_IconOnlyTabs, Mode_IconOnlyTabs,
Mode_PlainSidebar, Mode_PlainSidebar,
}; };
static const int TabSize_LargeSidebarMinWidth; static const int TabSize_LargeSidebarMinWidth;
static const int IconSize_LargeSidebar; static const int IconSize_LargeSidebar;

View File

@ -212,7 +212,7 @@ void FreeSpaceBar::DrawText(QPainter *p, const QRect r) {
for (const Label &label : labels) { for (const Label &label : labels) {
const bool light = palette().color(QPalette::Base).value() > 128; const bool light = palette().color(QPalette::Base).value() > 128;
QRect box(x, r.top() + (r.height() - kLabelBoxSize)/2, kLabelBoxSize, kLabelBoxSize); QRect box(x, r.top() + (r.height() - kLabelBoxSize) / 2, kLabelBoxSize, kLabelBoxSize);
p->setPen(label.color.darker()); p->setPen(label.color.darker());
p->setBrush(label.color); p->setBrush(label.color);
p->drawRect(box); p->drawRect(box);

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