From 2e6123540353343d4ea24ce7742e8dfcf0a69180 Mon Sep 17 00:00:00 2001 From: Jonas Kvinge Date: Fri, 21 Jul 2023 05:55:24 +0200 Subject: [PATCH] Application: Use shared pointers Fixes #1239 --- src/CMakeLists.txt | 2 + src/analyzer/analyzerbase.cpp | 4 +- src/analyzer/analyzerbase.h | 5 +- src/analyzer/analyzercontainer.cpp | 3 +- src/analyzer/analyzercontainer.h | 5 +- src/collection/collection.cpp | 56 ++-- src/collection/collection.h | 10 +- src/collection/collectionbackend.cpp | 9 +- src/collection/collectionbackend.h | 14 +- src/collection/collectiondirectorymodel.cpp | 15 +- src/collection/collectiondirectorymodel.h | 11 +- src/collection/collectionmodel.cpp | 32 ++- src/collection/collectionmodel.h | 7 +- src/collection/collectiontask.cpp | 3 +- src/collection/collectiontask.h | 6 +- src/collection/collectionview.cpp | 12 +- src/collection/collectionview.h | 7 +- src/collection/collectionwatcher.cpp | 6 + src/collection/collectionwatcher.h | 10 +- src/collection/groupbydialog.cpp | 6 +- src/collection/groupbydialog.h | 7 +- src/context/contextalbum.cpp | 22 +- src/context/contextalbum.h | 13 +- src/core/application.cpp | 165 ++++++------ src/core/application.h | 49 ++-- src/core/deletefiles.cpp | 3 +- src/core/deletefiles.h | 9 +- src/core/lazy.h | 16 +- src/core/macsystemtrayicon.h | 5 +- src/core/mainwindow.cpp | 243 +++++++++--------- src/core/mainwindow.h | 14 +- src/core/mergedproxymodel.h | 5 +- src/core/mpris2.cpp | 16 +- src/core/musicstorage.h | 3 +- src/core/player.cpp | 36 +-- src/core/player.h | 15 +- src/core/scoped_ptr.h | 28 ++ src/core/scopedwchararray.h | 6 +- src/core/shared_ptr.h | 28 ++ src/core/songloader.cpp | 38 +-- src/core/songloader.h | 9 +- src/core/stylesheetloader.cpp | 7 +- src/core/stylesheetloader.h | 8 +- .../albumcoverchoicecontroller.cpp | 2 +- src/covermanager/albumcoverfetcher.cpp | 3 +- src/covermanager/albumcoverfetcher.h | 8 +- src/covermanager/albumcoverfetchersearch.cpp | 5 +- src/covermanager/albumcoverfetchersearch.h | 7 +- src/covermanager/albumcoverloader.cpp | 4 +- src/covermanager/albumcoverloader.h | 9 +- src/covermanager/albumcovermanager.cpp | 9 +- src/covermanager/albumcovermanager.h | 7 +- src/covermanager/albumcovermanagerlist.cpp | 7 +- src/covermanager/albumcoversearcher.cpp | 2 +- src/covermanager/coverfromurldialog.cpp | 3 +- src/covermanager/coverfromurldialog.h | 5 +- src/covermanager/coverprovider.cpp | 3 +- src/covermanager/coverprovider.h | 5 +- src/covermanager/currentalbumcoverloader.cpp | 10 +- src/covermanager/currentalbumcoverloader.h | 8 +- src/covermanager/deezercoverprovider.cpp | 2 +- src/covermanager/deezercoverprovider.h | 2 +- src/covermanager/discogscoverprovider.cpp | 17 +- src/covermanager/discogscoverprovider.h | 15 +- src/covermanager/jsoncoverprovider.cpp | 3 +- src/covermanager/jsoncoverprovider.h | 3 +- src/covermanager/lastfmcoverprovider.cpp | 3 +- src/covermanager/lastfmcoverprovider.h | 3 +- src/covermanager/musicbrainzcoverprovider.cpp | 3 +- src/covermanager/musicbrainzcoverprovider.h | 3 +- src/covermanager/musixmatchcoverprovider.cpp | 3 +- src/covermanager/musixmatchcoverprovider.h | 3 +- src/covermanager/qobuzcoverprovider.cpp | 3 +- src/covermanager/qobuzcoverprovider.h | 5 +- src/covermanager/spotifycoverprovider.cpp | 3 +- src/covermanager/spotifycoverprovider.h | 3 +- src/covermanager/tidalcoverprovider.cpp | 3 +- src/covermanager/tidalcoverprovider.h | 5 +- src/device/cddadevice.cpp | 3 +- src/device/cddadevice.h | 3 +- src/device/cddasongloader.cpp | 7 +- src/device/cddasongloader.h | 3 +- src/device/connecteddevice.cpp | 19 +- src/device/connecteddevice.h | 12 +- src/device/devicedatabasebackend.cpp | 3 +- src/device/devicedatabasebackend.h | 7 +- src/device/deviceinfo.h | 2 +- src/device/devicemanager.cpp | 59 ++--- src/device/devicemanager.h | 14 +- src/device/deviceproperties.cpp | 12 +- src/device/deviceproperties.h | 7 +- src/device/deviceview.cpp | 19 +- src/device/deviceview.h | 7 +- src/device/filesystemdevice.cpp | 33 +-- src/device/filesystemdevice.h | 3 +- src/device/gpoddevice.cpp | 7 +- src/device/gpoddevice.h | 7 +- src/device/gpodloader.cpp | 3 +- src/device/gpodloader.h | 10 +- src/device/mtpconnection.h | 4 +- src/device/mtpdevice.cpp | 3 +- src/device/mtpdevice.h | 9 +- src/device/mtploader.cpp | 12 +- src/device/mtploader.h | 13 +- src/device/udisks2lister.cpp | 15 +- src/device/udisks2lister.h | 9 +- src/dialogs/edittagdialog.cpp | 2 +- src/dialogs/lastfmimportdialog.cpp | 3 +- src/dialogs/lastfmimportdialog.h | 6 +- src/engine/ebur128analysis.cpp | 6 +- src/engine/gstengine.cpp | 45 ++-- src/engine/gstengine.h | 16 +- src/engine/gstenginepipeline.cpp | 5 +- src/engine/gstenginepipeline.h | 4 +- src/engine/vlcengine.cpp | 3 +- src/engine/vlcengine.h | 4 +- .../globalshortcutsbackend-macos.h | 6 +- src/internet/internetcollectionview.cpp | 7 +- src/internet/internetcollectionview.h | 5 +- src/internet/internetplaylistitem.cpp | 2 +- src/internet/internetplaylistitem.h | 3 +- src/internet/internetsearchmodel.cpp | 2 +- src/internet/internetsearchmodel.h | 5 +- src/internet/internetsearchview.cpp | 18 +- src/internet/internetsearchview.h | 10 +- src/internet/internetservice.h | 11 +- src/internet/internetservices.cpp | 23 +- src/internet/internetservices.h | 16 +- src/internet/internetsongmimedata.h | 5 +- src/internet/internetsongsview.cpp | 12 +- src/internet/internetsongsview.h | 5 +- src/internet/internettabsview.cpp | 38 +-- src/internet/internettabsview.h | 5 +- src/lyrics/chartlyricsprovider.cpp | 3 +- src/lyrics/chartlyricsprovider.h | 3 +- src/lyrics/geniuslyricsprovider.cpp | 7 +- src/lyrics/geniuslyricsprovider.h | 9 +- src/lyrics/jsonlyricsprovider.cpp | 3 +- src/lyrics/jsonlyricsprovider.h | 3 +- src/lyrics/lololyricsprovider.cpp | 3 +- src/lyrics/lololyricsprovider.h | 3 +- src/lyrics/lyricscomlyricsprovider.cpp | 3 +- src/lyrics/lyricscomlyricsprovider.h | 3 +- src/lyrics/lyricsfetcher.cpp | 3 +- src/lyrics/lyricsfetcher.h | 5 +- src/lyrics/lyricsfetchersearch.cpp | 3 +- src/lyrics/lyricsfetchersearch.h | 3 +- src/lyrics/lyricsprovider.cpp | 3 +- src/lyrics/lyricsprovider.h | 5 +- src/lyrics/musixmatchlyricsprovider.cpp | 7 +- src/lyrics/musixmatchlyricsprovider.h | 7 +- src/lyrics/ovhlyricsprovider.cpp | 3 +- src/lyrics/ovhlyricsprovider.h | 3 +- src/main.cpp | 14 +- src/moodbar/moodbarcontroller.cpp | 4 +- src/moodbar/moodbarloader.cpp | 5 +- src/moodbar/moodbarpipeline.cpp | 4 +- src/moodbar/moodbarpipeline.h | 6 +- src/musicbrainz/acoustidclient.cpp | 8 +- src/musicbrainz/acoustidclient.h | 6 +- src/musicbrainz/musicbrainzclient.cpp | 3 +- src/musicbrainz/musicbrainzclient.h | 8 +- src/musicbrainz/tagfetcher.cpp | 3 +- src/musicbrainz/tagfetcher.h | 3 +- src/organize/organize.cpp | 3 +- src/organize/organize.h | 8 +- src/organize/organizedialog.cpp | 21 +- src/organize/organizedialog.h | 12 +- src/osd/osdbase.cpp | 5 +- src/osd/osdbase.h | 7 +- src/osd/osddbus.cpp | 9 +- src/osd/osddbus.h | 7 +- src/osd/osdmac.h | 2 +- src/osd/osdmac.mm | 2 +- src/playlist/playlist.cpp | 66 ++--- src/playlist/playlist.h | 11 +- src/playlist/playlistbackend.cpp | 15 +- src/playlist/playlistbackend.h | 11 +- src/playlist/playlistcontainer.cpp | 25 +- src/playlist/playlistcontainer.h | 6 +- src/playlist/playlistdelegates.cpp | 6 +- src/playlist/playlistdelegates.h | 8 +- src/playlist/playlistitem.cpp | 18 +- src/playlist/playlistitem.h | 11 +- src/playlist/playlistlistcontainer.cpp | 8 +- src/playlist/playlistlistcontainer.h | 6 +- src/playlist/playlistmanager.cpp | 17 +- src/playlist/playlistmanager.h | 15 +- src/playlist/playlistsequence.h | 6 +- src/playlist/playlisttabbar.cpp | 9 +- src/playlist/playlisttabbar.h | 6 +- src/playlist/playlistview.cpp | 10 +- src/playlist/playlistview.h | 5 +- src/playlist/songloaderinserter.cpp | 9 +- src/playlist/songloaderinserter.h | 9 +- src/playlist/songmimedata.h | 3 +- src/playlistparsers/asxiniparser.cpp | 5 +- src/playlistparsers/asxiniparser.h | 3 +- src/playlistparsers/asxparser.cpp | 5 +- src/playlistparsers/asxparser.h | 3 +- src/playlistparsers/cueparser.cpp | 5 +- src/playlistparsers/cueparser.h | 3 +- src/playlistparsers/m3uparser.cpp | 5 +- src/playlistparsers/m3uparser.h | 3 +- src/playlistparsers/parserbase.cpp | 9 +- src/playlistparsers/parserbase.h | 8 +- src/playlistparsers/playlistparser.cpp | 17 +- src/playlistparsers/playlistparser.h | 3 +- src/playlistparsers/plsparser.cpp | 5 +- src/playlistparsers/plsparser.h | 3 +- src/playlistparsers/wplparser.cpp | 5 +- src/playlistparsers/wplparser.h | 3 +- src/playlistparsers/xmlparser.cpp | 5 +- src/playlistparsers/xmlparser.h | 3 +- src/playlistparsers/xspfparser.cpp | 5 +- src/playlistparsers/xspfparser.h | 3 +- src/qobuz/qobuzbaserequest.cpp | 3 +- src/qobuz/qobuzbaserequest.h | 6 +- src/qobuz/qobuzfavoriterequest.cpp | 3 +- src/qobuz/qobuzfavoriterequest.h | 5 +- src/qobuz/qobuzrequest.cpp | 3 +- src/qobuz/qobuzrequest.h | 5 +- src/qobuz/qobuzservice.cpp | 85 +++--- src/qobuz/qobuzservice.h | 29 ++- src/qobuz/qobuzstreamurlrequest.cpp | 3 +- src/qobuz/qobuzstreamurlrequest.h | 3 +- src/queue/queueview.cpp | 11 +- src/queue/queueview.h | 6 +- src/radios/radiobackend.cpp | 3 +- src/radios/radiobackend.h | 5 +- src/radios/radiomodel.cpp | 2 +- src/radios/radioparadiseservice.cpp | 2 +- src/radios/radioparadiseservice.h | 2 +- src/radios/radioservice.cpp | 3 +- src/radios/radioservice.h | 5 +- src/radios/radioservices.cpp | 17 +- src/radios/radioservices.h | 8 +- src/radios/somafmservice.cpp | 2 +- src/radios/somafmservice.h | 2 +- src/scrobbler/audioscrobbler.cpp | 160 ++++-------- src/scrobbler/audioscrobbler.h | 56 ++-- src/scrobbler/lastfmimport.cpp | 5 +- src/scrobbler/lastfmimport.h | 6 +- src/scrobbler/lastfmscrobbler.cpp | 7 +- src/scrobbler/lastfmscrobbler.h | 3 +- src/scrobbler/librefmscrobbler.cpp | 7 +- src/scrobbler/librefmscrobbler.h | 5 +- src/scrobbler/listenbrainzscrobbler.cpp | 21 +- src/scrobbler/listenbrainzscrobbler.h | 16 +- src/scrobbler/scrobblercache.cpp | 7 +- src/scrobbler/scrobblercacheitem.h | 5 +- src/scrobbler/scrobblerservice.h | 10 +- src/scrobbler/scrobblersettings.cpp | 122 +++++++++ src/scrobbler/scrobblersettings.h | 81 ++++++ src/scrobbler/scrobblingapi20.cpp | 25 +- src/scrobbler/scrobblingapi20.h | 18 +- src/scrobbler/subsonicscrobbler.cpp | 38 ++- src/scrobbler/subsonicscrobbler.h | 19 +- src/settings/backendsettingspage.h | 3 +- src/settings/globalshortcutssettingspage.cpp | 2 +- src/settings/globalshortcutssettingspage.h | 5 +- src/settings/qobuzsettingspage.cpp | 6 +- src/settings/qobuzsettingspage.h | 3 +- src/settings/scrobblersettingspage.cpp | 30 +-- src/settings/scrobblersettingspage.h | 12 +- src/settings/settingsdialog.h | 9 +- src/settings/subsonicsettingspage.cpp | 8 +- src/settings/subsonicsettingspage.h | 3 +- src/settings/tidalsettingspage.cpp | 8 +- src/settings/tidalsettingspage.h | 3 +- src/smartplaylists/playlistgenerator.cpp | 6 +- src/smartplaylists/playlistgenerator.h | 13 +- src/smartplaylists/playlistgenerator_fwd.h | 4 +- .../playlistgeneratorinserter.cpp | 7 +- .../playlistgeneratorinserter.h | 8 +- src/smartplaylists/playlistquerygenerator.cpp | 2 +- .../smartplaylistquerywizardplugin.cpp | 17 +- .../smartplaylistquerywizardplugin.h | 8 +- .../smartplaylistsearchpreview.cpp | 16 +- .../smartplaylistsearchpreview.h | 6 +- .../smartplaylistsearchtermwidget.cpp | 3 +- .../smartplaylistsearchtermwidget.h | 5 +- src/smartplaylists/smartplaylistsmodel.cpp | 27 +- src/smartplaylists/smartplaylistsmodel.h | 6 +- src/smartplaylists/smartplaylistwizard.cpp | 3 +- src/smartplaylists/smartplaylistwizard.h | 7 +- .../smartplaylistwizardplugin.cpp | 3 +- .../smartplaylistwizardplugin.h | 5 +- src/subsonic/subsonicbaserequest.cpp | 2 - src/subsonic/subsonicbaserequest.h | 6 +- src/subsonic/subsonicservice.cpp | 33 ++- src/subsonic/subsonicservice.h | 21 +- src/tidal/tidalbaserequest.cpp | 3 +- src/tidal/tidalbaserequest.h | 6 +- src/tidal/tidalfavoriterequest.cpp | 3 +- src/tidal/tidalfavoriterequest.h | 9 +- src/tidal/tidalrequest.cpp | 3 +- src/tidal/tidalrequest.h | 6 +- src/tidal/tidalservice.cpp | 104 ++++---- src/tidal/tidalservice.h | 32 +-- src/tidal/tidalstreamurlrequest.cpp | 3 +- src/tidal/tidalstreamurlrequest.h | 4 +- src/tidal/tidalurlhandler.cpp | 4 +- src/transcoder/transcoder.cpp | 7 +- src/transcoder/transcoder.h | 4 +- src/utilities/fileutils.cpp | 5 +- src/utilities/transliterate.cpp | 4 +- src/widgets/fileview.cpp | 11 +- src/widgets/fileview.h | 12 +- src/widgets/multiloadingindicator.cpp | 5 +- src/widgets/multiloadingindicator.h | 6 +- src/widgets/playingwidget.cpp | 6 +- src/widgets/playingwidget.h | 5 +- tests/src/collectionbackend_test.cpp | 43 ++-- tests/src/collectionmodel_test.cpp | 75 +++--- tests/src/songplaylistitem_test.cpp | 7 +- 316 files changed, 2170 insertions(+), 1643 deletions(-) create mode 100644 src/core/scoped_ptr.h create mode 100644 src/core/shared_ptr.h create mode 100644 src/scrobbler/scrobblersettings.cpp create mode 100644 src/scrobbler/scrobblersettings.h diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 1b0586dc..f56b64ad 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -269,6 +269,7 @@ set(SOURCES radios/radioparadiseservice.cpp scrobbler/audioscrobbler.cpp + scrobbler/scrobblersettings.cpp scrobbler/scrobblerservice.cpp scrobbler/scrobblercache.cpp scrobbler/scrobblercacheitem.cpp @@ -502,6 +503,7 @@ set(HEADERS radios/radioparadiseservice.h scrobbler/audioscrobbler.h + scrobbler/scrobblersettings.h scrobbler/scrobblerservice.h scrobbler/scrobblercache.h scrobbler/scrobblingapi20.h diff --git a/src/analyzer/analyzerbase.cpp b/src/analyzer/analyzerbase.cpp index b244f9dd..83065999 100644 --- a/src/analyzer/analyzerbase.cpp +++ b/src/analyzer/analyzerbase.cpp @@ -24,9 +24,9 @@ #include "analyzerbase.h" -#include -#include #include +#include +#include #include #include diff --git a/src/analyzer/analyzerbase.h b/src/analyzer/analyzerbase.h index fefde125..4e80c212 100644 --- a/src/analyzer/analyzerbase.h +++ b/src/analyzer/analyzerbase.h @@ -38,6 +38,7 @@ #include #include +#include "core/shared_ptr.h" #include "analyzer/fht.h" #include "engine/enginebase.h" @@ -54,7 +55,7 @@ class AnalyzerBase : public QWidget { int timeout() const { return timeout_; } - void set_engine(EngineBase *engine) { engine_ = engine; } + void set_engine(SharedPtr engine) { engine_ = engine; } void ChangeTimeout(const int timeout); @@ -82,7 +83,7 @@ class AnalyzerBase : public QWidget { protected: QBasicTimer timer_; FHT *fht_; - EngineBase *engine_; + SharedPtr engine_; Scope lastscope_; bool new_frame_; diff --git a/src/analyzer/analyzercontainer.cpp b/src/analyzer/analyzercontainer.cpp index db682765..adbafa63 100644 --- a/src/analyzer/analyzercontainer.cpp +++ b/src/analyzer/analyzercontainer.cpp @@ -43,6 +43,7 @@ #include "sonogram.h" #include "core/logging.h" +#include "core/shared_ptr.h" #include "engine/enginebase.h" using namespace std::chrono_literals; @@ -125,7 +126,7 @@ void AnalyzerContainer::wheelEvent(QWheelEvent *e) { emit WheelEvent(e->angleDelta().y()); } -void AnalyzerContainer::SetEngine(EngineBase *engine) { +void AnalyzerContainer::SetEngine(SharedPtr engine) { if (current_analyzer_) current_analyzer_->set_engine(engine); engine_ = engine; diff --git a/src/analyzer/analyzercontainer.h b/src/analyzer/analyzercontainer.h index 77d4cf77..b5ff7a29 100644 --- a/src/analyzer/analyzercontainer.h +++ b/src/analyzer/analyzercontainer.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "engine/enginebase.h" class QTimer; @@ -44,7 +45,7 @@ class AnalyzerContainer : public QWidget { public: explicit AnalyzerContainer(QWidget *parent); - void SetEngine(EngineBase *engine); + void SetEngine(SharedPtr engine); void SetActions(QAction *visualisation); static const char *kSettingsGroup; @@ -93,7 +94,7 @@ class AnalyzerContainer : public QWidget { bool ignore_next_click_; AnalyzerBase *current_analyzer_; - EngineBase *engine_; + SharedPtr engine_; }; template diff --git a/src/collection/collection.cpp b/src/collection/collection.cpp index 6dd10890..3812959f 100644 --- a/src/collection/collection.cpp +++ b/src/collection/collection.cpp @@ -21,6 +21,8 @@ #include "config.h" +#include + #include #include #include @@ -43,6 +45,9 @@ #include "scrobbler/lastfmimport.h" #include "settings/collectionsettingspage.h" +using std::make_unique; +using std::make_shared; + const char *SCollection::kSongsTable = "songs"; const char *SCollection::kFtsTable = "songs_fts"; const char *SCollection::kDirsTable = "directories"; @@ -61,9 +66,9 @@ SCollection::SCollection(Application *app, QObject *parent) original_thread_ = thread(); - backend_ = new CollectionBackend(); + backend_ = make_shared(); backend()->moveToThread(app->database()->thread()); - qLog(Debug) << backend_ << "moved to thread" << app->database()->thread(); + qLog(Debug) << &*backend_ << "moved to thread" << app->database()->thread(); backend_->Init(app->database(), app->task_manager(), Song::Source::Collection, kSongsTable, kFtsTable, kDirsTable, kSubdirsTable); @@ -83,44 +88,43 @@ SCollection::~SCollection() { watcher_thread_->exit(); watcher_thread_->wait(5000); } - backend_->deleteLater(); } void SCollection::Init() { - watcher_ = new CollectionWatcher(Song::Source::Collection); + watcher_ = make_unique(Song::Source::Collection); watcher_thread_ = new Thread(this); watcher_thread_->SetIoPriority(Utilities::IoPriority::IOPRIO_CLASS_IDLE); watcher_->moveToThread(watcher_thread_); - qLog(Debug) << watcher_ << "moved to thread" << watcher_thread_; + qLog(Debug) << &*watcher_ << "moved to thread" << watcher_thread_; watcher_thread_->start(QThread::IdlePriority); watcher_->set_backend(backend_); watcher_->set_task_manager(app_->task_manager()); - QObject::connect(backend_, &CollectionBackend::Error, this, &SCollection::Error); - QObject::connect(backend_, &CollectionBackend::DirectoryDiscovered, watcher_, &CollectionWatcher::AddDirectory); - QObject::connect(backend_, &CollectionBackend::DirectoryDeleted, watcher_, &CollectionWatcher::RemoveDirectory); - QObject::connect(backend_, &CollectionBackend::SongsRatingChanged, this, &SCollection::SongsRatingChanged); - QObject::connect(backend_, &CollectionBackend::SongsStatisticsChanged, this, &SCollection::SongsPlaycountChanged); + QObject::connect(&*backend_, &CollectionBackend::Error, this, &SCollection::Error); + QObject::connect(&*backend_, &CollectionBackend::DirectoryDiscovered, &*watcher_, &CollectionWatcher::AddDirectory); + QObject::connect(&*backend_, &CollectionBackend::DirectoryDeleted, &*watcher_, &CollectionWatcher::RemoveDirectory); + QObject::connect(&*backend_, &CollectionBackend::SongsRatingChanged, this, &SCollection::SongsRatingChanged); + QObject::connect(&*backend_, &CollectionBackend::SongsStatisticsChanged, this, &SCollection::SongsPlaycountChanged); - QObject::connect(watcher_, &CollectionWatcher::NewOrUpdatedSongs, backend_, &CollectionBackend::AddOrUpdateSongs); - QObject::connect(watcher_, &CollectionWatcher::SongsMTimeUpdated, backend_, &CollectionBackend::UpdateMTimesOnly); - QObject::connect(watcher_, &CollectionWatcher::SongsDeleted, backend_, &CollectionBackend::DeleteSongs); - QObject::connect(watcher_, &CollectionWatcher::SongsUnavailable, backend_, &CollectionBackend::MarkSongsUnavailable); - QObject::connect(watcher_, &CollectionWatcher::SongsReadded, backend_, &CollectionBackend::MarkSongsUnavailable); - QObject::connect(watcher_, &CollectionWatcher::SubdirsDiscovered, backend_, &CollectionBackend::AddOrUpdateSubdirs); - QObject::connect(watcher_, &CollectionWatcher::SubdirsMTimeUpdated, backend_, &CollectionBackend::AddOrUpdateSubdirs); - QObject::connect(watcher_, &CollectionWatcher::CompilationsNeedUpdating, backend_, &CollectionBackend::CompilationsNeedUpdating); - QObject::connect(watcher_, &CollectionWatcher::UpdateLastSeen, backend_, &CollectionBackend::UpdateLastSeen); + QObject::connect(&*watcher_, &CollectionWatcher::NewOrUpdatedSongs, &*backend_, &CollectionBackend::AddOrUpdateSongs); + QObject::connect(&*watcher_, &CollectionWatcher::SongsMTimeUpdated, &*backend_, &CollectionBackend::UpdateMTimesOnly); + QObject::connect(&*watcher_, &CollectionWatcher::SongsDeleted, &*backend_, &CollectionBackend::DeleteSongs); + QObject::connect(&*watcher_, &CollectionWatcher::SongsUnavailable, &*backend_, &CollectionBackend::MarkSongsUnavailable); + QObject::connect(&*watcher_, &CollectionWatcher::SongsReadded, &*backend_, &CollectionBackend::MarkSongsUnavailable); + QObject::connect(&*watcher_, &CollectionWatcher::SubdirsDiscovered, &*backend_, &CollectionBackend::AddOrUpdateSubdirs); + QObject::connect(&*watcher_, &CollectionWatcher::SubdirsMTimeUpdated, &*backend_, &CollectionBackend::AddOrUpdateSubdirs); + QObject::connect(&*watcher_, &CollectionWatcher::CompilationsNeedUpdating, &*backend_, &CollectionBackend::CompilationsNeedUpdating); + QObject::connect(&*watcher_, &CollectionWatcher::UpdateLastSeen, &*backend_, &CollectionBackend::UpdateLastSeen); - QObject::connect(app_->lastfm_import(), &LastFMImport::UpdateLastPlayed, backend_, &CollectionBackend::UpdateLastPlayed); - QObject::connect(app_->lastfm_import(), &LastFMImport::UpdatePlayCount, backend_, &CollectionBackend::UpdatePlayCount); + QObject::connect(&*app_->lastfm_import(), &LastFMImport::UpdateLastPlayed, &*backend_, &CollectionBackend::UpdateLastPlayed); + QObject::connect(&*app_->lastfm_import(), &LastFMImport::UpdatePlayCount, &*backend_, &CollectionBackend::UpdatePlayCount); // This will start the watcher checking for updates backend_->LoadDirectoriesAsync(); @@ -129,13 +133,13 @@ void SCollection::Init() { void SCollection::Exit() { - wait_for_exit_ << backend_ << watcher_; + wait_for_exit_ << &*backend_ << &*watcher_; - QObject::disconnect(backend_, nullptr, watcher_, nullptr); - QObject::disconnect(watcher_, nullptr, backend_, nullptr); + QObject::disconnect(&*backend_, nullptr, &*watcher_, nullptr); + QObject::disconnect(&*watcher_, nullptr, &*backend_, nullptr); - QObject::connect(backend_, &CollectionBackend::ExitFinished, this, &SCollection::ExitReceived); - QObject::connect(watcher_, &CollectionWatcher::ExitFinished, this, &SCollection::ExitReceived); + QObject::connect(&*backend_, &CollectionBackend::ExitFinished, this, &SCollection::ExitReceived); + QObject::connect(&*watcher_, &CollectionWatcher::ExitFinished, this, &SCollection::ExitReceived); backend_->ExitAsync(); watcher_->Abort(); watcher_->ExitAsync(); diff --git a/src/collection/collection.h b/src/collection/collection.h index 1a99948b..e6af1ed5 100644 --- a/src/collection/collection.h +++ b/src/collection/collection.h @@ -29,6 +29,8 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/song.h" class QThread; @@ -42,7 +44,7 @@ class SCollection : public QObject { Q_OBJECT public: - explicit SCollection(Application *app, QObject *parent); + explicit SCollection(Application *app, QObject *parent = nullptr); ~SCollection() override; static const char *kSongsTable; @@ -53,7 +55,7 @@ class SCollection : public QObject { void Init(); void Exit(); - CollectionBackend *backend() const { return backend_; } + SharedPtr backend() const { return backend_; } CollectionModel *model() const { return model_; } QString full_rescan_reason(int schema_version) const { return full_rescan_revisions_.value(schema_version, QString()); } @@ -86,10 +88,10 @@ class SCollection : public QObject { private: Application *app_; - CollectionBackend *backend_; + SharedPtr backend_; CollectionModel *model_; - CollectionWatcher *watcher_; + ScopedPtr watcher_; Thread *watcher_thread_; QThread *original_thread_; diff --git a/src/collection/collectionbackend.cpp b/src/collection/collectionbackend.cpp index 6be2c99d..5a65300d 100644 --- a/src/collection/collectionbackend.cpp +++ b/src/collection/collectionbackend.cpp @@ -43,6 +43,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/logging.h" #include "core/database.h" #include "core/scopedtransaction.h" @@ -67,7 +68,13 @@ CollectionBackend::CollectionBackend(QObject *parent) } -void CollectionBackend::Init(Database *db, TaskManager *task_manager, const Song::Source source, const QString &songs_table, const QString &fts_table, const QString &dirs_table, const QString &subdirs_table) { +CollectionBackend::~CollectionBackend() { + + qLog(Debug) << "Collection backend" << this << "for" << Song::TextForSource(source_) << "deleted"; + +} + +void CollectionBackend::Init(SharedPtr db, SharedPtr task_manager, const Song::Source source, const QString &songs_table, const QString &fts_table, const QString &dirs_table, const QString &subdirs_table) { db_ = db; task_manager_ = task_manager; diff --git a/src/collection/collectionbackend.h b/src/collection/collectionbackend.h index f21e3895..03f2c2b9 100644 --- a/src/collection/collectionbackend.h +++ b/src/collection/collectionbackend.h @@ -25,6 +25,7 @@ #include "config.h" #include +#include #include #include @@ -35,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "collectionfilteroptions.h" #include "collectionquery.h" @@ -82,7 +84,7 @@ class CollectionBackendInterface : public QObject { virtual Song::Source source() const = 0; - virtual Database *db() const = 0; + virtual SharedPtr db() const = 0; // Get a list of directories in the collection. Emits DirectoriesDiscovered. virtual void LoadDirectoriesAsync() = 0; @@ -140,7 +142,9 @@ class CollectionBackend : public CollectionBackendInterface { Q_INVOKABLE explicit CollectionBackend(QObject *parent = nullptr); - void Init(Database *db, TaskManager *task_manager, const Song::Source source, const QString &songs_table, const QString &fts_table, const QString &dirs_table = QString(), const QString &subdirs_table = QString()); + ~CollectionBackend(); + + void Init(SharedPtr db, SharedPtr task_manager, const Song::Source source, const QString &songs_table, const QString &fts_table, const QString &dirs_table = QString(), const QString &subdirs_table = QString()); void Close(); void ExitAsync(); @@ -149,7 +153,7 @@ class CollectionBackend : public CollectionBackendInterface { Song::Source source() const override { return source_; } - Database *db() const override { return db_; } + SharedPtr db() const override { return db_; } QString songs_table() const override { return songs_table_; } QString fts_table() const override { return fts_table_; } @@ -305,8 +309,8 @@ class CollectionBackend : public CollectionBackendInterface { SongList GetSongsBySongId(const QStringList &song_ids, QSqlDatabase &db); private: - Database *db_; - TaskManager *task_manager_; + SharedPtr db_; + SharedPtr task_manager_; Song::Source source_; QString songs_table_; QString dirs_table_; diff --git a/src/collection/collectiondirectorymodel.cpp b/src/collection/collectiondirectorymodel.cpp index 704ba046..dccbeeff 100644 --- a/src/collection/collectiondirectorymodel.cpp +++ b/src/collection/collectiondirectorymodel.cpp @@ -20,12 +20,15 @@ #include "config.h" +#include + #include #include #include #include #include +#include "core/shared_ptr.h" #include "core/filesystemmusicstorage.h" #include "core/iconloader.h" #include "core/musicstorage.h" @@ -34,24 +37,24 @@ #include "collectionbackend.h" #include "collectiondirectorymodel.h" -CollectionDirectoryModel::CollectionDirectoryModel(CollectionBackend *backend, QObject *parent) +using std::make_shared; + +CollectionDirectoryModel::CollectionDirectoryModel(SharedPtr backend, QObject *parent) : QStandardItemModel(parent), dir_icon_(IconLoader::Load("document-open-folder")), backend_(backend) { - QObject::connect(backend_, &CollectionBackend::DirectoryDiscovered, this, &CollectionDirectoryModel::DirectoryDiscovered); - QObject::connect(backend_, &CollectionBackend::DirectoryDeleted, this, &CollectionDirectoryModel::DirectoryDeleted); + QObject::connect(&*backend_, &CollectionBackend::DirectoryDiscovered, this, &CollectionDirectoryModel::DirectoryDiscovered); + QObject::connect(&*backend_, &CollectionBackend::DirectoryDeleted, this, &CollectionDirectoryModel::DirectoryDeleted); } -CollectionDirectoryModel::~CollectionDirectoryModel() = default; - void CollectionDirectoryModel::DirectoryDiscovered(const CollectionDirectory &dir) { QStandardItem *item = new QStandardItem(dir.path); item->setData(dir.id, kIdRole); item->setIcon(dir_icon_); - storage_ << std::make_shared(backend_->source(), dir.path, dir.id); + storage_ << make_shared(backend_->source(), dir.path, dir.id); appendRow(item); } diff --git a/src/collection/collectiondirectorymodel.h b/src/collection/collectiondirectorymodel.h index 130a594e..b15d9b66 100644 --- a/src/collection/collectiondirectorymodel.h +++ b/src/collection/collectiondirectorymodel.h @@ -23,8 +23,6 @@ #include "config.h" -#include - #include #include #include @@ -32,6 +30,8 @@ #include #include +#include "core/shared_ptr.h" + class QModelIndex; struct CollectionDirectory; @@ -42,8 +42,7 @@ class CollectionDirectoryModel : public QStandardItemModel { Q_OBJECT public: - explicit CollectionDirectoryModel(CollectionBackend *backend, QObject *parent = nullptr); - ~CollectionDirectoryModel() override; + explicit CollectionDirectoryModel(SharedPtr collection_backend, QObject *parent = nullptr); // To be called by GUIs void AddDirectory(const QString &path); @@ -60,8 +59,8 @@ class CollectionDirectoryModel : public QStandardItemModel { static const int kIdRole = Qt::UserRole + 1; QIcon dir_icon_; - CollectionBackend *backend_; - QList> storage_; + SharedPtr backend_; + QList> storage_; }; #endif // COLLECTIONDIRECTORYMODEL_H diff --git a/src/collection/collectionmodel.cpp b/src/collection/collectionmodel.cpp index a99d84af..0009fcb3 100644 --- a/src/collection/collectionmodel.cpp +++ b/src/collection/collectionmodel.cpp @@ -53,6 +53,8 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/database.h" #include "core/iconloader.h" @@ -78,7 +80,7 @@ const char *CollectionModel::kPixmapDiskCacheDir = "pixmapcache"; QNetworkDiskCache *CollectionModel::sIconCache = nullptr; -CollectionModel::CollectionModel(CollectionBackend *backend, Application *app, QObject *parent) +CollectionModel::CollectionModel(SharedPtr backend, Application *app, QObject *parent) : SimpleTreeModel(new CollectionItem(this), parent), backend_(backend), app_(app), @@ -103,7 +105,7 @@ CollectionModel::CollectionModel(CollectionBackend *backend, Application *app, Q group_by_[2] = GroupBy::None; if (app_) { - QObject::connect(app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &CollectionModel::AlbumCoverLoaded); + QObject::connect(&*app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &CollectionModel::AlbumCoverLoaded); } QIcon nocover = IconLoader::Load("cdcase"); @@ -118,14 +120,14 @@ CollectionModel::CollectionModel(CollectionBackend *backend, Application *app, Q QObject::connect(app_, &Application::ClearPixmapDiskCache, this, &CollectionModel::ClearDiskCache); } - QObject::connect(backend_, &CollectionBackend::SongsDiscovered, this, &CollectionModel::SongsDiscovered); - QObject::connect(backend_, &CollectionBackend::SongsDeleted, this, &CollectionModel::SongsDeleted); - QObject::connect(backend_, &CollectionBackend::DatabaseReset, this, &CollectionModel::Reset); - QObject::connect(backend_, &CollectionBackend::TotalSongCountUpdated, this, &CollectionModel::TotalSongCountUpdatedSlot); - QObject::connect(backend_, &CollectionBackend::TotalArtistCountUpdated, this, &CollectionModel::TotalArtistCountUpdatedSlot); - QObject::connect(backend_, &CollectionBackend::TotalAlbumCountUpdated, this, &CollectionModel::TotalAlbumCountUpdatedSlot); - QObject::connect(backend_, &CollectionBackend::SongsStatisticsChanged, this, &CollectionModel::SongsSlightlyChanged); - QObject::connect(backend_, &CollectionBackend::SongsRatingChanged, this, &CollectionModel::SongsSlightlyChanged); + QObject::connect(&*backend_, &CollectionBackend::SongsDiscovered, this, &CollectionModel::SongsDiscovered); + QObject::connect(&*backend_, &CollectionBackend::SongsDeleted, this, &CollectionModel::SongsDeleted); + QObject::connect(&*backend_, &CollectionBackend::DatabaseReset, this, &CollectionModel::Reset); + QObject::connect(&*backend_, &CollectionBackend::TotalSongCountUpdated, this, &CollectionModel::TotalSongCountUpdatedSlot); + QObject::connect(&*backend_, &CollectionBackend::TotalArtistCountUpdated, this, &CollectionModel::TotalArtistCountUpdatedSlot); + QObject::connect(&*backend_, &CollectionBackend::TotalAlbumCountUpdated, this, &CollectionModel::TotalAlbumCountUpdatedSlot); + QObject::connect(&*backend_, &CollectionBackend::SongsStatisticsChanged, this, &CollectionModel::SongsSlightlyChanged); + QObject::connect(&*backend_, &CollectionBackend::SongsRatingChanged, this, &CollectionModel::SongsSlightlyChanged); backend_->UpdateTotalSongCountAsync(); backend_->UpdateTotalArtistCountAsync(); @@ -136,7 +138,11 @@ CollectionModel::CollectionModel(CollectionBackend *backend, Application *app, Q } CollectionModel::~CollectionModel() { + + qLog(Debug) << "Collection model" << this << "for" << Song::TextForSource(backend_->source()) << "deleted"; + delete root_; + } void CollectionModel::set_pretty_covers(const bool use_pretty_covers) { @@ -632,10 +638,10 @@ QVariant CollectionModel::AlbumIcon(const QModelIndex &idx) { // Try to load it from the disk cache if (use_disk_cache_ && sIconCache) { - std::unique_ptr disk_cache_img(sIconCache->data(AlbumIconPixmapDiskCacheKey(cache_key))); + ScopedPtr disk_cache_img(sIconCache->data(AlbumIconPixmapDiskCacheKey(cache_key))); if (disk_cache_img) { QImage cached_image; - if (cached_image.load(disk_cache_img.get(), "XPM")) { + if (cached_image.load(&*disk_cache_img, "XPM")) { QPixmapCache::insert(cache_key, QPixmap::fromImage(cached_image)); return QPixmap::fromImage(cached_image); } @@ -688,7 +694,7 @@ void CollectionModel::AlbumCoverLoaded(const quint64 id, const AlbumCoverLoaderR // If we have a valid cover not already in the disk cache if (use_disk_cache_ && sIconCache && result.success && !result.image_scaled.isNull()) { const QUrl disk_cache_key = AlbumIconPixmapDiskCacheKey(cache_key); - std::unique_ptr disk_cache_img(sIconCache->data(disk_cache_key)); + ScopedPtr disk_cache_img(sIconCache->data(disk_cache_key)); if (!disk_cache_img) { QNetworkCacheMetaData disk_cache_metadata; disk_cache_metadata.setSaveToDisk(true); diff --git a/src/collection/collectionmodel.h b/src/collection/collectionmodel.h index be41faa6..17deae0b 100644 --- a/src/collection/collectionmodel.h +++ b/src/collection/collectionmodel.h @@ -45,6 +45,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/simpletreemodel.h" #include "core/song.h" #include "core/sqlrow.h" @@ -64,7 +65,7 @@ class CollectionModel : public SimpleTreeModel { Q_OBJECT public: - explicit CollectionModel(CollectionBackend *backend, Application *app, QObject *parent = nullptr); + explicit CollectionModel(SharedPtr backend, Application *app, QObject *parent = nullptr); ~CollectionModel() override; static const int kPrettyCoverSize; @@ -131,7 +132,7 @@ class CollectionModel : public SimpleTreeModel { bool create_va; }; - CollectionBackend *backend() const { return backend_; } + SharedPtr backend() const { return backend_; } CollectionDirectoryModel *directory_model() const { return dir_model_; } // Call before Init() @@ -273,7 +274,7 @@ class CollectionModel : public SimpleTreeModel { static qint64 MaximumCacheSize(QSettings *s, const char *size_id, const char *size_unit_id, const qint64 cache_size_default); private: - CollectionBackend *backend_; + SharedPtr backend_; Application *app_; CollectionDirectoryModel *dir_model_; bool show_various_artists_; diff --git a/src/collection/collectiontask.cpp b/src/collection/collectiontask.cpp index 6bcc55a1..78eee232 100644 --- a/src/collection/collectiontask.cpp +++ b/src/collection/collectiontask.cpp @@ -19,10 +19,11 @@ #include +#include "core/shared_ptr.h" #include "core/taskmanager.h" #include "collectiontask.h" -CollectionTask::CollectionTask(TaskManager *task_manager, const QString &message) : task_manager_(task_manager), task_id_(-1) { +CollectionTask::CollectionTask(SharedPtr task_manager, const QString &message) : task_manager_(task_manager), task_id_(-1) { if (task_manager_) task_id_ = task_manager_->StartTask(message); diff --git a/src/collection/collectiontask.h b/src/collection/collectiontask.h index c0d218cc..c93e828d 100644 --- a/src/collection/collectiontask.h +++ b/src/collection/collectiontask.h @@ -23,15 +23,17 @@ #include #include +#include "core/shared_ptr.h" + class TaskManager; class CollectionTask { public: - explicit CollectionTask(TaskManager *task_manager, const QString &message); + explicit CollectionTask(SharedPtr task_manager, const QString &message); ~CollectionTask(); private: - TaskManager *task_manager_; + SharedPtr task_manager_; int task_id_; Q_DISABLE_COPY(CollectionTask) diff --git a/src/collection/collectionview.cpp b/src/collection/collectionview.cpp index 47fe4148..030600d3 100644 --- a/src/collection/collectionview.cpp +++ b/src/collection/collectionview.cpp @@ -71,6 +71,8 @@ #include "organize/organizeerrordialog.h" #include "settings/collectionsettingspage.h" +using std::make_unique; + CollectionView::CollectionView(QWidget *parent) : AutoExpandingTreeView(parent), app_(nullptr), @@ -573,7 +575,7 @@ SongList CollectionView::GetSelectedSongs() const { void CollectionView::Organize() { if (!organize_dialog_) { - organize_dialog_ = std::make_unique(app_->task_manager(), app_->collection_backend(), this); + organize_dialog_ = make_unique(app_->task_manager(), app_->collection_backend(), this); } organize_dialog_->SetDestinationModel(app_->collection_model()->directory_model()); @@ -591,8 +593,8 @@ void CollectionView::Organize() { void CollectionView::EditTracks() { if (!edit_tag_dialog_) { - edit_tag_dialog_ = std::make_unique(app_, this); - QObject::connect(edit_tag_dialog_.get(), &EditTagDialog::Error, this, &CollectionView::EditTagError); + edit_tag_dialog_ = make_unique(app_, this); + QObject::connect(&*edit_tag_dialog_, &EditTagDialog::Error, this, &CollectionView::EditTagError); } const SongList songs = GetSelectedSongs(); edit_tag_dialog_->SetSongs(songs); @@ -614,7 +616,7 @@ void CollectionView::CopyToDevice() { #ifndef Q_OS_WIN if (!organize_dialog_) { - organize_dialog_ = std::make_unique(app_->task_manager(), nullptr, this); + organize_dialog_ = make_unique(app_->task_manager(), nullptr, this); } organize_dialog_->SetDestinationModel(app_->device_manager()->connected_devices_model(), true); @@ -686,7 +688,7 @@ void CollectionView::Delete() { if (DeleteConfirmationDialog::warning(files) != QDialogButtonBox::Yes) return; // We can cheat and always take the storage of the first directory, since they'll all be FilesystemMusicStorage in a collection and deleting doesn't check the actual directory. - std::shared_ptr storage = app_->collection_model()->directory_model()->index(0, 0).data(MusicStorage::Role_Storage).value>(); + SharedPtr storage = app_->collection_model()->directory_model()->index(0, 0).data(MusicStorage::Role_Storage).value>(); DeleteFiles *delete_files = new DeleteFiles(app_->task_manager(), storage, true); QObject::connect(delete_files, &DeleteFiles::Finished, this, &CollectionView::DeleteFilesFinished); diff --git a/src/collection/collectionview.h b/src/collection/collectionview.h index a2c98ef4..e2c716ee 100644 --- a/src/collection/collectionview.h +++ b/src/collection/collectionview.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -33,6 +31,7 @@ #include #include +#include "core/scoped_ptr.h" #include "core/song.h" #include "widgets/autoexpandingtreeview.h" @@ -148,8 +147,8 @@ class CollectionView : public AutoExpandingTreeView { QAction *action_no_show_in_various_; QAction *action_delete_files_; - std::unique_ptr organize_dialog_; - std::unique_ptr edit_tag_dialog_; + ScopedPtr organize_dialog_; + ScopedPtr edit_tag_dialog_; bool is_in_keyboard_search_; bool delete_files_; diff --git a/src/collection/collectionwatcher.cpp b/src/collection/collectionwatcher.cpp index 1c6976ec..5a669aba 100644 --- a/src/collection/collectionwatcher.cpp +++ b/src/collection/collectionwatcher.cpp @@ -119,6 +119,12 @@ CollectionWatcher::CollectionWatcher(Song::Source source, QObject *parent) } +CollectionWatcher::~CollectionWatcher() { + + qLog(Debug) << "Collection watcher" << this << "for" << Song::TextForSource(source_) << "deleted."; + +} + void CollectionWatcher::ExitAsync() { QMetaObject::invokeMethod(this, &CollectionWatcher::Exit, Qt::QueuedConnection); } diff --git a/src/collection/collectionwatcher.h b/src/collection/collectionwatcher.h index 482074fc..5bfcfe8e 100644 --- a/src/collection/collectionwatcher.h +++ b/src/collection/collectionwatcher.h @@ -35,6 +35,7 @@ #include #include "collectiondirectory.h" +#include "core/shared_ptr.h" #include "core/song.h" class QThread; @@ -50,11 +51,12 @@ class CollectionWatcher : public QObject { public: explicit CollectionWatcher(Song::Source source, QObject *parent = nullptr); + ~CollectionWatcher(); Song::Source source() { return source_; } - void set_backend(CollectionBackend *backend) { backend_ = backend; } - void set_task_manager(TaskManager *task_manager) { task_manager_ = task_manager; } + void set_backend(SharedPtr backend) { backend_ = backend; } + void set_task_manager(SharedPtr task_manager) { task_manager_ = task_manager; } void set_device_name(const QString &device_name) { device_name_ = device_name; } void IncrementalScanAsync(); @@ -208,8 +210,8 @@ class CollectionWatcher : public QObject { private: Song::Source source_; - CollectionBackend *backend_; - TaskManager *task_manager_; + SharedPtr backend_; + SharedPtr task_manager_; QString device_name_; FileSystemWatcherInterface *fs_watcher_; diff --git a/src/collection/groupbydialog.cpp b/src/collection/groupbydialog.cpp index 282e2ca0..cfa7d1fd 100644 --- a/src/collection/groupbydialog.cpp +++ b/src/collection/groupbydialog.cpp @@ -21,7 +21,7 @@ #include "config.h" -#include +#include #include #include @@ -41,6 +41,8 @@ #include #include +using std::make_unique; + using boost::multi_index_container; using boost::multi_index::indexed_by; using boost::multi_index::ordered_unique; @@ -69,7 +71,7 @@ class GroupByDialogPrivate { MappingContainer mapping_; }; -GroupByDialog::GroupByDialog(QWidget *parent) : QDialog(parent), ui_(new Ui_GroupByDialog), p_(new GroupByDialogPrivate) { +GroupByDialog::GroupByDialog(QWidget *parent) : QDialog(parent), ui_(make_unique()), p_(make_unique()) { ui_->setupUi(this); Reset(); diff --git a/src/collection/groupbydialog.h b/src/collection/groupbydialog.h index 2f23618b..da4ce83c 100644 --- a/src/collection/groupbydialog.h +++ b/src/collection/groupbydialog.h @@ -24,12 +24,11 @@ #include "config.h" -#include - #include #include #include +#include "core/scoped_ptr.h" #include "collectionmodel.h" #include "ui_groupbydialog.h" @@ -55,8 +54,8 @@ class GroupByDialog : public QDialog { void Reset(); private: - std::unique_ptr ui_; - std::unique_ptr p_; + ScopedPtr ui_; + ScopedPtr p_; }; #endif // GROUPBYDIALOG_H diff --git a/src/context/contextalbum.cpp b/src/context/contextalbum.cpp index 95d6e363..7e4b080c 100644 --- a/src/context/contextalbum.cpp +++ b/src/context/contextalbum.cpp @@ -37,12 +37,16 @@ #include #include +#include "core/shared_ptr.h" #include "utilities/imageutils.h" #include "covermanager/albumcoverchoicecontroller.h" #include "contextview.h" #include "contextalbum.h" +using std::make_unique; +using std::make_shared; + const int ContextAlbum::kFadeTimeLineMs = 1000; ContextAlbum::ContextAlbum(QWidget *parent) @@ -155,15 +159,15 @@ void ContextAlbum::SetImage(QImage image) { ScaleCover(); if (!pixmap_previous.isNull()) { - std::shared_ptr previous_cover = std::make_shared(); + SharedPtr previous_cover = make_shared(); previous_cover->image = image_previous; previous_cover->pixmap = pixmap_previous; previous_cover->opacity = opacity_previous; previous_cover->timeline.reset(new QTimeLine(kFadeTimeLineMs), [](QTimeLine *timeline) { timeline->deleteLater(); }); previous_cover->timeline->setDirection(QTimeLine::Backward); previous_cover->timeline->setCurrentTime(timeline_fade_->state() == QTimeLine::Running ? timeline_fade_->currentTime() : kFadeTimeLineMs); - QObject::connect(previous_cover->timeline.get(), &QTimeLine::valueChanged, this, [this, previous_cover]() { FadePreviousCover(previous_cover); }); - QObject::connect(previous_cover->timeline.get(), &QTimeLine::finished, this, [this, previous_cover]() { FadePreviousCoverFinished(previous_cover); }); + QObject::connect(&*previous_cover->timeline, &QTimeLine::valueChanged, this, [this, previous_cover]() { FadePreviousCover(previous_cover); }); + QObject::connect(&*previous_cover->timeline, &QTimeLine::finished, this, [this, previous_cover]() { FadePreviousCoverFinished(previous_cover); }); previous_covers_ << previous_cover; previous_cover->timeline->start(); } @@ -194,7 +198,7 @@ void ContextAlbum::DrawSpinner(QPainter *p) { void ContextAlbum::DrawPreviousCovers(QPainter *p) { - for (std::shared_ptr previous_cover : previous_covers_) { + for (SharedPtr previous_cover : previous_covers_) { DrawImage(p, previous_cover->pixmap, previous_cover->opacity); } @@ -217,7 +221,7 @@ void ContextAlbum::FadeCurrentCoverFinished() { } -void ContextAlbum::FadePreviousCover(std::shared_ptr previous_cover) { +void ContextAlbum::FadePreviousCover(SharedPtr previous_cover) { if (previous_cover->timeline->currentValue() >= previous_cover->opacity) return; @@ -225,7 +229,7 @@ void ContextAlbum::FadePreviousCover(std::shared_ptr previous_cov } -void ContextAlbum::FadePreviousCoverFinished(std::shared_ptr previous_cover) { +void ContextAlbum::FadePreviousCoverFinished(SharedPtr previous_cover) { previous_covers_.removeAll(previous_cover); @@ -245,7 +249,7 @@ void ContextAlbum::ScaleCover() { void ContextAlbum::ScalePreviousCovers() { - for (std::shared_ptr previous_cover : previous_covers_) { + for (SharedPtr previous_cover : previous_covers_) { QImage image = ImageUtils::ScaleImage(previous_cover->image, QSize(desired_height_, desired_height_), devicePixelRatioF(), true); if (image.isNull()) { previous_cover->pixmap = QPixmap(); @@ -262,8 +266,8 @@ void ContextAlbum::SearchCoverInProgress() { downloading_covers_ = true; // Show a spinner animation - spinner_animation_ = std::make_unique(":/pictures/spinner.gif", QByteArray(), this); - QObject::connect(spinner_animation_.get(), &QMovie::updated, this, &ContextAlbum::Update); + spinner_animation_ = make_unique(":/pictures/spinner.gif", QByteArray(), this); + QObject::connect(&*spinner_animation_, &QMovie::updated, this, &ContextAlbum::Update); spinner_animation_->start(); update(); diff --git a/src/context/contextalbum.h b/src/context/contextalbum.h index 6bebcb65..e3b7ff6f 100644 --- a/src/context/contextalbum.h +++ b/src/context/contextalbum.h @@ -33,6 +33,9 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" + class QMenu; class QTimeLine; class QPainter; @@ -64,10 +67,10 @@ class ContextAlbum : public QWidget { QImage image; QPixmap pixmap; qreal opacity; - std::shared_ptr timeline; + SharedPtr timeline; }; - QList> previous_covers_; + QList> previous_covers_; void DrawImage(QPainter *p, const QPixmap &pixmap, const qreal opacity); void DrawSpinner(QPainter *p); @@ -84,8 +87,8 @@ class ContextAlbum : public QWidget { void AutomaticCoverSearchDone(); void FadeCurrentCover(const qreal value); void FadeCurrentCoverFinished(); - void FadePreviousCover(std::shared_ptr previouscover); - void FadePreviousCoverFinished(std::shared_ptr previouscover); + void FadePreviousCover(SharedPtr previouscover); + void FadePreviousCoverFinished(SharedPtr previouscover); public slots: void SearchCoverInProgress(); @@ -103,7 +106,7 @@ class ContextAlbum : public QWidget { QImage image_original_; QPixmap pixmap_current_; qreal pixmap_current_opacity_; - std::unique_ptr spinner_animation_; + ScopedPtr spinner_animation_; int desired_height_; }; diff --git a/src/core/application.cpp b/src/core/application.cpp index 9feb7d18..a103d703 100644 --- a/src/core/application.cpp +++ b/src/core/application.cpp @@ -31,10 +31,11 @@ #include #include -#include "core/lazy.h" -#include "core/tagreaderclient.h" #include "core/logging.h" +#include "shared_ptr.h" +#include "lazy.h" +#include "tagreaderclient.h" #include "database.h" #include "taskmanager.h" #include "player.h" @@ -98,99 +99,103 @@ #include "radios/radioservices.h" #include "radios/radiobackend.h" +using std::make_shared; using namespace std::chrono_literals; class ApplicationImpl { public: explicit ApplicationImpl(Application *app) : - tag_reader_client_([app]() { - TagReaderClient *client = new TagReaderClient(app); + tag_reader_client_([app](){ + TagReaderClient *client = new TagReaderClient(); app->MoveToNewThread(client); client->Start(); return client; }), database_([app]() { - Database *db = new Database(app, app); + Database *db = new Database(app); app->MoveToNewThread(db); QTimer::singleShot(30s, db, &Database::DoBackup); return db; }), - task_manager_([app]() { return new TaskManager(app); }), - player_([app]() { return new Player(app, app); }), - network_([app]() { return new NetworkAccessManager(app); }), - device_finders_([app]() { return new DeviceFinders(app); }), + task_manager_([]() { return new TaskManager(); }), + player_([app]() { return new Player(app); }), + network_([]() { return new NetworkAccessManager(); }), + device_finders_([]() { return new DeviceFinders(); }), #ifndef Q_OS_WIN - device_manager_([app]() { return new DeviceManager(app, app); }), + device_manager_([app]() { return new DeviceManager(app); }), #endif - collection_([app]() { return new SCollection(app, app); }), + collection_([app]() { return new SCollection(app); }), playlist_backend_([this, app]() { - PlaylistBackend *backend = new PlaylistBackend(app, app); + PlaylistBackend *backend = new PlaylistBackend(app); app->MoveToThread(backend, database_->thread()); return backend; }), playlist_manager_([app]() { return new PlaylistManager(app); }), cover_providers_([app]() { - CoverProviders *cover_providers = new CoverProviders(app); + CoverProviders *cover_providers = new CoverProviders(); // Initialize the repository of cover providers. - cover_providers->AddProvider(new LastFmCoverProvider(app, app->network(), app)); - cover_providers->AddProvider(new MusicbrainzCoverProvider(app, app->network(), app)); - cover_providers->AddProvider(new DiscogsCoverProvider(app, app->network(), app)); - cover_providers->AddProvider(new DeezerCoverProvider(app, app->network(), app)); - cover_providers->AddProvider(new MusixmatchCoverProvider(app, app->network(), app)); - cover_providers->AddProvider(new SpotifyCoverProvider(app, app->network(), app)); + cover_providers->AddProvider(new LastFmCoverProvider(app, app->network())); + cover_providers->AddProvider(new MusicbrainzCoverProvider(app, app->network())); + cover_providers->AddProvider(new DiscogsCoverProvider(app, app->network())); + cover_providers->AddProvider(new DeezerCoverProvider(app, app->network())); + cover_providers->AddProvider(new MusixmatchCoverProvider(app, app->network())); + cover_providers->AddProvider(new SpotifyCoverProvider(app, app->network())); #ifdef HAVE_TIDAL - cover_providers->AddProvider(new TidalCoverProvider(app, app->network(), app)); + cover_providers->AddProvider(new TidalCoverProvider(app, app->network())); #endif #ifdef HAVE_QOBUZ - cover_providers->AddProvider(new QobuzCoverProvider(app, app->network(), app)); + cover_providers->AddProvider(new QobuzCoverProvider(app, app->network())); #endif cover_providers->ReloadSettings(); return cover_providers; }), album_cover_loader_([app]() { - AlbumCoverLoader *loader = new AlbumCoverLoader(app); + AlbumCoverLoader *loader = new AlbumCoverLoader(); app->MoveToNewThread(loader); return loader; }), - current_albumcover_loader_([app]() { return new CurrentAlbumCoverLoader(app, app); }), + current_albumcover_loader_([app]() { return new CurrentAlbumCoverLoader(app); }), lyrics_providers_([app]() { LyricsProviders *lyrics_providers = new LyricsProviders(app); // Initialize the repository of lyrics providers. - lyrics_providers->AddProvider(new GeniusLyricsProvider(app->network(), app)); - lyrics_providers->AddProvider(new OVHLyricsProvider(app->network(), app)); - lyrics_providers->AddProvider(new LoloLyricsProvider(app->network(), app)); - lyrics_providers->AddProvider(new MusixmatchLyricsProvider(app->network(), app)); - lyrics_providers->AddProvider(new ChartLyricsProvider(app->network(), app)); - lyrics_providers->AddProvider(new LyricsComLyricsProvider(app->network(), app)); + lyrics_providers->AddProvider(new GeniusLyricsProvider(app->network())); + lyrics_providers->AddProvider(new OVHLyricsProvider(app->network())); + lyrics_providers->AddProvider(new LoloLyricsProvider(app->network())); + lyrics_providers->AddProvider(new MusixmatchLyricsProvider(app->network())); + lyrics_providers->AddProvider(new ChartLyricsProvider(app->network())); + lyrics_providers->AddProvider(new LyricsComLyricsProvider(app->network())); lyrics_providers->ReloadSettings(); return lyrics_providers; }), internet_services_([app]() { - InternetServices *internet_services = new InternetServices(app); + InternetServices *internet_services = new InternetServices(); #ifdef HAVE_SUBSONIC - internet_services->AddService(new SubsonicService(app, internet_services)); + internet_services->AddService(make_shared(app)); #endif #ifdef HAVE_TIDAL - internet_services->AddService(new TidalService(app, internet_services)); + internet_services->AddService(make_shared(app)); #endif #ifdef HAVE_QOBUZ - internet_services->AddService(new QobuzService(app, internet_services)); + internet_services->AddService(make_shared(app)); #endif return internet_services; }), - radio_services_([app]() { return new RadioServices(app, app); }), + radio_services_([app]() { return new RadioServices(app); }), scrobbler_([app]() { AudioScrobbler *scrobbler = new AudioScrobbler(app); - scrobbler->AddService(new LastFMScrobbler(scrobbler, app->network(), app)); - scrobbler->AddService(new LibreFMScrobbler(scrobbler, app->network(), app)); - scrobbler->AddService(new ListenBrainzScrobbler(scrobbler, app->network(), app)); + scrobbler->AddService(make_shared(scrobbler->settings(), app->network())); + scrobbler->AddService(make_shared(scrobbler->settings(), app->network())); + scrobbler->AddService(make_shared(scrobbler->settings(), app->network())); +#ifdef HAVE_SUBSONIC + scrobbler->AddService(make_shared(scrobbler->settings(), app)); +#endif return scrobbler; }), #ifdef HAVE_MOODBAR - moodbar_loader_([app]() { return new MoodbarLoader(app, app); }), - moodbar_controller_([app]() { return new MoodbarController(app, app); }), + moodbar_loader_([app]() { return new MoodbarLoader(app); }), + moodbar_controller_([app]() { return new MoodbarController(app); }), #endif - lastfm_import_([app]() { return new LastFMImport(app->network(), app); }) + lastfm_import_([app]() { return new LastFMImport(app->network()); }) {} Lazy tag_reader_client_; @@ -227,17 +232,13 @@ Application::Application(QObject *parent) collection()->Init(); tag_reader_client(); - QObject::connect(database(), &Database::Error, this, &Application::ErrorAdded); + QObject::connect(&*database(), &Database::Error, this, &Application::ErrorAdded); } Application::~Application() { - // It's important that the device manager is deleted before the database. - // Deleting the database deletes all objects that have been created in its thread, including some device collection backends. -#ifndef Q_OS_WIN - p_->device_manager_.reset(); -#endif + qLog(Debug) << "Terminating application"; for (QThread *thread : threads_) { thread->quit(); @@ -271,37 +272,37 @@ void Application::MoveToThread(QObject *object, QThread *thread) { void Application::Exit() { - wait_for_exit_ << tag_reader_client() - << collection() - << playlist_backend() - << album_cover_loader() + wait_for_exit_ << &*tag_reader_client() + << &*collection() + << &*playlist_backend() + << &*album_cover_loader() #ifndef Q_OS_WIN - << device_manager() + << &*device_manager() #endif - << internet_services() - << radio_services()->radio_backend(); + << &*internet_services() + << &*radio_services()->radio_backend(); - QObject::connect(tag_reader_client(), &TagReaderClient::ExitFinished, this, &Application::ExitReceived); + QObject::connect(&*tag_reader_client(), &TagReaderClient::ExitFinished, this, &Application::ExitReceived); tag_reader_client()->ExitAsync(); - QObject::connect(collection(), &SCollection::ExitFinished, this, &Application::ExitReceived); + QObject::connect(&*collection(), &SCollection::ExitFinished, this, &Application::ExitReceived); collection()->Exit(); - QObject::connect(playlist_backend(), &PlaylistBackend::ExitFinished, this, &Application::ExitReceived); + QObject::connect(&*playlist_backend(), &PlaylistBackend::ExitFinished, this, &Application::ExitReceived); playlist_backend()->ExitAsync(); - QObject::connect(album_cover_loader(), &AlbumCoverLoader::ExitFinished, this, &Application::ExitReceived); + QObject::connect(&*album_cover_loader(), &AlbumCoverLoader::ExitFinished, this, &Application::ExitReceived); album_cover_loader()->ExitAsync(); #ifndef Q_OS_WIN - QObject::connect(device_manager(), &DeviceManager::ExitFinished, this, &Application::ExitReceived); + QObject::connect(&*device_manager(), &DeviceManager::ExitFinished, this, &Application::ExitReceived); device_manager()->Exit(); #endif - QObject::connect(internet_services(), &InternetServices::ExitFinished, this, &Application::ExitReceived); + QObject::connect(&*internet_services(), &InternetServices::ExitFinished, this, &Application::ExitReceived); internet_services()->Exit(); - QObject::connect(radio_services()->radio_backend(), &RadioBackend::ExitFinished, this, &Application::ExitReceived); + QObject::connect(&*radio_services()->radio_backend(), &RadioBackend::ExitFinished, this, &Application::ExitReceived); radio_services()->radio_backend()->ExitAsync(); } @@ -316,7 +317,7 @@ void Application::ExitReceived() { wait_for_exit_.removeAll(obj); if (wait_for_exit_.isEmpty()) { database()->Close(); - QObject::connect(database(), &Database::ExitFinished, this, &Application::ExitFinished); + QObject::connect(&*database(), &Database::ExitFinished, this, &Application::ExitFinished); database()->ExitAsync(); } @@ -326,29 +327,29 @@ void Application::AddError(const QString &message) { emit ErrorAdded(message); } void Application::ReloadSettings() { emit SettingsChanged(); } void Application::OpenSettingsDialogAtPage(SettingsDialog::Page page) { emit SettingsDialogRequested(page); } -TagReaderClient *Application::tag_reader_client() const { return p_->tag_reader_client_.get(); } -Database *Application::database() const { return p_->database_.get(); } -TaskManager *Application::task_manager() const { return p_->task_manager_.get(); } -Player *Application::player() const { return p_->player_.get(); } -NetworkAccessManager *Application::network() const { return p_->network_.get(); } -DeviceFinders *Application::device_finders() const { return p_->device_finders_.get(); } +SharedPtr Application::tag_reader_client() const { return p_->tag_reader_client_.ptr(); } +SharedPtr Application::database() const { return p_->database_.ptr(); } +SharedPtr Application::task_manager() const { return p_->task_manager_.ptr(); } +SharedPtr Application::player() const { return p_->player_.ptr(); } +SharedPtr Application::network() const { return p_->network_.ptr(); } +SharedPtr Application::device_finders() const { return p_->device_finders_.ptr(); } #ifndef Q_OS_WIN -DeviceManager *Application::device_manager() const { return p_->device_manager_.get(); } +SharedPtr Application::device_manager() const { return p_->device_manager_.ptr(); } #endif -SCollection *Application::collection() const { return p_->collection_.get(); } -CollectionBackend *Application::collection_backend() const { return collection()->backend(); } +SharedPtr Application::collection() const { return p_->collection_.ptr(); } +SharedPtr Application::collection_backend() const { return collection()->backend(); } CollectionModel *Application::collection_model() const { return collection()->model(); } -AlbumCoverLoader *Application::album_cover_loader() const { return p_->album_cover_loader_.get(); } -CoverProviders *Application::cover_providers() const { return p_->cover_providers_.get(); } -CurrentAlbumCoverLoader *Application::current_albumcover_loader() const { return p_->current_albumcover_loader_.get(); } -LyricsProviders *Application::lyrics_providers() const { return p_->lyrics_providers_.get(); } -PlaylistBackend *Application::playlist_backend() const { return p_->playlist_backend_.get(); } -PlaylistManager *Application::playlist_manager() const { return p_->playlist_manager_.get(); } -InternetServices *Application::internet_services() const { return p_->internet_services_.get(); } -RadioServices *Application::radio_services() const { return p_->radio_services_.get(); } -AudioScrobbler *Application::scrobbler() const { return p_->scrobbler_.get(); } -LastFMImport *Application::lastfm_import() const { return p_->lastfm_import_.get(); } +SharedPtr Application::album_cover_loader() const { return p_->album_cover_loader_.ptr(); } +SharedPtr Application::cover_providers() const { return p_->cover_providers_.ptr(); } +SharedPtr Application::current_albumcover_loader() const { return p_->current_albumcover_loader_.ptr(); } +SharedPtr Application::lyrics_providers() const { return p_->lyrics_providers_.ptr(); } +SharedPtr Application::playlist_backend() const { return p_->playlist_backend_.ptr(); } +SharedPtr Application::playlist_manager() const { return p_->playlist_manager_.ptr(); } +SharedPtr Application::internet_services() const { return p_->internet_services_.ptr(); } +SharedPtr Application::radio_services() const { return p_->radio_services_.ptr(); } +SharedPtr Application::scrobbler() const { return p_->scrobbler_.ptr(); } +SharedPtr Application::lastfm_import() const { return p_->lastfm_import_.ptr(); } #ifdef HAVE_MOODBAR -MoodbarController *Application::moodbar_controller() const { return p_->moodbar_controller_.get(); } -MoodbarLoader *Application::moodbar_loader() const { return p_->moodbar_loader_.get(); } +SharedPtr Application::moodbar_controller() const { return p_->moodbar_controller_.ptr(); } +SharedPtr Application::moodbar_loader() const { return p_->moodbar_loader_.ptr(); } #endif diff --git a/src/core/application.h b/src/core/application.h index 7f9c9c8e..3e31e8ca 100644 --- a/src/core/application.h +++ b/src/core/application.h @@ -25,12 +25,13 @@ #include "config.h" -#include - #include #include #include +#include "scoped_ptr.h" +#include "shared_ptr.h" + #include "settings/settingsdialog.h" class QThread; @@ -71,40 +72,40 @@ class Application : public QObject { explicit Application(QObject *parent = nullptr); ~Application() override; - TagReaderClient *tag_reader_client() const; - Database *database() const; - TaskManager *task_manager() const; - Player *player() const; - NetworkAccessManager *network() const; - DeviceFinders *device_finders() const; + SharedPtr tag_reader_client() const; + SharedPtr database() const; + SharedPtr task_manager() const; + SharedPtr player() const; + SharedPtr network() const; + SharedPtr device_finders() const; #ifndef Q_OS_WIN - DeviceManager *device_manager() const; + SharedPtr device_manager() const; #endif - SCollection *collection() const; - CollectionBackend *collection_backend() const; + SharedPtr collection() const; + SharedPtr collection_backend() const; CollectionModel *collection_model() const; - PlaylistBackend *playlist_backend() const; - PlaylistManager *playlist_manager() const; + SharedPtr playlist_backend() const; + SharedPtr playlist_manager() const; - CoverProviders *cover_providers() const; - AlbumCoverLoader *album_cover_loader() const; - CurrentAlbumCoverLoader *current_albumcover_loader() const; + SharedPtr cover_providers() const; + SharedPtr album_cover_loader() const; + SharedPtr current_albumcover_loader() const; - LyricsProviders *lyrics_providers() const; + SharedPtr lyrics_providers() const; - AudioScrobbler *scrobbler() const; + SharedPtr scrobbler() const; - InternetServices *internet_services() const; - RadioServices *radio_services() const; + SharedPtr internet_services() const; + SharedPtr radio_services() const; #ifdef HAVE_MOODBAR - MoodbarController *moodbar_controller() const; - MoodbarLoader *moodbar_loader() const; + SharedPtr moodbar_controller() const; + SharedPtr moodbar_loader() const; #endif - LastFMImport *lastfm_import() const; + SharedPtr lastfm_import() const; void Exit(); @@ -127,7 +128,7 @@ class Application : public QObject { void ClearPixmapDiskCache(); private: - std::unique_ptr p_; + ScopedPtr p_; QList threads_; QList wait_for_exit_; diff --git a/src/core/deletefiles.cpp b/src/core/deletefiles.cpp index 2a699c9d..1e94f228 100644 --- a/src/core/deletefiles.cpp +++ b/src/core/deletefiles.cpp @@ -28,6 +28,7 @@ #include #include +#include "shared_ptr.h" #include "taskmanager.h" #include "song.h" #include "deletefiles.h" @@ -35,7 +36,7 @@ const int DeleteFiles::kBatchSize = 50; -DeleteFiles::DeleteFiles(TaskManager *task_manager, std::shared_ptr storage, const bool use_trash, QObject *parent) +DeleteFiles::DeleteFiles(SharedPtr task_manager, SharedPtr storage, const bool use_trash, QObject *parent) : QObject(parent), thread_(nullptr), task_manager_(task_manager), diff --git a/src/core/deletefiles.h b/src/core/deletefiles.h index 0d359010..b1c117de 100644 --- a/src/core/deletefiles.h +++ b/src/core/deletefiles.h @@ -24,11 +24,10 @@ #include "config.h" -#include - #include #include +#include "shared_ptr.h" #include "song.h" class QThread; @@ -39,7 +38,7 @@ class DeleteFiles : public QObject { Q_OBJECT public: - explicit DeleteFiles(TaskManager *task_manager, std::shared_ptr storage, const bool use_trash, QObject *parent = nullptr); + explicit DeleteFiles(SharedPtr task_manager, SharedPtr storage, const bool use_trash, QObject *parent = nullptr); ~DeleteFiles() override; static const int kBatchSize; @@ -56,8 +55,8 @@ class DeleteFiles : public QObject { private: QThread *thread_; QThread *original_thread_; - TaskManager *task_manager_; - std::shared_ptr storage_; + SharedPtr task_manager_; + SharedPtr storage_; SongList songs_; bool use_trash_; diff --git a/src/core/lazy.h b/src/core/lazy.h index b45cc125..de3deb28 100644 --- a/src/core/lazy.h +++ b/src/core/lazy.h @@ -19,7 +19,11 @@ #define LAZY_H #include -#include +#include + +#include "core/logging.h" + +#include "shared_ptr.h" // Helper for lazy initialization of objects. // Usage: @@ -38,6 +42,11 @@ class Lazy { return ptr_.get(); } + SharedPtr ptr() const { + CheckInitialized(); + return ptr_; + } + typename std::add_lvalue_reference::type operator*() const { CheckInitialized(); return *ptr_; @@ -54,12 +63,13 @@ class Lazy { private: void CheckInitialized() const { if (!ptr_) { - ptr_.reset(init_(), [](T*obj) { obj->deleteLater(); }); + ptr_ = SharedPtr(init_(), [](T*obj) { qLog(Debug) << obj << "deleted"; delete obj; }); + qLog(Debug) << &*ptr_ << "created"; } } const std::function init_; - mutable std::shared_ptr ptr_; + mutable SharedPtr ptr_; }; #endif // LAZY_H diff --git a/src/core/macsystemtrayicon.h b/src/core/macsystemtrayicon.h index ce81cf4f..278e96a4 100644 --- a/src/core/macsystemtrayicon.h +++ b/src/core/macsystemtrayicon.h @@ -24,13 +24,12 @@ #include "config.h" -#include - #include #include #include #include +#include "scoped_ptr.h" #include "song.h" class MacSystemTrayIconPrivate; @@ -85,7 +84,7 @@ class SystemTrayIcon : public QObject { void PlayPause(); private: - std::unique_ptr p_; + ScopedPtr p_; QPixmap normal_icon_; QPixmap grey_icon_; diff --git a/src/core/mainwindow.cpp b/src/core/mainwindow.cpp index ec174c23..ed4ab5c9 100644 --- a/src/core/mainwindow.cpp +++ b/src/core/mainwindow.cpp @@ -22,11 +22,11 @@ #include "config.h" #include "version.h" -#include +#include #include #include #include -#include +#include #include #include @@ -79,6 +79,7 @@ #include "mainwindow.h" #include "ui_mainwindow.h" +#include "shared_ptr.h" #include "commandlineoptions.h" #include "mimedata.h" #include "iconloader.h" @@ -166,7 +167,6 @@ #include "settings/playlistsettingspage.h" #ifdef HAVE_SUBSONIC # include "settings/subsonicsettingspage.h" -# include "scrobbler/subsonicscrobbler.h" #endif #ifdef HAVE_TIDAL # include "tidal/tidalservice.h" @@ -212,6 +212,8 @@ # endif #endif // HAVE_QTSPARKLE +using std::make_unique; +using std::make_shared; using namespace std::chrono_literals; const char *MainWindow::kSettingsGroup = "MainWindow"; @@ -238,7 +240,7 @@ constexpr char QTSPARKLE_URL[] = "https://www.strawberrymusicplayer.org/sparkle- # endif #endif -MainWindow::MainWindow(Application *app, std::shared_ptr tray_icon, OSDBase *osd, const CommandlineOptions &options, QWidget *parent) +MainWindow::MainWindow(Application *app, SharedPtr tray_icon, OSDBase *osd, const CommandlineOptions &options, QWidget *parent) : QMainWindow(parent), ui_(new Ui_MainWindow), #ifdef Q_OS_WIN @@ -397,7 +399,7 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic // Start initializing the player qLog(Debug) << "Initializing player"; app_->player()->SetAnalyzer(ui_->analyzer); - app_->player()->SetEqualizer(equalizer_.get()); + app_->player()->SetEqualizer(equalizer_); app_->player()->Init(); EngineChanged(app_->player()->engine()->type()); const uint volume = app_->player()->GetVolume(); @@ -504,17 +506,17 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic file_view_->SetTaskManager(app_->task_manager()); // Action connections - QObject::connect(ui_->action_next_track, &QAction::triggered, app_->player(), &Player::Next); - QObject::connect(ui_->action_previous_track, &QAction::triggered, app_->player(), &Player::Previous); - QObject::connect(ui_->action_play_pause, &QAction::triggered, app_->player(), &Player::PlayPauseHelper); - QObject::connect(ui_->action_stop, &QAction::triggered, app_->player(), &Player::Stop); + QObject::connect(ui_->action_next_track, &QAction::triggered, &*app_->player(), &Player::Next); + QObject::connect(ui_->action_previous_track, &QAction::triggered, &*app_->player(), &Player::Previous); + QObject::connect(ui_->action_play_pause, &QAction::triggered, &*app_->player(), &Player::PlayPauseHelper); + QObject::connect(ui_->action_stop, &QAction::triggered, &*app_->player(), &Player::Stop); QObject::connect(ui_->action_quit, &QAction::triggered, this, &MainWindow::Exit); QObject::connect(ui_->action_stop_after_this_track, &QAction::triggered, this, &MainWindow::StopAfterCurrent); - QObject::connect(ui_->action_mute, &QAction::triggered, app_->player(), &Player::Mute); + QObject::connect(ui_->action_mute, &QAction::triggered, &*app_->player(), &Player::Mute); QObject::connect(ui_->action_clear_playlist, &QAction::triggered, this, &MainWindow::PlaylistClearCurrent); - QObject::connect(ui_->action_remove_duplicates, &QAction::triggered, app_->playlist_manager(), &PlaylistManager::RemoveDuplicatesCurrent); - QObject::connect(ui_->action_remove_unavailable, &QAction::triggered, app_->playlist_manager(), &PlaylistManager::RemoveUnavailableCurrent); + QObject::connect(ui_->action_remove_duplicates, &QAction::triggered, &*app_->playlist_manager(), &PlaylistManager::RemoveDuplicatesCurrent); + QObject::connect(ui_->action_remove_unavailable, &QAction::triggered, &*app_->playlist_manager(), &PlaylistManager::RemoveUnavailableCurrent); QObject::connect(ui_->action_remove_from_playlist, &QAction::triggered, this, &MainWindow::PlaylistRemoveCurrent); QObject::connect(ui_->action_edit_track, &QAction::triggered, this, &MainWindow::EditTracks); QObject::connect(ui_->action_renumber_tracks, &QAction::triggered, this, &MainWindow::RenumberTracks); @@ -528,7 +530,7 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic QObject::connect(ui_->action_toggle_show_sidebar, &QAction::toggled, this, &MainWindow::ToggleSidebar); QObject::connect(ui_->action_about_strawberry, &QAction::triggered, this, &MainWindow::ShowAboutDialog); QObject::connect(ui_->action_about_qt, &QAction::triggered, qApp, &QApplication::aboutQt); - QObject::connect(ui_->action_shuffle, &QAction::triggered, app_->playlist_manager(), &PlaylistManager::ShuffleCurrent); + QObject::connect(ui_->action_shuffle, &QAction::triggered, &*app_->playlist_manager(), &PlaylistManager::ShuffleCurrent); QObject::connect(ui_->action_open_file, &QAction::triggered, this, &MainWindow::AddFile); QObject::connect(ui_->action_open_cd, &QAction::triggered, this, &MainWindow::AddCDTracks); QObject::connect(ui_->action_add_file, &QAction::triggered, this, &MainWindow::AddFile); @@ -542,9 +544,9 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic ui_->action_transcoder->setDisabled(true); #endif QObject::connect(ui_->action_jump, &QAction::triggered, ui_->playlist->view(), &PlaylistView::JumpToCurrentlyPlayingTrack); - QObject::connect(ui_->action_update_collection, &QAction::triggered, app_->collection(), &SCollection::IncrementalScan); - QObject::connect(ui_->action_full_collection_scan, &QAction::triggered, app_->collection(), &SCollection::FullScan); - QObject::connect(ui_->action_abort_collection_scan, &QAction::triggered, app_->collection(), &SCollection::AbortScan); + QObject::connect(ui_->action_update_collection, &QAction::triggered, &*app_->collection(), &SCollection::IncrementalScan); + QObject::connect(ui_->action_full_collection_scan, &QAction::triggered, &*app_->collection(), &SCollection::FullScan); + QObject::connect(ui_->action_abort_collection_scan, &QAction::triggered, &*app_->collection(), &SCollection::AbortScan); #if defined(HAVE_GSTREAMER) QObject::connect(ui_->action_add_files_to_transcoder, &QAction::triggered, this, &MainWindow::AddFilesToTranscoder); ui_->action_add_files_to_transcoder->setIcon(IconLoader::Load("tools-wizard")); @@ -552,9 +554,9 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic ui_->action_add_files_to_transcoder->setDisabled(true); #endif - QObject::connect(ui_->action_toggle_scrobbling, &QAction::triggered, app_->scrobbler(), &AudioScrobbler::ToggleScrobbling); + QObject::connect(ui_->action_toggle_scrobbling, &QAction::triggered, &*app_->scrobbler(), &AudioScrobbler::ToggleScrobbling); QObject::connect(ui_->action_love, &QAction::triggered, this, &MainWindow::Love); - QObject::connect(app_->scrobbler(), &AudioScrobbler::ErrorMessage, this, &MainWindow::ShowErrorDialog); + QObject::connect(&*app_->scrobbler(), &AudioScrobbler::ErrorMessage, this, &MainWindow::ShowErrorDialog); // Playlist view actions ui_->action_next_playlist->setShortcuts(QList() << QKeySequence::fromString("Ctrl+Tab") << QKeySequence::fromString("Ctrl+PgDown")); @@ -584,55 +586,55 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic ui_->stop_button->setMenu(stop_menu); // Player connections - QObject::connect(ui_->volume, &VolumeSlider::valueChanged, app_->player(), &Player::SetVolumeFromSlider); + QObject::connect(ui_->volume, &VolumeSlider::valueChanged, &*app_->player(), &Player::SetVolumeFromSlider); - QObject::connect(app_->player(), &Player::EngineChanged, this, &MainWindow::EngineChanged); - QObject::connect(app_->player(), &Player::Error, this, &MainWindow::ShowErrorDialog); - QObject::connect(app_->player(), &Player::SongChangeRequestProcessed, app_->playlist_manager(), &PlaylistManager::SongChangeRequestProcessed); + QObject::connect(&*app_->player(), &Player::EngineChanged, this, &MainWindow::EngineChanged); + QObject::connect(&*app_->player(), &Player::Error, this, &MainWindow::ShowErrorDialog); + QObject::connect(&*app_->player(), &Player::SongChangeRequestProcessed, &*app_->playlist_manager(), &PlaylistManager::SongChangeRequestProcessed); - QObject::connect(app_->player(), &Player::Paused, this, &MainWindow::MediaPaused); - QObject::connect(app_->player(), &Player::Playing, this, &MainWindow::MediaPlaying); - QObject::connect(app_->player(), &Player::Stopped, this, &MainWindow::MediaStopped); - QObject::connect(app_->player(), &Player::Seeked, this, &MainWindow::Seeked); - QObject::connect(app_->player(), &Player::TrackSkipped, this, &MainWindow::TrackSkipped); - QObject::connect(app_->player(), &Player::VolumeChanged, this, &MainWindow::VolumeChanged); + QObject::connect(&*app_->player(), &Player::Paused, this, &MainWindow::MediaPaused); + QObject::connect(&*app_->player(), &Player::Playing, this, &MainWindow::MediaPlaying); + QObject::connect(&*app_->player(), &Player::Stopped, this, &MainWindow::MediaStopped); + QObject::connect(&*app_->player(), &Player::Seeked, this, &MainWindow::Seeked); + QObject::connect(&*app_->player(), &Player::TrackSkipped, this, &MainWindow::TrackSkipped); + QObject::connect(&*app_->player(), &Player::VolumeChanged, this, &MainWindow::VolumeChanged); - QObject::connect(app_->player(), &Player::Paused, ui_->playlist, &PlaylistContainer::ActivePaused); - QObject::connect(app_->player(), &Player::Playing, ui_->playlist, &PlaylistContainer::ActivePlaying); - QObject::connect(app_->player(), &Player::Stopped, ui_->playlist, &PlaylistContainer::ActiveStopped); + QObject::connect(&*app_->player(), &Player::Paused, ui_->playlist, &PlaylistContainer::ActivePaused); + QObject::connect(&*app_->player(), &Player::Playing, ui_->playlist, &PlaylistContainer::ActivePlaying); + QObject::connect(&*app_->player(), &Player::Stopped, ui_->playlist, &PlaylistContainer::ActiveStopped); - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, osd_, &OSDBase::SongChanged); - QObject::connect(app_->player(), &Player::Paused, osd_, &OSDBase::Paused); - QObject::connect(app_->player(), &Player::Resumed, osd_, &OSDBase::Resumed); - QObject::connect(app_->player(), &Player::Stopped, osd_, &OSDBase::Stopped); - QObject::connect(app_->player(), &Player::PlaylistFinished, osd_, &OSDBase::PlaylistFinished); - QObject::connect(app_->player(), &Player::VolumeChanged, osd_, &OSDBase::VolumeChanged); - QObject::connect(app_->player(), &Player::VolumeChanged, ui_->volume, &VolumeSlider::SetValue); - QObject::connect(app_->player(), &Player::ForceShowOSD, this, &MainWindow::ForceShowOSD); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, osd_, &OSDBase::SongChanged); + QObject::connect(&*app_->player(), &Player::Paused, osd_, &OSDBase::Paused); + QObject::connect(&*app_->player(), &Player::Resumed, osd_, &OSDBase::Resumed); + QObject::connect(&*app_->player(), &Player::Stopped, osd_, &OSDBase::Stopped); + QObject::connect(&*app_->player(), &Player::PlaylistFinished, osd_, &OSDBase::PlaylistFinished); + QObject::connect(&*app_->player(), &Player::VolumeChanged, osd_, &OSDBase::VolumeChanged); + QObject::connect(&*app_->player(), &Player::VolumeChanged, ui_->volume, &VolumeSlider::SetValue); + QObject::connect(&*app_->player(), &Player::ForceShowOSD, this, &MainWindow::ForceShowOSD); - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &MainWindow::SongChanged); - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, app_->player(), &Player::CurrentMetadataChanged); - QObject::connect(app_->playlist_manager(), &PlaylistManager::EditingFinished, this, &MainWindow::PlaylistEditFinished); - QObject::connect(app_->playlist_manager(), &PlaylistManager::Error, this, &MainWindow::ShowErrorDialog); - QObject::connect(app_->playlist_manager(), &PlaylistManager::SummaryTextChanged, ui_->playlist_summary, &QLabel::setText); - QObject::connect(app_->playlist_manager(), &PlaylistManager::PlayRequested, this, &MainWindow::PlayIndex); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &MainWindow::SongChanged); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, &*app_->player(), &Player::CurrentMetadataChanged); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::EditingFinished, this, &MainWindow::PlaylistEditFinished); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::Error, this, &MainWindow::ShowErrorDialog); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::SummaryTextChanged, ui_->playlist_summary, &QLabel::setText); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::PlayRequested, this, &MainWindow::PlayIndex); QObject::connect(ui_->playlist->view(), &PlaylistView::doubleClicked, this, &MainWindow::PlaylistDoubleClick); QObject::connect(ui_->playlist->view(), &PlaylistView::PlayItem, this, &MainWindow::PlayIndex); - QObject::connect(ui_->playlist->view(), &PlaylistView::PlayPause, app_->player(), &Player::PlayPause); + QObject::connect(ui_->playlist->view(), &PlaylistView::PlayPause, &*app_->player(), &Player::PlayPause); QObject::connect(ui_->playlist->view(), &PlaylistView::RightClicked, this, &MainWindow::PlaylistRightClick); - QObject::connect(ui_->playlist->view(), &PlaylistView::SeekForward, app_->player(), &Player::SeekForward); - QObject::connect(ui_->playlist->view(), &PlaylistView::SeekBackward, app_->player(), &Player::SeekBackward); + QObject::connect(ui_->playlist->view(), &PlaylistView::SeekForward, &*app_->player(), &Player::SeekForward); + QObject::connect(ui_->playlist->view(), &PlaylistView::SeekBackward, &*app_->player(), &Player::SeekBackward); QObject::connect(ui_->playlist->view(), &PlaylistView::BackgroundPropertyChanged, this, &MainWindow::RefreshStyleSheet); - QObject::connect(ui_->track_slider, &TrackSlider::ValueChangedSeconds, app_->player(), &Player::SeekTo); - QObject::connect(ui_->track_slider, &TrackSlider::SeekForward, app_->player(), &Player::SeekForward); - QObject::connect(ui_->track_slider, &TrackSlider::SeekBackward, app_->player(), &Player::SeekBackward); - QObject::connect(ui_->track_slider, &TrackSlider::Previous, app_->player(), &Player::Previous); - QObject::connect(ui_->track_slider, &TrackSlider::Next, app_->player(), &Player::Next); + QObject::connect(ui_->track_slider, &TrackSlider::ValueChangedSeconds, &*app_->player(), &Player::SeekTo); + QObject::connect(ui_->track_slider, &TrackSlider::SeekForward, &*app_->player(), &Player::SeekForward); + QObject::connect(ui_->track_slider, &TrackSlider::SeekBackward, &*app_->player(), &Player::SeekBackward); + QObject::connect(ui_->track_slider, &TrackSlider::Previous, &*app_->player(), &Player::Previous); + QObject::connect(ui_->track_slider, &TrackSlider::Next, &*app_->player(), &Player::Next); // Collection connections - QObject::connect(app_->collection(), &SCollection::Error, this, &MainWindow::ShowErrorDialog); + QObject::connect(&*app_->collection(), &SCollection::Error, this, &MainWindow::ShowErrorDialog); QObject::connect(collection_view_->view(), &CollectionView::AddToPlaylistSignal, this, &MainWindow::AddToPlaylist); QObject::connect(collection_view_->view(), &CollectionView::ShowConfigDialog, this, &MainWindow::ShowCollectionConfig); QObject::connect(collection_view_->view(), &CollectionView::Error, this, &MainWindow::ShowErrorDialog); @@ -642,10 +644,10 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic QObject::connect(app_->collection_model(), &CollectionModel::modelAboutToBeReset, collection_view_->view(), &CollectionView::SaveFocus); QObject::connect(app_->collection_model(), &CollectionModel::modelReset, collection_view_->view(), &CollectionView::RestoreFocus); - QObject::connect(app_->task_manager(), &TaskManager::PauseCollectionWatchers, app_->collection(), &SCollection::PauseWatcher); - QObject::connect(app_->task_manager(), &TaskManager::ResumeCollectionWatchers, app_->collection(), &SCollection::ResumeWatcher); + QObject::connect(&*app_->task_manager(), &TaskManager::PauseCollectionWatchers, &*app_->collection(), &SCollection::PauseWatcher); + QObject::connect(&*app_->task_manager(), &TaskManager::ResumeCollectionWatchers, &*app_->collection(), &SCollection::ResumeWatcher); - QObject::connect(app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::AlbumCoverLoaded, this, &MainWindow::AlbumCoverLoaded); + QObject::connect(&*app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::AlbumCoverLoaded, this, &MainWindow::AlbumCoverLoaded); QObject::connect(album_cover_choice_controller_, &AlbumCoverChoiceController::Error, this, &MainWindow::ShowErrorDialog); QObject::connect(album_cover_choice_controller_->cover_from_file_action(), &QAction::triggered, this, &MainWindow::LoadCoverFromFile); QObject::connect(album_cover_choice_controller_->cover_to_file_action(), &QAction::triggered, this, &MainWindow::SaveCoverToFile); @@ -700,8 +702,8 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic 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_->search_view(), &InternetSearchView::AddToPlaylist, this, &MainWindow::AddToPlaylist); - if (TidalService *tidalservice = qobject_cast(app_->internet_services()->ServiceBySource(Song::Source::Tidal))) { - QObject::connect(this, &MainWindow::AuthorizationUrlReceived, tidalservice, &TidalService::AuthorizationUrlReceived); + if (TidalServicePtr tidalservice = app_->internet_services()->Service()) { + QObject::connect(this, &MainWindow::AuthorizationUrlReceived, &*tidalservice, &TidalService::AuthorizationUrlReceived); } #endif @@ -712,8 +714,8 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic QObject::connect(qobuz_view_->search_view(), &InternetSearchView::AddToPlaylist, this, &MainWindow::AddToPlaylist); #endif - QObject::connect(radio_view_, &RadioViewContainer::Refresh, app_->radio_services(), &RadioServices::RefreshChannels); - QObject::connect(radio_view_->view(), &RadioView::GetChannels, app_->radio_services(), &RadioServices::GetChannels); + QObject::connect(radio_view_, &RadioViewContainer::Refresh, &*app_->radio_services(), &RadioServices::RefreshChannels); + QObject::connect(radio_view_->view(), &RadioView::GetChannels, &*app_->radio_services(), &RadioServices::GetChannels); QObject::connect(radio_view_->view(), &RadioView::AddToPlaylistSignal, this, &MainWindow::AddToPlaylist); // Playlist menu @@ -777,22 +779,22 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic QObject::connect(app_->device_manager()->connected_devices_model(), &DeviceStateFilterModel::IsEmptyChanged, playlist_copy_to_device_, &QAction::setDisabled); #endif - QObject::connect(app_->scrobbler(), &AudioScrobbler::ScrobblingEnabledChanged, this, &MainWindow::ScrobblingEnabledChanged); - QObject::connect(app_->scrobbler(), &AudioScrobbler::ScrobbleButtonVisibilityChanged, this, &MainWindow::ScrobbleButtonVisibilityChanged); - QObject::connect(app_->scrobbler(), &AudioScrobbler::LoveButtonVisibilityChanged, this, &MainWindow::LoveButtonVisibilityChanged); + QObject::connect(&*app_->scrobbler()->settings(), &ScrobblerSettings::ScrobblingEnabledChanged, this, &MainWindow::ScrobblingEnabledChanged); + QObject::connect(&*app_->scrobbler()->settings(), &ScrobblerSettings::ScrobbleButtonVisibilityChanged, this, &MainWindow::ScrobbleButtonVisibilityChanged); + QObject::connect(&*app_->scrobbler()->settings(), &ScrobblerSettings::LoveButtonVisibilityChanged, this, &MainWindow::LoveButtonVisibilityChanged); #ifdef Q_OS_MACOS mac::SetApplicationHandler(this); #endif // Tray icon tray_icon_->SetupMenu(ui_->action_previous_track, ui_->action_play_pause, ui_->action_stop, ui_->action_stop_after_this_track, ui_->action_next_track, ui_->action_mute, ui_->action_love, ui_->action_quit); - QObject::connect(tray_icon_.get(), &SystemTrayIcon::PlayPause, app_->player(), &Player::PlayPauseHelper); - QObject::connect(tray_icon_.get(), &SystemTrayIcon::SeekForward, app_->player(), &Player::SeekForward); - QObject::connect(tray_icon_.get(), &SystemTrayIcon::SeekBackward, app_->player(), &Player::SeekBackward); - QObject::connect(tray_icon_.get(), &SystemTrayIcon::NextTrack, app_->player(), &Player::Next); - QObject::connect(tray_icon_.get(), &SystemTrayIcon::PreviousTrack, app_->player(), &Player::Previous); - QObject::connect(tray_icon_.get(), &SystemTrayIcon::ShowHide, this, &MainWindow::ToggleShowHide); - QObject::connect(tray_icon_.get(), &SystemTrayIcon::ChangeVolume, this, &MainWindow::VolumeWheelEvent); + QObject::connect(&*tray_icon_, &SystemTrayIcon::PlayPause, &*app_->player(), &Player::PlayPauseHelper); + QObject::connect(&*tray_icon_, &SystemTrayIcon::SeekForward, &*app_->player(), &Player::SeekForward); + QObject::connect(&*tray_icon_, &SystemTrayIcon::SeekBackward, &*app_->player(), &Player::SeekBackward); + QObject::connect(&*tray_icon_, &SystemTrayIcon::NextTrack, &*app_->player(), &Player::Next); + QObject::connect(&*tray_icon_, &SystemTrayIcon::PreviousTrack, &*app_->player(), &Player::Previous); + QObject::connect(&*tray_icon_, &SystemTrayIcon::ShowHide, this, &MainWindow::ToggleShowHide); + QObject::connect(&*tray_icon_, &SystemTrayIcon::ChangeVolume, this, &MainWindow::VolumeWheelEvent); // Windows 7 thumbbar buttons #ifdef Q_OS_WIN @@ -806,35 +808,35 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic #ifdef HAVE_GLOBALSHORTCUTS // Global shortcuts - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Play, app_->player(), &Player::PlayHelper); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Pause, app_->player(), &Player::Pause); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Play, &*app_->player(), &Player::PlayHelper); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Pause, &*app_->player(), &Player::Pause); QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::PlayPause, ui_->action_play_pause, &QAction::trigger); QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Stop, ui_->action_stop, &QAction::trigger); QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::StopAfter, ui_->action_stop_after_this_track, &QAction::trigger); QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Next, ui_->action_next_track, &QAction::trigger); QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Previous, ui_->action_previous_track, &QAction::trigger); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::IncVolume, app_->player(), &Player::VolumeUp); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::DecVolume, app_->player(), &Player::VolumeDown); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Mute, app_->player(), &Player::Mute); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::SeekForward, app_->player(), &Player::SeekForward); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::SeekBackward, app_->player(), &Player::SeekBackward); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::IncVolume, &*app_->player(), &Player::VolumeUp); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::DecVolume, &*app_->player(), &Player::VolumeDown); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Mute, &*app_->player(), &Player::Mute); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::SeekForward, &*app_->player(), &Player::SeekForward); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::SeekBackward, &*app_->player(), &Player::SeekBackward); QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::ShowHide, this, &MainWindow::ToggleShowHide); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::ShowOSD, app_->player(), &Player::ShowOSD); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::TogglePrettyOSD, app_->player(), &Player::TogglePrettyOSD); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::ToggleScrobbling, app_->scrobbler(), &AudioScrobbler::ToggleScrobbling); - QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Love, app_->scrobbler(), &AudioScrobbler::Love); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::ShowOSD, &*app_->player(), &Player::ShowOSD); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::TogglePrettyOSD, &*app_->player(), &Player::TogglePrettyOSD); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::ToggleScrobbling, &*app_->scrobbler(), &AudioScrobbler::ToggleScrobbling); + QObject::connect(globalshortcuts_manager_, &GlobalShortcutsManager::Love, &*app_->scrobbler(), &AudioScrobbler::Love); #endif // Fancy tabs QObject::connect(ui_->tabs, &FancyTabWidget::CurrentChanged, this, &MainWindow::TabSwitched); // Context - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, context_view_, &ContextView::SongChanged); - QObject::connect(app_->playlist_manager(), &PlaylistManager::SongMetadataChanged, context_view_, &ContextView::SongChanged); - QObject::connect(app_->player(), &Player::PlaylistFinished, context_view_, &ContextView::Stopped); - QObject::connect(app_->player(), &Player::Playing, context_view_, &ContextView::Playing); - QObject::connect(app_->player(), &Player::Stopped, context_view_, &ContextView::Stopped); - QObject::connect(app_->player(), &Player::Error, context_view_, &ContextView::Error); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, context_view_, &ContextView::SongChanged); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::SongMetadataChanged, context_view_, &ContextView::SongChanged); + QObject::connect(&*app_->player(), &Player::PlaylistFinished, context_view_, &ContextView::Stopped); + QObject::connect(&*app_->player(), &Player::Playing, context_view_, &ContextView::Playing); + QObject::connect(&*app_->player(), &Player::Stopped, context_view_, &ContextView::Stopped); + QObject::connect(&*app_->player(), &Player::Error, context_view_, &ContextView::Error); QObject::connect(this, &MainWindow::AlbumCoverReady, context_view_, &ContextView::AlbumCoverLoaded); QObject::connect(this, &MainWindow::SearchCoverInProgress, context_view_->album_widget(), &ContextAlbum::SearchCoverInProgress); QObject::connect(context_view_, &ContextView::AlbumEnabledChanged, this, &MainWindow::TabSwitched); @@ -851,17 +853,17 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic #ifdef HAVE_MOODBAR // Moodbar connections - QObject::connect(app_->moodbar_controller(), &MoodbarController::CurrentMoodbarDataChanged, ui_->track_slider->moodbar_style(), &MoodbarProxyStyle::SetMoodbarData); + QObject::connect(&*app_->moodbar_controller(), &MoodbarController::CurrentMoodbarDataChanged, ui_->track_slider->moodbar_style(), &MoodbarProxyStyle::SetMoodbarData); #endif // Playing widget qLog(Debug) << "Creating playing widget"; ui_->widget_playing->set_ideal_height(ui_->status_bar->sizeHint().height() + ui_->player_controls->sizeHint().height()); - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, ui_->widget_playing, &PlayingWidget::SongChanged); - QObject::connect(app_->player(), &Player::PlaylistFinished, ui_->widget_playing, &PlayingWidget::Stopped); - QObject::connect(app_->player(), &Player::Playing, ui_->widget_playing, &PlayingWidget::Playing); - QObject::connect(app_->player(), &Player::Stopped, ui_->widget_playing, &PlayingWidget::Stopped); - QObject::connect(app_->player(), &Player::Error, ui_->widget_playing, &PlayingWidget::Error); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, ui_->widget_playing, &PlayingWidget::SongChanged); + QObject::connect(&*app_->player(), &Player::PlaylistFinished, ui_->widget_playing, &PlayingWidget::Stopped); + QObject::connect(&*app_->player(), &Player::Playing, ui_->widget_playing, &PlayingWidget::Playing); + QObject::connect(&*app_->player(), &Player::Stopped, ui_->widget_playing, &PlayingWidget::Stopped); + QObject::connect(&*app_->player(), &Player::Error, ui_->widget_playing, &PlayingWidget::Error); QObject::connect(ui_->widget_playing, &PlayingWidget::ShowAboveStatusBarChanged, this, &MainWindow::PlayingWidgetPositionChanged); QObject::connect(this, &MainWindow::AlbumCoverReady, ui_->widget_playing, &PlayingWidget::AlbumCoverLoaded); QObject::connect(this, &MainWindow::SearchCoverInProgress, ui_->widget_playing, &PlayingWidget::SearchCoverInProgress); @@ -891,15 +893,15 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic // Smart playlists QObject::connect(smartplaylists_view_, &SmartPlaylistsViewContainer::AddToPlaylist, this, &MainWindow::AddToPlaylist); - ScrobbleButtonVisibilityChanged(app_->scrobbler()->ScrobbleButton()); - LoveButtonVisibilityChanged(app_->scrobbler()->LoveButton()); - ScrobblingEnabledChanged(app_->scrobbler()->IsEnabled()); + ScrobbleButtonVisibilityChanged(app_->scrobbler()->scrobble_button()); + LoveButtonVisibilityChanged(app_->scrobbler()->love_button()); + ScrobblingEnabledChanged(app_->scrobbler()->enabled()); // Last.fm ImportData - QObject::connect(app_->lastfm_import(), &LastFMImport::Finished, lastfm_import_dialog_, &LastFMImportDialog::Finished); - QObject::connect(app_->lastfm_import(), &LastFMImport::FinishedWithError, lastfm_import_dialog_, &LastFMImportDialog::FinishedWithError); - QObject::connect(app_->lastfm_import(), &LastFMImport::UpdateTotal, lastfm_import_dialog_, &LastFMImportDialog::UpdateTotal); - QObject::connect(app_->lastfm_import(), &LastFMImport::UpdateProgress, lastfm_import_dialog_, &LastFMImportDialog::UpdateProgress); + QObject::connect(&*app_->lastfm_import(), &LastFMImport::Finished, lastfm_import_dialog_, &LastFMImportDialog::Finished); + QObject::connect(&*app_->lastfm_import(), &LastFMImport::FinishedWithError, lastfm_import_dialog_, &LastFMImportDialog::FinishedWithError); + QObject::connect(&*app_->lastfm_import(), &LastFMImport::UpdateTotal, lastfm_import_dialog_, &LastFMImportDialog::UpdateTotal); + QObject::connect(&*app_->lastfm_import(), &LastFMImport::UpdateProgress, lastfm_import_dialog_, &LastFMImportDialog::UpdateProgress); // Load settings qLog(Debug) << "Loading settings"; @@ -1008,7 +1010,7 @@ MainWindow::MainWindow(Application *app, std::shared_ptr tray_ic if (!options.contains_play_options()) { LoadPlaybackStatus(); } - if (app_->scrobbler()->IsEnabled() && !app_->scrobbler()->IsOffline()) { + if (app_->scrobbler()->enabled() && !app_->scrobbler()->offline()) { app_->scrobbler()->Submit(); } @@ -1134,7 +1136,6 @@ void MainWindow::ReloadSettings() { else { ui_->tabs->DisableTab(subsonic_view_); } - app_->scrobbler()->Service()->ReloadSettings(); #endif #ifdef HAVE_TIDAL @@ -1239,7 +1240,7 @@ void MainWindow::Exit() { else { if (app_->player()->engine()->is_fadeout_enabled()) { // To shut down the application when fadeout will be finished - QObject::connect(app_->player()->engine(), &EngineBase::FadeoutFinishedSignal, this, &MainWindow::DoExit); + QObject::connect(&*app_->player()->engine(), &EngineBase::FadeoutFinishedSignal, this, &MainWindow::DoExit); if (app_->player()->GetState() == EngineBase::State::Playing) { app_->player()->Stop(); ignore_close_ = true; @@ -1355,7 +1356,7 @@ void MainWindow::SendNowPlaying() { // Send now playing to scrobble services Playlist *playlist = app_->playlist_manager()->active(); - if (app_->scrobbler()->IsEnabled() && playlist && playlist->current_item() && playlist->current_item()->Metadata().is_metadata_good()) { + if (app_->scrobbler()->enabled() && playlist && playlist->current_item() && playlist->current_item()->Metadata().is_metadata_good()) { app_->scrobbler()->UpdateNowPlaying(playlist->current_item()->Metadata()); ui_->action_love->setEnabled(true); ui_->button_love->setEnabled(true); @@ -1480,8 +1481,8 @@ void MainWindow::LoadPlaybackStatus() { s.endGroup(); if (resume_playback && playback_state != EngineBase::State::Empty && playback_state != EngineBase::State::Idle) { - std::shared_ptr connection = std::make_shared(); - *connection = QObject::connect(app_->playlist_manager(), &PlaylistManager::AllPlaylistsLoaded, this, [this, connection]() { + SharedPtr connection = make_shared(); + *connection = QObject::connect(&*app_->playlist_manager(), &PlaylistManager::AllPlaylistsLoaded, this, [this, connection]() { QObject::disconnect(*connection); QTimer::singleShot(400ms, this, &MainWindow::ResumePlayback); }); @@ -1504,10 +1505,10 @@ void MainWindow::ResumePlayback() { // Set active to current to resume playback on correct playlist. app_->playlist_manager()->SetActiveToCurrent(); if (playback_state == EngineBase::State::Paused) { - std::shared_ptr connection = std::make_shared(); - *connection = QObject::connect(app_->player(), &Player::Playing, app_->player(), [this, connection]() { + SharedPtr connection = make_shared(); + *connection = QObject::connect(&*app_->player(), &Player::Playing, &*app_->player(), [this, connection]() { QObject::disconnect(*connection); - QTimer::singleShot(300, app_->player(), &Player::PlayPauseHelper); + QTimer::singleShot(300, &*app_->player(), &Player::PlayPauseHelper); }); } app_->player()->Play(playback_position * kNsecPerSec); @@ -1682,7 +1683,7 @@ void MainWindow::UpdateTrackPosition() { if (position % 10 == 0) tray_icon_->SetProgress(static_cast(static_cast(position) / static_cast(length) * 100.0)); // Send Scrobble - if (app_->scrobbler()->IsEnabled() && item->Metadata().is_metadata_good()) { + if (app_->scrobbler()->enabled() && item->Metadata().is_metadata_good()) { Playlist *playlist = app_->playlist_manager()->active(); if (playlist && !playlist->scrobbled()) { const qint64 scrobble_point = (playlist->scrobble_point_nanosec() / kNsecPerSec); @@ -2926,15 +2927,15 @@ void MainWindow::AutoCompleteTags() { // Create the tag fetching stuff if it hasn't been already if (!tag_fetcher_) { - tag_fetcher_ = std::make_unique(app_->network()); - track_selection_dialog_ = std::make_unique(); + tag_fetcher_ = make_unique(app_->network()); + track_selection_dialog_ = make_unique(); track_selection_dialog_->set_save_on_close(true); - QObject::connect(tag_fetcher_.get(), &TagFetcher::ResultAvailable, track_selection_dialog_.get(), &TrackSelectionDialog::FetchTagFinished, Qt::QueuedConnection); - QObject::connect(tag_fetcher_.get(), &TagFetcher::Progress, track_selection_dialog_.get(), &TrackSelectionDialog::FetchTagProgress); - QObject::connect(track_selection_dialog_.get(), &TrackSelectionDialog::accepted, this, &MainWindow::AutoCompleteTagsAccepted); - QObject::connect(track_selection_dialog_.get(), &TrackSelectionDialog::finished, tag_fetcher_.get(), &TagFetcher::Cancel); - QObject::connect(track_selection_dialog_.get(), &TrackSelectionDialog::Error, this, &MainWindow::ShowErrorDialog); + QObject::connect(&*tag_fetcher_, &TagFetcher::ResultAvailable, &*track_selection_dialog_, &TrackSelectionDialog::FetchTagFinished, Qt::QueuedConnection); + QObject::connect(&*tag_fetcher_, &TagFetcher::Progress, &*track_selection_dialog_, &TrackSelectionDialog::FetchTagProgress); + QObject::connect(&*track_selection_dialog_, &TrackSelectionDialog::accepted, this, &MainWindow::AutoCompleteTagsAccepted); + QObject::connect(&*track_selection_dialog_, &TrackSelectionDialog::finished, &*tag_fetcher_, &TagFetcher::Cancel); + QObject::connect(&*track_selection_dialog_, &TrackSelectionDialog::Error, this, &MainWindow::ShowErrorDialog); } // Get the selected songs and start fetching tags for them @@ -3104,14 +3105,14 @@ void MainWindow::GetCoverAutomatically() { } void MainWindow::ScrobblingEnabledChanged(const bool value) { - if (app_->scrobbler()->ScrobbleButton()) SetToggleScrobblingIcon(value); + if (app_->scrobbler()->scrobble_button()) SetToggleScrobblingIcon(value); } void MainWindow::ScrobbleButtonVisibilityChanged(const bool value) { ui_->button_scrobble->setVisible(value); ui_->action_toggle_scrobbling->setVisible(value); - if (value) SetToggleScrobblingIcon(app_->scrobbler()->IsEnabled()); + if (value) SetToggleScrobblingIcon(app_->scrobbler()->enabled()); } @@ -3180,7 +3181,7 @@ void MainWindow::PlaylistDelete() { app_->player()->Next(); } - std::shared_ptr storage = std::make_shared(Song::Source::LocalFile, "/"); + SharedPtr storage = make_shared(Song::Source::LocalFile, "/"); DeleteFiles *delete_files = new DeleteFiles(app_->task_manager(), storage, true); //QObject::connect(delete_files, &DeleteFiles::Finished, this, &MainWindow::DeleteFinished); delete_files->Start(selected_songs); diff --git a/src/core/mainwindow.h b/src/core/mainwindow.h index 1c53ae40..31a71017 100644 --- a/src/core/mainwindow.h +++ b/src/core/mainwindow.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -48,6 +46,8 @@ #include #include +#include "scoped_ptr.h" +#include "shared_ptr.h" #include "lazy.h" #include "platforminterface.h" #include "song.h" @@ -104,7 +104,7 @@ class MainWindow : public QMainWindow, public PlatformInterface { Q_OBJECT public: - explicit MainWindow(Application *app, std::shared_ptr tray_icon, OSDBase *osd, const CommandlineOptions &options, QWidget *parent = nullptr); + explicit MainWindow(Application *app, SharedPtr tray_icon, OSDBase *osd, const CommandlineOptions &options, QWidget *parent = nullptr); ~MainWindow() override; static const char *kSettingsGroup; @@ -297,7 +297,7 @@ class MainWindow : public QMainWindow, public PlatformInterface { #endif Application *app_; - std::shared_ptr tray_icon_; + SharedPtr tray_icon_; OSDBase *osd_; Lazy about_dialog_; Lazy console_; @@ -318,7 +318,7 @@ class MainWindow : public QMainWindow, public PlatformInterface { Lazy error_dialog_; Lazy settings_dialog_; Lazy cover_manager_; - std::unique_ptr equalizer_; + SharedPtr equalizer_; Lazy organize_dialog_; #ifdef HAVE_GSTREAMER Lazy transcode_dialog_; @@ -326,9 +326,9 @@ class MainWindow : public QMainWindow, public PlatformInterface { Lazy add_stream_dialog_; #ifdef HAVE_MUSICBRAINZ - std::unique_ptr tag_fetcher_; + ScopedPtr tag_fetcher_; #endif - std::unique_ptr track_selection_dialog_; + ScopedPtr track_selection_dialog_; PlaylistItemPtrList autocomplete_tag_items_; SmartPlaylistsViewContainer *smartplaylists_view_; diff --git a/src/core/mergedproxymodel.h b/src/core/mergedproxymodel.h index 2ab1fa89..136b3180 100644 --- a/src/core/mergedproxymodel.h +++ b/src/core/mergedproxymodel.h @@ -24,7 +24,6 @@ #include "config.h" -#include #include #include @@ -36,6 +35,8 @@ #include #include +#include "core/scoped_ptr.h" + class QMimeData; std::size_t hash_value(const QModelIndex &idx); @@ -112,7 +113,7 @@ class MergedProxyModel : public QAbstractProxyModel { QHash old_merge_points_; - std::unique_ptr p_; + ScopedPtr p_; }; #endif // MERGEDPROXYMODEL_H diff --git a/src/core/mpris2.cpp b/src/core/mpris2.cpp index 04119d83..21da9225 100644 --- a/src/core/mpris2.cpp +++ b/src/core/mpris2.cpp @@ -118,16 +118,16 @@ Mpris2::Mpris2(Application *app, QObject *parent) return; } - QObject::connect(app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::AlbumCoverLoaded, this, &Mpris2::AlbumCoverLoaded); + QObject::connect(&*app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::AlbumCoverLoaded, this, &Mpris2::AlbumCoverLoaded); - QObject::connect(app_->player()->engine(), &EngineBase::StateChanged, this, &Mpris2::EngineStateChanged); - QObject::connect(app_->player(), &Player::VolumeChanged, this, &Mpris2::VolumeChanged); - QObject::connect(app_->player(), &Player::Seeked, this, &Mpris2::Seeked); + QObject::connect(&*app_->player()->engine(), &EngineBase::StateChanged, this, &Mpris2::EngineStateChanged); + QObject::connect(&*app_->player(), &Player::VolumeChanged, this, &Mpris2::VolumeChanged); + QObject::connect(&*app_->player(), &Player::Seeked, this, &Mpris2::Seeked); - QObject::connect(app_->playlist_manager(), &PlaylistManager::PlaylistManagerInitialized, this, &Mpris2::PlaylistManagerInitialized); - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &Mpris2::CurrentSongChanged); - QObject::connect(app_->playlist_manager(), &PlaylistManager::PlaylistChanged, this, &Mpris2::PlaylistChangedSlot); - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentChanged, this, &Mpris2::PlaylistCollectionChanged); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::PlaylistManagerInitialized, this, &Mpris2::PlaylistManagerInitialized); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &Mpris2::CurrentSongChanged); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::PlaylistChanged, this, &Mpris2::PlaylistChangedSlot); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentChanged, this, &Mpris2::PlaylistCollectionChanged); app_name_[0] = app_name_[0].toUpper(); diff --git a/src/core/musicstorage.h b/src/core/musicstorage.h index edb4fa5f..bf90c1d0 100644 --- a/src/core/musicstorage.h +++ b/src/core/musicstorage.h @@ -35,6 +35,7 @@ #include #include +#include "shared_ptr.h" #include "song.h" class MusicStorage { @@ -102,6 +103,6 @@ class MusicStorage { }; Q_DECLARE_METATYPE(MusicStorage*) -Q_DECLARE_METATYPE(std::shared_ptr) +Q_DECLARE_METATYPE(SharedPtr) #endif // MUSICSTORAGE_H diff --git a/src/core/player.cpp b/src/core/player.cpp index 406e15a5..96e7bdf9 100644 --- a/src/core/player.cpp +++ b/src/core/player.cpp @@ -38,6 +38,8 @@ #include "core/logging.h" #include "utilities/timeconstants.h" +#include "scoped_ptr.h" +#include "shared_ptr.h" #include "song.h" #include "urlhandler.h" #include "application.h" @@ -65,6 +67,8 @@ #include "settings/behavioursettingspage.h" #include "settings/playlistsettingspage.h" +using std::make_shared; + const char *Player::kSettingsGroup = "Player"; Player::Player(Application *app, QObject *parent) @@ -108,7 +112,7 @@ EngineBase::Type Player::CreateEngine(EngineBase::Type enginetype) { #ifdef HAVE_GSTREAMER case EngineBase::Type::GStreamer:{ use_enginetype=EngineBase::Type::GStreamer; - std::unique_ptr gst_engine(new GstEngine(app_->task_manager())); + ScopedPtr gst_engine(new GstEngine(app_->task_manager())); gst_engine->SetStartup(gst_startup_); engine_.reset(gst_engine.release()); break; @@ -117,7 +121,7 @@ EngineBase::Type Player::CreateEngine(EngineBase::Type enginetype) { #ifdef HAVE_VLC case EngineBase::Type::VLC: use_enginetype = EngineBase::Type::VLC; - engine_ = std::make_shared(app_->task_manager()); + engine_ = make_shared(app_->task_manager()); break; #endif default: @@ -163,23 +167,23 @@ void Player::Init() { qFatal("Error initializing audio engine"); } - analyzer_->SetEngine(engine_.get()); + analyzer_->SetEngine(engine_); - QObject::connect(engine_.get(), &EngineBase::Error, this, &Player::Error); - QObject::connect(engine_.get(), &EngineBase::FatalError, this, &Player::FatalError); - QObject::connect(engine_.get(), &EngineBase::ValidSongRequested, this, &Player::ValidSongRequested); - QObject::connect(engine_.get(), &EngineBase::InvalidSongRequested, this, &Player::InvalidSongRequested); - QObject::connect(engine_.get(), &EngineBase::StateChanged, this, &Player::EngineStateChanged); - QObject::connect(engine_.get(), &EngineBase::TrackAboutToEnd, this, &Player::TrackAboutToEnd); - QObject::connect(engine_.get(), &EngineBase::TrackEnded, this, &Player::TrackEnded); - QObject::connect(engine_.get(), &EngineBase::MetaData, this, &Player::EngineMetadataReceived); - QObject::connect(engine_.get(), &EngineBase::VolumeChanged, this, &Player::SetVolumeFromEngine); + QObject::connect(&*engine_, &EngineBase::Error, this, &Player::Error); + QObject::connect(&*engine_, &EngineBase::FatalError, this, &Player::FatalError); + QObject::connect(&*engine_, &EngineBase::ValidSongRequested, this, &Player::ValidSongRequested); + QObject::connect(&*engine_, &EngineBase::InvalidSongRequested, this, &Player::InvalidSongRequested); + QObject::connect(&*engine_, &EngineBase::StateChanged, this, &Player::EngineStateChanged); + QObject::connect(&*engine_, &EngineBase::TrackAboutToEnd, this, &Player::TrackAboutToEnd); + QObject::connect(&*engine_, &EngineBase::TrackEnded, this, &Player::TrackEnded); + QObject::connect(&*engine_, &EngineBase::MetaData, this, &Player::EngineMetadataReceived); + QObject::connect(&*engine_, &EngineBase::VolumeChanged, this, &Player::SetVolumeFromEngine); // Equalizer - QObject::connect(equalizer_, &Equalizer::StereoBalancerEnabledChanged, app_->player()->engine(), &EngineBase::SetStereoBalancerEnabled); - QObject::connect(equalizer_, &Equalizer::StereoBalanceChanged, app_->player()->engine(), &EngineBase::SetStereoBalance); - QObject::connect(equalizer_, &Equalizer::EqualizerEnabledChanged, app_->player()->engine(), &EngineBase::SetEqualizerEnabled); - QObject::connect(equalizer_, &Equalizer::EqualizerParametersChanged, app_->player()->engine(), &EngineBase::SetEqualizerParameters); + QObject::connect(&*equalizer_, &Equalizer::StereoBalancerEnabledChanged, &*app_->player()->engine(), &EngineBase::SetStereoBalancerEnabled); + QObject::connect(&*equalizer_, &Equalizer::StereoBalanceChanged, &*app_->player()->engine(), &EngineBase::SetStereoBalance); + QObject::connect(&*equalizer_, &Equalizer::EqualizerEnabledChanged, &*app_->player()->engine(), &EngineBase::SetEqualizerEnabled); + QObject::connect(&*equalizer_, &Equalizer::EqualizerParametersChanged, &*app_->player()->engine(), &EngineBase::SetEqualizerParameters); engine_->SetStereoBalancerEnabled(equalizer_->is_stereo_balancer_enabled()); engine_->SetStereoBalance(equalizer_->stereo_balance()); diff --git a/src/core/player.h b/src/core/player.h index 449ca31a..8c51224e 100644 --- a/src/core/player.h +++ b/src/core/player.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -33,6 +31,7 @@ #include #include +#include "shared_ptr.h" #include "urlhandler.h" #include "engine/enginebase.h" #include "engine/enginemetadata.h" @@ -54,7 +53,7 @@ class PlayerInterface : public QObject { public: explicit PlayerInterface(QObject *parent = nullptr) : QObject(parent) {} - virtual EngineBase *engine() const = 0; + virtual SharedPtr engine() const = 0; virtual EngineBase::State GetState() const = 0; virtual uint GetVolume() const = 0; @@ -130,14 +129,14 @@ class Player : public PlayerInterface { Q_OBJECT public: - explicit Player(Application *app, QObject *parent); + explicit Player(Application *app, QObject *parent = nullptr); static const char *kSettingsGroup; EngineBase::Type CreateEngine(EngineBase::Type Type); void Init(); - EngineBase *engine() const override { return engine_.get(); } + SharedPtr engine() const override { return engine_; } EngineBase::State GetState() const override { return last_state_; } uint GetVolume() const override; @@ -152,7 +151,7 @@ class Player : public PlayerInterface { bool PreviousWouldRestartTrack() const; void SetAnalyzer(AnalyzerContainer *analyzer) { analyzer_ = analyzer; } - void SetEqualizer(Equalizer *equalizer) { equalizer_ = equalizer; } + void SetEqualizer(SharedPtr equalizer) { equalizer_ = equalizer; } public slots: void ReloadSettings() override; @@ -218,12 +217,12 @@ class Player : public PlayerInterface { private: Application *app_; - std::shared_ptr engine_; + SharedPtr engine_; #ifdef HAVE_GSTREAMER GstStartup *gst_startup_; #endif AnalyzerContainer *analyzer_; - Equalizer *equalizer_; + SharedPtr equalizer_; PlaylistItemPtr current_item_; diff --git a/src/core/scoped_ptr.h b/src/core/scoped_ptr.h new file mode 100644 index 00000000..2b8941ba --- /dev/null +++ b/src/core/scoped_ptr.h @@ -0,0 +1,28 @@ +/* + * Strawberry Music Player + * Copyright 2023, Jonas Kvinge + * + * Strawberry is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Strawberry is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Strawberry. If not, see . + * + */ + +#ifndef SCOPED_PTR_H +#define SCOPED_PTR_H + +#include + +template > +using ScopedPtr = std::unique_ptr; + +#endif // SCOPED_PTR_H diff --git a/src/core/scopedwchararray.h b/src/core/scopedwchararray.h index ac2e0c24..e796adb4 100644 --- a/src/core/scopedwchararray.h +++ b/src/core/scopedwchararray.h @@ -21,11 +21,11 @@ #ifndef SCOPEDWCHARARRAY_H #define SCOPEDWCHARARRAY_H -#include - #include #include +#include "scoped_ptr.h" + class ScopedWCharArray { public: explicit ScopedWCharArray(const QString &str); @@ -42,7 +42,7 @@ class ScopedWCharArray { Q_DISABLE_COPY(ScopedWCharArray) qint64 chars_; - std::unique_ptr data_; + ScopedPtr data_; }; #endif // SCOPEDWCHARARRAY_H diff --git a/src/core/shared_ptr.h b/src/core/shared_ptr.h new file mode 100644 index 00000000..b72da637 --- /dev/null +++ b/src/core/shared_ptr.h @@ -0,0 +1,28 @@ +/* + * Strawberry Music Player + * Copyright 2023, Jonas Kvinge + * + * Strawberry is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Strawberry is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Strawberry. If not, see . + * + */ + +#ifndef SHARED_PTR_H +#define SHARED_PTR_H + +#include + +template +using SharedPtr = std::shared_ptr; + +#endif // SHARED_PTR_H diff --git a/src/core/songloader.cpp b/src/core/songloader.cpp index 82a7f8a3..66839c3a 100644 --- a/src/core/songloader.cpp +++ b/src/core/songloader.cpp @@ -21,7 +21,6 @@ #include "config.h" -#include #include #ifdef HAVE_GSTREAMER @@ -44,6 +43,7 @@ #include "core/logging.h" +#include "shared_ptr.h" #include "signalchecker.h" #include "player.h" #include "song.h" @@ -65,13 +65,13 @@ QSet SongLoader::sRawUriSchemes; const int SongLoader::kDefaultTimeout = 5000; -SongLoader::SongLoader(CollectionBackendInterface *collection, const Player *player, QObject *parent) +SongLoader::SongLoader(SharedPtr collection_backend, const SharedPtr player, QObject *parent) : QObject(parent), player_(player), - collection_(collection), + collection_backend_(collection_backend), timeout_timer_(new QTimer(this)), - playlist_parser_(new PlaylistParser(collection, this)), - cue_parser_(new CueParser(collection, this)), + playlist_parser_(new PlaylistParser(collection_backend, this)), + cue_parser_(new CueParser(collection_backend, this)), parser_(nullptr), state_(State::WaitingForType), timeout_(kDefaultTimeout), @@ -233,10 +233,10 @@ SongLoader::Result SongLoader::LoadLocal(const QString &filename) { // Search in the database. QUrl url = QUrl::fromLocalFile(filename); - QMutexLocker l(collection_->db()->Mutex()); - QSqlDatabase db(collection_->db()->Connect()); + QMutexLocker l(collection_backend_->db()->Mutex()); + QSqlDatabase db(collection_backend_->db()->Connect()); - CollectionQuery query(db, collection_->songs_table(), collection_->fts_table()); + CollectionQuery query(db, collection_backend_->songs_table(), collection_backend_->fts_table()); query.SetColumnSpec("%songs_table.ROWID, " + Song::kColumnSpec); query.AddWhere("url", url.toEncoded()); @@ -348,7 +348,7 @@ void SongLoader::EffectiveSongLoad(Song *song) { } // First, try to get the song from the collection - Song collection_song = collection_->GetSongByUrl(song->url()); + Song collection_song = collection_backend_->GetSongByUrl(song->url()); if (collection_song.is_valid()) { *song = collection_song; } @@ -429,7 +429,7 @@ void SongLoader::StopTypefind() { #ifdef HAVE_GSTREAMER // Destroy the pipeline if (pipeline_) { - gst_element_set_state(pipeline_.get(), GST_STATE_NULL); + gst_element_set_state(&*pipeline_, GST_STATE_NULL); CleanupPipeline(); } #endif @@ -471,7 +471,7 @@ SongLoader::Result SongLoader::LoadRemote() { ScheduleTimeoutAsync(); // Create the pipeline - it gets unreffed if it goes out of scope - std::shared_ptr pipeline(gst_pipeline_new(nullptr), std::bind(&gst_object_unref, std::placeholders::_1)); + SharedPtr pipeline(gst_pipeline_new(nullptr), std::bind(&gst_object_unref, std::placeholders::_1)); // Create the source element automatically based on the URL GstElement *source = gst_element_make_from_uri(GST_URI_SRC, url_.toEncoded().constData(), nullptr, nullptr); @@ -479,7 +479,7 @@ SongLoader::Result SongLoader::LoadRemote() { errors_ << tr("Couldn't create GStreamer source element for %1").arg(url_.toString()); return Result::Error; } - gst_bin_add(GST_BIN(pipeline.get()), source); + gst_bin_add(GST_BIN(&*pipeline), source); g_object_set(source, "ssl-strict", FALSE, nullptr); @@ -489,14 +489,14 @@ SongLoader::Result SongLoader::LoadRemote() { errors_ << tr("Couldn't create GStreamer typefind element for %1").arg(url_.toString()); return Result::Error; } - gst_bin_add(GST_BIN(pipeline.get()), typefind); + gst_bin_add(GST_BIN(&*pipeline), typefind); fakesink_ = gst_element_factory_make("fakesink", nullptr); if (!fakesink_) { errors_ << tr("Couldn't create GStreamer fakesink element for %1").arg(url_.toString()); return Result::Error; } - gst_bin_add(GST_BIN(pipeline.get()), fakesink_); + gst_bin_add(GST_BIN(&*pipeline), fakesink_); if (!gst_element_link_many(source, typefind, fakesink_, nullptr)) { errors_ << tr("Couldn't link GStreamer source, typefind and fakesink elements for %1").arg(url_.toString()); @@ -505,7 +505,7 @@ SongLoader::Result SongLoader::LoadRemote() { // Connect callbacks CHECKED_GCONNECT(typefind, "have-type", &TypeFound, this); - GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline.get())); + GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(&*pipeline)); if (bus) { gst_bus_set_sync_handler(bus, BusCallbackSync, this, nullptr); gst_bus_add_watch(bus, BusWatchCallback, this); @@ -524,7 +524,7 @@ SongLoader::Result SongLoader::LoadRemote() { // Start "playing" pipeline_ = pipeline; - gst_element_set_state(pipeline.get(), GST_STATE_PLAYING); + gst_element_set_state(&*pipeline, GST_STATE_PLAYING); // Wait until loading is finished loop.exec(); @@ -718,7 +718,7 @@ bool SongLoader::IsPipelinePlaying() { GstState state = GST_STATE_NULL; GstState pending_state = GST_STATE_NULL; - GstStateChangeReturn ret = gst_element_get_state(pipeline_.get(), &state, &pending_state, GST_SECOND); + GstStateChangeReturn ret = gst_element_get_state(&*pipeline_, &state, &pending_state, GST_SECOND); if (ret == GST_STATE_CHANGE_ASYNC && pending_state == GST_STATE_PLAYING) { // We're still on the way to playing @@ -763,7 +763,7 @@ void SongLoader::CleanupPipeline() { if (pipeline_) { - gst_element_set_state(pipeline_.get(), GST_STATE_NULL); + gst_element_set_state(&*pipeline_, GST_STATE_NULL); if (fakesink_ && buffer_probe_cb_id_ != 0) { GstPad *pad = gst_element_get_static_pad(fakesink_, "src"); @@ -774,7 +774,7 @@ void SongLoader::CleanupPipeline() { } { - GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline_.get())); + GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(&*pipeline_)); if (bus) { gst_bus_remove_watch(bus); gst_bus_set_sync_handler(bus, nullptr, nullptr, nullptr); diff --git a/src/core/songloader.h b/src/core/songloader.h index 1bfddab8..5ccceae5 100644 --- a/src/core/songloader.h +++ b/src/core/songloader.h @@ -41,6 +41,7 @@ #include #include +#include "shared_ptr.h" #include "song.h" class QTimer; @@ -58,7 +59,7 @@ class SongLoader : public QObject { Q_OBJECT public: - explicit SongLoader(CollectionBackendInterface *collection, const Player *player, QObject *parent = nullptr); + explicit SongLoader(SharedPtr collection_backend, const SharedPtr player, QObject *parent = nullptr); ~SongLoader() override; enum class Result { @@ -143,8 +144,8 @@ class SongLoader : public QObject { QUrl url_; SongList songs_; - const Player *player_; - CollectionBackendInterface *collection_; + const SharedPtr player_; + SharedPtr collection_backend_; QTimer *timeout_timer_; PlaylistParser *playlist_parser_; CueParser *cue_parser_; @@ -158,7 +159,7 @@ class SongLoader : public QObject { int timeout_; #ifdef HAVE_GSTREAMER - std::shared_ptr pipeline_; + SharedPtr pipeline_; GstElement *fakesink_; gulong buffer_probe_cb_id_; #endif diff --git a/src/core/stylesheetloader.cpp b/src/core/stylesheetloader.cpp index af1fd2bb..0b2ebd1a 100644 --- a/src/core/stylesheetloader.cpp +++ b/src/core/stylesheetloader.cpp @@ -35,9 +35,12 @@ #include #include +#include "shared_ptr.h" #include "core/logging.h" #include "stylesheetloader.h" +using std::make_shared; + StyleSheetLoader::StyleSheetLoader(QObject *parent) : QObject(parent) {} void StyleSheetLoader::SetStyleSheet(QWidget *widget, const QString &filename) { @@ -57,7 +60,7 @@ void StyleSheetLoader::SetStyleSheet(QWidget *widget, const QString &filename) { } file.close(); - std::shared_ptr styledata = std::make_shared(); + SharedPtr styledata = make_shared(); styledata->filename_ = filename; styledata->stylesheet_template_ = stylesheet; styledata->stylesheet_current_ = widget->styleSheet(); @@ -68,7 +71,7 @@ void StyleSheetLoader::SetStyleSheet(QWidget *widget, const QString &filename) { } -void StyleSheetLoader::UpdateStyleSheet(QWidget *widget, std::shared_ptr styledata) { +void StyleSheetLoader::UpdateStyleSheet(QWidget *widget, SharedPtr styledata) { QString stylesheet = styledata->stylesheet_template_; diff --git a/src/core/stylesheetloader.h b/src/core/stylesheetloader.h index 7e21e95d..b48302fe 100644 --- a/src/core/stylesheetloader.h +++ b/src/core/stylesheetloader.h @@ -24,14 +24,14 @@ #include "config.h" -#include - #include #include #include #include #include +#include "shared_ptr.h" + class QWidget; class QEvent; @@ -58,11 +58,11 @@ class StyleSheetLoader : public QObject { }; private: - void UpdateStyleSheet(QWidget *widget, std::shared_ptr styledata); + void UpdateStyleSheet(QWidget *widget, SharedPtr styledata); static void ReplaceColor(QString *css, const QString &name, const QPalette &palette, const QPalette::ColorRole role); private: - QHash> styledata_; + QHash> styledata_; }; #endif // STYLESHEETLOADER_H diff --git a/src/covermanager/albumcoverchoicecontroller.cpp b/src/covermanager/albumcoverchoicecontroller.cpp index f29ad53f..60d0ede9 100644 --- a/src/covermanager/albumcoverchoicecontroller.cpp +++ b/src/covermanager/albumcoverchoicecontroller.cpp @@ -577,7 +577,7 @@ void AlbumCoverChoiceController::SaveArtManualToSong(Song *song, const QUrl &art case Song::Source::Tidal: case Song::Source::Qobuz: case Song::Source::Subsonic: - InternetService *service = app_->internet_services()->ServiceBySource(song->source()); + InternetServicePtr service = app_->internet_services()->ServiceBySource(song->source()); if (!service) break; if (service->artists_collection_backend()) { service->artists_collection_backend()->UpdateManualAlbumArtAsync(song->effective_albumartist(), song->album(), art_manual); diff --git a/src/covermanager/albumcoverfetcher.cpp b/src/covermanager/albumcoverfetcher.cpp index 6caff8e9..0f16452c 100644 --- a/src/covermanager/albumcoverfetcher.cpp +++ b/src/covermanager/albumcoverfetcher.cpp @@ -28,6 +28,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/song.h" #include "albumcoverfetcher.h" @@ -37,7 +38,7 @@ using namespace std::chrono_literals; const int AlbumCoverFetcher::kMaxConcurrentRequests = 5; -AlbumCoverFetcher::AlbumCoverFetcher(CoverProviders *cover_providers, NetworkAccessManager *network, QObject *parent) +AlbumCoverFetcher::AlbumCoverFetcher(SharedPtr cover_providers, SharedPtr network, QObject *parent) : QObject(parent), cover_providers_(cover_providers), network_(network), diff --git a/src/covermanager/albumcoverfetcher.h b/src/covermanager/albumcoverfetcher.h index ab515361..f9714731 100644 --- a/src/covermanager/albumcoverfetcher.h +++ b/src/covermanager/albumcoverfetcher.h @@ -36,6 +36,8 @@ #include #include +#include "core/shared_ptr.h" + #include "coversearchstatistics.h" #include "albumcoverimageresult.h" @@ -107,7 +109,7 @@ class AlbumCoverFetcher : public QObject { Q_OBJECT public: - explicit AlbumCoverFetcher(CoverProviders *cover_providers, NetworkAccessManager *network, QObject *parent = nullptr); + explicit AlbumCoverFetcher(SharedPtr cover_providers, SharedPtr network, QObject *parent = nullptr); ~AlbumCoverFetcher() override; static const int kMaxConcurrentRequests; @@ -129,8 +131,8 @@ class AlbumCoverFetcher : public QObject { private: void AddRequest(const CoverSearchRequest &req); - CoverProviders *cover_providers_; - NetworkAccessManager *network_; + SharedPtr cover_providers_; + SharedPtr network_; quint64 next_id_; QQueue queued_requests_; diff --git a/src/covermanager/albumcoverfetchersearch.cpp b/src/covermanager/albumcoverfetchersearch.cpp index 051cf6b0..7995cab9 100644 --- a/src/covermanager/albumcoverfetchersearch.cpp +++ b/src/covermanager/albumcoverfetchersearch.cpp @@ -36,6 +36,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/networktimeouts.h" #include "utilities/imageutils.h" @@ -51,7 +52,7 @@ const int AlbumCoverFetcherSearch::kImageLoadTimeoutMs = 6000; const int AlbumCoverFetcherSearch::kTargetSize = 500; const float AlbumCoverFetcherSearch::kGoodScore = 4.0; -AlbumCoverFetcherSearch::AlbumCoverFetcherSearch(const CoverSearchRequest &request, NetworkAccessManager *network, QObject *parent) +AlbumCoverFetcherSearch::AlbumCoverFetcherSearch(const CoverSearchRequest &request, SharedPtr network, QObject *parent) : QObject(parent), request_(request), image_load_timeout_(new NetworkTimeouts(kImageLoadTimeoutMs, this)), @@ -79,7 +80,7 @@ void AlbumCoverFetcherSearch::TerminateSearch() { } -void AlbumCoverFetcherSearch::Start(CoverProviders *cover_providers) { +void AlbumCoverFetcherSearch::Start(SharedPtr cover_providers) { // Ignore Radio Paradise "commercial" break. if (request_.artist.compare("commercial-free", Qt::CaseInsensitive) == 0 && request_.title.compare("listener-supported", Qt::CaseInsensitive) == 0) { diff --git a/src/covermanager/albumcoverfetchersearch.h b/src/covermanager/albumcoverfetchersearch.h index 4e188dd7..4c4907d1 100644 --- a/src/covermanager/albumcoverfetchersearch.h +++ b/src/covermanager/albumcoverfetchersearch.h @@ -35,6 +35,7 @@ #include #include +#include "core/shared_ptr.h" #include "albumcoverfetcher.h" #include "coversearchstatistics.h" #include "albumcoverimageresult.h" @@ -52,10 +53,10 @@ class AlbumCoverFetcherSearch : public QObject { Q_OBJECT public: - explicit AlbumCoverFetcherSearch(const CoverSearchRequest &request, NetworkAccessManager *network, QObject *parent); + explicit AlbumCoverFetcherSearch(const CoverSearchRequest &request, SharedPtr network, QObject *parent); ~AlbumCoverFetcherSearch() override; - void Start(CoverProviders *cover_providers); + void Start(SharedPtr cover_providers); // Cancels all pending requests. No Finished signals will be emitted, and it is the caller's responsibility to delete the AlbumCoverFetcherSearch. void Cancel(); @@ -114,7 +115,7 @@ class AlbumCoverFetcherSearch : public QObject { }; QMultiMap candidate_images_; - NetworkAccessManager *network_; + SharedPtr network_; bool cancel_requested_; diff --git a/src/covermanager/albumcoverloader.cpp b/src/covermanager/albumcoverloader.cpp index 96ca901e..c8a8233a 100644 --- a/src/covermanager/albumcoverloader.cpp +++ b/src/covermanager/albumcoverloader.cpp @@ -102,7 +102,7 @@ void AlbumCoverLoader::CancelTasks(const QSet &ids) { quint64 AlbumCoverLoader::LoadImageAsync(const AlbumCoverLoaderOptions &options, const Song &song) { - TaskPtr task = std::make_shared(); + TaskPtr task = make_shared(); task->options = options; task->art_embedded = song.art_embedded(); task->art_automatic = song.art_automatic(); @@ -118,7 +118,7 @@ quint64 AlbumCoverLoader::LoadImageAsync(const AlbumCoverLoaderOptions &options, quint64 AlbumCoverLoader::LoadImageAsync(const AlbumCoverLoaderOptions &options, const bool art_embedded, const QUrl &art_automatic, const QUrl &art_manual, const bool art_unset, const QUrl &song_url, const Song::Source song_source) { - TaskPtr task = std::make_shared(); + TaskPtr task = make_shared(); task->options = options; task->art_embedded = art_embedded; task->art_automatic = art_automatic; diff --git a/src/covermanager/albumcoverloader.h b/src/covermanager/albumcoverloader.h index 3ff402e4..ffe7faf3 100644 --- a/src/covermanager/albumcoverloader.h +++ b/src/covermanager/albumcoverloader.h @@ -22,8 +22,6 @@ #include "config.h" -#include - #include #include #include @@ -34,6 +32,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "albumcoverloaderoptions.h" #include "albumcoverloaderresult.h" @@ -43,8 +42,6 @@ class QThread; class QNetworkReply; class NetworkAccessManager; -using std::shared_ptr; - class AlbumCoverLoader : public QObject { Q_OBJECT @@ -94,7 +91,7 @@ class AlbumCoverLoader : public QObject { QUrl art_automatic_updated; int redirects; }; - using TaskPtr = shared_ptr; + using TaskPtr = SharedPtr; class LoadImageResult { public: @@ -127,7 +124,7 @@ class AlbumCoverLoader : public QObject { private: static const int kMaxRedirects = 3; - NetworkAccessManager *network_; + SharedPtr network_; bool stop_requested_; QMutex mutex_load_image_async_; QQueue tasks_; diff --git a/src/covermanager/albumcovermanager.cpp b/src/covermanager/albumcovermanager.cpp index 8ca3e4f2..467e9c9d 100644 --- a/src/covermanager/albumcovermanager.cpp +++ b/src/covermanager/albumcovermanager.cpp @@ -21,7 +21,6 @@ #include "config.h" -#include #include #include @@ -64,6 +63,8 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/iconloader.h" #include "core/tagreaderclient.h" @@ -97,7 +98,7 @@ const char *AlbumCoverManager::kSettingsGroup = "CoverManager"; constexpr int AlbumCoverManager::kThumbnailSize = 120; -AlbumCoverManager::AlbumCoverManager(Application *app, CollectionBackend *collection_backend, QMainWindow *mainwindow, QWidget *parent) +AlbumCoverManager::AlbumCoverManager(Application *app, SharedPtr collection_backend, QMainWindow *mainwindow, QWidget *parent) : QMainWindow(parent), ui_(new Ui_CoverManager), mainwindow_(mainwindow), @@ -231,7 +232,7 @@ void AlbumCoverManager::Init() { s.endGroup(); - QObject::connect(app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &AlbumCoverManager::AlbumCoverLoaded); + QObject::connect(&*app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &AlbumCoverManager::AlbumCoverLoaded); cover_searcher_->Init(cover_fetcher_); @@ -255,7 +256,7 @@ void AlbumCoverManager::showEvent(QShowEvent *e) { void AlbumCoverManager::closeEvent(QCloseEvent *e) { if (!cover_fetching_tasks_.isEmpty()) { - std::unique_ptr message_box(new QMessageBox(QMessageBox::Question, tr("Really cancel?"), tr("Closing this window will stop searching for album covers."), QMessageBox::Abort, this)); + ScopedPtr message_box(new QMessageBox(QMessageBox::Question, tr("Really cancel?"), tr("Closing this window will stop searching for album covers."), QMessageBox::Abort, this)); message_box->addButton(tr("Don't stop!"), QMessageBox::AcceptRole); if (message_box->exec() != QMessageBox::Abort) { diff --git a/src/covermanager/albumcovermanager.h b/src/covermanager/albumcovermanager.h index 19e9a9b8..1742dcd3 100644 --- a/src/covermanager/albumcovermanager.h +++ b/src/covermanager/albumcovermanager.h @@ -36,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "core/tagreaderclient.h" #include "albumcoverloaderoptions.h" @@ -76,7 +77,7 @@ class AlbumCoverManager : public QMainWindow { Q_OBJECT public: - explicit AlbumCoverManager(Application *app, CollectionBackend *collection_backend, QMainWindow *mainwindow, QWidget *parent = nullptr); + explicit AlbumCoverManager(Application *app, SharedPtr collection_backend, QMainWindow *mainwindow, QWidget *parent = nullptr); ~AlbumCoverManager() override; void Reset(); @@ -87,7 +88,7 @@ class AlbumCoverManager : public QMainWindow { SongList GetSongsInAlbum(const QModelIndex &idx) const; - CollectionBackend *backend() const { return collection_backend_; } + SharedPtr collection_backend() const { return collection_backend_; } protected: void showEvent(QShowEvent *e) override; @@ -190,7 +191,7 @@ class AlbumCoverManager : public QMainWindow { Ui_CoverManager *ui_; QMainWindow *mainwindow_; Application *app_; - CollectionBackend *collection_backend_; + SharedPtr collection_backend_; AlbumCoverChoiceController *album_cover_choice_controller_; QAction *filter_all_; diff --git a/src/covermanager/albumcovermanagerlist.cpp b/src/covermanager/albumcovermanagerlist.cpp index 4e9400bb..e2cdb2e3 100644 --- a/src/covermanager/albumcovermanagerlist.cpp +++ b/src/covermanager/albumcovermanagerlist.cpp @@ -21,8 +21,6 @@ #include "config.h" -#include - #include #include #include @@ -33,6 +31,7 @@ #include #include +#include "core/scoped_ptr.h" #include "core/song.h" #include "collection/collectionbackend.h" #include "playlist/songmimedata.h" @@ -63,10 +62,10 @@ QMimeData *AlbumCoverManagerList::mimeData(const QList items) } // Get the QAbstractItemModel data so the picture works - std::unique_ptr orig_data(QListWidget::mimeData(items)); + ScopedPtr orig_data(QListWidget::mimeData(items)); SongMimeData *mime_data = new SongMimeData; - mime_data->backend = manager_->backend(); + mime_data->backend = manager_->collection_backend(); mime_data->songs = songs; mime_data->setUrls(urls); mime_data->setData(orig_data->formats()[0], orig_data->data(orig_data->formats()[0])); diff --git a/src/covermanager/albumcoversearcher.cpp b/src/covermanager/albumcoversearcher.cpp index d064cd6b..74958856 100644 --- a/src/covermanager/albumcoversearcher.cpp +++ b/src/covermanager/albumcoversearcher.cpp @@ -128,7 +128,7 @@ AlbumCoverSearcher::AlbumCoverSearcher(const QIcon &no_cover_icon, Application * ui_->covers->setItemDelegate(new SizeOverlayDelegate(this)); ui_->covers->setModel(model_); - QObject::connect(app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &AlbumCoverSearcher::AlbumCoverLoaded); + QObject::connect(&*app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &AlbumCoverSearcher::AlbumCoverLoaded); QObject::connect(ui_->search, &QPushButton::clicked, this, &AlbumCoverSearcher::Search); QObject::connect(ui_->covers, &GroupedIconView::doubleClicked, this, &AlbumCoverSearcher::CoverDoubleClicked); diff --git a/src/covermanager/coverfromurldialog.cpp b/src/covermanager/coverfromurldialog.cpp index 4d873a66..ffb45505 100644 --- a/src/covermanager/coverfromurldialog.cpp +++ b/src/covermanager/coverfromurldialog.cpp @@ -31,6 +31,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "utilities/mimeutils.h" #include "widgets/busyindicator.h" @@ -38,7 +39,7 @@ #include "coverfromurldialog.h" #include "ui_coverfromurldialog.h" -CoverFromURLDialog::CoverFromURLDialog(NetworkAccessManager *network, QWidget *parent) +CoverFromURLDialog::CoverFromURLDialog(SharedPtr network, QWidget *parent) : QDialog(parent), network_(network), ui_(new Ui_CoverFromURLDialog) { diff --git a/src/covermanager/coverfromurldialog.h b/src/covermanager/coverfromurldialog.h index ec370808..ebd80bc4 100644 --- a/src/covermanager/coverfromurldialog.h +++ b/src/covermanager/coverfromurldialog.h @@ -28,6 +28,7 @@ #include #include +#include "core/shared_ptr.h" #include "albumcoverimageresult.h" class QWidget; @@ -40,7 +41,7 @@ class CoverFromURLDialog : public QDialog { Q_OBJECT public: - explicit CoverFromURLDialog(NetworkAccessManager *network, QWidget *parent = nullptr); + explicit CoverFromURLDialog(SharedPtr network, QWidget *parent = nullptr); ~CoverFromURLDialog() override; // Opens the dialog. This returns an image found at the URL chosen by user or null image if the dialog got rejected. @@ -51,7 +52,7 @@ class CoverFromURLDialog : public QDialog { void LoadCoverFromURLFinished(); private: - NetworkAccessManager *network_; + SharedPtr network_; Ui_CoverFromURLDialog *ui_; AlbumCoverImageResult last_album_cover_; }; diff --git a/src/covermanager/coverprovider.cpp b/src/covermanager/coverprovider.cpp index e9484147..955dba70 100644 --- a/src/covermanager/coverprovider.cpp +++ b/src/covermanager/coverprovider.cpp @@ -24,7 +24,8 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "coverprovider.h" -CoverProvider::CoverProvider(const QString &name, const bool enabled, const bool authentication_required, const float quality, const bool batch, const bool allow_missing_album, Application *app, NetworkAccessManager *network, QObject *parent) : QObject(parent), app_(app), network_(network), name_(name), enabled_(enabled), order_(0), authentication_required_(authentication_required), quality_(quality), batch_(batch), allow_missing_album_(allow_missing_album) {} +CoverProvider::CoverProvider(const QString &name, const bool enabled, const bool authentication_required, const float quality, const bool batch, const bool allow_missing_album, Application *app, SharedPtr network, QObject *parent) : QObject(parent), app_(app), network_(network), name_(name), enabled_(enabled), order_(0), authentication_required_(authentication_required), quality_(quality), batch_(batch), allow_missing_album_(allow_missing_album) {} diff --git a/src/covermanager/coverprovider.h b/src/covermanager/coverprovider.h index 2438c211..3a656635 100644 --- a/src/covermanager/coverprovider.h +++ b/src/covermanager/coverprovider.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "albumcoverfetcher.h" class Application; @@ -41,7 +42,7 @@ class CoverProvider : public QObject { Q_OBJECT public: - explicit CoverProvider(const QString &name, const bool enabled, const bool authentication_required, const float quality, const bool batch, const bool allow_missing_album, Application *app, NetworkAccessManager *network, QObject *parent); + explicit CoverProvider(const QString &name, const bool enabled, const bool authentication_required, const float quality, const bool batch, const bool allow_missing_album, Application *app, SharedPtr network, QObject *parent); // A name (very short description) of this provider, like "last.fm". QString name() const { return name_; } @@ -79,7 +80,7 @@ class CoverProvider : public QObject { using ParamList = QList; Application *app_; - NetworkAccessManager *network_; + SharedPtr network_; QString name_; bool enabled_; int order_; diff --git a/src/covermanager/currentalbumcoverloader.cpp b/src/covermanager/currentalbumcoverloader.cpp index 4e58f043..7667ffa5 100644 --- a/src/covermanager/currentalbumcoverloader.cpp +++ b/src/covermanager/currentalbumcoverloader.cpp @@ -36,6 +36,8 @@ #include "albumcoverloaderresult.h" #include "currentalbumcoverloader.h" +using std::make_unique; + CurrentAlbumCoverLoader::CurrentAlbumCoverLoader(Application *app, QObject *parent) : QObject(parent), app_(app), @@ -46,8 +48,8 @@ CurrentAlbumCoverLoader::CurrentAlbumCoverLoader(Application *app, QObject *pare options_.desired_scaled_size = QSize(120, 120); options_.default_cover = ":/pictures/cdcase.png"; - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &CurrentAlbumCoverLoader::LoadAlbumCover); - QObject::connect(app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &CurrentAlbumCoverLoader::AlbumCoverReady); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &CurrentAlbumCoverLoader::LoadAlbumCover); + QObject::connect(&*app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &CurrentAlbumCoverLoader::AlbumCoverReady); ReloadSettingsAsync(); @@ -85,7 +87,7 @@ void CurrentAlbumCoverLoader::AlbumCoverReady(const quint64 id, AlbumCoverLoader id_ = 0; if (!result.album_cover.image.isNull()) { - temp_cover_ = std::make_unique(temp_file_pattern_); + temp_cover_ = make_unique(temp_file_pattern_); temp_cover_->setAutoRemove(true); if (temp_cover_->open()) { if (result.album_cover.image.save(temp_cover_->fileName(), "JPEG")) { @@ -102,7 +104,7 @@ void CurrentAlbumCoverLoader::AlbumCoverReady(const quint64 id, AlbumCoverLoader QUrl thumbnail_url; if (!result.image_scaled.isNull()) { - temp_cover_thumbnail_ = std::make_unique(temp_file_pattern_); + temp_cover_thumbnail_ = make_unique(temp_file_pattern_); temp_cover_thumbnail_->setAutoRemove(true); if (temp_cover_thumbnail_->open()) { if (result.image_scaled.save(temp_cover_thumbnail_->fileName(), "JPEG")) { diff --git a/src/covermanager/currentalbumcoverloader.h b/src/covermanager/currentalbumcoverloader.h index 18b75609..ae7d0a48 100644 --- a/src/covermanager/currentalbumcoverloader.h +++ b/src/covermanager/currentalbumcoverloader.h @@ -24,14 +24,13 @@ #include "config.h" -#include - #include #include #include #include #include +#include "core/scoped_ptr.h" #include "core/song.h" #include "albumcoverloaderoptions.h" #include "albumcoverloaderresult.h" @@ -67,12 +66,11 @@ class CurrentAlbumCoverLoader : public QObject { QString temp_file_pattern_; - std::unique_ptr temp_cover_; - std::unique_ptr temp_cover_thumbnail_; + ScopedPtr temp_cover_; + ScopedPtr temp_cover_thumbnail_; quint64 id_; Song last_song_; - }; #endif // CURRENTALBUMCOVERLOADER_H diff --git a/src/covermanager/deezercoverprovider.cpp b/src/covermanager/deezercoverprovider.cpp index f73e4df5..2a003e1c 100644 --- a/src/covermanager/deezercoverprovider.cpp +++ b/src/covermanager/deezercoverprovider.cpp @@ -50,7 +50,7 @@ const char *DeezerCoverProvider::kApiUrl = "https://api.deezer.com"; const int DeezerCoverProvider::kLimit = 10; -DeezerCoverProvider::DeezerCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent) +DeezerCoverProvider::DeezerCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider("Deezer", true, false, 2.0, true, true, app, network, parent) {} DeezerCoverProvider::~DeezerCoverProvider() { diff --git a/src/covermanager/deezercoverprovider.h b/src/covermanager/deezercoverprovider.h index db03b9cd..08faa15a 100644 --- a/src/covermanager/deezercoverprovider.h +++ b/src/covermanager/deezercoverprovider.h @@ -40,7 +40,7 @@ class DeezerCoverProvider : public JsonCoverProvider { Q_OBJECT public: - explicit DeezerCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit DeezerCoverProvider(Application *app, SharedPtr network, QObject *parent = nullptr); ~DeezerCoverProvider() override; bool StartSearch(const QString &artist, const QString &album, const QString &title, const int id) override; diff --git a/src/covermanager/discogscoverprovider.cpp b/src/covermanager/discogscoverprovider.cpp index 03cc6213..df2928ef 100644 --- a/src/covermanager/discogscoverprovider.cpp +++ b/src/covermanager/discogscoverprovider.cpp @@ -41,6 +41,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/logging.h" #include "core/networkaccessmanager.h" @@ -49,12 +50,14 @@ #include "jsoncoverprovider.h" #include "discogscoverprovider.h" +using std::make_shared; + const char *DiscogsCoverProvider::kUrlSearch = "https://api.discogs.com/database/search"; const char *DiscogsCoverProvider::kAccessKeyB64 = "dGh6ZnljUGJlZ1NEeXBuSFFxSVk="; const char *DiscogsCoverProvider::kSecretKeyB64 = "ZkFIcmlaSER4aHhRSlF2U3d0bm5ZVmdxeXFLWUl0UXI="; const int DiscogsCoverProvider::kRequestsDelay = 1000; -DiscogsCoverProvider::DiscogsCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent) +DiscogsCoverProvider::DiscogsCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider("Discogs", false, false, 0.0, false, false, app, network, parent), timer_flush_requests_(new QTimer(this)) { @@ -86,7 +89,7 @@ bool DiscogsCoverProvider::StartSearch(const QString &artist, const QString &alb if (artist.isEmpty() || album.isEmpty()) return false; - std::shared_ptr search = std::make_shared(id, artist, album); + SharedPtr search = make_shared(id, artist, album); requests_search_.insert(search->id, search); queue_search_requests_.enqueue(search); @@ -121,7 +124,7 @@ void DiscogsCoverProvider::FlushRequests() { } -void DiscogsCoverProvider::SendSearchRequest(std::shared_ptr search) { +void DiscogsCoverProvider::SendSearchRequest(SharedPtr search) { ParamList params = ParamList() << Param("format", "album") << Param("artist", search->artist.toLower()) @@ -227,7 +230,7 @@ void DiscogsCoverProvider::HandleSearchReply(QNetworkReply *reply, const int id) reply->deleteLater(); if (!requests_search_.contains(id)) return; - std::shared_ptr search = requests_search_.value(id); + SharedPtr search = requests_search_.value(id); QByteArray data = GetReplyData(reply); if (data.isEmpty()) { @@ -307,7 +310,7 @@ void DiscogsCoverProvider::HandleSearchReply(QNetworkReply *reply, const int id) } -void DiscogsCoverProvider::StartReleaseRequest(std::shared_ptr search, const quint64 release_id, const QUrl &url) { +void DiscogsCoverProvider::StartReleaseRequest(SharedPtr search, const quint64 release_id, const QUrl &url) { DiscogsCoverReleaseContext release(search->id, release_id, url); search->requests_release_.insert(release_id, release); @@ -334,7 +337,7 @@ void DiscogsCoverProvider::HandleReleaseReply(QNetworkReply *reply, const int se reply->deleteLater(); if (!requests_search_.contains(search_id)) return; - std::shared_ptr search = requests_search_.value(search_id); + SharedPtr search = requests_search_.value(search_id); if (!search->requests_release_.contains(release_id)) return; const DiscogsCoverReleaseContext &release = search->requests_release_.value(release_id); @@ -447,7 +450,7 @@ void DiscogsCoverProvider::HandleReleaseReply(QNetworkReply *reply, const int se } -void DiscogsCoverProvider::EndSearch(std::shared_ptr search, const quint64 release_id) { +void DiscogsCoverProvider::EndSearch(SharedPtr search, const quint64 release_id) { if (search->requests_release_.contains(release_id)) { search->requests_release_.remove(release_id); diff --git a/src/covermanager/discogscoverprovider.h b/src/covermanager/discogscoverprovider.h index ef22f1b6..41dbb721 100644 --- a/src/covermanager/discogscoverprovider.h +++ b/src/covermanager/discogscoverprovider.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -37,6 +35,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsoncoverprovider.h" #include "albumcoverfetcher.h" @@ -49,7 +48,7 @@ class DiscogsCoverProvider : public JsonCoverProvider { Q_OBJECT public: - explicit DiscogsCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit DiscogsCoverProvider(Application *app, SharedPtr network, QObject *parent = nullptr); ~DiscogsCoverProvider() override; bool StartSearch(const QString &artist, const QString &album, const QString &title, const int id) override; @@ -77,12 +76,12 @@ class DiscogsCoverProvider : public JsonCoverProvider { }; private: - void SendSearchRequest(std::shared_ptr search); + void SendSearchRequest(SharedPtr search); void SendReleaseRequest(const DiscogsCoverReleaseContext &release); QNetworkReply *CreateRequest(QUrl url, const ParamList ¶ms_provided = ParamList()); QByteArray GetReplyData(QNetworkReply *reply); - void StartReleaseRequest(std::shared_ptr search, const quint64 release_id, const QUrl &url); - void EndSearch(std::shared_ptr search, const quint64 release_id = 0); + void StartReleaseRequest(SharedPtr search, const quint64 release_id, const QUrl &url); + void EndSearch(SharedPtr search, const quint64 release_id = 0); void Error(const QString &error, const QVariant &debug = QVariant()) override; private slots: @@ -97,9 +96,9 @@ class DiscogsCoverProvider : public JsonCoverProvider { static const int kRequestsDelay; QTimer *timer_flush_requests_; - QQueue> queue_search_requests_; + QQueue> queue_search_requests_; QQueue queue_release_requests_; - QMap> requests_search_; + QMap> requests_search_; QList replies_; }; diff --git a/src/covermanager/jsoncoverprovider.cpp b/src/covermanager/jsoncoverprovider.cpp index df6d0500..4ac98c62 100644 --- a/src/covermanager/jsoncoverprovider.cpp +++ b/src/covermanager/jsoncoverprovider.cpp @@ -25,12 +25,13 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/networkaccessmanager.h" #include "coverprovider.h" #include "jsoncoverprovider.h" -JsonCoverProvider::JsonCoverProvider(const QString &name, const bool enabled, const bool authentication_required, const float quality, const bool batch, const bool allow_missing_album, Application *app, NetworkAccessManager *network, QObject *parent) +JsonCoverProvider::JsonCoverProvider(const QString &name, const bool enabled, const bool authentication_required, const float quality, const bool batch, const bool allow_missing_album, Application *app, SharedPtr network, QObject *parent) : CoverProvider(name, enabled, authentication_required, quality, batch, allow_missing_album, app, network, parent) {} QJsonObject JsonCoverProvider::ExtractJsonObj(const QByteArray &data) { diff --git a/src/covermanager/jsoncoverprovider.h b/src/covermanager/jsoncoverprovider.h index 92f547c9..e00a8390 100644 --- a/src/covermanager/jsoncoverprovider.h +++ b/src/covermanager/jsoncoverprovider.h @@ -27,6 +27,7 @@ #include #include +#include "core/shared_ptr.h" #include "coverprovider.h" class Application; @@ -36,7 +37,7 @@ class JsonCoverProvider : public CoverProvider { Q_OBJECT public: - explicit JsonCoverProvider(const QString &name, const bool enabled, const bool authentication_required, const float quality, const bool batch, const bool allow_missing_album, Application *app, NetworkAccessManager *network, QObject *parent); + explicit JsonCoverProvider(const QString &name, const bool enabled, const bool authentication_required, const float quality, const bool batch, const bool allow_missing_album, Application *app, SharedPtr network, QObject *parent); protected: QJsonObject ExtractJsonObj(const QByteArray &data); diff --git a/src/covermanager/lastfmcoverprovider.cpp b/src/covermanager/lastfmcoverprovider.cpp index 7d0f306c..2b5b44da 100644 --- a/src/covermanager/lastfmcoverprovider.cpp +++ b/src/covermanager/lastfmcoverprovider.cpp @@ -37,6 +37,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/networkaccessmanager.h" #include "core/logging.h" @@ -49,7 +50,7 @@ const char *LastFmCoverProvider::kUrl = "https://ws.audioscrobbler.com/2.0/"; const char *LastFmCoverProvider::kApiKey = "211990b4c96782c05d1536e7219eb56e"; const char *LastFmCoverProvider::kSecret = "80fd738f49596e9709b1bf9319c444a8"; -LastFmCoverProvider::LastFmCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent) +LastFmCoverProvider::LastFmCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider("Last.fm", true, false, 1.0, true, false, app, network, parent) {} LastFmCoverProvider::~LastFmCoverProvider() { diff --git a/src/covermanager/lastfmcoverprovider.h b/src/covermanager/lastfmcoverprovider.h index 2bcee60c..e35e6f42 100644 --- a/src/covermanager/lastfmcoverprovider.h +++ b/src/covermanager/lastfmcoverprovider.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsoncoverprovider.h" class NetworkAccessManager; @@ -39,7 +40,7 @@ class LastFmCoverProvider : public JsonCoverProvider { Q_OBJECT public: - explicit LastFmCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit LastFmCoverProvider(Application *app, SharedPtr network, QObject *parent = nullptr); ~LastFmCoverProvider() override; bool StartSearch(const QString &artist, const QString &album, const QString &title, const int id) override; diff --git a/src/covermanager/musicbrainzcoverprovider.cpp b/src/covermanager/musicbrainzcoverprovider.cpp index 42b7702e..41f974e3 100644 --- a/src/covermanager/musicbrainzcoverprovider.cpp +++ b/src/covermanager/musicbrainzcoverprovider.cpp @@ -36,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/networkaccessmanager.h" #include "core/logging.h" @@ -48,7 +49,7 @@ const char *MusicbrainzCoverProvider::kAlbumCoverUrl = "https://coverartarchive. const int MusicbrainzCoverProvider::kLimit = 8; const int MusicbrainzCoverProvider::kRequestsDelay = 1000; -MusicbrainzCoverProvider::MusicbrainzCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent) +MusicbrainzCoverProvider::MusicbrainzCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider("MusicBrainz", true, false, 1.5, true, false, app, network, parent), timer_flush_requests_(new QTimer(this)) { diff --git a/src/covermanager/musicbrainzcoverprovider.h b/src/covermanager/musicbrainzcoverprovider.h index 64c5f754..3a315db9 100644 --- a/src/covermanager/musicbrainzcoverprovider.h +++ b/src/covermanager/musicbrainzcoverprovider.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsoncoverprovider.h" class QNetworkReply; @@ -41,7 +42,7 @@ class MusicbrainzCoverProvider : public JsonCoverProvider { Q_OBJECT public: - explicit MusicbrainzCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit MusicbrainzCoverProvider(Application *app, SharedPtr network, QObject *parent = nullptr); ~MusicbrainzCoverProvider() override; bool StartSearch(const QString &artist, const QString &album, const QString &title, const int id) override; diff --git a/src/covermanager/musixmatchcoverprovider.cpp b/src/covermanager/musixmatchcoverprovider.cpp index 0bcc424e..8800763a 100644 --- a/src/covermanager/musixmatchcoverprovider.cpp +++ b/src/covermanager/musixmatchcoverprovider.cpp @@ -32,6 +32,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/logging.h" #include "core/networkaccessmanager.h" #include "providers/musixmatchprovider.h" @@ -39,7 +40,7 @@ #include "jsoncoverprovider.h" #include "musixmatchcoverprovider.h" -MusixmatchCoverProvider::MusixmatchCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent) +MusixmatchCoverProvider::MusixmatchCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider("Musixmatch", true, false, 1.0, true, false, app, network, parent) {} MusixmatchCoverProvider::~MusixmatchCoverProvider() { diff --git a/src/covermanager/musixmatchcoverprovider.h b/src/covermanager/musixmatchcoverprovider.h index 45609bb6..140f3ff6 100644 --- a/src/covermanager/musixmatchcoverprovider.h +++ b/src/covermanager/musixmatchcoverprovider.h @@ -28,6 +28,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsoncoverprovider.h" #include "providers/musixmatchprovider.h" @@ -38,7 +39,7 @@ class MusixmatchCoverProvider : public JsonCoverProvider, MusixmatchProvider { Q_OBJECT public: - explicit MusixmatchCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit MusixmatchCoverProvider(Application *app, SharedPtr network, QObject *parent = nullptr); ~MusixmatchCoverProvider() override; bool StartSearch(const QString &artist, const QString &album, const QString &title, const int id) override; diff --git a/src/covermanager/qobuzcoverprovider.cpp b/src/covermanager/qobuzcoverprovider.cpp index 6e35c687..11157417 100644 --- a/src/covermanager/qobuzcoverprovider.cpp +++ b/src/covermanager/qobuzcoverprovider.cpp @@ -35,6 +35,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/networkaccessmanager.h" #include "core/logging.h" @@ -47,7 +48,7 @@ constexpr int QobuzCoverProvider::kLimit = 10; -QobuzCoverProvider::QobuzCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent) +QobuzCoverProvider::QobuzCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider("Qobuz", true, true, 2.0, true, true, app, network, parent), service_(app->internet_services()->Service()) {} diff --git a/src/covermanager/qobuzcoverprovider.h b/src/covermanager/qobuzcoverprovider.h index a0e4e5cc..cd0c1a67 100644 --- a/src/covermanager/qobuzcoverprovider.h +++ b/src/covermanager/qobuzcoverprovider.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsoncoverprovider.h" #include "qobuz/qobuzservice.h" @@ -41,7 +42,7 @@ class QobuzCoverProvider : public JsonCoverProvider { Q_OBJECT public: - explicit QobuzCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit QobuzCoverProvider(Application *app, SharedPtr network, QObject *parent = nullptr); ~QobuzCoverProvider() override; bool StartSearch(const QString &artist, const QString &album, const QString &title, const int id) override; @@ -60,7 +61,7 @@ class QobuzCoverProvider : public JsonCoverProvider { private: static const int kLimit; - QobuzService *service_; + QobuzServicePtr service_; QList replies_; }; diff --git a/src/covermanager/spotifycoverprovider.cpp b/src/covermanager/spotifycoverprovider.cpp index f19ad070..375c7bc6 100644 --- a/src/covermanager/spotifycoverprovider.cpp +++ b/src/covermanager/spotifycoverprovider.cpp @@ -41,6 +41,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/networkaccessmanager.h" #include "core/logging.h" @@ -60,7 +61,7 @@ const char *SpotifyCoverProvider::kClientSecretB64 = "N2ZlMDMxODk1NTBlNDE3ZGI1ZW const char *SpotifyCoverProvider::kApiUrl = "https://api.spotify.com/v1"; const int SpotifyCoverProvider::kLimit = 10; -SpotifyCoverProvider::SpotifyCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent) +SpotifyCoverProvider::SpotifyCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider("Spotify", true, true, 2.5, true, true, app, network, parent), server_(nullptr), expires_in_(0), diff --git a/src/covermanager/spotifycoverprovider.h b/src/covermanager/spotifycoverprovider.h index 73fb26ce..a0a5bd10 100644 --- a/src/covermanager/spotifycoverprovider.h +++ b/src/covermanager/spotifycoverprovider.h @@ -34,6 +34,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsoncoverprovider.h" class QNetworkReply; @@ -45,7 +46,7 @@ class SpotifyCoverProvider : public JsonCoverProvider { Q_OBJECT public: - explicit SpotifyCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit SpotifyCoverProvider(Application *app, SharedPtr network, QObject *parent = nullptr); ~SpotifyCoverProvider() override; bool StartSearch(const QString &artist, const QString &album, const QString &title, const int id) override; diff --git a/src/covermanager/tidalcoverprovider.cpp b/src/covermanager/tidalcoverprovider.cpp index 7a0da725..e5bd189e 100644 --- a/src/covermanager/tidalcoverprovider.cpp +++ b/src/covermanager/tidalcoverprovider.cpp @@ -34,6 +34,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/networkaccessmanager.h" #include "core/logging.h" @@ -46,7 +47,7 @@ constexpr int TidalCoverProvider::kLimit = 10; -TidalCoverProvider::TidalCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent) +TidalCoverProvider::TidalCoverProvider(Application *app, SharedPtr network, QObject *parent) : JsonCoverProvider("Tidal", true, true, 2.5, true, true, app, network, parent), service_(app->internet_services()->Service()) {} diff --git a/src/covermanager/tidalcoverprovider.h b/src/covermanager/tidalcoverprovider.h index 8ae36708..977240fe 100644 --- a/src/covermanager/tidalcoverprovider.h +++ b/src/covermanager/tidalcoverprovider.h @@ -32,6 +32,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsoncoverprovider.h" #include "tidal/tidalservice.h" @@ -43,7 +44,7 @@ class TidalCoverProvider : public JsonCoverProvider { Q_OBJECT public: - explicit TidalCoverProvider(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit TidalCoverProvider(Application *app, SharedPtr network, QObject *parent = nullptr); ~TidalCoverProvider() override; bool StartSearch(const QString &artist, const QString &album, const QString &title, const int id) override; @@ -64,7 +65,7 @@ class TidalCoverProvider : public JsonCoverProvider { private: static const int kLimit; - TidalService *service_; + TidalServicePtr service_; QList replies_; }; diff --git a/src/device/cddadevice.cpp b/src/device/cddadevice.cpp index b259953c..6161f54a 100644 --- a/src/device/cddadevice.cpp +++ b/src/device/cddadevice.cpp @@ -24,6 +24,7 @@ #include #include +#include "core/shared_ptr.h" #include "collection/collectionmodel.h" #include "cddasongloader.h" #include "connecteddevice.h" @@ -33,7 +34,7 @@ class Application; class DeviceLister; class DeviceManager; -CddaDevice::CddaDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, int database_id, bool first_time, QObject *parent) +CddaDevice::CddaDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, SharedPtr manager, Application *app, int database_id, bool first_time, QObject *parent) : ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time, parent), cdda_song_loader_(url) { diff --git a/src/device/cddadevice.h b/src/device/cddadevice.h index 81567fef..11d602ad 100644 --- a/src/device/cddadevice.h +++ b/src/device/cddadevice.h @@ -33,6 +33,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "core/musicstorage.h" #include "cddasongloader.h" @@ -46,7 +47,7 @@ class CddaDevice : public ConnectedDevice { Q_OBJECT public: - Q_INVOKABLE explicit CddaDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); + Q_INVOKABLE explicit CddaDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, SharedPtr manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); bool Init() override; void Refresh() override; diff --git a/src/device/cddasongloader.cpp b/src/device/cddasongloader.cpp index eeaac7b9..f9fcf80c 100644 --- a/src/device/cddasongloader.cpp +++ b/src/device/cddasongloader.cpp @@ -21,6 +21,8 @@ #include "config.h" +#include + #include #include #include @@ -39,13 +41,16 @@ #include "cddasongloader.h" #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "utilities/timeconstants.h" +using std::make_shared; + CddaSongLoader::CddaSongLoader(const QUrl &url, QObject *parent) : QObject(parent), url_(url), - network_(new NetworkAccessManager(this)), + network_(make_shared()), cdda_(nullptr), cdio_(nullptr) {} diff --git a/src/device/cddasongloader.h b/src/device/cddasongloader.h index 5b947866..4800bde1 100644 --- a/src/device/cddasongloader.h +++ b/src/device/cddasongloader.h @@ -35,6 +35,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #ifdef HAVE_MUSICBRAINZ # include "musicbrainz/musicbrainzclient.h" @@ -71,7 +72,7 @@ class CddaSongLoader : public QObject { private: const QUrl url_; - NetworkAccessManager *network_; + SharedPtr network_; GstElement *cdda_; CdIo_t *cdio_; QMutex mutex_load_; diff --git a/src/device/connecteddevice.cpp b/src/device/connecteddevice.cpp index fb33d33f..9fdd9827 100644 --- a/src/device/connecteddevice.cpp +++ b/src/device/connecteddevice.cpp @@ -19,12 +19,15 @@ * */ +#include + #include #include #include #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/database.h" #include "collection/collectionbackend.h" @@ -35,7 +38,9 @@ #include "devicemanager.h" #include "deviceinfo.h" -ConnectedDevice::ConnectedDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent) +using std::make_shared; + +ConnectedDevice::ConnectedDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, SharedPtr manager, Application *app, const int database_id, const bool first_time, QObject *parent) : QObject(parent), app_(app), url_(url), @@ -51,12 +56,12 @@ ConnectedDevice::ConnectedDevice(const QUrl &url, DeviceLister *lister, const QS qLog(Info) << "Connected" << url << unique_id << first_time; // Create the backend in the database thread. - backend_ = new CollectionBackend(); + backend_ = make_shared(); backend_->moveToThread(app_->database()->thread()); - qLog(Debug) << backend_ << "for device" << unique_id_ << "moved to thread" << app_->database()->thread(); + qLog(Debug) << &*backend_ << "for device" << unique_id_ << "moved to thread" << app_->database()->thread(); if (url_.scheme() != "cdda") { - QObject::connect(backend_, &CollectionBackend::TotalSongCountUpdated, this, &ConnectedDevice::BackendTotalSongCountUpdated); + QObject::connect(&*backend_, &CollectionBackend::TotalSongCountUpdated, this, &ConnectedDevice::BackendTotalSongCountUpdated); } backend_->Init(app_->database(), @@ -72,10 +77,6 @@ ConnectedDevice::ConnectedDevice(const QUrl &url, DeviceLister *lister, const QS } -ConnectedDevice::~ConnectedDevice() { - backend_->deleteLater(); -} - void ConnectedDevice::InitBackendDirectory(const QString &mount_point, const bool first_time, const bool rewrite_path) { QList directories = backend_->GetAllDirectories(); @@ -108,7 +109,7 @@ void ConnectedDevice::ConnectAsync() { emit DeviceConnectFinished(unique_id_, tr void ConnectedDevice::Close() { - QObject::connect(backend_, &CollectionBackend::ExitFinished, this, &ConnectedDevice::BackendCloseFinished); + QObject::connect(&*backend_, &CollectionBackend::ExitFinished, this, &ConnectedDevice::BackendCloseFinished); backend_->ExitAsync(); } diff --git a/src/device/connecteddevice.h b/src/device/connecteddevice.h index b6f14643..f3247282 100644 --- a/src/device/connecteddevice.h +++ b/src/device/connecteddevice.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/musicstorage.h" #include "core/song.h" @@ -39,12 +40,13 @@ class CollectionModel; class DeviceLister; class DeviceManager; -class ConnectedDevice : public QObject, public virtual MusicStorage, public std::enable_shared_from_this { +using std::enable_shared_from_this; + +class ConnectedDevice : public QObject, public virtual MusicStorage, public enable_shared_from_this { Q_OBJECT public: - explicit ConnectedDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); - ~ConnectedDevice() override; + explicit ConnectedDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, SharedPtr manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); Song::Source source() const override { return Song::Source::Device; } @@ -91,9 +93,9 @@ class ConnectedDevice : public QObject, public virtual MusicStorage, public std: DeviceLister *lister_; QString unique_id_; int database_id_; - DeviceManager *manager_; + SharedPtr manager_; - CollectionBackend *backend_; + SharedPtr backend_; CollectionModel *model_; qint64 song_count_; diff --git a/src/device/devicedatabasebackend.cpp b/src/device/devicedatabasebackend.cpp index 00d6662b..5acccf26 100644 --- a/src/device/devicedatabasebackend.cpp +++ b/src/device/devicedatabasebackend.cpp @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/database.h" #include "core/sqlquery.h" #include "core/scopedtransaction.h" @@ -46,7 +47,7 @@ DeviceDatabaseBackend::DeviceDatabaseBackend(QObject *parent) } -void DeviceDatabaseBackend::Init(Database *db) { db_ = db; } +void DeviceDatabaseBackend::Init(SharedPtr db) { db_ = db; } void DeviceDatabaseBackend::Close() { diff --git a/src/device/devicedatabasebackend.h b/src/device/devicedatabasebackend.h index 3c30ccf6..bdea60cc 100644 --- a/src/device/devicedatabasebackend.h +++ b/src/device/devicedatabasebackend.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "core/musicstorage.h" @@ -57,11 +58,11 @@ class DeviceDatabaseBackend : public QObject { static const int kDeviceSchemaVersion; - void Init(Database *db); + void Init(SharedPtr db); void Close(); void ExitAsync(); - Database *db() const { return db_; } + SharedPtr db() const { return db_; } DeviceList GetAllDevices(); int AddDevice(const Device &device); @@ -76,7 +77,7 @@ class DeviceDatabaseBackend : public QObject { void ExitFinished(); private: - Database *db_; + SharedPtr db_; QThread *original_thread_; }; diff --git a/src/device/deviceinfo.h b/src/device/deviceinfo.h index cbabb3b8..842630cb 100644 --- a/src/device/deviceinfo.h +++ b/src/device/deviceinfo.h @@ -102,7 +102,7 @@ class DeviceInfo : public SimpleTreeItem { const Backend *BestBackend() const; int database_id_; // -1 if not remembered in the database - std::shared_ptr device_; // nullptr if not connected + SharedPtr device_; // nullptr if not connected QList backends_; QString friendly_name_; diff --git a/src/device/devicemanager.cpp b/src/device/devicemanager.cpp index 98fa1ca9..ff8a0d9f 100644 --- a/src/device/devicemanager.cpp +++ b/src/device/devicemanager.cpp @@ -21,8 +21,8 @@ #include "config.h" -#include #include +#include #include #include @@ -45,6 +45,8 @@ #include "devicemanager.h" #include "core/logging.h" +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/database.h" #include "core/iconloader.h" @@ -81,6 +83,8 @@ # include "giolister.h" // Needs to be last because of #undef signals. #endif +using std::make_unique; + const int DeviceManager::kDeviceIconSize = 32; const int DeviceManager::kDeviceIconOverlaySize = 16; @@ -90,10 +94,10 @@ DeviceManager::DeviceManager(Application *app, QObject *parent) not_connected_overlay_(IconLoader::Load("edit-delete")) { thread_pool_.setMaxThreadCount(1); - QObject::connect(app_->task_manager(), &TaskManager::TasksChanged, this, &DeviceManager::TasksChanged); + QObject::connect(&*app_->task_manager(), &TaskManager::TasksChanged, this, &DeviceManager::TasksChanged); // Create the backend in the database thread - backend_ = new DeviceDatabaseBackend; + backend_ = make_unique(); backend_->moveToThread(app_->database()->thread()); backend_->Init(app_->database()); @@ -151,9 +155,6 @@ DeviceManager::~DeviceManager() { delete root_; root_ = nullptr; - backend_->deleteLater(); - backend_ = nullptr; - } void DeviceManager::Exit() { @@ -164,9 +165,9 @@ void DeviceManager::CloseDevices() { for (DeviceInfo *info : devices_) { if (!info->device_) continue; - if (wait_for_exit_.contains(info->device_.get())) continue; - wait_for_exit_ << info->device_.get(); - QObject::connect(info->device_.get(), &ConnectedDevice::destroyed, this, &DeviceManager::DeviceDestroyed); + if (wait_for_exit_.contains(&*info->device_)) continue; + wait_for_exit_ << &*info->device_; + QObject::connect(&*info->device_, &ConnectedDevice::destroyed, this, &DeviceManager::DeviceDestroyed); info->device_->Close(); } if (wait_for_exit_.isEmpty()) CloseListers(); @@ -187,9 +188,9 @@ void DeviceManager::CloseListers() { void DeviceManager::CloseBackend() { - if (!backend_ || wait_for_exit_.contains(backend_)) return; - wait_for_exit_ << backend_; - QObject::connect(backend_, &DeviceDatabaseBackend::ExitFinished, this, &DeviceManager::BackendClosed); + if (!backend_ || wait_for_exit_.contains(&*backend_)) return; + wait_for_exit_ << &*backend_; + QObject::connect(&*backend_, &DeviceDatabaseBackend::ExitFinished, this, &DeviceManager::BackendClosed); backend_->ExitAsync(); } @@ -290,7 +291,7 @@ QVariant DeviceManager::data(const QModelIndex &idx, int role) const { if (info->size_ > 0) { text = text + QString(" (%1)").arg(Utilities::PrettySize(info->size_)); } - if (info->device_.get()) info->device_->Refresh(); + if (&*info->device_) info->device_->Refresh(); return text; } @@ -341,14 +342,14 @@ QVariant DeviceManager::data(const QModelIndex &idx, int role) const { const_cast(this)->Connect(info); } if (!info->device_) return QVariant(); - return QVariant::fromValue>(info->device_); + return QVariant::fromValue>(info->device_); case MusicStorage::Role_StorageForceConnect: if (!info->BestBackend()) return QVariant(); if (!info->device_) { if (info->database_id_ == -1 && !info->BestBackend()->lister_->DeviceNeedsMount(info->BestBackend()->unique_id_)) { if (info->BestBackend()->lister_->AskForScan(info->BestBackend()->unique_id_)) { - std::unique_ptr dialog(new QMessageBox(QMessageBox::Information, tr("Connect device"), tr("This is the first time you have connected this device. Strawberry will now scan the device to find music files - this may take some time."), QMessageBox::Cancel)); + ScopedPtr dialog(new QMessageBox(QMessageBox::Information, tr("Connect device"), tr("This is the first time you have connected this device. Strawberry will now scan the device to find music files - this may take some time."), QMessageBox::Cancel)); QPushButton *pushbutton = dialog->addButton(tr("Connect device"), QMessageBox::AcceptRole); dialog->exec(); if (dialog->clickedButton() != pushbutton) return QVariant(); @@ -357,7 +358,7 @@ QVariant DeviceManager::data(const QModelIndex &idx, int role) const { const_cast(this)->Connect(info); } if (!info->device_) return QVariant(); - return QVariant::fromValue>(info->device_); + return QVariant::fromValue>(info->device_); case Role_MountPath: { if (!info->device_) return QVariant(); @@ -551,9 +552,9 @@ void DeviceManager::PhysicalDeviceChanged(const QString &id) { } -std::shared_ptr DeviceManager::Connect(const QModelIndex &idx) { +SharedPtr DeviceManager::Connect(const QModelIndex &idx) { - std::shared_ptr ret; + SharedPtr ret; DeviceInfo *info = IndexToItem(idx); if (!info) return ret; @@ -562,9 +563,9 @@ std::shared_ptr DeviceManager::Connect(const QModelIndex &idx) } -std::shared_ptr DeviceManager::Connect(DeviceInfo *info) { +SharedPtr DeviceManager::Connect(DeviceInfo *info) { - std::shared_ptr ret; + SharedPtr ret; if (!info) return ret; if (info->device_) { // Already connected @@ -661,10 +662,10 @@ std::shared_ptr DeviceManager::Connect(DeviceInfo *info) { emit dataChanged(idx, idx); - QObject::connect(info->device_.get(), &ConnectedDevice::TaskStarted, this, &DeviceManager::DeviceTaskStarted); - QObject::connect(info->device_.get(), &ConnectedDevice::SongCountUpdated, this, &DeviceManager::DeviceSongCountUpdated); - QObject::connect(info->device_.get(), &ConnectedDevice::DeviceConnectFinished, this, &DeviceManager::DeviceConnectFinished); - QObject::connect(info->device_.get(), &ConnectedDevice::DeviceCloseFinished, this, &DeviceManager::DeviceCloseFinished); + QObject::connect(&*info->device_, &ConnectedDevice::TaskStarted, this, &DeviceManager::DeviceTaskStarted); + QObject::connect(&*info->device_, &ConnectedDevice::SongCountUpdated, this, &DeviceManager::DeviceSongCountUpdated); + QObject::connect(&*info->device_, &ConnectedDevice::DeviceConnectFinished, this, &DeviceManager::DeviceConnectFinished); + QObject::connect(&*info->device_, &ConnectedDevice::DeviceCloseFinished, this, &DeviceManager::DeviceCloseFinished); ret->ConnectAsync(); return ret; @@ -717,18 +718,18 @@ DeviceInfo *DeviceManager::GetDevice(const QModelIndex &idx) const { } -std::shared_ptr DeviceManager::GetConnectedDevice(const QModelIndex &idx) const { +SharedPtr DeviceManager::GetConnectedDevice(const QModelIndex &idx) const { - std::shared_ptr ret; + SharedPtr ret; DeviceInfo *info = IndexToItem(idx); if (!info) return ret; return info->device_; } -std::shared_ptr DeviceManager::GetConnectedDevice(DeviceInfo *info) const { +SharedPtr DeviceManager::GetConnectedDevice(DeviceInfo *info) const { - std::shared_ptr ret; + SharedPtr ret; if (!info) return ret; return info->device_; @@ -829,7 +830,7 @@ void DeviceManager::DeviceTaskStarted(const int id) { for (int i = 0; i < devices_.count(); ++i) { DeviceInfo *info = devices_[i]; - if (info->device_.get() == device) { + if (&*info->device_ == device) { QModelIndex index = ItemToIndex(info); if (!index.isValid()) continue; active_tasks_[id] = index; diff --git a/src/device/devicemanager.h b/src/device/devicemanager.h index 22ef8431..6f5831cb 100644 --- a/src/device/devicemanager.h +++ b/src/device/devicemanager.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -39,6 +37,8 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/song.h" #include "core/musicstorage.h" #include "core/simpletreemodel.h" @@ -95,8 +95,8 @@ class DeviceManager : public SimpleTreeModel { int GetDatabaseId(const QModelIndex &idx) const; DeviceLister *GetLister(const QModelIndex &idx) const; DeviceInfo *GetDevice(const QModelIndex &idx) const; - std::shared_ptr GetConnectedDevice(const QModelIndex &idx) const; - std::shared_ptr GetConnectedDevice(DeviceInfo *info) const; + SharedPtr GetConnectedDevice(const QModelIndex &idx) const; + SharedPtr GetConnectedDevice(DeviceInfo *info) const; DeviceInfo *FindDeviceById(const QString &id) const; DeviceInfo *FindDeviceByUrl(const QList &url) const; @@ -104,8 +104,8 @@ class DeviceManager : public SimpleTreeModel { DeviceInfo *FindEquivalentDevice(DeviceInfo *info) const; // Actions on devices - std::shared_ptr Connect(DeviceInfo *info); - std::shared_ptr Connect(const QModelIndex &idx); + SharedPtr Connect(DeviceInfo *info); + SharedPtr Connect(const QModelIndex &idx); void Disconnect(DeviceInfo *info, const QModelIndex &idx); void Forget(const QModelIndex &idx); void UnmountAsync(const QModelIndex &idx); @@ -153,7 +153,7 @@ class DeviceManager : public SimpleTreeModel { private: Application *app_; - DeviceDatabaseBackend *backend_; + ScopedPtr backend_; DeviceStateFilterModel *connected_devices_model_; diff --git a/src/device/deviceproperties.cpp b/src/device/deviceproperties.cpp index c09175a0..4c337375 100644 --- a/src/device/deviceproperties.cpp +++ b/src/device/deviceproperties.cpp @@ -22,7 +22,6 @@ #include "config.h" #include -#include #include #include @@ -46,6 +45,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/iconloader.h" #include "core/musicstorage.h" #include "widgets/freespacebar.h" @@ -75,12 +75,12 @@ DeviceProperties::DeviceProperties(QWidget *parent) DeviceProperties::~DeviceProperties() { delete ui_; } -void DeviceProperties::SetDeviceManager(DeviceManager *manager) { +void DeviceProperties::SetDeviceManager(SharedPtr manager) { manager_ = manager; - QObject::connect(manager_, &DeviceManager::dataChanged, this, &DeviceProperties::ModelChanged); - QObject::connect(manager_, &DeviceManager::rowsInserted, this, &DeviceProperties::ModelChanged); - QObject::connect(manager_, &DeviceManager::rowsRemoved, this, &DeviceProperties::ModelChanged); + QObject::connect(&*manager_, &DeviceManager::dataChanged, this, &DeviceProperties::ModelChanged); + QObject::connect(&*manager_, &DeviceManager::rowsInserted, this, &DeviceProperties::ModelChanged); + QObject::connect(&*manager_, &DeviceManager::rowsRemoved, this, &DeviceProperties::ModelChanged); } @@ -204,7 +204,7 @@ void DeviceProperties::UpdateHardwareInfo() { void DeviceProperties::UpdateFormats() { DeviceLister *lister = manager_->GetLister(index_); - std::shared_ptr device = manager_->GetConnectedDevice(index_); + SharedPtr device = manager_->GetConnectedDevice(index_); // Transcode mode MusicStorage::TranscodeMode mode = static_cast(index_.data(DeviceManager::Role_TranscodeMode).toInt()); diff --git a/src/device/deviceproperties.h b/src/device/deviceproperties.h index 2485f2cc..a34566c2 100644 --- a/src/device/deviceproperties.h +++ b/src/device/deviceproperties.h @@ -24,6 +24,8 @@ #include "config.h" +#include + #include #include #include @@ -31,6 +33,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" class QWidget; @@ -45,7 +48,7 @@ class DeviceProperties : public QDialog { explicit DeviceProperties(QWidget *parent = nullptr); ~DeviceProperties() override; - void SetDeviceManager(DeviceManager *manager); + void SetDeviceManager(SharedPtr manager); void ShowDevice(const QModelIndex &idx); public slots: @@ -64,7 +67,7 @@ class DeviceProperties : public QDialog { private: Ui_DeviceProperties *ui_; - DeviceManager *manager_; + SharedPtr manager_; QPersistentModelIndex index_; bool updating_formats_; diff --git a/src/device/deviceview.cpp b/src/device/deviceview.cpp index 7c940d41..3c751c2d 100644 --- a/src/device/deviceview.cpp +++ b/src/device/deviceview.cpp @@ -48,6 +48,7 @@ #include #include +#include "core/scoped_ptr.h" #include "core/iconloader.h" #include "core/application.h" #include "core/deletefiles.h" @@ -66,6 +67,8 @@ #include "deviceproperties.h" #include "deviceview.h" +using std::make_unique; + const int DeviceItemDelegate::kIconPadding = 6; DeviceItemDelegate::DeviceItemDelegate(QObject *parent) : CollectionItemDelegate(parent) {} @@ -203,11 +206,11 @@ void DeviceView::SetApplication(Application *app) { Q_ASSERT(app_ == nullptr); app_ = app; - QObject::connect(app_->device_manager(), &DeviceManager::DeviceConnected, this, &DeviceView::DeviceConnected); - QObject::connect(app_->device_manager(), &DeviceManager::DeviceDisconnected, this, &DeviceView::DeviceDisconnected); + QObject::connect(&*app_->device_manager(), &DeviceManager::DeviceConnected, this, &DeviceView::DeviceConnected); + QObject::connect(&*app_->device_manager(), &DeviceManager::DeviceDisconnected, this, &DeviceView::DeviceDisconnected); sort_model_ = new QSortFilterProxyModel(this); - sort_model_->setSourceModel(app_->device_manager()); + sort_model_->setSourceModel(&*app_->device_manager()); sort_model_->setDynamicSortFilter(true); sort_model_->setSortCaseSensitivity(Qt::CaseInsensitive); sort_model_->sort(0); @@ -220,7 +223,7 @@ void DeviceView::SetApplication(Application *app) { properties_dialog_->SetDeviceManager(app_->device_manager()); - organize_dialog_ = std::make_unique(app_->task_manager(), nullptr, this); + organize_dialog_ = make_unique(app_->task_manager(), nullptr, this); organize_dialog_->SetDestinationModel(app_->collection_model()->directory_model()); } @@ -266,7 +269,7 @@ void DeviceView::contextMenuEvent(QContextMenuEvent *e) { bool is_filesystem_device = false; if (parent_device_index.isValid()) { - std::shared_ptr device = app_->device_manager()->GetConnectedDevice(parent_device_index); + SharedPtr device = app_->device_manager()->GetConnectedDevice(parent_device_index); if (device && !device->LocalPath().isEmpty()) is_filesystem_device = true; } @@ -312,7 +315,7 @@ void DeviceView::DeviceConnected(const QModelIndex &idx) { if (!idx.isValid()) return; - std::shared_ptr device = app_->device_manager()->GetConnectedDevice(idx); + SharedPtr device = app_->device_manager()->GetConnectedDevice(idx); if (!device) return; QModelIndex sort_idx = sort_model_->mapFromSource(idx); @@ -339,7 +342,7 @@ void DeviceView::Forget() { QModelIndex device_idx = MapToDevice(menu_index_); QString unique_id = app_->device_manager()->data(device_idx, DeviceManager::Role_UniqueId).toString(); if (app_->device_manager()->GetLister(device_idx) && app_->device_manager()->GetLister(device_idx)->AskForScan(unique_id)) { - std::unique_ptr dialog(new QMessageBox( + ScopedPtr dialog(new QMessageBox( QMessageBox::Question, tr("Forget device"), tr("Forgetting a device will remove it from this list and Strawberry will have to rescan all the songs again next time you connect it."), QMessageBox::Cancel, this)); @@ -427,7 +430,7 @@ void DeviceView::Delete() { return; } - std::shared_ptr storage = device_index.data(MusicStorage::Role_Storage).value>(); + SharedPtr storage = device_index.data(MusicStorage::Role_Storage).value>(); DeleteFiles *delete_files = new DeleteFiles(app_->task_manager(), storage, false); QObject::connect(delete_files, &DeleteFiles::Finished, this, &DeviceView::DeleteFinished); diff --git a/src/device/deviceview.h b/src/device/deviceview.h index 15bde784..77d36dbe 100644 --- a/src/device/deviceview.h +++ b/src/device/deviceview.h @@ -24,14 +24,13 @@ #include "config.h" -#include - #include #include #include #include #include +#include "core/scoped_ptr.h" #include "core/song.h" #include "collection/collectionitemdelegate.h" #include "widgets/autoexpandingtreeview.h" @@ -107,8 +106,8 @@ class DeviceView : public AutoExpandingTreeView { MergedProxyModel *merged_model_; QSortFilterProxyModel *sort_model_; - std::unique_ptr properties_dialog_; - std::unique_ptr organize_dialog_; + ScopedPtr properties_dialog_; + ScopedPtr organize_dialog_; QMenu *device_menu_; QAction *eject_action_; diff --git a/src/device/filesystemdevice.cpp b/src/device/filesystemdevice.cpp index 38d6146b..60df123c 100644 --- a/src/device/filesystemdevice.cpp +++ b/src/device/filesystemdevice.cpp @@ -26,6 +26,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/song.h" @@ -38,7 +39,7 @@ 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, SharedPtr manager, Application *app, const int database_id, const bool first_time, QObject *parent) : FilesystemMusicStorage(Song::Source::Device, url.toLocalFile()), ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time, parent), watcher_(new CollectionWatcher(Song::Source::Device)), @@ -52,17 +53,17 @@ FilesystemDevice::FilesystemDevice(const QUrl &url, DeviceLister *lister, const watcher_->set_backend(backend_); watcher_->set_task_manager(app_->task_manager()); - QObject::connect(backend_, &CollectionBackend::DirectoryDiscovered, watcher_, &CollectionWatcher::AddDirectory); - QObject::connect(backend_, &CollectionBackend::DirectoryDeleted, watcher_, &CollectionWatcher::RemoveDirectory); - QObject::connect(watcher_, &CollectionWatcher::NewOrUpdatedSongs, backend_, &CollectionBackend::AddOrUpdateSongs); - QObject::connect(watcher_, &CollectionWatcher::SongsMTimeUpdated, backend_, &CollectionBackend::UpdateMTimesOnly); - QObject::connect(watcher_, &CollectionWatcher::SongsDeleted, backend_, &CollectionBackend::DeleteSongs); - QObject::connect(watcher_, &CollectionWatcher::SongsUnavailable, backend_, &CollectionBackend::MarkSongsUnavailable); - QObject::connect(watcher_, &CollectionWatcher::SongsReadded, backend_, &CollectionBackend::MarkSongsUnavailable); - QObject::connect(watcher_, &CollectionWatcher::SubdirsDiscovered, backend_, &CollectionBackend::AddOrUpdateSubdirs); - QObject::connect(watcher_, &CollectionWatcher::SubdirsMTimeUpdated, backend_, &CollectionBackend::AddOrUpdateSubdirs); - QObject::connect(watcher_, &CollectionWatcher::CompilationsNeedUpdating, backend_, &CollectionBackend::CompilationsNeedUpdating); - QObject::connect(watcher_, &CollectionWatcher::UpdateLastSeen, backend_, &CollectionBackend::UpdateLastSeen); + QObject::connect(&*backend_, &CollectionBackend::DirectoryDiscovered, watcher_, &CollectionWatcher::AddDirectory); + QObject::connect(&*backend_, &CollectionBackend::DirectoryDeleted, watcher_, &CollectionWatcher::RemoveDirectory); + QObject::connect(watcher_, &CollectionWatcher::NewOrUpdatedSongs, &*backend_, &CollectionBackend::AddOrUpdateSongs); + QObject::connect(watcher_, &CollectionWatcher::SongsMTimeUpdated, &*backend_, &CollectionBackend::UpdateMTimesOnly); + QObject::connect(watcher_, &CollectionWatcher::SongsDeleted, &*backend_, &CollectionBackend::DeleteSongs); + QObject::connect(watcher_, &CollectionWatcher::SongsUnavailable, &*backend_, &CollectionBackend::MarkSongsUnavailable); + QObject::connect(watcher_, &CollectionWatcher::SongsReadded, &*backend_, &CollectionBackend::MarkSongsUnavailable); + QObject::connect(watcher_, &CollectionWatcher::SubdirsDiscovered, &*backend_, &CollectionBackend::AddOrUpdateSubdirs); + QObject::connect(watcher_, &CollectionWatcher::SubdirsMTimeUpdated, &*backend_, &CollectionBackend::AddOrUpdateSubdirs); + QObject::connect(watcher_, &CollectionWatcher::CompilationsNeedUpdating, &*backend_, &CollectionBackend::CompilationsNeedUpdating); + QObject::connect(watcher_, &CollectionWatcher::UpdateLastSeen, &*backend_, &CollectionBackend::UpdateLastSeen); QObject::connect(watcher_, &CollectionWatcher::ScanStarted, this, &FilesystemDevice::TaskStarted); } @@ -92,12 +93,12 @@ void FilesystemDevice::Close() { Q_ASSERT(QThread::currentThread() == thread()); - wait_for_exit_ << backend_ << watcher_; + wait_for_exit_ << &*backend_ << watcher_; - QObject::disconnect(backend_, nullptr, watcher_, nullptr); - QObject::disconnect(watcher_, nullptr, backend_, nullptr); + QObject::disconnect(&*backend_, nullptr, watcher_, nullptr); + QObject::disconnect(watcher_, nullptr, &*backend_, nullptr); - QObject::connect(backend_, &CollectionBackend::ExitFinished, this, &FilesystemDevice::ExitFinished); + QObject::connect(&*backend_, &CollectionBackend::ExitFinished, this, &FilesystemDevice::ExitFinished); QObject::connect(watcher_, &CollectionWatcher::ExitFinished, this, &FilesystemDevice::ExitFinished); backend_->ExitAsync(); watcher_->ExitAsync(); diff --git a/src/device/filesystemdevice.h b/src/device/filesystemdevice.h index 76e392e4..d481b4a8 100644 --- a/src/device/filesystemdevice.h +++ b/src/device/filesystemdevice.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/filesystemmusicstorage.h" #include "connecteddevice.h" @@ -43,7 +44,7 @@ class FilesystemDevice : public ConnectedDevice, public virtual FilesystemMusicS Q_OBJECT public: - Q_INVOKABLE FilesystemDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); + Q_INVOKABLE FilesystemDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, SharedPtr manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); ~FilesystemDevice() override; Song::Source source() const final { return Song::Source::Device; } diff --git a/src/device/gpoddevice.cpp b/src/device/gpoddevice.cpp index fa9f5bec..ffe9c540 100644 --- a/src/device/gpoddevice.cpp +++ b/src/device/gpoddevice.cpp @@ -40,6 +40,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "collection/collectionbackend.h" #include "collection/collectionmodel.h" @@ -50,7 +51,9 @@ class DeviceLister; class DeviceManager; -GPodDevice::GPodDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent) +using std::make_shared; + +GPodDevice::GPodDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, SharedPtr manager, Application *app, const int database_id, const bool first_time, QObject *parent) : ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time, parent), loader_(nullptr), loader_thread_(nullptr), @@ -197,7 +200,7 @@ bool GPodDevice::CopyToStorage(const CopyJob &job) { QString temp_path = QStandardPaths::writableLocation(QStandardPaths::TempLocation); #endif if (!QDir(temp_path).exists()) QDir().mkpath(temp_path); - std::shared_ptr cover_file = std::make_shared(temp_path + "/track-albumcover-XXXXXX.jpg"); + SharedPtr cover_file = make_shared(temp_path + "/track-albumcover-XXXXXX.jpg"); cover_file->setAutoRemove(true); if (cover_file->open()) { cover_file->close(); diff --git a/src/device/gpoddevice.h b/src/device/gpoddevice.h index 06a032ae..493896c0 100644 --- a/src/device/gpoddevice.h +++ b/src/device/gpoddevice.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include @@ -37,6 +35,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "core/musicstorage.h" #include "connecteddevice.h" @@ -51,7 +50,7 @@ class GPodDevice : public ConnectedDevice, public virtual MusicStorage { Q_OBJECT public: - Q_INVOKABLE GPodDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); + Q_INVOKABLE GPodDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, SharedPtr manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); ~GPodDevice() override; bool Init() override; @@ -98,7 +97,7 @@ class GPodDevice : public ConnectedDevice, public virtual MusicStorage { QMutex db_busy_; SongList songs_to_add_; SongList songs_to_remove_; - QList> cover_files_; + QList> cover_files_; }; #endif // GPODDEVICE_H diff --git a/src/device/gpodloader.cpp b/src/device/gpodloader.cpp index 6dec0a90..432fe6ed 100644 --- a/src/device/gpodloader.cpp +++ b/src/device/gpodloader.cpp @@ -30,12 +30,13 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/song.h" #include "core/taskmanager.h" #include "collection/collectionbackend.h" #include "gpodloader.h" -GPodLoader::GPodLoader(const QString &mount_point, TaskManager *task_manager, CollectionBackend *backend, std::shared_ptr device, QObject *parent) +GPodLoader::GPodLoader(const QString &mount_point, SharedPtr task_manager, SharedPtr backend, SharedPtr device, QObject *parent) : QObject(parent), device_(device), mount_point_(mount_point), diff --git a/src/device/gpodloader.h b/src/device/gpodloader.h index 70452953..63c0d5d7 100644 --- a/src/device/gpodloader.h +++ b/src/device/gpodloader.h @@ -24,12 +24,12 @@ #include "config.h" -#include #include #include #include +#include "core/shared_ptr.h" #include "core/song.h" class QThread; @@ -41,7 +41,7 @@ class GPodLoader : public QObject { Q_OBJECT public: - explicit GPodLoader(const QString &mount_point, TaskManager *task_manager, CollectionBackend *backend, std::shared_ptr device, QObject *parent = nullptr); + explicit GPodLoader(const QString &mount_point, SharedPtr task_manager, SharedPtr backend, SharedPtr device, QObject *parent = nullptr); ~GPodLoader() override; void set_music_path_prefix(const QString &prefix) { path_prefix_ = prefix; } @@ -61,14 +61,14 @@ class GPodLoader : public QObject { Itdb_iTunesDB *TryLoad(); private: - std::shared_ptr device_; + SharedPtr device_; QThread *original_thread_; QString mount_point_; QString path_prefix_; Song::FileType type_; - TaskManager *task_manager_; - CollectionBackend *backend_; + SharedPtr task_manager_; + SharedPtr backend_; bool abort_; }; diff --git a/src/device/mtpconnection.h b/src/device/mtpconnection.h index 5be0d226..2b1a0cfe 100644 --- a/src/device/mtpconnection.h +++ b/src/device/mtpconnection.h @@ -35,7 +35,9 @@ #include "core/song.h" -class MtpConnection : public QObject, public std::enable_shared_from_this { +using std::enable_shared_from_this; + +class MtpConnection : public QObject, public enable_shared_from_this { Q_OBJECT public: diff --git a/src/device/mtpdevice.cpp b/src/device/mtpdevice.cpp index 2d46d920..bc6f72c3 100644 --- a/src/device/mtpdevice.cpp +++ b/src/device/mtpdevice.cpp @@ -34,6 +34,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/musicstorage.h" #include "collection/collectionmodel.h" @@ -48,7 +49,7 @@ class DeviceManager; bool MtpDevice::sInitializedLibMTP = false; -MtpDevice::MtpDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent) +MtpDevice::MtpDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, SharedPtr manager, Application *app, const int database_id, const bool first_time, QObject *parent) : ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time, parent), loader_(nullptr), loader_thread_(nullptr), diff --git a/src/device/mtpdevice.h b/src/device/mtpdevice.h index 07d2989a..d56f8925 100644 --- a/src/device/mtpdevice.h +++ b/src/device/mtpdevice.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -33,6 +31,8 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/song.h" #include "connecteddevice.h" @@ -48,7 +48,7 @@ class MtpDevice : public ConnectedDevice { Q_OBJECT public: - Q_INVOKABLE MtpDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, DeviceManager *manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); + Q_INVOKABLE MtpDevice(const QUrl &url, DeviceLister *lister, const QString &unique_id, SharedPtr manager, Application *app, const int database_id, const bool first_time, QObject *parent = nullptr); ~MtpDevice() override; static QStringList url_schemes() { return QStringList() << "mtp"; } @@ -90,8 +90,7 @@ class MtpDevice : public ConnectedDevice { SongList songs_to_add_; SongList songs_to_remove_; - std::unique_ptr connection_; - + ScopedPtr connection_; }; #endif // MTPDEVICE_H diff --git a/src/device/mtploader.cpp b/src/device/mtploader.cpp index 5a069c7a..4cb30b87 100644 --- a/src/device/mtploader.cpp +++ b/src/device/mtploader.cpp @@ -23,17 +23,21 @@ #include -#include -#include #include +#include +#include + +#include "core/shared_ptr.h" #include "core/taskmanager.h" #include "core/song.h" #include "collection/collectionbackend.h" #include "mtpconnection.h" #include "mtploader.h" -MtpLoader::MtpLoader(const QUrl &url, TaskManager *task_manager, CollectionBackend *backend, QObject *parent) +using std::make_unique; + +MtpLoader::MtpLoader(const QUrl &url, SharedPtr task_manager, SharedPtr backend, QObject *parent) : QObject(parent), url_(url), task_manager_(task_manager), @@ -62,7 +66,7 @@ void MtpLoader::LoadDatabase() { bool MtpLoader::TryLoad() { - connection_ = std::make_unique(url_); + connection_ = make_unique(url_); if (!connection_ || !connection_->is_valid()) { emit Error(tr("Error connecting MTP device %1").arg(url_.toString())); diff --git a/src/device/mtploader.h b/src/device/mtploader.h index 336b301f..7edf870b 100644 --- a/src/device/mtploader.h +++ b/src/device/mtploader.h @@ -24,12 +24,13 @@ #include "config.h" -#include - #include #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" + class QThread; class TaskManager; class CollectionBackend; @@ -39,7 +40,7 @@ class MtpLoader : public QObject { Q_OBJECT public: - explicit MtpLoader(const QUrl &url, TaskManager *task_manager, CollectionBackend *backend, QObject *parent = nullptr); + explicit MtpLoader(const QUrl &url, SharedPtr task_manager, SharedPtr backend, QObject *parent = nullptr); ~MtpLoader() override; bool Init(); @@ -58,9 +59,9 @@ class MtpLoader : public QObject { private: QUrl url_; - TaskManager *task_manager_; - CollectionBackend *backend_; - std::unique_ptr connection_; + SharedPtr task_manager_; + SharedPtr backend_; + ScopedPtr connection_; QThread *original_thread_; bool abort_; diff --git a/src/device/udisks2lister.cpp b/src/device/udisks2lister.cpp index ef8f7add..bf66e465 100644 --- a/src/device/udisks2lister.cpp +++ b/src/device/udisks2lister.cpp @@ -42,6 +42,8 @@ #include #include "core/logging.h" +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "utilities/diskutils.h" #include "udisks2lister.h" @@ -52,6 +54,9 @@ #include "udisks2filesystem.h" #include "udisks2job.h" +using std::make_unique; +using std::make_shared; + Udisks2Lister::Udisks2Lister(QObject *parent) : DeviceLister(parent) {} Udisks2Lister::~Udisks2Lister() = default; @@ -180,7 +185,7 @@ void Udisks2Lister::UpdateDeviceFreeSpace(const QString &id) { bool Udisks2Lister::Init() { - udisks2_interface_ = std::make_unique(udisks2_service_, "/org/freedesktop/UDisks2", QDBusConnection::systemBus()); + udisks2_interface_ = make_unique(udisks2_service_, "/org/freedesktop/UDisks2", QDBusConnection::systemBus()); QDBusPendingReply reply = udisks2_interface_->GetManagedObjects(); reply.waitForFinished(); @@ -206,8 +211,8 @@ bool Udisks2Lister::Init() { emit DeviceAdded(id); } - QObject::connect(udisks2_interface_.get(), &OrgFreedesktopDBusObjectManagerInterface::InterfacesAdded, this, &Udisks2Lister::DBusInterfaceAdded); - QObject::connect(udisks2_interface_.get(), &OrgFreedesktopDBusObjectManagerInterface::InterfacesRemoved, this, &Udisks2Lister::DBusInterfaceRemoved); + QObject::connect(&*udisks2_interface_, &OrgFreedesktopDBusObjectManagerInterface::InterfacesAdded, this, &Udisks2Lister::DBusInterfaceAdded); + QObject::connect(&*udisks2_interface_, &OrgFreedesktopDBusObjectManagerInterface::InterfacesRemoved, this, &Udisks2Lister::DBusInterfaceRemoved); return true; @@ -219,7 +224,7 @@ void Udisks2Lister::DBusInterfaceAdded(const QDBusObjectPath &path, const Interf if (interface.key() != "org.freedesktop.UDisks2.Job") continue; - std::shared_ptr job = std::make_shared(udisks2_service_, path.path(), QDBusConnection::systemBus()); + SharedPtr job = make_shared(udisks2_service_, path.path(), QDBusConnection::systemBus()); if (!job->isValid()) continue; @@ -247,7 +252,7 @@ void Udisks2Lister::DBusInterfaceAdded(const QDBusObjectPath &path, const Interf mounting_jobs_[path].dbus_interface = job; mounting_jobs_[path].is_mount = is_mount_job; mounting_jobs_[path].mounted_partitions = mounted_partitions; - QObject::connect(job.get(), &OrgFreedesktopUDisks2JobInterface::Completed, this, &Udisks2Lister::JobCompleted); + QObject::connect(&*job, &OrgFreedesktopUDisks2JobInterface::Completed, this, &Udisks2Lister::JobCompleted); } } } diff --git a/src/device/udisks2lister.h b/src/device/udisks2lister.h index 8243176a..f7e64a4d 100644 --- a/src/device/udisks2lister.h +++ b/src/device/udisks2lister.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -40,6 +38,9 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" + #include "dbus/metatypes.h" #include "devicelister.h" @@ -85,7 +86,7 @@ class Udisks2Lister : public DeviceLister { Udisks2Job(); bool is_mount; QList mounted_partitions; - std::shared_ptr dbus_interface; + SharedPtr dbus_interface; }; QMutex jobs_lock_; @@ -122,7 +123,7 @@ class Udisks2Lister : public DeviceLister { QMap device_data_; private: - std::unique_ptr udisks2_interface_; + ScopedPtr udisks2_interface_; static constexpr char udisks2_service_[] = "org.freedesktop.UDisks2"; }; diff --git a/src/dialogs/edittagdialog.cpp b/src/dialogs/edittagdialog.cpp index 62e3d0f3..7b08545a 100644 --- a/src/dialogs/edittagdialog.cpp +++ b/src/dialogs/edittagdialog.cpp @@ -120,7 +120,7 @@ EditTagDialog::EditTagDialog(Application *app, QWidget *parent) cover_art_is_set_(false), save_tag_pending_(0) { - QObject::connect(app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &EditTagDialog::AlbumCoverLoaded); + QObject::connect(&*app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &EditTagDialog::AlbumCoverLoaded); #ifdef HAVE_MUSICBRAINZ QObject::connect(tag_fetcher_, &TagFetcher::ResultAvailable, results_dialog_, &TrackSelectionDialog::FetchTagFinished, Qt::QueuedConnection); diff --git a/src/dialogs/lastfmimportdialog.cpp b/src/dialogs/lastfmimportdialog.cpp index 5967851f..fd41f8af 100644 --- a/src/dialogs/lastfmimportdialog.cpp +++ b/src/dialogs/lastfmimportdialog.cpp @@ -27,10 +27,11 @@ #include "lastfmimportdialog.h" #include "ui_lastfmimportdialog.h" +#include "core/shared_ptr.h" #include "core/iconloader.h" #include "scrobbler/lastfmimport.h" -LastFMImportDialog::LastFMImportDialog(LastFMImport *lastfm_import, QWidget *parent) +LastFMImportDialog::LastFMImportDialog(SharedPtr lastfm_import, QWidget *parent) : QDialog(parent), ui_(new Ui_LastFMImportDialog), lastfm_import_(lastfm_import), diff --git a/src/dialogs/lastfmimportdialog.h b/src/dialogs/lastfmimportdialog.h index 4c63a645..c4539a29 100644 --- a/src/dialogs/lastfmimportdialog.h +++ b/src/dialogs/lastfmimportdialog.h @@ -26,6 +26,8 @@ #include #include +#include "core/shared_ptr.h" + #include "ui_lastfmimportdialog.h" class QCloseEvent; @@ -35,7 +37,7 @@ class LastFMImportDialog : public QDialog { Q_OBJECT public: - explicit LastFMImportDialog(LastFMImport *lastfm_import, QWidget *parent = nullptr); + explicit LastFMImportDialog(SharedPtr lastfm_import, QWidget *parent = nullptr); ~LastFMImportDialog() override; protected: @@ -59,7 +61,7 @@ class LastFMImportDialog : public QDialog { private: Ui_LastFMImportDialog *ui_; - LastFMImport *lastfm_import_; + SharedPtr lastfm_import_; bool finished_; int playcount_total_; diff --git a/src/engine/ebur128analysis.cpp b/src/engine/ebur128analysis.cpp index 3771041a..fc2def57 100644 --- a/src/engine/ebur128analysis.cpp +++ b/src/engine/ebur128analysis.cpp @@ -45,6 +45,8 @@ #include "ebur128analysis.h" +using std::unique_ptr; + static const int kTimeoutSecs = 60; namespace { @@ -185,7 +187,7 @@ class EBUR128State { static std::optional Finalize(EBUR128State &&state); private: - std::unique_ptr st; + unique_ptr st; }; class EBUR128AnalysisImpl { @@ -342,7 +344,7 @@ GstFlowReturn EBUR128AnalysisImpl::NewBufferCallback(GstAppSink *app_sink, gpoin EBUR128AnalysisImpl *me = reinterpret_cast(self); - std::unique_ptr sample(gst_app_sink_pull_sample(app_sink)); + unique_ptr sample(gst_app_sink_pull_sample(app_sink)); if (!sample) return GST_FLOW_ERROR; const FrameFormat dsc(gst_sample_get_caps(&*sample)); diff --git a/src/engine/gstengine.cpp b/src/engine/gstengine.cpp index f6304a78..041b6f5c 100644 --- a/src/engine/gstengine.cpp +++ b/src/engine/gstengine.cpp @@ -48,6 +48,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/logging.h" #include "core/taskmanager.h" #include "core/signalchecker.h" @@ -58,6 +59,8 @@ #include "gstbufferconsumer.h" #include "enginemetadata.h" +using std::make_shared; + const char *GstEngine::kAutoSink = "autoaudiosink"; const char *GstEngine::kALSASink = "alsasink"; const char *GstEngine::kOpenALSASink = "openalsink"; @@ -75,7 +78,7 @@ const qint64 GstEngine::kTimerIntervalNanosec = 1000 * kNsecPerMsec; // 1s const qint64 GstEngine::kPreloadGapNanosec = 8000 * kNsecPerMsec; // 8s const qint64 GstEngine::kSeekDelayNanosec = 100 * kNsecPerMsec; // 100msec -GstEngine::GstEngine(TaskManager *task_manager, QObject *parent) +GstEngine::GstEngine(SharedPtr task_manager, QObject *parent) : EngineBase(parent), task_manager_(task_manager), gst_startup_(nullptr), @@ -197,7 +200,7 @@ bool GstEngine::Load(const QUrl &media_url, const QUrl &stream_url, const Engine return true; } - std::shared_ptr pipeline = CreatePipeline(media_url, stream_url, gst_url, force_stop_at_end ? end_nanosec : 0, ebur128_loudness_normalizing_gain_db_); + SharedPtr pipeline = CreatePipeline(media_url, stream_url, gst_url, force_stop_at_end ? end_nanosec : 0, ebur128_loudness_normalizing_gain_db_); if (!pipeline) return false; if (crossfade) StartFadeout(); @@ -269,7 +272,7 @@ void GstEngine::Stop(const bool stop_after) { // Check if we started a fade out. If it isn't finished yet and the user pressed stop, we cancel the fader and just stop the playback. if (is_fading_out_to_pause_) { - QObject::disconnect(current_pipeline_.get(), &GstEnginePipeline::FaderFinished, nullptr, nullptr); + QObject::disconnect(&*current_pipeline_, &GstEnginePipeline::FaderFinished, nullptr, nullptr); is_fading_out_to_pause_ = false; has_faded_out_ = true; @@ -291,7 +294,7 @@ void GstEngine::Pause() { // Check if we started a fade out. If it isn't finished yet and the user pressed play, we inverse the fader and resume the playback. if (is_fading_out_to_pause_) { - QObject::disconnect(current_pipeline_.get(), &GstEnginePipeline::FaderFinished, nullptr, nullptr); + QObject::disconnect(&*current_pipeline_, &GstEnginePipeline::FaderFinished, nullptr, nullptr); current_pipeline_->StartFader(fadeout_pause_duration_nanosec_, QTimeLine::Forward, QEasingCurve::InOutQuad, false); is_fading_out_to_pause_ = false; has_faded_out_ = false; @@ -322,7 +325,7 @@ void GstEngine::Unpause() { // Check if we faded out last time. If yes, fade in no matter what the settings say. // If we pause with fadeout, deactivate fadeout and resume playback, the player would be muted if not faded in. if (has_faded_out_) { - QObject::disconnect(current_pipeline_.get(), &GstEnginePipeline::FaderFinished, nullptr, nullptr); + QObject::disconnect(&*current_pipeline_, &GstEnginePipeline::FaderFinished, nullptr, nullptr); current_pipeline_->StartFader(fadeout_pause_duration_nanosec_, QTimeLine::Forward, QEasingCurve::InOutQuad, false); has_faded_out_ = false; } @@ -742,24 +745,24 @@ void GstEngine::StartFadeout() { if (is_fading_out_to_pause_) return; fadeout_pipeline_ = current_pipeline_; - QObject::disconnect(fadeout_pipeline_.get(), nullptr, nullptr, nullptr); + QObject::disconnect(&*fadeout_pipeline_, nullptr, nullptr, nullptr); fadeout_pipeline_->RemoveAllBufferConsumers(); fadeout_pipeline_->StartFader(fadeout_duration_nanosec_, QTimeLine::Backward); - QObject::connect(fadeout_pipeline_.get(), &GstEnginePipeline::FaderFinished, this, &GstEngine::FadeoutFinished); + QObject::connect(&*fadeout_pipeline_, &GstEnginePipeline::FaderFinished, this, &GstEngine::FadeoutFinished); } void GstEngine::StartFadeoutPause() { fadeout_pause_pipeline_ = current_pipeline_; - QObject::disconnect(fadeout_pause_pipeline_.get(), &GstEnginePipeline::FaderFinished, nullptr, nullptr); + QObject::disconnect(&*fadeout_pause_pipeline_, &GstEnginePipeline::FaderFinished, nullptr, nullptr); fadeout_pause_pipeline_->StartFader(fadeout_pause_duration_nanosec_, QTimeLine::Backward, QEasingCurve::InOutQuad, false); if (fadeout_pipeline_ && fadeout_pipeline_->state() == GST_STATE_PLAYING) { fadeout_pipeline_->StartFader(fadeout_pause_duration_nanosec_, QTimeLine::Backward, QEasingCurve::Linear, false); } - QObject::connect(fadeout_pause_pipeline_.get(), &GstEnginePipeline::FaderFinished, this, &GstEngine::FadeoutPauseFinished); + QObject::connect(&*fadeout_pause_pipeline_, &GstEnginePipeline::FaderFinished, this, &GstEngine::FadeoutPauseFinished); is_fading_out_to_pause_ = true; } @@ -780,11 +783,11 @@ void GstEngine::StopTimers() { } -std::shared_ptr GstEngine::CreatePipeline() { +SharedPtr GstEngine::CreatePipeline() { EnsureInitialized(); - std::shared_ptr ret = std::make_shared(); + SharedPtr ret = make_shared(); ret->set_output_device(output_, device_); ret->set_volume_enabled(volume_control_); ret->set_stereo_balancer_enabled(stereo_balancer_enabled_); @@ -805,22 +808,22 @@ std::shared_ptr GstEngine::CreatePipeline() { ret->AddBufferConsumer(consumer); } - QObject::connect(ret.get(), &GstEnginePipeline::EndOfStreamReached, this, &GstEngine::EndOfStreamReached); - QObject::connect(ret.get(), &GstEnginePipeline::Error, this, &GstEngine::HandlePipelineError); - QObject::connect(ret.get(), &GstEnginePipeline::MetadataFound, this, &GstEngine::NewMetaData); - QObject::connect(ret.get(), &GstEnginePipeline::BufferingStarted, this, &GstEngine::BufferingStarted); - QObject::connect(ret.get(), &GstEnginePipeline::BufferingProgress, this, &GstEngine::BufferingProgress); - QObject::connect(ret.get(), &GstEnginePipeline::BufferingFinished, this, &GstEngine::BufferingFinished); - QObject::connect(ret.get(), &GstEnginePipeline::VolumeChanged, this, &EngineBase::UpdateVolume); - QObject::connect(ret.get(), &GstEnginePipeline::AboutToFinish, this, &EngineBase::EmitAboutToFinish); + QObject::connect(&*ret, &GstEnginePipeline::EndOfStreamReached, this, &GstEngine::EndOfStreamReached); + QObject::connect(&*ret, &GstEnginePipeline::Error, this, &GstEngine::HandlePipelineError); + QObject::connect(&*ret, &GstEnginePipeline::MetadataFound, this, &GstEngine::NewMetaData); + QObject::connect(&*ret, &GstEnginePipeline::BufferingStarted, this, &GstEngine::BufferingStarted); + QObject::connect(&*ret, &GstEnginePipeline::BufferingProgress, this, &GstEngine::BufferingProgress); + QObject::connect(&*ret, &GstEnginePipeline::BufferingFinished, this, &GstEngine::BufferingFinished); + QObject::connect(&*ret, &GstEnginePipeline::VolumeChanged, this, &EngineBase::UpdateVolume); + QObject::connect(&*ret, &GstEnginePipeline::AboutToFinish, this, &EngineBase::EmitAboutToFinish); return ret; } -std::shared_ptr GstEngine::CreatePipeline(const QUrl &media_url, const QUrl &stream_url, const QByteArray &gst_url, const qint64 end_nanosec, const double ebur128_loudness_normalizing_gain_db) { +SharedPtr GstEngine::CreatePipeline(const QUrl &media_url, const QUrl &stream_url, const QByteArray &gst_url, const qint64 end_nanosec, const double ebur128_loudness_normalizing_gain_db) { - std::shared_ptr ret = CreatePipeline(); + SharedPtr ret = CreatePipeline(); QString error; if (!ret->InitFromUrl(media_url, stream_url, gst_url, end_nanosec, ebur128_loudness_normalizing_gain_db, error)) { ret.reset(); diff --git a/src/engine/gstengine.h b/src/engine/gstengine.h index 91bd5a05..8ceecaa9 100644 --- a/src/engine/gstengine.h +++ b/src/engine/gstengine.h @@ -25,7 +25,6 @@ #include "config.h" -#include #include #include @@ -39,6 +38,7 @@ #include #include +#include "core/shared_ptr.h" #include "enginebase.h" #include "gststartup.h" #include "gstbufferconsumer.h" @@ -52,7 +52,7 @@ class GstEngine : public EngineBase, public GstBufferConsumer { Q_OBJECT public: - explicit GstEngine(TaskManager *task_manager, QObject *parent = nullptr); + explicit GstEngine(SharedPtr task_manager, QObject *parent = nullptr); ~GstEngine() override; static const char *kAutoSink; @@ -131,8 +131,8 @@ class GstEngine : public EngineBase, public GstBufferConsumer { void StartTimers(); void StopTimers(); - std::shared_ptr CreatePipeline(); - std::shared_ptr CreatePipeline(const QUrl &media_url, const QUrl &stream_url, const QByteArray &gst_url, const qint64 end_nanosec, const double ebur128_loudness_normalizing_gain_db); + SharedPtr CreatePipeline(); + SharedPtr CreatePipeline(const QUrl &media_url, const QUrl &stream_url, const QByteArray &gst_url, const qint64 end_nanosec, const double ebur128_loudness_normalizing_gain_db); void UpdateScope(int chunk_length); @@ -157,15 +157,15 @@ class GstEngine : public EngineBase, public GstBufferConsumer { static const qint64 kPreloadGapNanosec; static const qint64 kSeekDelayNanosec; - TaskManager *task_manager_; + SharedPtr task_manager_; GstStartup *gst_startup_; GstDiscoverer *discoverer_; int buffering_task_id_; - std::shared_ptr current_pipeline_; - std::shared_ptr fadeout_pipeline_; - std::shared_ptr fadeout_pause_pipeline_; + SharedPtr current_pipeline_; + SharedPtr fadeout_pipeline_; + SharedPtr fadeout_pause_pipeline_; QList buffer_consumers_; diff --git a/src/engine/gstenginepipeline.cpp b/src/engine/gstenginepipeline.cpp index 3355065d..193f02cb 100644 --- a/src/engine/gstenginepipeline.cpp +++ b/src/engine/gstenginepipeline.cpp @@ -21,7 +21,6 @@ #include "config.h" -#include #include #include #include @@ -1655,8 +1654,8 @@ void GstEnginePipeline::StartFader(const qint64 duration_nanosec, const QTimeLin } timeline->deleteLater(); }); - QObject::connect(fader_.get(), &QTimeLine::valueChanged, this, &GstEnginePipeline::SetFaderVolume); - QObject::connect(fader_.get(), &QTimeLine::finished, this, &GstEnginePipeline::FaderTimelineFinished); + QObject::connect(&*fader_, &QTimeLine::valueChanged, this, &GstEnginePipeline::SetFaderVolume); + QObject::connect(&*fader_, &QTimeLine::finished, this, &GstEnginePipeline::FaderTimelineFinished); fader_->setDirection(direction); fader_->setEasingCurve(shape); fader_->setCurrentTime(static_cast(start_time)); diff --git a/src/engine/gstenginepipeline.h b/src/engine/gstenginepipeline.h index b670b7dc..d14d9fd3 100644 --- a/src/engine/gstenginepipeline.h +++ b/src/engine/gstenginepipeline.h @@ -24,7 +24,6 @@ #include "config.h" -#include #include #include #include @@ -44,6 +43,7 @@ #include #include +#include "core/shared_ptr.h" #include "enginemetadata.h" class QTimerEvent; @@ -294,7 +294,7 @@ class GstEnginePipeline : public QObject { gdouble volume_internal_; uint volume_percent_; - std::shared_ptr fader_; + SharedPtr fader_; QBasicTimer fader_fudge_timer_; bool use_fudge_timer_; diff --git a/src/engine/vlcengine.cpp b/src/engine/vlcengine.cpp index 3ba6eccf..5741733a 100644 --- a/src/engine/vlcengine.cpp +++ b/src/engine/vlcengine.cpp @@ -32,6 +32,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/taskmanager.h" #include "core/logging.h" #include "utilities/timeconstants.h" @@ -39,7 +40,7 @@ #include "vlcengine.h" #include "vlcscopedref.h" -VLCEngine::VLCEngine(TaskManager *task_manager, QObject *parent) +VLCEngine::VLCEngine(SharedPtr task_manager, QObject *parent) : EngineBase(parent), instance_(nullptr), player_(nullptr), diff --git a/src/engine/vlcengine.h b/src/engine/vlcengine.h index e09ff00c..c62ba831 100644 --- a/src/engine/vlcengine.h +++ b/src/engine/vlcengine.h @@ -33,6 +33,8 @@ #include #include +#include "core/shared_ptr.h" + #include "enginebase.h" struct libvlc_event_t; @@ -43,7 +45,7 @@ class VLCEngine : public EngineBase { Q_OBJECT public: - explicit VLCEngine(TaskManager *task_manager, QObject *parent = nullptr); + explicit VLCEngine(SharedPtr task_manager, QObject *parent = nullptr); ~VLCEngine() override; Type type() const override { return Type::VLC; } diff --git a/src/globalshortcuts/globalshortcutsbackend-macos.h b/src/globalshortcuts/globalshortcutsbackend-macos.h index d0015cbf..4abd1251 100644 --- a/src/globalshortcuts/globalshortcutsbackend-macos.h +++ b/src/globalshortcuts/globalshortcutsbackend-macos.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include "globalshortcutsbackend.h" #include @@ -33,6 +31,8 @@ #include #include +#include "core/scoped_ptr.h" + class GlobalShortcutsBackendMacOSPrivate; class GlobalShortcutsBackendMacOS : public GlobalShortcutsBackend { @@ -59,7 +59,7 @@ class GlobalShortcutsBackendMacOS : public GlobalShortcutsBackend { QMap shortcuts_; friend class GlobalShortcutsBackendMacOSPrivate; - std::unique_ptr p_; + ScopedPtr p_; }; #endif // GLOBALSHORTCUTSBACKEND_MACOS_H diff --git a/src/internet/internetcollectionview.cpp b/src/internet/internetcollectionview.cpp index 37ab9d8e..fab1b0b6 100644 --- a/src/internet/internetcollectionview.cpp +++ b/src/internet/internetcollectionview.cpp @@ -36,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/iconloader.h" #include "core/mimedata.h" @@ -79,11 +80,11 @@ InternetCollectionView::InternetCollectionView(QWidget *parent) } -void InternetCollectionView::Init(Application *app, CollectionBackend *backend, CollectionModel *model, const bool favorite) { +void InternetCollectionView::Init(Application *app, SharedPtr collection_backend, CollectionModel *collection_model, const bool favorite) { app_ = app; - collection_backend_ = backend; - collection_model_ = model; + collection_backend_ = collection_backend; + collection_model_ = collection_model; favorite_ = favorite; collection_model_->set_pretty_covers(true); diff --git a/src/internet/internetcollectionview.h b/src/internet/internetcollectionview.h index 1476c53f..9554a427 100644 --- a/src/internet/internetcollectionview.h +++ b/src/internet/internetcollectionview.h @@ -32,6 +32,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "widgets/autoexpandingtreeview.h" @@ -54,7 +55,7 @@ class InternetCollectionView : public AutoExpandingTreeView { public: explicit InternetCollectionView(QWidget *parent = nullptr); - void Init(Application *app, CollectionBackend *backend, CollectionModel *model, const bool favorite = false); + void Init(Application *app, SharedPtr collection_backend, CollectionModel *collection_model, const bool favorite = false); // Returns Songs currently selected in the collection view. // Please note that the selection is recursive meaning that if for example an album is selected this will return all of it's songs. @@ -111,7 +112,7 @@ class InternetCollectionView : public AutoExpandingTreeView { private: Application *app_; - CollectionBackend *collection_backend_; + SharedPtr collection_backend_; CollectionModel *collection_model_; CollectionFilterWidget *filter_; bool favorite_; diff --git a/src/internet/internetplaylistitem.cpp b/src/internet/internetplaylistitem.cpp index ae46c41b..bd70a374 100644 --- a/src/internet/internetplaylistitem.cpp +++ b/src/internet/internetplaylistitem.cpp @@ -39,7 +39,7 @@ InternetPlaylistItem::InternetPlaylistItem(const Song &metadata) InitMetadata(); } -InternetPlaylistItem::InternetPlaylistItem(InternetService *service, const Song &metadata) +InternetPlaylistItem::InternetPlaylistItem(InternetServicePtr service, const Song &metadata) : PlaylistItem(metadata.source()), source_(service->source()), metadata_(metadata) { diff --git a/src/internet/internetplaylistitem.h b/src/internet/internetplaylistitem.h index a5830ff2..be6ab389 100644 --- a/src/internet/internetplaylistitem.h +++ b/src/internet/internetplaylistitem.h @@ -27,6 +27,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "core/sqlrow.h" #include "playlist/playlistitem.h" @@ -38,7 +39,7 @@ class InternetPlaylistItem : public PlaylistItem { public: explicit InternetPlaylistItem(const Song::Source source); explicit InternetPlaylistItem(const Song &metadata); - explicit InternetPlaylistItem(InternetService *service, const Song &metadata); + explicit InternetPlaylistItem(SharedPtr service, const Song &metadata); bool InitFromQuery(const SqlRow &query) override; Song Metadata() const override; diff --git a/src/internet/internetsearchmodel.cpp b/src/internet/internetsearchmodel.cpp index 693e829b..907fcc6b 100644 --- a/src/internet/internetsearchmodel.cpp +++ b/src/internet/internetsearchmodel.cpp @@ -37,7 +37,7 @@ #include "internetsearchmodel.h" #include "internetsearchview.h" -InternetSearchModel::InternetSearchModel(InternetService *service, QObject *parent) +InternetSearchModel::InternetSearchModel(InternetServicePtr service, QObject *parent) : QStandardItemModel(parent), service_(service), proxy_(nullptr), diff --git a/src/internet/internetsearchmodel.h b/src/internet/internetsearchmodel.h index bd56f954..7f288c0b 100644 --- a/src/internet/internetsearchmodel.h +++ b/src/internet/internetsearchmodel.h @@ -36,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "collection/collectionmodel.h" #include "internetsearchview.h" @@ -50,7 +51,7 @@ class InternetSearchModel : public QStandardItemModel { Q_OBJECT public: - explicit InternetSearchModel(InternetService *service, QObject *parent = nullptr); + explicit InternetSearchModel(SharedPtr service, QObject *parent = nullptr); enum Role { Role_Result = CollectionModel::LastRole, @@ -85,7 +86,7 @@ class InternetSearchModel : public QStandardItemModel { void GetChildResults(const QStandardItem *item, InternetSearchView::ResultList *results, QSet *visited) const; private: - InternetService *service_; + SharedPtr service_; QSortFilterProxyModel *proxy_; bool use_pretty_covers_; QIcon artist_icon_; diff --git a/src/internet/internetsearchview.cpp b/src/internet/internetsearchview.cpp index f2f8de03..922217a9 100644 --- a/src/internet/internetsearchview.cpp +++ b/src/internet/internetsearchview.cpp @@ -83,6 +83,8 @@ #include "ui_internetsearchview.h" #include "settings/appearancesettingspage.h" +using std::make_unique; + const int InternetSearchView::kSwapModelsTimeoutMsec = 250; const int InternetSearchView::kDelayedSearchTimeoutMs = 200; const int InternetSearchView::kArtHeight = 32; @@ -143,7 +145,7 @@ InternetSearchView::InternetSearchView(QWidget *parent) InternetSearchView::~InternetSearchView() { delete ui_; } -void InternetSearchView::Init(Application *app, InternetService *service) { +void InternetSearchView::Init(Application *app, InternetServicePtr service) { app_ = app; service_ = service; @@ -191,13 +193,13 @@ void InternetSearchView::Init(Application *app, InternetService *service) { QObject::connect(ui_->results, &AutoExpandingTreeView::AddToPlaylistSignal, this, &InternetSearchView::AddToPlaylist); QObject::connect(ui_->results, &AutoExpandingTreeView::FocusOnFilterSignal, this, &InternetSearchView::FocusOnFilter); - QObject::connect(service_, &InternetService::SearchUpdateStatus, this, &InternetSearchView::UpdateStatus); - QObject::connect(service_, &InternetService::SearchProgressSetMaximum, this, &InternetSearchView::ProgressSetMaximum); - QObject::connect(service_, &InternetService::SearchUpdateProgress, this, &InternetSearchView::UpdateProgress); - QObject::connect(service_, &InternetService::SearchResults, this, &InternetSearchView::SearchDone); + QObject::connect(&*service_, &InternetService::SearchUpdateStatus, this, &InternetSearchView::UpdateStatus); + QObject::connect(&*service_, &InternetService::SearchProgressSetMaximum, this, &InternetSearchView::ProgressSetMaximum); + QObject::connect(&*service_, &InternetService::SearchUpdateProgress, this, &InternetSearchView::UpdateProgress); + QObject::connect(&*service_, &InternetService::SearchResults, this, &InternetSearchView::SearchDone); QObject::connect(app_, &Application::SettingsChanged, this, &InternetSearchView::ReloadSettings); - QObject::connect(app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &InternetSearchView::AlbumCoverLoaded); + QObject::connect(&*app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &InternetSearchView::AlbumCoverLoaded); QObject::connect(ui_->settings, &QToolButton::clicked, ui_->settings, &QToolButton::showMenu); @@ -679,8 +681,8 @@ void InternetSearchView::GroupByClicked(QAction *action) { if (action->property("group_by").isNull()) { if (!group_by_dialog_) { - group_by_dialog_ = std::make_unique(); - QObject::connect(group_by_dialog_.get(), &GroupByDialog::Accepted, this, &InternetSearchView::SetGroupBy); + group_by_dialog_ = make_unique(); + QObject::connect(&*group_by_dialog_, &GroupByDialog::Accepted, this, &InternetSearchView::SetGroupBy); } group_by_dialog_->show(); diff --git a/src/internet/internetsearchview.h b/src/internet/internetsearchview.h index 2b3977c8..628ad035 100644 --- a/src/internet/internetsearchview.h +++ b/src/internet/internetsearchview.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -40,6 +38,8 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/song.h" #include "collection/collectionmodel.h" #include "covermanager/albumcoverloaderresult.h" @@ -81,7 +81,7 @@ class InternetSearchView : public QWidget { }; using ResultList = QList; - void Init(Application *app, InternetService *service); + void Init(Application *app, SharedPtr service); bool SearchFieldHasFocus() const; void FocusSearchField(); @@ -183,9 +183,9 @@ class InternetSearchView : public QWidget { private: Application *app_; - InternetService *service_; + SharedPtr service_; Ui_InternetSearchView *ui_; - std::unique_ptr group_by_dialog_; + ScopedPtr group_by_dialog_; QMenu *context_menu_; QList context_actions_; diff --git a/src/internet/internetservice.h b/src/internet/internetservice.h index 5c841d70..da71c9a6 100644 --- a/src/internet/internetservice.h +++ b/src/internet/internetservice.h @@ -28,6 +28,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/settingsdialog.h" #include "internetsearchview.h" @@ -60,9 +61,9 @@ class InternetService : public QObject { virtual int Search(const QString &query, InternetSearchView::SearchType type) { Q_UNUSED(query); Q_UNUSED(type); return 0; } virtual void CancelSearch() {} - virtual CollectionBackend *artists_collection_backend() { return nullptr; } - virtual CollectionBackend *albums_collection_backend() { return nullptr; } - virtual CollectionBackend *songs_collection_backend() { return nullptr; } + virtual SharedPtr artists_collection_backend() { return nullptr; } + virtual SharedPtr albums_collection_backend() { return nullptr; } + virtual SharedPtr songs_collection_backend() { return nullptr; } virtual CollectionModel *artists_collection_model() { return nullptr; } virtual CollectionModel *albums_collection_model() { return nullptr; } @@ -142,6 +143,10 @@ class InternetService : public QObject { QString settings_group_; SettingsDialog::Page settings_page_; }; + +using InternetServicePtr = SharedPtr; + Q_DECLARE_METATYPE(InternetService*) +Q_DECLARE_METATYPE(InternetServicePtr) #endif // INTERNETSERVICE_H diff --git a/src/internet/internetservices.cpp b/src/internet/internetservices.cpp index df97b0ec..10df1c82 100644 --- a/src/internet/internetservices.cpp +++ b/src/internet/internetservices.cpp @@ -34,12 +34,13 @@ InternetServices::InternetServices(QObject *parent) : QObject(parent) {} InternetServices::~InternetServices() { while (!services_.isEmpty()) { - delete services_.take(services_.firstKey()); + InternetServicePtr service = services_.first(); + RemoveService(service); } } -void InternetServices::AddService(InternetService *service) { +void InternetServices::AddService(InternetServicePtr service) { services_.insert(service->source(), service); if (service->has_initial_load_settings()) service->InitialLoadSettings(); @@ -49,17 +50,17 @@ void InternetServices::AddService(InternetService *service) { } -void InternetServices::RemoveService(InternetService *service) { +void InternetServices::RemoveService(InternetServicePtr service) { if (!services_.contains(service->source())) return; services_.remove(service->source()); - QObject::disconnect(service, nullptr, this, nullptr); + QObject::disconnect(&*service, nullptr, this, nullptr); qLog(Debug) << "Removed internet service" << service->name(); } -InternetService *InternetServices::ServiceBySource(const Song::Source source) const { +InternetServicePtr InternetServices::ServiceBySource(const Song::Source source) const { if (services_.contains(source)) return services_.value(source); return nullptr; @@ -68,8 +69,8 @@ InternetService *InternetServices::ServiceBySource(const Song::Source source) co void InternetServices::ReloadSettings() { - QList services = services_.values(); - for (InternetService *service : services) { + QList services = services_.values(); + for (InternetServicePtr service : services) { service->ReloadSettings(); } @@ -77,10 +78,10 @@ void InternetServices::ReloadSettings() { void InternetServices::Exit() { - QList services = services_.values(); - for (InternetService *service : services) { - wait_for_exit_ << service; - QObject::connect(service, &InternetService::ExitFinished, this, &InternetServices::ExitReceived); + QList services = services_.values(); + for (InternetServicePtr service : services) { + wait_for_exit_ << &*service; + QObject::connect(&*service, &InternetService::ExitFinished, this, &InternetServices::ExitReceived); service->Exit(); } if (wait_for_exit_.isEmpty()) emit ExitFinished(); diff --git a/src/internet/internetservices.h b/src/internet/internetservices.h index 44b8cbcc..4d6f50a4 100644 --- a/src/internet/internetservices.h +++ b/src/internet/internetservices.h @@ -24,11 +24,14 @@ #include "config.h" +#include + #include #include #include #include +#include #include "core/song.h" class InternetService; @@ -40,14 +43,15 @@ class InternetServices : public QObject { explicit InternetServices(QObject *parent = nullptr); ~InternetServices() override; - InternetService *ServiceBySource(const Song::Source source) const; + SharedPtr ServiceBySource(const Song::Source source) const; + template - T *Service() { - return static_cast(ServiceBySource(T::kSource)); + SharedPtr Service() { + return std::static_pointer_cast(ServiceBySource(T::kSource)); } - void AddService(InternetService *service); - void RemoveService(InternetService *service); + void AddService(SharedPtr service); + void RemoveService(SharedPtr service); void ReloadSettings(); void Exit(); @@ -58,7 +62,7 @@ class InternetServices : public QObject { void ExitReceived(); private: - QMap services_; + QMap> services_; QList wait_for_exit_; }; diff --git a/src/internet/internetsongmimedata.h b/src/internet/internetsongmimedata.h index 05fc2a33..ad288869 100644 --- a/src/internet/internetsongmimedata.h +++ b/src/internet/internetsongmimedata.h @@ -21,6 +21,7 @@ #ifndef INTERNETSONGMIMEDATA_H #define INTERNETSONGMIMEDATA_H +#include "core/shared_ptr.h" #include "core/mimedata.h" #include "core/song.h" @@ -30,9 +31,9 @@ class InternetSongMimeData : public MimeData { Q_OBJECT public: - explicit InternetSongMimeData(InternetService *_service, QObject* = nullptr) : service(_service) {} + explicit InternetSongMimeData(SharedPtr _service, QObject* = nullptr) : service(_service) {} - InternetService *service; + SharedPtr service; SongList songs; }; diff --git a/src/internet/internetsongsview.cpp b/src/internet/internetsongsview.cpp index b768e5ea..648e0488 100644 --- a/src/internet/internetsongsview.cpp +++ b/src/internet/internetsongsview.cpp @@ -39,7 +39,7 @@ #include "internetcollectionview.h" #include "ui_internetcollectionviewcontainer.h" -InternetSongsView::InternetSongsView(Application *app, InternetService *service, const QString &settings_group, const SettingsDialog::Page settings_page, QWidget *parent) +InternetSongsView::InternetSongsView(Application *app, InternetServicePtr service, const QString &settings_group, const SettingsDialog::Page settings_page, QWidget *parent) : QWidget(parent), app_(app), service_(service), @@ -61,15 +61,15 @@ InternetSongsView::InternetSongsView(Application *app, InternetService *service, ui_->filter_widget->AddMenuAction(action_configure); QObject::connect(ui_->view, &InternetCollectionView::GetSongs, this, &InternetSongsView::GetSongs); - QObject::connect(ui_->view, &InternetCollectionView::RemoveSongs, service_, &InternetService::RemoveSongsByList); + QObject::connect(ui_->view, &InternetCollectionView::RemoveSongs, &*service_, &InternetService::RemoveSongsByList); QObject::connect(ui_->refresh, &QPushButton::clicked, this, &InternetSongsView::GetSongs); QObject::connect(ui_->close, &QPushButton::clicked, this, &InternetSongsView::AbortGetSongs); QObject::connect(ui_->abort, &QPushButton::clicked, this, &InternetSongsView::AbortGetSongs); - QObject::connect(service_, &InternetService::SongsResults, this, &InternetSongsView::SongsFinished); - QObject::connect(service_, &InternetService::SongsUpdateStatus, ui_->status, &QLabel::setText); - QObject::connect(service_, &InternetService::SongsProgressSetMaximum, ui_->progressbar, &QProgressBar::setMaximum); - QObject::connect(service_, &InternetService::SongsUpdateProgress, ui_->progressbar, &QProgressBar::setValue); + QObject::connect(&*service_, &InternetService::SongsResults, this, &InternetSongsView::SongsFinished); + QObject::connect(&*service_, &InternetService::SongsUpdateStatus, ui_->status, &QLabel::setText); + QObject::connect(&*service_, &InternetService::SongsProgressSetMaximum, ui_->progressbar, &QProgressBar::setMaximum); + QObject::connect(&*service_, &InternetService::SongsUpdateProgress, ui_->progressbar, &QProgressBar::setValue); QObject::connect(service_->songs_collection_model(), &CollectionModel::TotalArtistCountUpdated, ui_->view, &InternetCollectionView::TotalArtistCountUpdated); QObject::connect(service_->songs_collection_model(), &CollectionModel::TotalAlbumCountUpdated, ui_->view, &InternetCollectionView::TotalAlbumCountUpdated); diff --git a/src/internet/internetsongsview.h b/src/internet/internetsongsview.h index 38d06e33..2f196ebd 100644 --- a/src/internet/internetsongsview.h +++ b/src/internet/internetsongsview.h @@ -27,6 +27,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/settingsdialog.h" #include "ui_internetcollectionviewcontainer.h" @@ -41,7 +42,7 @@ class InternetSongsView : public QWidget { Q_OBJECT public: - explicit InternetSongsView(Application *app, InternetService *service, const QString &settings_group, const SettingsDialog::Page settings_page, QWidget *parent = nullptr); + explicit InternetSongsView(Application *app, SharedPtr service, const QString &settings_group, const SettingsDialog::Page settings_page, QWidget *parent = nullptr); ~InternetSongsView() override; void ReloadSettings(); @@ -59,7 +60,7 @@ class InternetSongsView : public QWidget { private: Application *app_; - InternetService *service_; + SharedPtr service_; QString settings_group_; SettingsDialog::Page settings_page_; Ui_InternetCollectionViewContainer *ui_; diff --git a/src/internet/internettabsview.cpp b/src/internet/internettabsview.cpp index 9f096b1c..43f79b0d 100644 --- a/src/internet/internettabsview.cpp +++ b/src/internet/internettabsview.cpp @@ -44,7 +44,7 @@ #include "internetcollectionviewcontainer.h" #include "ui_internettabsview.h" -InternetTabsView::InternetTabsView(Application *app, InternetService *service, const QString &settings_group, const SettingsDialog::Page settings_page, QWidget *parent) +InternetTabsView::InternetTabsView(Application *app, InternetServicePtr service, const QString &settings_group, const SettingsDialog::Page settings_page, QWidget *parent) : QWidget(parent), app_(app), service_(service), @@ -55,9 +55,9 @@ InternetTabsView::InternetTabsView(Application *app, InternetService *service, c ui_->setupUi(this); ui_->search_view->Init(app, service); - QObject::connect(ui_->search_view, &InternetSearchView::AddArtistsSignal, service_, &InternetService::AddArtists); - QObject::connect(ui_->search_view, &InternetSearchView::AddAlbumsSignal, service_, &InternetService::AddAlbums); - QObject::connect(ui_->search_view, &InternetSearchView::AddSongsSignal, service_, &InternetService::AddSongs); + QObject::connect(ui_->search_view, &InternetSearchView::AddArtistsSignal, &*service_, &InternetService::AddArtists); + QObject::connect(ui_->search_view, &InternetSearchView::AddAlbumsSignal, &*service_, &InternetService::AddAlbums); + QObject::connect(ui_->search_view, &InternetSearchView::AddSongsSignal, &*service_, &InternetService::AddSongs); QAction *action_configure = new QAction(IconLoader::Load("configure"), tr("Configure %1...").arg(Song::TextForSource(service_->source())), this); QObject::connect(action_configure, &QAction::triggered, this, &InternetTabsView::OpenSettingsDialog); @@ -73,15 +73,15 @@ InternetTabsView::InternetTabsView(Application *app, InternetService *service, c ui_->artists_collection->filter_widget()->AddMenuAction(action_configure); QObject::connect(ui_->artists_collection->view(), &InternetCollectionView::GetSongs, this, &InternetTabsView::GetArtists); - QObject::connect(ui_->artists_collection->view(), &InternetCollectionView::RemoveSongs, service_, &InternetService::RemoveArtists); + QObject::connect(ui_->artists_collection->view(), &InternetCollectionView::RemoveSongs, &*service_, &InternetService::RemoveArtists); QObject::connect(ui_->artists_collection->button_refresh(), &QPushButton::clicked, this, &InternetTabsView::GetArtists); QObject::connect(ui_->artists_collection->button_close(), &QPushButton::clicked, this, &InternetTabsView::AbortGetArtists); QObject::connect(ui_->artists_collection->button_abort(), &QPushButton::clicked, this, &InternetTabsView::AbortGetArtists); - QObject::connect(service_, &InternetService::ArtistsResults, this, &InternetTabsView::ArtistsFinished); - QObject::connect(service_, &InternetService::ArtistsUpdateStatus, ui_->artists_collection->status(), &QLabel::setText); - QObject::connect(service_, &InternetService::ArtistsProgressSetMaximum, ui_->artists_collection->progressbar(), &QProgressBar::setMaximum); - QObject::connect(service_, &InternetService::ArtistsUpdateProgress, ui_->artists_collection->progressbar(), &QProgressBar::setValue); + QObject::connect(&*service_, &InternetService::ArtistsResults, this, &InternetTabsView::ArtistsFinished); + QObject::connect(&*service_, &InternetService::ArtistsUpdateStatus, ui_->artists_collection->status(), &QLabel::setText); + QObject::connect(&*service_, &InternetService::ArtistsProgressSetMaximum, ui_->artists_collection->progressbar(), &QProgressBar::setMaximum); + QObject::connect(&*service_, &InternetService::ArtistsUpdateProgress, ui_->artists_collection->progressbar(), &QProgressBar::setValue); QObject::connect(service_->artists_collection_model(), &CollectionModel::TotalArtistCountUpdated, ui_->artists_collection->view(), &InternetCollectionView::TotalArtistCountUpdated); QObject::connect(service_->artists_collection_model(), &CollectionModel::TotalAlbumCountUpdated, ui_->artists_collection->view(), &InternetCollectionView::TotalAlbumCountUpdated); @@ -105,15 +105,15 @@ InternetTabsView::InternetTabsView(Application *app, InternetService *service, c ui_->albums_collection->filter_widget()->AddMenuAction(action_configure); QObject::connect(ui_->albums_collection->view(), &InternetCollectionView::GetSongs, this, &InternetTabsView::GetAlbums); - QObject::connect(ui_->albums_collection->view(), &InternetCollectionView::RemoveSongs, service_, &InternetService::RemoveAlbums); + QObject::connect(ui_->albums_collection->view(), &InternetCollectionView::RemoveSongs, &*service_, &InternetService::RemoveAlbums); QObject::connect(ui_->albums_collection->button_refresh(), &QPushButton::clicked, this, &InternetTabsView::GetAlbums); QObject::connect(ui_->albums_collection->button_close(), &QPushButton::clicked, this, &InternetTabsView::AbortGetAlbums); QObject::connect(ui_->albums_collection->button_abort(), &QPushButton::clicked, this, &InternetTabsView::AbortGetAlbums); - QObject::connect(service_, &InternetService::AlbumsResults, this, &InternetTabsView::AlbumsFinished); - QObject::connect(service_, &InternetService::AlbumsUpdateStatus, ui_->albums_collection->status(), &QLabel::setText); - QObject::connect(service_, &InternetService::AlbumsProgressSetMaximum, ui_->albums_collection->progressbar(), &QProgressBar::setMaximum); - QObject::connect(service_, &InternetService::AlbumsUpdateProgress, ui_->albums_collection->progressbar(), &QProgressBar::setValue); + QObject::connect(&*service_, &InternetService::AlbumsResults, this, &InternetTabsView::AlbumsFinished); + QObject::connect(&*service_, &InternetService::AlbumsUpdateStatus, ui_->albums_collection->status(), &QLabel::setText); + QObject::connect(&*service_, &InternetService::AlbumsProgressSetMaximum, ui_->albums_collection->progressbar(), &QProgressBar::setMaximum); + QObject::connect(&*service_, &InternetService::AlbumsUpdateProgress, ui_->albums_collection->progressbar(), &QProgressBar::setValue); QObject::connect(service_->albums_collection_model(), &CollectionModel::TotalArtistCountUpdated, ui_->albums_collection->view(), &InternetCollectionView::TotalArtistCountUpdated); QObject::connect(service_->albums_collection_model(), &CollectionModel::TotalAlbumCountUpdated, ui_->albums_collection->view(), &InternetCollectionView::TotalAlbumCountUpdated); @@ -137,15 +137,15 @@ InternetTabsView::InternetTabsView(Application *app, InternetService *service, c ui_->songs_collection->filter_widget()->AddMenuAction(action_configure); QObject::connect(ui_->songs_collection->view(), &InternetCollectionView::GetSongs, this, &InternetTabsView::GetSongs); - QObject::connect(ui_->songs_collection->view(), &InternetCollectionView::RemoveSongs, service_, &InternetService::RemoveSongsByList); + QObject::connect(ui_->songs_collection->view(), &InternetCollectionView::RemoveSongs, &*service_, &InternetService::RemoveSongsByList); QObject::connect(ui_->songs_collection->button_refresh(), &QPushButton::clicked, this, &InternetTabsView::GetSongs); QObject::connect(ui_->songs_collection->button_close(), &QPushButton::clicked, this, &InternetTabsView::AbortGetSongs); QObject::connect(ui_->songs_collection->button_abort(), &QPushButton::clicked, this, &InternetTabsView::AbortGetSongs); - QObject::connect(service_, &InternetService::SongsResults, this, &InternetTabsView::SongsFinished); - QObject::connect(service_, &InternetService::SongsUpdateStatus, ui_->songs_collection->status(), &QLabel::setText); - QObject::connect(service_, &InternetService::SongsProgressSetMaximum, ui_->songs_collection->progressbar(), &QProgressBar::setMaximum); - QObject::connect(service_, &InternetService::SongsUpdateProgress, ui_->songs_collection->progressbar(), &QProgressBar::setValue); + QObject::connect(&*service_, &InternetService::SongsResults, this, &InternetTabsView::SongsFinished); + QObject::connect(&*service_, &InternetService::SongsUpdateStatus, ui_->songs_collection->status(), &QLabel::setText); + QObject::connect(&*service_, &InternetService::SongsProgressSetMaximum, ui_->songs_collection->progressbar(), &QProgressBar::setMaximum); + QObject::connect(&*service_, &InternetService::SongsUpdateProgress, ui_->songs_collection->progressbar(), &QProgressBar::setValue); QObject::connect(service_->songs_collection_model(), &CollectionModel::TotalArtistCountUpdated, ui_->songs_collection->view(), &InternetCollectionView::TotalArtistCountUpdated); QObject::connect(service_->songs_collection_model(), &CollectionModel::TotalAlbumCountUpdated, ui_->songs_collection->view(), &InternetCollectionView::TotalAlbumCountUpdated); diff --git a/src/internet/internettabsview.h b/src/internet/internettabsview.h index 57e79d5a..51203e2d 100644 --- a/src/internet/internettabsview.h +++ b/src/internet/internettabsview.h @@ -27,6 +27,7 @@ #include #include +#include "core/shared_ptr.h" #include "settings/settingsdialog.h" #include "internetcollectionviewcontainer.h" #include "ui_internettabsview.h" @@ -43,7 +44,7 @@ class InternetTabsView : public QWidget { Q_OBJECT public: - explicit InternetTabsView(Application *app, InternetService *service, const QString &settings_group, const SettingsDialog::Page settings_page, QWidget *parent = nullptr); + explicit InternetTabsView(Application *app, SharedPtr service, const QString &settings_group, const SettingsDialog::Page settings_page, QWidget *parent = nullptr); ~InternetTabsView() override; void ReloadSettings(); @@ -70,7 +71,7 @@ class InternetTabsView : public QWidget { private: Application *app_; - InternetService *service_; + SharedPtr service_; QString settings_group_; SettingsDialog::Page settings_page_; Ui_InternetTabsView *ui_; diff --git a/src/lyrics/chartlyricsprovider.cpp b/src/lyrics/chartlyricsprovider.cpp index 6841a6ea..7cccdfcf 100644 --- a/src/lyrics/chartlyricsprovider.cpp +++ b/src/lyrics/chartlyricsprovider.cpp @@ -30,6 +30,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "utilities/strutils.h" #include "lyricssearchrequest.h" @@ -38,7 +39,7 @@ const char *ChartLyricsProvider::kUrlSearch = "http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect"; -ChartLyricsProvider::ChartLyricsProvider(NetworkAccessManager *network, QObject *parent) : LyricsProvider("ChartLyrics", false, false, network, parent) {} +ChartLyricsProvider::ChartLyricsProvider(SharedPtr network, QObject *parent) : LyricsProvider("ChartLyrics", false, false, network, parent) {} ChartLyricsProvider::~ChartLyricsProvider() { diff --git a/src/lyrics/chartlyricsprovider.h b/src/lyrics/chartlyricsprovider.h index 9e24ad6e..984b563e 100644 --- a/src/lyrics/chartlyricsprovider.h +++ b/src/lyrics/chartlyricsprovider.h @@ -27,6 +27,7 @@ #include #include +#include "core/shared_ptr.h" #include "lyricsprovider.h" #include "lyricsfetcher.h" @@ -37,7 +38,7 @@ class ChartLyricsProvider : public LyricsProvider { Q_OBJECT public: - explicit ChartLyricsProvider(NetworkAccessManager *network, QObject *parent = nullptr); + explicit ChartLyricsProvider(SharedPtr network, QObject *parent = nullptr); ~ChartLyricsProvider() override; bool StartSearch(const int id, const LyricsSearchRequest &request) override; diff --git a/src/lyrics/geniuslyricsprovider.cpp b/src/lyrics/geniuslyricsprovider.cpp index 60a3a607..8b3338f3 100644 --- a/src/lyrics/geniuslyricsprovider.cpp +++ b/src/lyrics/geniuslyricsprovider.cpp @@ -43,12 +43,15 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "utilities/randutils.h" #include "internet/localredirectserver.h" #include "jsonlyricsprovider.h" #include "geniuslyricsprovider.h" +using std::make_shared; + const char *GeniusLyricsProvider::kSettingsGroup = "GeniusLyrics"; const char *GeniusLyricsProvider::kOAuthAuthorizeUrl = "https://api.genius.com/oauth/authorize"; const char *GeniusLyricsProvider::kOAuthAccessTokenUrl = "https://api.genius.com/oauth/token"; @@ -57,7 +60,7 @@ const char *GeniusLyricsProvider::kUrlSearch = "https://api.genius.com/search/"; const char *GeniusLyricsProvider::kClientIDB64 = "RUNTNXU4U1VyMU1KUU5hdTZySEZteUxXY2hkanFiY3lfc2JjdXBpNG5WMU9SNUg4dTBZelEtZTZCdFg2dl91SQ=="; const char *GeniusLyricsProvider::kClientSecretB64 = "VE9pMU9vUjNtTXZ3eFR3YVN0QVRyUjVoUlhVWDI1Ylp5X240eEt1M0ZkYlNwRG5JUnd0LXFFbHdGZkZkRWY2VzJ1S011UnQzM3c2Y3hqY0tVZ3NGN2c="; -GeniusLyricsProvider::GeniusLyricsProvider(NetworkAccessManager *network, QObject *parent) : JsonLyricsProvider("Genius", true, true, network, parent), server_(nullptr) { +GeniusLyricsProvider::GeniusLyricsProvider(SharedPtr network, QObject *parent) : JsonLyricsProvider("Genius", true, true, network, parent), server_(nullptr) { QSettings s; s.beginGroup(kSettingsGroup); @@ -287,7 +290,7 @@ bool GeniusLyricsProvider::StartSearch(const int id, const LyricsSearchRequest & if (access_token_.isEmpty()) return false; - GeniusLyricsSearchContextPtr search = std::make_shared(); + GeniusLyricsSearchContextPtr search = make_shared(); search->id = id; search->request = request; requests_search_.insert(id, search); diff --git a/src/lyrics/geniuslyricsprovider.h b/src/lyrics/geniuslyricsprovider.h index f8505809..1baf924e 100644 --- a/src/lyrics/geniuslyricsprovider.h +++ b/src/lyrics/geniuslyricsprovider.h @@ -22,8 +22,6 @@ #include "config.h" -#include - #include #include #include @@ -35,6 +33,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsonlyricsprovider.h" #include "lyricssearchrequest.h" #include "lyricssearchresult.h" @@ -47,7 +46,7 @@ class GeniusLyricsProvider : public JsonLyricsProvider { Q_OBJECT public: - explicit GeniusLyricsProvider(NetworkAccessManager *network, QObject *parent = nullptr); + explicit GeniusLyricsProvider(SharedPtr network, QObject *parent = nullptr); ~GeniusLyricsProvider() override; bool IsAuthenticated() const override { return !access_token_.isEmpty(); } @@ -72,7 +71,7 @@ class GeniusLyricsProvider : public JsonLyricsProvider { LyricsSearchResults results; }; - using GeniusLyricsSearchContextPtr = std::shared_ptr; + using GeniusLyricsSearchContextPtr = SharedPtr; private: void RequestAccessToken(const QUrl &url, const QUrl &redirect_url); @@ -102,7 +101,7 @@ class GeniusLyricsProvider : public JsonLyricsProvider { QString code_challenge_; QString access_token_; QStringList login_errors_; - QMap> requests_search_; + QMap> requests_search_; QList replies_; }; diff --git a/src/lyrics/jsonlyricsprovider.cpp b/src/lyrics/jsonlyricsprovider.cpp index 2519d342..7a340b9c 100644 --- a/src/lyrics/jsonlyricsprovider.cpp +++ b/src/lyrics/jsonlyricsprovider.cpp @@ -27,10 +27,11 @@ #include #include +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "jsonlyricsprovider.h" -JsonLyricsProvider::JsonLyricsProvider(const QString &name, const bool enabled, const bool authentication_required, NetworkAccessManager *network, QObject *parent) : LyricsProvider(name, enabled, authentication_required, network, parent) {} +JsonLyricsProvider::JsonLyricsProvider(const QString &name, const bool enabled, const bool authentication_required, SharedPtr network, QObject *parent) : LyricsProvider(name, enabled, authentication_required, network, parent) {} QByteArray JsonLyricsProvider::ExtractData(QNetworkReply *reply) { diff --git a/src/lyrics/jsonlyricsprovider.h b/src/lyrics/jsonlyricsprovider.h index cecc003b..58135424 100644 --- a/src/lyrics/jsonlyricsprovider.h +++ b/src/lyrics/jsonlyricsprovider.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "lyricsprovider.h" class NetworkAccessManager; @@ -38,7 +39,7 @@ class JsonLyricsProvider : public LyricsProvider { Q_OBJECT public: - explicit JsonLyricsProvider(const QString &name, const bool enabled, const bool authentication_required, NetworkAccessManager *network, QObject *parent = nullptr); + explicit JsonLyricsProvider(const QString &name, const bool enabled, const bool authentication_required, SharedPtr network, QObject *parent = nullptr); protected: QByteArray ExtractData(QNetworkReply *reply); diff --git a/src/lyrics/lololyricsprovider.cpp b/src/lyrics/lololyricsprovider.cpp index cce37109..c9fc3931 100644 --- a/src/lyrics/lololyricsprovider.cpp +++ b/src/lyrics/lololyricsprovider.cpp @@ -30,6 +30,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "utilities/strutils.h" #include "lyricssearchrequest.h" @@ -38,7 +39,7 @@ const char *LoloLyricsProvider::kUrlSearch = "http://api.lololyrics.com/0.5/getLyric"; -LoloLyricsProvider::LoloLyricsProvider(NetworkAccessManager *network, QObject *parent) : LyricsProvider("LoloLyrics", true, false, network, parent) {} +LoloLyricsProvider::LoloLyricsProvider(SharedPtr network, QObject *parent) : LyricsProvider("LoloLyrics", true, false, network, parent) {} LoloLyricsProvider::~LoloLyricsProvider() { diff --git a/src/lyrics/lololyricsprovider.h b/src/lyrics/lololyricsprovider.h index 755f9359..be1d3306 100644 --- a/src/lyrics/lololyricsprovider.h +++ b/src/lyrics/lololyricsprovider.h @@ -28,6 +28,7 @@ #include #include +#include "core/shared_ptr.h" #include "lyricsprovider.h" #include "lyricssearchrequest.h" @@ -38,7 +39,7 @@ class LoloLyricsProvider : public LyricsProvider { Q_OBJECT public: - explicit LoloLyricsProvider(NetworkAccessManager *network, QObject *parent = nullptr); + explicit LoloLyricsProvider(SharedPtr network, QObject *parent = nullptr); ~LoloLyricsProvider() override; bool StartSearch(const int id, const LyricsSearchRequest &request) override; diff --git a/src/lyrics/lyricscomlyricsprovider.cpp b/src/lyrics/lyricscomlyricsprovider.cpp index 8afea3e5..8265db98 100644 --- a/src/lyrics/lyricscomlyricsprovider.cpp +++ b/src/lyrics/lyricscomlyricsprovider.cpp @@ -33,6 +33,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "lyricssearchrequest.h" #include "lyricssearchresult.h" @@ -43,7 +44,7 @@ const char *LyricsComLyricsProvider::kLyricsUrl = "https://www.lyrics.com/lyrics const char *LyricsComLyricsProvider::kUID = "11363"; const char *LyricsComLyricsProvider::kTokenB64 = "b3FOYmxhV1ZKRGxIMnV4OA=="; -LyricsComLyricsProvider::LyricsComLyricsProvider(NetworkAccessManager *network, QObject *parent) : JsonLyricsProvider("Lyrics.com", true, false, network, parent), use_api_(true) {} +LyricsComLyricsProvider::LyricsComLyricsProvider(SharedPtr network, QObject *parent) : JsonLyricsProvider("Lyrics.com", true, false, network, parent), use_api_(true) {} LyricsComLyricsProvider::~LyricsComLyricsProvider() { diff --git a/src/lyrics/lyricscomlyricsprovider.h b/src/lyrics/lyricscomlyricsprovider.h index de81a85f..8b1601af 100644 --- a/src/lyrics/lyricscomlyricsprovider.h +++ b/src/lyrics/lyricscomlyricsprovider.h @@ -27,6 +27,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsonlyricsprovider.h" #include "lyricssearchrequest.h" @@ -37,7 +38,7 @@ class LyricsComLyricsProvider : public JsonLyricsProvider { Q_OBJECT public: - explicit LyricsComLyricsProvider(NetworkAccessManager *network, QObject *parent = nullptr); + explicit LyricsComLyricsProvider(SharedPtr network, QObject *parent = nullptr); ~LyricsComLyricsProvider() override; bool StartSearch(const int id, const LyricsSearchRequest &request) override; diff --git a/src/lyrics/lyricsfetcher.cpp b/src/lyrics/lyricsfetcher.cpp index ffa6c636..9e65dbd7 100644 --- a/src/lyrics/lyricsfetcher.cpp +++ b/src/lyrics/lyricsfetcher.cpp @@ -26,6 +26,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "lyricsfetcher.h" #include "lyricsfetchersearch.h" @@ -36,7 +37,7 @@ using namespace std::chrono_literals; const int LyricsFetcher::kMaxConcurrentRequests = 5; -LyricsFetcher::LyricsFetcher(LyricsProviders *lyrics_providers, QObject *parent) +LyricsFetcher::LyricsFetcher(SharedPtr lyrics_providers, QObject *parent) : QObject(parent), lyrics_providers_(lyrics_providers), next_id_(0), diff --git a/src/lyrics/lyricsfetcher.h b/src/lyrics/lyricsfetcher.h index 4ad1b640..b214af2b 100644 --- a/src/lyrics/lyricsfetcher.h +++ b/src/lyrics/lyricsfetcher.h @@ -32,6 +32,7 @@ #include #include +#include "core/shared_ptr.h" #include "lyricssearchrequest.h" #include "lyricssearchresult.h" @@ -43,7 +44,7 @@ class LyricsFetcher : public QObject { Q_OBJECT public: - explicit LyricsFetcher(LyricsProviders *lyrics_providers, QObject *parent = nullptr); + explicit LyricsFetcher(SharedPtr lyrics_providers, QObject *parent = nullptr); ~LyricsFetcher() override {} struct Request { @@ -70,7 +71,7 @@ class LyricsFetcher : public QObject { private: static const int kMaxConcurrentRequests; - LyricsProviders *lyrics_providers_; + SharedPtr lyrics_providers_; quint64 next_id_; QQueue queued_requests_; diff --git a/src/lyrics/lyricsfetchersearch.cpp b/src/lyrics/lyricsfetchersearch.cpp index 35d082d0..290e74a5 100644 --- a/src/lyrics/lyricsfetchersearch.cpp +++ b/src/lyrics/lyricsfetchersearch.cpp @@ -26,6 +26,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "lyricsfetchersearch.h" #include "lyricssearchrequest.h" #include "lyricssearchresult.h" @@ -56,7 +57,7 @@ void LyricsFetcherSearch::TerminateSearch() { } -void LyricsFetcherSearch::Start(LyricsProviders *lyrics_providers) { +void LyricsFetcherSearch::Start(SharedPtr lyrics_providers) { // Ignore Radio Paradise "commercial" break. if (request_.artist.compare("commercial-free", Qt::CaseInsensitive) == 0 && request_.title.compare("listener-supported", Qt::CaseInsensitive) == 0) { diff --git a/src/lyrics/lyricsfetchersearch.h b/src/lyrics/lyricsfetchersearch.h index c9995225..f20367e0 100644 --- a/src/lyrics/lyricsfetchersearch.h +++ b/src/lyrics/lyricsfetchersearch.h @@ -27,6 +27,7 @@ #include #include +#include "core/shared_ptr.h" #include "lyricssearchrequest.h" #include "lyricssearchresult.h" @@ -39,7 +40,7 @@ class LyricsFetcherSearch : public QObject { public: explicit LyricsFetcherSearch(const quint64 id, const LyricsSearchRequest &request, QObject *parent); - void Start(LyricsProviders *lyrics_providers); + void Start(SharedPtr lyrics_providers); void Cancel(); signals: diff --git a/src/lyrics/lyricsprovider.cpp b/src/lyrics/lyricsprovider.cpp index 80dea974..a6cab13b 100644 --- a/src/lyrics/lyricsprovider.cpp +++ b/src/lyrics/lyricsprovider.cpp @@ -24,10 +24,11 @@ #include #include "utilities/strutils.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "lyricsprovider.h" -LyricsProvider::LyricsProvider(const QString &name, const bool enabled, const bool authentication_required, NetworkAccessManager *network, QObject *parent) +LyricsProvider::LyricsProvider(const QString &name, const bool enabled, const bool authentication_required, SharedPtr network, QObject *parent) : QObject(parent), network_(network), name_(name), enabled_(enabled), order_(0), authentication_required_(authentication_required) {} QString LyricsProvider::ParseLyricsFromHTML(const QString &content, const QRegularExpression &start_tag, const QRegularExpression &end_tag, const QRegularExpression &lyrics_start, const bool multiple) { diff --git a/src/lyrics/lyricsprovider.h b/src/lyrics/lyricsprovider.h index 57e56821..1931607d 100644 --- a/src/lyrics/lyricsprovider.h +++ b/src/lyrics/lyricsprovider.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "lyricssearchrequest.h" #include "lyricssearchresult.h" @@ -38,7 +39,7 @@ class LyricsProvider : public QObject { Q_OBJECT public: - explicit LyricsProvider(const QString &name, const bool enabled, const bool authentication_required, NetworkAccessManager *network, QObject *parent); + explicit LyricsProvider(const QString &name, const bool enabled, const bool authentication_required, SharedPtr network, QObject *parent); QString name() const { return name_; } bool is_enabled() const { return enabled_; } @@ -66,7 +67,7 @@ class LyricsProvider : public QObject { void SearchFinished(const int id, const LyricsSearchResults &results = LyricsSearchResults()); protected: - NetworkAccessManager *network_; + SharedPtr network_; QString name_; bool enabled_; int order_; diff --git a/src/lyrics/musixmatchlyricsprovider.cpp b/src/lyrics/musixmatchlyricsprovider.cpp index a4ffffec..893b38a7 100644 --- a/src/lyrics/musixmatchlyricsprovider.cpp +++ b/src/lyrics/musixmatchlyricsprovider.cpp @@ -34,6 +34,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "utilities/strutils.h" #include "jsonlyricsprovider.h" @@ -42,7 +43,9 @@ #include "musixmatchlyricsprovider.h" #include "providers/musixmatchprovider.h" -MusixmatchLyricsProvider::MusixmatchLyricsProvider(NetworkAccessManager *network, QObject *parent) : JsonLyricsProvider("Musixmatch", true, false, network, parent), use_api_(true) {} +using std::make_shared; + +MusixmatchLyricsProvider::MusixmatchLyricsProvider(SharedPtr network, QObject *parent) : JsonLyricsProvider("Musixmatch", true, false, network, parent), use_api_(true) {} MusixmatchLyricsProvider::~MusixmatchLyricsProvider() { @@ -57,7 +60,7 @@ MusixmatchLyricsProvider::~MusixmatchLyricsProvider() { bool MusixmatchLyricsProvider::StartSearch(const int id, const LyricsSearchRequest &request) { - LyricsSearchContextPtr search = std::make_shared(); + LyricsSearchContextPtr search = make_shared(); search->id = id; search->request = request; requests_search_.append(search); diff --git a/src/lyrics/musixmatchlyricsprovider.h b/src/lyrics/musixmatchlyricsprovider.h index 79bb69d4..1f078ccb 100644 --- a/src/lyrics/musixmatchlyricsprovider.h +++ b/src/lyrics/musixmatchlyricsprovider.h @@ -22,8 +22,6 @@ #include "config.h" -#include - #include #include #include @@ -31,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsonlyricsprovider.h" #include "lyricssearchrequest.h" #include "lyricssearchresult.h" @@ -43,7 +42,7 @@ class MusixmatchLyricsProvider : public JsonLyricsProvider, public MusixmatchPro Q_OBJECT public: - explicit MusixmatchLyricsProvider(NetworkAccessManager *network, QObject *parent = nullptr); + explicit MusixmatchLyricsProvider(SharedPtr network, QObject *parent = nullptr); ~MusixmatchLyricsProvider() override; bool StartSearch(const int id, const LyricsSearchRequest &request) override; @@ -58,7 +57,7 @@ class MusixmatchLyricsProvider : public JsonLyricsProvider, public MusixmatchPro LyricsSearchResults results; }; - using LyricsSearchContextPtr = std::shared_ptr; + using LyricsSearchContextPtr = SharedPtr; bool SendSearchRequest(LyricsSearchContextPtr search); bool CreateLyricsRequest(LyricsSearchContextPtr search); diff --git a/src/lyrics/ovhlyricsprovider.cpp b/src/lyrics/ovhlyricsprovider.cpp index fc8bd4cc..bc5925c7 100644 --- a/src/lyrics/ovhlyricsprovider.cpp +++ b/src/lyrics/ovhlyricsprovider.cpp @@ -28,6 +28,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "utilities/strutils.h" #include "lyricssearchrequest.h" @@ -37,7 +38,7 @@ const char *OVHLyricsProvider::kUrlSearch = "https://api.lyrics.ovh/v1/"; -OVHLyricsProvider::OVHLyricsProvider(NetworkAccessManager *network, QObject *parent) : JsonLyricsProvider("Lyrics.ovh", true, false, network, parent) {} +OVHLyricsProvider::OVHLyricsProvider(SharedPtr network, QObject *parent) : JsonLyricsProvider("Lyrics.ovh", true, false, network, parent) {} OVHLyricsProvider::~OVHLyricsProvider() { diff --git a/src/lyrics/ovhlyricsprovider.h b/src/lyrics/ovhlyricsprovider.h index 114957cb..dabdbba0 100644 --- a/src/lyrics/ovhlyricsprovider.h +++ b/src/lyrics/ovhlyricsprovider.h @@ -28,6 +28,7 @@ #include #include +#include "core/shared_ptr.h" #include "jsonlyricsprovider.h" #include "lyricssearchrequest.h" @@ -38,7 +39,7 @@ class OVHLyricsProvider : public JsonLyricsProvider { Q_OBJECT public: - explicit OVHLyricsProvider(NetworkAccessManager *network, QObject *parent = nullptr); + explicit OVHLyricsProvider(SharedPtr network, QObject *parent = nullptr); ~OVHLyricsProvider() override; bool StartSearch(const int id, const LyricsSearchRequest &request) override; diff --git a/src/main.cpp b/src/main.cpp index dd9afe9a..2e5f13ff 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -24,10 +24,9 @@ #include -#include #include -#include #include +#include #ifdef Q_OS_UNIX # include @@ -43,6 +42,8 @@ # include #endif // Q_OS_WIN32 +#include + #include #include #include @@ -66,6 +67,9 @@ #include "core/logging.h" +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" + #include #ifdef HAVE_QTSPARKLE @@ -109,6 +113,8 @@ # include "osd/osdbase.h" #endif +using std::make_shared; + int main(int argc, char *argv[]) { #ifdef Q_OS_MACOS @@ -270,7 +276,7 @@ int main(int argc, char *argv[]) { const QString language = override_language.isEmpty() ? system_language : override_language; - std::unique_ptr translations(new Translations); + ScopedPtr translations(new Translations); # if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) translations->LoadTranslation("qt", QLibraryInfo::path(QLibraryInfo::TranslationsPath), language); @@ -294,7 +300,7 @@ int main(int argc, char *argv[]) { QNetworkProxyFactory::setApplicationProxyFactory(NetworkProxyFactory::Instance()); // Create the tray icon and OSD - std::shared_ptr tray_icon = std::make_shared(); + SharedPtr tray_icon = make_shared(); #if defined(Q_OS_MACOS) OSDMac osd(tray_icon, &app); diff --git a/src/moodbar/moodbarcontroller.cpp b/src/moodbar/moodbarcontroller.cpp index d709a795..22513465 100644 --- a/src/moodbar/moodbarcontroller.cpp +++ b/src/moodbar/moodbarcontroller.cpp @@ -35,8 +35,8 @@ MoodbarController::MoodbarController(Application *app, QObject *parent) app_(app), enabled_(false) { - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &MoodbarController::CurrentSongChanged); - QObject::connect(app_->player(), &Player::Stopped, this, &MoodbarController::PlaybackStopped); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &MoodbarController::CurrentSongChanged); + QObject::connect(&*app_->player(), &Player::Stopped, this, &MoodbarController::PlaybackStopped); ReloadSettings(); diff --git a/src/moodbar/moodbarloader.cpp b/src/moodbar/moodbarloader.cpp index 4b5a5cb8..2d239318 100644 --- a/src/moodbar/moodbarloader.cpp +++ b/src/moodbar/moodbarloader.cpp @@ -37,8 +37,9 @@ #include #include -#include "core/application.h" #include "core/logging.h" +#include "core/scoped_ptr.h" +#include "core/application.h" #include "moodbarpipeline.h" @@ -131,7 +132,7 @@ MoodbarLoader::Result MoodbarLoader::Load(const QUrl &url, const bool has_cue, Q QNetworkCacheMetaData disk_cache_metadata = cache_->metaData(CacheUrlEntry(filename)); if (disk_cache_metadata.isValid()) { - std::unique_ptr device_cache_file(cache_->data(disk_cache_metadata.url())); + ScopedPtr device_cache_file(cache_->data(disk_cache_metadata.url())); if (device_cache_file) { qLog(Info) << "Loading cached moodbar data for" << filename; *data = device_cache_file->readAll(); diff --git a/src/moodbar/moodbarpipeline.cpp b/src/moodbar/moodbarpipeline.cpp index badcc20f..dc8de97d 100644 --- a/src/moodbar/moodbarpipeline.cpp +++ b/src/moodbar/moodbarpipeline.cpp @@ -39,6 +39,8 @@ #include "ext/gstmoodbar/gstfastspectrum.h" +using std::make_unique; + const int MoodbarPipeline::kBands = 128; MoodbarPipeline::MoodbarPipeline(const QUrl &url, QObject *parent) @@ -109,7 +111,7 @@ void MoodbarPipeline::Start() { return; } - builder_ = std::make_unique(); + builder_ = make_unique(); // Set properties diff --git a/src/moodbar/moodbarpipeline.h b/src/moodbar/moodbarpipeline.h index e55f116b..bedbd9d9 100644 --- a/src/moodbar/moodbarpipeline.h +++ b/src/moodbar/moodbarpipeline.h @@ -23,13 +23,13 @@ #include #include -#include - #include #include #include #include +#include "core/scoped_ptr.h" + class MoodbarBuilder; // Creates moodbar data for a single local music file. @@ -69,7 +69,7 @@ class MoodbarPipeline : public QObject { GstElement *pipeline_; GstElement *convert_element_; - std::unique_ptr builder_; + ScopedPtr builder_; bool success_; bool running_; diff --git a/src/musicbrainz/acoustidclient.cpp b/src/musicbrainz/acoustidclient.cpp index 4b6d2709..70f9526e 100644 --- a/src/musicbrainz/acoustidclient.cpp +++ b/src/musicbrainz/acoustidclient.cpp @@ -40,17 +40,19 @@ #include #include -#include "acoustidclient.h" +#include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/networktimeouts.h" -#include "core/logging.h" #include "utilities/timeconstants.h" +#include "acoustidclient.h" + const char *AcoustidClient::kClientId = "0qjUoxbowg"; const char *AcoustidClient::kUrl = "https://api.acoustid.org/v2/lookup"; const int AcoustidClient::kDefaultTimeout = 5000; // msec -AcoustidClient::AcoustidClient(NetworkAccessManager *network, QObject *parent) +AcoustidClient::AcoustidClient(SharedPtr network, QObject *parent) : QObject(parent), network_(network), timeouts_(new NetworkTimeouts(kDefaultTimeout, this)) {} diff --git a/src/musicbrainz/acoustidclient.h b/src/musicbrainz/acoustidclient.h index 7e6670af..a0374b53 100644 --- a/src/musicbrainz/acoustidclient.h +++ b/src/musicbrainz/acoustidclient.h @@ -29,6 +29,8 @@ #include #include +#include "core/shared_ptr.h" + class QNetworkReply; class NetworkAccessManager; class NetworkTimeouts; @@ -43,7 +45,7 @@ class AcoustidClient : public QObject { // IDs are provided by the caller when a request is started and included in the Finished signal - they have no meaning to AcoustidClient. public: - explicit AcoustidClient(NetworkAccessManager *network, QObject *parent = nullptr); + explicit AcoustidClient(SharedPtr network, QObject *parent = nullptr); ~AcoustidClient() override; // Network requests will be aborted after this interval. @@ -69,7 +71,7 @@ class AcoustidClient : public QObject { static const char *kUrl; static const int kDefaultTimeout; - NetworkAccessManager *network_; + SharedPtr network_; NetworkTimeouts *timeouts_; QMap requests_; }; diff --git a/src/musicbrainz/musicbrainzclient.cpp b/src/musicbrainz/musicbrainzclient.cpp index b04893f5..2bf7f0da 100644 --- a/src/musicbrainz/musicbrainzclient.cpp +++ b/src/musicbrainz/musicbrainzclient.cpp @@ -43,6 +43,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/networktimeouts.h" #include "utilities/xmlutils.h" @@ -55,7 +56,7 @@ const int MusicBrainzClient::kRequestsDelay = 1200; const int MusicBrainzClient::kDefaultTimeout = 8000; const int MusicBrainzClient::kMaxRequestPerTrack = 3; -MusicBrainzClient::MusicBrainzClient(QNetworkAccessManager *network, QObject *parent) +MusicBrainzClient::MusicBrainzClient(SharedPtr network, QObject *parent) : QObject(parent), network_(network), timeouts_(new NetworkTimeouts(kDefaultTimeout, this)), diff --git a/src/musicbrainz/musicbrainzclient.h b/src/musicbrainz/musicbrainzclient.h index 5c96121d..d576d578 100644 --- a/src/musicbrainz/musicbrainzclient.h +++ b/src/musicbrainz/musicbrainzclient.h @@ -33,10 +33,12 @@ #include #include -class QNetworkAccessManager; +#include "core/shared_ptr.h" + class QNetworkReply; class QTimer; class QXmlStreamReader; +class NetworkAccessManager; class NetworkTimeouts; class MusicBrainzClient : public QObject { @@ -50,7 +52,7 @@ class MusicBrainzClient : public QObject { public: // The second argument allows for specifying a custom network access manager. // It is used in tests. The ownership of network is not transferred. - explicit MusicBrainzClient(QNetworkAccessManager *network, QObject *parent = nullptr); + explicit MusicBrainzClient(SharedPtr network, QObject *parent = nullptr); ~MusicBrainzClient() override; struct Result { @@ -208,7 +210,7 @@ class MusicBrainzClient : public QObject { static const int kDefaultTimeout; static const int kMaxRequestPerTrack; - QNetworkAccessManager *network_; + SharedPtr network_; NetworkTimeouts *timeouts_; QMultiMap requests_pending_; QMultiMap requests_; diff --git a/src/musicbrainz/tagfetcher.cpp b/src/musicbrainz/tagfetcher.cpp index 5d023bf5..269896a0 100644 --- a/src/musicbrainz/tagfetcher.cpp +++ b/src/musicbrainz/tagfetcher.cpp @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "utilities/timeconstants.h" #include "engine/chromaprinter.h" @@ -36,7 +37,7 @@ #include "musicbrainzclient.h" #include "tagfetcher.h" -TagFetcher::TagFetcher(NetworkAccessManager *network, QObject *parent) +TagFetcher::TagFetcher(SharedPtr network, QObject *parent) : QObject(parent), fingerprint_watcher_(nullptr), acoustid_client_(new AcoustidClient(network, this)), diff --git a/src/musicbrainz/tagfetcher.h b/src/musicbrainz/tagfetcher.h index b0a1cd7d..cb3028c6 100644 --- a/src/musicbrainz/tagfetcher.h +++ b/src/musicbrainz/tagfetcher.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "musicbrainzclient.h" @@ -41,7 +42,7 @@ class TagFetcher : public QObject { // High level interface to Fingerprinter, AcoustidClient and MusicBrainzClient. public: - explicit TagFetcher(NetworkAccessManager *network, QObject *parent = nullptr); + explicit TagFetcher(SharedPtr network, QObject *parent = nullptr); void StartFetch(const SongList &songs); diff --git a/src/organize/organize.cpp b/src/organize/organize.cpp index 9550361b..81f459b3 100644 --- a/src/organize/organize.cpp +++ b/src/organize/organize.cpp @@ -35,6 +35,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/taskmanager.h" #include "core/musicstorage.h" #include "core/tagreaderclient.h" @@ -54,7 +55,7 @@ const int Organize::kBatchSize = 10; const int Organize::kTranscodeProgressInterval = 500; #endif -Organize::Organize(TaskManager *task_manager, std::shared_ptr destination, const OrganizeFormat &format, const bool copy, const bool overwrite, const bool albumcover, const NewSongInfoList &songs_info, const bool eject_after, const QString &playlist, QObject *parent) +Organize::Organize(SharedPtr task_manager, SharedPtr destination, const OrganizeFormat &format, const bool copy, const bool overwrite, const bool albumcover, const NewSongInfoList &songs_info, const bool eject_after, const QString &playlist, QObject *parent) : QObject(parent), thread_(nullptr), task_manager_(task_manager), diff --git a/src/organize/organize.h b/src/organize/organize.h index 7c468c01..7868a35e 100644 --- a/src/organize/organize.h +++ b/src/organize/organize.h @@ -24,7 +24,6 @@ #include "config.h" -#include #include #include @@ -37,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "organizeformat.h" @@ -63,7 +63,7 @@ class Organize : public QObject { }; using NewSongInfoList = QList; - explicit Organize(TaskManager *task_manager, std::shared_ptr destination, const OrganizeFormat &format, const bool copy, const bool overwrite, const bool albumcover, const NewSongInfoList &songs, const bool eject_after, const QString &playlist = QString(), QObject *parent = nullptr); + explicit Organize(SharedPtr task_manager, SharedPtr destination, const OrganizeFormat &format, const bool copy, const bool overwrite, const bool albumcover, const NewSongInfoList &songs, const bool eject_after, const QString &playlist = QString(), QObject *parent = nullptr); ~Organize() override; static const int kBatchSize; @@ -108,12 +108,12 @@ class Organize : public QObject { QThread *thread_; QThread *original_thread_; - TaskManager *task_manager_; + SharedPtr task_manager_; #ifdef HAVE_GSTREAMER Transcoder *transcoder_; #endif QTimer *process_files_timer_; - std::shared_ptr destination_; + SharedPtr destination_; QList supported_filetypes_; const OrganizeFormat format_; diff --git a/src/organize/organizedialog.cpp b/src/organize/organizedialog.cpp index bb590d06..0b52434d 100644 --- a/src/organize/organizedialog.cpp +++ b/src/organize/organizedialog.cpp @@ -21,9 +21,9 @@ #include "config.h" -#include #include #include +#include #include #include @@ -55,6 +55,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/iconloader.h" #include "core/musicstorage.h" #include "core/tagreaderclient.h" @@ -72,15 +73,17 @@ # include "transcoder/transcoder.h" #endif +using std::make_unique; + constexpr char OrganizeDialog::kSettingsGroup[] = "OrganizeDialog"; constexpr char OrganizeDialog::kDefaultFormat[] = "%albumartist/%album{ (Disc %disc)}/{%track - }{%albumartist - }%album{ (Disc %disc)} - %title.%extension"; -OrganizeDialog::OrganizeDialog(TaskManager *task_manager, CollectionBackend *backend, QWidget *parentwindow, QWidget *parent) +OrganizeDialog::OrganizeDialog(SharedPtr task_manager, SharedPtr collection_backend, QWidget *parentwindow, QWidget *parent) : QDialog(parent), parentwindow_(parentwindow), ui_(new Ui_OrganizeDialog), task_manager_(task_manager), - backend_(backend), + collection_backend_(collection_backend), total_size_(0), devices_(false) { @@ -179,7 +182,7 @@ void OrganizeDialog::accept() { SaveSettings(); const QModelIndex destination = ui_->destination->model()->index(ui_->destination->currentIndex(), 0); - std::shared_ptr storage = destination.data(MusicStorage::Role_StorageForceConnect).value>(); + SharedPtr storage = destination.data(MusicStorage::Role_StorageForceConnect).value>(); if (!storage) return; @@ -188,8 +191,8 @@ void OrganizeDialog::accept() { Organize *organize = new Organize(task_manager_, storage, format_, copy, ui_->overwrite->isChecked(), ui_->albumcover->isChecked(), new_songs_info_, ui_->eject_after->isChecked(), playlist_); QObject::connect(organize, &Organize::Finished, this, &OrganizeDialog::OrganizeFinished); QObject::connect(organize, &Organize::FileCopied, this, &OrganizeDialog::FileCopied); - if (backend_) { - QObject::connect(organize, &Organize::SongPathChanged, backend_, &CollectionBackend::SongPathChanged); + if (collection_backend_) { + QObject::connect(organize, &Organize::SongPathChanged, &*collection_backend_, &CollectionBackend::SongPathChanged); } organize->Start(); @@ -468,11 +471,11 @@ void OrganizeDialog::UpdatePreviews() { } const QModelIndex destination = ui_->destination->model()->index(ui_->destination->currentIndex(), 0); - std::shared_ptr storage; + SharedPtr storage; bool has_local_destination = false; if (destination.isValid()) { - storage = destination.data(MusicStorage::Role_Storage).value>(); + storage = destination.data(MusicStorage::Role_Storage).value>(); if (storage) { has_local_destination = !storage->LocalPath().isEmpty(); } @@ -550,7 +553,7 @@ void OrganizeDialog::OrganizeFinished(const QStringList &files_with_errors, cons if (files_with_errors.isEmpty()) return; - error_dialog_ = std::make_unique(); + error_dialog_ = make_unique(); error_dialog_->Show(OrganizeErrorDialog::OperationType::Copy, files_with_errors, log); } diff --git a/src/organize/organizedialog.h b/src/organize/organizedialog.h index 7480c5d1..92d06a2d 100644 --- a/src/organize/organizedialog.h +++ b/src/organize/organizedialog.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -37,6 +35,8 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/song.h" #include "organize.h" #include "organizeformat.h" @@ -56,7 +56,7 @@ class OrganizeDialog : public QDialog { Q_OBJECT public: - explicit OrganizeDialog(TaskManager *task_manager, CollectionBackend *backend = nullptr, QWidget *parentwindow = nullptr, QWidget *parent = nullptr); + explicit OrganizeDialog(SharedPtr task_manager, SharedPtr collection_backend = nullptr, QWidget *parentwindow = nullptr, QWidget *parent = nullptr); ~OrganizeDialog() override; void SetDestinationModel(QAbstractItemModel *model, const bool devices = false); @@ -110,8 +110,8 @@ class OrganizeDialog : public QDialog { QWidget *parentwindow_; Ui_OrganizeDialog *ui_; - TaskManager *task_manager_; - CollectionBackend *backend_; + SharedPtr task_manager_; + SharedPtr collection_backend_; OrganizeFormat format_; @@ -121,7 +121,7 @@ class OrganizeDialog : public QDialog { quint64 total_size_; QString playlist_; - std::unique_ptr error_dialog_; + ScopedPtr error_dialog_; bool devices_; }; diff --git a/src/osd/osdbase.cpp b/src/osd/osdbase.cpp index 6afcbe32..fbfbd542 100644 --- a/src/osd/osdbase.cpp +++ b/src/osd/osdbase.cpp @@ -31,6 +31,7 @@ #include "osdbase.h" #include "osdpretty.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/logging.h" #ifdef Q_OS_MACOS @@ -43,7 +44,7 @@ const char *OSDBase::kSettingsGroup = "OSD"; -OSDBase::OSDBase(std::shared_ptr tray_icon, Application *app, QObject *parent) +OSDBase::OSDBase(SharedPtr tray_icon, Application *app, QObject *parent) : QObject(parent), app_(app), tray_icon_(tray_icon), @@ -61,7 +62,7 @@ OSDBase::OSDBase(std::shared_ptr tray_icon, Application *app, QO ignore_next_stopped_(false), playing_(false) { - QObject::connect(app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::ThumbnailLoaded, this, &OSDBase::AlbumCoverLoaded); + QObject::connect(&*app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::ThumbnailLoaded, this, &OSDBase::AlbumCoverLoaded); app_name_[0] = app_name_[0].toUpper(); diff --git a/src/osd/osdbase.h b/src/osd/osdbase.h index 4803a99d..7f4f5c9c 100644 --- a/src/osd/osdbase.h +++ b/src/osd/osdbase.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -33,6 +31,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "playlist/playlistsequence.h" @@ -44,7 +43,7 @@ class OSDBase : public QObject { Q_OBJECT public: - explicit OSDBase(std::shared_ptr tray_icon, Application *app, QObject *parent = nullptr); + explicit OSDBase(SharedPtr tray_icon, Application *app, QObject *parent = nullptr); ~OSDBase() override; static const char *kSettingsGroup; @@ -97,7 +96,7 @@ class OSDBase : public QObject { private: Application *app_; - std::shared_ptr tray_icon_; + SharedPtr tray_icon_; OSDPretty *pretty_popup_; QString app_name_; diff --git a/src/osd/osddbus.cpp b/src/osd/osddbus.cpp index 7f666a7f..8dda254c 100644 --- a/src/osd/osddbus.cpp +++ b/src/osd/osddbus.cpp @@ -41,10 +41,13 @@ #include #include "core/logging.h" +#include "core/scoped_ptr.h" #include "osddbus.h" #include "notification.h" +using std::make_unique; + QDBusArgument &operator<<(QDBusArgument &arg, const QImage &image) { if (image.isNull()) { @@ -101,7 +104,7 @@ const QDBusArgument &operator>>(const QDBusArgument &arg, QImage &image) { } -OSDDBus::OSDDBus(std::shared_ptr tray_icon, Application *app, QObject *parent) +OSDDBus::OSDDBus(SharedPtr tray_icon, Application *app, QObject *parent) : OSDBase(tray_icon, app, parent), version_(1, 1), notification_id_(0) { @@ -114,7 +117,7 @@ OSDDBus::~OSDDBus() = default; void OSDDBus::Init() { - interface_ = std::make_unique(OrgFreedesktopNotificationsInterface::staticInterfaceName(), "/org/freedesktop/Notifications", QDBusConnection::sessionBus()); + interface_ = make_unique(OrgFreedesktopNotificationsInterface::staticInterfaceName(), "/org/freedesktop/Notifications", QDBusConnection::sessionBus()); if (!interface_->isValid()) { qLog(Warning) << "Error connecting to notifications service."; } @@ -173,7 +176,7 @@ void OSDDBus::ShowMessageNative(const QString &summary, const QString &message, void OSDDBus::CallFinished(QDBusPendingCallWatcher *watcher) { - std::unique_ptr w(watcher); + ScopedPtr w(watcher); QDBusPendingReply reply = *w; if (reply.isError()) { diff --git a/src/osd/osddbus.h b/src/osd/osddbus.h index 3a383d28..30dc3ffd 100644 --- a/src/osd/osddbus.h +++ b/src/osd/osddbus.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -35,6 +33,7 @@ #include #include +#include "core/scoped_ptr.h" #include "osdbase.h" class OrgFreedesktopNotificationsInterface; @@ -47,7 +46,7 @@ class OSDDBus : public OSDBase { Q_OBJECT public: - explicit OSDDBus(std::shared_ptr tray_icon, Application *app, QObject *parent = nullptr); + explicit OSDDBus(SharedPtr tray_icon, Application *app, QObject *parent = nullptr); ~OSDDBus() override; static const char *kSettingsGroup; @@ -63,7 +62,7 @@ class OSDDBus : public OSDBase { void CallFinished(QDBusPendingCallWatcher *watcher); private: - std::unique_ptr interface_; + ScopedPtr interface_; QVersionNumber version_; uint notification_id_; QDateTime last_notification_time_; diff --git a/src/osd/osdmac.h b/src/osd/osdmac.h index b9131295..a3b270d8 100644 --- a/src/osd/osdmac.h +++ b/src/osd/osdmac.h @@ -37,7 +37,7 @@ class OSDMac : public OSDBase { Q_OBJECT public: - explicit OSDMac(std::shared_ptr tray_icon, Application *app, QObject *parent = nullptr); + explicit OSDMac(SharedPtr tray_icon, Application *app, QObject *parent = nullptr); ~OSDMac() override; bool SupportsNativeNotifications() override; diff --git a/src/osd/osdmac.mm b/src/osd/osdmac.mm index f038f955..2e95bca2 100644 --- a/src/osd/osdmac.mm +++ b/src/osd/osdmac.mm @@ -53,7 +53,7 @@ void SendNotificationCenterMessage(NSString *title, NSString *subtitle) { } // namespace -OSDMac::OSDMac(std::shared_ptr tray_icon, Application *app, QObject *parent) : OSDBase(tray_icon, app, parent) {} +OSDMac::OSDMac(SharedPtr tray_icon, Application *app, QObject *parent) : OSDBase(tray_icon, app, parent) {} OSDMac::~OSDMac() = default; diff --git a/src/playlist/playlist.cpp b/src/playlist/playlist.cpp index 0a09fbab..d9ed7d72 100644 --- a/src/playlist/playlist.cpp +++ b/src/playlist/playlist.cpp @@ -58,6 +58,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/logging.h" #include "core/mimedata.h" @@ -92,6 +93,7 @@ #include "radios/radiomimedata.h" #include "radios/radioplaylistitem.h" +using std::make_shared; using namespace std::chrono_literals; const char *Playlist::kCddaMimeType = "x-content/audio-cdda"; @@ -112,7 +114,7 @@ const int Playlist::kUndoItemLimit = 500; const qint64 Playlist::kMinScrobblePointNsecs = 31LL * kNsecPerSec; const qint64 Playlist::kMaxScrobblePointNsecs = 240LL * kNsecPerSec; -Playlist::Playlist(PlaylistBackend *backend, TaskManager *task_manager, CollectionBackend *collection, const int id, const QString &special_type, const bool favorite, QObject *parent) +Playlist::Playlist(SharedPtr backend, SharedPtr task_manager, SharedPtr collection_backend, const int id, const QString &special_type, const bool favorite, QObject *parent) : QAbstractListModel(parent), is_loading_(false), filter_(new PlaylistFilter(this)), @@ -120,7 +122,7 @@ Playlist::Playlist(PlaylistBackend *backend, TaskManager *task_manager, Collecti timer_save_(new QTimer(this)), backend_(backend), task_manager_(task_manager), - collection_(collection), + collection_backend_(collection_backend), id_(id), favorite_(favorite), current_is_paused_(false), @@ -175,7 +177,7 @@ void Playlist::InsertSongItems(const SongList &songs, const int pos, const bool PlaylistItemPtrList items; items.reserve(songs.count()); for (const Song &song : songs) { - items << std::make_shared(song); + items << make_shared(song); } InsertItems(items, pos, play_now, enqueue, enqueue_next); @@ -730,7 +732,7 @@ void Playlist::set_current_row(const int i, const AutoScroll autoscroll, const b void Playlist::InsertDynamicItems(const int count) { - PlaylistGeneratorInserter *inserter = new PlaylistGeneratorInserter(task_manager_, collection_, this); + PlaylistGeneratorInserter *inserter = new PlaylistGeneratorInserter(task_manager_, collection_backend_, this); QObject::connect(inserter, &PlaylistGeneratorInserter::Error, this, &Playlist::Error); QObject::connect(inserter, &PlaylistGeneratorInserter::PlayRequested, this, &Playlist::PlayRequested); @@ -850,7 +852,7 @@ bool Playlist::dropMimeData(const QMimeData *data, Qt::DropAction action, int ro } } else if (data->hasFormat(kCddaMimeType)) { - SongLoaderInserter *inserter = new SongLoaderInserter(task_manager_, collection_, backend_->app()->player()); + SongLoaderInserter *inserter = new SongLoaderInserter(task_manager_, collection_backend_, backend_->app()->player()); QObject::connect(inserter, &SongLoaderInserter::Error, this, &Playlist::Error); inserter->LoadAudioCD(this, row, play_now, enqueue_now, enqueue_next_now); } @@ -865,7 +867,7 @@ bool Playlist::dropMimeData(const QMimeData *data, Qt::DropAction action, int ro void Playlist::InsertUrls(const QList &urls, const int pos, const bool play_now, const bool enqueue, const bool enqueue_next) { - SongLoaderInserter *inserter = new SongLoaderInserter(task_manager_, collection_, backend_->app()->player()); + SongLoaderInserter *inserter = new SongLoaderInserter(task_manager_, collection_backend_, backend_->app()->player()); QObject::connect(inserter, &SongLoaderInserter::Error, this, &Playlist::Error); inserter->Load(this, pos, play_now, enqueue, enqueue_next, urls); @@ -876,10 +878,10 @@ void Playlist::InsertSmartPlaylist(PlaylistGeneratorPtr generator, const int pos // Hack: If the generator hasn't got a collection set then use the main one if (!generator->collection()) { - generator->set_collection(collection_); + generator->set_collection_backend(collection_backend_); } - PlaylistGeneratorInserter *inserter = new PlaylistGeneratorInserter(task_manager_, collection_, this); + PlaylistGeneratorInserter *inserter = new PlaylistGeneratorInserter(task_manager_, collection_backend_, this); QObject::connect(inserter, &PlaylistGeneratorInserter::Error, this, &Playlist::Error); inserter->Load(this, pos, play_now, enqueue, enqueue_next, generator); @@ -1142,18 +1144,18 @@ void Playlist::InsertSongsOrCollectionItems(const SongList &songs, const int pos for (const Song &song : songs) { if (song.url().isLocalFile()) { if (song.is_collection_song()) { - items << std::make_shared(song); + items << make_shared(song); } else { - items << std::make_shared(song); + items << make_shared(song); } } else { if (song.is_radio()) { - items << std::make_shared(song); + items << make_shared(song); } else { - items << std::make_shared(song); + items << make_shared(song); } } } @@ -1161,12 +1163,12 @@ void Playlist::InsertSongsOrCollectionItems(const SongList &songs, const int pos } -void Playlist::InsertInternetItems(InternetService *service, const SongList &songs, const int pos, const bool play_now, const bool enqueue, const bool enqueue_next) { +void Playlist::InsertInternetItems(InternetServicePtr service, const SongList &songs, const int pos, const bool play_now, const bool enqueue, const bool enqueue_next) { PlaylistItemPtrList playlist_items; playlist_items.reserve(songs.count()); for (const Song &song : songs) { - playlist_items << std::make_shared(service, song); + playlist_items << make_shared(service, song); } InsertItems(playlist_items, pos, play_now, enqueue, enqueue_next); @@ -1178,7 +1180,7 @@ void Playlist::InsertRadioItems(const SongList &songs, const int pos, const bool PlaylistItemPtrList playlist_items; playlist_items.reserve(songs.count()); for (const Song &song : songs) { - playlist_items << std::make_shared(song); + playlist_items << make_shared(song); } InsertItems(playlist_items, pos, play_now, enqueue, enqueue_next); @@ -1205,20 +1207,20 @@ void Playlist::UpdateItems(SongList songs) { PlaylistItemPtr new_item; if (song.url().isLocalFile()) { if (song.is_collection_song()) { - new_item = std::make_shared(song); + new_item = make_shared(song); if (collection_items_by_id_.contains(song.id(), item)) collection_items_by_id_.remove(song.id(), item); collection_items_by_id_.insert(song.id(), new_item); } else { - new_item = std::make_shared(song); + new_item = make_shared(song); } } else { if (song.is_radio()) { - new_item = std::make_shared(song); + new_item = make_shared(song); } else { - new_item = std::make_shared(song); + new_item = make_shared(song); } } items_[i] = new_item; @@ -1284,10 +1286,10 @@ QMimeData *Playlist::mimeData(const QModelIndexList &indexes) const { } -bool Playlist::CompareItems(const int column, const Qt::SortOrder order, std::shared_ptr _a, std::shared_ptr _b) { +bool Playlist::CompareItems(const int column, const Qt::SortOrder order, SharedPtr _a, SharedPtr _b) { - std::shared_ptr a = order == Qt::AscendingOrder ? _a : _b; - std::shared_ptr b = order == Qt::AscendingOrder ? _b : _a; + SharedPtr a = order == Qt::AscendingOrder ? _a : _b; + SharedPtr b = order == Qt::AscendingOrder ? _b : _a; #define cmp(field) return a->Metadata().field() < b->Metadata().field() #define strcmp(field) return QString::localeAwareCompare(a->Metadata().field().toLower(), b->Metadata().field().toLower()) < 0; @@ -1343,10 +1345,10 @@ bool Playlist::CompareItems(const int column, const Qt::SortOrder order, std::sh } -bool Playlist::ComparePathDepths(const Qt::SortOrder order, std::shared_ptr _a, std::shared_ptr _b) { +bool Playlist::ComparePathDepths(const Qt::SortOrder order, SharedPtr _a, SharedPtr _b) { - std::shared_ptr a = order == Qt::AscendingOrder ? _a : _b; - std::shared_ptr b = order == Qt::AscendingOrder ? _b : _a; + SharedPtr a = order == Qt::AscendingOrder ? _a : _b; + SharedPtr b = order == Qt::AscendingOrder ? _b : _a; qint64 a_dir_level = a->Url().path().count('/'); qint64 b_dir_level = b->Url().path().count('/'); @@ -1462,11 +1464,11 @@ void Playlist::ReOrderWithoutUndo(const PlaylistItemPtrList &new_items) { QHash new_rows; for (int i = 0; i < new_items.length(); ++i) { - new_rows[new_items[i].get()] = i; + new_rows[&*new_items[i]] = i; } for (const QModelIndex &idx : persistentIndexList()) { - const PlaylistItem *item = old_items[idx.row()].get(); + const PlaylistItem *item = &*old_items[idx.row()]; changePersistentIndex(idx, index(new_rows[item], idx.column(), idx.parent())); } @@ -1574,11 +1576,11 @@ void Playlist::ItemsLoaded() { PlaylistGeneratorPtr gen = PlaylistGenerator::Create(p.dynamic_type); if (gen) { - CollectionBackend *backend = nullptr; - if (p.dynamic_backend == collection_->songs_table()) backend = collection_; + SharedPtr backend = nullptr; + if (p.dynamic_backend == collection_backend_->songs_table()) backend = collection_backend_; if (backend) { - gen->set_collection(backend); + gen->set_collection_backend(collection_backend_); gen->Load(p.dynamic_data); TurnOnDynamicPlaylist(gen); } @@ -2365,7 +2367,7 @@ void Playlist::RateSong(const QModelIndex &idx, const float rating) { if (has_item_at(idx.row())) { PlaylistItemPtr item = item_at(idx.row()); if (item && item->IsLocalCollectionItem() && item->Metadata().id() != -1) { - collection_->UpdateSongRatingAsync(item->Metadata().id(), rating); + collection_backend_->UpdateSongRatingAsync(item->Metadata().id(), rating); } } @@ -2383,6 +2385,6 @@ void Playlist::RateSongs(const QModelIndexList &index_list, const float rating) } } } - collection_->UpdateSongsRatingAsync(id_list, rating); + collection_backend_->UpdateSongsRatingAsync(id_list, rating); } diff --git a/src/playlist/playlist.h b/src/playlist/playlist.h index fabfb78e..2abefd77 100644 --- a/src/playlist/playlist.h +++ b/src/playlist/playlist.h @@ -41,6 +41,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "core/tagreaderclient.h" #include "covermanager/albumcoverloaderresult.h" @@ -94,7 +95,7 @@ class Playlist : public QAbstractListModel { friend class PlaylistUndoCommands::ReOrderItems; public: - explicit Playlist(PlaylistBackend *backend, TaskManager *task_manager, CollectionBackend *collection, const int id, const QString &special_type = QString(), const bool favorite = false, QObject *parent = nullptr); + explicit Playlist(SharedPtr playlist_backend, SharedPtr task_manager, SharedPtr collection_backend, const int id, const QString &special_type = QString(), const bool favorite = false, QObject *parent = nullptr); ~Playlist() override; void SkipTracks(const QModelIndexList &source_indexes); @@ -236,7 +237,7 @@ class Playlist : public QAbstractListModel { void InsertSongs(const SongList &songs, const int pos = -1, const bool play_now = false, const bool enqueue = false, const bool enqueue_next = false); void InsertSongsOrCollectionItems(const SongList &songs, const int pos = -1, const bool play_now = false, const bool enqueue = false, const bool enqueue_next = false); void InsertSmartPlaylist(PlaylistGeneratorPtr gen, const int pos = -1, const bool play_now = false, const bool enqueue = false, const bool enqueue_next = false); - void InsertInternetItems(InternetService *service, const SongList &songs, const int pos = -1, const bool play_now = false, const bool enqueue = false, const bool enqueue_next = false); + void InsertInternetItems(SharedPtr service, const SongList &songs, const int pos = -1, const bool play_now = false, const bool enqueue = false, const bool enqueue_next = false); void InsertRadioItems(const SongList &songs, const int pos = -1, const bool play_now = false, const bool enqueue = false, const bool enqueue_next = false); void ReshuffleIndices(); @@ -387,9 +388,9 @@ class Playlist : public QAbstractListModel { QList temp_dequeue_change_indexes_; - PlaylistBackend *backend_; - TaskManager *task_manager_; - CollectionBackend *collection_; + SharedPtr backend_; + SharedPtr task_manager_; + SharedPtr collection_backend_; int id_; QString ui_path_; bool favorite_; diff --git a/src/playlist/playlistbackend.cpp b/src/playlist/playlistbackend.cpp index f5f5ad7b..3ced8070 100644 --- a/src/playlist/playlistbackend.cpp +++ b/src/playlist/playlistbackend.cpp @@ -37,6 +37,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/database.h" #include "core/logging.h" @@ -51,6 +52,8 @@ #include "playlistparsers/cueparser.h" #include "smartplaylists/playlistgenerator.h" +using std::make_shared; + const int PlaylistBackend::kSongTableJoins = 2; PlaylistBackend::PlaylistBackend(Application *app, QObject *parent) @@ -193,7 +196,7 @@ PlaylistItemPtrList PlaylistBackend::GetPlaylistItems(const int playlist) { } // it's probable that we'll have a few songs associated with the same CUE, so we're caching results of parsing CUEs - std::shared_ptr state_ptr = std::make_shared(); + SharedPtr state_ptr = make_shared(); while (q.next()) { playlistitems << NewPlaylistItemFromQuery(SqlRow(q), state_ptr); } @@ -228,7 +231,7 @@ SongList PlaylistBackend::GetPlaylistSongs(const int playlist) { } // it's probable that we'll have a few songs associated with the same CUE, so we're caching results of parsing CUEs - std::shared_ptr state_ptr = std::make_shared(); + SharedPtr state_ptr = make_shared(); while (q.next()) { songs << NewSongFromQuery(SqlRow(q), state_ptr); } @@ -243,7 +246,7 @@ SongList PlaylistBackend::GetPlaylistSongs(const int playlist) { } -PlaylistItemPtr PlaylistBackend::NewPlaylistItemFromQuery(const SqlRow &row, std::shared_ptr state) { +PlaylistItemPtr PlaylistBackend::NewPlaylistItemFromQuery(const SqlRow &row, SharedPtr state) { // The song tables get joined first, plus one each for the song ROWIDs const int playlist_row = static_cast(Song::kColumns.count() + 1) * kSongTableJoins; @@ -259,7 +262,7 @@ PlaylistItemPtr PlaylistBackend::NewPlaylistItemFromQuery(const SqlRow &row, std } -Song PlaylistBackend::NewSongFromQuery(const SqlRow &row, std::shared_ptr state) { +Song PlaylistBackend::NewSongFromQuery(const SqlRow &row, SharedPtr state) { return NewPlaylistItemFromQuery(row, state)->Metadata(); @@ -267,7 +270,7 @@ Song PlaylistBackend::NewSongFromQuery(const SqlRow &row, std::shared_ptr state) { +PlaylistItemPtr PlaylistBackend::RestoreCueData(PlaylistItemPtr item, SharedPtr state) { // We need collection to run a CueParser; also, this method applies only to file-type PlaylistItems if (item->source() != Song::Source::LocalFile) return item; @@ -305,7 +308,7 @@ PlaylistItemPtr PlaylistBackend::RestoreCueData(PlaylistItemPtr item, std::share for (const Song &from_list : song_list) { if (from_list.url().toEncoded() == song.url().toEncoded() && from_list.beginning_nanosec() == song.beginning_nanosec()) { // We found a matching section; replace the input item with a new one containing CUE metadata - return std::make_shared(from_list); + return make_shared(from_list); } } diff --git a/src/playlist/playlistbackend.h b/src/playlist/playlistbackend.h index 126c7a52..82e4cc2c 100644 --- a/src/playlist/playlistbackend.h +++ b/src/playlist/playlistbackend.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -34,6 +32,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "core/sqlquery.h" #include "core/sqlrow.h" @@ -102,9 +101,9 @@ class PlaylistBackend : public QObject { QMutex mutex_; }; - Song NewSongFromQuery(const SqlRow &row, std::shared_ptr state); - PlaylistItemPtr NewPlaylistItemFromQuery(const SqlRow &row, std::shared_ptr state); - PlaylistItemPtr RestoreCueData(PlaylistItemPtr item, std::shared_ptr state); + Song NewSongFromQuery(const SqlRow &row, SharedPtr state); + PlaylistItemPtr NewPlaylistItemFromQuery(const SqlRow &row, SharedPtr state); + PlaylistItemPtr RestoreCueData(PlaylistItemPtr item, SharedPtr state); enum GetPlaylistsFlags { GetPlaylists_OpenInUi = 1, @@ -114,7 +113,7 @@ class PlaylistBackend : public QObject { PlaylistList GetPlaylists(const GetPlaylistsFlags flags); Application *app_; - Database *db_; + SharedPtr db_; QThread *original_thread_; }; diff --git a/src/playlist/playlistcontainer.cpp b/src/playlist/playlistcontainer.cpp index 99420ebe..610b949f 100644 --- a/src/playlist/playlistcontainer.cpp +++ b/src/playlist/playlistcontainer.cpp @@ -46,6 +46,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/iconloader.h" #include "playlist.h" #include "playlisttabbar.h" @@ -146,27 +147,27 @@ void PlaylistContainer::SetActions(QAction *new_playlist, QAction *load_playlist QObject::connect(next_playlist, &QAction::triggered, this, &PlaylistContainer::GoToNextPlaylistTab); QObject::connect(previous_playlist, &QAction::triggered, this, &PlaylistContainer::GoToPreviousPlaylistTab); QObject::connect(clear_playlist, &QAction::triggered, this, &PlaylistContainer::ClearPlaylist); - QObject::connect(save_all_playlists, &QAction::triggered, manager_, &PlaylistManager::SaveAllPlaylists); + QObject::connect(save_all_playlists, &QAction::triggered, &*manager_, &PlaylistManager::SaveAllPlaylists); } -void PlaylistContainer::SetManager(PlaylistManager *manager) { +void PlaylistContainer::SetManager(SharedPtr manager) { manager_ = manager; ui_->tab_bar->SetManager(manager); - QObject::connect(ui_->tab_bar, &PlaylistTabBar::CurrentIdChanged, manager, &PlaylistManager::SetCurrentPlaylist); - QObject::connect(ui_->tab_bar, &PlaylistTabBar::Rename, manager, &PlaylistManager::Rename); - QObject::connect(ui_->tab_bar, &PlaylistTabBar::Close, manager, &PlaylistManager::Close); - QObject::connect(ui_->tab_bar, &PlaylistTabBar::PlaylistFavorited, manager, &PlaylistManager::Favorite); + QObject::connect(ui_->tab_bar, &PlaylistTabBar::CurrentIdChanged, &*manager, &PlaylistManager::SetCurrentPlaylist); + QObject::connect(ui_->tab_bar, &PlaylistTabBar::Rename, &*manager, &PlaylistManager::Rename); + QObject::connect(ui_->tab_bar, &PlaylistTabBar::Close, &*manager, &PlaylistManager::Close); + QObject::connect(ui_->tab_bar, &PlaylistTabBar::PlaylistFavorited, &*manager, &PlaylistManager::Favorite); - QObject::connect(ui_->tab_bar, &PlaylistTabBar::PlaylistOrderChanged, manager, &PlaylistManager::ChangePlaylistOrder); + QObject::connect(ui_->tab_bar, &PlaylistTabBar::PlaylistOrderChanged, &*manager, &PlaylistManager::ChangePlaylistOrder); - QObject::connect(manager, &PlaylistManager::CurrentChanged, this, &PlaylistContainer::SetViewModel); - QObject::connect(manager, &PlaylistManager::PlaylistAdded, this, &PlaylistContainer::PlaylistAdded); - QObject::connect(manager, &PlaylistManager::PlaylistManagerInitialized, this, &PlaylistContainer::Started); - QObject::connect(manager, &PlaylistManager::PlaylistClosed, this, &PlaylistContainer::PlaylistClosed); - QObject::connect(manager, &PlaylistManager::PlaylistRenamed, this, &PlaylistContainer::PlaylistRenamed); + QObject::connect(&*manager, &PlaylistManager::CurrentChanged, this, &PlaylistContainer::SetViewModel); + QObject::connect(&*manager, &PlaylistManager::PlaylistAdded, this, &PlaylistContainer::PlaylistAdded); + QObject::connect(&*manager, &PlaylistManager::PlaylistManagerInitialized, this, &PlaylistContainer::Started); + QObject::connect(&*manager, &PlaylistManager::PlaylistClosed, this, &PlaylistContainer::PlaylistClosed); + QObject::connect(&*manager, &PlaylistManager::PlaylistRenamed, this, &PlaylistContainer::PlaylistRenamed); } diff --git a/src/playlist/playlistcontainer.h b/src/playlist/playlistcontainer.h index 96793b5f..3165054d 100644 --- a/src/playlist/playlistcontainer.h +++ b/src/playlist/playlistcontainer.h @@ -44,6 +44,8 @@ class PlaylistView; class Ui_PlaylistContainer; +#include "core/shared_ptr.h" + class PlaylistContainer : public QWidget { Q_OBJECT @@ -54,7 +56,7 @@ class PlaylistContainer : public QWidget { static const char *kSettingsGroup; void SetActions(QAction *new_playlist, QAction *load_playlist, QAction *save_playlist, QAction *clear_playlist, QAction *next_playlist, QAction *previous_playlist, QAction *save_all_playlists); - void SetManager(PlaylistManager *manager); + void SetManager(SharedPtr manager); void ReloadSettings(); bool SearchFieldHasFocus() const; @@ -118,7 +120,7 @@ class PlaylistContainer : public QWidget { Ui_PlaylistContainer *ui_; - PlaylistManager *manager_; + SharedPtr manager_; QAction *undo_; QAction *redo_; Playlist *playlist_; diff --git a/src/playlist/playlistdelegates.cpp b/src/playlist/playlistdelegates.cpp index 08ea15f0..6de6548f 100644 --- a/src/playlist/playlistdelegates.cpp +++ b/src/playlist/playlistdelegates.cpp @@ -365,7 +365,7 @@ QWidget *TextItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewI return new QLineEdit(parent); } -TagCompletionModel::TagCompletionModel(CollectionBackend *backend, const Playlist::Column column, QObject *parent) : QStringListModel(parent) { +TagCompletionModel::TagCompletionModel(SharedPtr backend, const Playlist::Column column, QObject *parent) : QStringListModel(parent) { QString col = database_column(column); if (!col.isEmpty()) { @@ -395,13 +395,13 @@ QString TagCompletionModel::database_column(Playlist::Column column) { } -static TagCompletionModel *InitCompletionModel(CollectionBackend *backend, Playlist::Column column) { +static TagCompletionModel *InitCompletionModel(SharedPtr backend, Playlist::Column column) { return new TagCompletionModel(backend, column); } -TagCompleter::TagCompleter(CollectionBackend *backend, Playlist::Column column, QLineEdit *editor) : QCompleter(editor), editor_(editor) { +TagCompleter::TagCompleter(SharedPtr backend, Playlist::Column column, QLineEdit *editor) : QCompleter(editor), editor_(editor) { QFuture future = QtConcurrent::run(&InitCompletionModel, backend, column); QFutureWatcher *watcher = new QFutureWatcher(); diff --git a/src/playlist/playlistdelegates.h b/src/playlist/playlistdelegates.h index 95853e7b..a75318b4 100644 --- a/src/playlist/playlistdelegates.h +++ b/src/playlist/playlistdelegates.h @@ -151,7 +151,7 @@ class TagCompletionModel : public QStringListModel { Q_OBJECT public: - explicit TagCompletionModel(CollectionBackend *backend, const Playlist::Column column, QObject *parent = nullptr); + explicit TagCompletionModel(SharedPtr backend, const Playlist::Column column, QObject *parent = nullptr); private: static QString database_column(Playlist::Column column); @@ -161,7 +161,7 @@ class TagCompleter : public QCompleter { Q_OBJECT public: - explicit TagCompleter(CollectionBackend *backend, Playlist::Column column, QLineEdit *editor); + explicit TagCompleter(SharedPtr backend, Playlist::Column column, QLineEdit *editor); ~TagCompleter() override; private slots: @@ -175,12 +175,12 @@ class TagCompletionItemDelegate : public PlaylistDelegateBase { Q_OBJECT public: - explicit TagCompletionItemDelegate(QObject *parent, CollectionBackend *backend, Playlist::Column column) : PlaylistDelegateBase(parent), backend_(backend), column_(column) {}; + explicit TagCompletionItemDelegate(QObject *parent, SharedPtr backend, Playlist::Column column) : PlaylistDelegateBase(parent), backend_(backend), column_(column) {}; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &idx) const override; private: - CollectionBackend *backend_; + SharedPtr backend_; Playlist::Column column_; }; diff --git a/src/playlist/playlistitem.cpp b/src/playlist/playlistitem.cpp index d4d90854..1a8e4dd9 100644 --- a/src/playlist/playlistitem.cpp +++ b/src/playlist/playlistitem.cpp @@ -37,19 +37,21 @@ #include "internet/internetplaylistitem.h" #include "radios/radioplaylistitem.h" +using std::make_shared; + PlaylistItemPtr PlaylistItem::NewFromSource(const Song::Source source) { switch (source) { case Song::Source::Collection: - return std::make_shared(); + return make_shared(); case Song::Source::Subsonic: case Song::Source::Tidal: case Song::Source::Qobuz: - return std::make_shared(source); + return make_shared(source); case Song::Source::Stream: case Song::Source::RadioParadise: case Song::Source::SomaFM: - return std::make_shared(source); + return make_shared(source); case Song::Source::LocalFile: case Song::Source::CDDA: case Song::Source::Device: @@ -57,7 +59,7 @@ PlaylistItemPtr PlaylistItem::NewFromSource(const Song::Source source) { break; } - return std::make_shared(source); + return make_shared(source); } @@ -65,15 +67,15 @@ PlaylistItemPtr PlaylistItem::NewFromSong(const Song &song) { switch (song.source()) { case Song::Source::Collection: - return std::make_shared(song); + return make_shared(song); case Song::Source::Subsonic: case Song::Source::Tidal: case Song::Source::Qobuz: - return std::make_shared(song); + return make_shared(song); case Song::Source::Stream: case Song::Source::RadioParadise: case Song::Source::SomaFM: - return std::make_shared(song); + return make_shared(song); case Song::Source::LocalFile: case Song::Source::CDDA: case Song::Source::Device: @@ -81,7 +83,7 @@ PlaylistItemPtr PlaylistItem::NewFromSong(const Song &song) { break; } - return std::make_shared(song); + return make_shared(song); } diff --git a/src/playlist/playlistitem.h b/src/playlist/playlistitem.h index e37e9066..7bf3ba09 100644 --- a/src/playlist/playlistitem.h +++ b/src/playlist/playlistitem.h @@ -36,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" class QAction; @@ -43,13 +44,15 @@ class QAction; class SqlQuery; class SqlRow; -class PlaylistItem : public std::enable_shared_from_this { +using std::enable_shared_from_this; + +class PlaylistItem : public enable_shared_from_this { public: explicit PlaylistItem(const Song::Source source) : should_skip_(false), source_(source) {} virtual ~PlaylistItem(); - static std::shared_ptr NewFromSource(const Song::Source source); - static std::shared_ptr NewFromSong(const Song &song); + static SharedPtr NewFromSource(const Song::Source source); + static SharedPtr NewFromSong(const Song &song); enum class Option { Default = 0x00, @@ -133,7 +136,7 @@ class PlaylistItem : public std::enable_shared_from_this { Q_DISABLE_COPY(PlaylistItem) }; -using PlaylistItemPtr = std::shared_ptr; +using PlaylistItemPtr = SharedPtr; using PlaylistItemPtrList = QList; Q_DECLARE_METATYPE(PlaylistItemPtr) diff --git a/src/playlist/playlistlistcontainer.cpp b/src/playlist/playlistlistcontainer.cpp index d772168e..3ba55bdd 100644 --- a/src/playlist/playlistlistcontainer.cpp +++ b/src/playlist/playlistlistcontainer.cpp @@ -63,6 +63,8 @@ # include "device/devicestatefiltermodel.h" #endif +using std::make_unique; + PlaylistListContainer::PlaylistListContainer(QWidget *parent) : QWidget(parent), app_(nullptr), @@ -120,8 +122,8 @@ PlaylistListContainer::~PlaylistListContainer() { delete ui_; } void PlaylistListContainer::SetApplication(Application *app) { app_ = app; - PlaylistManager *manager = app_->playlist_manager(); - Player *player = app_->player(); + PlaylistManager *manager = &*app_->playlist_manager(); + Player *player = &*app_->player(); QObject::connect(manager, &PlaylistManager::PlaylistAdded, this, &PlaylistListContainer::AddPlaylist); QObject::connect(manager, &PlaylistManager::PlaylistFavorited, this, &PlaylistListContainer::PlaylistFavoriteStateChanged); @@ -370,7 +372,7 @@ void PlaylistListContainer::CopyToDevice() { // Reuse the organize dialog, but set the detail about the playlist name if (!organize_dialog_) { - organize_dialog_ = std::make_unique(app_->task_manager(), nullptr, this); + organize_dialog_ = make_unique(app_->task_manager(), nullptr, this); } organize_dialog_->SetDestinationModel(app_->device_manager()->connected_devices_model(), true); organize_dialog_->SetCopy(true); diff --git a/src/playlist/playlistlistcontainer.h b/src/playlist/playlistlistcontainer.h index 9bc7a6be..0193af3a 100644 --- a/src/playlist/playlistlistcontainer.h +++ b/src/playlist/playlistlistcontainer.h @@ -24,14 +24,14 @@ #include "config.h" -#include - #include #include #include #include #include +#include "core/scoped_ptr.h" + class QStandardItem; class QSortFilterProxyModel; class QMenu; @@ -115,7 +115,7 @@ class PlaylistListContainer : public QWidget { int active_playlist_id_; - std::unique_ptr organize_dialog_; + ScopedPtr organize_dialog_; }; #endif // PLAYLISTLISTCONTAINER_H diff --git a/src/playlist/playlistmanager.cpp b/src/playlist/playlistmanager.cpp index 226ad70d..6be5e663 100644 --- a/src/playlist/playlistmanager.cpp +++ b/src/playlist/playlistmanager.cpp @@ -42,6 +42,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/player.h" #include "utilities/filenameconstants.h" @@ -73,9 +74,9 @@ PlaylistManager::PlaylistManager(Application *app, QObject *parent) active_(-1), playlists_loading_(0) { - QObject::connect(app_->player(), &Player::Paused, this, &PlaylistManager::SetActivePaused); - QObject::connect(app_->player(), &Player::Playing, this, &PlaylistManager::SetActivePlaying); - QObject::connect(app_->player(), &Player::Stopped, this, &PlaylistManager::SetActiveStopped); + QObject::connect(&*app_->player(), &Player::Paused, this, &PlaylistManager::SetActivePaused); + QObject::connect(&*app_->player(), &Player::Playing, this, &PlaylistManager::SetActivePlaying); + QObject::connect(&*app_->player(), &Player::Stopped, this, &PlaylistManager::SetActiveStopped); } @@ -86,7 +87,7 @@ PlaylistManager::~PlaylistManager() { } -void PlaylistManager::Init(CollectionBackend *collection_backend, PlaylistBackend *playlist_backend, PlaylistSequence *sequence, PlaylistContainer *playlist_container) { +void PlaylistManager::Init(SharedPtr collection_backend, SharedPtr playlist_backend, PlaylistSequence *sequence, PlaylistContainer *playlist_container) { collection_backend_ = collection_backend; playlist_backend_ = playlist_backend; @@ -94,9 +95,9 @@ void PlaylistManager::Init(CollectionBackend *collection_backend, PlaylistBacken parser_ = new PlaylistParser(collection_backend, this); playlist_container_ = playlist_container; - QObject::connect(collection_backend_, &CollectionBackend::SongsDiscovered, this, &PlaylistManager::SongsDiscovered); - QObject::connect(collection_backend_, &CollectionBackend::SongsStatisticsChanged, this, &PlaylistManager::SongsDiscovered); - QObject::connect(collection_backend_, &CollectionBackend::SongsRatingChanged, this, &PlaylistManager::SongsDiscovered); + QObject::connect(&*collection_backend_, &CollectionBackend::SongsDiscovered, this, &PlaylistManager::SongsDiscovered); + QObject::connect(&*collection_backend_, &CollectionBackend::SongsStatisticsChanged, this, &PlaylistManager::SongsDiscovered); + QObject::connect(&*collection_backend_, &CollectionBackend::SongsRatingChanged, this, &PlaylistManager::SongsDiscovered); for (const PlaylistBackend::Playlist &p : playlist_backend->GetAllOpenPlaylists()) { ++playlists_loading_; @@ -156,7 +157,7 @@ Playlist *PlaylistManager::AddPlaylist(const int id, const QString &name, const QObject::connect(ret, &Playlist::Error, this, &PlaylistManager::Error); QObject::connect(ret, &Playlist::PlayRequested, this, &PlaylistManager::PlayRequested); QObject::connect(playlist_container_->view(), &PlaylistView::ColumnAlignmentChanged, ret, &Playlist::SetColumnAlignment); - QObject::connect(app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::AlbumCoverLoaded, ret, &Playlist::AlbumCoverLoaded); + QObject::connect(&*app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::AlbumCoverLoaded, ret, &Playlist::AlbumCoverLoaded); playlists_[id] = Data(ret, name); diff --git a/src/playlist/playlistmanager.h b/src/playlist/playlistmanager.h index 5642efc6..dfbbb148 100644 --- a/src/playlist/playlistmanager.h +++ b/src/playlist/playlistmanager.h @@ -33,6 +33,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" #include "playlist.h" @@ -73,8 +74,8 @@ class PlaylistManagerInterface : public QObject { virtual QString GetPlaylistName(const int index) const = 0; - virtual CollectionBackend *collection_backend() const = 0; - virtual PlaylistBackend *playlist_backend() const = 0; + virtual SharedPtr collection_backend() const = 0; + virtual SharedPtr playlist_backend() const = 0; virtual PlaylistSequence *sequence() const = 0; virtual PlaylistParser *parser() const = 0; virtual PlaylistContainer *playlist_container() const = 0; @@ -171,10 +172,10 @@ class PlaylistManager : public PlaylistManagerInterface { QString GetPlaylistName(const int index) const override { return playlists_[index].name; } bool IsPlaylistFavorite(const int index) const { return playlists_[index].p->is_favorite(); } - void Init(CollectionBackend *collection_backend, PlaylistBackend *playlist_backend, PlaylistSequence *sequence, PlaylistContainer *playlist_container); + void Init(SharedPtr collection_backend, SharedPtr playlist_backend, PlaylistSequence *sequence, PlaylistContainer *playlist_container); - CollectionBackend *collection_backend() const override { return collection_backend_; } - PlaylistBackend *playlist_backend() const override { return playlist_backend_; } + SharedPtr collection_backend() const override { return collection_backend_; } + SharedPtr playlist_backend() const override { return playlist_backend_; } PlaylistSequence *sequence() const override { return sequence_; } PlaylistParser *parser() const override { return parser_; } PlaylistContainer *playlist_container() const override { return playlist_container_; } @@ -249,8 +250,8 @@ class PlaylistManager : public PlaylistManagerInterface { }; Application *app_; - PlaylistBackend *playlist_backend_; - CollectionBackend *collection_backend_; + SharedPtr playlist_backend_; + SharedPtr collection_backend_; PlaylistSequence *sequence_; PlaylistParser *parser_; PlaylistContainer *playlist_container_; diff --git a/src/playlist/playlistsequence.h b/src/playlist/playlistsequence.h index 65a2ce43..ce13908c 100644 --- a/src/playlist/playlistsequence.h +++ b/src/playlist/playlistsequence.h @@ -24,14 +24,14 @@ #include "config.h" -#include - #include #include #include #include #include +#include "core/scoped_ptr.h" + class QMenu; class QAction; @@ -92,7 +92,7 @@ class PlaylistSequence : public QWidget { private: Ui_PlaylistSequence *ui_; - std::unique_ptr settings_; + ScopedPtr settings_; QMenu *repeat_menu_; QMenu *shuffle_menu_; diff --git a/src/playlist/playlisttabbar.cpp b/src/playlist/playlisttabbar.cpp index 9072bf0b..77480471 100644 --- a/src/playlist/playlisttabbar.cpp +++ b/src/playlist/playlisttabbar.cpp @@ -44,6 +44,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/iconloader.h" #include "core/mimedata.h" #include "widgets/favoritewidget.h" @@ -100,11 +101,11 @@ void PlaylistTabBar::SetActions(QAction *new_playlist, QAction *load_playlist) { } -void PlaylistTabBar::SetManager(PlaylistManager *manager) { +void PlaylistTabBar::SetManager(SharedPtr manager) { manager_ = manager; - QObject::connect(manager_, &PlaylistManager::PlaylistFavorited, this, &PlaylistTabBar::PlaylistFavoritedSlot); - QObject::connect(manager_, &PlaylistManager::PlaylistManagerInitialized, this, &PlaylistTabBar::PlaylistManagerInitialized); + QObject::connect(&*manager_, &PlaylistManager::PlaylistFavorited, this, &PlaylistTabBar::PlaylistFavoritedSlot); + QObject::connect(&*manager_, &PlaylistManager::PlaylistManagerInitialized, this, &PlaylistTabBar::PlaylistManagerInitialized); } @@ -112,7 +113,7 @@ void PlaylistTabBar::PlaylistManagerInitialized() { // Signal that we are done loading and thus further changes should be committed to the db. initialized_ = true; - QObject::disconnect(manager_, &PlaylistManager::PlaylistManagerInitialized, this, &PlaylistTabBar::PlaylistManagerInitialized); + QObject::disconnect(&*manager_, &PlaylistManager::PlaylistManagerInitialized, this, &PlaylistTabBar::PlaylistManagerInitialized); } diff --git a/src/playlist/playlisttabbar.h b/src/playlist/playlisttabbar.h index e297e34b..589e52e2 100644 --- a/src/playlist/playlisttabbar.h +++ b/src/playlist/playlisttabbar.h @@ -46,6 +46,8 @@ class QTimerEvent; class PlaylistManager; class RenameTabLineEdit; +#include "core/shared_ptr.h" + class PlaylistTabBar : public QTabBar { Q_OBJECT @@ -56,7 +58,7 @@ class PlaylistTabBar : public QTabBar { static const char *kSettingsGroup; void SetActions(QAction *new_playlist, QAction *load_playlist); - void SetManager(PlaylistManager *manager); + void SetManager(SharedPtr manager); // We use IDs to refer to tabs so the tabs can be moved around (and their indexes change). int index_of(const int id) const; @@ -106,7 +108,7 @@ class PlaylistTabBar : public QTabBar { void SaveSlot(); private: - PlaylistManager *manager_; + SharedPtr manager_; QMenu *menu_; int menu_index_; diff --git a/src/playlist/playlistview.cpp b/src/playlist/playlistview.cpp index bf07cf45..7a4331fd 100644 --- a/src/playlist/playlistview.cpp +++ b/src/playlist/playlistview.cpp @@ -232,11 +232,11 @@ void PlaylistView::Init(Application *app) { SetItemDelegates(); - QObject::connect(app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &PlaylistView::SongChanged); - QObject::connect(app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::AlbumCoverLoaded, this, &PlaylistView::AlbumCoverLoaded); - QObject::connect(app_->player(), &Player::Playing, this, &PlaylistView::StartGlowing); - QObject::connect(app_->player(), &Player::Paused, this, &PlaylistView::StopGlowing); - QObject::connect(app_->player(), &Player::Stopped, this, &PlaylistView::Stopped); + QObject::connect(&*app_->playlist_manager(), &PlaylistManager::CurrentSongChanged, this, &PlaylistView::SongChanged); + QObject::connect(&*app_->current_albumcover_loader(), &CurrentAlbumCoverLoader::AlbumCoverLoaded, this, &PlaylistView::AlbumCoverLoaded); + QObject::connect(&*app_->player(), &Player::Playing, this, &PlaylistView::StartGlowing); + QObject::connect(&*app_->player(), &Player::Paused, this, &PlaylistView::StopGlowing); + QObject::connect(&*app_->player(), &Player::Stopped, this, &PlaylistView::Stopped); } diff --git a/src/playlist/playlistview.h b/src/playlist/playlistview.h index ea6ff9cd..61d348a5 100644 --- a/src/playlist/playlistview.h +++ b/src/playlist/playlistview.h @@ -24,8 +24,6 @@ #include "config.h" -#include - #include #include #include @@ -47,6 +45,7 @@ #include #include +#include "core/scoped_ptr.h" #include "core/song.h" #include "covermanager/albumcoverloaderresult.h" #include "settings/appearancesettingspage.h" @@ -91,7 +90,7 @@ class PlaylistProxyStyle : public QProxyStyle { void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const override; private: - std::unique_ptr common_style_; + ScopedPtr common_style_; }; class PlaylistView : public QTreeView { diff --git a/src/playlist/songloaderinserter.cpp b/src/playlist/songloaderinserter.cpp index 4bec6d15..b69548c5 100644 --- a/src/playlist/songloaderinserter.cpp +++ b/src/playlist/songloaderinserter.cpp @@ -27,12 +27,13 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/songloader.h" #include "core/taskmanager.h" #include "playlist.h" #include "songloaderinserter.h" -SongLoaderInserter::SongLoaderInserter(TaskManager *task_manager, CollectionBackendInterface *collection, const Player *player, QObject *parent) +SongLoaderInserter::SongLoaderInserter(SharedPtr task_manager, SharedPtr collection_backend, const SharedPtr player, QObject *parent) : QObject(parent), task_manager_(task_manager), destination_(nullptr), @@ -40,7 +41,7 @@ SongLoaderInserter::SongLoaderInserter(TaskManager *task_manager, CollectionBack play_now_(true), enqueue_(false), enqueue_next_(false), - collection_(collection), + collection_backend_(collection_backend), player_(player) {} SongLoaderInserter::~SongLoaderInserter() { qDeleteAll(pending_); } @@ -58,7 +59,7 @@ void SongLoaderInserter::Load(Playlist *destination, int row, bool play_now, boo QObject::connect(this, &SongLoaderInserter::EffectiveLoadFinished, destination, &Playlist::UpdateItems); for (const QUrl &url : urls) { - SongLoader *loader = new SongLoader(collection_, player_, this); + SongLoader *loader = new SongLoader(collection_backend_, player_, this); SongLoader::Result ret = loader->Load(url); @@ -103,7 +104,7 @@ void SongLoaderInserter::LoadAudioCD(Playlist *destination, int row, bool play_n enqueue_ = enqueue; enqueue_next_ = enqueue_next; - SongLoader *loader = new SongLoader(collection_, player_, this); + SongLoader *loader = new SongLoader(collection_backend_, player_, this); QObject::connect(loader, &SongLoader::AudioCDTracksLoadFinished, this, [this, loader]() { AudioCDTracksLoadFinished(loader); }); QObject::connect(loader, &SongLoader::LoadAudioCDFinished, this, &SongLoaderInserter::AudioCDTagsLoaded); qLog(Info) << "Loading audio CD..."; diff --git a/src/playlist/songloaderinserter.h b/src/playlist/songloaderinserter.h index a5de406f..e7e34d20 100644 --- a/src/playlist/songloaderinserter.h +++ b/src/playlist/songloaderinserter.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" class Player; @@ -41,7 +42,7 @@ class SongLoaderInserter : public QObject { Q_OBJECT public: - explicit SongLoaderInserter(TaskManager *task_manager, CollectionBackendInterface *collection, const Player *player, QObject *parent = nullptr); + explicit SongLoaderInserter(SharedPtr task_manager, SharedPtr collection_backend, const SharedPtr player, QObject *parent = nullptr); ~SongLoaderInserter() override; void Load(Playlist *destination, int row, bool play_now, bool enqueue, bool enqueue_next, const QList &urls); @@ -62,7 +63,7 @@ class SongLoaderInserter : public QObject { void AsyncLoad(); private: - TaskManager *task_manager_; + SharedPtr task_manager_; Playlist *destination_; int row_; @@ -73,8 +74,8 @@ class SongLoaderInserter : public QObject { SongList songs_; QList pending_; - CollectionBackendInterface *collection_; - const Player *player_; + SharedPtr collection_backend_; + const SharedPtr player_; }; #endif // SONGLOADERINSERTER_H diff --git a/src/playlist/songmimedata.h b/src/playlist/songmimedata.h index 7e6421f3..1d5ba878 100644 --- a/src/playlist/songmimedata.h +++ b/src/playlist/songmimedata.h @@ -26,6 +26,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/mimedata.h" #include "core/song.h" @@ -37,7 +38,7 @@ class SongMimeData : public MimeData { public: explicit SongMimeData(QObject* = nullptr) : MimeData(), backend(nullptr) {} - CollectionBackendInterface *backend; + SharedPtr backend; SongList songs; }; diff --git a/src/playlistparsers/asxiniparser.cpp b/src/playlistparsers/asxiniparser.cpp index 1ecb6208..ffd96994 100644 --- a/src/playlistparsers/asxiniparser.cpp +++ b/src/playlistparsers/asxiniparser.cpp @@ -26,6 +26,7 @@ #include #include +#include "core/shared_ptr.h" #include "settings/playlistsettingspage.h" #include "parserbase.h" #include "asxiniparser.h" @@ -38,8 +39,8 @@ constexpr auto qt_endl = Qt::endl; constexpr auto qt_endl = endl; #endif -AsxIniParser::AsxIniParser(CollectionBackendInterface *collection, QObject *parent) - : ParserBase(collection, parent) {} +AsxIniParser::AsxIniParser(SharedPtr collection_backend, QObject *parent) + : ParserBase(collection_backend, parent) {} bool AsxIniParser::TryMagic(const QByteArray &data) const { return data.toLower().contains("[reference]"); diff --git a/src/playlistparsers/asxiniparser.h b/src/playlistparsers/asxiniparser.h index 05d2014e..a6dfd490 100644 --- a/src/playlistparsers/asxiniparser.h +++ b/src/playlistparsers/asxiniparser.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" #include "parserbase.h" @@ -40,7 +41,7 @@ class AsxIniParser : public ParserBase { Q_OBJECT public: - explicit AsxIniParser(CollectionBackendInterface *collection, QObject *parent = nullptr); + explicit AsxIniParser(SharedPtr collection_backend, QObject *parent = nullptr); QString name() const override { return "ASX/INI"; } QStringList file_extensions() const override { return QStringList() << "asxini"; } diff --git a/src/playlistparsers/asxparser.cpp b/src/playlistparsers/asxparser.cpp index 5347814c..e315932e 100644 --- a/src/playlistparsers/asxparser.cpp +++ b/src/playlistparsers/asxparser.cpp @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "utilities/xmlutils.h" #include "settings/playlistsettingspage.h" #include "xmlparser.h" @@ -36,8 +37,8 @@ class CollectionBackendInterface; -ASXParser::ASXParser(CollectionBackendInterface *collection, QObject *parent) - : XMLParser(collection, parent) {} +ASXParser::ASXParser(SharedPtr collection_backend, QObject *parent) + : XMLParser(collection_backend, parent) {} SongList ASXParser::Load(QIODevice *device, const QString &playlist_path, const QDir &dir, const bool collection_search) const { diff --git a/src/playlistparsers/asxparser.h b/src/playlistparsers/asxparser.h index ad0b7412..3462a34e 100644 --- a/src/playlistparsers/asxparser.h +++ b/src/playlistparsers/asxparser.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" #include "xmlparser.h" @@ -42,7 +43,7 @@ class ASXParser : public XMLParser { Q_OBJECT public: - explicit ASXParser(CollectionBackendInterface *collection, QObject *parent = nullptr); + explicit ASXParser(SharedPtr collection_backend, QObject *parent = nullptr); QString name() const override { return "ASX"; } QStringList file_extensions() const override { return QStringList() << "asx"; } diff --git a/src/playlistparsers/cueparser.cpp b/src/playlistparsers/cueparser.cpp index cfb6b835..3bf20d24 100644 --- a/src/playlistparsers/cueparser.cpp +++ b/src/playlistparsers/cueparser.cpp @@ -34,6 +34,7 @@ # include #endif +#include "core/shared_ptr.h" #include "core/logging.h" #include "utilities/timeconstants.h" #include "settings/playlistsettingspage.h" @@ -59,8 +60,8 @@ const char *CueParser::kGenre = "genre"; const char *CueParser::kDate = "date"; const char *CueParser::kDisc = "discnumber"; -CueParser::CueParser(CollectionBackendInterface *collection, QObject *parent) - : ParserBase(collection, parent) {} +CueParser::CueParser(SharedPtr collection_backend, QObject *parent) + : ParserBase(collection_backend, parent) {} SongList CueParser::Load(QIODevice *device, const QString &playlist_path, const QDir &dir, const bool collection_search) const { diff --git a/src/playlistparsers/cueparser.h b/src/playlistparsers/cueparser.h index 325e917c..3e26e90a 100644 --- a/src/playlistparsers/cueparser.h +++ b/src/playlistparsers/cueparser.h @@ -31,6 +31,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" #include "parserbase.h" @@ -60,7 +61,7 @@ class CueParser : public ParserBase { static const char *kDate; static const char *kDisc; - explicit CueParser(CollectionBackendInterface *collection, QObject *parent = nullptr); + explicit CueParser(SharedPtr collection_backend, QObject *parent = nullptr); QString name() const override { return "CUE"; } QStringList file_extensions() const override { return QStringList() << "cue"; } diff --git a/src/playlistparsers/m3uparser.cpp b/src/playlistparsers/m3uparser.cpp index 118cb85c..82a8766d 100644 --- a/src/playlistparsers/m3uparser.cpp +++ b/src/playlistparsers/m3uparser.cpp @@ -27,6 +27,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/logging.h" #include "utilities/timeconstants.h" #include "settings/playlistsettingspage.h" @@ -35,8 +36,8 @@ class CollectionBackendInterface; -M3UParser::M3UParser(CollectionBackendInterface *collection, QObject *parent) - : ParserBase(collection, parent) {} +M3UParser::M3UParser(SharedPtr collection_backend, QObject *parent) + : ParserBase(collection_backend, parent) {} SongList M3UParser::Load(QIODevice *device, const QString &playlist_path, const QDir &dir, const bool collection_search) const { diff --git a/src/playlistparsers/m3uparser.h b/src/playlistparsers/m3uparser.h index 930ea226..fd814aa3 100644 --- a/src/playlistparsers/m3uparser.h +++ b/src/playlistparsers/m3uparser.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" #include "parserbase.h" @@ -41,7 +42,7 @@ class M3UParser : public ParserBase { Q_OBJECT public: - explicit M3UParser(CollectionBackendInterface *collection, QObject *parent = nullptr); + explicit M3UParser(SharedPtr collection_backend, QObject *parent = nullptr); QString name() const override { return "M3U"; } QStringList file_extensions() const override { return QStringList() << "m3u" << "m3u8"; } diff --git a/src/playlistparsers/parserbase.cpp b/src/playlistparsers/parserbase.cpp index 8f719246..e8bf4cb0 100644 --- a/src/playlistparsers/parserbase.cpp +++ b/src/playlistparsers/parserbase.cpp @@ -27,14 +27,15 @@ #include #include +#include "core/shared_ptr.h" #include "core/logging.h" #include "core/tagreaderclient.h" #include "collection/collectionbackend.h" #include "settings/playlistsettingspage.h" #include "parserbase.h" -ParserBase::ParserBase(CollectionBackendInterface *collection, QObject *parent) - : QObject(parent), collection_(collection) {} +ParserBase::ParserBase(SharedPtr collection_backend, QObject *parent) + : QObject(parent), collection_backend_(collection_backend) {} void ParserBase::LoadSong(const QString &filename_or_url, const qint64 beginning, const QDir &dir, Song *song, const bool collection_search) const { @@ -79,8 +80,8 @@ void ParserBase::LoadSong(const QString &filename_or_url, const qint64 beginning const QUrl url = QUrl::fromLocalFile(filename); // Search in the collection - if (collection_ && collection_search) { - Song collection_song = collection_->GetSongByUrl(url, beginning); + if (collection_backend_ && collection_search) { + Song collection_song = collection_backend_->GetSongByUrl(url, beginning); // If it was found in the collection then use it, otherwise load metadata from disk. if (collection_song.is_valid()) { *song = collection_song; diff --git a/src/playlistparsers/parserbase.h b/src/playlistparsers/parserbase.h index e01c0da9..31f260cf 100644 --- a/src/playlistparsers/parserbase.h +++ b/src/playlistparsers/parserbase.h @@ -22,6 +22,8 @@ #ifndef PARSERBASE_H #define PARSERBASE_H +#include "config.h" + #include #include #include @@ -30,7 +32,7 @@ #include #include -#include "config.h" +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" @@ -41,7 +43,7 @@ class ParserBase : public QObject { Q_OBJECT public: - explicit ParserBase(CollectionBackendInterface *collection, QObject *parent = nullptr); + explicit ParserBase(SharedPtr collection_backend, QObject *parent = nullptr); virtual QString name() const = 0; virtual QStringList file_extensions() const = 0; @@ -72,7 +74,7 @@ class ParserBase : public QObject { static QString URLOrFilename(const QUrl &url, const QDir &dir, const PlaylistSettingsPage::PathType path_type); private: - CollectionBackendInterface *collection_; + SharedPtr collection_backend_; }; #endif // PARSERBASE_H diff --git a/src/playlistparsers/playlistparser.cpp b/src/playlistparsers/playlistparser.cpp index d49188bd..2a41af33 100644 --- a/src/playlistparsers/playlistparser.cpp +++ b/src/playlistparsers/playlistparser.cpp @@ -30,6 +30,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "settings/playlistsettingspage.h" #include "playlistparser.h" #include "parserbase.h" @@ -43,16 +44,16 @@ const int PlaylistParser::kMagicSize = 512; -PlaylistParser::PlaylistParser(CollectionBackendInterface *collection, QObject *parent) : QObject(parent) { +PlaylistParser::PlaylistParser(SharedPtr collection_backend, QObject *parent) : QObject(parent) { - default_parser_ = new XSPFParser(collection, this); + default_parser_ = new XSPFParser(collection_backend, this); parsers_ << default_parser_; - parsers_ << new M3UParser(collection, this); - parsers_ << new PLSParser(collection, this); - parsers_ << new ASXParser(collection, this); - parsers_ << new AsxIniParser(collection, this); - parsers_ << new CueParser(collection, this); - parsers_ << new WplParser(collection, this); + parsers_ << new M3UParser(collection_backend, this); + parsers_ << new PLSParser(collection_backend, this); + parsers_ << new ASXParser(collection_backend, this); + parsers_ << new AsxIniParser(collection_backend, this); + parsers_ << new CueParser(collection_backend, this); + parsers_ << new WplParser(collection_backend, this); } diff --git a/src/playlistparsers/playlistparser.h b/src/playlistparsers/playlistparser.h index 5a8c6fbc..f31bc8ee 100644 --- a/src/playlistparsers/playlistparser.h +++ b/src/playlistparsers/playlistparser.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" @@ -41,7 +42,7 @@ class PlaylistParser : public QObject { Q_OBJECT public: - explicit PlaylistParser(CollectionBackendInterface *collection = nullptr, QObject *parent = nullptr); + explicit PlaylistParser(SharedPtr collection_backend = nullptr, QObject *parent = nullptr); enum class Type { Load, diff --git a/src/playlistparsers/plsparser.cpp b/src/playlistparsers/plsparser.cpp index fb694bb5..88e4314b 100644 --- a/src/playlistparsers/plsparser.cpp +++ b/src/playlistparsers/plsparser.cpp @@ -28,6 +28,7 @@ #include #include +#include "core/shared_ptr.h" #include "utilities/timeconstants.h" #include "settings/playlistsettingspage.h" #include "parserbase.h" @@ -41,8 +42,8 @@ constexpr auto qt_endl = Qt::endl; constexpr auto qt_endl = endl; #endif -PLSParser::PLSParser(CollectionBackendInterface *collection, QObject *parent) - : ParserBase(collection, parent) {} +PLSParser::PLSParser(SharedPtr collection_backend, QObject *parent) + : ParserBase(collection_backend, parent) {} SongList PLSParser::Load(QIODevice *device, const QString &playlist_path, const QDir &dir, const bool collection_search) const { diff --git a/src/playlistparsers/plsparser.h b/src/playlistparsers/plsparser.h index 3aacabdd..9cb5eb3b 100644 --- a/src/playlistparsers/plsparser.h +++ b/src/playlistparsers/plsparser.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" #include "parserbase.h" @@ -40,7 +41,7 @@ class PLSParser : public ParserBase { Q_OBJECT public: - explicit PLSParser(CollectionBackendInterface *collection, QObject *parent = nullptr); + explicit PLSParser(SharedPtr collection_backend, QObject *parent = nullptr); QString name() const override { return "PLS"; } QStringList file_extensions() const override { return QStringList() << "pls"; } diff --git a/src/playlistparsers/wplparser.cpp b/src/playlistparsers/wplparser.cpp index 84878c0d..f850814d 100644 --- a/src/playlistparsers/wplparser.cpp +++ b/src/playlistparsers/wplparser.cpp @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "utilities/xmlutils.h" #include "settings/playlistsettingspage.h" #include "xmlparser.h" @@ -36,8 +37,8 @@ class CollectionBackendInterface; -WplParser::WplParser(CollectionBackendInterface *collection, QObject *parent) - : XMLParser(collection, parent) {} +WplParser::WplParser(SharedPtr collection_backend, QObject *parent) + : XMLParser(collection_backend, parent) {} bool WplParser::TryMagic(const QByteArray &data) const { return data.contains(""); diff --git a/src/playlistparsers/wplparser.h b/src/playlistparsers/wplparser.h index f43170c5..dff4f807 100644 --- a/src/playlistparsers/wplparser.h +++ b/src/playlistparsers/wplparser.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" #include "xmlparser.h" @@ -43,7 +44,7 @@ class WplParser : public XMLParser { Q_OBJECT public: - explicit WplParser(CollectionBackendInterface *collection, QObject *parent = nullptr); + explicit WplParser(SharedPtr collection_backend, QObject *parent = nullptr); QString name() const override { return "WPL"; } QStringList file_extensions() const override { return QStringList() << "wpl"; } diff --git a/src/playlistparsers/xmlparser.cpp b/src/playlistparsers/xmlparser.cpp index 8d2e9c2b..90c188e6 100644 --- a/src/playlistparsers/xmlparser.cpp +++ b/src/playlistparsers/xmlparser.cpp @@ -20,10 +20,11 @@ #include +#include "core/shared_ptr.h" #include "parserbase.h" #include "xmlparser.h" class CollectionBackendInterface; -XMLParser::XMLParser(CollectionBackendInterface *collection, QObject *parent) - : ParserBase(collection, parent) {} +XMLParser::XMLParser(SharedPtr collection_backend, QObject *parent) + : ParserBase(collection_backend, parent) {} diff --git a/src/playlistparsers/xmlparser.h b/src/playlistparsers/xmlparser.h index 97dbd459..4bca7e06 100644 --- a/src/playlistparsers/xmlparser.h +++ b/src/playlistparsers/xmlparser.h @@ -28,6 +28,7 @@ #include #include +#include "core/shared_ptr.h" #include "parserbase.h" class CollectionBackendInterface; @@ -36,7 +37,7 @@ class XMLParser : public ParserBase { Q_OBJECT protected: - explicit XMLParser(CollectionBackendInterface *collection, QObject *parent); + explicit XMLParser(SharedPtr collection_backend, QObject *parent); class StreamElement { public: diff --git a/src/playlistparsers/xspfparser.cpp b/src/playlistparsers/xspfparser.cpp index 6e3a61d7..7f26e971 100644 --- a/src/playlistparsers/xspfparser.cpp +++ b/src/playlistparsers/xspfparser.cpp @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "utilities/xmlutils.h" #include "utilities/timeconstants.h" #include "settings/playlistsettingspage.h" @@ -37,8 +38,8 @@ class CollectionBackendInterface; -XSPFParser::XSPFParser(CollectionBackendInterface *collection, QObject *parent) - : XMLParser(collection, parent) {} +XSPFParser::XSPFParser(SharedPtr collection_backend, QObject *parent) + : XMLParser(collection_backend, parent) {} SongList XSPFParser::Load(QIODevice *device, const QString &playlist_path, const QDir &dir, const bool collection_search) const { diff --git a/src/playlistparsers/xspfparser.h b/src/playlistparsers/xspfparser.h index 8f6e7f30..766ab94d 100644 --- a/src/playlistparsers/xspfparser.h +++ b/src/playlistparsers/xspfparser.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "settings/playlistsettingspage.h" #include "xmlparser.h" @@ -41,7 +42,7 @@ class XSPFParser : public XMLParser { Q_OBJECT public: - explicit XSPFParser(CollectionBackendInterface *collection, QObject *parent = nullptr); + explicit XSPFParser(SharedPtr collection_backend, QObject *parent = nullptr); QString name() const override { return "XSPF"; } QStringList file_extensions() const override { return QStringList() << "xspf"; } diff --git a/src/qobuz/qobuzbaserequest.cpp b/src/qobuz/qobuzbaserequest.cpp index 0b376c46..b82d19e5 100644 --- a/src/qobuz/qobuzbaserequest.cpp +++ b/src/qobuz/qobuzbaserequest.cpp @@ -37,11 +37,12 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "qobuzservice.h" #include "qobuzbaserequest.h" -QobuzBaseRequest::QobuzBaseRequest(QobuzService *service, NetworkAccessManager *network, QObject *parent) +QobuzBaseRequest::QobuzBaseRequest(QobuzService *service, SharedPtr network, QObject *parent) : QObject(parent), service_(service), network_(network) {} diff --git a/src/qobuz/qobuzbaserequest.h b/src/qobuz/qobuzbaserequest.h index acc7f24b..d25f63d0 100644 --- a/src/qobuz/qobuzbaserequest.h +++ b/src/qobuz/qobuzbaserequest.h @@ -34,6 +34,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "qobuzservice.h" @@ -44,7 +45,7 @@ class QobuzBaseRequest : public QObject { Q_OBJECT public: - explicit QobuzBaseRequest(QobuzService *service, NetworkAccessManager *network, QObject *parent = nullptr); + explicit QobuzBaseRequest(QobuzService *service, SharedPtr network, QObject *parent = nullptr); ~QobuzBaseRequest(); enum class QueryType { @@ -95,8 +96,7 @@ class QobuzBaseRequest : public QObject { private: QobuzService *service_; - NetworkAccessManager *network_; - + SharedPtr network_; }; #endif // QOBUZBASEREQUEST_H diff --git a/src/qobuz/qobuzfavoriterequest.cpp b/src/qobuz/qobuzfavoriterequest.cpp index aa51e0a7..53a04237 100644 --- a/src/qobuz/qobuzfavoriterequest.cpp +++ b/src/qobuz/qobuzfavoriterequest.cpp @@ -29,13 +29,14 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/song.h" #include "qobuzservice.h" #include "qobuzbaserequest.h" #include "qobuzfavoriterequest.h" -QobuzFavoriteRequest::QobuzFavoriteRequest(QobuzService *service, NetworkAccessManager *network, QObject *parent) +QobuzFavoriteRequest::QobuzFavoriteRequest(QobuzService *service, SharedPtr network, QObject *parent) : QobuzBaseRequest(service, network, parent), service_(service), network_(network) {} diff --git a/src/qobuz/qobuzfavoriterequest.h b/src/qobuz/qobuzfavoriterequest.h index ded73372..239b2c5e 100644 --- a/src/qobuz/qobuzfavoriterequest.h +++ b/src/qobuz/qobuzfavoriterequest.h @@ -28,6 +28,7 @@ #include #include "qobuzbaserequest.h" +#include "core/shared_ptr.h" #include "core/song.h" class QNetworkReply; @@ -38,7 +39,7 @@ class QobuzFavoriteRequest : public QobuzBaseRequest { Q_OBJECT public: - explicit QobuzFavoriteRequest(QobuzService *service, NetworkAccessManager *network, QObject *parent = nullptr); + explicit QobuzFavoriteRequest(QobuzService *service, SharedPtr network, QObject *parent = nullptr); ~QobuzFavoriteRequest(); private: @@ -80,7 +81,7 @@ class QobuzFavoriteRequest : public QobuzBaseRequest { void RemoveFavoritesRequest(const FavoriteType type, const QStringList &ids_list, const SongList &songs); QobuzService *service_; - NetworkAccessManager *network_; + SharedPtr network_; QList replies_; }; diff --git a/src/qobuz/qobuzrequest.cpp b/src/qobuz/qobuzrequest.cpp index a38474f3..62f7366c 100644 --- a/src/qobuz/qobuzrequest.cpp +++ b/src/qobuz/qobuzrequest.cpp @@ -35,6 +35,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/song.h" #include "core/application.h" @@ -54,7 +55,7 @@ constexpr int QobuzRequest::kMaxConcurrentAlbumSongsRequests = 3; constexpr int QobuzRequest::kMaxConcurrentAlbumCoverRequests = 1; constexpr int QobuzRequest::kFlushRequestsDelay = 200; -QobuzRequest::QobuzRequest(QobuzService *service, QobuzUrlHandler *url_handler, Application *app, NetworkAccessManager *network, const QueryType query_type, QObject *parent) +QobuzRequest::QobuzRequest(QobuzService *service, QobuzUrlHandler *url_handler, Application *app, SharedPtr network, const QueryType query_type, QObject *parent) : QobuzBaseRequest(service, network, parent), service_(service), url_handler_(url_handler), diff --git a/src/qobuz/qobuzrequest.h b/src/qobuz/qobuzrequest.h index 8ac9ac45..1f615781 100644 --- a/src/qobuz/qobuzrequest.h +++ b/src/qobuz/qobuzrequest.h @@ -37,6 +37,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "qobuzbaserequest.h" @@ -52,7 +53,7 @@ class QobuzRequest : public QobuzBaseRequest { public: - explicit QobuzRequest(QobuzService *service, QobuzUrlHandler *url_handler, Application *app, NetworkAccessManager *network, const QueryType query_type, QObject *parent = nullptr); + explicit QobuzRequest(QobuzService *service, QobuzUrlHandler *url_handler, Application *app, SharedPtr network, const QueryType query_type, QObject *parent = nullptr); ~QobuzRequest() override; void ReloadSettings(); @@ -181,7 +182,7 @@ class QobuzRequest : public QobuzBaseRequest { QobuzService *service_; QobuzUrlHandler *url_handler_; Application *app_; - NetworkAccessManager *network_; + SharedPtr network_; QTimer *timer_flush_requests_; const QueryType query_type_; diff --git a/src/qobuz/qobuzservice.cpp b/src/qobuz/qobuzservice.cpp index 0962613d..d33256fb 100644 --- a/src/qobuz/qobuzservice.cpp +++ b/src/qobuz/qobuzservice.cpp @@ -38,6 +38,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/player.h" #include "core/logging.h" @@ -57,6 +58,8 @@ #include "settings/settingsdialog.h" #include "settings/qobuzsettingspage.h" +using std::make_shared; + const Song::Source QobuzService::kSource = Song::Source::Qobuz; const char QobuzService::kApiUrl[] = "https://www.qobuz.com/api.json/0.2"; @@ -110,15 +113,15 @@ QobuzService::QobuzService(Application *app, QObject *parent) // Backends - artists_collection_backend_ = new CollectionBackend(); + artists_collection_backend_ = make_shared(); artists_collection_backend_->moveToThread(app_->database()->thread()); artists_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Qobuz, kArtistsSongsTable, kArtistsSongsFtsTable); - albums_collection_backend_ = new CollectionBackend(); + albums_collection_backend_ = make_shared(); albums_collection_backend_->moveToThread(app_->database()->thread()); albums_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Qobuz, kAlbumsSongsTable, kAlbumsSongsFtsTable); - songs_collection_backend_ = new CollectionBackend(); + songs_collection_backend_ = make_shared(); songs_collection_backend_->moveToThread(app_->database()->thread()); songs_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Qobuz, kSongsTable, kSongsFtsTable); @@ -164,13 +167,13 @@ QobuzService::QobuzService(Application *app, QObject *parent) QObject::connect(this, &QobuzService::RemoveSongsByList, favorite_request_, QOverload::of(&QobuzFavoriteRequest::RemoveSongs)); QObject::connect(this, &QobuzService::RemoveSongsByMap, favorite_request_, QOverload::of(&QobuzFavoriteRequest::RemoveSongs)); - QObject::connect(favorite_request_, &QobuzFavoriteRequest::ArtistsAdded, artists_collection_backend_, &CollectionBackend::AddOrUpdateSongs); - QObject::connect(favorite_request_, &QobuzFavoriteRequest::AlbumsAdded, albums_collection_backend_, &CollectionBackend::AddOrUpdateSongs); - QObject::connect(favorite_request_, &QobuzFavoriteRequest::SongsAdded, songs_collection_backend_, &CollectionBackend::AddOrUpdateSongs); + QObject::connect(favorite_request_, &QobuzFavoriteRequest::ArtistsAdded, &*artists_collection_backend_, &CollectionBackend::AddOrUpdateSongs); + QObject::connect(favorite_request_, &QobuzFavoriteRequest::AlbumsAdded, &*albums_collection_backend_, &CollectionBackend::AddOrUpdateSongs); + QObject::connect(favorite_request_, &QobuzFavoriteRequest::SongsAdded, &*songs_collection_backend_, &CollectionBackend::AddOrUpdateSongs); - QObject::connect(favorite_request_, &QobuzFavoriteRequest::ArtistsRemoved, artists_collection_backend_, &CollectionBackend::DeleteSongs); - QObject::connect(favorite_request_, &QobuzFavoriteRequest::AlbumsRemoved, albums_collection_backend_, &CollectionBackend::DeleteSongs); - QObject::connect(favorite_request_, &QobuzFavoriteRequest::SongsRemoved, songs_collection_backend_, &CollectionBackend::DeleteSongs); + QObject::connect(favorite_request_, &QobuzFavoriteRequest::ArtistsRemoved, &*artists_collection_backend_, &CollectionBackend::DeleteSongs); + QObject::connect(favorite_request_, &QobuzFavoriteRequest::AlbumsRemoved, &*albums_collection_backend_, &CollectionBackend::DeleteSongs); + QObject::connect(favorite_request_, &QobuzFavoriteRequest::SongsRemoved, &*songs_collection_backend_, &CollectionBackend::DeleteSongs); QobuzService::ReloadSettings(); @@ -186,23 +189,23 @@ QobuzService::~QobuzService() { } while (!stream_url_requests_.isEmpty()) { - std::shared_ptr stream_url_req = stream_url_requests_.take(stream_url_requests_.firstKey()); - QObject::disconnect(stream_url_req.get(), nullptr, this, nullptr); + SharedPtr stream_url_req = stream_url_requests_.take(stream_url_requests_.firstKey()); + QObject::disconnect(&*stream_url_req, nullptr, this, nullptr); } - artists_collection_backend_->deleteLater(); - albums_collection_backend_->deleteLater(); - songs_collection_backend_->deleteLater(); + artists_collection_backend_.reset(); + albums_collection_backend_.reset(); + songs_collection_backend_.reset(); } void QobuzService::Exit() { - wait_for_exit_ << artists_collection_backend_ << albums_collection_backend_ << songs_collection_backend_; + wait_for_exit_ << &*artists_collection_backend_ << &*albums_collection_backend_ << &*songs_collection_backend_; - QObject::connect(artists_collection_backend_, &CollectionBackend::ExitFinished, this, &QobuzService::ExitReceived); - QObject::connect(albums_collection_backend_, &CollectionBackend::ExitFinished, this, &QobuzService::ExitReceived); - QObject::connect(songs_collection_backend_, &CollectionBackend::ExitFinished, this, &QobuzService::ExitReceived); + QObject::connect(&*artists_collection_backend_, &CollectionBackend::ExitFinished, this, &QobuzService::ExitReceived); + QObject::connect(&*albums_collection_backend_, &CollectionBackend::ExitFinished, this, &QobuzService::ExitReceived); + QObject::connect(&*songs_collection_backend_, &CollectionBackend::ExitFinished, this, &QobuzService::ExitReceived); artists_collection_backend_->ExitAsync(); albums_collection_backend_->ExitAsync(); @@ -515,8 +518,8 @@ void QobuzService::TryLogin() { void QobuzService::ResetArtistsRequest() { if (artists_request_) { - QObject::disconnect(artists_request_.get(), nullptr, this, nullptr); - QObject::disconnect(this, nullptr, artists_request_.get(), nullptr); + QObject::disconnect(&*artists_request_, nullptr, this, nullptr); + QObject::disconnect(this, nullptr, &*artists_request_, nullptr); artists_request_.reset(); } @@ -536,9 +539,9 @@ void QobuzService::GetArtists() { ResetArtistsRequest(); artists_request_.reset(new QobuzRequest(this, url_handler_, app_, network_, QobuzBaseRequest::QueryType::Artists), [](QobuzRequest *request) { request->deleteLater(); }); - QObject::connect(artists_request_.get(), &QobuzRequest::Results, this, &QobuzService::ArtistsResultsReceived); - QObject::connect(artists_request_.get(), &QobuzRequest::UpdateStatus, this, &QobuzService::ArtistsUpdateStatusReceived); - QObject::connect(artists_request_.get(), &QobuzRequest::UpdateProgress, this, &QobuzService::ArtistsUpdateProgressReceived); + QObject::connect(&*artists_request_, &QobuzRequest::Results, this, &QobuzService::ArtistsResultsReceived); + QObject::connect(&*artists_request_, &QobuzRequest::UpdateStatus, this, &QobuzService::ArtistsUpdateStatusReceived); + QObject::connect(&*artists_request_, &QobuzRequest::UpdateProgress, this, &QobuzService::ArtistsUpdateProgressReceived); artists_request_->Process(); @@ -565,8 +568,8 @@ void QobuzService::ArtistsUpdateProgressReceived(const int id, const int progres void QobuzService::ResetAlbumsRequest() { if (albums_request_) { - QObject::disconnect(albums_request_.get(), nullptr, this, nullptr); - QObject::disconnect(this, nullptr, albums_request_.get(), nullptr); + QObject::disconnect(&*albums_request_, nullptr, this, nullptr); + QObject::disconnect(this, nullptr, &*albums_request_, nullptr); albums_request_.reset(); } @@ -586,9 +589,9 @@ void QobuzService::GetAlbums() { ResetAlbumsRequest(); albums_request_.reset(new QobuzRequest(this, url_handler_, app_, network_, QobuzBaseRequest::QueryType::Albums), [](QobuzRequest *request) { request->deleteLater(); }); - QObject::connect(albums_request_.get(), &QobuzRequest::Results, this, &QobuzService::AlbumsResultsReceived); - QObject::connect(albums_request_.get(), &QobuzRequest::UpdateStatus, this, &QobuzService::AlbumsUpdateStatusReceived); - QObject::connect(albums_request_.get(), &QobuzRequest::UpdateProgress, this, &QobuzService::AlbumsUpdateProgressReceived); + QObject::connect(&*albums_request_, &QobuzRequest::Results, this, &QobuzService::AlbumsResultsReceived); + QObject::connect(&*albums_request_, &QobuzRequest::UpdateStatus, this, &QobuzService::AlbumsUpdateStatusReceived); + QObject::connect(&*albums_request_, &QobuzRequest::UpdateProgress, this, &QobuzService::AlbumsUpdateProgressReceived); albums_request_->Process(); @@ -615,8 +618,8 @@ void QobuzService::AlbumsUpdateProgressReceived(const int id, const int progress void QobuzService::ResetSongsRequest() { if (songs_request_) { - QObject::disconnect(songs_request_.get(), nullptr, this, nullptr); - QObject::disconnect(this, nullptr, songs_request_.get(), nullptr); + QObject::disconnect(&*songs_request_, nullptr, this, nullptr); + QObject::disconnect(this, nullptr, &*songs_request_, nullptr); songs_request_.reset(); } @@ -636,9 +639,9 @@ void QobuzService::GetSongs() { ResetSongsRequest(); songs_request_.reset(new QobuzRequest(this, url_handler_, app_, network_, QobuzBaseRequest::QueryType::Songs), [](QobuzRequest *request) { request->deleteLater(); }); - QObject::connect(songs_request_.get(), &QobuzRequest::Results, this, &QobuzService::SongsResultsReceived); - QObject::connect(songs_request_.get(), &QobuzRequest::UpdateStatus, this, &QobuzService::SongsUpdateStatusReceived); - QObject::connect(songs_request_.get(), &QobuzRequest::UpdateProgress, this, &QobuzService::SongsUpdateProgressReceived); + QObject::connect(&*songs_request_, &QobuzRequest::Results, this, &QobuzService::SongsResultsReceived); + QObject::connect(&*songs_request_, &QobuzRequest::UpdateStatus, this, &QobuzService::SongsUpdateStatusReceived); + QObject::connect(&*songs_request_, &QobuzRequest::UpdateProgress, this, &QobuzService::SongsUpdateProgressReceived); songs_request_->Process(); @@ -716,9 +719,9 @@ void QobuzService::SendSearch() { search_request_.reset(new QobuzRequest(this, url_handler_, app_, network_, query_type), [](QobuzRequest *request) { request->deleteLater(); } ); - QObject::connect(search_request_.get(), &QobuzRequest::Results, this, &QobuzService::SearchResultsReceived); - QObject::connect(search_request_.get(), &QobuzRequest::UpdateStatus, this, &QobuzService::SearchUpdateStatus); - QObject::connect(search_request_.get(), &QobuzRequest::UpdateProgress, this, &QobuzService::SearchUpdateProgress); + QObject::connect(&*search_request_, &QobuzRequest::Results, this, &QobuzService::SearchResultsReceived); + QObject::connect(&*search_request_, &QobuzRequest::UpdateStatus, this, &QobuzService::SearchUpdateStatus); + QObject::connect(&*search_request_, &QobuzRequest::UpdateProgress, this, &QobuzService::SearchUpdateProgress); search_request_->Search(search_id_, search_text_); search_request_->Process(); @@ -741,14 +744,14 @@ uint QobuzService::GetStreamURL(const QUrl &url, QString &error) { uint id = 0; while (id == 0) id = ++next_stream_url_request_id_; - std::shared_ptr stream_url_req; + SharedPtr stream_url_req; stream_url_req.reset(new QobuzStreamURLRequest(this, network_, url, id), [](QobuzStreamURLRequest *request) { request->deleteLater(); }); stream_url_requests_.insert(id, stream_url_req); - QObject::connect(stream_url_req.get(), &QobuzStreamURLRequest::TryLogin, this, &QobuzService::TryLogin); - QObject::connect(stream_url_req.get(), &QobuzStreamURLRequest::StreamURLFailure, this, &QobuzService::HandleStreamURLFailure); - QObject::connect(stream_url_req.get(), &QobuzStreamURLRequest::StreamURLSuccess, this, &QobuzService::HandleStreamURLSuccess); - QObject::connect(this, &QobuzService::LoginComplete, stream_url_req.get(), &QobuzStreamURLRequest::LoginComplete); + QObject::connect(&*stream_url_req, &QobuzStreamURLRequest::TryLogin, this, &QobuzService::TryLogin); + QObject::connect(&*stream_url_req, &QobuzStreamURLRequest::StreamURLFailure, this, &QobuzService::HandleStreamURLFailure); + QObject::connect(&*stream_url_req, &QobuzStreamURLRequest::StreamURLSuccess, this, &QobuzService::HandleStreamURLSuccess); + QObject::connect(this, &QobuzService::LoginComplete, &*stream_url_req, &QobuzStreamURLRequest::LoginComplete); stream_url_req->Process(); diff --git a/src/qobuz/qobuzservice.h b/src/qobuz/qobuzservice.h index ad6625de..90fb5918 100644 --- a/src/qobuz/qobuzservice.h +++ b/src/qobuz/qobuzservice.h @@ -37,6 +37,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "internet/internetservice.h" #include "internet/internetsearchview.h" @@ -57,7 +58,7 @@ class QobuzService : public InternetService { Q_OBJECT public: - explicit QobuzService(Application *app, QObject *parent); + explicit QobuzService(Application *app, QObject *parent = nullptr); ~QobuzService(); static const Song::Source kSource; @@ -95,9 +96,9 @@ class QobuzService : public InternetService { uint GetStreamURL(const QUrl &url, QString &error); - CollectionBackend *artists_collection_backend() override { return artists_collection_backend_; } - CollectionBackend *albums_collection_backend() override { return albums_collection_backend_; } - CollectionBackend *songs_collection_backend() override { return songs_collection_backend_; } + SharedPtr artists_collection_backend() override { return artists_collection_backend_; } + SharedPtr albums_collection_backend() override { return albums_collection_backend_; } + SharedPtr songs_collection_backend() override { return songs_collection_backend_; } CollectionModel *artists_collection_model() override { return artists_collection_model_; } CollectionModel *albums_collection_model() override { return albums_collection_model_; } @@ -160,12 +161,12 @@ class QobuzService : public InternetService { static const char kSongsFtsTable[]; Application *app_; - NetworkAccessManager *network_; + SharedPtr network_; QobuzUrlHandler *url_handler_; - CollectionBackend *artists_collection_backend_; - CollectionBackend *albums_collection_backend_; - CollectionBackend *songs_collection_backend_; + SharedPtr artists_collection_backend_; + SharedPtr albums_collection_backend_; + SharedPtr songs_collection_backend_; CollectionModel *artists_collection_model_; CollectionModel *albums_collection_model_; @@ -178,10 +179,10 @@ class QobuzService : public InternetService { QTimer *timer_search_delay_; QTimer *timer_login_attempt_; - std::shared_ptr artists_request_; - std::shared_ptr albums_request_; - std::shared_ptr songs_request_; - std::shared_ptr search_request_; + SharedPtr artists_request_; + SharedPtr albums_request_; + SharedPtr songs_request_; + SharedPtr search_request_; QobuzFavoriteRequest *favorite_request_; QString app_id_; @@ -211,7 +212,7 @@ class QobuzService : public InternetService { int login_attempts_; uint next_stream_url_request_id_; - QMap> stream_url_requests_; + QMap> stream_url_requests_; QStringList login_errors_; @@ -219,4 +220,6 @@ class QobuzService : public InternetService { QList replies_; }; +using QobuzServicePtr = SharedPtr; + #endif // QOBUZSERVICE_H diff --git a/src/qobuz/qobuzstreamurlrequest.cpp b/src/qobuz/qobuzstreamurlrequest.cpp index dd9b87a7..4c733853 100644 --- a/src/qobuz/qobuzstreamurlrequest.cpp +++ b/src/qobuz/qobuzstreamurlrequest.cpp @@ -34,6 +34,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/song.h" #include "utilities/timeconstants.h" @@ -41,7 +42,7 @@ #include "qobuzbaserequest.h" #include "qobuzstreamurlrequest.h" -QobuzStreamURLRequest::QobuzStreamURLRequest(QobuzService *service, NetworkAccessManager *network, const QUrl &media_url, const uint id, QObject *parent) +QobuzStreamURLRequest::QobuzStreamURLRequest(QobuzService *service, SharedPtr network, const QUrl &media_url, const uint id, QObject *parent) : QobuzBaseRequest(service, network, parent), service_(service), reply_(nullptr), diff --git a/src/qobuz/qobuzstreamurlrequest.h b/src/qobuz/qobuzstreamurlrequest.h index 1c2de9a0..97a44ffb 100644 --- a/src/qobuz/qobuzstreamurlrequest.h +++ b/src/qobuz/qobuzstreamurlrequest.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "qobuzbaserequest.h" @@ -40,7 +41,7 @@ class QobuzStreamURLRequest : public QobuzBaseRequest { Q_OBJECT public: - explicit QobuzStreamURLRequest(QobuzService *service, NetworkAccessManager *network, const QUrl &media_url, const uint id, QObject *parent = nullptr); + explicit QobuzStreamURLRequest(QobuzService *service, SharedPtr network, const QUrl &media_url, const uint id, QObject *parent = nullptr); ~QobuzStreamURLRequest(); void GetStreamURL(); diff --git a/src/queue/queueview.cpp b/src/queue/queueview.cpp index 18ee32cf..527b7c0e 100644 --- a/src/queue/queueview.cpp +++ b/src/queue/queueview.cpp @@ -33,6 +33,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/iconloader.h" #include "playlist/playlist.h" #include "playlist/playlistdelegates.h" @@ -45,7 +46,7 @@ QueueView::QueueView(QWidget *parent) : QWidget(parent), ui_(new Ui_QueueView), - playlists_(nullptr), + playlist_manager_(nullptr), current_playlist_(nullptr) { ui_->setupUi(this); @@ -74,12 +75,12 @@ QueueView::~QueueView() { delete ui_; } -void QueueView::SetPlaylistManager(PlaylistManager *manager) { +void QueueView::SetPlaylistManager(SharedPtr playlist_manager) { - playlists_ = manager; + playlist_manager_ = playlist_manager; - QObject::connect(playlists_, &PlaylistManager::CurrentChanged, this, &QueueView::CurrentPlaylistChanged); - CurrentPlaylistChanged(playlists_->current()); + QObject::connect(&*playlist_manager, &PlaylistManager::CurrentChanged, this, &QueueView::CurrentPlaylistChanged); + CurrentPlaylistChanged(playlist_manager_->current()); } diff --git a/src/queue/queueview.h b/src/queue/queueview.h index c734bcfb..cc8b4a25 100644 --- a/src/queue/queueview.h +++ b/src/queue/queueview.h @@ -28,6 +28,8 @@ #include #include +#include "core/shared_ptr.h" + class Playlist; class PlaylistManager; class Ui_QueueView; @@ -39,7 +41,7 @@ class QueueView : public QWidget { explicit QueueView(QWidget *parent = nullptr); ~QueueView() override; - void SetPlaylistManager(PlaylistManager *manager); + void SetPlaylistManager(SharedPtr playlist_manager); void ReloadSettings(); private slots: @@ -55,7 +57,7 @@ class QueueView : public QWidget { private: Ui_QueueView *ui_; - PlaylistManager *playlists_; + SharedPtr playlist_manager_; Playlist *current_playlist_; }; diff --git a/src/radios/radiobackend.cpp b/src/radios/radiobackend.cpp index 542f7e05..be7a53af 100644 --- a/src/radios/radiobackend.cpp +++ b/src/radios/radiobackend.cpp @@ -23,13 +23,14 @@ #include #include +#include "core/shared_ptr.h" #include "core/database.h" #include "core/sqlquery.h" #include "core/song.h" #include "radiobackend.h" #include "radiochannel.h" -RadioBackend::RadioBackend(Database *db, QObject *parent) +RadioBackend::RadioBackend(SharedPtr db, QObject *parent) : QObject(parent), db_(db), original_thread_(thread()) {} diff --git a/src/radios/radiobackend.h b/src/radios/radiobackend.h index e8d373ea..fc79c09c 100644 --- a/src/radios/radiobackend.h +++ b/src/radios/radiobackend.h @@ -22,6 +22,7 @@ #include +#include "core/shared_ptr.h" #include "radiochannel.h" class QThread; @@ -31,7 +32,7 @@ class RadioBackend : public QObject { Q_OBJECT public: - explicit RadioBackend(Database *db, QObject *parent = nullptr); + explicit RadioBackend(SharedPtr db, QObject *parent = nullptr); void Close(); void ExitAsync(); @@ -53,7 +54,7 @@ class RadioBackend : public QObject { void Exit(); private: - Database *db_; + SharedPtr db_; QThread *original_thread_; }; diff --git a/src/radios/radiomodel.cpp b/src/radios/radiomodel.cpp index 3f81aba4..7cbc7157 100644 --- a/src/radios/radiomodel.cpp +++ b/src/radios/radiomodel.cpp @@ -48,7 +48,7 @@ RadioModel::RadioModel(Application *app, QObject *parent) root_->lazy_loaded = true; if (app_) { - QObject::connect(app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &RadioModel::AlbumCoverLoaded); + QObject::connect(&*app_->album_cover_loader(), &AlbumCoverLoader::AlbumCoverLoaded, this, &RadioModel::AlbumCoverLoaded); } } diff --git a/src/radios/radioparadiseservice.cpp b/src/radios/radioparadiseservice.cpp index 33d48b5b..d5434fb2 100644 --- a/src/radios/radioparadiseservice.cpp +++ b/src/radios/radioparadiseservice.cpp @@ -24,7 +24,7 @@ #include "radioparadiseservice.h" #include "radiochannel.h" -RadioParadiseService::RadioParadiseService(Application *app, NetworkAccessManager *network, QObject *parent) +RadioParadiseService::RadioParadiseService(Application *app, SharedPtr network, QObject *parent) : RadioService(Song::Source::RadioParadise, "Radio Paradise", IconLoader::Load("radioparadise"), app, network, parent) {} QUrl RadioParadiseService::Homepage() { return QUrl("https://radioparadise.com/"); } diff --git a/src/radios/radioparadiseservice.h b/src/radios/radioparadiseservice.h index 8f62e3a0..bf43ad04 100644 --- a/src/radios/radioparadiseservice.h +++ b/src/radios/radioparadiseservice.h @@ -32,7 +32,7 @@ class RadioParadiseService : public RadioService { Q_OBJECT public: - explicit RadioParadiseService(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit RadioParadiseService(Application *app, SharedPtr network, QObject *parent = nullptr); QUrl Homepage() override; QUrl Donate() override; diff --git a/src/radios/radioservice.cpp b/src/radios/radioservice.cpp index 16005feb..f3ecc143 100644 --- a/src/radios/radioservice.cpp +++ b/src/radios/radioservice.cpp @@ -27,10 +27,11 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "radioservice.h" -RadioService::RadioService(const Song::Source source, const QString &name, const QIcon &icon, Application *app, NetworkAccessManager *network, QObject *parent) +RadioService::RadioService(const Song::Source source, const QString &name, const QIcon &icon, Application *app, SharedPtr network, QObject *parent) : QObject(parent), app_(app), network_(network), diff --git a/src/radios/radioservice.h b/src/radios/radioservice.h index 2b7d80bf..d3026eb7 100644 --- a/src/radios/radioservice.h +++ b/src/radios/radioservice.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "radiochannel.h" @@ -42,7 +43,7 @@ class RadioService : public QObject { Q_OBJECT public: - explicit RadioService(const Song::Source source, const QString &name, const QIcon &icon, Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit RadioService(const Song::Source source, const QString &name, const QIcon &icon, Application *app, SharedPtr network, QObject *parent = nullptr); Song::Source source() const { return source_; } QString name() const { return name_; } @@ -66,7 +67,7 @@ class RadioService : public QObject { protected: Application *app_; - NetworkAccessManager *network_; + SharedPtr network_; Song::Source source_; QString name_; QIcon icon_; diff --git a/src/radios/radioservices.cpp b/src/radios/radioservices.cpp index b19d1736..7b0e7fbb 100644 --- a/src/radios/radioservices.cpp +++ b/src/radios/radioservices.cpp @@ -17,10 +17,13 @@ * */ +#include + #include #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/database.h" #include "core/networkaccessmanager.h" @@ -32,6 +35,8 @@ #include "somafmservice.h" #include "radioparadiseservice.h" +using std::make_shared; + RadioServices::RadioServices(Application *app, QObject *parent) : QObject(parent), network_(app->network()), @@ -40,10 +45,10 @@ RadioServices::RadioServices(Application *app, QObject *parent) sort_model_(new QSortFilterProxyModel(this)), channels_refresh_(false) { - backend_ = new RadioBackend(app->database()); - app->MoveToThread(backend_, app->database()->thread()); + backend_ = make_shared(app->database()); + app->MoveToThread(&*backend_, app->database()->thread()); - QObject::connect(backend_, &RadioBackend::NewChannels, this, &RadioServices::GotChannelsFromBackend); + QObject::connect(&*backend_, &RadioBackend::NewChannels, this, &RadioServices::GotChannelsFromBackend); sort_model_->setSourceModel(model_); sort_model_->setSortRole(RadioModel::Role_SortText); @@ -56,12 +61,6 @@ RadioServices::RadioServices(Application *app, QObject *parent) } -RadioServices::~RadioServices() { - - backend_->deleteLater(); - -} - void RadioServices::AddService(RadioService *service) { qLog(Debug) << "Adding radio service:" << service->name(); diff --git a/src/radios/radioservices.h b/src/radios/radioservices.h index 102f86e6..8d665917 100644 --- a/src/radios/radioservices.h +++ b/src/radios/radioservices.h @@ -23,6 +23,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "radiochannel.h" @@ -39,7 +40,6 @@ class RadioServices : public QObject { public: explicit RadioServices(Application *app, QObject *parent = nullptr); - ~RadioServices(); void AddService(RadioService *service); void RemoveService(RadioService *service); @@ -53,7 +53,7 @@ class RadioServices : public QObject { void ReloadSettings(); - RadioBackend *radio_backend() const { return backend_; } + SharedPtr radio_backend() const { return backend_; } QSortFilterProxyModel *sort_model() const { return sort_model_; } private slots: @@ -66,8 +66,8 @@ class RadioServices : public QObject { void RefreshChannels(); private: - NetworkAccessManager *network_; - RadioBackend *backend_; + SharedPtr network_; + SharedPtr backend_; RadioModel *model_; QSortFilterProxyModel *sort_model_; QMap services_; diff --git a/src/radios/somafmservice.cpp b/src/radios/somafmservice.cpp index 546d2939..30aa354f 100644 --- a/src/radios/somafmservice.cpp +++ b/src/radios/somafmservice.cpp @@ -36,7 +36,7 @@ const char *SomaFMService::kApiChannelsUrl = "https://somafm.com/channels.json"; -SomaFMService::SomaFMService(Application *app, NetworkAccessManager *network, QObject *parent) +SomaFMService::SomaFMService(Application *app, SharedPtr network, QObject *parent) : RadioService(Song::Source::SomaFM, "SomaFM", IconLoader::Load("somafm"), app, network, parent) {} SomaFMService::~SomaFMService() { diff --git a/src/radios/somafmservice.h b/src/radios/somafmservice.h index c30ab870..da8e6492 100644 --- a/src/radios/somafmservice.h +++ b/src/radios/somafmservice.h @@ -34,7 +34,7 @@ class SomaFMService : public RadioService { Q_OBJECT public: - explicit SomaFMService(Application *app, NetworkAccessManager *network, QObject *parent = nullptr); + explicit SomaFMService(Application *app, SharedPtr network, QObject *parent = nullptr); ~SomaFMService(); QUrl Homepage() override; diff --git a/src/scrobbler/audioscrobbler.cpp b/src/scrobbler/audioscrobbler.cpp index 6e4ec0ba..9f2dd1cf 100644 --- a/src/scrobbler/audioscrobbler.cpp +++ b/src/scrobbler/audioscrobbler.cpp @@ -19,36 +19,27 @@ #include "config.h" -#include +#include + #include #include -#include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/logging.h" #include "core/song.h" #include "settings/settingsdialog.h" -#include "settings/scrobblersettingspage.h" #include "audioscrobbler.h" +#include "scrobblersettings.h" #include "scrobblerservice.h" -#include "lastfmscrobbler.h" -#include "librefmscrobbler.h" -#include "listenbrainzscrobbler.h" -#ifdef HAVE_SUBSONIC -# include "subsonicscrobbler.h" -#endif + +using std::make_shared; AudioScrobbler::AudioScrobbler(Application *app, QObject *parent) : QObject(parent), app_(app), - enabled_(false), - offline_(false), - scrobble_button_(false), - love_button_(false), - submit_delay_(0), - prefer_albumartist_(false), - show_error_dialog_(false) { + settings_(make_shared(app)) { ReloadSettings(); @@ -57,56 +48,46 @@ AudioScrobbler::AudioScrobbler(Application *app, QObject *parent) AudioScrobbler::~AudioScrobbler() { while (!services_.isEmpty()) { - delete services_.take(services_.firstKey()); + ScrobblerServicePtr service = services_.first(); + RemoveService(service); } } -void AudioScrobbler::AddService(ScrobblerService *service) { +void AudioScrobbler::AddService(ScrobblerServicePtr service) { - { - QMutexLocker locker(&mutex_); - services_.insert(service->name(), service); - } + services_.insert(service->name(), service); - QObject::connect(service, &ScrobblerService::ErrorMessage, this, &AudioScrobbler::ErrorReceived); + QObject::connect(&*service, &ScrobblerService::ErrorMessage, this, &AudioScrobbler::ErrorReceived); qLog(Debug) << "Registered scrobbler service" << service->name(); } -void AudioScrobbler::RemoveService(ScrobblerService *service) { +void AudioScrobbler::RemoveService(ScrobblerServicePtr service) { if (!service || !services_.contains(service->name())) return; - { - QMutexLocker locker(&mutex_); - services_.remove(service->name()); - QObject::disconnect(service, nullptr, this, nullptr); - } + services_.remove(service->name()); + QObject::disconnect(&*service, nullptr, this, nullptr); - QObject::disconnect(service, &ScrobblerService::ErrorMessage, this, &AudioScrobbler::ErrorReceived); + QObject::disconnect(&*service, &ScrobblerService::ErrorMessage, this, &AudioScrobbler::ErrorReceived); qLog(Debug) << "Unregistered scrobbler service" << service->name(); } -int AudioScrobbler::NextId() { return next_id_.fetchAndAddRelaxed(1); } +QList AudioScrobbler::GetAll() { -QList AudioScrobbler::GetAll() { + QList services; - QList services; - - { - QMutexLocker locker(&mutex_); services = services_.values(); - } return services; } -ScrobblerService *AudioScrobbler::ServiceByName(const QString &name) { +ScrobblerServicePtr AudioScrobbler::ServiceByName(const QString &name) { if (services_.contains(name)) return services_.value(name); return nullptr; @@ -115,45 +96,10 @@ ScrobblerService *AudioScrobbler::ServiceByName(const QString &name) { void AudioScrobbler::ReloadSettings() { - QSettings s; - s.beginGroup(ScrobblerSettingsPage::kSettingsGroup); - enabled_ = s.value("enabled", false).toBool(); - offline_ = s.value("offline", false).toBool(); - scrobble_button_ = s.value("scrobble_button", false).toBool(); - love_button_ = s.value("love_button", false).toBool(); - submit_delay_ = s.value("submit", 0).toInt(); - prefer_albumartist_ = s.value("albumartist", false).toBool(); - show_error_dialog_ = s.value("show_error_dialog", true).toBool(); - QStringList sources = s.value("sources").toStringList(); - s.endGroup(); + settings_->ReloadSettings(); - sources_.clear(); - - if (sources.isEmpty()) { - sources_ << Song::Source::Unknown - << Song::Source::LocalFile - << Song::Source::Collection - << Song::Source::CDDA - << Song::Source::Device - << Song::Source::Stream - << Song::Source::Tidal - << Song::Source::Subsonic - << Song::Source::Qobuz - << Song::Source::SomaFM - << Song::Source::RadioParadise; - } - else { - for (const QString &source : sources) { - sources_ << Song::SourceFromText(source); - } - } - - emit ScrobblingEnabledChanged(enabled_); - emit ScrobbleButtonVisibilityChanged(scrobble_button_); - emit LoveButtonVisibilityChanged(love_button_); - - QList services = services_.values(); - for (ScrobblerService *service : services) { + QList services = services_.values(); + for (ScrobblerServicePtr service : services) { service->ReloadSettings(); } @@ -161,31 +107,17 @@ void AudioScrobbler::ReloadSettings() { void AudioScrobbler::ToggleScrobbling() { - bool enabled_old_ = enabled_; - enabled_ = !enabled_; + settings_->ToggleScrobbling(); - QSettings s; - s.beginGroup(ScrobblerSettingsPage::kSettingsGroup); - s.setValue("enabled", enabled_); - s.endGroup(); - - if (enabled_ != enabled_old_) emit ScrobblingEnabledChanged(enabled_); - if (enabled_ && !offline_) { Submit(); } + if (settings_->enabled() && !settings_->offline()) { Submit(); } } void AudioScrobbler::ToggleOffline() { - bool offline_old_ = offline_; - offline_ = !offline_; + settings_->ToggleOffline(); - QSettings s; - s.beginGroup(ScrobblerSettingsPage::kSettingsGroup); - s.setValue("offline", offline_); - s.endGroup(); - - if (offline_ != offline_old_) { emit ScrobblingOfflineChanged(offline_); } - if (enabled_ && !offline_) { Submit(); } + if (settings_->enabled() && !settings_->offline()) { Submit(); } } @@ -195,13 +127,13 @@ void AudioScrobbler::ShowConfig() { void AudioScrobbler::UpdateNowPlaying(const Song &song) { - if (!sources_.contains(song.source())) return; + if (!settings_->sources().contains(song.source())) return; qLog(Debug) << "Sending now playing for song" << song.artist() << song.album() << song.title(); - QList services = GetAll(); - for (ScrobblerService *service : services) { - if (!service->IsEnabled()) continue; + QList services = GetAll(); + for (ScrobblerServicePtr service : services) { + if (!service->enabled()) continue; service->UpdateNowPlaying(song); } @@ -209,9 +141,9 @@ void AudioScrobbler::UpdateNowPlaying(const Song &song) { void AudioScrobbler::ClearPlaying() { - QList services = GetAll(); - for (ScrobblerService *service : services) { - if (!service->IsEnabled()) continue; + QList services = GetAll(); + for (ScrobblerServicePtr service : services) { + if (!service->enabled()) continue; service->ClearPlaying(); } @@ -219,13 +151,13 @@ void AudioScrobbler::ClearPlaying() { void AudioScrobbler::Scrobble(const Song &song, const qint64 scrobble_point) { - if (!sources_.contains(song.source())) return; + if (!settings_->sources().contains(song.source())) return; qLog(Debug) << "Scrobbling song" << song.artist() << song.album() << song.title() << "at" << scrobble_point; - QList services = GetAll(); - for (ScrobblerService *service : services) { - if (!service->IsEnabled()) continue; + QList services = GetAll(); + for (ScrobblerServicePtr service : services) { + if (!service->enabled()) continue; service->Scrobble(song); } @@ -233,9 +165,9 @@ void AudioScrobbler::Scrobble(const Song &song, const qint64 scrobble_point) { void AudioScrobbler::Love() { - QList services = GetAll(); - for (ScrobblerService *service : services) { - if (!service->IsEnabled() || !service->IsAuthenticated()) continue; + QList services = GetAll(); + for (ScrobblerServicePtr service : services) { + if (!service->enabled() || !service->authenticated()) continue; service->Love(); } @@ -243,9 +175,9 @@ void AudioScrobbler::Love() { void AudioScrobbler::Submit() { - QList services = GetAll(); - for (ScrobblerService *service : services) { - if (!service->IsEnabled() || !service->IsAuthenticated() || service->IsSubmitted()) continue; + QList services = GetAll(); + for (ScrobblerServicePtr service : services) { + if (!service->enabled() || !service->authenticated() || service->submitted()) continue; service->StartSubmit(); } @@ -253,9 +185,9 @@ void AudioScrobbler::Submit() { void AudioScrobbler::WriteCache() { - QList services = GetAll(); - for (ScrobblerService *service : services) { - if (!service->IsEnabled()) continue; + QList services = GetAll(); + for (ScrobblerServicePtr service : services) { + if (!service->enabled()) continue; service->WriteCache(); } diff --git a/src/scrobbler/audioscrobbler.h b/src/scrobbler/audioscrobbler.h index d83fe3c0..31a6bea3 100644 --- a/src/scrobbler/audioscrobbler.h +++ b/src/scrobbler/audioscrobbler.h @@ -22,15 +22,17 @@ #include "config.h" +#include + #include #include -#include #include #include #include -#include +#include "core/shared_ptr.h" #include "core/song.h" +#include "scrobblersettings.h" class Application; class ScrobblerService; @@ -43,29 +45,30 @@ class AudioScrobbler : public QObject { explicit AudioScrobbler(Application *app, QObject *parent = nullptr); ~AudioScrobbler(); - void AddService(ScrobblerService *service); - void RemoveService(ScrobblerService *service); - QList List() const { return services_.values(); } + void AddService(SharedPtr service); + void RemoveService(SharedPtr service); + QList> List() const { return services_.values(); } bool HasAnyServices() const { return !services_.isEmpty(); } int NextId(); - QList GetAll(); - ScrobblerService *ServiceByName(const QString &name); + QList> GetAll(); + SharedPtr ServiceByName(const QString &name); template - T *Service() { - return qobject_cast(ServiceByName(T::kName)); + SharedPtr Service() { + return std::static_pointer_cast(ServiceByName(T::kName)); } void ReloadSettings(); + SharedPtr settings() { return settings_; } - bool IsEnabled() const { return enabled_; } - bool IsOffline() const { return offline_; } - bool ScrobbleButton() const { return scrobble_button_; } - bool LoveButton() const { return love_button_; } - int SubmitDelay() const { return submit_delay_; } - bool PreferAlbumArtist() const { return prefer_albumartist_; } - bool ShowErrorDialog() const { return show_error_dialog_; } - QList sources() const { return sources_; } + bool enabled() const { return settings_->enabled(); } + bool offline() const { return settings_->offline(); } + bool scrobble_button() const { return settings_->scrobble_button(); } + bool love_button() const { return settings_->love_button(); } + int submit_delay() const { return settings_->submit_delay(); } + bool prefer_albumartist() const { return settings_->prefer_albumartist(); } + bool ShowErrorDialog() const { return settings_->show_error_dialog(); } + QList sources() const { return settings_->sources(); } void ShowConfig(); @@ -83,26 +86,11 @@ class AudioScrobbler : public QObject { signals: void ErrorMessage(const QString &error); - void ScrobblingEnabledChanged(const bool value); - void ScrobblingOfflineChanged(const bool value); - void ScrobbleButtonVisibilityChanged(const bool value); - void LoveButtonVisibilityChanged(const bool value); private: Application *app_; - - QMap services_; - QMutex mutex_; - QAtomicInt next_id_; - - bool enabled_; - bool offline_; - bool scrobble_button_; - bool love_button_; - int submit_delay_; - bool prefer_albumartist_; - bool show_error_dialog_; - QList sources_; + SharedPtr settings_; + QMap> services_; Q_DISABLE_COPY(AudioScrobbler) }; diff --git a/src/scrobbler/lastfmimport.cpp b/src/scrobbler/lastfmimport.cpp index 7cd68439..0102b52c 100644 --- a/src/scrobbler/lastfmimport.cpp +++ b/src/scrobbler/lastfmimport.cpp @@ -38,8 +38,9 @@ #include #include -#include "core/networkaccessmanager.h" #include "core/logging.h" +#include "core/shared_ptr.h" +#include "core/networkaccessmanager.h" #include "lastfmimport.h" @@ -48,7 +49,7 @@ const int LastFMImport::kRequestsDelay = 2000; -LastFMImport::LastFMImport(NetworkAccessManager *network, QObject *parent) +LastFMImport::LastFMImport(SharedPtr network, QObject *parent) : QObject(parent), network_(network), timer_flush_requests_(new QTimer(this)), diff --git a/src/scrobbler/lastfmimport.h b/src/scrobbler/lastfmimport.h index eef89163..e992e1e9 100644 --- a/src/scrobbler/lastfmimport.h +++ b/src/scrobbler/lastfmimport.h @@ -31,6 +31,8 @@ #include #include +#include "core/shared_ptr.h" + class QTimer; class QNetworkReply; @@ -40,7 +42,7 @@ class LastFMImport : public QObject { Q_OBJECT public: - explicit LastFMImport(NetworkAccessManager *network, QObject *parent = nullptr); + explicit LastFMImport(SharedPtr network, QObject *parent = nullptr); ~LastFMImport() override; void ReloadSettings(); @@ -94,7 +96,7 @@ class LastFMImport : public QObject { private: static const int kRequestsDelay; - NetworkAccessManager *network_; + SharedPtr network_; QTimer *timer_flush_requests_; QString username_; diff --git a/src/scrobbler/lastfmscrobbler.cpp b/src/scrobbler/lastfmscrobbler.cpp index 89119397..a8de1b8d 100644 --- a/src/scrobbler/lastfmscrobbler.cpp +++ b/src/scrobbler/lastfmscrobbler.cpp @@ -21,9 +21,10 @@ #include +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" -#include "audioscrobbler.h" +#include "scrobblersettings.h" #include "lastfmscrobbler.h" const char *LastFMScrobbler::kName = "Last.fm"; @@ -32,5 +33,5 @@ const char *LastFMScrobbler::kAuthUrl = "https://www.last.fm/api/auth/"; const char *LastFMScrobbler::kApiUrl = "https://ws.audioscrobbler.com/2.0/"; const char *LastFMScrobbler::kCacheFile = "lastfmscrobbler.cache"; -LastFMScrobbler::LastFMScrobbler(AudioScrobbler *scrobbler, NetworkAccessManager *network, QObject *parent) - : ScrobblingAPI20(kName, kSettingsGroup, kAuthUrl, kApiUrl, true, kCacheFile, scrobbler, network, parent) {} +LastFMScrobbler::LastFMScrobbler(SharedPtr settings, SharedPtr network, QObject *parent) + : ScrobblingAPI20(kName, kSettingsGroup, kAuthUrl, kApiUrl, true, kCacheFile, settings, network, parent) {} diff --git a/src/scrobbler/lastfmscrobbler.h b/src/scrobbler/lastfmscrobbler.h index a0195baa..7b8af1ee 100644 --- a/src/scrobbler/lastfmscrobbler.h +++ b/src/scrobbler/lastfmscrobbler.h @@ -25,6 +25,7 @@ #include #include +#include "core/shared_ptr.h" #include "scrobblingapi20.h" class AudioScrobbler; @@ -34,7 +35,7 @@ class LastFMScrobbler : public ScrobblingAPI20 { Q_OBJECT public: - explicit LastFMScrobbler(AudioScrobbler *scrobbler, NetworkAccessManager *network, QObject *parent = nullptr); + explicit LastFMScrobbler(SharedPtr settings, SharedPtr network, QObject *parent = nullptr); static const char *kName; static const char *kSettingsGroup; diff --git a/src/scrobbler/librefmscrobbler.cpp b/src/scrobbler/librefmscrobbler.cpp index 8b363300..1d8a11b2 100644 --- a/src/scrobbler/librefmscrobbler.cpp +++ b/src/scrobbler/librefmscrobbler.cpp @@ -21,9 +21,10 @@ #include +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" -#include "audioscrobbler.h" +#include "scrobblersettings.h" #include "scrobblingapi20.h" #include "librefmscrobbler.h" @@ -33,5 +34,5 @@ const char *LibreFMScrobbler::kAuthUrl = "https://www.libre.fm/api/auth/"; const char *LibreFMScrobbler::kApiUrl = "https://libre.fm/2.0/"; const char *LibreFMScrobbler::kCacheFile = "librefmscrobbler.cache"; -LibreFMScrobbler::LibreFMScrobbler(AudioScrobbler *scrobbler, NetworkAccessManager *network, QObject *parent) - : ScrobblingAPI20(kName, kSettingsGroup, kAuthUrl, kApiUrl, false, kCacheFile, scrobbler, network, parent) {} +LibreFMScrobbler::LibreFMScrobbler(SharedPtr settings, SharedPtr network, QObject *parent) + : ScrobblingAPI20(kName, kSettingsGroup, kAuthUrl, kApiUrl, false, kCacheFile, settings, network, parent) {} diff --git a/src/scrobbler/librefmscrobbler.h b/src/scrobbler/librefmscrobbler.h index 60735bef..920c8e1e 100644 --- a/src/scrobbler/librefmscrobbler.h +++ b/src/scrobbler/librefmscrobbler.h @@ -25,16 +25,17 @@ #include #include +#include "core/shared_ptr.h" #include "scrobblingapi20.h" -class AudioScrobbler; +class ScrobblerSettings; class NetworkAccessManager; class LibreFMScrobbler : public ScrobblingAPI20 { Q_OBJECT public: - explicit LibreFMScrobbler(AudioScrobbler *scrobbler, NetworkAccessManager *network, QObject *parent = nullptr); + explicit LibreFMScrobbler(SharedPtr settings, SharedPtr network, QObject *parent = nullptr); static const char *kName; static const char *kSettingsGroup; diff --git a/src/scrobbler/listenbrainzscrobbler.cpp b/src/scrobbler/listenbrainzscrobbler.cpp index 908893b8..a648a649 100644 --- a/src/scrobbler/listenbrainzscrobbler.cpp +++ b/src/scrobbler/listenbrainzscrobbler.cpp @@ -40,6 +40,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/song.h" #include "core/logging.h" @@ -47,7 +48,7 @@ #include "internet/localredirectserver.h" #include "settings/scrobblersettingspage.h" -#include "audioscrobbler.h" +#include "scrobblersettings.h" #include "scrobblerservice.h" #include "scrobblercache.h" #include "scrobblercacheitem.h" @@ -65,9 +66,9 @@ const char *ListenBrainzScrobbler::kClientSecretB64 = "Uk9GZ2hrZVEzRjNvUHlFaHFpe const char *ListenBrainzScrobbler::kCacheFile = "listenbrainzscrobbler.cache"; const int ListenBrainzScrobbler::kScrobblesPerRequest = 10; -ListenBrainzScrobbler::ListenBrainzScrobbler(AudioScrobbler *scrobbler, NetworkAccessManager *network, QObject *parent) +ListenBrainzScrobbler::ListenBrainzScrobbler(SharedPtr settings, SharedPtr network, QObject *parent) : ScrobblerService(kName, parent), - scrobbler_(scrobbler), + settings_(settings), network_(network), cache_(new ScrobblerCache(kCacheFile, this)), server_(nullptr), @@ -449,7 +450,7 @@ void ListenBrainzScrobbler::UpdateNowPlaying(const Song &song) { scrobbled_ = false; timestamp_ = QDateTime::currentDateTime().toSecsSinceEpoch(); - if (!song.is_metadata_good() || !IsAuthenticated() || scrobbler_->IsOffline()) return; + if (!song.is_metadata_good() || !authenticated() || settings_->offline()) return; QJsonObject object_listen; object_listen.insert("track_metadata", JsonTrackMetadata(ScrobbleMetadata(song))); @@ -509,7 +510,7 @@ void ListenBrainzScrobbler::Scrobble(const Song &song) { cache_->Add(song, timestamp_); - if (scrobbler_->IsOffline() || !IsAuthenticated()) return; + if (settings_->offline() || !authenticated()) return; StartSubmit(); @@ -518,14 +519,14 @@ void ListenBrainzScrobbler::Scrobble(const Song &song) { void ListenBrainzScrobbler::StartSubmit(const bool initial) { if (!submitted_ && cache_->Count() > 0) { - if (initial && scrobbler_->SubmitDelay() <= 0 && !submit_error_) { + if (initial && settings_->submit_delay() <= 0 && !submit_error_) { if (timer_submit_.isActive()) { timer_submit_.stop(); } Submit(); } else if (!timer_submit_.isActive()) { - int submit_delay = static_cast(std::max(scrobbler_->SubmitDelay(), submit_error_ ? 30 : 5) * kMsecPerSec); + int submit_delay = static_cast(std::max(settings_->submit_delay(), submit_error_ ? 30 : 5) * kMsecPerSec); timer_submit_.setInterval(submit_delay); timer_submit_.start(); } @@ -537,7 +538,7 @@ void ListenBrainzScrobbler::Submit() { qLog(Debug) << "ListenBrainz: Submitting scrobbles."; - if (!IsEnabled() || !IsAuthenticated() || scrobbler_->IsOffline()) return; + if (!enabled() || !authenticated() || settings_->offline()) return; QJsonArray array; ScrobblerCacheItemPtrList cache_items_sent; @@ -620,7 +621,7 @@ void ListenBrainzScrobbler::Love() { if (!song_playing_.is_valid() || !song_playing_.is_metadata_good()) return; - if (!IsAuthenticated()) scrobbler_->ShowConfig(); + if (!authenticated()) settings_->ShowConfig(); if (song_playing_.musicbrainz_recording_id().isEmpty()) { Error(tr("Missing MusicBrainz recording ID for %1 %2 %3").arg(song_playing_.artist()).arg(song_playing_.album()).arg(song_playing_.title())); @@ -671,7 +672,7 @@ void ListenBrainzScrobbler::Error(const QString &error, const QVariant &debug) { qLog(Error) << "ListenBrainz:" << error; if (debug.isValid()) qLog(Debug) << debug; - if (scrobbler_->ShowErrorDialog()) { + if (settings_->show_error_dialog()) { emit ErrorMessage(tr("ListenBrainz error: %1").arg(error)); } diff --git a/src/scrobbler/listenbrainzscrobbler.h b/src/scrobbler/listenbrainzscrobbler.h index 7ab084ad..19265599 100644 --- a/src/scrobbler/listenbrainzscrobbler.h +++ b/src/scrobbler/listenbrainzscrobbler.h @@ -32,6 +32,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "scrobblerservice.h" #include "scrobblercache.h" @@ -39,7 +40,7 @@ class QNetworkReply; -class AudioScrobbler; +class ScrobblerSettings; class NetworkAccessManager; class LocalRedirectServer; @@ -47,7 +48,7 @@ class ListenBrainzScrobbler : public ScrobblerService { Q_OBJECT public: - explicit ListenBrainzScrobbler(AudioScrobbler *scrobbler, NetworkAccessManager *network, QObject *parent = nullptr); + explicit ListenBrainzScrobbler(SharedPtr settings, SharedPtr network, QObject *parent = nullptr); ~ListenBrainzScrobbler() override; static const char *kName; @@ -56,10 +57,9 @@ class ListenBrainzScrobbler : public ScrobblerService { void ReloadSettings() override; void LoadSession(); - bool IsEnabled() const override { return enabled_; } - bool IsAuthenticated() const override { return !access_token_.isEmpty() && !user_token_.isEmpty(); } - bool IsSubmitted() const override { return submitted_; } - void Submitted() override { submitted_ = true; } + bool enabled() const override { return enabled_; } + bool authenticated() const override { return !access_token_.isEmpty() && !user_token_.isEmpty(); } + bool submitted() const override { return submitted_; } QString user_token() const { return user_token_; } void Authenticate(); @@ -110,8 +110,8 @@ class ListenBrainzScrobbler : public ScrobblerService { static const char *kCacheFile; static const int kScrobblesPerRequest; - AudioScrobbler *scrobbler_; - NetworkAccessManager *network_; + SharedPtr settings_; + SharedPtr network_; ScrobblerCache *cache_; LocalRedirectServer *server_; bool enabled_; diff --git a/src/scrobbler/scrobblercache.cpp b/src/scrobbler/scrobblercache.cpp index e164d420..eb8c05be 100644 --- a/src/scrobbler/scrobblercache.cpp +++ b/src/scrobbler/scrobblercache.cpp @@ -19,9 +19,9 @@ #include "config.h" -#include #include #include +#include #include #include @@ -41,6 +41,7 @@ #include "scrobblercache.h" #include "scrobblercacheitem.h" +using std::make_shared; using namespace std::chrono_literals; ScrobblerCache::ScrobblerCache(const QString &filename, QObject *parent) @@ -182,7 +183,7 @@ void ScrobblerCache::ReadCache() { metadata.musicbrainz_work_id = json_obj_track["musicbrainz_work_id"].toString(); } - ScrobblerCacheItemPtr cache_item = std::make_shared(metadata, timestamp); + ScrobblerCacheItemPtr cache_item = make_shared(metadata, timestamp); scrobbler_cache_ << cache_item; } @@ -248,7 +249,7 @@ void ScrobblerCache::WriteCache() { ScrobblerCacheItemPtr ScrobblerCache::Add(const Song &song, const quint64 timestamp) { - ScrobblerCacheItemPtr cache_item = std::make_shared(ScrobbleMetadata(song), timestamp); + ScrobblerCacheItemPtr cache_item = make_shared(ScrobbleMetadata(song), timestamp); scrobbler_cache_ << cache_item; diff --git a/src/scrobbler/scrobblercacheitem.h b/src/scrobbler/scrobblercacheitem.h index 4091d4ce..e274e0da 100644 --- a/src/scrobbler/scrobblercacheitem.h +++ b/src/scrobbler/scrobblercacheitem.h @@ -22,11 +22,10 @@ #include "config.h" -#include - #include #include +#include "core/shared_ptr.h" #include "scrobblemetadata.h" class ScrobblerCacheItem { @@ -40,7 +39,7 @@ class ScrobblerCacheItem { bool error; }; -using ScrobblerCacheItemPtr = std::shared_ptr; +using ScrobblerCacheItemPtr = SharedPtr; using ScrobblerCacheItemPtrList = QList; Q_DECLARE_METATYPE(ScrobblerCacheItemPtr) diff --git a/src/scrobbler/scrobblerservice.h b/src/scrobbler/scrobblerservice.h index ab229d52..ea1daed7 100644 --- a/src/scrobbler/scrobblerservice.h +++ b/src/scrobbler/scrobblerservice.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" class ScrobblerService : public QObject { @@ -42,8 +43,8 @@ class ScrobblerService : public QObject { virtual void ReloadSettings() = 0; - virtual bool IsEnabled() const { return false; } - virtual bool IsAuthenticated() const { return false; } + virtual bool enabled() const { return false; } + virtual bool authenticated() const { return false; } virtual void UpdateNowPlaying(const Song &song) = 0; virtual void ClearPlaying() = 0; @@ -51,8 +52,7 @@ class ScrobblerService : public QObject { virtual void Love() {} virtual void StartSubmit(const bool initial = false) = 0; - virtual void Submitted() = 0; - virtual bool IsSubmitted() const { return false; } + virtual bool submitted() const { return false; } protected: using Param = QPair; @@ -75,4 +75,6 @@ class ScrobblerService : public QObject { QString name_; }; +using ScrobblerServicePtr = SharedPtr; + #endif // SCROBBLERSERVICE_H diff --git a/src/scrobbler/scrobblersettings.cpp b/src/scrobbler/scrobblersettings.cpp new file mode 100644 index 00000000..8ed3168f --- /dev/null +++ b/src/scrobbler/scrobblersettings.cpp @@ -0,0 +1,122 @@ +/* + * Strawberry Music Player + * Copyright 2018-2023, Jonas Kvinge + * + * Strawberry is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Strawberry is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Strawberry. If not, see . + * + */ + +#include "config.h" + +#include +#include +#include + +#include "core/application.h" +#include "core/song.h" +#include "settings/settingsdialog.h" +#include "settings/scrobblersettingspage.h" +#include "scrobblersettings.h" + +ScrobblerSettings::ScrobblerSettings(Application *app, QObject *parent) + : QObject(parent), + app_(app), + enabled_(false), + offline_(false), + scrobble_button_(false), + love_button_(false), + submit_delay_(0), + prefer_albumartist_(false), + show_error_dialog_(false) { + + ReloadSettings(); + +} + +void ScrobblerSettings::ReloadSettings() { + + QSettings s; + s.beginGroup(ScrobblerSettingsPage::kSettingsGroup); + enabled_ = s.value("enabled", false).toBool(); + offline_ = s.value("offline", false).toBool(); + scrobble_button_ = s.value("scrobble_button", false).toBool(); + love_button_ = s.value("love_button", false).toBool(); + submit_delay_ = s.value("submit", 0).toInt(); + prefer_albumartist_ = s.value("albumartist", false).toBool(); + show_error_dialog_ = s.value("show_error_dialog", true).toBool(); + QStringList sources = s.value("sources").toStringList(); + s.endGroup(); + + sources_.clear(); + + if (sources.isEmpty()) { + sources_ << Song::Source::Unknown + << Song::Source::LocalFile + << Song::Source::Collection + << Song::Source::CDDA + << Song::Source::Device + << Song::Source::Stream + << Song::Source::Tidal + << Song::Source::Subsonic + << Song::Source::Qobuz + << Song::Source::SomaFM + << Song::Source::RadioParadise; + } + else { + for (const QString &source : sources) { + sources_ << Song::SourceFromText(source); + } + } + + emit ScrobblingEnabledChanged(enabled_); + emit ScrobbleButtonVisibilityChanged(scrobble_button_); + emit LoveButtonVisibilityChanged(love_button_); + +} + +void ScrobblerSettings::ToggleScrobbling() { + + bool enabled_old_ = enabled_; + enabled_ = !enabled_; + + QSettings s; + s.beginGroup(ScrobblerSettingsPage::kSettingsGroup); + s.setValue("enabled", enabled_); + s.endGroup(); + + if (enabled_ != enabled_old_) emit ScrobblingEnabledChanged(enabled_); + +} + +void ScrobblerSettings::ToggleOffline() { + + bool offline_old_ = offline_; + offline_ = !offline_; + + QSettings s; + s.beginGroup(ScrobblerSettingsPage::kSettingsGroup); + s.setValue("offline", offline_); + s.endGroup(); + + if (offline_ != offline_old_) { emit ScrobblingOfflineChanged(offline_); } + +} + +void ScrobblerSettings::ShowConfig() { + app_->OpenSettingsDialogAtPage(SettingsDialog::Page::Scrobbler); +} + +void ScrobblerSettings::ErrorReceived(const QString &error) { + emit ErrorMessage(error); +} diff --git a/src/scrobbler/scrobblersettings.h b/src/scrobbler/scrobblersettings.h new file mode 100644 index 00000000..08be56c9 --- /dev/null +++ b/src/scrobbler/scrobblersettings.h @@ -0,0 +1,81 @@ +/* + * Strawberry Music Player + * Copyright 2018-2023, Jonas Kvinge + * + * Strawberry is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Strawberry is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Strawberry. If not, see . + * + */ + +#ifndef SCROBBLERSETTINGS_H +#define SCROBBLERSETTINGS_H + +#include "config.h" + +#include +#include +#include +#include + +#include "core/song.h" + +class Application; +class Song; + +class ScrobblerSettings : public QObject { + Q_OBJECT + + public: + explicit ScrobblerSettings(Application *app, QObject *parent = nullptr); + + void ReloadSettings(); + + bool enabled() const { return enabled_; } + bool offline() const { return offline_; } + bool scrobble_button() const { return scrobble_button_; } + bool love_button() const { return love_button_; } + int submit_delay() const { return submit_delay_; } + bool prefer_albumartist() const { return prefer_albumartist_; } + bool show_error_dialog() const { return show_error_dialog_; } + QList sources() const { return sources_; } + + void ShowConfig(); + + public slots: + void ToggleScrobbling(); + void ToggleOffline(); + void ErrorReceived(const QString &error); + + signals: + void ErrorMessage(const QString &error); + void ScrobblingEnabledChanged(const bool value); + void ScrobblingOfflineChanged(const bool value); + void ScrobbleButtonVisibilityChanged(const bool value); + void LoveButtonVisibilityChanged(const bool value); + + private: + Application *app_; + + bool enabled_; + bool offline_; + bool scrobble_button_; + bool love_button_; + int submit_delay_; + bool prefer_albumartist_; + bool show_error_dialog_; + QList sources_; + + Q_DISABLE_COPY(ScrobblerSettings) +}; + +#endif // SCROBBLERSETTINGS_H diff --git a/src/scrobbler/scrobblingapi20.cpp b/src/scrobbler/scrobblingapi20.cpp index a32be1ef..7163c34d 100644 --- a/src/scrobbler/scrobblingapi20.cpp +++ b/src/scrobbler/scrobblingapi20.cpp @@ -44,6 +44,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/song.h" #include "core/logging.h" @@ -51,7 +52,7 @@ #include "internet/localredirectserver.h" #include "settings/scrobblersettingspage.h" -#include "audioscrobbler.h" +#include "scrobblersettings.h" #include "scrobblerservice.h" #include "scrobblingapi20.h" #include "scrobblercache.h" @@ -62,14 +63,14 @@ const char *ScrobblingAPI20::kApiKey = "211990b4c96782c05d1536e7219eb56e"; const char *ScrobblingAPI20::kSecret = "80fd738f49596e9709b1bf9319c444a8"; const int ScrobblingAPI20::kScrobblesPerRequest = 50; -ScrobblingAPI20::ScrobblingAPI20(const QString &name, const QString &settings_group, const QString &auth_url, const QString &api_url, const bool batch, const QString &cache_file, AudioScrobbler *scrobbler, NetworkAccessManager *network, QObject *parent) +ScrobblingAPI20::ScrobblingAPI20(const QString &name, const QString &settings_group, const QString &auth_url, const QString &api_url, const bool batch, const QString &cache_file, SharedPtr settings, SharedPtr network, QObject *parent) : ScrobblerService(name, parent), name_(name), settings_group_(settings_group), auth_url_(auth_url), api_url_(api_url), batch_(batch), - scrobbler_(scrobbler), + settings_(settings), network_(network), cache_(new ScrobblerCache(cache_file, this)), server_(nullptr), @@ -394,7 +395,7 @@ void ScrobblingAPI20::UpdateNowPlaying(const Song &song) { timestamp_ = QDateTime::currentDateTime().toSecsSinceEpoch(); scrobbled_ = false; - if (!IsAuthenticated() || !song.is_metadata_good() || scrobbler_->IsOffline()) return; + if (!authenticated() || !song.is_metadata_good() || settings_->offline()) return; ParamList params = ParamList() << Param("method", "track.updateNowPlaying") @@ -453,10 +454,10 @@ void ScrobblingAPI20::Scrobble(const Song &song) { cache_->Add(song, timestamp_); - if (scrobbler_->IsOffline()) return; + if (settings_->offline()) return; - if (!IsAuthenticated()) { - if (scrobbler_->ShowErrorDialog()) { + if (!authenticated()) { + if (settings_->show_error_dialog()) { emit ErrorMessage(tr("Scrobbler %1 is not authenticated!").arg(name_)); } return; @@ -468,14 +469,14 @@ void ScrobblingAPI20::Scrobble(const Song &song) { void ScrobblingAPI20::StartSubmit(const bool initial) { if (!submitted_ && cache_->Count() > 0) { - if (initial && (!batch_ || scrobbler_->SubmitDelay() <= 0) && !submit_error_) { + if (initial && (!batch_ || settings_->submit_delay() <= 0) && !submit_error_) { if (timer_submit_.isActive()) { timer_submit_.stop(); } Submit(); } else if (!timer_submit_.isActive()) { - int submit_delay = static_cast(std::max(scrobbler_->SubmitDelay(), submit_error_ ? 30 : 5) * kMsecPerSec); + int submit_delay = static_cast(std::max(settings_->submit_delay(), submit_error_ ? 30 : 5) * kMsecPerSec); timer_submit_.setInterval(submit_delay); timer_submit_.start(); } @@ -485,7 +486,7 @@ void ScrobblingAPI20::StartSubmit(const bool initial) { void ScrobblingAPI20::Submit() { - if (!IsEnabled() || !IsAuthenticated() || scrobbler_->IsOffline()) return; + if (!enabled() || !authenticated() || settings_->offline()) return; qLog(Debug) << name_ << "Submitting scrobbles."; @@ -823,7 +824,7 @@ void ScrobblingAPI20::Love() { if (!song_playing_.is_valid() || !song_playing_.is_metadata_good()) return; - if (!IsAuthenticated()) scrobbler_->ShowConfig(); + if (!authenticated()) settings_->ShowConfig(); qLog(Debug) << name_ << "Sending love for song" << song_playing_.artist() << song_playing_.album() << song_playing_.title(); @@ -905,7 +906,7 @@ void ScrobblingAPI20::Error(const QString &error, const QVariant &debug) { qLog(Error) << name_ << error; if (debug.isValid()) qLog(Debug) << debug; - if (scrobbler_->ShowErrorDialog()) { + if (settings_->show_error_dialog()) { emit ErrorMessage(tr("Scrobbler %1 error: %2").arg(name_, error)); } } diff --git a/src/scrobbler/scrobblingapi20.h b/src/scrobbler/scrobblingapi20.h index 78ff4c62..ea71b6ed 100644 --- a/src/scrobbler/scrobblingapi20.h +++ b/src/scrobbler/scrobblingapi20.h @@ -30,6 +30,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "scrobblerservice.h" #include "scrobblercache.h" @@ -37,7 +38,7 @@ class QNetworkReply; -class AudioScrobbler; +class ScrobblerSettings; class NetworkAccessManager; class LocalRedirectServer; @@ -45,7 +46,7 @@ class ScrobblingAPI20 : public ScrobblerService { Q_OBJECT public: - explicit ScrobblingAPI20(const QString &name, const QString &settings_group, const QString &auth_url, const QString &api_url, const bool batch, const QString &cache_file, AudioScrobbler *scrobbler, NetworkAccessManager *network, QObject *parent = nullptr); + explicit ScrobblingAPI20(const QString &name, const QString &settings_group, const QString &auth_url, const QString &api_url, const bool batch, const QString &cache_file, SharedPtr settings, SharedPtr network, QObject *parent = nullptr); ~ScrobblingAPI20() override; static const char *kApiKey; @@ -53,11 +54,10 @@ class ScrobblingAPI20 : public ScrobblerService { void ReloadSettings() override; void LoadSession(); - bool IsEnabled() const override { return enabled_; } - bool IsAuthenticated() const override { return !username_.isEmpty() && !session_key_.isEmpty(); } - bool IsSubscriber() const { return subscriber_; } - bool IsSubmitted() const override { return submitted_; } - void Submitted() override { submitted_ = true; } + bool enabled() const override { return enabled_; } + bool authenticated() const override { return !username_.isEmpty() && !session_key_.isEmpty(); } + bool subscriber() const { return subscriber_; } + bool submitted() const override { return submitted_; } QString username() const { return username_; } void Authenticate(); @@ -141,8 +141,8 @@ class ScrobblingAPI20 : public ScrobblerService { QString api_url_; bool batch_; - AudioScrobbler *scrobbler_; - NetworkAccessManager *network_; + SharedPtr settings_; + SharedPtr network_; ScrobblerCache *cache_; LocalRedirectServer *server_; diff --git a/src/scrobbler/subsonicscrobbler.cpp b/src/scrobbler/subsonicscrobbler.cpp index dce32d3b..2b07f1ad 100644 --- a/src/scrobbler/subsonicscrobbler.cpp +++ b/src/scrobbler/subsonicscrobbler.cpp @@ -20,29 +20,33 @@ #include "config.h" +#include + #include #include #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/song.h" #include "core/logging.h" #include "utilities/timeconstants.h" -#include "internet/internetservices.h" #include "settings/subsonicsettingspage.h" +#include "internet/internetservices.h" #include "subsonic/subsonicservice.h" -#include "audioscrobbler.h" +#include "scrobblersettings.h" #include "scrobblerservice.h" #include "subsonicscrobbler.h" const char *SubsonicScrobbler::kName = "Subsonic"; -SubsonicScrobbler::SubsonicScrobbler(AudioScrobbler *scrobbler, SubsonicService *service, QObject *parent) +SubsonicScrobbler::SubsonicScrobbler(SharedPtr settings, Application *app, QObject *parent) : ScrobblerService(kName, parent), - scrobbler_(scrobbler), - service_(service), + settings_(settings), + app_(app), + service_(nullptr), enabled_(false), submitted_(false) { @@ -62,6 +66,16 @@ void SubsonicScrobbler::ReloadSettings() { } +SubsonicServicePtr SubsonicScrobbler::service() { + + if (!service_) { + service_ = app_->internet_services()->Service(); + } + + return service_; + +} + void SubsonicScrobbler::UpdateNowPlaying(const Song &song) { if (song.source() != Song::Source::Subsonic) return; @@ -69,9 +83,9 @@ void SubsonicScrobbler::UpdateNowPlaying(const Song &song) { song_playing_ = song; time_ = QDateTime::currentDateTime(); - if (!song.is_metadata_good() || scrobbler_->IsOffline()) return; + if (!song.is_metadata_good() || settings_->offline() || !service()) return; - service_->Scrobble(song.song_id(), false, time_); + service()->Scrobble(song.song_id(), false, time_); } @@ -86,15 +100,15 @@ void SubsonicScrobbler::Scrobble(const Song &song) { if (song.source() != Song::Source::Subsonic || song.id() != song_playing_.id() || song.url() != song_playing_.url() || !song.is_metadata_good()) return; - if (scrobbler_->IsOffline()) return; + if (settings_->offline()) return; if (!submitted_) { submitted_ = true; - if (scrobbler_->SubmitDelay() <= 0) { + if (settings_->submit_delay() <= 0) { Submit(); } else if (!timer_submit_.isActive()) { - timer_submit_.setInterval(static_cast(scrobbler_->SubmitDelay() * kMsecPerSec)); + timer_submit_.setInterval(static_cast(settings_->submit_delay() * kMsecPerSec)); timer_submit_.start(); } } @@ -106,8 +120,8 @@ void SubsonicScrobbler::Submit() { qLog(Debug) << "SubsonicScrobbler: Submitting scrobble for" << song_playing_.artist() << song_playing_.title(); submitted_ = false; - if (scrobbler_->IsOffline()) return; + if (settings_->offline() || !service()) return; - service_->Scrobble(song_playing_.song_id(), true, time_); + service()->Scrobble(song_playing_.song_id(), true, time_); } diff --git a/src/scrobbler/subsonicscrobbler.h b/src/scrobbler/subsonicscrobbler.h index 5d3c4cf0..0c61c9e2 100644 --- a/src/scrobbler/subsonicscrobbler.h +++ b/src/scrobbler/subsonicscrobbler.h @@ -30,41 +30,44 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "scrobblerservice.h" class Application; -class AudioScrobbler; +class ScrobblerSettings; class SubsonicService; class SubsonicScrobbler : public ScrobblerService { Q_OBJECT public: - explicit SubsonicScrobbler(AudioScrobbler *scrobbler, SubsonicService *service, QObject *parent = nullptr); + explicit SubsonicScrobbler(SharedPtr settings, Application *app, QObject *parent = nullptr); static const char *kName; void ReloadSettings() override; - bool IsEnabled() const override { return enabled_; } - bool IsAuthenticated() const override { return true; } + bool enabled() const override { return enabled_; } + bool authenticated() const override { return true; } void UpdateNowPlaying(const Song &song) override; void ClearPlaying() override; void Scrobble(const Song &song) override; void StartSubmit(const bool initial = false) override { Q_UNUSED(initial) } - void Submitted() override { submitted_ = true; } - bool IsSubmitted() const override { return submitted_; } + bool submitted() const override { return submitted_; } + + SharedPtr service(); public slots: void WriteCache() override {} void Submit() override; private: - AudioScrobbler *scrobbler_; - SubsonicService *service_; + SharedPtr settings_; + Application *app_; + SharedPtr service_; bool enabled_; bool submitted_; Song song_playing_; diff --git a/src/settings/backendsettingspage.h b/src/settings/backendsettingspage.h index 5386f1fe..a04580f9 100644 --- a/src/settings/backendsettingspage.h +++ b/src/settings/backendsettingspage.h @@ -26,6 +26,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/application.h" #include "core/player.h" #include "engine/enginebase.h" @@ -51,7 +52,7 @@ class BackendSettingsPage : public SettingsPage { void Save() override; void Cancel() override; - EngineBase *engine() const { return dialog()->app()->player()->engine(); } + SharedPtr engine() const { return dialog()->app()->player()->engine(); } #ifdef HAVE_ALSA enum class ALSAPluginType { diff --git a/src/settings/globalshortcutssettingspage.cpp b/src/settings/globalshortcutssettingspage.cpp index e6b4d237..dbc38a36 100644 --- a/src/settings/globalshortcutssettingspage.cpp +++ b/src/settings/globalshortcutssettingspage.cpp @@ -54,7 +54,7 @@ GlobalShortcutsSettingsPage::GlobalShortcutsSettingsPage(SettingsDialog *dialog, : SettingsPage(dialog, parent), ui_(new Ui_GlobalShortcutsSettingsPage), initialized_(false), - grabber_(new GlobalShortcutGrabber) { + grabber_(new GlobalShortcutGrabber()) { ui_->setupUi(this); ui_->shortcut_options->setEnabled(false); diff --git a/src/settings/globalshortcutssettingspage.h b/src/settings/globalshortcutssettingspage.h index f4bbb4c3..749efcfb 100644 --- a/src/settings/globalshortcutssettingspage.h +++ b/src/settings/globalshortcutssettingspage.h @@ -24,14 +24,13 @@ #include "config.h" -#include - #include #include #include #include #include +#include "core/scoped_ptr.h" #include "globalshortcuts/globalshortcutsmanager.h" #include "settingspage.h" @@ -77,7 +76,7 @@ class GlobalShortcutsSettingsPage : public SettingsPage { Ui_GlobalShortcutsSettingsPage *ui_; bool initialized_; - std::unique_ptr grabber_; + ScopedPtr grabber_; QMap shortcuts_; diff --git a/src/settings/qobuzsettingspage.cpp b/src/settings/qobuzsettingspage.cpp index 956eb414..6cf4add7 100644 --- a/src/settings/qobuzsettingspage.cpp +++ b/src/settings/qobuzsettingspage.cpp @@ -53,10 +53,10 @@ QobuzSettingsPage::QobuzSettingsPage(SettingsDialog *dialog, QWidget *parent) QObject::connect(ui_->button_login, &QPushButton::clicked, this, &QobuzSettingsPage::LoginClicked); QObject::connect(ui_->login_state, &LoginStateWidget::LogoutClicked, this, &QobuzSettingsPage::LogoutClicked); - QObject::connect(this, &QobuzSettingsPage::Login, service_, &InternetService::LoginWithCredentials); + QObject::connect(this, &QobuzSettingsPage::Login, &*service_, &InternetService::LoginWithCredentials); - QObject::connect(service_, &InternetService::LoginFailure, this, &QobuzSettingsPage::LoginFailure); - QObject::connect(service_, &InternetService::LoginSuccess, this, &QobuzSettingsPage::LoginSuccess); + QObject::connect(&*service_, &InternetService::LoginFailure, this, &QobuzSettingsPage::LoginFailure); + QObject::connect(&*service_, &InternetService::LoginSuccess, this, &QobuzSettingsPage::LoginSuccess); dialog->installEventFilter(this); diff --git a/src/settings/qobuzsettingspage.h b/src/settings/qobuzsettingspage.h index c3cd88dd..bd0ccf63 100644 --- a/src/settings/qobuzsettingspage.h +++ b/src/settings/qobuzsettingspage.h @@ -23,6 +23,7 @@ #include #include +#include "core/shared_ptr.h" #include "settings/settingspage.h" class QEvent; @@ -55,7 +56,7 @@ class QobuzSettingsPage : public SettingsPage { private: Ui_QobuzSettingsPage *ui_; - QobuzService *service_; + SharedPtr service_; }; #endif // QOBUZSETTINGSPAGE_H diff --git a/src/settings/scrobblersettingspage.cpp b/src/settings/scrobblersettingspage.cpp index 194cf41b..43268be1 100644 --- a/src/settings/scrobblersettingspage.cpp +++ b/src/settings/scrobblersettingspage.cpp @@ -58,21 +58,21 @@ ScrobblerSettingsPage::ScrobblerSettingsPage(SettingsDialog *dialog, QWidget *pa setWindowIcon(IconLoader::Load("scrobble", true, 0, 32)); // Last.fm - QObject::connect(lastfmscrobbler_, &LastFMScrobbler::AuthenticationComplete, this, &ScrobblerSettingsPage::LastFM_AuthenticationComplete); + QObject::connect(&*lastfmscrobbler_, &LastFMScrobbler::AuthenticationComplete, this, &ScrobblerSettingsPage::LastFM_AuthenticationComplete); QObject::connect(ui_->button_lastfm_login, &QPushButton::clicked, this, &ScrobblerSettingsPage::LastFM_Login); QObject::connect(ui_->widget_lastfm_login_state, &LoginStateWidget::LoginClicked, this, &ScrobblerSettingsPage::LastFM_Login); QObject::connect(ui_->widget_lastfm_login_state, &LoginStateWidget::LogoutClicked, this, &ScrobblerSettingsPage::LastFM_Logout); ui_->widget_lastfm_login_state->AddCredentialGroup(ui_->widget_lastfm_login); // Libre.fm - QObject::connect(librefmscrobbler_, &LibreFMScrobbler::AuthenticationComplete, this, &ScrobblerSettingsPage::LibreFM_AuthenticationComplete); + QObject::connect(&*librefmscrobbler_, &LibreFMScrobbler::AuthenticationComplete, this, &ScrobblerSettingsPage::LibreFM_AuthenticationComplete); QObject::connect(ui_->button_librefm_login, &QPushButton::clicked, this, &ScrobblerSettingsPage::LibreFM_Login); QObject::connect(ui_->widget_librefm_login_state, &LoginStateWidget::LoginClicked, this, &ScrobblerSettingsPage::LibreFM_Login); QObject::connect(ui_->widget_librefm_login_state, &LoginStateWidget::LogoutClicked, this, &ScrobblerSettingsPage::LibreFM_Logout); ui_->widget_librefm_login_state->AddCredentialGroup(ui_->widget_librefm_login); // ListenBrainz - QObject::connect(listenbrainzscrobbler_, &ListenBrainzScrobbler::AuthenticationComplete, this, &ScrobblerSettingsPage::ListenBrainz_AuthenticationComplete); + QObject::connect(&*listenbrainzscrobbler_, &ListenBrainzScrobbler::AuthenticationComplete, this, &ScrobblerSettingsPage::ListenBrainz_AuthenticationComplete); QObject::connect(ui_->button_listenbrainz_login, &QPushButton::clicked, this, &ScrobblerSettingsPage::ListenBrainz_Login); QObject::connect(ui_->widget_listenbrainz_login_state, &LoginStateWidget::LoginClicked, this, &ScrobblerSettingsPage::ListenBrainz_Login); QObject::connect(ui_->widget_listenbrainz_login_state, &LoginStateWidget::LogoutClicked, this, &ScrobblerSettingsPage::ListenBrainz_Logout); @@ -91,12 +91,12 @@ void ScrobblerSettingsPage::Load() { QSettings s; if (!s.contains(kSettingsGroup)) set_changed(); - ui_->checkbox_enable->setChecked(scrobbler_->IsEnabled()); - ui_->checkbox_scrobble_button->setChecked(scrobbler_->ScrobbleButton()); - ui_->checkbox_love_button->setChecked(scrobbler_->LoveButton()); - ui_->checkbox_offline->setChecked(scrobbler_->IsOffline()); - ui_->spinbox_submit->setValue(scrobbler_->SubmitDelay()); - ui_->checkbox_albumartist->setChecked(scrobbler_->PreferAlbumArtist()); + ui_->checkbox_enable->setChecked(scrobbler_->enabled()); + ui_->checkbox_scrobble_button->setChecked(scrobbler_->scrobble_button()); + ui_->checkbox_love_button->setChecked(scrobbler_->love_button()); + ui_->checkbox_offline->setChecked(scrobbler_->offline()); + ui_->spinbox_submit->setValue(scrobbler_->submit_delay()); + ui_->checkbox_albumartist->setChecked(scrobbler_->prefer_albumartist()); ui_->checkbox_show_error_dialog->setChecked(scrobbler_->ShowErrorDialog()); ui_->checkbox_source_collection->setChecked(scrobbler_->sources().contains(Song::Source::Collection)); @@ -111,15 +111,15 @@ void ScrobblerSettingsPage::Load() { ui_->checkbox_source_radioparadise->setChecked(scrobbler_->sources().contains(Song::Source::RadioParadise)); ui_->checkbox_source_unknown->setChecked(scrobbler_->sources().contains(Song::Source::Unknown)); - ui_->checkbox_lastfm_enable->setChecked(lastfmscrobbler_->IsEnabled()); - LastFM_RefreshControls(lastfmscrobbler_->IsAuthenticated()); + ui_->checkbox_lastfm_enable->setChecked(lastfmscrobbler_->enabled()); + LastFM_RefreshControls(lastfmscrobbler_->authenticated()); - ui_->checkbox_librefm_enable->setChecked(librefmscrobbler_->IsEnabled()); - LibreFM_RefreshControls(librefmscrobbler_->IsAuthenticated()); + ui_->checkbox_librefm_enable->setChecked(librefmscrobbler_->enabled()); + LibreFM_RefreshControls(librefmscrobbler_->authenticated()); - ui_->checkbox_listenbrainz_enable->setChecked(listenbrainzscrobbler_->IsEnabled()); + ui_->checkbox_listenbrainz_enable->setChecked(listenbrainzscrobbler_->enabled()); ui_->lineedit_listenbrainz_user_token->setText(listenbrainzscrobbler_->user_token()); - ListenBrainz_RefreshControls(listenbrainzscrobbler_->IsAuthenticated()); + ListenBrainz_RefreshControls(listenbrainzscrobbler_->authenticated()); Init(ui_->layout_scrobblersettingspage->parentWidget()); diff --git a/src/settings/scrobblersettingspage.h b/src/settings/scrobblersettingspage.h index 3c91c1ed..bea54542 100644 --- a/src/settings/scrobblersettingspage.h +++ b/src/settings/scrobblersettingspage.h @@ -20,11 +20,15 @@ #ifndef SCROBBLERSETTINGSPAGE_H #define SCROBBLERSETTINGSPAGE_H +#include + #include "settingspage.h" #include #include +#include "core/shared_ptr.h" + class SettingsDialog; class Ui_ScrobblerSettingsPage; class AudioScrobbler; @@ -56,10 +60,10 @@ class ScrobblerSettingsPage : public SettingsPage { void ListenBrainz_AuthenticationComplete(const bool success, const QString &error = QString()); private: - AudioScrobbler *scrobbler_; - LastFMScrobbler *lastfmscrobbler_; - LibreFMScrobbler *librefmscrobbler_; - ListenBrainzScrobbler *listenbrainzscrobbler_; + SharedPtr scrobbler_; + SharedPtr lastfmscrobbler_; + SharedPtr librefmscrobbler_; + SharedPtr listenbrainzscrobbler_; Ui_ScrobblerSettingsPage *ui_; bool lastfm_waiting_for_auth_; diff --git a/src/settings/settingsdialog.h b/src/settings/settingsdialog.h index 0ead153f..013890dd 100644 --- a/src/settings/settingsdialog.h +++ b/src/settings/settingsdialog.h @@ -34,6 +34,7 @@ #include #include +#include "core/shared_ptr.h" #include "engine/enginebase.h" #include "osd/osdbase.h" @@ -104,8 +105,8 @@ class SettingsDialog : public QDialog { Application *app() const { return app_; } OSDBase *osd() const { return osd_; } - Player *player() const { return player_; } - EngineBase *engine() const { return engine_; } + SharedPtr player() const { return player_; } + SharedPtr engine() const { return engine_; } CollectionDirectoryModel *collection_directory_model() const { return model_; } GlobalShortcutsManager *global_shortcuts_manager() const { return manager_; } @@ -150,8 +151,8 @@ class SettingsDialog : public QDialog { QMainWindow *mainwindow_; Application *app_; OSDBase *osd_; - Player *player_; - EngineBase *engine_; + SharedPtr player_; + SharedPtr engine_; CollectionDirectoryModel *model_; GlobalShortcutsManager *manager_; diff --git a/src/settings/subsonicsettingspage.cpp b/src/settings/subsonicsettingspage.cpp index 796a0810..993988e9 100644 --- a/src/settings/subsonicsettingspage.cpp +++ b/src/settings/subsonicsettingspage.cpp @@ -50,12 +50,12 @@ SubsonicSettingsPage::SubsonicSettingsPage(SettingsDialog *dialog, QWidget *pare setWindowIcon(IconLoader::Load("subsonic", true, 0, 32)); QObject::connect(ui_->button_test, &QPushButton::clicked, this, &SubsonicSettingsPage::TestClicked); - QObject::connect(ui_->button_deletesongs, &QPushButton::clicked, service_, &SubsonicService::DeleteSongs); + QObject::connect(ui_->button_deletesongs, &QPushButton::clicked, &*service_, &SubsonicService::DeleteSongs); - QObject::connect(this, &SubsonicSettingsPage::Test, service_, &SubsonicService::SendPingWithCredentials); + QObject::connect(this, &SubsonicSettingsPage::Test, &*service_, &SubsonicService::SendPingWithCredentials); - QObject::connect(service_, &SubsonicService::TestFailure, this, &SubsonicSettingsPage::TestFailure); - QObject::connect(service_, &SubsonicService::TestSuccess, this, &SubsonicSettingsPage::TestSuccess); + QObject::connect(&*service_, &SubsonicService::TestFailure, this, &SubsonicSettingsPage::TestFailure); + QObject::connect(&*service_, &SubsonicService::TestSuccess, this, &SubsonicSettingsPage::TestSuccess); dialog->installEventFilter(this); diff --git a/src/settings/subsonicsettingspage.h b/src/settings/subsonicsettingspage.h index f2727871..de126cc8 100644 --- a/src/settings/subsonicsettingspage.h +++ b/src/settings/subsonicsettingspage.h @@ -26,6 +26,7 @@ #include #include +#include "core/shared_ptr.h" #include "settings/settingspage.h" class QEvent; @@ -62,7 +63,7 @@ class SubsonicSettingsPage : public SettingsPage { private: Ui_SubsonicSettingsPage *ui_; - SubsonicService *service_; + SharedPtr service_; }; #endif // SUBSONICSETTINGSPAGE_H diff --git a/src/settings/tidalsettingspage.cpp b/src/settings/tidalsettingspage.cpp index eae58704..882bccce 100644 --- a/src/settings/tidalsettingspage.cpp +++ b/src/settings/tidalsettingspage.cpp @@ -54,11 +54,11 @@ TidalSettingsPage::TidalSettingsPage(SettingsDialog *dialog, QWidget *parent) QObject::connect(ui_->login_state, &LoginStateWidget::LogoutClicked, this, &TidalSettingsPage::LogoutClicked); QObject::connect(ui_->oauth, &QCheckBox::toggled, this, &TidalSettingsPage::OAuthClicked); - QObject::connect(this, &TidalSettingsPage::Authorize, service_, &TidalService::StartAuthorization); - QObject::connect(this, &TidalSettingsPage::Login, service_, &TidalService::SendLoginWithCredentials); + QObject::connect(this, &TidalSettingsPage::Authorize, &*service_, &TidalService::StartAuthorization); + QObject::connect(this, &TidalSettingsPage::Login, &*service_, &TidalService::SendLoginWithCredentials); - QObject::connect(service_, &InternetService::LoginFailure, this, &TidalSettingsPage::LoginFailure); - QObject::connect(service_, &InternetService::LoginSuccess, this, &TidalSettingsPage::LoginSuccess); + QObject::connect(&*service_, &InternetService::LoginFailure, this, &TidalSettingsPage::LoginFailure); + QObject::connect(&*service_, &InternetService::LoginSuccess, this, &TidalSettingsPage::LoginSuccess); dialog->installEventFilter(this); diff --git a/src/settings/tidalsettingspage.h b/src/settings/tidalsettingspage.h index 04818d48..17f2d7da 100644 --- a/src/settings/tidalsettingspage.h +++ b/src/settings/tidalsettingspage.h @@ -25,6 +25,7 @@ #include #include +#include "core/shared_ptr.h" #include "settings/settingspage.h" class QEvent; @@ -65,7 +66,7 @@ class TidalSettingsPage : public SettingsPage { private: Ui_TidalSettingsPage *ui_; - TidalService *service_; + SharedPtr service_; }; #endif // TIDALSETTINGSPAGE_H diff --git a/src/smartplaylists/playlistgenerator.cpp b/src/smartplaylists/playlistgenerator.cpp index 41b74497..a5aee3a2 100644 --- a/src/smartplaylists/playlistgenerator.cpp +++ b/src/smartplaylists/playlistgenerator.cpp @@ -28,16 +28,18 @@ #include "playlistgenerator.h" #include "playlistquerygenerator.h" +using std::make_shared; + const int PlaylistGenerator::kDefaultLimit = 20; const int PlaylistGenerator::kDefaultDynamicHistory = 5; const int PlaylistGenerator::kDefaultDynamicFuture = 15; -PlaylistGenerator::PlaylistGenerator(QObject *parent) : QObject(parent), backend_(nullptr) {} +PlaylistGenerator::PlaylistGenerator(QObject *parent) : QObject(parent), collection_backend_(nullptr) {} PlaylistGeneratorPtr PlaylistGenerator::Create(const Type type) { Q_UNUSED(type) - return std::make_shared(); + return make_shared(); } diff --git a/src/smartplaylists/playlistgenerator.h b/src/smartplaylists/playlistgenerator.h index f4349113..a52b2bb1 100644 --- a/src/smartplaylists/playlistgenerator.h +++ b/src/smartplaylists/playlistgenerator.h @@ -29,11 +29,14 @@ #include #include +#include "core/shared_ptr.h" #include "playlist/playlistitem.h" class CollectionBackend; -class PlaylistGenerator : public QObject, public std::enable_shared_from_this { +using std::enable_shared_from_this; + +class PlaylistGenerator : public QObject, public enable_shared_from_this { Q_OBJECT public: @@ -49,12 +52,12 @@ class PlaylistGenerator : public QObject, public std::enable_shared_from_this Create(const Type type = Type::Query); + static SharedPtr Create(const Type type = Type::Query); // Should be called before Load on a new PlaylistGenerator - void set_collection(CollectionBackend *backend) { backend_ = backend; } + void set_collection_backend(SharedPtr collection_backend) { collection_backend_ = collection_backend; } void set_name(const QString &name) { name_ = name; } - CollectionBackend *collection() const { return backend_; } + SharedPtr collection() const { return collection_backend_; } QString name() const { return name_; } // Name of the subclass @@ -88,7 +91,7 @@ class PlaylistGenerator : public QObject, public std::enable_shared_from_this collection_backend_; private: QString name_; diff --git a/src/smartplaylists/playlistgenerator_fwd.h b/src/smartplaylists/playlistgenerator_fwd.h index 3a801b8b..a2b816e4 100644 --- a/src/smartplaylists/playlistgenerator_fwd.h +++ b/src/smartplaylists/playlistgenerator_fwd.h @@ -23,10 +23,10 @@ #include "config.h" -#include +#include "core/shared_ptr.h" class PlaylistGenerator; -using PlaylistGeneratorPtr = std::shared_ptr; +using PlaylistGeneratorPtr = SharedPtr; #endif // PLAYLISTGENERATOR_FWD_H diff --git a/src/smartplaylists/playlistgeneratorinserter.cpp b/src/smartplaylists/playlistgeneratorinserter.cpp index 2676ec84..6977aeaa 100644 --- a/src/smartplaylists/playlistgeneratorinserter.cpp +++ b/src/smartplaylists/playlistgeneratorinserter.cpp @@ -26,6 +26,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/taskmanager.h" #include "playlist/playlist.h" @@ -34,10 +35,10 @@ class CollectionBackend; -PlaylistGeneratorInserter::PlaylistGeneratorInserter(TaskManager *task_manager, CollectionBackend *collection, QObject *parent) +PlaylistGeneratorInserter::PlaylistGeneratorInserter(SharedPtr task_manager, SharedPtr collection_backend, QObject *parent) : QObject(parent), task_manager_(task_manager), - collection_(collection), + collection_backend_(collection_backend), task_id_(-1), destination_(nullptr), row_(0), @@ -68,7 +69,7 @@ void PlaylistGeneratorInserter::Load(Playlist *destination, const int row, const enqueue_next_ = enqueue_next; is_dynamic_ = generator->is_dynamic(); - QObject::connect(generator.get(), &PlaylistGenerator::Error, this, &PlaylistGeneratorInserter::Error); + QObject::connect(&*generator, &PlaylistGenerator::Error, this, &PlaylistGeneratorInserter::Error); QFuture future = QtConcurrent::run(PlaylistGeneratorInserter::Generate, generator, dynamic_count); QFutureWatcher *watcher = new QFutureWatcher(); diff --git a/src/smartplaylists/playlistgeneratorinserter.h b/src/smartplaylists/playlistgeneratorinserter.h index f75d52f4..c01650aa 100644 --- a/src/smartplaylists/playlistgeneratorinserter.h +++ b/src/smartplaylists/playlistgeneratorinserter.h @@ -26,6 +26,8 @@ #include #include +#include "core/shared_ptr.h" + #include "playlist/playlist.h" #include "playlist/playlistitem.h" @@ -39,7 +41,7 @@ class PlaylistGeneratorInserter : public QObject { Q_OBJECT public: - explicit PlaylistGeneratorInserter(TaskManager *task_manager, CollectionBackend *collection, QObject *parent); + explicit PlaylistGeneratorInserter(SharedPtr task_manager, SharedPtr collection_backend, QObject *parent); void Load(Playlist *destination, const int row, const bool play_now, const bool enqueue, const bool enqueue_next, PlaylistGeneratorPtr generator, const int dynamic_count = 0); @@ -54,8 +56,8 @@ class PlaylistGeneratorInserter : public QObject { void Finished(); private: - TaskManager *task_manager_; - CollectionBackend *collection_; + SharedPtr task_manager_; + SharedPtr collection_backend_; int task_id_; Playlist *destination_; diff --git a/src/smartplaylists/playlistquerygenerator.cpp b/src/smartplaylists/playlistquerygenerator.cpp index b1605d7d..0cbe2aaa 100644 --- a/src/smartplaylists/playlistquerygenerator.cpp +++ b/src/smartplaylists/playlistquerygenerator.cpp @@ -88,7 +88,7 @@ PlaylistItemPtrList PlaylistQueryGenerator::GenerateMore(const int count) { current_pos_ += search_copy.limit_; } - SongList songs = backend_->SmartPlaylistsFindSongs(search_copy); + SongList songs = collection_backend_->SmartPlaylistsFindSongs(search_copy); PlaylistItemPtrList items; items.reserve(songs.count()); for (const Song &song : songs) { diff --git a/src/smartplaylists/smartplaylistquerywizardplugin.cpp b/src/smartplaylists/smartplaylistquerywizardplugin.cpp index 10cb0d28..b4337d7c 100644 --- a/src/smartplaylists/smartplaylistquerywizardplugin.cpp +++ b/src/smartplaylists/smartplaylistquerywizardplugin.cpp @@ -20,8 +20,8 @@ #include "config.h" -#include #include +#include #include #include @@ -29,12 +29,17 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "playlistquerygenerator.h" #include "smartplaylistquerywizardplugin.h" #include "smartplaylistsearchtermwidget.h" #include "ui_smartplaylistquerysearchpage.h" #include "ui_smartplaylistquerysortpage.h" +using std::make_unique; +using std::make_shared; + class SmartPlaylistQueryWizardPlugin::SearchPage : public QWizardPage { // clazy:exclude=missing-qobject-macro friend class SmartPlaylistQueryWizardPlugin; @@ -64,7 +69,7 @@ class SmartPlaylistQueryWizardPlugin::SearchPage : public QWizardPage { // claz SmartPlaylistSearchPreview *preview_; - std::unique_ptr ui_; + ScopedPtr ui_; }; class SmartPlaylistQueryWizardPlugin::SortPage : public QWizardPage { // clazy:exclude=missing-qobject-macro @@ -80,7 +85,7 @@ class SmartPlaylistQueryWizardPlugin::SortPage : public QWizardPage { // clazy: SmartPlaylistQueryWizardPlugin *plugin_; }; -SmartPlaylistQueryWizardPlugin::SmartPlaylistQueryWizardPlugin(Application *app, CollectionBackend *collection_backend, QObject *parent) +SmartPlaylistQueryWizardPlugin::SmartPlaylistQueryWizardPlugin(Application *app, SharedPtr collection_backend, QObject *parent) : SmartPlaylistWizardPlugin(app, collection_backend, parent), search_page_(nullptr), previous_scrollarea_max_(0) {} @@ -99,7 +104,7 @@ int SmartPlaylistQueryWizardPlugin::CreatePages(QWizard *wizard, int finish_page search_page_ = new SearchPage(wizard); QWizardPage *sort_page = new SortPage(this, wizard, finish_page_id); - sort_ui_ = std::make_unique(); + sort_ui_ = make_unique(); sort_ui_->setupUi(sort_page); sort_ui_->limit_value->setValue(PlaylistGenerator::kDefaultLimit); @@ -167,7 +172,7 @@ int SmartPlaylistQueryWizardPlugin::CreatePages(QWizard *wizard, int finish_page void SmartPlaylistQueryWizardPlugin::SetGenerator(PlaylistGeneratorPtr g) { - std::shared_ptr gen = std::dynamic_pointer_cast(g); + SharedPtr gen = std::dynamic_pointer_cast(g); if (!gen) return; SmartPlaylistSearch search = gen->search(); @@ -206,7 +211,7 @@ void SmartPlaylistQueryWizardPlugin::SetGenerator(PlaylistGeneratorPtr g) { PlaylistGeneratorPtr SmartPlaylistQueryWizardPlugin::CreateGenerator() const { - std::shared_ptr gen = std::make_shared(); + SharedPtr gen = make_shared(); gen->Load(MakeSearch()); return std::static_pointer_cast(gen); diff --git a/src/smartplaylists/smartplaylistquerywizardplugin.h b/src/smartplaylists/smartplaylistquerywizardplugin.h index 426dcfa4..52bcb238 100644 --- a/src/smartplaylists/smartplaylistquerywizardplugin.h +++ b/src/smartplaylists/smartplaylistquerywizardplugin.h @@ -23,11 +23,11 @@ #include "config.h" -#include - #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "smartplaylistwizardplugin.h" #include "smartplaylistsearch.h" @@ -41,7 +41,7 @@ class SmartPlaylistQueryWizardPlugin : public SmartPlaylistWizardPlugin { Q_OBJECT public: - explicit SmartPlaylistQueryWizardPlugin(Application *app, CollectionBackend *collection_backend, QObject *parent); + explicit SmartPlaylistQueryWizardPlugin(Application *app, SharedPtr collection_backend, QObject *parent); ~SmartPlaylistQueryWizardPlugin() override; PlaylistGenerator::Type type() const override { return PlaylistGenerator::Type::Query; } @@ -71,7 +71,7 @@ class SmartPlaylistQueryWizardPlugin : public SmartPlaylistWizardPlugin { SmartPlaylistSearch MakeSearch() const; - std::unique_ptr sort_ui_; + ScopedPtr sort_ui_; SearchPage *search_page_; int previous_scrollarea_max_; diff --git a/src/smartplaylists/smartplaylistsearchpreview.cpp b/src/smartplaylists/smartplaylistsearchpreview.cpp index 33402e51..a69e79ad 100644 --- a/src/smartplaylists/smartplaylistsearchpreview.cpp +++ b/src/smartplaylists/smartplaylistsearchpreview.cpp @@ -29,16 +29,20 @@ #include #include +#include "core/shared_ptr.h" + #include "smartplaylistsearchpreview.h" #include "ui_smartplaylistsearchpreview.h" #include "playlist/playlist.h" #include "playlistquerygenerator.h" +using std::make_shared; + SmartPlaylistSearchPreview::SmartPlaylistSearchPreview(QWidget *parent) : QWidget(parent), ui_(new Ui_SmartPlaylistSearchPreview), - backend_(nullptr), + collection_backend_(nullptr), model_(nullptr) { ui_->setupUi(this); @@ -64,11 +68,11 @@ void SmartPlaylistSearchPreview::set_application(Application *app) { } -void SmartPlaylistSearchPreview::set_collection(CollectionBackend *backend) { +void SmartPlaylistSearchPreview::set_collection(SharedPtr collection_backend) { - backend_ = backend; + collection_backend_ = collection_backend; - model_ = new Playlist(nullptr, nullptr, backend_, -1, QString(), false, this); + model_ = new Playlist(nullptr, nullptr, collection_backend_, -1, QString(), false, this); ui_->tree->setModel(model_); ui_->tree->SetPlaylist(model_); ui_->tree->SetItemDelegates(); @@ -110,8 +114,8 @@ PlaylistItemPtrList DoRunSearch(PlaylistGeneratorPtr gen) { return gen->Generate void SmartPlaylistSearchPreview::RunSearch(const SmartPlaylistSearch &search) { - generator_ = std::make_shared(); - generator_->set_collection(backend_); + generator_ = make_shared(); + generator_->set_collection_backend(collection_backend_); std::dynamic_pointer_cast(generator_)->Load(search); ui_->busy_container->show(); diff --git a/src/smartplaylists/smartplaylistsearchpreview.h b/src/smartplaylists/smartplaylistsearchpreview.h index 709e07af..6202566c 100644 --- a/src/smartplaylists/smartplaylistsearchpreview.h +++ b/src/smartplaylists/smartplaylistsearchpreview.h @@ -26,6 +26,8 @@ #include #include +#include "core/shared_ptr.h" + #include "smartplaylistsearch.h" #include "playlistgenerator_fwd.h" @@ -44,7 +46,7 @@ class SmartPlaylistSearchPreview : public QWidget { ~SmartPlaylistSearchPreview() override; void set_application(Application *app); - void set_collection(CollectionBackend *backend); + void set_collection(SharedPtr backend); void Update(const SmartPlaylistSearch &search); @@ -61,7 +63,7 @@ class SmartPlaylistSearchPreview : public QWidget { Ui_SmartPlaylistSearchPreview *ui_; QList fields_; - CollectionBackend *backend_; + SharedPtr collection_backend_; Playlist *model_; SmartPlaylistSearch pending_search_; diff --git a/src/smartplaylists/smartplaylistsearchtermwidget.cpp b/src/smartplaylists/smartplaylistsearchtermwidget.cpp index 0441e4c1..711fcc26 100644 --- a/src/smartplaylists/smartplaylistsearchtermwidget.cpp +++ b/src/smartplaylists/smartplaylistsearchtermwidget.cpp @@ -34,6 +34,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/iconloader.h" #include "utilities/colorutils.h" #include "playlist/playlist.h" @@ -73,7 +74,7 @@ class SmartPlaylistSearchTermWidget::Overlay : public QWidget { // clazy:exclud const int SmartPlaylistSearchTermWidget::Overlay::kSpacing = 6; const int SmartPlaylistSearchTermWidget::Overlay::kIconSize = 22; -SmartPlaylistSearchTermWidget::SmartPlaylistSearchTermWidget(CollectionBackend *collection_backend, QWidget *parent) +SmartPlaylistSearchTermWidget::SmartPlaylistSearchTermWidget(SharedPtr collection_backend, QWidget *parent) : QWidget(parent), ui_(new Ui_SmartPlaylistSearchTermWidget), collection_backend_(collection_backend), diff --git a/src/smartplaylists/smartplaylistsearchtermwidget.h b/src/smartplaylists/smartplaylistsearchtermwidget.h index 5939bf4a..2fbea2e2 100644 --- a/src/smartplaylists/smartplaylistsearchtermwidget.h +++ b/src/smartplaylists/smartplaylistsearchtermwidget.h @@ -26,6 +26,7 @@ #include #include +#include "core/shared_ptr.h" #include "smartplaylistsearchterm.h" class QPropertyAnimation; @@ -43,7 +44,7 @@ class SmartPlaylistSearchTermWidget : public QWidget { Q_PROPERTY(float overlay_opacity READ overlay_opacity WRITE set_overlay_opacity) public: - explicit SmartPlaylistSearchTermWidget(CollectionBackend *collection_backend, QWidget *parent); + explicit SmartPlaylistSearchTermWidget(SharedPtr collection_backend, QWidget *parent); ~SmartPlaylistSearchTermWidget() override; void SetActive(const bool active); @@ -81,7 +82,7 @@ class SmartPlaylistSearchTermWidget : public QWidget { friend class Overlay; Ui_SmartPlaylistSearchTermWidget *ui_; - CollectionBackend *collection_backend_; + SharedPtr collection_backend_; Overlay *overlay_; QPropertyAnimation *animation_; diff --git a/src/smartplaylists/smartplaylistsmodel.cpp b/src/smartplaylists/smartplaylistsmodel.cpp index 78267561..2084191c 100644 --- a/src/smartplaylists/smartplaylistsmodel.cpp +++ b/src/smartplaylists/smartplaylistsmodel.cpp @@ -28,6 +28,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/iconloader.h" #include "core/simpletreemodel.h" @@ -44,9 +45,9 @@ const char *SmartPlaylistsModel::kSettingsGroup = "SerializedSmartPlaylists"; const char *SmartPlaylistsModel::kSmartPlaylistsMimeType = "application/x-strawberry-smart-playlist-generator"; const int SmartPlaylistsModel::kSmartPlaylistsVersion = 1; -SmartPlaylistsModel::SmartPlaylistsModel(CollectionBackend *backend, QObject *parent) +SmartPlaylistsModel::SmartPlaylistsModel(SharedPtr collection_backend, QObject *parent) : SimpleTreeModel(new SmartPlaylistsItem(this), parent), - backend_(backend), + collection_backend_(collection_backend), icon_(IconLoader::Load("view-media-playlist")) { root_->lazy_loaded = true; @@ -117,7 +118,7 @@ void SmartPlaylistsModel::Init() { QSettings s; s.beginGroup(kSettingsGroup); - int version = s.value(backend_->songs_table() + "_version", 0).toInt(); + int version = s.value(collection_backend_->songs_table() + "_version", 0).toInt(); // How many defaults do we have to write? int unwritten_defaults = 0; @@ -128,11 +129,11 @@ void SmartPlaylistsModel::Init() { // Save the defaults if there are any unwritten ones if (unwritten_defaults > 0) { // How many items are stored already? - int playlist_index = s.beginReadArray(backend_->songs_table()); + int playlist_index = s.beginReadArray(collection_backend_->songs_table()); s.endArray(); // Append the new ones - s.beginWriteArray(backend_->songs_table(), playlist_index + unwritten_defaults); + s.beginWriteArray(collection_backend_->songs_table(), playlist_index + unwritten_defaults); for (; version < default_smart_playlists_.count(); ++version) { for (PlaylistGeneratorPtr gen : default_smart_playlists_[version]) { // clazy:exclude=range-loop-reference SaveGenerator(&s, playlist_index++, gen); @@ -141,9 +142,9 @@ void SmartPlaylistsModel::Init() { s.endArray(); } - s.setValue(backend_->songs_table() + "_version", version); + s.setValue(collection_backend_->songs_table() + "_version", version); - const int count = s.beginReadArray(backend_->songs_table()); + const int count = s.beginReadArray(collection_backend_->songs_table()); for (int i = 0; i < count; ++i) { s.setArrayIndex(i); ItemFromSmartPlaylist(s, false); @@ -172,11 +173,11 @@ void SmartPlaylistsModel::AddGenerator(PlaylistGeneratorPtr gen) { s.beginGroup(kSettingsGroup); // Count the existing items - const int count = s.beginReadArray(backend_->songs_table()); + const int count = s.beginReadArray(collection_backend_->songs_table()); s.endArray(); // Add this one to the end - s.beginWriteArray(backend_->songs_table(), count + 1); + s.beginWriteArray(collection_backend_->songs_table(), count + 1); SaveGenerator(&s, count, gen); // Add it to the model @@ -198,10 +199,10 @@ void SmartPlaylistsModel::UpdateGenerator(const QModelIndex &idx, PlaylistGenera s.beginGroup(kSettingsGroup); // Count the existing items - const int count = s.beginReadArray(backend_->songs_table()); + const int count = s.beginReadArray(collection_backend_->songs_table()); s.endArray(); - s.beginWriteArray(backend_->songs_table(), count); + s.beginWriteArray(collection_backend_->songs_table(), count); SaveGenerator(&s, idx.row(), gen); s.endArray(); @@ -227,7 +228,7 @@ void SmartPlaylistsModel::DeleteGenerator(const QModelIndex &idx) { s.beginGroup(kSettingsGroup); // Rewrite all the items to the settings - s.beginWriteArray(backend_->songs_table(), static_cast(root_->children.count())); + s.beginWriteArray(collection_backend_->songs_table(), static_cast(root_->children.count())); int i = 0; for (SmartPlaylistsItem *item : root_->children) { s.setArrayIndex(i++); @@ -260,7 +261,7 @@ PlaylistGeneratorPtr SmartPlaylistsModel::CreateGenerator(const QModelIndex &idx if (!ret) return ret; ret->set_name(item->display_text); - ret->set_collection(backend_); + ret->set_collection_backend(collection_backend_); ret->Load(item->smart_playlist_data); return ret; diff --git a/src/smartplaylists/smartplaylistsmodel.h b/src/smartplaylists/smartplaylistsmodel.h index fd85f8c5..898426a1 100644 --- a/src/smartplaylists/smartplaylistsmodel.h +++ b/src/smartplaylists/smartplaylistsmodel.h @@ -31,6 +31,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/simpletreemodel.h" #include "smartplaylistsitem.h" #include "playlistgenerator_fwd.h" @@ -45,7 +46,7 @@ class SmartPlaylistsModel : public SimpleTreeModel { Q_OBJECT public: - explicit SmartPlaylistsModel(CollectionBackend *backend, QObject *parent = nullptr); + explicit SmartPlaylistsModel(SharedPtr backend, QObject *parent = nullptr); ~SmartPlaylistsModel(); void Init(); @@ -80,11 +81,10 @@ class SmartPlaylistsModel : public SimpleTreeModel { void ItemFromSmartPlaylist(const QSettings &s, const bool notify); private: - CollectionBackend *backend_; + SharedPtr collection_backend_; QIcon icon_; DefaultGenerators default_smart_playlists_; QList items_; - }; #endif // SMARTPLAYLISTSMODEL_H diff --git a/src/smartplaylists/smartplaylistwizard.cpp b/src/smartplaylists/smartplaylistwizard.cpp index 9525ac8f..c785ee36 100644 --- a/src/smartplaylists/smartplaylistwizard.cpp +++ b/src/smartplaylists/smartplaylistwizard.cpp @@ -27,6 +27,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/iconloader.h" #include "smartplaylistquerywizardplugin.h" @@ -58,7 +59,7 @@ class SmartPlaylistWizard::FinishPage : public QWizardPage { // clazy:exclude=m }; -SmartPlaylistWizard::SmartPlaylistWizard(Application *app, CollectionBackend *collection_backend, QWidget *parent) +SmartPlaylistWizard::SmartPlaylistWizard(Application *app, SharedPtr collection_backend, QWidget *parent) : QWizard(parent), app_(app), collection_backend_(collection_backend), diff --git a/src/smartplaylists/smartplaylistwizard.h b/src/smartplaylists/smartplaylistwizard.h index fb0ba2fb..b27667a1 100644 --- a/src/smartplaylists/smartplaylistwizard.h +++ b/src/smartplaylists/smartplaylistwizard.h @@ -25,6 +25,8 @@ #include +#include "core/shared_ptr.h" + #include "playlistgenerator_fwd.h" class Application; @@ -35,7 +37,7 @@ class SmartPlaylistWizard : public QWizard { Q_OBJECT public: - explicit SmartPlaylistWizard(Application *app, CollectionBackend *collection_backend, QWidget *parent); + explicit SmartPlaylistWizard(Application *app, SharedPtr collection_backend, QWidget *parent); ~SmartPlaylistWizard() override; void SetGenerator(PlaylistGeneratorPtr gen); @@ -55,14 +57,13 @@ class SmartPlaylistWizard : public QWizard { private: Application *app_; - CollectionBackend *collection_backend_; + SharedPtr collection_backend_; TypePage *type_page_; FinishPage *finish_page_; int finish_id_; int type_index_; QList plugins_; - }; #endif // SMARTPLAYLISTWIZARD_H diff --git a/src/smartplaylists/smartplaylistwizardplugin.cpp b/src/smartplaylists/smartplaylistwizardplugin.cpp index d9417840..50e0c6fc 100644 --- a/src/smartplaylists/smartplaylistwizardplugin.cpp +++ b/src/smartplaylists/smartplaylistwizardplugin.cpp @@ -23,9 +23,10 @@ #include #include +#include "core/shared_ptr.h" #include "smartplaylistwizardplugin.h" -SmartPlaylistWizardPlugin::SmartPlaylistWizardPlugin(Application *app, CollectionBackend *collection_backend, QObject *parent) +SmartPlaylistWizardPlugin::SmartPlaylistWizardPlugin(Application *app, SharedPtr collection_backend, QObject *parent) : QObject(parent), app_(app), collection_backend_(collection_backend), diff --git a/src/smartplaylists/smartplaylistwizardplugin.h b/src/smartplaylists/smartplaylistwizardplugin.h index 1ffe8d20..49525b4c 100644 --- a/src/smartplaylists/smartplaylistwizardplugin.h +++ b/src/smartplaylists/smartplaylistwizardplugin.h @@ -23,6 +23,7 @@ #include +#include "core/shared_ptr.h" #include "playlistgenerator.h" class QWizard; @@ -34,7 +35,7 @@ class SmartPlaylistWizardPlugin : public QObject { Q_OBJECT public: - explicit SmartPlaylistWizardPlugin(Application *app, CollectionBackend *collection_backend, QObject *parent); + explicit SmartPlaylistWizardPlugin(Application *app, SharedPtr collection_backend, QObject *parent); virtual PlaylistGenerator::Type type() const = 0; virtual QString name() const = 0; @@ -51,7 +52,7 @@ class SmartPlaylistWizardPlugin : public QObject { virtual int CreatePages(QWizard *wizard, const int finish_page_id) = 0; Application *app_; - CollectionBackend *collection_backend_; + SharedPtr collection_backend_; private: int start_page_; diff --git a/src/subsonic/subsonicbaserequest.cpp b/src/subsonic/subsonicbaserequest.cpp index a20cec65..235030b0 100644 --- a/src/subsonic/subsonicbaserequest.cpp +++ b/src/subsonic/subsonicbaserequest.cpp @@ -19,8 +19,6 @@ #include "config.h" -#include - #include #include #include diff --git a/src/subsonic/subsonicbaserequest.h b/src/subsonic/subsonicbaserequest.h index 65b58fd3..17a72e22 100644 --- a/src/subsonic/subsonicbaserequest.h +++ b/src/subsonic/subsonicbaserequest.h @@ -22,8 +22,6 @@ #include "config.h" -#include - #include #include #include @@ -36,6 +34,7 @@ #include #include +#include "core/scoped_ptr.h" #include "subsonicservice.h" #include "settings/subsonicsettingspage.h" @@ -76,8 +75,7 @@ class SubsonicBaseRequest : public QObject { private: SubsonicService *service_; - std::unique_ptr network_; - + ScopedPtr network_; }; #endif // SUBSONICBASEREQUEST_H diff --git a/src/subsonic/subsonicservice.cpp b/src/subsonic/subsonicservice.cpp index b0a01ca6..2796c22c 100644 --- a/src/subsonic/subsonicservice.cpp +++ b/src/subsonic/subsonicservice.cpp @@ -42,13 +42,13 @@ #include #include -#include "utilities/randutils.h" +#include "core/logging.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/player.h" -#include "core/logging.h" -#include "core/networkaccessmanager.h" #include "core/database.h" #include "core/song.h" +#include "utilities/randutils.h" #include "collection/collectionbackend.h" #include "collection/collectionmodel.h" #include "subsonicservice.h" @@ -57,8 +57,9 @@ #include "subsonicscrobblerequest.h" #include "settings/settingsdialog.h" #include "settings/subsonicsettingspage.h" -#include "scrobbler/audioscrobbler.h" -#include "scrobbler/subsonicscrobbler.h" + +using std::make_unique; +using std::make_shared; const Song::Source SubsonicService::kSource = Song::Source::Subsonic; const char *SubsonicService::kClientName = "Strawberry"; @@ -84,7 +85,7 @@ SubsonicService::SubsonicService(Application *app, QObject *parent) // Backend - collection_backend_ = new CollectionBackend(); + collection_backend_ = make_shared(); collection_backend_->moveToThread(app_->database()->thread()); collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Subsonic, kSongsTable, kSongsFtsTable); @@ -99,8 +100,6 @@ SubsonicService::SubsonicService(Application *app, QObject *parent) SubsonicService::ReloadSettings(); - app->scrobbler()->AddService(new SubsonicScrobbler(app->scrobbler(), this, this)); - } SubsonicService::~SubsonicService() { @@ -112,13 +111,11 @@ SubsonicService::~SubsonicService() { reply->deleteLater(); } - collection_backend_->deleteLater(); - } void SubsonicService::Exit() { - QObject::connect(collection_backend_, &CollectionBackend::ExitFinished, this, &SubsonicService::ExitFinished); + QObject::connect(&*collection_backend_, &CollectionBackend::ExitFinished, this, &SubsonicService::ExitFinished); collection_backend_->ExitAsync(); } @@ -154,7 +151,7 @@ void SubsonicService::SendPing() { void SubsonicService::SendPingWithCredentials(QUrl url, const QString &username, const QString &password, const SubsonicSettingsPage::AuthMethod auth_method, const bool redirect) { if (!network_ || !redirect) { - network_ = std::make_unique(); + network_ = make_unique(); network_->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy); ping_redirects_ = 0; } @@ -413,8 +410,8 @@ void SubsonicService::Scrobble(const QString &song_id, const bool submission, co void SubsonicService::ResetSongsRequest() { if (songs_request_) { - QObject::disconnect(songs_request_.get(), nullptr, this, nullptr); - QObject::disconnect(this, nullptr, songs_request_.get(), nullptr); + QObject::disconnect(&*songs_request_, nullptr, this, nullptr); + QObject::disconnect(this, nullptr, &*songs_request_, nullptr); songs_request_.reset(); } @@ -434,10 +431,10 @@ void SubsonicService::GetSongs() { ResetSongsRequest(); songs_request_.reset(new SubsonicRequest(this, url_handler_, app_), [](SubsonicRequest *request) { request->deleteLater(); }); - QObject::connect(songs_request_.get(), &SubsonicRequest::Results, this, &SubsonicService::SongsResultsReceived); - QObject::connect(songs_request_.get(), &SubsonicRequest::UpdateStatus, this, &SubsonicService::SongsUpdateStatus); - QObject::connect(songs_request_.get(), &SubsonicRequest::ProgressSetMaximum, this, &SubsonicService::SongsProgressSetMaximum); - QObject::connect(songs_request_.get(), &SubsonicRequest::UpdateProgress, this, &SubsonicService::SongsUpdateProgress); + QObject::connect(&*songs_request_, &SubsonicRequest::Results, this, &SubsonicService::SongsResultsReceived); + QObject::connect(&*songs_request_, &SubsonicRequest::UpdateStatus, this, &SubsonicService::SongsUpdateStatus); + QObject::connect(&*songs_request_, &SubsonicRequest::ProgressSetMaximum, this, &SubsonicService::SongsProgressSetMaximum); + QObject::connect(&*songs_request_, &SubsonicRequest::UpdateProgress, this, &SubsonicService::SongsUpdateProgress); songs_request_->GetAlbums(); diff --git a/src/subsonic/subsonicservice.h b/src/subsonic/subsonicservice.h index c7408d4b..42ebb21a 100644 --- a/src/subsonic/subsonicservice.h +++ b/src/subsonic/subsonicservice.h @@ -22,8 +22,6 @@ #include "config.h" -#include - #include #include #include @@ -38,6 +36,8 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/song.h" #include "internet/internetservice.h" #include "settings/subsonicsettingspage.h" @@ -56,7 +56,7 @@ class SubsonicService : public InternetService { Q_OBJECT public: - explicit SubsonicService(Application *app, QObject *parent); + explicit SubsonicService(Application *app, QObject *parent = nullptr); ~SubsonicService() override; static const Song::Source kSource; @@ -76,11 +76,11 @@ class SubsonicService : public InternetService { bool download_album_covers() const { return download_album_covers_; } SubsonicSettingsPage::AuthMethod auth_method() const { return auth_method_; } - CollectionBackend *collection_backend() const { return collection_backend_; } + SharedPtr collection_backend() const { return collection_backend_; } CollectionModel *collection_model() const { return collection_model_; } QSortFilterProxyModel *collection_sort_model() const { return collection_sort_model_; } - CollectionBackend *songs_collection_backend() override { return collection_backend_; } + SharedPtr songs_collection_backend() override { return collection_backend_; } CollectionModel *songs_collection_model() override { return collection_model_; } QSortFilterProxyModel *songs_collection_sort_model() override { return collection_sort_model_; } @@ -108,15 +108,15 @@ class SubsonicService : public InternetService { static const int kMaxRedirects; Application *app_; - std::unique_ptr network_; + ScopedPtr network_; SubsonicUrlHandler *url_handler_; - CollectionBackend *collection_backend_; + SharedPtr collection_backend_; CollectionModel *collection_model_; QSortFilterProxyModel *collection_sort_model_; - std::shared_ptr songs_request_; - std::shared_ptr scrobble_request_; + SharedPtr songs_request_; + SharedPtr scrobble_request_; QUrl server_url_; QString username_; @@ -130,7 +130,8 @@ class SubsonicService : public InternetService { int ping_redirects_; QList replies_; - }; +using SubsonicServicePtr = SharedPtr; + #endif // SUBSONICSERVICE_H diff --git a/src/tidal/tidalbaserequest.cpp b/src/tidal/tidalbaserequest.cpp index 8fe70eaf..9f402f6f 100644 --- a/src/tidal/tidalbaserequest.cpp +++ b/src/tidal/tidalbaserequest.cpp @@ -35,11 +35,12 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "tidalservice.h" #include "tidalbaserequest.h" -TidalBaseRequest::TidalBaseRequest(TidalService *service, NetworkAccessManager *network, QObject *parent) +TidalBaseRequest::TidalBaseRequest(TidalService *service, SharedPtr network, QObject *parent) : QObject(parent), service_(service), network_(network) {} diff --git a/src/tidal/tidalbaserequest.h b/src/tidal/tidalbaserequest.h index a3ca38f1..3f669aa9 100644 --- a/src/tidal/tidalbaserequest.h +++ b/src/tidal/tidalbaserequest.h @@ -36,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "tidalservice.h" class QNetworkReply; @@ -45,7 +46,7 @@ class TidalBaseRequest : public QObject { Q_OBJECT public: - explicit TidalBaseRequest(TidalService *service, NetworkAccessManager *network, QObject *parent = nullptr); + explicit TidalBaseRequest(TidalService *service, SharedPtr network, QObject *parent = nullptr); enum class QueryType { None, @@ -101,8 +102,7 @@ class TidalBaseRequest : public QObject { private: TidalService *service_; - NetworkAccessManager *network_; - + SharedPtr network_; }; #endif // TIDALBASEREQUEST_H diff --git a/src/tidal/tidalfavoriterequest.cpp b/src/tidal/tidalfavoriterequest.cpp index 4070e2d7..15e39b0b 100644 --- a/src/tidal/tidalfavoriterequest.cpp +++ b/src/tidal/tidalfavoriterequest.cpp @@ -32,13 +32,14 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/song.h" #include "tidalservice.h" #include "tidalbaserequest.h" #include "tidalfavoriterequest.h" -TidalFavoriteRequest::TidalFavoriteRequest(TidalService *service, NetworkAccessManager *network, QObject *parent) +TidalFavoriteRequest::TidalFavoriteRequest(TidalService *service, SharedPtr network, QObject *parent) : TidalBaseRequest(service, network, parent), service_(service), network_(network), diff --git a/src/tidal/tidalfavoriterequest.h b/src/tidal/tidalfavoriterequest.h index 2845583f..fc537748 100644 --- a/src/tidal/tidalfavoriterequest.h +++ b/src/tidal/tidalfavoriterequest.h @@ -27,9 +27,11 @@ #include #include -#include "tidalbaserequest.h" +#include "core/shared_ptr.h" #include "core/song.h" +#include "tidalbaserequest.h" + class QNetworkReply; class TidalService; class NetworkAccessManager; @@ -38,7 +40,7 @@ class TidalFavoriteRequest : public TidalBaseRequest { Q_OBJECT public: - explicit TidalFavoriteRequest(TidalService *service, NetworkAccessManager *network, QObject *parent = nullptr); + explicit TidalFavoriteRequest(TidalService *service, SharedPtr network, QObject *parent = nullptr); ~TidalFavoriteRequest() override; bool need_login() { return need_login_; } @@ -85,10 +87,9 @@ class TidalFavoriteRequest : public TidalBaseRequest { void RemoveFavoritesRequest(const FavoriteType type, const QString &id, const SongList &songs); TidalService *service_; - NetworkAccessManager *network_; + SharedPtr network_; QList replies_; bool need_login_; - }; #endif // TIDALFAVORITEREQUEST_H diff --git a/src/tidal/tidalrequest.cpp b/src/tidal/tidalrequest.cpp index d1366b05..64bb939c 100644 --- a/src/tidal/tidalrequest.cpp +++ b/src/tidal/tidalrequest.cpp @@ -35,6 +35,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/song.h" #include "core/application.h" @@ -55,7 +56,7 @@ constexpr int TidalRequest::kMaxConcurrentAlbumSongsRequests = 3; constexpr int TidalRequest::kMaxConcurrentAlbumCoverRequests = 1; constexpr int TidalRequest::kFlushRequestsDelay = 200; -TidalRequest::TidalRequest(TidalService *service, TidalUrlHandler *url_handler, Application *app, NetworkAccessManager *network, QueryType query_type, QObject *parent) +TidalRequest::TidalRequest(TidalService *service, TidalUrlHandler *url_handler, Application *app, SharedPtr network, QueryType query_type, QObject *parent) : TidalBaseRequest(service, network, parent), service_(service), url_handler_(url_handler), diff --git a/src/tidal/tidalrequest.h b/src/tidal/tidalrequest.h index db3964bf..148ddad0 100644 --- a/src/tidal/tidalrequest.h +++ b/src/tidal/tidalrequest.h @@ -37,6 +37,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "tidalbaserequest.h" @@ -52,7 +53,7 @@ class TidalRequest : public TidalBaseRequest { Q_OBJECT public: - explicit TidalRequest(TidalService *service, TidalUrlHandler *url_handler, Application *app, NetworkAccessManager *network, QueryType query_type, QObject *parent); + explicit TidalRequest(TidalService *service, TidalUrlHandler *url_handler, Application *app, SharedPtr network, QueryType query_type, QObject *parent); ~TidalRequest() override; void ReloadSettings(); @@ -183,7 +184,7 @@ class TidalRequest : public TidalBaseRequest { TidalService *service_; TidalUrlHandler *url_handler_; Application *app_; - NetworkAccessManager *network_; + SharedPtr network_; QTimer *timer_flush_requests_; const QueryType query_type_; @@ -246,7 +247,6 @@ class TidalRequest : public TidalBaseRequest { bool need_login_; QList replies_; QList album_cover_replies_; - }; #endif // TIDALREQUEST_H diff --git a/src/tidal/tidalservice.cpp b/src/tidal/tidalservice.cpp index 9c2c9b40..5bfd646b 100644 --- a/src/tidal/tidalservice.cpp +++ b/src/tidal/tidalservice.cpp @@ -19,8 +19,8 @@ #include "config.h" -#include #include +#include #include #include @@ -42,6 +42,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/application.h" #include "core/player.h" #include "core/networkaccessmanager.h" @@ -61,6 +62,9 @@ #include "settings/settingsdialog.h" #include "settings/tidalsettingspage.h" +using std::make_shared; +using namespace std::chrono_literals; + const Song::Source TidalService::kSource = Song::Source::Tidal; const char TidalService::kApiUrl[] = "https://api.tidalhifi.com/v1"; @@ -82,8 +86,6 @@ constexpr char TidalService::kArtistsSongsFtsTable[] = "tidal_artists_songs_fts" constexpr char TidalService::kAlbumsSongsFtsTable[] = "tidal_albums_songs_fts"; constexpr char TidalService::kSongsFtsTable[] = "tidal_songs_fts"; -using namespace std::chrono_literals; - TidalService::TidalService(Application *app, QObject *parent) : InternetService(Song::Source::Tidal, "Tidal", "tidal", TidalSettingsPage::kSettingsGroup, SettingsDialog::Page::Tidal, app, parent), app_(app), @@ -126,15 +128,15 @@ TidalService::TidalService(Application *app, QObject *parent) // Backends - artists_collection_backend_ = new CollectionBackend(); + artists_collection_backend_ = make_shared(); artists_collection_backend_->moveToThread(app_->database()->thread()); artists_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Tidal, kArtistsSongsTable, kArtistsSongsFtsTable); - albums_collection_backend_ = new CollectionBackend(); + albums_collection_backend_ = make_shared(); albums_collection_backend_->moveToThread(app_->database()->thread()); albums_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Tidal, kAlbumsSongsTable, kAlbumsSongsFtsTable); - songs_collection_backend_ = new CollectionBackend(); + songs_collection_backend_ = make_shared(); songs_collection_backend_->moveToThread(app_->database()->thread()); songs_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source::Tidal, kSongsTable, kSongsFtsTable); @@ -186,13 +188,13 @@ TidalService::TidalService(Application *app, QObject *parent) QObject::connect(favorite_request_, &TidalFavoriteRequest::RequestLogin, this, &TidalService::SendLogin); - QObject::connect(favorite_request_, &TidalFavoriteRequest::ArtistsAdded, artists_collection_backend_, &CollectionBackend::AddOrUpdateSongs); - QObject::connect(favorite_request_, &TidalFavoriteRequest::AlbumsAdded, albums_collection_backend_, &CollectionBackend::AddOrUpdateSongs); - QObject::connect(favorite_request_, &TidalFavoriteRequest::SongsAdded, songs_collection_backend_, &CollectionBackend::AddOrUpdateSongs); + QObject::connect(favorite_request_, &TidalFavoriteRequest::ArtistsAdded, &*artists_collection_backend_, &CollectionBackend::AddOrUpdateSongs); + QObject::connect(favorite_request_, &TidalFavoriteRequest::AlbumsAdded, &*albums_collection_backend_, &CollectionBackend::AddOrUpdateSongs); + QObject::connect(favorite_request_, &TidalFavoriteRequest::SongsAdded, &*songs_collection_backend_, &CollectionBackend::AddOrUpdateSongs); - QObject::connect(favorite_request_, &TidalFavoriteRequest::ArtistsRemoved, artists_collection_backend_, &CollectionBackend::DeleteSongs); - QObject::connect(favorite_request_, &TidalFavoriteRequest::AlbumsRemoved, albums_collection_backend_, &CollectionBackend::DeleteSongs); - QObject::connect(favorite_request_, &TidalFavoriteRequest::SongsRemoved, songs_collection_backend_, &CollectionBackend::DeleteSongs); + QObject::connect(favorite_request_, &TidalFavoriteRequest::ArtistsRemoved, &*artists_collection_backend_, &CollectionBackend::DeleteSongs); + QObject::connect(favorite_request_, &TidalFavoriteRequest::AlbumsRemoved, &*albums_collection_backend_, &CollectionBackend::DeleteSongs); + QObject::connect(favorite_request_, &TidalFavoriteRequest::SongsRemoved, &*songs_collection_backend_, &CollectionBackend::DeleteSongs); TidalService::ReloadSettings(); LoadSession(); @@ -209,23 +211,19 @@ TidalService::~TidalService() { } while (!stream_url_requests_.isEmpty()) { - std::shared_ptr stream_url_req = stream_url_requests_.take(stream_url_requests_.firstKey()); - QObject::disconnect(stream_url_req.get(), nullptr, this, nullptr); + SharedPtr stream_url_req = stream_url_requests_.take(stream_url_requests_.firstKey()); + QObject::disconnect(&*stream_url_req, nullptr, this, nullptr); } - artists_collection_backend_->deleteLater(); - albums_collection_backend_->deleteLater(); - songs_collection_backend_->deleteLater(); - } void TidalService::Exit() { - wait_for_exit_ << artists_collection_backend_ << albums_collection_backend_ << songs_collection_backend_; + wait_for_exit_ << &*artists_collection_backend_ << &*albums_collection_backend_ << &*songs_collection_backend_; - QObject::connect(artists_collection_backend_, &CollectionBackend::ExitFinished, this, &TidalService::ExitReceived); - QObject::connect(albums_collection_backend_, &CollectionBackend::ExitFinished, this, &TidalService::ExitReceived); - QObject::connect(songs_collection_backend_, &CollectionBackend::ExitFinished, this, &TidalService::ExitReceived); + QObject::connect(&*artists_collection_backend_, &CollectionBackend::ExitFinished, this, &TidalService::ExitReceived); + QObject::connect(&*albums_collection_backend_, &CollectionBackend::ExitFinished, this, &TidalService::ExitReceived); + QObject::connect(&*songs_collection_backend_, &CollectionBackend::ExitFinished, this, &TidalService::ExitReceived); artists_collection_backend_->ExitAsync(); albums_collection_backend_->ExitAsync(); @@ -729,8 +727,8 @@ void TidalService::TryLogin() { void TidalService::ResetArtistsRequest() { if (artists_request_) { - QObject::disconnect(artists_request_.get(), nullptr, this, nullptr); - QObject::disconnect(this, nullptr, artists_request_.get(), nullptr); + QObject::disconnect(&*artists_request_, nullptr, this, nullptr); + QObject::disconnect(this, nullptr, &*artists_request_, nullptr); artists_request_.reset(); } @@ -753,11 +751,11 @@ void TidalService::GetArtists() { ResetArtistsRequest(); artists_request_.reset(new TidalRequest(this, url_handler_, app_, network_, TidalBaseRequest::QueryType::Artists, this), [](TidalRequest *request) { request->deleteLater(); }); - QObject::connect(artists_request_.get(), &TidalRequest::RequestLogin, this, &TidalService::SendLogin); - QObject::connect(artists_request_.get(), &TidalRequest::Results, this, &TidalService::ArtistsResultsReceived); - QObject::connect(artists_request_.get(), &TidalRequest::UpdateStatus, this, &TidalService::ArtistsUpdateStatusReceived); - QObject::connect(artists_request_.get(), &TidalRequest::UpdateProgress, this, &TidalService::ArtistsUpdateProgressReceived); - QObject::connect(this, &TidalService::LoginComplete, artists_request_.get(), &TidalRequest::LoginComplete); + QObject::connect(&*artists_request_, &TidalRequest::RequestLogin, this, &TidalService::SendLogin); + QObject::connect(&*artists_request_, &TidalRequest::Results, this, &TidalService::ArtistsResultsReceived); + QObject::connect(&*artists_request_, &TidalRequest::UpdateStatus, this, &TidalService::ArtistsUpdateStatusReceived); + QObject::connect(&*artists_request_, &TidalRequest::UpdateProgress, this, &TidalService::ArtistsUpdateProgressReceived); + QObject::connect(this, &TidalService::LoginComplete, &*artists_request_, &TidalRequest::LoginComplete); artists_request_->Process(); @@ -784,8 +782,8 @@ void TidalService::ArtistsUpdateProgressReceived(const int id, const int progres void TidalService::ResetAlbumsRequest() { if (albums_request_) { - QObject::disconnect(albums_request_.get(), nullptr, this, nullptr); - QObject::disconnect(this, nullptr, albums_request_.get(), nullptr); + QObject::disconnect(&*albums_request_, nullptr, this, nullptr); + QObject::disconnect(this, nullptr, &*albums_request_, nullptr); albums_request_.reset(); } @@ -808,11 +806,11 @@ void TidalService::GetAlbums() { ResetAlbumsRequest(); albums_request_.reset(new TidalRequest(this, url_handler_, app_, network_, TidalBaseRequest::QueryType::Albums, this), [](TidalRequest *request) { request->deleteLater(); }); - QObject::connect(albums_request_.get(), &TidalRequest::RequestLogin, this, &TidalService::SendLogin); - QObject::connect(albums_request_.get(), &TidalRequest::Results, this, &TidalService::AlbumsResultsReceived); - QObject::connect(albums_request_.get(), &TidalRequest::UpdateStatus, this, &TidalService::AlbumsUpdateStatusReceived); - QObject::connect(albums_request_.get(), &TidalRequest::UpdateProgress, this, &TidalService::AlbumsUpdateProgressReceived); - QObject::connect(this, &TidalService::LoginComplete, albums_request_.get(), &TidalRequest::LoginComplete); + QObject::connect(&*albums_request_, &TidalRequest::RequestLogin, this, &TidalService::SendLogin); + QObject::connect(&*albums_request_, &TidalRequest::Results, this, &TidalService::AlbumsResultsReceived); + QObject::connect(&*albums_request_, &TidalRequest::UpdateStatus, this, &TidalService::AlbumsUpdateStatusReceived); + QObject::connect(&*albums_request_, &TidalRequest::UpdateProgress, this, &TidalService::AlbumsUpdateProgressReceived); + QObject::connect(this, &TidalService::LoginComplete, &*albums_request_, &TidalRequest::LoginComplete); albums_request_->Process(); @@ -839,8 +837,8 @@ void TidalService::AlbumsUpdateProgressReceived(const int id, const int progress void TidalService::ResetSongsRequest() { if (songs_request_) { - QObject::disconnect(songs_request_.get(), nullptr, this, nullptr); - QObject::disconnect(this, nullptr, songs_request_.get(), nullptr); + QObject::disconnect(&*songs_request_, nullptr, this, nullptr); + QObject::disconnect(this, nullptr, &*songs_request_, nullptr); songs_request_.reset(); } @@ -863,11 +861,11 @@ void TidalService::GetSongs() { ResetSongsRequest(); songs_request_.reset(new TidalRequest(this, url_handler_, app_, network_, TidalBaseRequest::QueryType::Songs, this), [](TidalRequest *request) { request->deleteLater(); }); - QObject::connect(songs_request_.get(), &TidalRequest::RequestLogin, this, &TidalService::SendLogin); - QObject::connect(songs_request_.get(), &TidalRequest::Results, this, &TidalService::SongsResultsReceived); - QObject::connect(songs_request_.get(), &TidalRequest::UpdateStatus, this, &TidalService::SongsUpdateStatusReceived); - QObject::connect(songs_request_.get(), &TidalRequest::UpdateProgress, this, &TidalService::SongsUpdateProgressReceived); - QObject::connect(this, &TidalService::LoginComplete, songs_request_.get(), &TidalRequest::LoginComplete); + QObject::connect(&*songs_request_, &TidalRequest::RequestLogin, this, &TidalService::SendLogin); + QObject::connect(&*songs_request_, &TidalRequest::Results, this, &TidalService::SongsResultsReceived); + QObject::connect(&*songs_request_, &TidalRequest::UpdateStatus, this, &TidalService::SongsUpdateStatusReceived); + QObject::connect(&*songs_request_, &TidalRequest::UpdateProgress, this, &TidalService::SongsUpdateProgressReceived); + QObject::connect(this, &TidalService::LoginComplete, &*songs_request_, &TidalRequest::LoginComplete); songs_request_->Process(); @@ -955,11 +953,11 @@ void TidalService::SendSearch() { search_request_.reset(new TidalRequest(this, url_handler_, app_, network_, query_type, this), [](TidalRequest *request) { request->deleteLater(); }); - QObject::connect(search_request_.get(), &TidalRequest::RequestLogin, this, &TidalService::SendLogin); - QObject::connect(search_request_.get(), &TidalRequest::Results, this, &TidalService::SearchResultsReceived); - QObject::connect(search_request_.get(), &TidalRequest::UpdateStatus, this, &TidalService::SearchUpdateStatus); - QObject::connect(search_request_.get(), &TidalRequest::UpdateProgress, this, &TidalService::SearchUpdateProgress); - QObject::connect(this, &TidalService::LoginComplete, search_request_.get(), &TidalRequest::LoginComplete); + QObject::connect(&*search_request_, &TidalRequest::RequestLogin, this, &TidalService::SendLogin); + QObject::connect(&*search_request_, &TidalRequest::Results, this, &TidalService::SearchResultsReceived); + QObject::connect(&*search_request_, &TidalRequest::UpdateStatus, this, &TidalService::SearchUpdateStatus); + QObject::connect(&*search_request_, &TidalRequest::UpdateProgress, this, &TidalService::SearchUpdateProgress); + QObject::connect(this, &TidalService::LoginComplete, &*search_request_, &TidalRequest::LoginComplete); search_request_->Search(search_id_, search_text_); search_request_->Process(); @@ -988,14 +986,14 @@ uint TidalService::GetStreamURL(const QUrl &url, QString &error) { uint id = 0; while (id == 0) id = ++next_stream_url_request_id_; - std::shared_ptr stream_url_req; + SharedPtr stream_url_req; stream_url_req.reset(new TidalStreamURLRequest(this, network_, url, id), [](TidalStreamURLRequest *request) { request->deleteLater(); }); stream_url_requests_.insert(id, stream_url_req); - QObject::connect(stream_url_req.get(), &TidalStreamURLRequest::TryLogin, this, &TidalService::TryLogin); - QObject::connect(stream_url_req.get(), &TidalStreamURLRequest::StreamURLFailure, this, &TidalService::HandleStreamURLFailure); - QObject::connect(stream_url_req.get(), &TidalStreamURLRequest::StreamURLSuccess, this, &TidalService::HandleStreamURLSuccess); - QObject::connect(this, &TidalService::LoginComplete, stream_url_req.get(), &TidalStreamURLRequest::LoginComplete); + QObject::connect(&*stream_url_req, &TidalStreamURLRequest::TryLogin, this, &TidalService::TryLogin); + QObject::connect(&*stream_url_req, &TidalStreamURLRequest::StreamURLFailure, this, &TidalService::HandleStreamURLFailure); + QObject::connect(&*stream_url_req, &TidalStreamURLRequest::StreamURLSuccess, this, &TidalService::HandleStreamURLSuccess); + QObject::connect(this, &TidalService::LoginComplete, &*stream_url_req, &TidalStreamURLRequest::LoginComplete); stream_url_req->Process(); diff --git a/src/tidal/tidalservice.h b/src/tidal/tidalservice.h index 24944a42..bd02302e 100644 --- a/src/tidal/tidalservice.h +++ b/src/tidal/tidalservice.h @@ -22,8 +22,6 @@ #include "config.h" -#include - #include #include #include @@ -38,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "internet/internetservice.h" #include "internet/internetsearchview.h" @@ -60,7 +59,7 @@ class TidalService : public InternetService { Q_OBJECT public: - explicit TidalService(Application *app, QObject *parent); + explicit TidalService(Application *app, QObject *parent = nullptr); ~TidalService() override; static const Song::Source kSource; @@ -104,9 +103,9 @@ class TidalService : public InternetService { uint GetStreamURL(const QUrl &url, QString &error); - CollectionBackend *artists_collection_backend() override { return artists_collection_backend_; } - CollectionBackend *albums_collection_backend() override { return albums_collection_backend_; } - CollectionBackend *songs_collection_backend() override { return songs_collection_backend_; } + SharedPtr artists_collection_backend() override { return artists_collection_backend_; } + SharedPtr albums_collection_backend() override { return albums_collection_backend_; } + SharedPtr songs_collection_backend() override { return songs_collection_backend_; } CollectionModel *artists_collection_model() override { return artists_collection_model_; } CollectionModel *albums_collection_model() override { return albums_collection_model_; } @@ -177,12 +176,12 @@ class TidalService : public InternetService { static const char kSongsFtsTable[]; Application *app_; - NetworkAccessManager *network_; + SharedPtr network_; TidalUrlHandler *url_handler_; - CollectionBackend *artists_collection_backend_; - CollectionBackend *albums_collection_backend_; - CollectionBackend *songs_collection_backend_; + SharedPtr artists_collection_backend_; + SharedPtr albums_collection_backend_; + SharedPtr songs_collection_backend_; CollectionModel *artists_collection_model_; CollectionModel *albums_collection_model_; @@ -196,10 +195,10 @@ class TidalService : public InternetService { QTimer *timer_login_attempt_; QTimer *timer_refresh_login_; - std::shared_ptr artists_request_; - std::shared_ptr albums_request_; - std::shared_ptr songs_request_; - std::shared_ptr search_request_; + SharedPtr artists_request_; + SharedPtr albums_request_; + SharedPtr songs_request_; + SharedPtr search_request_; TidalFavoriteRequest *favorite_request_; bool enabled_; @@ -240,13 +239,14 @@ class TidalService : public InternetService { QString code_challenge_; uint next_stream_url_request_id_; - QMap> stream_url_requests_; + QMap> stream_url_requests_; QStringList login_errors_; QList wait_for_exit_; QList replies_; - }; +using TidalServicePtr = SharedPtr; + #endif // TIDALSERVICE_H diff --git a/src/tidal/tidalstreamurlrequest.cpp b/src/tidal/tidalstreamurlrequest.cpp index f6cdd6d6..93d3388f 100644 --- a/src/tidal/tidalstreamurlrequest.cpp +++ b/src/tidal/tidalstreamurlrequest.cpp @@ -34,6 +34,7 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/networkaccessmanager.h" #include "core/song.h" #include "settings/tidalsettingspage.h" @@ -41,7 +42,7 @@ #include "tidalbaserequest.h" #include "tidalstreamurlrequest.h" -TidalStreamURLRequest::TidalStreamURLRequest(TidalService *service, NetworkAccessManager *network, const QUrl &media_url, const uint id, QObject *parent) +TidalStreamURLRequest::TidalStreamURLRequest(TidalService *service, SharedPtr network, const QUrl &media_url, const uint id, QObject *parent) : TidalBaseRequest(service, network, parent), service_(service), reply_(nullptr), diff --git a/src/tidal/tidalstreamurlrequest.h b/src/tidal/tidalstreamurlrequest.h index 13255c13..031c8a98 100644 --- a/src/tidal/tidalstreamurlrequest.h +++ b/src/tidal/tidalstreamurlrequest.h @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" #include "tidalservice.h" #include "tidalbaserequest.h" @@ -41,7 +42,7 @@ class TidalStreamURLRequest : public TidalBaseRequest { Q_OBJECT public: - explicit TidalStreamURLRequest(TidalService *service, NetworkAccessManager *network, const QUrl &media_url, const uint id, QObject *parent = nullptr); + explicit TidalStreamURLRequest(TidalService *service, SharedPtr network, const QUrl &media_url, const uint id, QObject *parent = nullptr); ~TidalStreamURLRequest() override; void GetStreamURL(); @@ -78,7 +79,6 @@ class TidalStreamURLRequest : public TidalBaseRequest { int tries_; bool need_login_; QStringList errors_; - }; #endif // TIDALSTREAMURLREQUEST_H diff --git a/src/tidal/tidalurlhandler.cpp b/src/tidal/tidalurlhandler.cpp index 9601e166..a41b5e1c 100644 --- a/src/tidal/tidalurlhandler.cpp +++ b/src/tidal/tidalurlhandler.cpp @@ -34,8 +34,8 @@ TidalUrlHandler::TidalUrlHandler(Application *app, TidalService *service) app_(app), service_(service) { - QObject::connect(service, &TidalService::StreamURLFailure, this, &TidalUrlHandler::GetStreamURLFailure); - QObject::connect(service, &TidalService::StreamURLSuccess, this, &TidalUrlHandler::GetStreamURLSuccess); + QObject::connect(&*service, &TidalService::StreamURLFailure, this, &TidalUrlHandler::GetStreamURLFailure); + QObject::connect(&*service, &TidalService::StreamURLSuccess, this, &TidalUrlHandler::GetStreamURLSuccess); } diff --git a/src/transcoder/transcoder.cpp b/src/transcoder/transcoder.cpp index 9d144425..84433f3f 100644 --- a/src/transcoder/transcoder.cpp +++ b/src/transcoder/transcoder.cpp @@ -43,9 +43,12 @@ #include #include "core/logging.h" +#include "core/shared_ptr.h" #include "core/signalchecker.h" #include "transcoder.h" +using std::make_shared; + int Transcoder::JobFinishedEvent::sEventType = -1; TranscoderPreset::TranscoderPreset(const Song::FileType filetype, const QString &name, const QString &extension, const QString &codec_mimetype, const QString &muxer_mimetype) @@ -418,7 +421,7 @@ void Transcoder::JobState::ReportError(GstMessage *msg) const { bool Transcoder::StartJob(const Job &job) { - std::shared_ptr state = std::make_shared(job, this); + SharedPtr state = make_shared(job, this); emit LogLine(tr("Starting %1").arg(QDir::toNativeSeparators(job.input))); @@ -529,7 +532,7 @@ void Transcoder::Cancel() { // Stop the running ones JobStateList::iterator it = current_jobs_.begin(); while (it != current_jobs_.end()) { - std::shared_ptr state(*it); + SharedPtr state(*it); // Remove event handlers from the gstreamer pipeline, so they don't get called after the pipeline is shutting down gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(state->pipeline_)), nullptr, nullptr, nullptr); diff --git a/src/transcoder/transcoder.h b/src/transcoder/transcoder.h index aed5bd9e..a6f85713 100644 --- a/src/transcoder/transcoder.h +++ b/src/transcoder/transcoder.h @@ -24,7 +24,6 @@ #include "config.h" -#include #include #include #include @@ -37,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/song.h" struct TranscoderPreset { @@ -140,7 +140,7 @@ class Transcoder : public QObject { static GstBusSyncReply BusCallbackSync(GstBus*, GstMessage *msg, gpointer data); private: - using JobStateList = QList>; + using JobStateList = QList>; int max_threads_; QList queued_jobs_; diff --git a/src/utilities/fileutils.cpp b/src/utilities/fileutils.cpp index a7db99fb..af044be0 100644 --- a/src/utilities/fileutils.cpp +++ b/src/utilities/fileutils.cpp @@ -29,11 +29,14 @@ #include #include "core/logging.h" +#include "core/scoped_ptr.h" #include "fileutils.h" namespace Utilities { +using std::unique_ptr; + QByteArray ReadDataFromFile(const QString &filename) { QFile file(filename); @@ -56,7 +59,7 @@ bool Copy(QIODevice *source, QIODevice *destination) { if (!destination->open(QIODevice::WriteOnly)) return false; const qint64 bytes = source->size(); - std::unique_ptr data(new char[bytes]); + unique_ptr data(new char[bytes]); qint64 pos = 0; qint64 bytes_read = 0; diff --git a/src/utilities/transliterate.cpp b/src/utilities/transliterate.cpp index 02887f76..6adb1ac6 100644 --- a/src/utilities/transliterate.cpp +++ b/src/utilities/transliterate.cpp @@ -19,7 +19,6 @@ #include "config.h" -#include #include #include @@ -32,6 +31,7 @@ #include #include +#include "core/scoped_ptr.h" #include "transliterate.h" namespace Utilities { @@ -41,7 +41,7 @@ QString Transliterate(const QString &accented_str) { #ifdef HAVE_ICU UErrorCode errorcode = U_ZERO_ERROR; - std::unique_ptr transliterator; + ScopedPtr transliterator; transliterator.reset(icu::Transliterator::createInstance("Any-Latin; Latin-ASCII;", UTRANS_FORWARD, errorcode)); if (!transliterator) return accented_str; diff --git a/src/widgets/fileview.cpp b/src/widgets/fileview.cpp index 63d5837c..1b3aeffa 100644 --- a/src/widgets/fileview.cpp +++ b/src/widgets/fileview.cpp @@ -18,6 +18,8 @@ * */ +#include + #include #include #include @@ -34,6 +36,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/deletefiles.h" #include "core/filesystemmusicstorage.h" #include "core/iconloader.h" @@ -45,6 +48,8 @@ #include "organize/organizeerrordialog.h" #include "settings/appearancesettingspage.h" +using std::make_unique; + const char *FileView::kFileFilter = "*.wav *.flac *.wv *.ogg *.oga *.opus *.spx *.ape *.mpc " "*.mp2 *.mp3 *.m4a *.mp4 *.aac *.asf *.asx *.wma " @@ -124,7 +129,7 @@ void FileView::SetPath(const QString &path) { } -void FileView::SetTaskManager(TaskManager *task_manager) { +void FileView::SetTaskManager(SharedPtr task_manager) { task_manager_ = task_manager; } @@ -268,8 +273,8 @@ void FileView::showEvent(QShowEvent *e) { model_ = new QFileSystemModel(this); if (!model_->iconProvider() || model_->iconProvider()->icon(QFileIconProvider::Folder).isNull()) { - file_icon_provider_ = std::make_unique(); - model_->setIconProvider(file_icon_provider_.get()); + file_icon_provider_ = make_unique(); + model_->setIconProvider(&*file_icon_provider_); } model_->setNameFilters(filter_list_); diff --git a/src/widgets/fileview.h b/src/widgets/fileview.h index a3111155..25ed50ab 100644 --- a/src/widgets/fileview.h +++ b/src/widgets/fileview.h @@ -21,8 +21,6 @@ #ifndef FILEVIEW_H #define FILEVIEW_H -#include - #include #include #include @@ -32,6 +30,8 @@ #include #include +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/song.h" class QMimeData; @@ -57,7 +57,7 @@ class FileView : public QWidget { void ReloadSettings(); void SetPath(const QString &path); - void SetTaskManager(TaskManager *task_manager); + void SetTaskManager(SharedPtr task_manager); protected: void showEvent(QShowEvent*) override; @@ -114,14 +114,14 @@ class FileView : public QWidget { QFileSystemModel *model_; QUndoStack *undo_stack_; - TaskManager *task_manager_; - std::shared_ptr storage_; + SharedPtr task_manager_; + SharedPtr storage_; QString lazy_set_path_; QStringList filter_list_; - std::unique_ptr file_icon_provider_; + ScopedPtr file_icon_provider_; }; #endif // FILEVIEW_H diff --git a/src/widgets/multiloadingindicator.cpp b/src/widgets/multiloadingindicator.cpp index fc9b6e5a..41bc6aa3 100644 --- a/src/widgets/multiloadingindicator.cpp +++ b/src/widgets/multiloadingindicator.cpp @@ -29,6 +29,7 @@ #include #include +#include "core/shared_ptr.h" #include "core/taskmanager.h" #include "multiloadingindicator.h" #include "widgets/busyindicator.h" @@ -56,10 +57,10 @@ QSize MultiLoadingIndicator::sizeHint() const { } -void MultiLoadingIndicator::SetTaskManager(TaskManager *task_manager) { +void MultiLoadingIndicator::SetTaskManager(SharedPtr task_manager) { task_manager_ = task_manager; - QObject::connect(task_manager_, &TaskManager::TasksChanged, this, &MultiLoadingIndicator::UpdateText); + QObject::connect(&*task_manager_, &TaskManager::TasksChanged, this, &MultiLoadingIndicator::UpdateText); } diff --git a/src/widgets/multiloadingindicator.h b/src/widgets/multiloadingindicator.h index 558b61fe..9cc06d0f 100644 --- a/src/widgets/multiloadingindicator.h +++ b/src/widgets/multiloadingindicator.h @@ -26,6 +26,8 @@ #include #include +#include "core/shared_ptr.h" + class QPaintEvent; class BusyIndicator; @@ -41,7 +43,7 @@ class MultiLoadingIndicator : public QWidget { static const int kHorizontalPadding; static const int kSpacing; - void SetTaskManager(TaskManager *task_manager); + void SetTaskManager(SharedPtr task_manager); QSize sizeHint() const override; @@ -55,7 +57,7 @@ class MultiLoadingIndicator : public QWidget { void UpdateText(); private: - TaskManager *task_manager_; + SharedPtr task_manager_; BusyIndicator *spinner_; QString text_; diff --git a/src/widgets/playingwidget.cpp b/src/widgets/playingwidget.cpp index 689fbc7a..ad8e3da9 100644 --- a/src/widgets/playingwidget.cpp +++ b/src/widgets/playingwidget.cpp @@ -44,6 +44,8 @@ #include "covermanager/albumcoverchoicecontroller.h" #include "playingwidget.h" +using std::make_unique; + const char *PlayingWidget::kSettingsGroup = "PlayingWidget"; // Space between the cover and the details in small mode @@ -545,8 +547,8 @@ void PlayingWidget::SearchCoverInProgress() { downloading_covers_ = true; // Show a spinner animation - spinner_animation_ = std::make_unique(":/pictures/spinner.gif", QByteArray(), this); - QObject::connect(spinner_animation_.get(), &QMovie::updated, this, &PlayingWidget::Update); + spinner_animation_ = make_unique(":/pictures/spinner.gif", QByteArray(), this); + QObject::connect(&*spinner_animation_, &QMovie::updated, this, &PlayingWidget::Update); spinner_animation_->start(); update(); diff --git a/src/widgets/playingwidget.h b/src/widgets/playingwidget.h index 90400351..82079121 100644 --- a/src/widgets/playingwidget.h +++ b/src/widgets/playingwidget.h @@ -22,8 +22,6 @@ #ifndef PLAYINGWIDGET_H #define PLAYINGWIDGET_H -#include - #include #include #include @@ -34,6 +32,7 @@ #include #include +#include "core/scoped_ptr.h" #include "core/song.h" class QTimeLine; @@ -137,7 +136,7 @@ class PlayingWidget : public QWidget { QImage image_original_; QPixmap pixmap_cover_; QPixmap pixmap_previous_track_; - std::unique_ptr spinner_animation_; + ScopedPtr spinner_animation_; void SetVisible(const bool visible); void CreateModeAction(const Mode mode, const QString &text, QActionGroup *group); diff --git a/tests/src/collectionbackend_test.cpp b/tests/src/collectionbackend_test.cpp index d51ab68c..dcac0d29 100644 --- a/tests/src/collectionbackend_test.cpp +++ b/tests/src/collectionbackend_test.cpp @@ -28,15 +28,16 @@ #include #include -#include "test_utils.h" - +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/song.h" #include "core/database.h" -#include "core/logging.h" #include "utilities/timeconstants.h" #include "collection/collectionbackend.h" #include "collection/collection.h" +using std::make_unique; + // clazy:excludeall=non-pod-global-static,returning-void-expression namespace { @@ -45,8 +46,8 @@ class CollectionBackendTest : public ::testing::Test { protected: void SetUp() override { database_.reset(new MemoryDatabase(nullptr)); - backend_ = std::make_unique(); - backend_->Init(database_.get(), nullptr, Song::Source::Collection, SCollection::kSongsTable, SCollection::kFtsTable, SCollection::kDirsTable, SCollection::kSubdirsTable); + backend_ = make_unique(); + backend_->Init(database_, nullptr, Song::Source::Collection, SCollection::kSongsTable, SCollection::kFtsTable, SCollection::kDirsTable, SCollection::kSubdirsTable); } static Song MakeDummySong(int directory_id) { @@ -60,8 +61,8 @@ class CollectionBackendTest : public ::testing::Test { return ret; } - std::shared_ptr database_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) - std::unique_ptr backend_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + SharedPtr database_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + ScopedPtr backend_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) }; TEST_F(CollectionBackendTest, EmptyDatabase) { @@ -77,7 +78,7 @@ TEST_F(CollectionBackendTest, EmptyDatabase) { TEST_F(CollectionBackendTest, AddDirectory) { - QSignalSpy spy(backend_.get(), &CollectionBackend::DirectoryDiscovered); + QSignalSpy spy(&*backend_, &CollectionBackend::DirectoryDiscovered); backend_->AddDirectory("/tmp"); @@ -98,7 +99,7 @@ TEST_F(CollectionBackendTest, RemoveDirectory) { dir.path = "/tmp"; backend_->AddDirectory(dir.path); - QSignalSpy spy(backend_.get(), &CollectionBackend::DirectoryDeleted); + QSignalSpy spy(&*backend_, &CollectionBackend::DirectoryDeleted); // Remove the directory again backend_->RemoveDirectory(dir); @@ -131,8 +132,8 @@ class SingleSong : public CollectionBackendTest { } void AddDummySong() { - QSignalSpy added_spy(backend_.get(), &CollectionBackend::SongsDiscovered); - QSignalSpy deleted_spy(backend_.get(), &CollectionBackend::SongsDeleted); + QSignalSpy added_spy(&*backend_, &CollectionBackend::SongsDiscovered); + QSignalSpy deleted_spy(&*backend_, &CollectionBackend::SongsDeleted); // Add the song backend_->AddOrUpdateSongs(SongList() << song_); @@ -264,8 +265,8 @@ TEST_F(SingleSong, UpdateSong) { new_song.set_id(1); new_song.set_title("A different title"); - QSignalSpy deleted_spy(backend_.get(), &CollectionBackend::SongsDeleted); - QSignalSpy added_spy(backend_.get(), &CollectionBackend::SongsDiscovered); + QSignalSpy deleted_spy(&*backend_, &CollectionBackend::SongsDeleted); + QSignalSpy added_spy(&*backend_, &CollectionBackend::SongsDiscovered); backend_->AddOrUpdateSongs(SongList() << new_song); @@ -291,7 +292,7 @@ TEST_F(SingleSong, DeleteSongs) { Song new_song(song_); new_song.set_id(1); - QSignalSpy deleted_spy(backend_.get(), &CollectionBackend::SongsDeleted); + QSignalSpy deleted_spy(&*backend_, &CollectionBackend::SongsDeleted); backend_->DeleteSongs(SongList() << new_song); @@ -324,7 +325,7 @@ TEST_F(SingleSong, MarkSongsUnavailable) { Song new_song(song_); new_song.set_id(1); - QSignalSpy deleted_spy(backend_.get(), &CollectionBackend::SongsDeleted); + QSignalSpy deleted_spy(&*backend_, &CollectionBackend::SongsDeleted); backend_->MarkSongsUnavailable(SongList() << new_song); @@ -388,7 +389,7 @@ TEST_F(TestUrls, TestUrls) { } - QSignalSpy spy(backend_.get(), &CollectionBackend::SongsDiscovered); + QSignalSpy spy(&*backend_, &CollectionBackend::SongsDiscovered); backend_->AddOrUpdateSongs(songs); if (HasFatalFailure()) return; @@ -473,7 +474,7 @@ TEST_F(UpdateSongsBySongID, UpdateSongsBySongID) { } - QSignalSpy spy(backend_.get(), &CollectionBackend::SongsDiscovered); + QSignalSpy spy(&*backend_, &CollectionBackend::SongsDiscovered); backend_->UpdateSongsBySongID(songs); @@ -511,8 +512,8 @@ TEST_F(UpdateSongsBySongID, UpdateSongsBySongID) { } { // Remove some songs - QSignalSpy spy1(backend_.get(), &CollectionBackend::SongsDiscovered); - QSignalSpy spy2(backend_.get(), &CollectionBackend::SongsDeleted); + QSignalSpy spy1(&*backend_, &CollectionBackend::SongsDiscovered); + QSignalSpy spy2(&*backend_, &CollectionBackend::SongsDeleted); SongMap songs; @@ -556,8 +557,8 @@ TEST_F(UpdateSongsBySongID, UpdateSongsBySongID) { } { // Update some songs - QSignalSpy spy1(backend_.get(), &CollectionBackend::SongsDeleted); - QSignalSpy spy2(backend_.get(), &CollectionBackend::SongsDiscovered); + QSignalSpy spy1(&*backend_, &CollectionBackend::SongsDeleted); + QSignalSpy spy2(&*backend_, &CollectionBackend::SongsDiscovered); SongMap songs; diff --git a/tests/src/collectionmodel_test.cpp b/tests/src/collectionmodel_test.cpp index 91a234ae..fd89b1b8 100644 --- a/tests/src/collectionmodel_test.cpp +++ b/tests/src/collectionmodel_test.cpp @@ -31,14 +31,17 @@ #include #include -#include "test_utils.h" - #include "core/logging.h" +#include "core/scoped_ptr.h" +#include "core/shared_ptr.h" #include "core/database.h" #include "collection/collectionmodel.h" #include "collection/collectionbackend.h" #include "collection/collection.h" +using std::make_unique; +using std::make_shared; + // clazy:excludeall=non-pod-global-static,returning-void-expression namespace { @@ -49,15 +52,15 @@ class CollectionModelTest : public ::testing::Test { protected: void SetUp() override { - database_ = std::make_shared(nullptr); - backend_ = std::make_unique(); - backend_->Init(database_.get(), nullptr, Song::Source::Collection, SCollection::kSongsTable, SCollection::kFtsTable, SCollection::kDirsTable, SCollection::kSubdirsTable); - model_ = std::make_unique(backend_.get(), nullptr); + database_ = make_shared(nullptr); + backend_ = make_shared(); + backend_->Init(database_, nullptr, Song::Source::Collection, SCollection::kSongsTable, SCollection::kFtsTable, SCollection::kDirsTable, SCollection::kSubdirsTable); + model_ = make_unique(backend_, nullptr); added_dir_ = false; - model_sorted_ = std::make_unique(); - model_sorted_->setSourceModel(model_.get()); + model_sorted_ = make_unique(); + model_sorted_->setSourceModel(&*model_); model_sorted_->setSortRole(CollectionModel::Role_SortText); model_sorted_->setDynamicSortFilter(true); model_sorted_->sort(0); @@ -88,10 +91,10 @@ class CollectionModelTest : public ::testing::Test { return AddSong(song); } - std::shared_ptr database_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) - std::unique_ptr backend_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) - std::unique_ptr model_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) - std::unique_ptr model_sorted_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + SharedPtr database_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + SharedPtr backend_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + ScopedPtr model_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + ScopedPtr model_sorted_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) bool added_dir_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) }; @@ -258,9 +261,9 @@ TEST_F(CollectionModelTest, RemoveSongsLazyLoaded) { ASSERT_EQ(3, model_->rowCount(album_index)); // Remove the first two songs - QSignalSpy spy_preremove(model_.get(), &CollectionModel::rowsAboutToBeRemoved); - QSignalSpy spy_remove(model_.get(), &CollectionModel::rowsRemoved); - QSignalSpy spy_reset(model_.get(), &CollectionModel::modelReset); + QSignalSpy spy_preremove(&*model_, &CollectionModel::rowsAboutToBeRemoved); + QSignalSpy spy_remove(&*model_, &CollectionModel::rowsRemoved); + QSignalSpy spy_reset(&*model_, &CollectionModel::modelReset); backend_->DeleteSongs(SongList() << one << two); @@ -283,9 +286,9 @@ TEST_F(CollectionModelTest, RemoveSongsNotLazyLoaded) { model_->Init(false); // Remove the first two songs - QSignalSpy spy_preremove(model_.get(), &CollectionModel::rowsAboutToBeRemoved); - QSignalSpy spy_remove(model_.get(), &CollectionModel::rowsRemoved); - QSignalSpy spy_reset(model_.get(), &CollectionModel::modelReset); + QSignalSpy spy_preremove(&*model_, &CollectionModel::rowsAboutToBeRemoved); + QSignalSpy spy_remove(&*model_, &CollectionModel::rowsRemoved); + QSignalSpy spy_reset(&*model_, &CollectionModel::modelReset); backend_->DeleteSongs(SongList() << one << two); @@ -548,28 +551,28 @@ TEST_F(CollectionModelTest, TestContainerNodes) { qLog(Debug) << "Testing collection model grouping: " << f << s << t; - std::unique_ptr database1; - std::unique_ptr database2; - std::unique_ptr database3; - std::unique_ptr backend1; - std::unique_ptr backend2; - std::unique_ptr backend3; - std::unique_ptr model1; - std::unique_ptr model2; - std::unique_ptr model3; + ScopedPtr database1; + ScopedPtr database2; + ScopedPtr database3; + ScopedPtr backend1; + ScopedPtr backend2; + ScopedPtr backend3; + ScopedPtr model1; + ScopedPtr model2; + ScopedPtr model3; - database1 = std::make_unique(nullptr); - database2 = std::make_unique(nullptr); - database3 = std::make_unique(nullptr); - backend1 = std::make_unique(); - backend2= std::make_unique(); - backend3 = std::make_unique(); + database1 = make_unique(nullptr); + database2 = make_unique(nullptr); + database3 = make_unique(nullptr); + backend1 = make_unique(); + backend2= make_unique(); + backend3 = make_unique(); backend1->Init(database1.get(), Song::Source::Collection, SCollection::kSongsTable, SCollection::kFtsTable, SCollection::kDirsTable, SCollection::kSubdirsTable); backend2->Init(database2.get(), Song::Source::Collection, SCollection::kSongsTable, SCollection::kFtsTable, SCollection::kDirsTable, SCollection::kSubdirsTable); backend3->Init(database3.get(), Song::Source::Collection, SCollection::kSongsTable, SCollection::kFtsTable, SCollection::kDirsTable, SCollection::kSubdirsTable); - model1 = std::make_unique(backend1.get(), nullptr); - model2 = std::make_unique(backend2.get(), nullptr); - model3 = std::make_unique(backend3.get(), nullptr); + model1 = make_unique(backend1.get(), nullptr); + model2 = make_unique(backend2.get(), nullptr); + model3 = make_unique(backend3.get(), nullptr); backend1->AddDirectory("/mnt/music"); backend2->AddDirectory("/mnt/music"); diff --git a/tests/src/songplaylistitem_test.cpp b/tests/src/songplaylistitem_test.cpp index bbcdfa97..68a6fd54 100644 --- a/tests/src/songplaylistitem_test.cpp +++ b/tests/src/songplaylistitem_test.cpp @@ -30,8 +30,11 @@ #include "test_utils.h" +#include "core/scoped_ptr.h" #include "playlist/songplaylistitem.h" +using std::make_unique; + // clazy:excludeall=non-pod-global-static namespace { @@ -49,7 +52,7 @@ class SongPlaylistItemTest : public ::testing::TestWithParam { song_.Init("Title", "Artist", "Album", 123); song_.set_url(QUrl::fromLocalFile(absolute_file_name_)); - item_ = std::make_unique(song_); + item_ = make_unique(song_); if (!absolute_file_name_.startsWith('/')) absolute_file_name_.prepend('/'); @@ -58,7 +61,7 @@ class SongPlaylistItemTest : public ::testing::TestWithParam { Song song_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) QTemporaryFile temp_file_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) QString absolute_file_name_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) - std::unique_ptr item_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + ScopedPtr item_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) }; INSTANTIATE_TEST_SUITE_P(RealFiles, SongPlaylistItemTest, testing::Values( // clazy:exclude=function-args-by-value,clazy-non-pod-global-static