From bebd781fdffdd617b8b1810549a164bdb77f55c9 Mon Sep 17 00:00:00 2001 From: John Maguire Date: Fri, 7 Feb 2014 16:34:20 +0100 Subject: [PATCH] Reformat all non-3rd-party C/C++/Objective-C++. Command line: find src ext -regex '.*\.\(h\|cpp\|mm\)' -exec clang-format -i -style='{BasedOnStyle: Google, DerivePointerBinding: false}' {} \; --- ext/clementine-spotifyblob/main.cpp | 1 - ext/clementine-spotifyblob/mediapipeline.cpp | 68 +- ext/clementine-spotifyblob/mediapipeline.h | 8 +- .../spotify_utilities.cpp | 10 +- .../spotify_utilities.h | 1 - .../spotify_utilities.mm | 20 +- ext/clementine-spotifyblob/spotifyclient.cpp | 298 ++-- ext/clementine-spotifyblob/spotifyclient.h | 79 +- ext/clementine-spotifyblob/spotifykey.h | 18 +- ext/clementine-tagreader/main.cpp | 8 +- ext/clementine-tagreader/tagreaderworker.cpp | 47 +- ext/clementine-tagreader/tagreaderworker.h | 8 +- ext/libclementine-common/core/closure.cpp | 43 +- ext/libclementine-common/core/closure.h | 134 +- ext/libclementine-common/core/concurrentrun.h | 72 +- ext/libclementine-common/core/logging.cpp | 87 +- ext/libclementine-common/core/logging.h | 51 +- .../core/messagehandler.cpp | 15 +- .../core/messagehandler.h | 59 +- .../core/messagereply.cpp | 12 +- ext/libclementine-common/core/messagereply.h | 19 +- ext/libclementine-common/core/override.h | 7 +- ext/libclementine-common/core/waitforsignal.h | 2 +- ext/libclementine-common/core/workerpool.cpp | 7 +- ext/libclementine-common/core/workerpool.h | 105 +- ext/libclementine-tagreader/cloudstream.cpp | 42 +- ext/libclementine-tagreader/cloudstream.h | 13 +- ext/libclementine-tagreader/fmpsparser.cpp | 31 +- ext/libclementine-tagreader/fmpsparser.h | 6 +- ext/libclementine-tagreader/tagreader.cpp | 508 +++--- ext/libclementine-tagreader/tagreader.h | 63 +- src/analyzers/analyzer.cpp | 6 +- src/analyzers/analyzerbase.cpp | 271 ++-- src/analyzers/analyzerbase.h | 84 +- src/analyzers/analyzercontainer.cpp | 71 +- src/analyzers/analyzercontainer.h | 24 +- src/analyzers/baranalyzer.cpp | 235 ++- src/analyzers/baranalyzer.h | 71 +- src/analyzers/blockanalyzer.cpp | 637 ++++---- src/analyzers/blockanalyzer.h | 68 +- src/analyzers/boomanalyzer.cpp | 205 ++- src/analyzers/boomanalyzer.h | 41 +- src/analyzers/glanalyzer.cpp | 473 +++--- src/analyzers/glanalyzer.h | 24 +- src/analyzers/glanalyzer2.cpp | 506 +++--- src/analyzers/glanalyzer2.h | 50 +- src/analyzers/glanalyzer3.cpp | 693 ++++----- src/analyzers/glanalyzer3.h | 89 +- src/analyzers/nyancatanalyzer.cpp | 94 +- src/analyzers/nyancatanalyzer.h | 16 +- src/analyzers/sonogram.cpp | 93 +- src/analyzers/sonogram.h | 23 +- src/analyzers/turbine.cpp | 97 +- src/analyzers/turbine.h | 11 +- src/core/appearance.cpp | 15 +- src/core/appearance.h | 34 +- src/core/application.cpp | 81 +- src/core/application.h | 16 +- src/core/backgroundstreams.cpp | 24 +- src/core/backgroundstreams.h | 2 +- src/core/boundfuturewatcher.h | 7 +- src/core/cachedlist.h | 24 +- src/core/commandlineoptions.cpp | 264 ++-- src/core/commandlineoptions.h | 10 +- src/core/crashreporting.cpp | 88 +- src/core/crashreporting.h | 24 +- src/core/database.cpp | 194 ++- src/core/database.h | 52 +- src/core/deletefiles.cpp | 23 +- src/core/deletefiles.h | 8 +- src/core/fht.cpp | 331 ++-- src/core/fht.h | 145 +- src/core/filesystemmusicstorage.cpp | 12 +- src/core/filesystemmusicstorage.h | 6 +- src/core/filesystemwatcherinterface.cpp | 6 +- src/core/filesystemwatcherinterface.h | 2 +- src/core/globalshortcutbackend.cpp | 9 +- src/core/globalshortcutbackend.h | 6 +- src/core/globalshortcuts.cpp | 86 +- src/core/globalshortcuts.h | 16 +- src/core/gnomeglobalshortcutbackend.cpp | 64 +- src/core/gnomeglobalshortcutbackend.h | 10 +- src/core/mac_delegate.h | 27 +- src/core/mac_utilities.h | 1 - src/core/macfslistener.h | 13 +- src/core/macglobalshortcutbackend.h | 8 +- src/core/mergedproxymodel.cpp | 266 ++-- src/core/mergedproxymodel.h | 49 +- src/core/metatypes.cpp | 18 +- src/core/mimedata.h | 34 +- src/core/modelfuturewatcher.h | 8 +- src/core/mpris.cpp | 9 +- src/core/mpris.h | 8 +- src/core/mpris1.cpp | 168 +- src/core/mpris1.h | 79 +- src/core/mpris2.cpp | 315 ++-- src/core/mpris2.h | 102 +- src/core/mpris_common.h | 25 +- src/core/multisortfilterproxy.cpp | 45 +- src/core/multisortfilterproxy.h | 8 +- src/core/musicstorage.cpp | 4 +- src/core/musicstorage.h | 18 +- src/core/network.cpp | 60 +- src/core/network.h | 37 +- src/core/networkproxyfactory.cpp | 75 +- src/core/networkproxyfactory.h | 12 +- src/core/organise.cpp | 87 +- src/core/organise.h | 23 +- src/core/organiseformat.cpp | 152 +- src/core/organiseformat.h | 5 +- src/core/player.cpp | 321 ++-- src/core/player.h | 20 +- src/core/potranslator.h | 5 +- src/core/qhash_qurl.h | 6 +- src/core/qtfslistener.cpp | 9 +- src/core/qtfslistener.h | 1 - src/core/qxtglobalshortcutbackend.cpp | 12 +- src/core/qxtglobalshortcutbackend.h | 8 +- src/core/scoped_cftyperef.h | 28 +- src/core/scoped_nsautorelease_pool.h | 3 +- src/core/scoped_nsobject.h | 39 +- src/core/scopedgobject.h | 23 +- src/core/scopedtransaction.cpp | 4 +- src/core/scopedtransaction.h | 2 +- src/core/settingsprovider.cpp | 23 +- src/core/settingsprovider.h | 2 +- src/core/signalchecker.cpp | 11 +- src/core/signalchecker.h | 16 +- src/core/simpletreeitem.h | 58 +- src/core/simpletreemodel.h | 28 +- src/core/song.cpp | 657 ++++---- src/core/song.h | 29 +- src/core/songloader.cpp | 210 +-- src/core/songloader.h | 26 +- src/core/stylesheetloader.cpp | 25 +- src/core/stylesheetloader.h | 2 +- src/core/tagreaderclient.cpp | 36 +- src/core/tagreaderclient.h | 16 +- src/core/taskmanager.cpp | 34 +- src/core/taskmanager.h | 14 +- src/core/timeconstants.h | 10 +- src/core/ubuntuunityhack.cpp | 23 +- src/core/ubuntuunityhack.h | 8 +- src/core/urlhandler.cpp | 20 +- src/core/urlhandler.h | 17 +- src/core/utilities.cpp | 289 ++-- src/core/utilities.h | 190 ++- src/covers/albumcoverexporter.cpp | 14 +- src/covers/albumcoverexporter.h | 2 +- src/covers/albumcoverfetcher.cpp | 42 +- src/covers/albumcoverfetcher.h | 13 +- src/covers/albumcoverfetchersearch.cpp | 74 +- src/covers/albumcoverfetchersearch.h | 6 +- src/covers/albumcoverloader.cpp | 82 +- src/covers/albumcoverloader.h | 28 +- src/covers/albumcoverloaderoptions.cpp | 7 +- src/covers/albumcoverloaderoptions.h | 15 +- src/covers/amazoncoverprovider.cpp | 101 +- src/covers/amazoncoverprovider.h | 11 +- src/covers/coverexportrunnable.cpp | 103 +- src/covers/coverexportrunnable.h | 4 +- src/covers/coverprovider.cpp | 5 +- src/covers/coverprovider.h | 9 +- src/covers/coverproviders.cpp | 11 +- src/covers/coverproviders.h | 8 +- src/covers/coversearchstatistics.cpp | 21 +- src/covers/coversearchstatistics.h | 4 +- src/covers/coversearchstatisticsdialog.cpp | 56 +- src/covers/coversearchstatisticsdialog.h | 8 +- src/covers/currentartloader.cpp | 19 +- src/covers/currentartloader.h | 13 +- src/covers/discogscoverprovider.cpp | 51 +- src/covers/discogscoverprovider.h | 18 +- src/covers/kittenloader.cpp | 18 +- src/covers/lastfmcoverprovider.cpp | 15 +- src/covers/lastfmcoverprovider.h | 8 +- src/covers/musicbrainzcoverprovider.cpp | 53 +- src/devices/cddadevice.cpp | 110 +- src/devices/cddadevice.h | 18 +- src/devices/cddalister.cpp | 27 +- src/devices/cddalister.h | 8 +- src/devices/connecteddevice.cpp | 41 +- src/devices/connecteddevice.h | 21 +- src/devices/devicedatabasebackend.cpp | 50 +- src/devices/devicedatabasebackend.h | 14 +- src/devices/devicekitlister.cpp | 122 +- src/devices/devicekitlister.h | 26 +- src/devices/devicelister.cpp | 15 +- src/devices/devicelister.h | 15 +- src/devices/devicemanager.cpp | 299 ++-- src/devices/devicemanager.h | 48 +- src/devices/deviceproperties.cpp | 125 +- src/devices/deviceproperties.h | 12 +- src/devices/devicestatefiltermodel.cpp | 19 +- src/devices/devicestatefiltermodel.h | 14 +- src/devices/deviceview.cpp | 182 ++- src/devices/deviceview.h | 22 +- src/devices/deviceviewcontainer.cpp | 20 +- src/devices/deviceviewcontainer.h | 14 +- src/devices/filesystemdevice.cpp | 56 +- src/devices/filesystemdevice.h | 18 +- src/devices/giolister.cpp | 177 +-- src/devices/giolister.h | 44 +- src/devices/gpoddevice.cpp | 60 +- src/devices/gpoddevice.h | 20 +- src/devices/gpodloader.cpp | 34 +- src/devices/gpodloader.h | 8 +- src/devices/macdevicelister.h | 12 +- src/devices/mtpconnection.cpp | 27 +- src/devices/mtpconnection.h | 6 +- src/devices/mtpdevice.cpp | 88 +- src/devices/mtpdevice.h | 21 +- src/devices/mtploader.cpp | 24 +- src/devices/mtploader.h | 14 +- src/engines/bufferconsumer.h | 4 +- src/engines/engine_fwd.h | 50 +- src/engines/enginebase.cpp | 55 +- src/engines/enginebase.h | 33 +- src/engines/gstelementdeleter.cpp | 5 +- src/engines/gstelementdeleter.h | 6 +- src/engines/gstengine.cpp | 289 ++-- src/engines/gstengine.h | 30 +- src/engines/gstenginepipeline.cpp | 348 +++-- src/engines/gstenginepipeline.h | 15 +- .../digitallyimportedsearchprovider.cpp | 16 +- .../digitallyimportedsearchprovider.h | 8 +- src/globalsearch/globalsearch.cpp | 105 +- src/globalsearch/globalsearch.h | 17 +- src/globalsearch/globalsearchitemdelegate.cpp | 17 +- src/globalsearch/globalsearchitemdelegate.h | 12 +- src/globalsearch/globalsearchmodel.cpp | 155 +- src/globalsearch/globalsearchmodel.h | 47 +- src/globalsearch/globalsearchsettingspage.cpp | 68 +- src/globalsearch/globalsearchsettingspage.h | 12 +- src/globalsearch/globalsearchsortmodel.cpp | 40 +- src/globalsearch/globalsearchsortmodel.h | 6 +- src/globalsearch/globalsearchview.cpp | 217 +-- src/globalsearch/globalsearchview.h | 24 +- .../groovesharksearchprovider.cpp | 43 +- src/globalsearch/icecastsearchprovider.cpp | 15 +- src/globalsearch/icecastsearchprovider.h | 10 +- src/globalsearch/lastfmsearchprovider.cpp | 28 +- src/globalsearch/lastfmsearchprovider.h | 11 +- src/globalsearch/librarysearchprovider.cpp | 19 +- src/globalsearch/librarysearchprovider.h | 11 +- src/globalsearch/savedradiosearchprovider.cpp | 13 +- src/globalsearch/savedradiosearchprovider.h | 11 +- src/globalsearch/searchprovider.cpp | 44 +- src/globalsearch/searchprovider.h | 32 +- .../searchproviderstatuswidget.cpp | 73 +- src/globalsearch/searchproviderstatuswidget.h | 19 +- src/globalsearch/simplesearchprovider.cpp | 48 +- src/globalsearch/simplesearchprovider.h | 14 +- src/globalsearch/somafmsearchprovider.cpp | 16 +- src/globalsearch/somafmsearchprovider.h | 11 +- src/globalsearch/soundcloudsearchprovider.cpp | 24 +- src/globalsearch/spotifysearchprovider.cpp | 45 +- src/globalsearch/spotifysearchprovider.h | 11 +- src/globalsearch/suggestionwidget.cpp | 50 +- src/globalsearch/suggestionwidget.h | 16 +- src/globalsearch/urlsearchprovider.cpp | 4 +- src/globalsearch/urlsearchprovider.h | 6 +- src/internet/boxservice.cpp | 98 +- src/internet/boxservice.h | 6 +- src/internet/boxsettingspage.cpp | 11 +- src/internet/boxsettingspage.h | 8 +- src/internet/boxurlhandler.cpp | 4 +- src/internet/cloudfileservice.cpp | 92 +- src/internet/cloudfileservice.h | 26 +- src/internet/digitallyimportedclient.cpp | 81 +- src/internet/digitallyimportedclient.h | 16 +- src/internet/digitallyimportedservicebase.cpp | 170 +- src/internet/digitallyimportedservicebase.h | 39 +- .../digitallyimportedsettingspage.cpp | 41 +- src/internet/digitallyimportedsettingspage.h | 10 +- src/internet/digitallyimportedurlhandler.cpp | 12 +- src/internet/digitallyimportedurlhandler.h | 10 +- src/internet/dropboxauthenticator.cpp | 43 +- src/internet/dropboxauthenticator.h | 7 +- src/internet/dropboxservice.cpp | 54 +- src/internet/dropboxservice.h | 2 +- src/internet/dropboxsettingspage.cpp | 24 +- src/internet/dropboxsettingspage.h | 8 +- src/internet/dropboxurlhandler.cpp | 8 +- src/internet/fixlastfm.cpp | 5 +- src/internet/fixlastfm.h | 8 +- src/internet/geolocator.cpp | 19 +- src/internet/geolocator.h | 2 +- src/internet/googledriveclient.cpp | 77 +- src/internet/googledriveclient.h | 33 +- src/internet/googledriveservice.cpp | 64 +- src/internet/googledriveservice.h | 12 +- src/internet/googledrivesettingspage.cpp | 18 +- src/internet/googledrivesettingspage.h | 8 +- src/internet/googledriveurlhandler.cpp | 9 +- src/internet/groovesharkradio.cpp | 25 +- src/internet/groovesharkradio.h | 8 +- src/internet/groovesharkservice.cpp | 716 +++++---- src/internet/groovesharkservice.h | 58 +- src/internet/groovesharksettingspage.cpp | 40 +- src/internet/groovesharksettingspage.h | 10 +- src/internet/groovesharkurlhandler.cpp | 32 +- src/internet/groovesharkurlhandler.h | 8 +- src/internet/icecastbackend.cpp | 57 +- src/internet/icecastbackend.h | 12 +- src/internet/icecastfilterwidget.cpp | 37 +- src/internet/icecastfilterwidget.h | 15 +- src/internet/icecastitem.h | 15 +- src/internet/icecastmodel.cpp | 71 +- src/internet/icecastmodel.h | 21 +- src/internet/icecastservice.cpp | 108 +- src/internet/icecastservice.h | 14 +- src/internet/internetmimedata.h | 7 +- src/internet/internetmodel.cpp | 110 +- src/internet/internetmodel.h | 18 +- src/internet/internetplaylistitem.cpp | 39 +- src/internet/internetplaylistitem.h | 2 +- src/internet/internetservice.cpp | 60 +- src/internet/internetservice.h | 29 +- src/internet/internetsongmimedata.h | 7 +- src/internet/internetview.cpp | 17 +- src/internet/internetview.h | 8 +- src/internet/internetviewcontainer.cpp | 64 +- src/internet/internetviewcontainer.h | 2 +- src/internet/jamendodynamicplaylist.cpp | 70 +- src/internet/jamendodynamicplaylist.h | 23 +- src/internet/jamendoplaylistitem.cpp | 11 +- src/internet/jamendoplaylistitem.h | 4 +- src/internet/jamendoservice.cpp | 170 +- src/internet/jamendoservice.h | 9 +- src/internet/lastfmcompat.cpp | 62 +- src/internet/lastfmcompat.h | 45 +- src/internet/lastfmservice.cpp | 428 ++--- src/internet/lastfmservice.h | 22 +- src/internet/lastfmsettingspage.cpp | 40 +- src/internet/lastfmsettingspage.h | 8 +- src/internet/lastfmstationdialog.cpp | 12 +- src/internet/lastfmstationdialog.h | 8 +- src/internet/lastfmurlhandler.cpp | 10 +- src/internet/lastfmurlhandler.h | 7 +- src/internet/localredirectserver.cpp | 19 +- src/internet/localredirectserver.h | 3 +- src/internet/magnatunedownloaddialog.cpp | 89 +- src/internet/magnatunedownloaddialog.h | 16 +- src/internet/magnatuneplaylistitem.cpp | 11 +- src/internet/magnatuneplaylistitem.h | 2 +- src/internet/magnatuneservice.cpp | 121 +- src/internet/magnatuneservice.h | 4 +- src/internet/magnatunesettingspage.cpp | 58 +- src/internet/magnatunesettingspage.h | 10 +- src/internet/magnatuneurlhandler.cpp | 7 +- src/internet/magnatuneurlhandler.h | 7 +- src/internet/oauthenticator.cpp | 68 +- src/internet/oauthenticator.h | 20 +- src/internet/savedradio.cpp | 61 +- src/internet/savedradio.h | 12 +- src/internet/searchboxwidget.cpp | 27 +- src/internet/searchboxwidget.h | 10 +- src/internet/skydriveservice.cpp | 47 +- src/internet/skydriveservice.h | 6 +- src/internet/skydriveurlhandler.cpp | 9 +- src/internet/somafmservice.cpp | 137 +- src/internet/somafmservice.h | 26 +- src/internet/somafmurlhandler.cpp | 25 +- src/internet/somafmurlhandler.h | 15 +- src/internet/soundcloudservice.cpp | 77 +- src/internet/soundcloudservice.h | 11 +- src/internet/spotifyblobdownloader.cpp | 82 +- src/internet/spotifyblobdownloader.h | 10 +- src/internet/spotifyserver.cpp | 70 +- src/internet/spotifyserver.h | 16 +- src/internet/spotifyservice.cpp | 240 +-- src/internet/spotifyservice.h | 17 +- src/internet/spotifysettingspage.cpp | 57 +- src/internet/spotifysettingspage.h | 12 +- src/internet/subsonicservice.cpp | 143 +- src/internet/subsonicservice.h | 33 +- src/internet/subsonicsettingspage.cpp | 168 +- src/internet/subsonicsettingspage.h | 7 +- src/internet/subsonicurlhandler.cpp | 7 +- src/internet/subsonicurlhandler.h | 4 +- src/internet/ubuntuoneauthenticator.cpp | 49 +- src/internet/ubuntuoneauthenticator.h | 13 +- src/internet/ubuntuoneservice.cpp | 43 +- src/internet/ubuntuonesettingspage.cpp | 14 +- src/internet/ubuntuoneurlhandler.cpp | 9 +- src/library/directory.h | 5 +- src/library/groupbydialog.cpp | 40 +- src/library/groupbydialog.h | 4 +- src/library/library.cpp | 173 ++- src/library/library.h | 7 +- src/library/librarybackend.cpp | 464 +++--- src/library/librarybackend.h | 89 +- src/library/librarydirectorymodel.cpp | 62 +- src/library/librarydirectorymodel.h | 4 +- src/library/libraryfilterwidget.cpp | 129 +- src/library/libraryfilterwidget.h | 14 +- src/library/libraryitem.h | 14 +- src/library/librarymodel.cpp | 860 +++++----- src/library/librarymodel.h | 54 +- src/library/libraryplaylistitem.cpp | 26 +- src/library/libraryplaylistitem.h | 2 +- src/library/libraryquery.cpp | 83 +- src/library/libraryquery.h | 24 +- src/library/librarysettingspage.cpp | 59 +- src/library/librarysettingspage.h | 8 +- src/library/libraryview.cpp | 292 ++-- src/library/libraryview.h | 21 +- src/library/libraryviewcontainer.cpp | 22 +- src/library/libraryviewcontainer.h | 6 +- src/library/librarywatcher.cpp | 306 ++-- src/library/librarywatcher.h | 65 +- src/library/sqlrow.cpp | 9 +- src/main.cpp | 122 +- src/moodbar/moodbarcontroller.cpp | 36 +- src/moodbar/moodbarcontroller.h | 14 +- src/moodbar/moodbaritemdelegate.cpp | 141 +- src/moodbar/moodbaritemdelegate.h | 21 +- src/moodbar/moodbarloader.cpp | 40 +- src/moodbar/moodbarloader.h | 13 +- src/moodbar/moodbarpipeline.cpp | 64 +- src/moodbar/moodbarpipeline.h | 13 +- src/moodbar/moodbarproxystyle.cpp | 208 +-- src/moodbar/moodbarproxystyle.h | 36 +- src/moodbar/moodbarrenderer.cpp | 105 +- src/moodbar/moodbarrenderer.h | 20 +- src/musicbrainz/acoustidclient.cpp | 31 +- src/musicbrainz/acoustidclient.h | 8 +- src/musicbrainz/chromaprinter.cpp | 80 +- src/musicbrainz/chromaprinter.h | 14 +- src/musicbrainz/musicbrainzclient.cpp | 54 +- src/musicbrainz/musicbrainzclient.h | 40 +- src/musicbrainz/tagfetcher.cpp | 32 +- src/musicbrainz/tagfetcher.h | 10 +- src/networkremote/avahi.cpp | 92 +- src/networkremote/avahi.h | 7 +- src/networkremote/bonjour.h | 7 +- src/networkremote/incomingdataparser.cpp | 119 +- src/networkremote/incomingdataparser.h | 14 +- src/networkremote/networkremote.cpp | 56 +- src/networkremote/networkremote.h | 10 +- src/networkremote/networkremotehelper.cpp | 27 +- src/networkremote/networkremotehelper.h | 10 +- src/networkremote/outgoingdatacreator.cpp | 336 ++-- src/networkremote/outgoingdatacreator.h | 32 +- src/networkremote/remoteclient.cpp | 24 +- src/networkremote/remoteclient.h | 10 +- src/networkremote/tinysvcmdns.cpp | 60 +- src/networkremote/tinysvcmdns.h | 7 +- src/networkremote/zeroconf.cpp | 37 +- src/networkremote/zeroconf.h | 14 +- src/playlist/dynamicplaylistcontrols.cpp | 10 +- src/playlist/dynamicplaylistcontrols.h | 6 +- src/playlist/playlist.cpp | 1012 ++++++------ src/playlist/playlist.h | 161 +- src/playlist/playlistbackend.cpp | 166 +- src/playlist/playlistbackend.h | 20 +- src/playlist/playlistcontainer.cpp | 202 +-- src/playlist/playlistcontainer.h | 24 +- src/playlist/playlistdelegates.cpp | 239 ++- src/playlist/playlistdelegates.h | 69 +- src/playlist/playlistfilter.cpp | 29 +- src/playlist/playlistfilter.h | 8 +- src/playlist/playlistfilterparser.cpp | 111 +- src/playlist/playlistfilterparser.h | 29 +- src/playlist/playlistheader.cpp | 45 +- src/playlist/playlistheader.h | 4 +- src/playlist/playlistitem.cpp | 38 +- src/playlist/playlistitem.h | 16 +- src/playlist/playlistitemmimedata.h | 9 +- src/playlist/playlistlistcontainer.cpp | 163 +- src/playlist/playlistlistcontainer.h | 13 +- src/playlist/playlistlistmodel.cpp | 127 +- src/playlist/playlistlistmodel.h | 20 +- src/playlist/playlistlistview.cpp | 13 +- src/playlist/playlistmanager.cpp | 208 ++- src/playlist/playlistmanager.h | 47 +- src/playlist/playlistsequence.cpp | 131 +- src/playlist/playlistsequence.h | 6 +- src/playlist/playlisttabbar.cpp | 146 +- src/playlist/playlisttabbar.h | 12 +- src/playlist/playlistundocommands.cpp | 89 +- src/playlist/playlistundocommands.h | 151 +- src/playlist/playlistview.cpp | 511 +++--- src/playlist/playlistview.h | 49 +- src/playlist/queue.cpp | 160 +- src/playlist/queue.h | 25 +- src/playlist/queuemanager.cpp | 84 +- src/playlist/queuemanager.h | 8 +- src/playlist/songloaderinserter.cpp | 39 +- src/playlist/songloaderinserter.h | 13 +- src/playlist/songmimedata.h | 7 +- src/playlist/songplaylistitem.cpp | 25 +- src/playlist/songplaylistitem.h | 2 +- src/playlistparsers/asxiniparser.cpp | 14 +- src/playlistparsers/asxiniparser.h | 12 +- src/playlistparsers/asxparser.cpp | 14 +- src/playlistparsers/asxparser.h | 7 +- src/playlistparsers/cueparser.cpp | 178 ++- src/playlistparsers/cueparser.h | 21 +- src/playlistparsers/m3uparser.cpp | 22 +- src/playlistparsers/m3uparser.h | 13 +- src/playlistparsers/parserbase.cpp | 19 +- src/playlistparsers/parserbase.h | 32 +- src/playlistparsers/playlistparser.cpp | 32 +- src/playlistparsers/playlistparser.h | 11 +- src/playlistparsers/plsparser.cpp | 15 +- src/playlistparsers/plsparser.h | 12 +- src/playlistparsers/wplparser.cpp | 9 +- src/playlistparsers/wplparser.h | 4 +- src/playlistparsers/xmlparser.cpp | 3 +- src/playlistparsers/xmlparser.h | 7 +- src/playlistparsers/xspfparser.cpp | 19 +- src/playlistparsers/xspfparser.h | 7 +- src/podcasts/addpodcastbyurl.cpp | 44 +- src/podcasts/addpodcastbyurl.h | 16 +- src/podcasts/addpodcastdialog.cpp | 61 +- src/podcasts/addpodcastdialog.h | 20 +- src/podcasts/addpodcastpage.cpp | 11 +- src/podcasts/addpodcastpage.h | 14 +- src/podcasts/fixedopmlpage.cpp | 37 +- src/podcasts/fixedopmlpage.h | 14 +- src/podcasts/gpoddersearchpage.cpp | 44 +- src/podcasts/gpoddersearchpage.h | 15 +- src/podcasts/gpoddersync.cpp | 225 +-- src/podcasts/gpoddersync.h | 22 +- src/podcasts/gpoddertoptagsmodel.cpp | 50 +- src/podcasts/gpoddertoptagsmodel.h | 22 +- src/podcasts/gpoddertoptagspage.cpp | 43 +- src/podcasts/gpoddertoptagspage.h | 14 +- src/podcasts/itunessearchpage.cpp | 39 +- src/podcasts/itunessearchpage.h | 14 +- src/podcasts/opmlcontainer.h | 10 +- src/podcasts/podcast.cpp | 70 +- src/podcasts/podcast.h | 24 +- src/podcasts/podcastbackend.cpp | 120 +- src/podcasts/podcastbackend.h | 19 +- src/podcasts/podcastdiscoverymodel.cpp | 37 +- src/podcasts/podcastdiscoverymodel.h | 26 +- src/podcasts/podcastdownloader.cpp | 88 +- src/podcasts/podcastdownloader.h | 19 +- src/podcasts/podcastepisode.cpp | 93 +- src/podcasts/podcastepisode.h | 14 +- src/podcasts/podcastinfowidget.cpp | 54 +- src/podcasts/podcastinfowidget.h | 14 +- src/podcasts/podcastparser.cpp | 335 ++-- src/podcasts/podcastparser.h | 18 +- src/podcasts/podcastservice.cpp | 294 ++-- src/podcasts/podcastservice.h | 45 +- src/podcasts/podcastservicemodel.cpp | 41 +- src/podcasts/podcastservicemodel.h | 22 +- src/podcasts/podcastsettingspage.cpp | 68 +- src/podcasts/podcastsettingspage.h | 14 +- src/podcasts/podcastupdater.cpp | 64 +- src/podcasts/podcastupdater.h | 18 +- src/podcasts/podcasturlloader.cpp | 73 +- src/podcasts/podcasturlloader.h | 28 +- src/smartplaylists/generator.cpp | 9 +- src/smartplaylists/generator.h | 24 +- src/smartplaylists/generator_fwd.h | 4 +- src/smartplaylists/generatorinserter.cpp | 24 +- src/smartplaylists/generatorinserter.h | 14 +- src/smartplaylists/generatormimedata.h | 9 +- src/smartplaylists/querygenerator.cpp | 20 +- src/smartplaylists/querygenerator.h | 13 +- src/smartplaylists/querywizardplugin.cpp | 126 +- src/smartplaylists/querywizardplugin.h | 10 +- src/smartplaylists/search.cpp | 48 +- src/smartplaylists/search.h | 29 +- src/smartplaylists/searchpreview.cpp | 26 +- src/smartplaylists/searchpreview.h | 16 +- src/smartplaylists/searchterm.cpp | 323 ++-- src/smartplaylists/searchterm.h | 28 +- src/smartplaylists/searchtermwidget.cpp | 223 +-- src/smartplaylists/searchtermwidget.h | 17 +- src/smartplaylists/wizard.cpp | 56 +- src/smartplaylists/wizard.h | 14 +- src/smartplaylists/wizardplugin.cpp | 12 +- src/smartplaylists/wizardplugin.h | 10 +- src/songinfo/artistinfoview.cpp | 42 +- src/songinfo/artistinfoview.h | 11 +- src/songinfo/collapsibleinfoheader.cpp | 36 +- src/songinfo/collapsibleinfoheader.h | 10 +- src/songinfo/collapsibleinfopane.cpp | 18 +- src/songinfo/collapsibleinfopane.h | 13 +- src/songinfo/echonestbiographies.cpp | 25 +- src/songinfo/echonestbiographies.h | 8 +- src/songinfo/echonestimages.cpp | 11 +- src/songinfo/echonestimages.h | 8 +- src/songinfo/echonestsimilarartists.cpp | 14 +- src/songinfo/echonestsimilarartists.h | 8 +- src/songinfo/echonesttags.cpp | 13 +- src/songinfo/echonesttags.h | 8 +- src/songinfo/lastfmtrackinfoprovider.cpp | 25 +- src/songinfo/lastfmtrackinfoprovider.h | 12 +- src/songinfo/songinfobase.cpp | 68 +- src/songinfo/songinfobase.h | 26 +- src/songinfo/songinfofetcher.cpp | 52 +- src/songinfo/songinfofetcher.h | 13 +- src/songinfo/songinfoprovider.cpp | 9 +- src/songinfo/songinfoprovider.h | 6 +- src/songinfo/songinfosettingspage.cpp | 47 +- src/songinfo/songinfosettingspage.h | 8 +- src/songinfo/songinfotextview.cpp | 26 +- src/songinfo/songinfotextview.h | 10 +- src/songinfo/songinfoview.cpp | 78 +- src/songinfo/songinfoview.h | 19 +- src/songinfo/songkickconcerts.cpp | 38 +- src/songinfo/songkickconcertwidget.cpp | 27 +- src/songinfo/songkickconcertwidget.h | 18 +- src/songinfo/songplaystats.cpp | 20 +- src/songinfo/songplaystats.h | 8 +- src/songinfo/tagwidget.cpp | 40 +- src/songinfo/tagwidget.h | 26 +- src/songinfo/ultimatelyricslyric.cpp | 8 +- src/songinfo/ultimatelyricslyric.h | 4 +- src/songinfo/ultimatelyricsprovider.cpp | 137 +- src/songinfo/ultimatelyricsprovider.h | 26 +- src/songinfo/ultimatelyricsreader.cpp | 50 +- src/songinfo/ultimatelyricsreader.h | 6 +- src/transcoder/transcodedialog.cpp | 107 +- src/transcoder/transcodedialog.h | 2 +- src/transcoder/transcoder.cpp | 239 +-- src/transcoder/transcoder.h | 22 +- src/transcoder/transcoderoptionsaac.cpp | 8 +- src/transcoder/transcoderoptionsaac.h | 6 +- src/transcoder/transcoderoptionsdialog.cpp | 41 +- src/transcoder/transcoderoptionsdialog.h | 8 +- src/transcoder/transcoderoptionsflac.cpp | 8 +- src/transcoder/transcoderoptionsflac.h | 6 +- src/transcoder/transcoderoptionsinterface.h | 4 +- src/transcoder/transcoderoptionsmp3.cpp | 23 +- src/transcoder/transcoderoptionsmp3.h | 8 +- src/transcoder/transcoderoptionsopus.cpp | 10 +- src/transcoder/transcoderoptionsopus.h | 6 +- src/transcoder/transcoderoptionsspeex.cpp | 8 +- src/transcoder/transcoderoptionsspeex.h | 6 +- src/transcoder/transcoderoptionsvorbis.cpp | 12 +- src/transcoder/transcoderoptionsvorbis.h | 6 +- src/transcoder/transcoderoptionswma.cpp | 8 +- src/transcoder/transcoderoptionswma.h | 6 +- src/transcoder/transcodersettingspage.cpp | 8 +- src/transcoder/transcodersettingspage.h | 6 +- src/ui/about.cpp | 47 +- src/ui/about.h | 7 +- src/ui/addstreamdialog.cpp | 35 +- src/ui/addstreamdialog.h | 10 +- src/ui/albumcoverchoicecontroller.cpp | 139 +- src/ui/albumcoverchoicecontroller.h | 22 +- src/ui/albumcoverexport.cpp | 35 +- src/ui/albumcoverexport.h | 2 +- src/ui/albumcovermanager.cpp | 312 ++-- src/ui/albumcovermanager.h | 36 +- src/ui/albumcovermanagerlist.cpp | 22 +- src/ui/albumcovermanagerlist.h | 12 +- src/ui/albumcoversearcher.cpp | 105 +- src/ui/albumcoversearcher.h | 20 +- src/ui/appearancesettingspage.cpp | 118 +- src/ui/appearancesettingspage.h | 11 +- src/ui/backgroundstreamssettingspage.cpp | 16 +- src/ui/backgroundstreamssettingspage.h | 10 +- src/ui/behavioursettingspage.cpp | 76 +- src/ui/behavioursettingspage.h | 8 +- src/ui/console.cpp | 3 +- src/ui/coverfromurldialog.cpp | 25 +- src/ui/coverfromurldialog.h | 2 +- src/ui/dbusscreensaver.cpp | 15 +- src/ui/dbusscreensaver.h | 2 +- src/ui/edittagdialog.cpp | 371 ++--- src/ui/edittagdialog.h | 25 +- src/ui/equalizer.cpp | 200 +-- src/ui/equalizer.h | 16 +- src/ui/flowlayout.cpp | 211 ++- src/ui/flowlayout.h | 48 +- src/ui/globalshortcutgrabber.cpp | 20 +- src/ui/globalshortcutgrabber.h | 8 +- src/ui/globalshortcutssettingspage.cpp | 59 +- src/ui/globalshortcutssettingspage.h | 12 +- src/ui/iconloader.cpp | 16 +- src/ui/iconloader.h | 6 +- src/ui/macscreensaver.cpp | 18 +- src/ui/macsystemtrayicon.h | 12 +- src/ui/mainwindow.cpp | 1382 ++++++++++------- src/ui/mainwindow.h | 26 +- src/ui/networkproxysettingspage.cpp | 50 +- src/ui/networkproxysettingspage.h | 6 +- src/ui/networkremotesettingspage.cpp | 10 +- src/ui/networkremotesettingspage.h | 8 +- src/ui/notificationssettingspage.cpp | 168 +- src/ui/notificationssettingspage.h | 10 +- src/ui/organisedialog.cpp | 85 +- src/ui/organisedialog.h | 15 +- src/ui/organiseerrordialog.cpp | 43 +- src/ui/organiseerrordialog.h | 11 +- src/ui/playbacksettingspage.cpp | 55 +- src/ui/playbacksettingspage.h | 8 +- src/ui/qt_blurimage.h | 2 +- src/ui/qtsystemtrayicon.cpp | 109 +- src/ui/qtsystemtrayicon.h | 16 +- src/ui/ripcd.cpp | 181 ++- src/ui/ripcd.h | 10 +- src/ui/screensaver.cpp | 39 +- src/ui/settingsdialog.cpp | 102 +- src/ui/settingsdialog.h | 28 +- src/ui/settingspage.cpp | 5 +- src/ui/settingspage.h | 6 +- src/ui/standarditemiconloader.cpp | 50 +- src/ui/standarditemiconloader.h | 16 +- src/ui/systemtrayicon.cpp | 26 +- src/ui/systemtrayicon.h | 4 +- src/ui/trackselectiondialog.cpp | 84 +- src/ui/trackselectiondialog.h | 19 +- src/ui/windows7thumbbar.cpp | 76 +- src/ui/windows7thumbbar.h | 12 +- src/visualisations/projectmpresetmodel.cpp | 82 +- src/visualisations/projectmpresetmodel.h | 30 +- src/visualisations/projectmvisualisation.cpp | 108 +- src/visualisations/projectmvisualisation.h | 25 +- src/visualisations/visualisationcontainer.cpp | 97 +- src/visualisations/visualisationcontainer.h | 26 +- src/visualisations/visualisationoverlay.cpp | 35 +- src/visualisations/visualisationoverlay.h | 18 +- src/visualisations/visualisationselector.cpp | 39 +- src/visualisations/visualisationselector.h | 14 +- src/widgets/autoexpandingtreeview.cpp | 40 +- src/widgets/autoexpandingtreeview.h | 20 +- src/widgets/busyindicator.cpp | 25 +- src/widgets/busyindicator.h | 2 +- src/widgets/clickablelabel.cpp | 5 +- src/widgets/clickablelabel.h | 6 +- src/widgets/didyoumean.cpp | 37 +- src/widgets/didyoumean.h | 12 +- src/widgets/elidedlabel.cpp | 9 +- src/widgets/elidedlabel.h | 12 +- src/widgets/equalizerslider.cpp | 18 +- src/widgets/equalizerslider.h | 6 +- src/widgets/errordialog.cpp | 22 +- src/widgets/errordialog.h | 12 +- src/widgets/fancytabwidget.cpp | 454 +++--- src/widgets/fancytabwidget.h | 147 +- src/widgets/favoritewidget.cpp | 19 +- src/widgets/favoritewidget.h | 4 +- src/widgets/fileview.cpp | 93 +- src/widgets/fileview.h | 4 +- src/widgets/fileviewlist.cpp | 49 +- src/widgets/fileviewlist.h | 4 +- src/widgets/forcescrollperpixel.cpp | 11 +- src/widgets/forcescrollperpixel.h | 8 +- src/widgets/freespacebar.cpp | 52 +- src/widgets/freespacebar.h | 40 +- src/widgets/fullscreenhypnotoad.cpp | 19 +- src/widgets/fullscreenhypnotoad.h | 8 +- src/widgets/groupediconview.cpp | 137 +- src/widgets/groupediconview.h | 26 +- src/widgets/lineedit.cpp | 78 +- src/widgets/lineedit.h | 63 +- src/widgets/linetextedit.cpp | 11 +- src/widgets/linetextedit.h | 6 +- src/widgets/loginstatewidget.cpp | 18 +- src/widgets/loginstatewidget.h | 16 +- src/widgets/multiloadingindicator.cpp | 27 +- src/widgets/multiloadingindicator.h | 10 +- src/widgets/nowplayingwidget.cpp | 249 +-- src/widgets/nowplayingwidget.h | 22 +- src/widgets/osd.cpp | 184 ++- src/widgets/osd.h | 27 +- src/widgets/osd_win.cpp | 15 +- src/widgets/osd_x11.cpp | 44 +- src/widgets/osdpretty.cpp | 158 +- src/widgets/osdpretty.h | 31 +- src/widgets/prettyimage.cpp | 75 +- src/widgets/prettyimage.h | 14 +- src/widgets/prettyimageview.cpp | 62 +- src/widgets/prettyimageview.h | 12 +- src/widgets/progressitemdelegate.cpp | 10 +- src/widgets/progressitemdelegate.h | 7 +- src/widgets/ratingwidget.cpp | 40 +- src/widgets/ratingwidget.h | 14 +- src/widgets/renametablineedit.cpp | 16 +- src/widgets/renametablineedit.h | 8 +- src/widgets/sliderwidget.cpp | 457 +++--- src/widgets/sliderwidget.h | 167 +- src/widgets/stickyslider.cpp | 13 +- src/widgets/stickyslider.h | 5 +- src/widgets/stretchheaderview.cpp | 88 +- src/widgets/stretchheaderview.h | 14 +- src/widgets/stylehelper.cpp | 299 ++-- src/widgets/stylehelper.h | 59 +- src/widgets/trackslider.cpp | 44 +- src/widgets/trackslider.h | 8 +- src/widgets/tracksliderpopup.cpp | 25 +- src/widgets/tracksliderpopup.h | 12 +- src/widgets/tracksliderslider.cpp | 25 +- src/widgets/tracksliderslider.h | 10 +- src/widgets/widgetfadehelper.cpp | 27 +- src/widgets/widgetfadehelper.h | 14 +- src/wiimotedev/consts.h | 290 ++-- src/wiimotedev/shortcuts.cpp | 141 +- src/wiimotedev/shortcuts.h | 16 +- src/wiimotedev/wiimotesettingspage.cpp | 79 +- src/wiimotedev/wiimotesettingspage.h | 8 +- src/wiimotedev/wiimoteshortcutgrabber.cpp | 68 +- src/wiimotedev/wiimoteshortcutgrabber.h | 10 +- 803 files changed, 22699 insertions(+), 22831 deletions(-) diff --git a/ext/clementine-spotifyblob/main.cpp b/ext/clementine-spotifyblob/main.cpp index 238049e04..cce0d106c 100644 --- a/ext/clementine-spotifyblob/main.cpp +++ b/ext/clementine-spotifyblob/main.cpp @@ -18,7 +18,6 @@ // it is used by the Spotify blob which links against libspotify and is not GPL // compatible. - #include #include diff --git a/ext/clementine-spotifyblob/mediapipeline.cpp b/ext/clementine-spotifyblob/mediapipeline.cpp index 859fd28ab..69f4c0d3f 100644 --- a/ext/clementine-spotifyblob/mediapipeline.cpp +++ b/ext/clementine-spotifyblob/mediapipeline.cpp @@ -25,15 +25,13 @@ #include MediaPipeline::MediaPipeline(int port, quint64 length_msec) - : port_(port), - length_msec_(length_msec), - accepting_data_(true), - pipeline_(nullptr), - appsrc_(nullptr), - byte_rate_(1), - offset_bytes_(0) -{ -} + : port_(port), + length_msec_(length_msec), + accepting_data_(true), + pipeline_(nullptr), + appsrc_(nullptr), + byte_rate_(1), + offset_bytes_(0) {} MediaPipeline::~MediaPipeline() { if (pipeline_) { @@ -43,8 +41,7 @@ MediaPipeline::~MediaPipeline() { } bool MediaPipeline::Init(int sample_rate, int channels) { - if (is_initialised()) - return false; + if (is_initialised()) return false; pipeline_ = gst_pipeline_new("pipeline"); @@ -54,10 +51,21 @@ bool MediaPipeline::Init(int sample_rate, int channels) { tcpsink_ = gst_element_factory_make("tcpclientsink", nullptr); if (!pipeline_ || !appsrc_ || !tcpsink_) { - if (pipeline_) { gst_object_unref(GST_OBJECT(pipeline_)); pipeline_ = nullptr; } - if (appsrc_) { gst_object_unref(GST_OBJECT(appsrc_)); appsrc_ = nullptr; } - if (gdppay) { gst_object_unref(GST_OBJECT(gdppay)); } - if (tcpsink_) { gst_object_unref(GST_OBJECT(tcpsink_)); tcpsink_ = nullptr; } + if (pipeline_) { + gst_object_unref(GST_OBJECT(pipeline_)); + pipeline_ = nullptr; + } + if (appsrc_) { + gst_object_unref(GST_OBJECT(appsrc_)); + appsrc_ = nullptr; + } + if (gdppay) { + gst_object_unref(GST_OBJECT(gdppay)); + } + if (tcpsink_) { + gst_object_unref(GST_OBJECT(tcpsink_)); + tcpsink_ = nullptr; + } return false; } @@ -73,7 +81,8 @@ bool MediaPipeline::Init(int sample_rate, int channels) { // Try to send 5 seconds of audio in advance to initially fill Clementine's // buffer. - g_object_set(G_OBJECT(tcpsink_), "ts-offset", qint64(-5 * kNsecPerSec), nullptr); + g_object_set(G_OBJECT(tcpsink_), "ts-offset", qint64(-5 * kNsecPerSec), + nullptr); // We know the time of each buffer g_object_set(G_OBJECT(appsrc_), "format", GST_FORMAT_TIME, nullptr); @@ -97,14 +106,11 @@ bool MediaPipeline::Init(int sample_rate, int channels) { #endif // Set caps - GstCaps* caps = gst_caps_new_simple("audio/x-raw-int", - "endianness", G_TYPE_INT, endianness, - "signed", G_TYPE_BOOLEAN, TRUE, - "width", G_TYPE_INT, 16, - "depth", G_TYPE_INT, 16, - "rate", G_TYPE_INT, sample_rate, - "channels", G_TYPE_INT, channels, - nullptr); + GstCaps* caps = gst_caps_new_simple( + "audio/x-raw-int", "endianness", G_TYPE_INT, endianness, "signed", + G_TYPE_BOOLEAN, TRUE, "width", G_TYPE_INT, 16, "depth", G_TYPE_INT, 16, + "rate", G_TYPE_INT, sample_rate, "channels", G_TYPE_INT, channels, + nullptr); gst_app_src_set_caps(appsrc_, caps); gst_caps_unref(caps); @@ -115,12 +121,12 @@ bool MediaPipeline::Init(int sample_rate, int channels) { gst_app_src_set_size(appsrc_, bytes); // Ready to go - return gst_element_set_state(pipeline_, GST_STATE_PLAYING) != GST_STATE_CHANGE_FAILURE; + return gst_element_set_state(pipeline_, GST_STATE_PLAYING) != + GST_STATE_CHANGE_FAILURE; } void MediaPipeline::WriteData(const char* data, qint64 length) { - if (!is_initialised()) - return; + if (!is_initialised()) return; GstBuffer* buffer = gst_buffer_new_and_alloc(length); @@ -137,8 +143,7 @@ void MediaPipeline::WriteData(const char* data, qint64 length) { } void MediaPipeline::EndStream() { - if (!is_initialised()) - return; + if (!is_initialised()) return; gst_app_src_end_of_stream(appsrc_); } @@ -153,8 +158,9 @@ void MediaPipeline::EnoughDataCallback(GstAppSrc* src, void* data) { me->accepting_data_ = false; } -gboolean MediaPipeline::SeekDataCallback(GstAppSrc* src, guint64 offset, void * data) { - //MediaPipeline* me = reinterpret_cast(data); +gboolean MediaPipeline::SeekDataCallback(GstAppSrc* src, guint64 offset, + void* data) { + // MediaPipeline* me = reinterpret_cast(data); qLog(Debug) << "Gstreamer wants seek to" << offset; return false; diff --git a/ext/clementine-spotifyblob/mediapipeline.h b/ext/clementine-spotifyblob/mediapipeline.h index 4e965d376..32c9b0420 100644 --- a/ext/clementine-spotifyblob/mediapipeline.h +++ b/ext/clementine-spotifyblob/mediapipeline.h @@ -27,7 +27,7 @@ #include class MediaPipeline { -public: + public: MediaPipeline(int port, quint64 length_msec); ~MediaPipeline(); @@ -38,12 +38,12 @@ public: void WriteData(const char* data, qint64 length); void EndStream(); -private: + private: static void NeedDataCallback(GstAppSrc* src, guint length, void* data); static void EnoughDataCallback(GstAppSrc* src, void* data); static gboolean SeekDataCallback(GstAppSrc* src, guint64 offset, void* data); -private: + private: Q_DISABLE_COPY(MediaPipeline) const int port_; @@ -59,4 +59,4 @@ private: quint64 offset_bytes_; }; -#endif // MEDIAPIPELINE_H +#endif // MEDIAPIPELINE_H diff --git a/ext/clementine-spotifyblob/spotify_utilities.cpp b/ext/clementine-spotifyblob/spotify_utilities.cpp index d49676c85..cfc077b96 100644 --- a/ext/clementine-spotifyblob/spotify_utilities.cpp +++ b/ext/clementine-spotifyblob/spotify_utilities.cpp @@ -31,7 +31,8 @@ namespace utilities { QString GetCacheDirectory() { QString user_cache = GetUserDataDirectory(); - return user_cache + "/" + QCoreApplication::applicationName() + "/spotify-cache"; + return user_cache + "/" + QCoreApplication::applicationName() + + "/spotify-cache"; } #ifndef Q_OS_DARWIN // See spotify_utilities.mm for Mac implementation. @@ -47,10 +48,11 @@ QString GetSettingsDirectory() { QString ret; #ifdef Q_OS_WIN32 - ret = GetUserDataDirectory() + "/" + QCoreApplication::applicationName() + "/spotify-settings"; + ret = GetUserDataDirectory() + "/" + QCoreApplication::applicationName() + + "/spotify-settings"; #else ret = QFileInfo(QSettings().fileName()).absolutePath() + "/spotify-settings"; -#endif // Q_OS_WIN32 +#endif // Q_OS_WIN32 // Create the directory QDir dir; @@ -59,6 +61,6 @@ QString GetSettingsDirectory() { return ret; } -#endif // Q_OS_DARWIN +#endif // Q_OS_DARWIN } // namespace utilities diff --git a/ext/clementine-spotifyblob/spotify_utilities.h b/ext/clementine-spotifyblob/spotify_utilities.h index 77481a540..52f103453 100644 --- a/ext/clementine-spotifyblob/spotify_utilities.h +++ b/ext/clementine-spotifyblob/spotify_utilities.h @@ -32,7 +32,6 @@ QString GetUserDataDirectory(); QString GetCacheDirectory(); QString GetSettingsDirectory(); - } #endif diff --git a/ext/clementine-spotifyblob/spotify_utilities.mm b/ext/clementine-spotifyblob/spotify_utilities.mm index dcfad233b..b8a564b9b 100644 --- a/ext/clementine-spotifyblob/spotify_utilities.mm +++ b/ext/clementine-spotifyblob/spotify_utilities.mm @@ -10,10 +10,8 @@ QString GetUserDataDirectory() { NSAutoreleasePool* pool = [NSAutoreleasePool alloc]; [pool init]; - NSArray* paths = NSSearchPathForDirectoriesInDomains( - NSCachesDirectory, - NSUserDomainMask, - YES); + NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, + NSUserDomainMask, YES); QString ret; if ([paths count] > 0) { NSString* user_path = [paths objectAtIndex:0]; @@ -28,9 +26,7 @@ QString GetUserDataDirectory() { QString GetSettingsDirectory() { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NSArray* paths = NSSearchPathForDirectoriesInDomains( - NSApplicationSupportDirectory, - NSUserDomainMask, - YES); + NSApplicationSupportDirectory, NSUserDomainMask, YES); NSString* ret; if ([paths count] > 0) { ret = [paths objectAtIndex:0]; @@ -40,15 +36,13 @@ QString GetSettingsDirectory() { ret = [ret stringByAppendingString:@"/Clementine/spotify-settings"]; NSFileManager* file_manager = [NSFileManager defaultManager]; - [file_manager createDirectoryAtPath: - ret - withIntermediateDirectories:YES - attributes:nil - error:nil]; + [file_manager createDirectoryAtPath:ret + withIntermediateDirectories:YES + attributes:nil + error:nil]; QString path = QString::fromUtf8([ret UTF8String]); [pool drain]; return path; } - } diff --git a/ext/clementine-spotifyblob/spotifyclient.cpp b/ext/clementine-spotifyblob/spotifyclient.cpp index 751d3f8e8..e157d07d9 100644 --- a/ext/clementine-spotifyblob/spotifyclient.cpp +++ b/ext/clementine-spotifyblob/spotifyclient.cpp @@ -36,18 +36,18 @@ const int SpotifyClient::kSpotifyImageIDSize = 20; const int SpotifyClient::kWaveHeaderSize = 44; - SpotifyClient::SpotifyClient(QObject* parent) - : AbstractMessageHandler(nullptr, parent), - api_key_(QByteArray::fromBase64(kSpotifyApiKey)), - protocol_socket_(new QTcpSocket(this)), - session_(nullptr), - events_timer_(new QTimer(this)) { + : AbstractMessageHandler(nullptr, parent), + api_key_(QByteArray::fromBase64(kSpotifyApiKey)), + protocol_socket_(new QTcpSocket(this)), + session_(nullptr), + events_timer_(new QTimer(this)) { SetDevice(protocol_socket_); memset(&spotify_callbacks_, 0, sizeof(spotify_callbacks_)); memset(&spotify_config_, 0, sizeof(spotify_config_)); - memset(&playlistcontainer_callbacks_, 0, sizeof(playlistcontainer_callbacks_)); + memset(&playlistcontainer_callbacks_, 0, + sizeof(playlistcontainer_callbacks_)); memset(&get_playlists_callbacks_, 0, sizeof(get_playlists_callbacks_)); memset(&load_playlist_callbacks_, 0, sizeof(load_playlist_callbacks_)); @@ -64,15 +64,17 @@ SpotifyClient::SpotifyClient(QObject* parent) spotify_callbacks_.start_playback = &StartPlaybackCallback; spotify_callbacks_.stop_playback = &StopPlaybackCallback; - - playlistcontainer_callbacks_.container_loaded = &PlaylistContainerLoadedCallback; + playlistcontainer_callbacks_.container_loaded = + &PlaylistContainerLoadedCallback; playlistcontainer_callbacks_.playlist_added = &PlaylistAddedCallback; playlistcontainer_callbacks_.playlist_moved = &PlaylistMovedCallback; playlistcontainer_callbacks_.playlist_removed = &PlaylistRemovedCallback; - get_playlists_callbacks_.playlist_state_changed = &PlaylistStateChangedForGetPlaylists; + get_playlists_callbacks_.playlist_state_changed = + &PlaylistStateChangedForGetPlaylists; - load_playlist_callbacks_.playlist_state_changed = &PlaylistStateChangedForLoadPlaylist; + load_playlist_callbacks_.playlist_state_changed = + &PlaylistStateChangedForLoadPlaylist; QString cache = utilities::GetCacheDirectory(); qLog(Debug) << "Using:" << cache << "for Spotify cache"; @@ -111,41 +113,43 @@ void SpotifyClient::Init(quint16 port) { } void SpotifyClient::LoggedInCallback(sp_session* session, sp_error error) { - SpotifyClient* me = reinterpret_cast(sp_session_userdata(session)); + SpotifyClient* me = + reinterpret_cast(sp_session_userdata(session)); const bool success = error == SP_ERROR_OK; - pb::spotify::LoginResponse_Error error_code = pb::spotify::LoginResponse_Error_Other; + pb::spotify::LoginResponse_Error error_code = + pb::spotify::LoginResponse_Error_Other; if (!success) { qLog(Warning) << "Failed to login" << sp_error_message(error); } switch (error) { - case SP_ERROR_BAD_USERNAME_OR_PASSWORD: - error_code = pb::spotify::LoginResponse_Error_BadUsernameOrPassword; - break; - case SP_ERROR_USER_BANNED: - error_code = pb::spotify::LoginResponse_Error_UserBanned; - break; - case SP_ERROR_USER_NEEDS_PREMIUM : - error_code = pb::spotify::LoginResponse_Error_UserNeedsPremium; - break; - default: - error_code = pb::spotify::LoginResponse_Error_Other; - break; + case SP_ERROR_BAD_USERNAME_OR_PASSWORD: + error_code = pb::spotify::LoginResponse_Error_BadUsernameOrPassword; + break; + case SP_ERROR_USER_BANNED: + error_code = pb::spotify::LoginResponse_Error_UserBanned; + break; + case SP_ERROR_USER_NEEDS_PREMIUM: + error_code = pb::spotify::LoginResponse_Error_UserNeedsPremium; + break; + default: + error_code = pb::spotify::LoginResponse_Error_Other; + break; } me->SendLoginCompleted(success, sp_error_message(error), error_code); if (success) { - sp_playlistcontainer_add_callbacks( - sp_session_playlistcontainer(session), - &me->playlistcontainer_callbacks_, me); + sp_playlistcontainer_add_callbacks(sp_session_playlistcontainer(session), + &me->playlistcontainer_callbacks_, me); sp_session_flush_caches(me->session_); } } void SpotifyClient::NotifyMainThreadCallback(sp_session* session) { - SpotifyClient* me = reinterpret_cast(sp_session_userdata(session)); + SpotifyClient* me = + reinterpret_cast(sp_session_userdata(session)); QMetaObject::invokeMethod(me, "ProcessEvents", Qt::QueuedConnection); } @@ -160,14 +164,11 @@ void SpotifyClient::LogMessageCallback(sp_session* session, const char* data) { } void SpotifyClient::Search(const pb::spotify::SearchRequest& req) { - sp_search* search = sp_search_create( - session_, req.query().c_str(), - 0, req.limit(), - 0, req.limit_album(), - 0, 0, // artists - 0, 0, // playlists - SP_SEARCH_STANDARD, - &SearchCompleteCallback, this); + sp_search* search = + sp_search_create(session_, req.query().c_str(), 0, req.limit(), 0, + req.limit_album(), 0, 0, // artists + 0, 0, // playlists + SP_SEARCH_STANDARD, &SearchCompleteCallback, this); pending_searches_[search] = req; } @@ -184,10 +185,10 @@ void SpotifyClient::SearchCompleteCallback(sp_search* result, void* userdata) { // we can send our response. const int count = sp_search_num_albums(result); if (count != 0) { - for (int i=0 ; isession_, album, &SearchAlbumBrowseComplete, me); + sp_albumbrowse* browse = sp_albumbrowse_create( + me->session_, album, &SearchAlbumBrowseComplete, me); me->pending_search_album_browse_responses_[browse] = result; } @@ -197,7 +198,8 @@ void SpotifyClient::SearchCompleteCallback(sp_search* result, void* userdata) { me->SendSearchResponse(result); } -void SpotifyClient::SearchAlbumBrowseComplete(sp_albumbrowse* result, void* userdata) { +void SpotifyClient::SearchAlbumBrowseComplete(sp_albumbrowse* result, + void* userdata) { SpotifyClient* me = reinterpret_cast(userdata); if (!me->pending_search_album_browse_responses_.contains(result)) { @@ -208,7 +210,8 @@ void SpotifyClient::SearchAlbumBrowseComplete(sp_albumbrowse* result, void* user sp_search* search = me->pending_search_album_browse_responses_.take(result); me->pending_search_album_browses_[search].append(result); - if (me->pending_search_album_browses_[search].count() >= sp_search_num_albums(search)) { + if (me->pending_search_album_browses_[search].count() >= + sp_search_num_albums(search)) { me->SendSearchResponse(search); } } @@ -235,14 +238,14 @@ void SpotifyClient::SendSearchResponse(sp_search* result) { // Get the list of tracks from the search int count = sp_search_num_tracks(result); - for (int i=0 ; iadd_result()); } // Get the albums from the search. All these should be resolved by now. QList browses = pending_search_album_browses_.take(result); - foreach (sp_albumbrowse* browse, browses) { + foreach(sp_albumbrowse * browse, browses) { sp_album* album = sp_albumbrowse_album(browse); pb::spotify::Album* msg = response->add_album(); @@ -251,7 +254,7 @@ void SpotifyClient::SendSearchResponse(sp_search* result) { // Add all tracks const int tracks = sp_albumbrowse_num_tracks(browse); - for (int i=0 ; iadd_track()); } @@ -290,16 +293,23 @@ void SpotifyClient::MessageArrived(const pb::spotify::Message& message) { } } -void SpotifyClient::SetPlaybackSettings(const pb::spotify::PlaybackSettings& req) { +void SpotifyClient::SetPlaybackSettings( + const pb::spotify::PlaybackSettings& req) { sp_bitrate bitrate = SP_BITRATE_320k; switch (req.bitrate()) { - case pb::spotify::Bitrate96k: bitrate = SP_BITRATE_96k; break; - case pb::spotify::Bitrate160k: bitrate = SP_BITRATE_160k; break; - case pb::spotify::Bitrate320k: bitrate = SP_BITRATE_320k; break; + case pb::spotify::Bitrate96k: + bitrate = SP_BITRATE_96k; + break; + case pb::spotify::Bitrate160k: + bitrate = SP_BITRATE_160k; + break; + case pb::spotify::Bitrate320k: + bitrate = SP_BITRATE_320k; + break; } - qLog(Debug) << "Setting playback settings: bitrate" - << bitrate << "normalisation" << req.volume_normalisation(); + qLog(Debug) << "Setting playback settings: bitrate" << bitrate + << "normalisation" << req.volume_normalisation(); sp_session_preferred_bitrate(session_, bitrate); sp_session_preferred_offline_bitrate(session_, bitrate, false); @@ -310,7 +320,8 @@ void SpotifyClient::Login(const pb::spotify::LoginRequest& req) { sp_error error = sp_session_create(&spotify_config_, &session_); if (error != SP_ERROR_OK) { qLog(Warning) << "Failed to create session" << sp_error_message(error); - SendLoginCompleted(false, sp_error_message(error), pb::spotify::LoginResponse_Error_Other); + SendLoginCompleted(false, sp_error_message(error), + pb::spotify::LoginResponse_Error_Other); return; } @@ -324,16 +335,15 @@ void SpotifyClient::Login(const pb::spotify::LoginRequest& req) { pb::spotify::LoginResponse_Error_ReloginFailed); } } else { - sp_session_login(session_, - req.username().c_str(), - req.password().c_str(), - true, // Remember the password. + sp_session_login(session_, req.username().c_str(), req.password().c_str(), + true, // Remember the password. nullptr); } } -void SpotifyClient::SendLoginCompleted(bool success, const QString& error, - pb::spotify::LoginResponse_Error error_code) { +void SpotifyClient::SendLoginCompleted( + bool success, const QString& error, + pb::spotify::LoginResponse_Error error_code) { pb::spotify::Message message; pb::spotify::LoginResponse* response = message.mutable_login_response(); @@ -347,12 +357,13 @@ void SpotifyClient::SendLoginCompleted(bool success, const QString& error, SendMessage(message); } -void SpotifyClient::PlaylistContainerLoadedCallback(sp_playlistcontainer* pc, void* userdata) { +void SpotifyClient::PlaylistContainerLoadedCallback(sp_playlistcontainer* pc, + void* userdata) { SpotifyClient* me = reinterpret_cast(userdata); // Install callbacks on all the playlists const int count = sp_playlistcontainer_num_playlists(pc); - for (int i=0 ; iget_playlists_callbacks_, me); } @@ -360,7 +371,9 @@ void SpotifyClient::PlaylistContainerLoadedCallback(sp_playlistcontainer* pc, vo me->SendPlaylistList(); } -void SpotifyClient::PlaylistAddedCallback(sp_playlistcontainer* pc, sp_playlist* playlist, int position, void* userdata) { +void SpotifyClient::PlaylistAddedCallback(sp_playlistcontainer* pc, + sp_playlist* playlist, int position, + void* userdata) { SpotifyClient* me = reinterpret_cast(userdata); // Install callbacks on this playlist @@ -369,12 +382,16 @@ void SpotifyClient::PlaylistAddedCallback(sp_playlistcontainer* pc, sp_playlist* me->SendPlaylistList(); } -void SpotifyClient::PlaylistMovedCallback(sp_playlistcontainer* pc, sp_playlist* playlist, int position, int new_position, void* userdata) { +void SpotifyClient::PlaylistMovedCallback(sp_playlistcontainer* pc, + sp_playlist* playlist, int position, + int new_position, void* userdata) { SpotifyClient* me = reinterpret_cast(userdata); me->SendPlaylistList(); } -void SpotifyClient::PlaylistRemovedCallback(sp_playlistcontainer* pc, sp_playlist* playlist, int position, void* userdata) { +void SpotifyClient::PlaylistRemovedCallback(sp_playlistcontainer* pc, + sp_playlist* playlist, int position, + void* userdata) { SpotifyClient* me = reinterpret_cast(userdata); // Remove callbacks from this playlist @@ -395,12 +412,13 @@ void SpotifyClient::SendPlaylistList() { const int count = sp_playlistcontainer_num_playlists(container); - for (int i=0 ; imutable_request() = req; SendMessage(message); return; } - sp_playlist_add_callbacks(pending_load.playlist_, &load_playlist_callbacks_, this); + sp_playlist_add_callbacks(pending_load.playlist_, &load_playlist_callbacks_, + this); pending_load_playlists_ << pending_load; PlaylistStateChangedForLoadPlaylist(pending_load.playlist_, this); } void SpotifyClient::SyncPlaylist(const pb::spotify::SyncPlaylistRequest& req) { - sp_playlist* playlist = GetPlaylist(req.request().type(), req.request().user_playlist_index()); + sp_playlist* playlist = + GetPlaylist(req.request().type(), req.request().user_playlist_index()); // The playlist should already be loaded. sp_playlist_set_offline_mode(session_, playlist, req.offline_sync()); } -void SpotifyClient::PlaylistStateChangedForLoadPlaylist(sp_playlist* pl, void* userdata) { +void SpotifyClient::PlaylistStateChangedForLoadPlaylist(sp_playlist* pl, + void* userdata) { SpotifyClient* me = reinterpret_cast(userdata); // If the playlist isn't loaded yet we have to wait @@ -500,7 +524,7 @@ void SpotifyClient::PlaylistStateChangedForLoadPlaylist(sp_playlist* pl, void* u // Find this playlist's pending load object int pending_load_index = -1; PendingLoadPlaylist* pending_load = nullptr; - for (int i=0 ; ipending_load_playlists_.count() ; ++i) { + for (int i = 0; i < me->pending_load_playlists_.count(); ++i) { if (me->pending_load_playlists_[i].playlist_ == pl) { pending_load_index = i; pending_load = &me->pending_load_playlists_[i]; @@ -516,7 +540,7 @@ void SpotifyClient::PlaylistStateChangedForLoadPlaylist(sp_playlist* pl, void* u // If the playlist was just loaded then get all its tracks and ref them if (pending_load->tracks_.isEmpty()) { const int count = sp_playlist_num_tracks(pl); - for (int i=0 ; itracks_ << track; @@ -524,7 +548,7 @@ void SpotifyClient::PlaylistStateChangedForLoadPlaylist(sp_playlist* pl, void* u } // If any of the tracks aren't loaded yet we have to wait - foreach (sp_track* track, pending_load->tracks_) { + foreach(sp_track * track, pending_load->tracks_) { if (!sp_track_is_loaded(track)) { qLog(Debug) << "One or more tracks aren't loaded yet, waiting"; return; @@ -533,17 +557,17 @@ void SpotifyClient::PlaylistStateChangedForLoadPlaylist(sp_playlist* pl, void* u // Everything is loaded so send the response protobuf and unref everything. pb::spotify::Message message; - pb::spotify::LoadPlaylistResponse* response = message.mutable_load_playlist_response(); + pb::spotify::LoadPlaylistResponse* response = + message.mutable_load_playlist_response(); // For some reason, we receive the starred tracks in reverse order but not // other playlists. if (pending_load->request_.type() == pb::spotify::Starred) { - std::reverse(pending_load->tracks_.begin(), - pending_load->tracks_.end()); + std::reverse(pending_load->tracks_.begin(), pending_load->tracks_.end()); } *response->mutable_request() = pending_load->request_; - foreach (sp_track* track, pending_load->tracks_) { + foreach(sp_track * track, pending_load->tracks_) { me->ConvertTrack(track, response->add_track()); sp_track_release(track); } @@ -557,7 +581,8 @@ void SpotifyClient::PlaylistStateChangedForLoadPlaylist(sp_playlist* pl, void* u me->pending_load_playlists_.removeAt(pending_load_index); } -void SpotifyClient::PlaylistStateChangedForGetPlaylists(sp_playlist* pl, void* userdata) { +void SpotifyClient::PlaylistStateChangedForGetPlaylists(sp_playlist* pl, + void* userdata) { SpotifyClient* me = reinterpret_cast(userdata); me->SendPlaylistList(); @@ -576,15 +601,14 @@ void SpotifyClient::ConvertTrack(sp_track* track, pb::spotify::Track* pb) { pb->set_track(sp_track_index(track)); // Album art - const QByteArray art_id( - reinterpret_cast( - sp_album_cover(sp_track_album(track), SP_IMAGE_SIZE_LARGE)), - kSpotifyImageIDSize); + const QByteArray art_id(reinterpret_cast(sp_album_cover( + sp_track_album(track), SP_IMAGE_SIZE_LARGE)), + kSpotifyImageIDSize); const QString art_id_b64 = QString::fromAscii(art_id.toBase64()); pb->set_album_art_id(DataCommaSizeFromQString(art_id_b64)); // Artists - for (int i=0 ; iadd_artist(sp_artist_name(sp_track_artist(track, i))); } @@ -613,8 +637,8 @@ void SpotifyClient::ConvertAlbum(sp_album* album, pb::spotify::Track* pb) { // Album art const QByteArray art_id( - reinterpret_cast(sp_album_cover(album, SP_IMAGE_SIZE_LARGE)), - kSpotifyImageIDSize); + reinterpret_cast(sp_album_cover(album, SP_IMAGE_SIZE_LARGE)), + kSpotifyImageIDSize); const QString art_id_b64 = QString::fromAscii(art_id.toBase64()); pb->set_album_art_id(DataCommaSizeFromQString(art_id_b64)); @@ -627,25 +651,29 @@ void SpotifyClient::ConvertAlbum(sp_album* album, pb::spotify::Track* pb) { pb->set_uri(uri); } -void SpotifyClient::ConvertAlbumBrowse(sp_albumbrowse* browse, pb::spotify::Track* pb) { +void SpotifyClient::ConvertAlbumBrowse(sp_albumbrowse* browse, + pb::spotify::Track* pb) { pb->set_track(sp_albumbrowse_num_tracks(browse)); } void SpotifyClient::MetadataUpdatedCallback(sp_session* session) { - SpotifyClient* me = reinterpret_cast(sp_session_userdata(session)); + SpotifyClient* me = + reinterpret_cast(sp_session_userdata(session)); - foreach (const PendingLoadPlaylist& load, me->pending_load_playlists_) { + foreach(const PendingLoadPlaylist & load, me->pending_load_playlists_) { PlaylistStateChangedForLoadPlaylist(load.playlist_, me); } - foreach (const PendingPlaybackRequest& playback, me->pending_playback_requests_) { + foreach(const PendingPlaybackRequest & playback, + me->pending_playback_requests_) { me->TryPlaybackAgain(playback); } } -int SpotifyClient::MusicDeliveryCallback( - sp_session* session, const sp_audioformat* format, - const void* frames, int num_frames) { - SpotifyClient* me = reinterpret_cast(sp_session_userdata(session)); +int SpotifyClient::MusicDeliveryCallback(sp_session* session, + const sp_audioformat* format, + const void* frames, int num_frames) { + SpotifyClient* me = + reinterpret_cast(sp_session_userdata(session)); if (!me->media_pipeline_) { return 0; @@ -668,21 +696,23 @@ int SpotifyClient::MusicDeliveryCallback( return 0; } - me->media_pipeline_->WriteData( - reinterpret_cast(frames), - num_frames * format->channels * 2); + me->media_pipeline_->WriteData(reinterpret_cast(frames), + num_frames * format->channels * 2); return num_frames; } void SpotifyClient::EndOfTrackCallback(sp_session* session) { - SpotifyClient* me = reinterpret_cast(sp_session_userdata(session)); + SpotifyClient* me = + reinterpret_cast(sp_session_userdata(session)); me->media_pipeline_.reset(); } -void SpotifyClient::StreamingErrorCallback(sp_session* session, sp_error error) { - SpotifyClient* me = reinterpret_cast(sp_session_userdata(session)); +void SpotifyClient::StreamingErrorCallback(sp_session* session, + sp_error error) { + SpotifyClient* me = + reinterpret_cast(sp_session_userdata(session)); me->media_pipeline_.reset(); @@ -690,11 +720,13 @@ void SpotifyClient::StreamingErrorCallback(sp_session* session, sp_error error) me->SendPlaybackError(QString::fromUtf8(sp_error_message(error))); } -void SpotifyClient::ConnectionErrorCallback(sp_session* session, sp_error error) { +void SpotifyClient::ConnectionErrorCallback(sp_session* session, + sp_error error) { qLog(Debug) << Q_FUNC_INFO << sp_error_message(error); } -void SpotifyClient::UserMessageCallback(sp_session* session, const char* message) { +void SpotifyClient::UserMessageCallback(sp_session* session, + const char* message) { qLog(Debug) << Q_FUNC_INFO << message; } @@ -707,7 +739,8 @@ void SpotifyClient::StopPlaybackCallback(sp_session* session) { } void SpotifyClient::OfflineStatusUpdatedCallback(sp_session* session) { - SpotifyClient* me = reinterpret_cast(sp_session_userdata(session)); + SpotifyClient* me = + reinterpret_cast(sp_session_userdata(session)); sp_playlistcontainer* container = sp_session_playlistcontainer(session); if (!container) { qLog(Warning) << "sp_session_playlistcontainer returned nullptr"; @@ -716,8 +749,9 @@ void SpotifyClient::OfflineStatusUpdatedCallback(sp_session* session) { const int count = sp_playlistcontainer_num_playlists(container); - for (int i=0 ; imutable_request()->set_type(type); if (index != -1) { progress->mutable_request()->set_user_playlist_index(index); @@ -762,7 +797,7 @@ void SpotifyClient::SendDownloadProgress( int SpotifyClient::GetDownloadProgress(sp_playlist* playlist) { sp_playlist_offline_status status = - sp_playlist_get_offline_status(session_, playlist); + sp_playlist_get_offline_status(session_, playlist); switch (status) { case SP_PLAYLIST_OFFLINE_STATUS_NO: return -1; @@ -864,14 +899,14 @@ void SpotifyClient::LoadImage(const QString& id_b64) { PendingImageRequest pending_load; pending_load.id_ = id; pending_load.id_b64_ = id_b64; - pending_load.image_ = sp_image_create(session_, - reinterpret_cast(id.constData())); + pending_load.image_ = + sp_image_create(session_, reinterpret_cast(id.constData())); pending_image_requests_ << pending_load; if (!image_callbacks_registered_[pending_load.image_]) { sp_image_add_load_callback(pending_load.image_, &ImageLoaded, this); } - image_callbacks_registered_[pending_load.image_] ++; + image_callbacks_registered_[pending_load.image_]++; TryImageAgain(pending_load.image_); } @@ -885,7 +920,7 @@ void SpotifyClient::TryImageAgain(sp_image* image) { // Find the pending request for this image int index = -1; PendingImageRequest* req = nullptr; - for (int i=0 ; i(userdata); - if (!me->pending_album_browses_.contains(result)) - return; + if (!me->pending_album_browses_.contains(result)) return; QString uri = me->pending_album_browses_.take(result); pb::spotify::Message message; - pb::spotify::BrowseAlbumResponse* msg = message.mutable_browse_album_response(); + pb::spotify::BrowseAlbumResponse* msg = + message.mutable_browse_album_response(); msg->set_uri(DataCommaSizeFromQString(uri)); const int count = sp_albumbrowse_num_tracks(result); - for (int i=0 ; iConvertTrack(sp_albumbrowse_track(result, i), msg->add_track()); } @@ -970,32 +1006,32 @@ void SpotifyClient::AlbumBrowseComplete(sp_albumbrowse* result, void* userdata) sp_albumbrowse_release(result); } -void SpotifyClient::BrowseToplist(const pb::spotify::BrowseToplistRequest& req) { +void SpotifyClient::BrowseToplist( + const pb::spotify::BrowseToplistRequest& req) { sp_toplistbrowse* browse = sp_toplistbrowse_create( - session_, - SP_TOPLIST_TYPE_TRACKS, // TODO: Support albums and artists. - SP_TOPLIST_REGION_EVERYWHERE, // TODO: Support other regions. - nullptr, - &ToplistBrowseComplete, - this); + session_, SP_TOPLIST_TYPE_TRACKS, // TODO: Support albums and artists. + SP_TOPLIST_REGION_EVERYWHERE, // TODO: Support other regions. + nullptr, &ToplistBrowseComplete, this); pending_toplist_browses_[browse] = req; } -void SpotifyClient::ToplistBrowseComplete(sp_toplistbrowse* result, void* userdata) { +void SpotifyClient::ToplistBrowseComplete(sp_toplistbrowse* result, + void* userdata) { SpotifyClient* me = reinterpret_cast(userdata); qLog(Debug) << "Toplist browse request took:" - << sp_toplistbrowse_backend_request_duration(result) - << "ms"; + << sp_toplistbrowse_backend_request_duration(result) << "ms"; if (!me->pending_toplist_browses_.contains(result)) { return; } - const pb::spotify::BrowseToplistRequest& request = me->pending_toplist_browses_.take(result); + const pb::spotify::BrowseToplistRequest& request = + me->pending_toplist_browses_.take(result); pb::spotify::Message message; - pb::spotify::BrowseToplistResponse* msg = message.mutable_browse_toplist_response(); + pb::spotify::BrowseToplistResponse* msg = + message.mutable_browse_toplist_response(); msg->mutable_request()->CopyFrom(request); const int count = sp_toplistbrowse_num_tracks(result); diff --git a/ext/clementine-spotifyblob/spotifyclient.h b/ext/clementine-spotifyblob/spotifyclient.h index 300695aa1..47afbfd3b 100644 --- a/ext/clementine-spotifyblob/spotifyclient.h +++ b/ext/clementine-spotifyblob/spotifyclient.h @@ -18,7 +18,6 @@ // it is used by the Spotify blob which links against libspotify and is not GPL // compatible. - #ifndef SPOTIFYCLIENT_H #define SPOTIFYCLIENT_H @@ -39,7 +38,7 @@ class ResponseMessage; class SpotifyClient : public AbstractMessageHandler { Q_OBJECT -public: + public: SpotifyClient(QObject* parent = 0); ~SpotifyClient(); @@ -48,14 +47,14 @@ public: void Init(quint16 port); -protected: + protected: void MessageArrived(const pb::spotify::Message& message); void DeviceClosed(); -private slots: + private slots: void ProcessEvents(); -private: + private: void SendLoginCompleted(bool success, const QString& error, pb::spotify::LoginResponse_Error error_code); void SendPlaybackError(const QString& error); @@ -64,49 +63,59 @@ private: // Spotify session callbacks. static void SP_CALLCONV LoggedInCallback(sp_session* session, sp_error error); static void SP_CALLCONV NotifyMainThreadCallback(sp_session* session); - static void SP_CALLCONV LogMessageCallback(sp_session* session, const char* data); - static void SP_CALLCONV SearchCompleteCallback(sp_search* result, void* userdata); + static void SP_CALLCONV + LogMessageCallback(sp_session* session, const char* data); + static void SP_CALLCONV + SearchCompleteCallback(sp_search* result, void* userdata); static void SP_CALLCONV MetadataUpdatedCallback(sp_session* session); - static int SP_CALLCONV MusicDeliveryCallback( - sp_session* session, const sp_audioformat* format, - const void* frames, int num_frames); + static int SP_CALLCONV + MusicDeliveryCallback(sp_session* session, const sp_audioformat* format, + const void* frames, int num_frames); static void SP_CALLCONV EndOfTrackCallback(sp_session* session); - static void SP_CALLCONV StreamingErrorCallback(sp_session* session, sp_error error); + static void SP_CALLCONV + StreamingErrorCallback(sp_session* session, sp_error error); static void SP_CALLCONV OfflineStatusUpdatedCallback(sp_session* session); - static void SP_CALLCONV ConnectionErrorCallback(sp_session* session, sp_error error); - static void SP_CALLCONV UserMessageCallback(sp_session* session, const char* message); + static void SP_CALLCONV + ConnectionErrorCallback(sp_session* session, sp_error error); + static void SP_CALLCONV + UserMessageCallback(sp_session* session, const char* message); static void SP_CALLCONV StartPlaybackCallback(sp_session* session); static void SP_CALLCONV StopPlaybackCallback(sp_session* session); // Spotify playlist container callbacks. - static void SP_CALLCONV PlaylistAddedCallback( - sp_playlistcontainer* pc, sp_playlist* playlist, - int position, void* userdata); - static void SP_CALLCONV PlaylistRemovedCallback( - sp_playlistcontainer* pc, sp_playlist* playlist, - int position, void* userdata); - static void SP_CALLCONV PlaylistMovedCallback( - sp_playlistcontainer* pc, sp_playlist* playlist, - int position, int new_position, void* userdata); - static void SP_CALLCONV PlaylistContainerLoadedCallback( - sp_playlistcontainer* pc, void* userdata); + static void SP_CALLCONV PlaylistAddedCallback(sp_playlistcontainer* pc, + sp_playlist* playlist, + int position, void* userdata); + static void SP_CALLCONV PlaylistRemovedCallback(sp_playlistcontainer* pc, + sp_playlist* playlist, + int position, void* userdata); + static void SP_CALLCONV + PlaylistMovedCallback(sp_playlistcontainer* pc, sp_playlist* playlist, + int position, int new_position, void* userdata); + static void SP_CALLCONV + PlaylistContainerLoadedCallback(sp_playlistcontainer* pc, void* userdata); // Spotify playlist callbacks - when loading the list of playlists // initially - static void SP_CALLCONV PlaylistStateChangedForGetPlaylists(sp_playlist* pl, void* userdata); + static void SP_CALLCONV + PlaylistStateChangedForGetPlaylists(sp_playlist* pl, void* userdata); // Spotify playlist callbacks - when loading a playlist - static void SP_CALLCONV PlaylistStateChangedForLoadPlaylist(sp_playlist* pl, void* userdata); + static void SP_CALLCONV + PlaylistStateChangedForLoadPlaylist(sp_playlist* pl, void* userdata); // Spotify image callbacks. static void SP_CALLCONV ImageLoaded(sp_image* image, void* userdata); // Spotify album browse callbacks. - static void SP_CALLCONV SearchAlbumBrowseComplete(sp_albumbrowse* result, void* userdata); - static void SP_CALLCONV AlbumBrowseComplete(sp_albumbrowse* result, void* userdata); + static void SP_CALLCONV + SearchAlbumBrowseComplete(sp_albumbrowse* result, void* userdata); + static void SP_CALLCONV + AlbumBrowseComplete(sp_albumbrowse* result, void* userdata); // Spotify toplist browse callbacks. - static void SP_CALLCONV ToplistBrowseComplete(sp_toplistbrowse* result, void* userdata); + static void SP_CALLCONV + ToplistBrowseComplete(sp_toplistbrowse* result, void* userdata); // Request handlers. void Login(const pb::spotify::LoginRequest& req); @@ -129,7 +138,7 @@ private: // Gets the appropriate sp_playlist* but does not load it. sp_playlist* GetPlaylist(pb::spotify::PlaylistType type, int user_index); -private: + private: struct PendingLoadPlaylist { pb::spotify::LoadPlaylistRequest request_; sp_playlist* playlist_; @@ -142,7 +151,7 @@ private: sp_link* link_; sp_track* track_; - bool operator ==(const PendingPlaybackRequest& other) const { + bool operator==(const PendingPlaybackRequest& other) const { return request_.track_uri() == other.request_.track_uri() && request_.media_port() == other.request_.media_port(); } @@ -157,7 +166,8 @@ private: void TryPlaybackAgain(const PendingPlaybackRequest& req); void TryImageAgain(sp_image* image); int GetDownloadProgress(sp_playlist* playlist); - void SendDownloadProgress(pb::spotify::PlaylistType type, int index, int download_progress); + void SendDownloadProgress(pb::spotify::PlaylistType type, int index, + int download_progress); QByteArray api_key_; @@ -178,7 +188,8 @@ private: QMap image_callbacks_registered_; QMap pending_searches_; QMap pending_album_browses_; - QMap pending_toplist_browses_; + QMap + pending_toplist_browses_; QMap > pending_search_album_browses_; QMap pending_search_album_browse_responses_; @@ -186,4 +197,4 @@ private: QScopedPointer media_pipeline_; }; -#endif // SPOTIFYCLIENT_H +#endif // SPOTIFYCLIENT_H diff --git a/ext/clementine-spotifyblob/spotifykey.h b/ext/clementine-spotifyblob/spotifykey.h index b4f6c13f4..22bedcb38 100644 --- a/ext/clementine-spotifyblob/spotifykey.h +++ b/ext/clementine-spotifyblob/spotifykey.h @@ -18,16 +18,20 @@ // it is used by the Spotify blob which links against libspotify and is not GPL // compatible. - // The Spotify terms of service require that application keys are not // accessible to third parties. Therefore this application key is heavily // encrypted here in the source to prevent third parties from viewing it. // It is most definitely not base64 encoded. static const char* kSpotifyApiKey = - "AVlOrvJkKx8T+LEsCk+Kyl24I0MSsjohZAtMFzm2O5Lms1bmAWFWgdZaHkpypzSJPmSd+Wi50wwg" - "JwVCU0sq4Lep1zB4t6Z8h26NK6+z8gmkHVkV9DRPkRgebcUkWTDTflwVPKWF4+gdRjUwprsqBw6O" - "iofRLJzeKaxbmaUGqkSkxVLOiXC9lxylNq6ju7Q7uY8u8XkDUsVM3YIxiWy2+EM7I/lhatzT9xrq" - "rxHe2lg7CzOwF5kuFdwgmi8MQ72xTYXIKnNlOry/hJDlN9lKxkbUBLh+pzbYvO92S2fYKK5PAHvX" - "5+SmSBGbh6dlpHeCGqb8MPdaeZ5I1YxMcDkxa2+tbLA/Muat7gKA9u57TFCtYjun/u/i/ONwdBIQ" - "rePzXZjipO32kYmQAiCkN1p8sgQEcF43QxaVwXGo2X0rRnJf"; + "AVlOrvJkKx8T+LEsCk+Kyl24I0MSsjohZAtMFzm2O5Lms1bmAWFWgdZaHkpypzSJPmSd+" + "Wi50wwg" + "JwVCU0sq4Lep1zB4t6Z8h26NK6+z8gmkHVkV9DRPkRgebcUkWTDTflwVPKWF4+" + "gdRjUwprsqBw6O" + "iofRLJzeKaxbmaUGqkSkxVLOiXC9lxylNq6ju7Q7uY8u8XkDUsVM3YIxiWy2+EM7I/" + "lhatzT9xrq" + "rxHe2lg7CzOwF5kuFdwgmi8MQ72xTYXIKnNlOry/" + "hJDlN9lKxkbUBLh+pzbYvO92S2fYKK5PAHvX" + "5+SmSBGbh6dlpHeCGqb8MPdaeZ5I1YxMcDkxa2+tbLA/Muat7gKA9u57TFCtYjun/u/i/" + "ONwdBIQ" + "rePzXZjipO32kYmQAiCkN1p8sgQEcF43QxaVwXGo2X0rRnJf"; diff --git a/ext/clementine-tagreader/main.cpp b/ext/clementine-tagreader/main.cpp index bebc58e7b..c5e5cfeb1 100644 --- a/ext/clementine-tagreader/main.cpp +++ b/ext/clementine-tagreader/main.cpp @@ -31,15 +31,17 @@ int main(int argc, char** argv) { QStringList args(a.arguments()); if (args.count() != 2) { - std::cerr << "This program is used internally by Clementine to parse tags in music files\n" - "without exposing the whole application to crashes caused by malformed\n" + std::cerr << "This program is used internally by Clementine to parse tags " + "in music files\n" + "without exposing the whole application to crashes caused by " + "malformed\n" "files. It is not meant to be run on its own.\n"; return 1; } // Seed random number generator timeval time; - gettimeofday(&time,nullptr); + gettimeofday(&time, nullptr); qsrand((time.tv_sec * 1000) + (time.tv_usec / 1000)); logging::Init(); diff --git a/ext/clementine-tagreader/tagreaderworker.cpp b/ext/clementine-tagreader/tagreaderworker.cpp index eb19dd1b5..e4b0b2c9b 100644 --- a/ext/clementine-tagreader/tagreaderworker.cpp +++ b/ext/clementine-tagreader/tagreaderworker.cpp @@ -24,11 +24,8 @@ #include #include - TagReaderWorker::TagReaderWorker(QIODevice* socket, QObject* parent) - : AbstractMessageHandler(socket, parent) -{ -} + : AbstractMessageHandler(socket, parent) {} void TagReaderWorker::MessageArrived(const pb::tagreader::Message& message) { pb::tagreader::Message reply; @@ -42,42 +39,44 @@ void TagReaderWorker::MessageArrived(const pb::tagreader::Message& message) { #endif if (message.has_read_file_request()) { - tag_reader_.ReadFile(QStringFromStdString(message.read_file_request().filename()), - reply.mutable_read_file_response()->mutable_metadata()); + tag_reader_.ReadFile( + QStringFromStdString(message.read_file_request().filename()), + reply.mutable_read_file_response()->mutable_metadata()); } else if (message.has_save_file_request()) { - reply.mutable_save_file_response()->set_success( - tag_reader_.SaveFile(QStringFromStdString(message.save_file_request().filename()), - message.save_file_request().metadata())); + reply.mutable_save_file_response()->set_success(tag_reader_.SaveFile( + QStringFromStdString(message.save_file_request().filename()), + message.save_file_request().metadata())); } else if (message.has_save_song_statistics_to_file_request()) { reply.mutable_save_song_statistics_to_file_response()->set_success( tag_reader_.SaveSongStatisticsToFile( - QStringFromStdString(message.save_song_statistics_to_file_request().filename()), + QStringFromStdString( + message.save_song_statistics_to_file_request().filename()), message.save_song_statistics_to_file_request().metadata())); } else if (message.has_save_song_rating_to_file_request()) { reply.mutable_save_song_rating_to_file_response()->set_success( tag_reader_.SaveSongRatingToFile( - QStringFromStdString(message.save_song_rating_to_file_request().filename()), + QStringFromStdString( + message.save_song_rating_to_file_request().filename()), message.save_song_rating_to_file_request().metadata())); } else if (message.has_is_media_file_request()) { - reply.mutable_is_media_file_response()->set_success( - tag_reader_.IsMediaFile(QStringFromStdString(message.is_media_file_request().filename()))); + reply.mutable_is_media_file_response()->set_success(tag_reader_.IsMediaFile( + QStringFromStdString(message.is_media_file_request().filename()))); } else if (message.has_load_embedded_art_request()) { QByteArray data = tag_reader_.LoadEmbeddedArt( - QStringFromStdString(message.load_embedded_art_request().filename())); - reply.mutable_load_embedded_art_response()->set_data( - data.constData(), data.size()); + QStringFromStdString(message.load_embedded_art_request().filename())); + reply.mutable_load_embedded_art_response()->set_data(data.constData(), + data.size()); } else if (message.has_read_cloud_file_request()) { #ifdef HAVE_GOOGLE_DRIVE const pb::tagreader::ReadCloudFileRequest& req = message.read_cloud_file_request(); if (!tag_reader_.ReadCloudFile( - QUrl::fromEncoded(QByteArray(req.download_url().data(), - req.download_url().size())), - QStringFromStdString(req.title()), - req.size(), - QStringFromStdString(req.mime_type()), - QStringFromStdString(req.authorisation_header()), - reply.mutable_read_cloud_file_response()->mutable_metadata())) { + QUrl::fromEncoded(QByteArray(req.download_url().data(), + req.download_url().size())), + QStringFromStdString(req.title()), req.size(), + QStringFromStdString(req.mime_type()), + QStringFromStdString(req.authorisation_header()), + reply.mutable_read_cloud_file_response()->mutable_metadata())) { reply.mutable_read_cloud_file_response()->clear_metadata(); } #endif @@ -86,10 +85,8 @@ void TagReaderWorker::MessageArrived(const pb::tagreader::Message& message) { SendReply(message, &reply); } - void TagReaderWorker::DeviceClosed() { AbstractMessageHandler::DeviceClosed(); qApp->exit(); } - diff --git a/ext/clementine-tagreader/tagreaderworker.h b/ext/clementine-tagreader/tagreaderworker.h index a2e6eea0a..796671d24 100644 --- a/ext/clementine-tagreader/tagreaderworker.h +++ b/ext/clementine-tagreader/tagreaderworker.h @@ -24,15 +24,15 @@ #include "core/messagehandler.h" class TagReaderWorker : public AbstractMessageHandler { -public: + public: TagReaderWorker(QIODevice* socket, QObject* parent = NULL); -protected: + protected: void MessageArrived(const pb::tagreader::Message& message); void DeviceClosed(); -private: + private: TagReader tag_reader_; }; -#endif // TAGREADERWORKER_H +#endif // TAGREADERWORKER_H diff --git a/ext/libclementine-common/core/closure.cpp b/ext/libclementine-common/core/closure.cpp index e2c27c13f..bd943c0eb 100644 --- a/ext/libclementine-common/core/closure.cpp +++ b/ext/libclementine-common/core/closure.cpp @@ -23,34 +23,22 @@ namespace _detail { -ClosureBase::ClosureBase(ObjectHelper* helper) - : helper_(helper) { -} +ClosureBase::ClosureBase(ObjectHelper* helper) : helper_(helper) {} -ClosureBase::~ClosureBase() { -} +ClosureBase::~ClosureBase() {} -CallbackClosure::CallbackClosure( - QObject* sender, - const char* signal, - std::function callback) - : ClosureBase(new ObjectHelper(sender, signal, this)), - callback_(callback) { -} +CallbackClosure::CallbackClosure(QObject* sender, const char* signal, + std::function callback) + : ClosureBase(new ObjectHelper(sender, signal, this)), + callback_(callback) {} -void CallbackClosure::Invoke() { - callback_(); -} +void CallbackClosure::Invoke() { callback_(); } -ObjectHelper* ClosureBase::helper() const { - return helper_; -} +ObjectHelper* ClosureBase::helper() const { return helper_; } -ObjectHelper::ObjectHelper( - QObject* sender, - const char* signal, - ClosureBase* closure) - : closure_(closure) { +ObjectHelper::ObjectHelper(QObject* sender, const char* signal, + ClosureBase* closure) + : closure_(closure) { connect(sender, signal, SLOT(Invoked())); connect(sender, SIGNAL(destroyed()), SLOT(deleteLater())); } @@ -64,12 +52,9 @@ void Unpack(QList*) {} } // namespace _detail -_detail::ClosureBase* NewClosure( - QObject* sender, - const char* signal, - std::function callback) { - return new _detail::CallbackClosure( - sender, signal, callback); +_detail::ClosureBase* NewClosure(QObject* sender, const char* signal, + std::function callback) { + return new _detail::CallbackClosure(sender, signal, callback); } void DoAfter(QObject* receiver, const char* slot, int msec) { diff --git a/ext/libclementine-common/core/closure.h b/ext/libclementine-common/core/closure.h index bb874d05f..9b41a332e 100644 --- a/ext/libclementine-common/core/closure.h +++ b/ext/libclementine-common/core/closure.h @@ -52,10 +52,7 @@ class ClosureBase { class ObjectHelper : public QObject { Q_OBJECT public: - ObjectHelper( - QObject* parent, - const char* signal, - ClosureBase* closure); + ObjectHelper(QObject* parent, const char* signal, ClosureBase* closure); private slots: void Invoked(); @@ -76,7 +73,8 @@ void Unpack(QList* list, const Arg& arg) { } template -void Unpack(QList* list, const Head& head, const Tail&... tail) { +void Unpack(QList* list, const Head& head, + const Tail&... tail) { Unpack(list, head); Unpack(list, tail...); } @@ -84,45 +82,39 @@ void Unpack(QList* list, const Head& head, const Tail&... tail template class Closure : public ClosureBase { public: - Closure( - QObject* sender, - const char* signal, - QObject* receiver, - const char* slot, - const Args&... args) - : ClosureBase(new ObjectHelper(sender, signal, this)), - // std::bind is the easiest way to store an argument list. - function_(std::bind(&Closure::Call, this, args...)), - receiver_(receiver) { + Closure(QObject* sender, const char* signal, QObject* receiver, + const char* slot, const Args&... args) + : ClosureBase(new ObjectHelper(sender, signal, this)), + // std::bind is the easiest way to store an argument list. + function_(std::bind(&Closure::Call, this, args...)), + receiver_(receiver) { const QMetaObject* meta_receiver = receiver->metaObject(); QByteArray normalised_slot = QMetaObject::normalizedSignature(slot + 1); const int index = meta_receiver->indexOfSlot(normalised_slot.constData()); Q_ASSERT(index != -1); slot_ = meta_receiver->method(index); - QObject::connect(receiver_, SIGNAL(destroyed()), helper_, SLOT(deleteLater())); + QObject::connect(receiver_, SIGNAL(destroyed()), helper_, + SLOT(deleteLater())); } - virtual void Invoke() { - function_(); - } + virtual void Invoke() { function_(); } private: void Call(const Args&... args) { QList arg_list; Unpack(&arg_list, args...); - slot_.invoke( - receiver_, - arg_list.size() > 0 ? arg_list[0] : QGenericArgument(), - arg_list.size() > 1 ? arg_list[1] : QGenericArgument(), - arg_list.size() > 2 ? arg_list[2] : QGenericArgument(), - arg_list.size() > 3 ? arg_list[3] : QGenericArgument(), - arg_list.size() > 4 ? arg_list[4] : QGenericArgument(), - arg_list.size() > 5 ? arg_list[5] : QGenericArgument(), - arg_list.size() > 6 ? arg_list[6] : QGenericArgument(), - arg_list.size() > 7 ? arg_list[7] : QGenericArgument(), - arg_list.size() > 8 ? arg_list[8] : QGenericArgument(), - arg_list.size() > 9 ? arg_list[9] : QGenericArgument()); + slot_.invoke(receiver_, + arg_list.size() > 0 ? arg_list[0] : QGenericArgument(), + arg_list.size() > 1 ? arg_list[1] : QGenericArgument(), + arg_list.size() > 2 ? arg_list[2] : QGenericArgument(), + arg_list.size() > 3 ? arg_list[3] : QGenericArgument(), + arg_list.size() > 4 ? arg_list[4] : QGenericArgument(), + arg_list.size() > 5 ? arg_list[5] : QGenericArgument(), + arg_list.size() > 6 ? arg_list[6] : QGenericArgument(), + arg_list.size() > 7 ? arg_list[7] : QGenericArgument(), + arg_list.size() > 8 ? arg_list[8] : QGenericArgument(), + arg_list.size() > 9 ? arg_list[9] : QGenericArgument()); } std::function function_; @@ -133,20 +125,10 @@ class Closure : public ClosureBase { template class SharedClosure : public Closure { public: - SharedClosure( - QSharedPointer sender, - const char* signal, - QObject* receiver, - const char* slot, - const Args&... args) - : Closure( - sender.data(), - signal, - receiver, - slot, - args...), - data_(sender) { - } + SharedClosure(QSharedPointer sender, const char* signal, QObject* receiver, + const char* slot, const Args&... args) + : Closure(sender.data(), signal, receiver, slot, args...), + data_(sender) {} private: QSharedPointer data_; @@ -154,10 +136,8 @@ class SharedClosure : public Closure { class CallbackClosure : public ClosureBase { public: - CallbackClosure( - QObject* sender, - const char* signal, - std::function callback); + CallbackClosure(QObject* sender, const char* signal, + std::function callback); virtual void Invoke(); @@ -168,61 +148,45 @@ class CallbackClosure : public ClosureBase { } // namespace _detail template -_detail::ClosureBase* NewClosure( - QObject* sender, - const char* signal, - QObject* receiver, - const char* slot, - const Args&... args) { - return new _detail::Closure( - sender, signal, receiver, slot, args...); +_detail::ClosureBase* NewClosure(QObject* sender, const char* signal, + QObject* receiver, const char* slot, + const Args&... args) { + return new _detail::Closure(sender, signal, receiver, slot, args...); } // QSharedPointer variant template -_detail::ClosureBase* NewClosure( - QSharedPointer sender, - const char* signal, - QObject* receiver, - const char* slot, - const Args&... args) { - return new _detail::SharedClosure( - sender, signal, receiver, slot, args...); +_detail::ClosureBase* NewClosure(QSharedPointer sender, const char* signal, + QObject* receiver, const char* slot, + const Args&... args) { + return new _detail::SharedClosure(sender, signal, receiver, slot, + args...); } -_detail::ClosureBase* NewClosure( - QObject* sender, - const char* signal, - std::function callback); +_detail::ClosureBase* NewClosure(QObject* sender, const char* signal, + std::function callback); template -_detail::ClosureBase* NewClosure( - QObject* sender, - const char* signal, - std::function callback, - const Args&... args) { +_detail::ClosureBase* NewClosure(QObject* sender, const char* signal, + std::function callback, + const Args&... args) { return NewClosure(sender, signal, std::bind(callback, args...)); } template -_detail::ClosureBase* NewClosure( - QObject* sender, - const char* signal, - void (*callback)(Args...), - const Args&... args) { +_detail::ClosureBase* NewClosure(QObject* sender, const char* signal, + void (*callback)(Args...), + const Args&... args) { return NewClosure(sender, signal, std::bind(callback, args...)); } template -_detail::ClosureBase* NewClosure( - QObject* sender, - const char* signal, - T* receiver, Unused (T::*callback)(Args...), - const Args&... args) { +_detail::ClosureBase* NewClosure(QObject* sender, const char* signal, + T* receiver, Unused (T::*callback)(Args...), + const Args&... args) { return NewClosure(sender, signal, std::bind(callback, receiver, args...)); } - void DoAfter(QObject* receiver, const char* slot, int msec); void DoInAMinuteOrSo(QObject* receiver, const char* slot); diff --git a/ext/libclementine-common/core/concurrentrun.h b/ext/libclementine-common/core/concurrentrun.h index 58fc05577..81c0d8b7f 100644 --- a/ext/libclementine-common/core/concurrentrun.h +++ b/ext/libclementine-common/core/concurrentrun.h @@ -41,13 +41,13 @@ ThreadFunctor object and start it. */ - /* Base abstract classes ThreadFunctorBase and ThreadFunctor (for void and non-void result): */ -template -class ThreadFunctorBase : public QFutureInterface, public QRunnable { +template +class ThreadFunctorBase : public QFutureInterface, + public QRunnable { public: ThreadFunctorBase() {} @@ -68,10 +68,8 @@ class ThreadFunctorBase : public QFutureInterface, public QRunnable template class ThreadFunctor : public ThreadFunctorBase { public: - ThreadFunctor(std::function function, - Args... args) - : function_(std::bind(function, args...)) { - } + ThreadFunctor(std::function function, Args... args) + : function_(std::bind(function, args...)) {} virtual void run() { this->reportResult(function_()); @@ -84,12 +82,10 @@ class ThreadFunctor : public ThreadFunctorBase { // Partial specialisation for void return type. template -class ThreadFunctor : public ThreadFunctorBase { +class ThreadFunctor : public ThreadFunctorBase { public: - ThreadFunctor(std::function function, - Args... args) - : function_(std::bind(function, args...)) { - } + ThreadFunctor(std::function function, Args... args) + : function_(std::bind(function, args...)) {} virtual void run() { function_(); @@ -100,39 +96,33 @@ class ThreadFunctor : public ThreadFunctorBase { std::function function_; }; - /* Run functions */ namespace ConcurrentRun { - // Empty argument form. - template - QFuture Run( - QThreadPool* threadpool, - std::function function) { - return (new ThreadFunctor(function))->Start(threadpool); - } - - // Function object with arguments form. - template - QFuture Run( - QThreadPool* threadpool, - std::function function, - const Args&... args) { - return (new ThreadFunctor( - function, args...))->Start(threadpool); - } - - // Support passing C function pointers instead of function objects. - template - QFuture Run( - QThreadPool* threadpool, - ReturnType (*function) (Args...), - const Args&... args) { - return Run( - threadpool, std::function(function), args...); - } +// Empty argument form. +template +QFuture Run(QThreadPool* threadpool, + std::function function) { + return (new ThreadFunctor(function))->Start(threadpool); } -#endif // CONCURRENTRUN_H +// Function object with arguments form. +template +QFuture Run(QThreadPool* threadpool, + std::function function, + const Args&... args) { + return (new ThreadFunctor(function, args...)) + ->Start(threadpool); +} + +// Support passing C function pointers instead of function objects. +template +QFuture Run(QThreadPool* threadpool, + ReturnType (*function)(Args...), const Args&... args) { + return Run(threadpool, std::function(function), args...); +} +} + +#endif // CONCURRENTRUN_H diff --git a/ext/libclementine-common/core/logging.cpp b/ext/libclementine-common/core/logging.cpp index 51c4ed4f8..414615a15 100644 --- a/ext/libclementine-common/core/logging.cpp +++ b/ext/libclementine-common/core/logging.cpp @@ -33,7 +33,6 @@ #include "logging.h" - namespace logging { static Level sDefaultLevel = Level_Debug; @@ -46,18 +45,25 @@ static const char* kMessageHandlerMagic = "__logging_message__"; static const int kMessageHandlerMagicLength = strlen(kMessageHandlerMagic); static QtMsgHandler sOriginalMessageHandler = nullptr; - void GLog(const char* domain, int level, const char* message, void* user_data) { switch (level) { case G_LOG_FLAG_RECURSION: case G_LOG_FLAG_FATAL: case G_LOG_LEVEL_ERROR: - case G_LOG_LEVEL_CRITICAL: qLog(Error) << message; break; - case G_LOG_LEVEL_WARNING: qLog(Warning) << message; break; + case G_LOG_LEVEL_CRITICAL: + qLog(Error) << message; + break; + case G_LOG_LEVEL_WARNING: + qLog(Warning) << message; + break; case G_LOG_LEVEL_MESSAGE: - case G_LOG_LEVEL_INFO: qLog(Info) << message; break; + case G_LOG_LEVEL_INFO: + qLog(Info) << message; + break; case G_LOG_LEVEL_DEBUG: - default: qLog(Debug) << message; break; + default: + qLog(Debug) << message; + break; } } @@ -70,13 +76,19 @@ static void MessageHandler(QtMsgType type, const char* message) { Level level = Level_Debug; switch (type) { case QtFatalMsg: - case QtCriticalMsg: level = Level_Error; break; - case QtWarningMsg: level = Level_Warning; break; + case QtCriticalMsg: + level = Level_Error; + break; + case QtWarningMsg: + level = Level_Warning; + break; case QtDebugMsg: - default: level = Level_Debug; break; + default: + level = Level_Debug; + break; } - foreach (const QString& line, QString::fromLocal8Bit(message).split('\n')) { + foreach(const QString & line, QString::fromLocal8Bit(message).split('\n')) { CreateLogger(level, "unknown", -1) << line.toLocal8Bit().constData(); } @@ -85,7 +97,6 @@ static void MessageHandler(QtMsgType type, const char* message) { } } - void Init() { delete sClassLevels; delete sNullDevice; @@ -100,10 +111,9 @@ void Init() { } void SetLevels(const QString& levels) { - if (!sClassLevels) - return; + if (!sClassLevels) return; - foreach (const QString& item, levels.split(',')) { + foreach(const QString & item, levels.split(',')) { const QStringList class_level = item.split(':'); QString class_name; @@ -122,14 +132,14 @@ void SetLevels(const QString& levels) { } if (class_name.isEmpty() || class_name == "*") { - sDefaultLevel = (Level) level; + sDefaultLevel = (Level)level; } else { - sClassLevels->insert(class_name, (Level) level); + sClassLevels->insert(class_name, (Level)level); } } } -QString ParsePrettyFunction(const char * pretty_function) { +QString ParsePrettyFunction(const char* pretty_function) { // Get the class name out of the function name. QString class_name = pretty_function; const int paren = class_name.indexOf('('); @@ -144,7 +154,7 @@ QString ParsePrettyFunction(const char * pretty_function) { const int space = class_name.lastIndexOf(' '); if (space != -1) { - class_name = class_name.mid(space+1); + class_name = class_name.mid(space + 1); } return class_name; @@ -154,11 +164,21 @@ QDebug CreateLogger(Level level, const QString& class_name, int line) { // Map the level to a string const char* level_name = nullptr; switch (level) { - case Level_Debug: level_name = " DEBUG "; break; - case Level_Info: level_name = " INFO "; break; - case Level_Warning: level_name = " WARN "; break; - case Level_Error: level_name = " ERROR "; break; - case Level_Fatal: level_name = " FATAL "; break; + case Level_Debug: + level_name = " DEBUG "; + break; + case Level_Info: + level_name = " INFO "; + break; + case Level_Warning: + level_name = " WARN "; + break; + case Level_Error: + level_name = " ERROR "; + break; + case Level_Fatal: + level_name = " FATAL "; + break; } // Check the settings to see if we're meant to show or hide this message. @@ -182,9 +202,11 @@ QDebug CreateLogger(Level level, const QString& class_name, int line) { } QDebug ret(type); - ret.nospace() << kMessageHandlerMagic - << QDateTime::currentDateTime().toString("hh:mm:ss.zzz").toAscii().constData() - << level_name << function_line.leftJustified(32).toAscii().constData(); + ret.nospace() << kMessageHandlerMagic << QDateTime::currentDateTime() + .toString("hh:mm:ss.zzz") + .toAscii() + .constData() << level_name + << function_line.leftJustified(32).toAscii().constData(); return ret.space(); } @@ -192,10 +214,7 @@ QDebug CreateLogger(Level level, const QString& class_name, int line) { QString CXXDemangle(const QString& mangled_function) { int status; char* demangled_function = abi::__cxa_demangle( - mangled_function.toAscii().constData(), - nullptr, - nullptr, - &status); + mangled_function.toAscii().constData(), nullptr, nullptr, &status); if (status == 0) { QString ret = QString::fromAscii(demangled_function); free(demangled_function); @@ -232,8 +251,10 @@ QString DemangleSymbol(const QString& symbol) { void DumpStackTrace() { #ifdef Q_OS_UNIX void* callstack[128]; - int callstack_size = backtrace(reinterpret_cast(&callstack), sizeof(callstack)); - char** symbols = backtrace_symbols(reinterpret_cast(&callstack), callstack_size); + int callstack_size = + backtrace(reinterpret_cast(&callstack), sizeof(callstack)); + char** symbols = + backtrace_symbols(reinterpret_cast(&callstack), callstack_size); // Start from 1 to skip ourself. for (int i = 1; i < callstack_size; ++i) { qLog(Debug) << DemangleSymbol(QString::fromAscii(symbols[i])); @@ -244,4 +265,4 @@ void DumpStackTrace() { #endif } -} // namespace logging +} // namespace logging diff --git a/ext/libclementine-common/core/logging.h b/ext/libclementine-common/core/logging.h index 3c582cf73..8cba187ea 100644 --- a/ext/libclementine-common/core/logging.h +++ b/ext/libclementine-common/core/logging.h @@ -18,46 +18,47 @@ // it is used by the Spotify blob which links against libspotify and is not GPL // compatible. - #ifndef LOGGING_H #define LOGGING_H #include #ifdef QT_NO_DEBUG_STREAM -# define qLog(level) while (false) QNoDebug() +#define qLog(level) \ + while (false) QNoDebug() #else -# define qLog(level) \ - logging::CreateLogger(logging::Level_##level, \ - logging::ParsePrettyFunction(__PRETTY_FUNCTION__), __LINE__) +#define qLog(level) \ + logging::CreateLogger(logging::Level_##level, \ + logging::ParsePrettyFunction(__PRETTY_FUNCTION__), \ + __LINE__) #endif namespace logging { - class NullDevice : public QIODevice { - protected: - qint64 readData(char*, qint64) { return -1; } - qint64 writeData(const char*, qint64 len) { return len; } - }; +class NullDevice : public QIODevice { + protected: + qint64 readData(char*, qint64) { return -1; } + qint64 writeData(const char*, qint64 len) { return len; } +}; - enum Level { - Level_Fatal = -1, - Level_Error = 0, - Level_Warning, - Level_Info, - Level_Debug, - }; +enum Level { + Level_Fatal = -1, + Level_Error = 0, + Level_Warning, + Level_Info, + Level_Debug, +}; - void Init(); - void SetLevels(const QString& levels); +void Init(); +void SetLevels(const QString& levels); - void DumpStackTrace(); +void DumpStackTrace(); - QString ParsePrettyFunction(const char* pretty_function); - QDebug CreateLogger(Level level, const QString& class_name, int line); +QString ParsePrettyFunction(const char* pretty_function); +QDebug CreateLogger(Level level, const QString& class_name, int line); - void GLog(const char* domain, int level, const char* message, void* user_data); +void GLog(const char* domain, int level, const char* message, void* user_data); - extern const char* kDefaultLogLevels; +extern const char* kDefaultLogLevels; } -#endif // LOGGING_H +#endif // LOGGING_H diff --git a/ext/libclementine-common/core/messagehandler.cpp b/ext/libclementine-common/core/messagehandler.cpp index d0de5297e..1ea64929b 100644 --- a/ext/libclementine-common/core/messagehandler.cpp +++ b/ext/libclementine-common/core/messagehandler.cpp @@ -18,7 +18,6 @@ // it is used by the Spotify blob which links against libspotify and is not GPL // compatible. - #include "messagehandler.h" #include "core/logging.h" @@ -26,13 +25,13 @@ #include _MessageHandlerBase::_MessageHandlerBase(QIODevice* device, QObject* parent) - : QObject(parent), - device_(nullptr), - flush_abstract_socket_(nullptr), - flush_local_socket_(nullptr), - reading_protobuf_(false), - expected_length_(0), - is_device_closed_(false) { + : QObject(parent), + device_(nullptr), + flush_abstract_socket_(nullptr), + flush_local_socket_(nullptr), + reading_protobuf_(false), + expected_length_(0), + is_device_closed_(false) { if (device) { SetDevice(device); } diff --git a/ext/libclementine-common/core/messagehandler.h b/ext/libclementine-common/core/messagehandler.h index cd2ec285b..405334147 100644 --- a/ext/libclementine-common/core/messagehandler.h +++ b/ext/libclementine-common/core/messagehandler.h @@ -18,7 +18,6 @@ // it is used by the Spotify blob which links against libspotify and is not GPL // compatible. - #ifndef MESSAGEHANDLER_H #define MESSAGEHANDLER_H @@ -37,11 +36,8 @@ class QAbstractSocket; class QIODevice; class QLocalSocket; -#define QStringFromStdString(x) \ - QString::fromUtf8(x.data(), x.size()) -#define DataCommaSizeFromQString(x) \ - x.toUtf8().constData(), x.toUtf8().length() - +#define QStringFromStdString(x) QString::fromUtf8(x.data(), x.size()) +#define DataCommaSizeFromQString(x) x.toUtf8().constData(), x.toUtf8().length() // Reads and writes uint32 length encoded protobufs to a socket. // This base QObject is separate from AbstractMessageHandler because moc can't @@ -49,7 +45,7 @@ class QLocalSocket; class _MessageHandlerBase : public QObject { Q_OBJECT -public: + public: // device can be NULL, in which case you must call SetDevice before writing // any messages. _MessageHandlerBase(QIODevice* device, QObject* parent); @@ -59,16 +55,16 @@ public: // After this is true, messages cannot be sent to the handler any more. bool is_device_closed() const { return is_device_closed_; } -protected slots: + protected slots: void WriteMessage(const QByteArray& data); void DeviceReadyRead(); virtual void DeviceClosed(); -protected: + protected: virtual bool RawMessageArrived(const QByteArray& data) = 0; virtual void AbortAll() = 0; -protected: + protected: typedef bool (QAbstractSocket::*FlushAbstractSocket)(); typedef bool (QLocalSocket::*FlushLocalSocket)(); @@ -83,13 +79,12 @@ protected: bool is_device_closed_; }; - // Reads and writes uint32 length encoded MessageType messages to a socket. // You should subclass this and implement the MessageArrived(MessageType) // method. template class AbstractMessageHandler : public _MessageHandlerBase { -public: + public: AbstractMessageHandler(QIODevice* device, QObject* parent); ~AbstractMessageHandler() { AbortAll(); } @@ -113,7 +108,7 @@ public: // reply on the socket. Used on the worker side. void SendReply(const MessageType& request, MessageType* reply); -protected: + protected: // Called when a message is received from the socket. virtual void MessageArrived(const MessageType& message) {} @@ -121,19 +116,16 @@ protected: bool RawMessageArrived(const QByteArray& data); void AbortAll(); -private: + private: QMap pending_replies_; }; +template +AbstractMessageHandler::AbstractMessageHandler(QIODevice* device, + QObject* parent) + : _MessageHandlerBase(device, parent) {} -template -AbstractMessageHandler::AbstractMessageHandler( - QIODevice* device, QObject* parent) - : _MessageHandlerBase(device, parent) -{ -} - -template +template void AbstractMessageHandler::SendMessage(const MessageType& message) { Q_ASSERT(QThread::currentThread() == thread()); @@ -141,27 +133,28 @@ void AbstractMessageHandler::SendMessage(const MessageType& message) { WriteMessage(QByteArray(data.data(), data.size())); } -template +template void AbstractMessageHandler::SendMessageAsync(const MessageType& message) { std::string data = message.SerializeAsString(); - metaObject()->invokeMethod(this, "WriteMessage", Qt::QueuedConnection, - Q_ARG(QByteArray, QByteArray(data.data(), data.size()))); + metaObject()->invokeMethod( + this, "WriteMessage", Qt::QueuedConnection, + Q_ARG(QByteArray, QByteArray(data.data(), data.size()))); } -template +template void AbstractMessageHandler::SendRequest(ReplyType* reply) { pending_replies_[reply->id()] = reply; SendMessage(reply->request_message()); } -template +template void AbstractMessageHandler::SendReply(const MessageType& request, MessageType* reply) { reply->set_id(request.id()); SendMessage(*reply); } -template +template bool AbstractMessageHandler::RawMessageArrived(const QByteArray& data) { MessageType message; if (!message.ParseFromArray(data.constData(), data.size())) { @@ -180,14 +173,10 @@ bool AbstractMessageHandler::RawMessageArrived(const QByteArray& data) { return true; } -template +template void AbstractMessageHandler::AbortAll() { - foreach (ReplyType* reply, pending_replies_) { - reply->Abort(); - } + foreach(ReplyType * reply, pending_replies_) { reply->Abort(); } pending_replies_.clear(); } - - -#endif // MESSAGEHANDLER_H +#endif // MESSAGEHANDLER_H diff --git a/ext/libclementine-common/core/messagereply.cpp b/ext/libclementine-common/core/messagereply.cpp index f2e99dc19..305752215 100644 --- a/ext/libclementine-common/core/messagereply.cpp +++ b/ext/libclementine-common/core/messagereply.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2011, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -18,11 +18,7 @@ #include "messagereply.h" _MessageReplyBase::_MessageReplyBase(QObject* parent) - : QObject(parent), - finished_(false), - success_(false) -{ -} + : QObject(parent), finished_(false), success_(false) {} bool _MessageReplyBase::WaitForFinished() { qLog(Debug) << "Waiting on ID" << id(); diff --git a/ext/libclementine-common/core/messagereply.h b/ext/libclementine-common/core/messagereply.h index ead5f38ba..1523709b8 100644 --- a/ext/libclementine-common/core/messagereply.h +++ b/ext/libclementine-common/core/messagereply.h @@ -29,7 +29,7 @@ class _MessageReplyBase : public QObject { Q_OBJECT -public: + public: _MessageReplyBase(QObject* parent = 0); virtual int id() const = 0; @@ -46,19 +46,18 @@ public: signals: void Finished(bool success); -protected: + protected: bool finished_; bool success_; QSemaphore semaphore_; }; - // A reply future class that is returned immediately for requests that will // occur in the background. Similar to QNetworkReply. template class MessageReply : public _MessageReplyBase { -public: + public: MessageReply(const MessageType& request_message, QObject* parent = 0); int id() const { return request_message_.id(); } @@ -67,21 +66,19 @@ public: void SetReply(const MessageType& message); -private: + private: MessageType request_message_; MessageType reply_message_; }; - -template +template MessageReply::MessageReply(const MessageType& request_message, QObject* parent) - : _MessageReplyBase(parent) -{ + : _MessageReplyBase(parent) { request_message_.MergeFrom(request_message); } -template +template void MessageReply::SetReply(const MessageType& message) { Q_ASSERT(!finished_); @@ -94,4 +91,4 @@ void MessageReply::SetReply(const MessageType& message) { semaphore_.release(); } -#endif // MESSAGEREPLY_H +#endif // MESSAGEREPLY_H diff --git a/ext/libclementine-common/core/override.h b/ext/libclementine-common/core/override.h index deeca9a6c..98c2764d5 100644 --- a/ext/libclementine-common/core/override.h +++ b/ext/libclementine-common/core/override.h @@ -18,7 +18,6 @@ // it is used by the Spotify blob which links against libspotify and is not GPL // compatible. - #ifndef OVERRIDE_H #define OVERRIDE_H @@ -26,13 +25,13 @@ // it is available. #ifndef __has_extension - #define __has_extension(x) 0 +#define __has_extension(x) 0 #endif #if __has_extension(cxx_override_control) // Clang feature checking macro. -# define OVERRIDE override +#define OVERRIDE override #else -# define OVERRIDE +#define OVERRIDE #endif #endif // OVERRIDE_H diff --git a/ext/libclementine-common/core/waitforsignal.h b/ext/libclementine-common/core/waitforsignal.h index 4c90c2e68..94e98249e 100644 --- a/ext/libclementine-common/core/waitforsignal.h +++ b/ext/libclementine-common/core/waitforsignal.h @@ -22,4 +22,4 @@ class QObject; void WaitForSignal(QObject* sender, const char* signal); -#endif // WAITFORSIGNAL_H +#endif // WAITFORSIGNAL_H diff --git a/ext/libclementine-common/core/workerpool.cpp b/ext/libclementine-common/core/workerpool.cpp index d3378eb61..2b74328d9 100644 --- a/ext/libclementine-common/core/workerpool.cpp +++ b/ext/libclementine-common/core/workerpool.cpp @@ -17,9 +17,4 @@ #include "workerpool.h" -_WorkerPoolBase::_WorkerPoolBase(QObject* parent) - : QObject(parent) -{ -} - - +_WorkerPoolBase::_WorkerPoolBase(QObject* parent) : QObject(parent) {} diff --git a/ext/libclementine-common/core/workerpool.h b/ext/libclementine-common/core/workerpool.h index 906c8dc73..598f47f13 100644 --- a/ext/libclementine-common/core/workerpool.h +++ b/ext/libclementine-common/core/workerpool.h @@ -32,13 +32,12 @@ #include "core/closure.h" #include "core/logging.h" - // Base class containing signals and slots - required because moc doesn't do // templated objects. class _WorkerPoolBase : public QObject { Q_OBJECT -public: + public: _WorkerPoolBase(QObject* parent = 0); signals: @@ -46,14 +45,13 @@ signals: // worker wasn't found, or couldn't be executed. void WorkerFailedToStart(); -protected slots: + protected slots: virtual void DoStart() {} virtual void NewConnection() {} virtual void ProcessError(QProcess::ProcessError) {} virtual void SendQueuedMessages() {} }; - // Manages a pool of one or more external processes. A local socket server is // started for each process, and the address is passed to the process as // argv[1]. The process is expected to connect back to the socket server, and @@ -61,7 +59,7 @@ protected slots: // Instances of HandlerType are created in the WorkerPool's thread. template class WorkerPool : public _WorkerPoolBase { -public: + public: WorkerPool(QObject* parent = 0); ~WorkerPool(); @@ -90,7 +88,7 @@ public: // worker. Can be called from any thread. ReplyType* SendMessageWithReply(MessageType* message); -protected: + protected: // These are all reimplemented slots, they are called on the WorkerPool's // thread. void DoStart(); @@ -98,10 +96,13 @@ protected: void ProcessError(QProcess::ProcessError error); void SendQueuedMessages(); -private: + private: struct Worker { - Worker() : local_server_(NULL), local_socket_(NULL), process_(NULL), - handler_(NULL) {} + Worker() + : local_server_(NULL), + local_socket_(NULL), + process_(NULL), + handler_(NULL) {} QLocalServer* local_server_; QLocalSocket* local_socket_; @@ -114,8 +115,8 @@ private: template Worker* FindWorker(T Worker::*member, T value) { - for (typename QList::iterator it = workers_.begin() ; - it != workers_.end() ; ++it) { + for (typename QList::iterator it = workers_.begin(); + it != workers_.end(); ++it) { if ((*it).*member == value) { return &(*it); } @@ -140,7 +141,7 @@ private: // my thread. HandlerType* NextHandler() const; -private: + private: QString local_server_name_; QString executable_name_; QString executable_path_; @@ -155,26 +156,21 @@ private: QQueue message_queue_; }; - template WorkerPool::WorkerPool(QObject* parent) - : _WorkerPoolBase(parent), - next_worker_(0), - next_id_(0) -{ + : _WorkerPoolBase(parent), next_worker_(0), next_id_(0) { worker_count_ = qBound(1, QThread::idealThreadCount() / 2, 2); local_server_name_ = qApp->applicationName().toLower(); - if (local_server_name_.isEmpty()) - local_server_name_ = "workerpool"; + if (local_server_name_.isEmpty()) local_server_name_ = "workerpool"; } template WorkerPool::~WorkerPool() { - foreach (const Worker& worker, workers_) { + foreach(const Worker & worker, workers_) { if (worker.local_socket_ && worker.process_) { - disconnect(worker.process_, SIGNAL(error(QProcess::ProcessError)), - this, SLOT(ProcessError(QProcess::ProcessError))); + disconnect(worker.process_, SIGNAL(error(QProcess::ProcessError)), this, + SLOT(ProcessError(QProcess::ProcessError))); // The worker is connected. Close his socket and wait for him to exit. qLog(Debug) << "Closing worker socket"; @@ -192,9 +188,7 @@ WorkerPool::~WorkerPool() { } } - foreach (ReplyType* reply, message_queue_) { - reply->Abort(); - } + foreach(ReplyType * reply, message_queue_) { reply->Abort(); } } template @@ -204,13 +198,15 @@ void WorkerPool::SetWorkerCount(int count) { } template -void WorkerPool::SetLocalServerName(const QString& local_server_name) { +void WorkerPool::SetLocalServerName( + const QString& local_server_name) { Q_ASSERT(workers_.isEmpty()); local_server_name_ = local_server_name; } template -void WorkerPool::SetExecutableName(const QString& executable_name) { +void WorkerPool::SetExecutableName( + const QString& executable_name) { Q_ASSERT(workers_.isEmpty()); executable_name_ = executable_name; } @@ -235,7 +231,7 @@ void WorkerPool::DoStart() { search_path << qApp->applicationDirPath() + "/../PlugIns"; #endif - foreach (const QString& path_prefix, search_path) { + foreach(const QString & path_prefix, search_path) { const QString executable_path = path_prefix + "/" + executable_name_; if (QFile::exists(executable_path)) { executable_path_ = executable_path; @@ -244,7 +240,7 @@ void WorkerPool::DoStart() { } // Start all the workers - for (int i=0 ; i::StartOneWorker(Worker* worker) { worker->local_server_ = new QLocalServer(this); worker->process_ = new QProcess(this); - connect(worker->local_server_, SIGNAL(newConnection()), SLOT(NewConnection())); + connect(worker->local_server_, SIGNAL(newConnection()), + SLOT(NewConnection())); connect(worker->process_, SIGNAL(error(QProcess::ProcessError)), SLOT(ProcessError(QProcess::ProcessError))); // Create a server, find an unused name and start listening forever { const int unique_number = qrand() ^ ((int)(quint64(this) & 0xFFFFFFFF)); - const QString name = QString("%1_%2").arg(local_server_name_).arg(unique_number); + const QString name = + QString("%1_%2").arg(local_server_name_).arg(unique_number); if (worker->local_server_->listen(name)) { break; @@ -284,7 +282,8 @@ void WorkerPool::StartOneWorker(Worker* worker) { // Start the process worker->process_->setProcessChannelMode(QProcess::ForwardedChannels); worker->process_->start(executable_path_, - QStringList() << worker->local_server_->fullServerName()); + QStringList() + << worker->local_server_->fullServerName()); } template @@ -295,10 +294,10 @@ void WorkerPool::NewConnection() { // Find the worker with this server. Worker* worker = FindWorker(&Worker::local_server_, server); - if (!worker) - return; + if (!worker) return; - qLog(Debug) << "Worker" << worker << "connected to" << server->fullServerName(); + qLog(Debug) << "Worker" << worker << "connected to" + << server->fullServerName(); // Accept the connection. worker->local_socket_ = server->nextPendingConnection(); @@ -322,29 +321,29 @@ void WorkerPool::ProcessError(QProcess::ProcessError error) { // Find the worker with this process. Worker* worker = FindWorker(&Worker::process_, process); - if (!worker) - return; + if (!worker) return; switch (error) { - case QProcess::FailedToStart: - // Failed to start errors are bad - it usually means the worker isn't - // installed. Don't restart the process, but tell our owner, who will - // probably want to do something fatal. - qLog(Error) << "Worker failed to start"; - emit WorkerFailedToStart(); - break; + case QProcess::FailedToStart: + // Failed to start errors are bad - it usually means the worker isn't + // installed. Don't restart the process, but tell our owner, who will + // probably want to do something fatal. + qLog(Error) << "Worker failed to start"; + emit WorkerFailedToStart(); + break; - default: - // On any other error we just restart the process. - qLog(Debug) << "Worker" << worker << "failed with error" << error << "- restarting"; - StartOneWorker(worker); - break; + default: + // On any other error we just restart the process. + qLog(Debug) << "Worker" << worker << "failed with error" << error + << "- restarting"; + StartOneWorker(worker); + break; } } template -typename WorkerPool::ReplyType* -WorkerPool::NewReply(MessageType* message) { +typename WorkerPool::ReplyType* WorkerPool::NewReply( + MessageType* message) { const int id = next_id_.fetchAndAddOrdered(1); message->set_id(id); @@ -390,7 +389,7 @@ void WorkerPool::SendQueuedMessages() { template HandlerType* WorkerPool::NextHandler() const { - for (int i=0 ; i::NextHandler() const { return NULL; } -#endif // WORKERPOOL_H +#endif // WORKERPOOL_H diff --git a/ext/libclementine-tagreader/cloudstream.cpp b/ext/libclementine-tagreader/cloudstream.cpp index 100174cca..253c14c95 100644 --- a/ext/libclementine-tagreader/cloudstream.cpp +++ b/ext/libclementine-tagreader/cloudstream.cpp @@ -28,13 +28,13 @@ #include "core/logging.h" namespace { - static const int kTaglibPrefixCacheBytes = 64 * 1024; // Should be enough. - static const int kTaglibSuffixCacheBytes = 8 * 1024; +static const int kTaglibPrefixCacheBytes = 64 * 1024; // Should be enough. +static const int kTaglibSuffixCacheBytes = 8 * 1024; } -CloudStream::CloudStream( - const QUrl& url, const QString& filename, const long length, - const QString& auth, QNetworkAccessManager* network) +CloudStream::CloudStream(const QUrl& url, const QString& filename, + const long length, const QString& auth, + QNetworkAccessManager* network) : url_(url), filename_(filename), encoded_filename_(filename_.toUtf8()), @@ -43,12 +43,9 @@ CloudStream::CloudStream( cursor_(0), network_(network), cache_(length), - num_requests_(0) { -} + num_requests_(0) {} -TagLib::FileName CloudStream::name() const { - return encoded_filename_.data(); -} +TagLib::FileName CloudStream::name() const { return encoded_filename_.data(); } bool CloudStream::CheckCache(int start, int end) { for (int i = start; i <= end; ++i) { @@ -113,8 +110,8 @@ TagLib::ByteVector CloudStream::readBlock(ulong length) { if (!auth_.isEmpty()) { request.setRawHeader("Authorization", auth_.toUtf8()); } - request.setRawHeader( - "Range", QString("bytes=%1-%2").arg(start).arg(end).toUtf8()); + request.setRawHeader("Range", + QString("bytes=%1-%2").arg(start).arg(end).toUtf8()); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork); // The Ubuntu One server applies the byte range to the gzipped data, rather @@ -124,7 +121,8 @@ TagLib::ByteVector CloudStream::readBlock(ulong length) { } QNetworkReply* reply = network_->get(request); - connect(reply, SIGNAL(sslErrors(QList)), SLOT(SSLErrors(QList))); + connect(reply, SIGNAL(sslErrors(QList)), + SLOT(SSLErrors(QList))); ++num_requests_; QEventLoop loop; @@ -163,9 +161,7 @@ bool CloudStream::readOnly() const { return true; } -bool CloudStream::isOpen() const { - return true; -} +bool CloudStream::isOpen() const { return true; } void CloudStream::seek(long offset, TagLib::IOStream::Position p) { switch (p) { @@ -184,24 +180,18 @@ void CloudStream::seek(long offset, TagLib::IOStream::Position p) { } } -void CloudStream::clear() { - cursor_ = 0; -} +void CloudStream::clear() { cursor_ = 0; } -long CloudStream::tell() const { - return cursor_; -} +long CloudStream::tell() const { return cursor_; } -long CloudStream::length() { - return length_; -} +long CloudStream::length() { return length_; } void CloudStream::truncate(long) { qLog(Debug) << Q_FUNC_INFO << "not implemented"; } void CloudStream::SSLErrors(const QList& errors) { - foreach (const QSslError& error, errors) { + foreach(const QSslError & error, errors) { qLog(Debug) << error.error() << error.errorString(); qLog(Debug) << error.certificate(); } diff --git a/ext/libclementine-tagreader/cloudstream.h b/ext/libclementine-tagreader/cloudstream.h index 6905171bd..4c2e1358d 100644 --- a/ext/libclementine-tagreader/cloudstream.h +++ b/ext/libclementine-tagreader/cloudstream.h @@ -31,11 +31,8 @@ class QNetworkAccessManager; class CloudStream : public QObject, public TagLib::IOStream { Q_OBJECT public: - CloudStream(const QUrl& url, - const QString& filename, - const long length, - const QString& auth, - QNetworkAccessManager* network); + CloudStream(const QUrl& url, const QString& filename, const long length, + const QString& auth, QNetworkAccessManager* network); // Taglib::IOStream virtual TagLib::FileName name() const; @@ -55,9 +52,7 @@ class CloudStream : public QObject, public TagLib::IOStream { return cache_.num_nonempty(); } - int num_requests() const { - return num_requests_; - } + int num_requests() const { return num_requests_; } // Use educated guess to request the bytes that TagLib will probably want. void Precache(); @@ -84,4 +79,4 @@ class CloudStream : public QObject, public TagLib::IOStream { int num_requests_; }; -#endif // GOOGLEDRIVESTREAM_H +#endif // GOOGLEDRIVESTREAM_H diff --git a/ext/libclementine-tagreader/fmpsparser.cpp b/ext/libclementine-tagreader/fmpsparser.cpp index 5eca59207..857aa979e 100644 --- a/ext/libclementine-tagreader/fmpsparser.cpp +++ b/ext/libclementine-tagreader/fmpsparser.cpp @@ -25,19 +25,18 @@ using std::placeholders::_1; using std::placeholders::_2; -FMPSParser::FMPSParser() : - // The float regex ends with (?:$|(?=::|;;)) to ensure it matches all the way - // up to the end of the value. Without it, it would match a string that - // starts with a number, like "123abc". - float_re_("\\s*([+-]?\\d+(?:\\.\\d+)?)\\s*(?:$|(?=::|;;))"), +FMPSParser::FMPSParser() + : // The float regex ends with (?:$|(?=::|;;)) to ensure it matches all the + // way + // up to the end of the value. Without it, it would match a string that + // starts with a number, like "123abc". + float_re_("\\s*([+-]?\\d+(?:\\.\\d+)?)\\s*(?:$|(?=::|;;))"), - // Matches any character except unescaped slashes, colons and semicolons. - string_re_("((?:[^\\\\;:]|(?:\\\\[\\\\:;]))+)(?:$|(?=::|;;))"), + // Matches any character except unescaped slashes, colons and semicolons. + string_re_("((?:[^\\\\;:]|(?:\\\\[\\\\:;]))+)(?:$|(?=::|;;))"), - // Used for replacing escaped characters. - escape_re_("\\\\([\\\\:;])") -{ -} + // Used for replacing escaped characters. + escape_re_("\\\\([\\\\:;])") {} // Parses a list of things (of type T) that are separated by two consecutive // Separator characters. Each individual thing is parsed by the F function. @@ -59,16 +58,16 @@ static int ParseContainer(const QStringRef& data, F f, QList* ret) { int pos = 0; while (pos < data.length()) { const int len = data.length() - pos; - int matched_len = f(QStringRef(data.string(), data.position() + pos, len), &value); - if (matched_len == -1 || matched_len > len) - break; + int matched_len = + f(QStringRef(data.string(), data.position() + pos, len), &value); + if (matched_len == -1 || matched_len > len) break; ret->append(value); pos += matched_len; // Expect two separators in a row - if (pos + 2 <= data.length() && data.at(pos) == Separator - && data.at(pos+1) == Separator) { + if (pos + 2 <= data.length() && data.at(pos) == Separator && + data.at(pos + 1) == Separator) { pos += 2; } else { break; diff --git a/ext/libclementine-tagreader/fmpsparser.h b/ext/libclementine-tagreader/fmpsparser.h index dfe669f14..961f5b4ae 100644 --- a/ext/libclementine-tagreader/fmpsparser.h +++ b/ext/libclementine-tagreader/fmpsparser.h @@ -22,7 +22,7 @@ #include class FMPSParser { -public: + public: FMPSParser(); // A FMPS result is a list of lists of values (where a value is a string or @@ -48,11 +48,11 @@ public: int ParseListList(const QString& data, Result* ret) const; int ParseListListRef(const QStringRef& data, Result* ret) const; -private: + private: QRegExp float_re_; QRegExp string_re_; QRegExp escape_re_; Result result_; }; -#endif // FMPSPARSER_H +#endif // FMPSPARSER_H diff --git a/ext/libclementine-tagreader/tagreader.cpp b/ext/libclementine-tagreader/tagreader.cpp index 475a2385a..e2f4137d5 100644 --- a/ext/libclementine-tagreader/tagreader.cpp +++ b/ext/libclementine-tagreader/tagreader.cpp @@ -59,15 +59,17 @@ #include "core/timeconstants.h" // Taglib added support for FLAC pictures in 1.7.0 -#if (TAGLIB_MAJOR_VERSION > 1) || (TAGLIB_MAJOR_VERSION == 1 && TAGLIB_MINOR_VERSION >= 7) -# define TAGLIB_HAS_FLAC_PICTURELIST +#if (TAGLIB_MAJOR_VERSION > 1) || \ + (TAGLIB_MAJOR_VERSION == 1 && TAGLIB_MINOR_VERSION >= 7) +#define TAGLIB_HAS_FLAC_PICTURELIST #endif #ifdef HAVE_GOOGLE_DRIVE -# include "cloudstream.h" +#include "cloudstream.h" #endif -#define NumberToASFAttribute(x) TagLib::ASF::Attribute(QStringToTaglibString(QString::number(x))) +#define NumberToASFAttribute(x) \ + TagLib::ASF::Attribute(QStringToTaglibString(QString::number(x))) class FileRefFactory { public: @@ -78,11 +80,11 @@ class FileRefFactory { class TagLibFileRefFactory : public FileRefFactory { public: virtual TagLib::FileRef* GetFileRef(const QString& filename) { - #ifdef Q_OS_WIN32 - return new TagLib::FileRef(filename.toStdWString().c_str()); - #else - return new TagLib::FileRef(QFile::encodeName(filename).constData()); - #endif +#ifdef Q_OS_WIN32 + return new TagLib::FileRef(filename.toStdWString().c_str()); +#else + return new TagLib::FileRef(QFile::encodeName(filename).constData()); +#endif } }; @@ -95,21 +97,22 @@ TagLib::String StdStringToTaglibString(const std::string& s) { TagLib::String QStringToTaglibString(const QString& s) { return TagLib::String(s.toUtf8().constData(), TagLib::String::UTF8); } - } -const char* TagReader::kMP4_FMPS_Rating_ID = "----:com.apple.iTunes:FMPS_Rating"; -const char* TagReader::kMP4_FMPS_Playcount_ID = "----:com.apple.iTunes:FMPS_Playcount"; -const char* TagReader::kMP4_FMPS_Score_ID = "----:com.apple.iTunes:FMPS_Rating_Amarok_Score"; +const char* TagReader::kMP4_FMPS_Rating_ID = + "----:com.apple.iTunes:FMPS_Rating"; +const char* TagReader::kMP4_FMPS_Playcount_ID = + "----:com.apple.iTunes:FMPS_Playcount"; +const char* TagReader::kMP4_FMPS_Score_ID = + "----:com.apple.iTunes:FMPS_Rating_Amarok_Score"; TagReader::TagReader() - : factory_(new TagLibFileRefFactory), - network_(new QNetworkAccessManager), - kEmbeddedCover("(embedded)") -{} + : factory_(new TagLibFileRefFactory), + network_(new QNetworkAccessManager), + kEmbeddedCover("(embedded)") {} void TagReader::ReadFile(const QString& filename, - pb::tagreader::SongMetadata* song) const { + pb::tagreader::SongMetadata* song) const { const QByteArray url(QUrl::fromLocalFile(filename).toEncoded()); const QFileInfo info(filename); @@ -122,7 +125,7 @@ void TagReader::ReadFile(const QString& filename, song->set_ctime(info.created().toTime_t()); std::unique_ptr fileref(factory_->GetFileRef(filename)); - if(fileref->isNull()) { + if (fileref->isNull()) { qLog(Info) << "TagLib hasn't been able to read " << filename << " file"; return; } @@ -130,7 +133,7 @@ void TagReader::ReadFile(const QString& filename, TagLib::Tag* tag = fileref->tag(); if (tag) { Decode(tag->title(), nullptr, song->mutable_title()); - Decode(tag->artist(), nullptr, song->mutable_artist()); // TPE1 + Decode(tag->artist(), nullptr, song->mutable_artist()); // TPE1 Decode(tag->album(), nullptr, song->mutable_album()); Decode(tag->genre(), nullptr, song->mutable_genre()); song->set_year(tag->year()); @@ -141,14 +144,17 @@ void TagReader::ReadFile(const QString& filename, QString disc; QString compilation; - // Handle all the files which have VorbisComments (Ogg, OPUS, ...) in the same way; + // Handle all the files which have VorbisComments (Ogg, OPUS, ...) in the same + // way; // apart, so we keep specific behavior for some formats by adding another // "else if" block below. - if (TagLib::Ogg::XiphComment* tag = dynamic_cast(fileref->file()->tag())) { + if (TagLib::Ogg::XiphComment* tag = + dynamic_cast(fileref->file()->tag())) { ParseOggTag(tag->fieldListMap(), nullptr, &disc, &compilation, song); } - if (TagLib::MPEG::File* file = dynamic_cast(fileref->file())) { + if (TagLib::MPEG::File* file = + dynamic_cast(fileref->file())) { if (file->ID3v2Tag()) { const TagLib::ID3v2::FrameListMap& map = file->ID3v2Tag()->frameListMap(); @@ -156,27 +162,32 @@ void TagReader::ReadFile(const QString& filename, disc = TStringToQString(map["TPOS"].front()->toString()).trimmed(); if (!map["TBPM"].isEmpty()) - song->set_bpm(TStringToQString(map["TBPM"].front()->toString()).trimmed().toFloat()); + song->set_bpm(TStringToQString(map["TBPM"].front()->toString()) + .trimmed() + .toFloat()); if (!map["TCOM"].isEmpty()) - Decode(map["TCOM"].front()->toString(), nullptr, song->mutable_composer()); + Decode(map["TCOM"].front()->toString(), nullptr, + song->mutable_composer()); - if (!map["TIT1"].isEmpty()) // content group - Decode(map["TIT1"].front()->toString(), nullptr, song->mutable_grouping()); + if (!map["TIT1"].isEmpty()) // content group + Decode(map["TIT1"].front()->toString(), nullptr, + song->mutable_grouping()); // Skip TPE1 (which is the artist) here because we already fetched it - if (!map["TPE2"].isEmpty()) // non-standard: Apple, Microsoft - Decode(map["TPE2"].front()->toString(), nullptr, song->mutable_albumartist()); + if (!map["TPE2"].isEmpty()) // non-standard: Apple, Microsoft + Decode(map["TPE2"].front()->toString(), nullptr, + song->mutable_albumartist()); if (!map["TCMP"].isEmpty()) - compilation = TStringToQString(map["TCMP"].front()->toString()).trimmed(); + compilation = + TStringToQString(map["TCMP"].front()->toString()).trimmed(); - if (!map["APIC"].isEmpty()) - song->set_art_automatic(kEmbeddedCover); + if (!map["APIC"].isEmpty()) song->set_art_automatic(kEmbeddedCover); // Find a suitable comment tag. For now we ignore iTunNORM comments. - for (int i=0 ; i(map["COMM"][i]); @@ -187,14 +198,14 @@ void TagReader::ReadFile(const QString& filename, } // Parse FMPS frames - for (int i=0 ; i(map["TXXX"][i]); + dynamic_cast( + map["TXXX"][i]); if (frame && frame->description().startsWith("FMPS_")) { ParseFMPSFrame(TStringToQString(frame->description()), - TStringToQString(frame->fieldList()[1]), - song); + TStringToQString(frame->fieldList()[1]), song); } } @@ -203,7 +214,8 @@ void TagReader::ReadFile(const QString& filename, // will consider POPM tags iff song has no rating/playcount already set. if (!map["POPM"].isEmpty()) { const TagLib::ID3v2::PopularimeterFrame* frame = - dynamic_cast(map["POPM"].front()); + dynamic_cast( + map["POPM"].front()); if (frame) { // Take a user rating only if there's no rating already set if (song->rating() <= 0 && frame->rating() > 0) { @@ -214,11 +226,12 @@ void TagReader::ReadFile(const QString& filename, } } } - } - } else if (TagLib::FLAC::File* file = dynamic_cast(fileref->file())) { - if ( file->xiphComment() ) { - ParseOggTag(file->xiphComment()->fieldListMap(), nullptr, &disc, &compilation, song); + } else if (TagLib::FLAC::File* file = + dynamic_cast(fileref->file())) { + if (file->xiphComment()) { + ParseOggTag(file->xiphComment()->fieldListMap(), nullptr, &disc, + &compilation, song); #ifdef TAGLIB_HAS_FLAC_PICTURELIST if (!file->pictureList().isEmpty()) { song->set_art_automatic(kEmbeddedCover); @@ -226,7 +239,8 @@ void TagReader::ReadFile(const QString& filename, #endif } Decode(tag->comment(), nullptr, song->mutable_comment()); - } else if (TagLib::MP4::File* file = dynamic_cast(fileref->file())) { + } else if (TagLib::MP4::File* file = + dynamic_cast(fileref->file())) { if (file->tag()) { TagLib::MP4::Tag* mp4_tag = file->tag(); const TagLib::MP4::ItemListMap& items = mp4_tag->itemListMap(); @@ -246,51 +260,67 @@ void TagReader::ReadFile(const QString& filename, } if (items.contains("disk")) { - disc = TStringToQString(TagLib::String::number(items["disk"].toIntPair().first)); + disc = TStringToQString( + TagLib::String::number(items["disk"].toIntPair().first)); } if (items.contains(kMP4_FMPS_Rating_ID)) { - float rating = TStringToQString(items[kMP4_FMPS_Rating_ID].toStringList().toString('\n')).toFloat(); + float rating = + TStringToQString(items[kMP4_FMPS_Rating_ID].toStringList().toString( + '\n')).toFloat(); if (song->rating() <= 0 && rating > 0) { song->set_rating(rating); } } if (items.contains(kMP4_FMPS_Playcount_ID)) { - int playcount = TStringToQString(items[kMP4_FMPS_Playcount_ID].toStringList().toString('\n')).toFloat(); + int playcount = + TStringToQString( + items[kMP4_FMPS_Playcount_ID].toStringList().toString('\n')) + .toFloat(); if (song->playcount() <= 0 && playcount > 0) { song->set_playcount(playcount); } } if (items.contains(kMP4_FMPS_Playcount_ID)) { - int score = TStringToQString(items[kMP4_FMPS_Score_ID].toStringList().toString('\n')).toFloat() * 100; + int score = TStringToQString( + items[kMP4_FMPS_Score_ID].toStringList().toString('\n')) + .toFloat() * + 100; if (song->score() <= 0 && score > 0) { song->set_score(score); } } - if(items.contains("\251wrt")) { - Decode(items["\251wrt"].toStringList().toString(", "), nullptr, song->mutable_composer()); + if (items.contains("\251wrt")) { + Decode(items["\251wrt"].toStringList().toString(", "), nullptr, + song->mutable_composer()); } - if(items.contains("\251grp")) { - Decode(items["\251grp"].toStringList().toString(" "), nullptr, song->mutable_grouping()); + if (items.contains("\251grp")) { + Decode(items["\251grp"].toStringList().toString(" "), nullptr, + song->mutable_grouping()); } Decode(mp4_tag->comment(), nullptr, song->mutable_comment()); } } #ifdef TAGLIB_WITH_ASF - else if (TagLib::ASF::File* file = dynamic_cast(fileref->file())) { - const TagLib::ASF::AttributeListMap& attributes_map = file->tag()->attributeListMap(); + else if (TagLib::ASF::File* file = + dynamic_cast(fileref->file())) { + const TagLib::ASF::AttributeListMap& attributes_map = + file->tag()->attributeListMap(); if (attributes_map.contains("FMPS/Rating")) { - const TagLib::ASF::AttributeList& attributes = attributes_map["FMPS/Rating"]; + const TagLib::ASF::AttributeList& attributes = + attributes_map["FMPS/Rating"]; if (!attributes.isEmpty()) { - float rating = TStringToQString(attributes.front().toString()).toFloat(); + float rating = + TStringToQString(attributes.front().toString()).toFloat(); if (song->rating() <= 0 && rating > 0) { song->set_rating(rating); } } } if (attributes_map.contains("FMPS/Playcount")) { - const TagLib::ASF::AttributeList& attributes = attributes_map["FMPS/Playcount"]; + const TagLib::ASF::AttributeList& attributes = + attributes_map["FMPS/Playcount"]; if (!attributes.isEmpty()) { int playcount = TStringToQString(attributes.front().toString()).toInt(); if (song->playcount() <= 0 && playcount > 0) { @@ -299,9 +329,11 @@ void TagReader::ReadFile(const QString& filename, } } if (attributes_map.contains("FMPS/Rating_Amarok_Score")) { - const TagLib::ASF::AttributeList& attributes = attributes_map["FMPS/Rating_Amarok_Score"]; + const TagLib::ASF::AttributeList& attributes = + attributes_map["FMPS/Rating_Amarok_Score"]; if (!attributes.isEmpty()) { - int score = TStringToQString(attributes.front().toString()).toFloat() * 100; + int score = + TStringToQString(attributes.front().toString()).toFloat() * 100; if (song->score() <= 0 && score > 0) { song->set_score(score); } @@ -316,7 +348,8 @@ void TagReader::ReadFile(const QString& filename, if (!disc.isEmpty()) { const int i = disc.indexOf('/'); if (i != -1) { - // disc.right( i ).toInt() is total number of discs, we don't use this at the moment + // disc.right( i ).toInt() is total number of discs, we don't use this at + // the moment song->set_disc(disc.left(i).toInt()); } else { song->set_disc(disc.toInt()); @@ -335,14 +368,18 @@ void TagReader::ReadFile(const QString& filename, if (fileref->audioProperties()) { song->set_bitrate(fileref->audioProperties()->bitrate()); song->set_samplerate(fileref->audioProperties()->sampleRate()); - song->set_length_nanosec(fileref->audioProperties()->length() * kNsecPerSec); + song->set_length_nanosec(fileref->audioProperties()->length() * + kNsecPerSec); } // Get the filetype if we can song->set_type(GuessFileType(fileref.get())); - // Set integer fields to -1 if they're not valid - #define SetDefault(field) if (song->field() <= 0) { song->set_##field(-1); } +// Set integer fields to -1 if they're not valid +#define SetDefault(field) \ + if (song->field() <= 0) { \ + song->set_##field(-1); \ + } SetDefault(track); SetDefault(disc); SetDefault(bpm); @@ -350,16 +387,16 @@ void TagReader::ReadFile(const QString& filename, SetDefault(bitrate); SetDefault(samplerate); SetDefault(lastplayed); - #undef SetDefault +#undef SetDefault } - void TagReader::Decode(const TagLib::String& tag, const QTextCodec* codec, - std::string* output) { + std::string* output) { QString tmp; if (codec && tag.isLatin1()) { // Never override UTF-8. - const std::string fixed = QString::fromUtf8(tag.toCString(true)).toStdString(); + const std::string fixed = + QString::fromUtf8(tag.toCString(true)).toStdString(); tmp = codec->toUnicode(fixed.c_str()).trimmed(); } else { tmp = TStringToQString(tag).trimmed(); @@ -369,7 +406,7 @@ void TagReader::Decode(const TagLib::String& tag, const QTextCodec* codec, } void TagReader::Decode(const QString& tag, const QTextCodec* codec, - std::string* output) { + std::string* output) { if (!codec) { output->assign(DataCommaSizeFromQString(tag)); } else { @@ -379,11 +416,10 @@ void TagReader::Decode(const QString& tag, const QTextCodec* codec, } void TagReader::ParseFMPSFrame(const QString& name, const QString& value, - pb::tagreader::SongMetadata* song) const { + pb::tagreader::SongMetadata* song) const { qLog(Debug) << "Parsing FMPSFrame" << name << ", " << value; FMPSParser parser; - if (!parser.Parse(value) || parser.is_empty()) - return; + if (!parser.Parse(value) || parser.is_empty()) return; QVariant var; if (name == "FMPS_Rating") { @@ -421,9 +457,9 @@ void TagReader::ParseFMPSFrame(const QString& name, const QString& value, } void TagReader::ParseOggTag(const TagLib::Ogg::FieldListMap& map, - const QTextCodec* codec, - QString* disc, QString* compilation, - pb::tagreader::SongMetadata* song) const { + const QTextCodec* codec, QString* disc, + QString* compilation, + pb::tagreader::SongMetadata* song) const { if (!map["COMPOSER"].isEmpty()) Decode(map["COMPOSER"].front(), codec, song->mutable_composer()); if (!map["PERFORMER"].isEmpty()) @@ -437,52 +473,76 @@ void TagReader::ParseOggTag(const TagLib::Ogg::FieldListMap& map, Decode(map["ALBUM ARTIST"].front(), codec, song->mutable_albumartist()); } - if (!map["BPM"].isEmpty() ) - song->set_bpm(TStringToQString( map["BPM"].front() ).trimmed().toFloat()); + if (!map["BPM"].isEmpty()) + song->set_bpm(TStringToQString(map["BPM"].front()).trimmed().toFloat()); - if (!map["DISCNUMBER"].isEmpty() ) - *disc = TStringToQString( map["DISCNUMBER"].front() ).trimmed(); + if (!map["DISCNUMBER"].isEmpty()) + *disc = TStringToQString(map["DISCNUMBER"].front()).trimmed(); - if (!map["COMPILATION"].isEmpty() ) - *compilation = TStringToQString( map["COMPILATION"].front() ).trimmed(); + if (!map["COMPILATION"].isEmpty()) + *compilation = TStringToQString(map["COMPILATION"].front()).trimmed(); - if (!map["COVERART"].isEmpty()) - song->set_art_automatic(kEmbeddedCover); + if (!map["COVERART"].isEmpty()) song->set_art_automatic(kEmbeddedCover); if (!map["METADATA_BLOCK_PICTURE"].isEmpty()) song->set_art_automatic(kEmbeddedCover); if (!map["FMPS_RATING"].isEmpty() && song->rating() <= 0) - song->set_rating(TStringToQString( map["FMPS_RATING"].front() ).trimmed().toFloat()); + song->set_rating( + TStringToQString(map["FMPS_RATING"].front()).trimmed().toFloat()); if (!map["FMPS_PLAYCOUNT"].isEmpty() && song->playcount() <= 0) - song->set_playcount(TStringToQString( map["FMPS_PLAYCOUNT"].front() ).trimmed().toFloat()); + song->set_playcount( + TStringToQString(map["FMPS_PLAYCOUNT"].front()).trimmed().toFloat()); if (!map["FMPS_RATING_AMAROK_SCORE"].isEmpty() && song->score() <= 0) - song->set_score(TStringToQString( map["FMPS_RATING_AMAROK_SCORE"].front() ).trimmed().toFloat() * 100); + song->set_score(TStringToQString(map["FMPS_RATING_AMAROK_SCORE"].front()) + .trimmed() + .toFloat() * + 100); } void TagReader::SetVorbisComments(TagLib::Ogg::XiphComment* vorbis_comments, - const pb::tagreader::SongMetadata& song) const { + const pb::tagreader::SongMetadata& song) + const { - vorbis_comments->addField("COMPOSER", StdStringToTaglibString(song.composer()), true); - vorbis_comments->addField("PERFORMER", StdStringToTaglibString(song.performer()), true); - vorbis_comments->addField("CONTENT GROUP", StdStringToTaglibString(song.grouping()), true); - vorbis_comments->addField("BPM", QStringToTaglibString(song.bpm() <= 0 -1 ? QString() : QString::number(song.bpm())), true); - vorbis_comments->addField("DISCNUMBER", QStringToTaglibString(song.disc() <= 0 -1 ? QString() : QString::number(song.disc())), true); - vorbis_comments->addField("COMPILATION", StdStringToTaglibString(song.compilation() ? "1" : "0"), true); + vorbis_comments->addField("COMPOSER", + StdStringToTaglibString(song.composer()), true); + vorbis_comments->addField("PERFORMER", + StdStringToTaglibString(song.performer()), true); + vorbis_comments->addField("CONTENT GROUP", + StdStringToTaglibString(song.grouping()), true); + vorbis_comments->addField( + "BPM", QStringToTaglibString( + song.bpm() <= 0 - 1 ? QString() : QString::number(song.bpm())), + true); + vorbis_comments->addField( + "DISCNUMBER", + QStringToTaglibString( + song.disc() <= 0 - 1 ? QString() : QString::number(song.disc())), + true); + vorbis_comments->addField( + "COMPILATION", StdStringToTaglibString(song.compilation() ? "1" : "0"), + true); } -void TagReader::SetFMPSStatisticsVorbisComments(TagLib::Ogg::XiphComment* vorbis_comments, - const pb::tagreader::SongMetadata& song) const { - vorbis_comments->addField("FMPS_PLAYCOUNT", QStringToTaglibString(QString::number(song.playcount()))); - vorbis_comments->addField("FMPS_RATING_AMAROK_SCORE", QStringToTaglibString(QString::number(song.score() / 100.0))); +void TagReader::SetFMPSStatisticsVorbisComments( + TagLib::Ogg::XiphComment* vorbis_comments, + const pb::tagreader::SongMetadata& song) const { + vorbis_comments->addField( + "FMPS_PLAYCOUNT", + QStringToTaglibString(QString::number(song.playcount()))); + vorbis_comments->addField( + "FMPS_RATING_AMAROK_SCORE", + QStringToTaglibString(QString::number(song.score() / 100.0))); } -void TagReader::SetFMPSRatingVorbisComments(TagLib::Ogg::XiphComment* vorbis_comments, - const pb::tagreader::SongMetadata& song) const { +void TagReader::SetFMPSRatingVorbisComments( + TagLib::Ogg::XiphComment* vorbis_comments, + const pb::tagreader::SongMetadata& song) const { - vorbis_comments->addField("FMPS_RATING", QStringToTaglibString(QString::number(song.rating()))); + vorbis_comments->addField( + "FMPS_RATING", QStringToTaglibString(QString::number(song.rating()))); } pb::tagreader::SongMetadata_Type TagReader::GuessFileType( @@ -522,135 +582,155 @@ pb::tagreader::SongMetadata_Type TagReader::GuessFileType( } bool TagReader::SaveFile(const QString& filename, - const pb::tagreader::SongMetadata& song) const { - if (filename.isNull()) - return false; + const pb::tagreader::SongMetadata& song) const { + if (filename.isNull()) return false; qLog(Debug) << "Saving tags to" << filename; std::unique_ptr fileref(factory_->GetFileRef(filename)); - if (!fileref || fileref->isNull()) // The file probably doesn't exist + if (!fileref || fileref->isNull()) // The file probably doesn't exist return false; fileref->tag()->setTitle(StdStringToTaglibString(song.title())); - fileref->tag()->setArtist(StdStringToTaglibString(song.artist())); // TPE1 + fileref->tag()->setArtist(StdStringToTaglibString(song.artist())); // TPE1 fileref->tag()->setAlbum(StdStringToTaglibString(song.album())); fileref->tag()->setGenre(StdStringToTaglibString(song.genre())); fileref->tag()->setComment(StdStringToTaglibString(song.comment())); fileref->tag()->setYear(song.year()); fileref->tag()->setTrack(song.track()); - if (TagLib::MPEG::File* file = dynamic_cast(fileref->file())) { + if (TagLib::MPEG::File* file = + dynamic_cast(fileref->file())) { TagLib::ID3v2::Tag* tag = file->ID3v2Tag(true); - SetTextFrame("TPOS", song.disc() <= 0 -1 ? QString() : QString::number(song.disc()), tag); - SetTextFrame("TBPM", song.bpm() <= 0 -1 ? QString() : QString::number(song.bpm()), tag); + SetTextFrame( + "TPOS", song.disc() <= 0 - 1 ? QString() : QString::number(song.disc()), + tag); + SetTextFrame("TBPM", + song.bpm() <= 0 - 1 ? QString() : QString::number(song.bpm()), + tag); SetTextFrame("TCOM", song.composer(), tag); SetTextFrame("TIT1", song.grouping(), tag); // Skip TPE1 (which is the artist) here because we already set it SetTextFrame("TPE2", song.albumartist(), tag); SetTextFrame("TCMP", std::string(song.compilation() ? "1" : "0"), tag); - } else if (TagLib::FLAC::File* file = dynamic_cast(fileref->file())) { + } else if (TagLib::FLAC::File* file = + dynamic_cast(fileref->file())) { TagLib::Ogg::XiphComment* tag = file->xiphComment(); SetVorbisComments(tag, song); - } else if (TagLib::MP4::File* file = dynamic_cast(fileref->file())) { + } else if (TagLib::MP4::File* file = + dynamic_cast(fileref->file())) { TagLib::MP4::Tag* tag = file->tag(); - tag->itemListMap()["disk"] = TagLib::MP4::Item(song.disc() <= 0 -1 ? 0 : song.disc(), 0); - tag->itemListMap()["tmpo"] = TagLib::StringList(song.bpm() <= 0 -1 ? "0" : TagLib::String::number(song.bpm())); + tag->itemListMap()["disk"] = + TagLib::MP4::Item(song.disc() <= 0 - 1 ? 0 : song.disc(), 0); + tag->itemListMap()["tmpo"] = TagLib::StringList( + song.bpm() <= 0 - 1 ? "0" : TagLib::String::number(song.bpm())); tag->itemListMap()["\251wrt"] = TagLib::StringList(song.composer()); tag->itemListMap()["\251grp"] = TagLib::StringList(song.grouping()); - tag->itemListMap()["aART"] = TagLib::StringList(song.albumartist()); - tag->itemListMap()["cpil"] = TagLib::StringList(song.compilation() ? "1" : "0"); + tag->itemListMap()["aART"] = TagLib::StringList(song.albumartist()); + tag->itemListMap()["cpil"] = + TagLib::StringList(song.compilation() ? "1" : "0"); } - // Handle all the files which have VorbisComments (Ogg, OPUS, ...) in the same way; + // Handle all the files which have VorbisComments (Ogg, OPUS, ...) in the same + // way; // apart, so we keep specific behavior for some formats by adding another // "else if" block above. - if (TagLib::Ogg::XiphComment* tag = dynamic_cast(fileref->file()->tag())) { - SetVorbisComments(tag, song); + if (TagLib::Ogg::XiphComment* tag = + dynamic_cast(fileref->file()->tag())) { + SetVorbisComments(tag, song); } bool ret = fileref->save(); - #ifdef Q_OS_LINUX +#ifdef Q_OS_LINUX if (ret) { // Linux: inotify doesn't seem to notice the change to the file unless we // change the timestamps as well. (this is what touch does) utimensat(0, QFile::encodeName(filename).constData(), nullptr, 0); } - #endif // Q_OS_LINUX +#endif // Q_OS_LINUX return ret; } -bool TagReader::SaveSongStatisticsToFile(const QString& filename, - const pb::tagreader::SongMetadata& song) const { - if (filename.isNull()) - return false; +bool TagReader::SaveSongStatisticsToFile( + const QString& filename, const pb::tagreader::SongMetadata& song) const { + if (filename.isNull()) return false; qLog(Debug) << "Saving song statistics tags to" << filename; std::unique_ptr fileref(factory_->GetFileRef(filename)); - if (!fileref || fileref->isNull()) // The file probably doesn't exist + if (!fileref || fileref->isNull()) // The file probably doesn't exist return false; - if (TagLib::MPEG::File* file = dynamic_cast(fileref->file())) { + if (TagLib::MPEG::File* file = + dynamic_cast(fileref->file())) { TagLib::ID3v2::Tag* tag = file->ID3v2Tag(true); // Save as FMPS SetUserTextFrame("FMPS_PlayCount", QString::number(song.playcount()), tag); - SetUserTextFrame("FMPS_Rating_Amarok_Score", QString::number(song.score() / 100.0), tag); + SetUserTextFrame("FMPS_Rating_Amarok_Score", + QString::number(song.score() / 100.0), tag); // Also save as POPM TagLib::ID3v2::PopularimeterFrame* frame = GetPOPMFrameFromTag(tag); frame->setCounter(song.playcount()); - } else if (TagLib::FLAC::File* file = dynamic_cast(fileref->file())) { + } else if (TagLib::FLAC::File* file = + dynamic_cast(fileref->file())) { TagLib::Ogg::XiphComment* vorbis_comments = file->xiphComment(true); SetFMPSStatisticsVorbisComments(vorbis_comments, song); - } else if (TagLib::Ogg::XiphComment* tag = dynamic_cast(fileref->file()->tag())) { + } else if (TagLib::Ogg::XiphComment* tag = + dynamic_cast( + fileref->file()->tag())) { SetFMPSStatisticsVorbisComments(tag, song); } #ifdef TAGLIB_WITH_ASF - else if (TagLib::ASF::File* file = dynamic_cast(fileref->file())) { + else if (TagLib::ASF::File* file = + dynamic_cast(fileref->file())) { TagLib::ASF::Tag* tag = file->tag(); tag->addAttribute("FMPS/Playcount", NumberToASFAttribute(song.playcount())); - tag->addAttribute("FMPS/Rating_Amarok_Score", NumberToASFAttribute(song.score() / 100.0)); + tag->addAttribute("FMPS/Rating_Amarok_Score", + NumberToASFAttribute(song.score() / 100.0)); } #endif - else if (TagLib::MP4::File* file = dynamic_cast(fileref->file())) { + else if (TagLib::MP4::File* file = + dynamic_cast(fileref->file())) { TagLib::MP4::Tag* tag = file->tag(); - tag->itemListMap()[kMP4_FMPS_Score_ID] = TagLib::StringList(QStringToTaglibString(QString::number(song.score() / 100.0))); - tag->itemListMap()[kMP4_FMPS_Playcount_ID] = TagLib::StringList(TagLib::String::number(song.playcount())); + tag->itemListMap()[kMP4_FMPS_Score_ID] = TagLib::StringList( + QStringToTaglibString(QString::number(song.score() / 100.0))); + tag->itemListMap()[kMP4_FMPS_Playcount_ID] = + TagLib::StringList(TagLib::String::number(song.playcount())); } else { // Nothing to save: stop now return true; } bool ret = fileref->save(); - #ifdef Q_OS_LINUX +#ifdef Q_OS_LINUX if (ret) { // Linux: inotify doesn't seem to notice the change to the file unless we // change the timestamps as well. (this is what touch does) utimensat(0, QFile::encodeName(filename).constData(), nullptr, 0); } - #endif // Q_OS_LINUX +#endif // Q_OS_LINUX return ret; } -bool TagReader::SaveSongRatingToFile(const QString& filename, - const pb::tagreader::SongMetadata& song) const { - if (filename.isNull()) - return false; +bool TagReader::SaveSongRatingToFile( + const QString& filename, const pb::tagreader::SongMetadata& song) const { + if (filename.isNull()) return false; qLog(Debug) << "Saving song rating tags to" << filename; std::unique_ptr fileref(factory_->GetFileRef(filename)); - if (!fileref || fileref->isNull()) // The file probably doesn't exist + if (!fileref || fileref->isNull()) // The file probably doesn't exist return false; - if (TagLib::MPEG::File* file = dynamic_cast(fileref->file())) { + if (TagLib::MPEG::File* file = + dynamic_cast(fileref->file())) { TagLib::ID3v2::Tag* tag = file->ID3v2Tag(true); // Save as FMPS @@ -660,38 +740,45 @@ bool TagReader::SaveSongRatingToFile(const QString& filename, TagLib::ID3v2::PopularimeterFrame* frame = GetPOPMFrameFromTag(tag); frame->setRating(ConvertToPOPMRating(song.rating())); - } else if (TagLib::FLAC::File* file = dynamic_cast(fileref->file())) { + } else if (TagLib::FLAC::File* file = + dynamic_cast(fileref->file())) { TagLib::Ogg::XiphComment* vorbis_comments = file->xiphComment(true); SetFMPSRatingVorbisComments(vorbis_comments, song); - } else if (TagLib::Ogg::XiphComment* tag = dynamic_cast(fileref->file()->tag())) { + } else if (TagLib::Ogg::XiphComment* tag = + dynamic_cast( + fileref->file()->tag())) { SetFMPSRatingVorbisComments(tag, song); } #ifdef TAGLIB_WITH_ASF - else if (TagLib::ASF::File* file = dynamic_cast(fileref->file())) { + else if (TagLib::ASF::File* file = + dynamic_cast(fileref->file())) { TagLib::ASF::Tag* tag = file->tag(); - tag->addAttribute("FMPS/Rating", NumberToASFAttribute(song.rating())); + tag->addAttribute("FMPS/Rating", NumberToASFAttribute(song.rating())); } #endif - else if (TagLib::MP4::File* file = dynamic_cast(fileref->file())) { + else if (TagLib::MP4::File* file = + dynamic_cast(fileref->file())) { TagLib::MP4::Tag* tag = file->tag(); - tag->itemListMap()[kMP4_FMPS_Rating_ID] = TagLib::StringList(QStringToTaglibString(QString::number(song.rating()))); + tag->itemListMap()[kMP4_FMPS_Rating_ID] = TagLib::StringList( + QStringToTaglibString(QString::number(song.rating()))); } else { // Nothing to save: stop now return true; } bool ret = fileref->save(); - #ifdef Q_OS_LINUX +#ifdef Q_OS_LINUX if (ret) { // Linux: inotify doesn't seem to notice the change to the file unless we // change the timestamps as well. (this is what touch does) utimensat(0, QFile::encodeName(filename).constData(), nullptr, 0); } - #endif // Q_OS_LINUX +#endif // Q_OS_LINUX return ret; } -void TagReader::SetUserTextFrame(const QString& description, const QString& value, +void TagReader::SetUserTextFrame(const QString& description, + const QString& value, TagLib::ID3v2::Tag* tag) const { const QByteArray descr_utf8(description.toUtf8()); const QByteArray value_utf8(value.toUtf8()); @@ -721,13 +808,13 @@ void TagReader::SetUserTextFrame(const std::string& description, } void TagReader::SetTextFrame(const char* id, const QString& value, - TagLib::ID3v2::Tag* tag) const { + TagLib::ID3v2::Tag* tag) const { const QByteArray utf8(value.toUtf8()); SetTextFrame(id, std::string(utf8.constData(), utf8.length()), tag); } void TagReader::SetTextFrame(const char* id, const std::string& value, - TagLib::ID3v2::Tag* tag) const { + TagLib::ID3v2::Tag* tag) const { TagLib::ByteVector id_vector(id); // Remove the frame if it already exists @@ -752,8 +839,7 @@ bool TagReader::IsMediaFile(const QString& filename) const { } QByteArray TagReader::LoadEmbeddedArt(const QString& filename) const { - if (filename.isEmpty()) - return QByteArray(); + if (filename.isEmpty()) return QByteArray(); qLog(Debug) << "Loading art from" << filename; @@ -763,20 +849,20 @@ QByteArray TagReader::LoadEmbeddedArt(const QString& filename) const { TagLib::FileRef ref(QFile::encodeName(filename).constData()); #endif - if (ref.isNull() || !ref.file()) - return QByteArray(); + if (ref.isNull() || !ref.file()) return QByteArray(); // MP3 TagLib::MPEG::File* file = dynamic_cast(ref.file()); if (file && file->ID3v2Tag()) { - TagLib::ID3v2::FrameList apic_frames = file->ID3v2Tag()->frameListMap()["APIC"]; - if (apic_frames.isEmpty()) - return QByteArray(); + TagLib::ID3v2::FrameList apic_frames = + file->ID3v2Tag()->frameListMap()["APIC"]; + if (apic_frames.isEmpty()) return QByteArray(); TagLib::ID3v2::AttachedPictureFrame* pic = static_cast(apic_frames.front()); - return QByteArray((const char*) pic->picture().data(), pic->picture().size()); + return QByteArray((const char*)pic->picture().data(), + pic->picture().size()); } // Ogg vorbis/speex @@ -786,12 +872,14 @@ QByteArray TagReader::LoadEmbeddedArt(const QString& filename) const { if (xiph_comment) { TagLib::Ogg::FieldListMap map = xiph_comment->fieldListMap(); - // Other than the below mentioned non-standard COVERART, METADATA_BLOCK_PICTURE + // Other than the below mentioned non-standard COVERART, + // METADATA_BLOCK_PICTURE // is the proposed tag for cover pictures. // (see http://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE) if (map.contains("METADATA_BLOCK_PICTURE")) { TagLib::StringList pict_list = map["METADATA_BLOCK_PICTURE"]; - for(std::list::iterator it = pict_list.begin(); it != pict_list.end(); ++it) { + for (std::list::iterator it = pict_list.begin(); + it != pict_list.end(); ++it) { QByteArray data(QByteArray::fromBase64(it->toCString())); TagLib::ByteVector tdata(data.data(), data.size()); TagLib::FLAC::Picture p(tdata); @@ -799,7 +887,8 @@ QByteArray TagReader::LoadEmbeddedArt(const QString& filename) const { return QByteArray(p.data().data(), p.data().size()); } // If there was no specific front cover, just take the first picture - QByteArray data(QByteArray::fromBase64(map["METADATA_BLOCK_PICTURE"].front().toCString())); + QByteArray data(QByteArray::fromBase64( + map["METADATA_BLOCK_PICTURE"].front().toCString())); TagLib::ByteVector tdata(data.data(), data.size()); TagLib::FLAC::Picture p(tdata); return QByteArray(p.data().data(), p.data().size()); @@ -807,8 +896,7 @@ QByteArray TagReader::LoadEmbeddedArt(const QString& filename) const { // Ogg lacks a definitive standard for embedding cover art, but it seems // b64 encoding a field called COVERART is the general convention - if (!map.contains("COVERART")) - return QByteArray(); + if (!map.contains("COVERART")) return QByteArray(); return QByteArray::fromBase64(map["COVERART"].toString().toCString()); } @@ -850,62 +938,45 @@ QByteArray TagReader::LoadEmbeddedArt(const QString& filename) const { return QByteArray(); } - #ifdef HAVE_GOOGLE_DRIVE -bool TagReader::ReadCloudFile(const QUrl& download_url, - const QString& title, - int size, - const QString& mime_type, - const QString& authorisation_header, - pb::tagreader::SongMetadata* song) const { +bool TagReader::ReadCloudFile(const QUrl& download_url, const QString& title, + int size, const QString& mime_type, + const QString& authorisation_header, + pb::tagreader::SongMetadata* song) const { qLog(Debug) << "Loading tags from" << title; - CloudStream* stream = new CloudStream( - download_url, title, size, authorisation_header, network_); + CloudStream* stream = new CloudStream(download_url, title, size, + authorisation_header, network_); stream->Precache(); std::unique_ptr tag; if (mime_type == "audio/mpeg" && title.endsWith(".mp3")) { - tag.reset(new TagLib::MPEG::File( - stream, // Takes ownership. - TagLib::ID3v2::FrameFactory::instance(), - TagLib::AudioProperties::Accurate)); + tag.reset(new TagLib::MPEG::File(stream, // Takes ownership. + TagLib::ID3v2::FrameFactory::instance(), + TagLib::AudioProperties::Accurate)); } else if (mime_type == "audio/mp4" || (mime_type == "audio/mpeg" && title.endsWith(".m4a"))) { - tag.reset(new TagLib::MP4::File( - stream, - true, - TagLib::AudioProperties::Accurate)); - } + tag.reset( + new TagLib::MP4::File(stream, true, TagLib::AudioProperties::Accurate)); + } #ifdef TAGLIB_HAS_OPUS - else if ((mime_type == "application/opus" || - mime_type == "audio/opus" || - mime_type == "application/ogg" || - mime_type == "audio/ogg") && title.endsWith(".opus")) { - tag.reset(new TagLib::Ogg::Opus::File( - stream, - true, - TagLib::AudioProperties::Accurate)); + else if ((mime_type == "application/opus" || mime_type == "audio/opus" || + mime_type == "application/ogg" || mime_type == "audio/ogg") && + title.endsWith(".opus")) { + tag.reset(new TagLib::Ogg::Opus::File(stream, true, + TagLib::AudioProperties::Accurate)); } #endif - else if (mime_type == "application/ogg" || - mime_type == "audio/ogg") { - tag.reset(new TagLib::Ogg::Vorbis::File( - stream, - true, - TagLib::AudioProperties::Accurate)); - } else if (mime_type == "application/x-flac" || - mime_type == "audio/flac" || - mime_type == "audio/x-flac") { - tag.reset(new TagLib::FLAC::File( - stream, - TagLib::ID3v2::FrameFactory::instance(), - true, - TagLib::AudioProperties::Accurate)); + else if (mime_type == "application/ogg" || mime_type == "audio/ogg") { + tag.reset(new TagLib::Ogg::Vorbis::File(stream, true, + TagLib::AudioProperties::Accurate)); + } else if (mime_type == "application/x-flac" || mime_type == "audio/flac" || + mime_type == "audio/x-flac") { + tag.reset(new TagLib::FLAC::File(stream, + TagLib::ID3v2::FrameFactory::instance(), + true, TagLib::AudioProperties::Accurate)); } else if (mime_type == "audio/x-ms-wma") { - tag.reset(new TagLib::ASF::File( - stream, - true, - TagLib::AudioProperties::Accurate)); + tag.reset( + new TagLib::ASF::File(stream, true, TagLib::AudioProperties::Accurate)); } else { qLog(Debug) << "Unknown mime type for tagging:" << mime_type; return false; @@ -914,8 +985,7 @@ bool TagReader::ReadCloudFile(const QUrl& download_url, if (stream->num_requests() > 2) { // Warn if pre-caching failed. qLog(Warning) << "Total requests for file:" << title - << stream->num_requests() - << stream->cached_bytes(); + << stream->num_requests() << stream->cached_bytes(); } if (tag->tag() && !tag->tag()->isEmpty()) { @@ -941,14 +1011,16 @@ bool TagReader::ReadCloudFile(const QUrl& download_url, return false; } -#endif // HAVE_GOOGLE_DRIVE +#endif // HAVE_GOOGLE_DRIVE -TagLib::ID3v2::PopularimeterFrame* TagReader::GetPOPMFrameFromTag(TagLib::ID3v2::Tag* tag) { +TagLib::ID3v2::PopularimeterFrame* TagReader::GetPOPMFrameFromTag( + TagLib::ID3v2::Tag* tag) { TagLib::ID3v2::PopularimeterFrame* frame = nullptr; const TagLib::ID3v2::FrameListMap& map = tag->frameListMap(); if (!map["POPM"].isEmpty()) { - frame = dynamic_cast(map["POPM"].front()); + frame = + dynamic_cast(map["POPM"].front()); } if (!frame) { @@ -962,15 +1034,15 @@ float TagReader::ConvertPOPMRating(const int POPM_rating) { if (POPM_rating < 0x01) { return 0.0; } else if (POPM_rating < 0x40) { - return 0.20; // 1 star + return 0.20; // 1 star } else if (POPM_rating < 0x80) { - return 0.40; // 2 stars + return 0.40; // 2 stars } else if (POPM_rating < 0xC0) { - return 0.60; // 3 stars - } else if (POPM_rating < 0xFC) { // some players store 5 stars as 0xFC - return 0.80; // 4 stars + return 0.60; // 3 stars + } else if (POPM_rating < 0xFC) { // some players store 5 stars as 0xFC + return 0.80; // 4 stars } - return 1.0; // 5 stars + return 1.0; // 5 stars } int TagReader::ConvertToPOPMRating(const float rating) { diff --git a/ext/libclementine-tagreader/tagreader.h b/ext/libclementine-tagreader/tagreader.h index 7dafd25c0..28d989803 100644 --- a/ext/libclementine-tagreader/tagreader.h +++ b/ext/libclementine-tagreader/tagreader.h @@ -30,15 +30,14 @@ class QString; class QTextCodec; class QUrl; - namespace TagLib { - class FileRef; - class String; +class FileRef; +class String; - namespace ID3v2 { - class Tag; - class PopularimeterFrame; - } +namespace ID3v2 { +class Tag; +class PopularimeterFrame; +} } class FileRefFactory; @@ -52,25 +51,26 @@ class TagReader { public: TagReader(); - void ReadFile(const QString& filename, pb::tagreader::SongMetadata* song) const; - bool SaveFile(const QString& filename, const pb::tagreader::SongMetadata& song) const; + void ReadFile(const QString& filename, + pb::tagreader::SongMetadata* song) const; + bool SaveFile(const QString& filename, + const pb::tagreader::SongMetadata& song) const; // Returns false if something went wrong; returns true otherwise (might // returns true if the file exists but nothing has been written inside because // statistics tag format is not supported for this kind of file) - bool SaveSongStatisticsToFile(const QString& filename, const pb::tagreader::SongMetadata& song) const; - bool SaveSongRatingToFile(const QString& filename, const pb::tagreader::SongMetadata& song) const; + bool SaveSongStatisticsToFile(const QString& filename, + const pb::tagreader::SongMetadata& song) const; + bool SaveSongRatingToFile(const QString& filename, + const pb::tagreader::SongMetadata& song) const; bool IsMediaFile(const QString& filename) const; QByteArray LoadEmbeddedArt(const QString& filename) const; - #ifdef HAVE_GOOGLE_DRIVE - bool ReadCloudFile(const QUrl& download_url, - const QString& title, - int size, - const QString& mime_type, - const QString& access_token, +#ifdef HAVE_GOOGLE_DRIVE + bool ReadCloudFile(const QUrl& download_url, const QString& title, int size, + const QString& mime_type, const QString& access_token, pb::tagreader::SongMetadata* song) const; - #endif // HAVE_GOOGLE_DRIVE +#endif // HAVE_GOOGLE_DRIVE static void Decode(const TagLib::String& tag, const QTextCodec* codec, std::string* output); @@ -80,21 +80,24 @@ class TagReader { void ParseFMPSFrame(const QString& name, const QString& value, pb::tagreader::SongMetadata* song) const; void ParseOggTag(const TagLib::Ogg::FieldListMap& map, - const QTextCodec* codec, - QString* disc, QString* compilation, + const QTextCodec* codec, QString* disc, QString* compilation, pb::tagreader::SongMetadata* song) const; void SetVorbisComments(TagLib::Ogg::XiphComment* vorbis_comments, const pb::tagreader::SongMetadata& song) const; - void SetFMPSStatisticsVorbisComments(TagLib::Ogg::XiphComment* vorbis_comments, - const pb::tagreader::SongMetadata& song) const; + void SetFMPSStatisticsVorbisComments( + TagLib::Ogg::XiphComment* vorbis_comments, + const pb::tagreader::SongMetadata& song) const; void SetFMPSRatingVorbisComments(TagLib::Ogg::XiphComment* vorbis_comments, - const pb::tagreader::SongMetadata& song) const; + const pb::tagreader::SongMetadata& song) + const; - pb::tagreader::SongMetadata_Type GuessFileType(TagLib::FileRef* fileref) const; + pb::tagreader::SongMetadata_Type GuessFileType(TagLib::FileRef* fileref) + const; void SetUserTextFrame(const QString& description, const QString& value, TagLib::ID3v2::Tag* tag) const; - void SetUserTextFrame(const std::string& description, const std::string& value, + void SetUserTextFrame(const std::string& description, + const std::string& value, TagLib::ID3v2::Tag* tag) const; void SetTextFrame(const char* id, const QString& value, @@ -102,15 +105,17 @@ class TagReader { void SetTextFrame(const char* id, const std::string& value, TagLib::ID3v2::Tag* tag) const; -private: + private: static const char* kMP4_FMPS_Rating_ID; static const char* kMP4_FMPS_Playcount_ID; static const char* kMP4_FMPS_Score_ID; - // Returns a float in [0.0..1.0] corresponding to the rating range we use in Clementine + // Returns a float in [0.0..1.0] corresponding to the rating range we use in + // Clementine static float ConvertPOPMRating(const int POPM_rating); // Reciprocal static int ConvertToPOPMRating(const float rating); - static TagLib::ID3v2::PopularimeterFrame* GetPOPMFrameFromTag(TagLib::ID3v2::Tag* tag); + static TagLib::ID3v2::PopularimeterFrame* GetPOPMFrameFromTag( + TagLib::ID3v2::Tag* tag); FileRefFactory* factory_; QNetworkAccessManager* network_; @@ -118,4 +123,4 @@ private: const std::string kEmbeddedCover; }; -#endif // TAGREADER_H +#endif // TAGREADER_H diff --git a/src/analyzers/analyzer.cpp b/src/analyzers/analyzer.cpp index 1a6e1dda1..54d0667a0 100644 --- a/src/analyzers/analyzer.cpp +++ b/src/analyzers/analyzer.cpp @@ -3,15 +3,13 @@ #include "engines/enginebase.h" AnalyzerBase::AnalyzerBase(QWidget* parent) - : QGLWidget(parent), - engine_(nullptr) { -} + : QGLWidget(parent), engine_(nullptr) {} void AnalyzerBase::set_engine(Engine::Base* engine) { disconnect(engine_); engine_ = engine; if (engine_) { connect(engine_, SIGNAL(SpectrumAvailable(const QVector&)), - SLOT(SpectrumAvailable(const QVector&))); + SLOT(SpectrumAvailable(const QVector&))); } } diff --git a/src/analyzers/analyzerbase.cpp b/src/analyzers/analyzerbase.cpp index b4e12b91b..f0ca647b1 100644 --- a/src/analyzers/analyzerbase.cpp +++ b/src/analyzers/analyzerbase.cpp @@ -17,9 +17,9 @@ #include "analyzerbase.h" -#include //interpolate() +#include //interpolate() -#include //event() +#include //event() #include #include #include @@ -27,205 +27,186 @@ #include "engines/enginebase.h" // INSTRUCTIONS Base2D -// 1. do anything that depends on height() in init(), Base2D will call it before you are shown +// 1. do anything that depends on height() in init(), Base2D will call it before +// you are shown // 2. otherwise you can use the constructor to initialise things -// 3. reimplement analyze(), and paint to canvas(), Base2D will update the widget when you return control to it +// 3. reimplement analyze(), and paint to canvas(), Base2D will update the +// widget when you return control to it // 4. if you want to manipulate the scope, reimplement transform() // 5. for convenience are pre-included // TODO make an INSTRUCTIONS file -//can't mod scope in analyze you have to use transform +// can't mod scope in analyze you have to use transform - -//TODO for 2D use setErasePixmap Qt function insetead of m_background +// TODO for 2D use setErasePixmap Qt function insetead of m_background // make the linker happy only for gcc < 4.0 -#if !( __GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 0 ) ) && !defined(Q_OS_WIN32) +#if !(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 0)) && \ + !defined(Q_OS_WIN32) template class Analyzer::Base; #endif +Analyzer::Base::Base(QWidget* parent, uint scopeSize) + : QWidget(parent), + m_timeout(40) // msec + , + m_fht(new FHT(scopeSize)), + m_engine(nullptr), + m_lastScope(512), + new_frame_(false), + is_playing_(false) {} -Analyzer::Base::Base( QWidget *parent, uint scopeSize ) - : QWidget( parent ) - , m_timeout( 40 ) // msec - , m_fht( new FHT(scopeSize) ) - , m_engine(nullptr) - , m_lastScope(512) - , new_frame_(false) - , is_playing_(false) +void Analyzer::Base::hideEvent(QHideEvent*) { m_timer.stop(); } + +void Analyzer::Base::showEvent(QShowEvent*) { m_timer.start(timeout(), this); } + +void Analyzer::Base::transform(Scope& scope) // virtual { + // this is a standard transformation that should give + // an FFT scope that has bands for pretty analyzers + + // NOTE resizing here is redundant as FHT routines only calculate FHT::size() + // values + // scope.resize( m_fht->size() ); + + float* front = static_cast(&scope.front()); + + float* f = new float[m_fht->size()]; + m_fht->copy(&f[0], front); + m_fht->logSpectrum(front, &f[0]); + m_fht->scale(front, 1.0 / 20); + + scope.resize(m_fht->size() / 2); // second half of values are rubbish + delete[] f; } -void Analyzer::Base::hideEvent(QHideEvent *) { - m_timer.stop(); -} +void Analyzer::Base::paintEvent(QPaintEvent* e) { + QPainter p(this); + p.fillRect(e->rect(), palette().color(QPalette::Window)); -void Analyzer::Base::showEvent(QShowEvent *) { - m_timer.start(timeout(), this); -} + switch (m_engine->state()) { + case Engine::Playing: { + const Engine::Scope& thescope = m_engine->scope(); + int i = 0; -void Analyzer::Base::transform( Scope &scope ) //virtual -{ - //this is a standard transformation that should give - //an FFT scope that has bands for pretty analyzers + // convert to mono here - our built in analyzers need mono, but we the + // engines provide interleaved pcm + for (uint x = 0; (int)x < m_fht->size(); ++x) { + m_lastScope[x] = + double(thescope[i] + thescope[i + 1]) / (2 * (1 << 15)); + i += 2; + } - //NOTE resizing here is redundant as FHT routines only calculate FHT::size() values - //scope.resize( m_fht->size() ); + is_playing_ = true; + transform(m_lastScope); + analyze(p, m_lastScope, new_frame_); - float *front = static_cast( &scope.front() ); + // scope.resize( m_fht->size() ); - float* f = new float[ m_fht->size() ]; - m_fht->copy( &f[0], front ); - m_fht->logSpectrum( front, &f[0] ); - m_fht->scale( front, 1.0 / 20 ); - - scope.resize( m_fht->size() / 2 ); //second half of values are rubbish - delete [] f; -} - -void Analyzer::Base::paintEvent(QPaintEvent * e) -{ - QPainter p(this); - p.fillRect(e->rect(), palette().color(QPalette::Window)); - - switch( m_engine->state() ) - { - case Engine::Playing: - { - const Engine::Scope &thescope = m_engine->scope(); - int i = 0; - - // convert to mono here - our built in analyzers need mono, but we the engines provide interleaved pcm - for( uint x = 0; (int)x < m_fht->size(); ++x ) - { - m_lastScope[x] = double(thescope[i] + thescope[i+1]) / (2*(1<<15)); - i += 2; - } - - is_playing_ = true; - transform( m_lastScope ); - analyze( p, m_lastScope, new_frame_ ); - - //scope.resize( m_fht->size() ); - - break; + break; } case Engine::Paused: - is_playing_ = false; - analyze(p, m_lastScope, new_frame_); - break; + is_playing_ = false; + analyze(p, m_lastScope, new_frame_); + break; default: - is_playing_ = false; - demo(p); - } + is_playing_ = false; + demo(p); + } - - new_frame_ = false; + new_frame_ = false; } -int Analyzer::Base::resizeExponent( int exp ) -{ - if ( exp < 3 ) - exp = 3; - else if ( exp > 9 ) - exp = 9; +int Analyzer::Base::resizeExponent(int exp) { + if (exp < 3) + exp = 3; + else if (exp > 9) + exp = 9; - if ( exp != m_fht->sizeExp() ) { - delete m_fht; - m_fht = new FHT( exp ); - } - return exp; + if (exp != m_fht->sizeExp()) { + delete m_fht; + m_fht = new FHT(exp); + } + return exp; } -int Analyzer::Base::resizeForBands( int bands ) -{ - int exp; - if ( bands <= 8 ) - exp = 4; - else if ( bands <= 16 ) - exp = 5; - else if ( bands <= 32 ) - exp = 6; - else if ( bands <= 64 ) - exp = 7; - else if ( bands <= 128 ) - exp = 8; - else - exp = 9; +int Analyzer::Base::resizeForBands(int bands) { + int exp; + if (bands <= 8) + exp = 4; + else if (bands <= 16) + exp = 5; + else if (bands <= 32) + exp = 6; + else if (bands <= 64) + exp = 7; + else if (bands <= 128) + exp = 8; + else + exp = 9; - resizeExponent( exp ); - return m_fht->size() / 2; + resizeExponent(exp); + return m_fht->size() / 2; } -void Analyzer::Base::demo(QPainter& p) //virtual +void Analyzer::Base::demo(QPainter& p) // virtual { - static int t = 201; //FIXME make static to namespace perhaps + static int t = 201; // FIXME make static to namespace perhaps - if( t > 999 ) t = 1; //0 = wasted calculations - if( t < 201 ) - { - Scope s( 32 ); + if (t > 999) t = 1; // 0 = wasted calculations + if (t < 201) { + Scope s(32); - const double dt = double(t) / 200; - for( uint i = 0; i < s.size(); ++i ) - s[i] = dt * (sin( M_PI + (i * M_PI) / s.size() ) + 1.0); + const double dt = double(t) / 200; + for (uint i = 0; i < s.size(); ++i) + s[i] = dt * (sin(M_PI + (i * M_PI) / s.size()) + 1.0); - analyze( p, s, new_frame_ ); - } - else analyze( p, Scope( 32, 0 ), new_frame_ ); + analyze(p, s, new_frame_); + } else + analyze(p, Scope(32, 0), new_frame_); - ++t; + ++t; } - -void Analyzer::Base::polishEvent() -{ - init(); //virtual +void Analyzer::Base::polishEvent() { + init(); // virtual } -void -Analyzer::interpolate( const Scope &inVec, Scope &outVec ) //static +void Analyzer::interpolate(const Scope& inVec, Scope& outVec) // static { - double pos = 0.0; - const double step = (double)inVec.size() / outVec.size(); + double pos = 0.0; + const double step = (double)inVec.size() / outVec.size(); - for ( uint i = 0; i < outVec.size(); ++i, pos += step ) - { - const double error = pos - std::floor( pos ); - const unsigned long offset = (unsigned long)pos; + for (uint i = 0; i < outVec.size(); ++i, pos += step) { + const double error = pos - std::floor(pos); + const unsigned long offset = (unsigned long)pos; - unsigned long indexLeft = offset + 0; + unsigned long indexLeft = offset + 0; - if ( indexLeft >= inVec.size() ) - indexLeft = inVec.size() - 1; + if (indexLeft >= inVec.size()) indexLeft = inVec.size() - 1; - unsigned long indexRight = offset + 1; + unsigned long indexRight = offset + 1; - if ( indexRight >= inVec.size() ) - indexRight = inVec.size() - 1; + if (indexRight >= inVec.size()) indexRight = inVec.size() - 1; - outVec[i] = inVec[indexLeft ] * ( 1.0 - error ) + - inVec[indexRight] * error; - } + outVec[i] = inVec[indexLeft] * (1.0 - error) + inVec[indexRight] * error; + } } -void -Analyzer::initSin( Scope &v, const uint size ) //static +void Analyzer::initSin(Scope& v, const uint size) // static { - double step = ( M_PI * 2 ) / size; - double radian = 0; + double step = (M_PI * 2) / size; + double radian = 0; - for ( uint i = 0; i < size; i++ ) - { - v.push_back( sin( radian ) ); - radian += step; - } + for (uint i = 0; i < size; i++) { + v.push_back(sin(radian)); + radian += step; + } } void Analyzer::Base::timerEvent(QTimerEvent* e) { QWidget::timerEvent(e); - if (e->timerId() != m_timer.timerId()) - return; + if (e->timerId() != m_timer.timerId()) return; new_frame_ = true; update(); diff --git a/src/analyzers/analyzerbase.h b/src/analyzers/analyzerbase.h index dc79af002..f6c7eebfd 100644 --- a/src/analyzers/analyzerbase.h +++ b/src/analyzers/analyzerbase.h @@ -4,19 +4,18 @@ #ifndef ANALYZERBASE_H #define ANALYZERBASE_H - #ifdef __FreeBSD__ #include #endif -#include "core/fht.h" //stack allocated and convenience +#include "core/fht.h" //stack allocated and convenience #include "engines/engine_fwd.h" -#include //stack allocated and convenience +#include //stack allocated and convenience #include //stack allocated -#include //baseclass -#include //included for convenience +#include //baseclass +#include //included for convenience -#include //baseclass +#include //baseclass #ifdef Q_WS_MACX #include //included for convenience #include //included for convenience @@ -29,63 +28,60 @@ class QEvent; class QPaintEvent; class QResizeEvent; - namespace Analyzer { typedef std::vector Scope; -class Base : public QWidget -{ +class Base : public QWidget { Q_OBJECT -public: - ~Base() { delete m_fht; } + public: + ~Base() { delete m_fht; } - uint timeout() const { return m_timeout; } + uint timeout() const { return m_timeout; } - void set_engine(EngineBase* engine) { m_engine = engine; } + void set_engine(EngineBase* engine) { m_engine = engine; } - void changeTimeout( uint newTimeout ) { - m_timeout = newTimeout; - if (m_timer.isActive()) { - m_timer.stop(); - m_timer.start(m_timeout, this); - } + void changeTimeout(uint newTimeout) { + m_timeout = newTimeout; + if (m_timer.isActive()) { + m_timer.stop(); + m_timer.start(m_timeout, this); } + } -protected: - Base( QWidget*, uint scopeSize = 7 ); + protected: + Base(QWidget*, uint scopeSize = 7); - void hideEvent(QHideEvent *); - void showEvent(QShowEvent *); - void paintEvent( QPaintEvent* ); - void timerEvent(QTimerEvent *); + void hideEvent(QHideEvent*); + void showEvent(QShowEvent*); + void paintEvent(QPaintEvent*); + void timerEvent(QTimerEvent*); - void polishEvent(); + void polishEvent(); - int resizeExponent( int ); - int resizeForBands( int ); - virtual void init() {} - virtual void transform( Scope& ); - virtual void analyze( QPainter& p, const Scope&, bool new_frame) = 0; - virtual void demo(QPainter& p); + int resizeExponent(int); + int resizeForBands(int); + virtual void init() {} + virtual void transform(Scope&); + virtual void analyze(QPainter& p, const Scope&, bool new_frame) = 0; + virtual void demo(QPainter& p); -protected: - QBasicTimer m_timer; - uint m_timeout; - FHT *m_fht; - EngineBase* m_engine; - Scope m_lastScope; + protected: + QBasicTimer m_timer; + uint m_timeout; + FHT* m_fht; + EngineBase* m_engine; + Scope m_lastScope; - bool new_frame_; - bool is_playing_; + bool new_frame_; + bool is_playing_; }; +void interpolate(const Scope&, Scope&); +void initSin(Scope&, const uint = 6000); -void interpolate( const Scope&, Scope& ); -void initSin( Scope&, const uint = 6000 ); - -} //END namespace Analyzer +} // END namespace Analyzer using Analyzer::Scope; diff --git a/src/analyzers/analyzercontainer.cpp b/src/analyzers/analyzercontainer.cpp index e3478a3b8..e6bd00ec1 100644 --- a/src/analyzers/analyzercontainer.cpp +++ b/src/analyzers/analyzercontainer.cpp @@ -39,21 +39,20 @@ const int AnalyzerContainer::kMediumFramerate = 25; const int AnalyzerContainer::kHighFramerate = 30; const int AnalyzerContainer::kSuperHighFramerate = 60; -AnalyzerContainer::AnalyzerContainer(QWidget *parent) - : QWidget(parent), - current_framerate_(kMediumFramerate), - context_menu_(new QMenu(this)), - context_menu_framerate_(new QMenu(tr("Framerate"), this)), - group_(new QActionGroup(this)), - group_framerate_(new QActionGroup(this)), - mapper_(new QSignalMapper(this)), - mapper_framerate_(new QSignalMapper(this)), - visualisation_action_(nullptr), - double_click_timer_(new QTimer(this)), - ignore_next_click_(false), - current_analyzer_(nullptr), - engine_(nullptr) -{ +AnalyzerContainer::AnalyzerContainer(QWidget* parent) + : QWidget(parent), + current_framerate_(kMediumFramerate), + context_menu_(new QMenu(this)), + context_menu_framerate_(new QMenu(tr("Framerate"), this)), + group_(new QActionGroup(this)), + group_framerate_(new QActionGroup(this)), + mapper_(new QSignalMapper(this)), + mapper_framerate_(new QSignalMapper(this)), + visualisation_action_(nullptr), + double_click_timer_(new QTimer(this)), + ignore_next_click_(false), + current_analyzer_(nullptr), + engine_(nullptr) { QHBoxLayout* layout = new QHBoxLayout(this); setLayout(layout); layout->setContentsMargins(0, 0, 0, 0); @@ -62,7 +61,8 @@ AnalyzerContainer::AnalyzerContainer(QWidget *parent) AddFramerate(tr("Low (%1 fps)").arg(kLowFramerate), kLowFramerate); AddFramerate(tr("Medium (%1 fps)").arg(kMediumFramerate), kMediumFramerate); AddFramerate(tr("High (%1 fps)").arg(kHighFramerate), kHighFramerate); - AddFramerate(tr("Super high (%1 fps)").arg(kSuperHighFramerate), kSuperHighFramerate); + AddFramerate(tr("Super high (%1 fps)").arg(kSuperHighFramerate), + kSuperHighFramerate); connect(mapper_framerate_, SIGNAL(mapped(int)), SLOT(ChangeFramerate(int))); context_menu_->addMenu(context_menu_framerate_); @@ -76,8 +76,8 @@ AnalyzerContainer::AnalyzerContainer(QWidget *parent) AddAnalyzerType(); connect(mapper_, SIGNAL(mapped(int)), SLOT(ChangeAnalyzer(int))); - disable_action_ = - context_menu_->addAction(tr("No analyzer"), this, SLOT(DisableAnalyzer())); + disable_action_ = context_menu_->addAction(tr("No analyzer"), this, + SLOT(DisableAnalyzer())); disable_action_->setCheckable(true); group_->addAction(disable_action_); @@ -115,12 +115,11 @@ void AnalyzerContainer::ShowPopupMenu() { context_menu_->popup(last_click_pos_); } -void AnalyzerContainer::mouseDoubleClickEvent(QMouseEvent *) { +void AnalyzerContainer::mouseDoubleClickEvent(QMouseEvent*) { double_click_timer_->stop(); ignore_next_click_ = true; - if (visualisation_action_) - visualisation_action_->trigger(); + if (visualisation_action_) visualisation_action_->trigger(); } void AnalyzerContainer::wheelEvent(QWheelEvent* e) { @@ -128,8 +127,7 @@ void AnalyzerContainer::wheelEvent(QWheelEvent* e) { } void AnalyzerContainer::SetEngine(EngineBase* engine) { - if (current_analyzer_) - current_analyzer_->set_engine(engine); + if (current_analyzer_) current_analyzer_->set_engine(engine); engine_ = engine; } @@ -144,7 +142,8 @@ void AnalyzerContainer::ChangeAnalyzer(int id) { QObject* instance = analyzer_types_[id]->newInstance(Q_ARG(QWidget*, this)); if (!instance) { - qLog(Warning) << "Couldn't intialise a new" << analyzer_types_[id]->className(); + qLog(Warning) << "Couldn't intialise a new" + << analyzer_types_[id]->className(); return; } @@ -152,7 +151,8 @@ void AnalyzerContainer::ChangeAnalyzer(int id) { current_analyzer_ = qobject_cast(instance); current_analyzer_->set_engine(engine_); // Even if it is not supposed to happen, I don't want to get a dbz error - current_framerate_ = current_framerate_ == 0 ? kMediumFramerate : current_framerate_; + current_framerate_ = + current_framerate_ == 0 ? kMediumFramerate : current_framerate_; current_analyzer_->changeTimeout(1000 / current_framerate_); layout()->addWidget(current_analyzer_); @@ -161,7 +161,7 @@ void AnalyzerContainer::ChangeAnalyzer(int id) { } void AnalyzerContainer::ChangeFramerate(int new_framerate) { - if(current_analyzer_) { + if (current_analyzer_) { // Even if it is not supposed to happen, I don't want to get a dbz error new_framerate = new_framerate == 0 ? kMediumFramerate : new_framerate; current_analyzer_->changeTimeout(1000 / new_framerate); @@ -179,7 +179,7 @@ void AnalyzerContainer::Load() { DisableAnalyzer(); disable_action_->setChecked(true); } else { - for (int i=0 ; iclassName()) { ChangeAnalyzer(i); actions_[i]->setChecked(true); @@ -190,8 +190,8 @@ void AnalyzerContainer::Load() { // Framerate current_framerate_ = s.value(kSettingsFramerate, kMediumFramerate).toInt(); - for (int i=0 ; iactions()[i]->setChecked(true); break; @@ -200,8 +200,8 @@ void AnalyzerContainer::Load() { } void AnalyzerContainer::SaveFramerate(int framerate) { -// For now, framerate is common for all analyzers. Maybe each analyzer should -// have its own framerate? + // For now, framerate is common for all analyzers. Maybe each analyzer should + // have its own framerate? current_framerate_ = framerate; QSettings s; s.beginGroup(kSettingsGroup); @@ -212,13 +212,14 @@ void AnalyzerContainer::Save() { QSettings s; s.beginGroup(kSettingsGroup); - s.setValue("type", current_analyzer_ ? - current_analyzer_->metaObject()->className() : - QVariant()); + s.setValue("type", current_analyzer_ + ? current_analyzer_->metaObject()->className() + : QVariant()); } void AnalyzerContainer::AddFramerate(const QString& name, int framerate) { - QAction *action = context_menu_framerate_->addAction(name, mapper_framerate_, SLOT(map())); + QAction* action = + context_menu_framerate_->addAction(name, mapper_framerate_, SLOT(map())); mapper_framerate_->setMapping(action, framerate); group_framerate_->addAction(action); framerate_list_ << framerate; diff --git a/src/analyzers/analyzercontainer.h b/src/analyzers/analyzercontainer.h index 20035798e..b9405d325 100644 --- a/src/analyzers/analyzercontainer.h +++ b/src/analyzers/analyzercontainer.h @@ -28,7 +28,7 @@ class AnalyzerContainer : public QWidget { Q_OBJECT -public: + public: AnalyzerContainer(QWidget* parent); void SetEngine(EngineBase* engine); @@ -40,18 +40,18 @@ public: signals: void WheelEvent(int delta); -protected: - void mouseReleaseEvent(QMouseEvent *); - void mouseDoubleClickEvent(QMouseEvent *); + protected: + void mouseReleaseEvent(QMouseEvent*); + void mouseDoubleClickEvent(QMouseEvent*); void wheelEvent(QWheelEvent* e); -private slots: + private slots: void ChangeAnalyzer(int id); void ChangeFramerate(int new_framerate); void DisableAnalyzer(); void ShowPopupMenu(); -private: + private: static const int kLowFramerate; static const int kMediumFramerate; static const int kHighFramerate; @@ -61,11 +61,11 @@ private: void Save(); void SaveFramerate(int framerate); template - void AddAnalyzerType(); + void AddAnalyzerType(); void AddFramerate(const QString& name, int framerate); -private: - int current_framerate_; // fps + private: + int current_framerate_; // fps QMenu* context_menu_; QMenu* context_menu_framerate_; QActionGroup* group_; @@ -88,11 +88,12 @@ private: }; template - void AnalyzerContainer::AddAnalyzerType() { +void AnalyzerContainer::AddAnalyzerType() { int id = analyzer_types_.count(); analyzer_types_ << &T::staticMetaObject; - QAction* action = context_menu_->addAction(tr(T::kName), mapper_, SLOT(map())); + QAction* action = + context_menu_->addAction(tr(T::kName), mapper_, SLOT(map())); group_->addAction(action); mapper_->setMapping(action, id); action->setCheckable(true); @@ -100,4 +101,3 @@ template } #endif - diff --git a/src/analyzers/baranalyzer.cpp b/src/analyzers/baranalyzer.cpp index 1e9844289..c4a39bc54 100644 --- a/src/analyzers/baranalyzer.cpp +++ b/src/analyzers/baranalyzer.cpp @@ -12,155 +12,150 @@ // #include "baranalyzer.h" -#include //log10(), etc. +#include //log10(), etc. #include #include -const char* BarAnalyzer::kName = QT_TRANSLATE_NOOP("AnalyzerContainer", "Bar analyzer"); +const char* BarAnalyzer::kName = + QT_TRANSLATE_NOOP("AnalyzerContainer", "Bar analyzer"); - -BarAnalyzer::BarAnalyzer( QWidget *parent ) - : Analyzer::Base( parent, 8 ) - //, m_bands( BAND_COUNT ) - //, barVector( BAND_COUNT, 0 ) - //, roofVector( BAND_COUNT, 50 ) - //, roofVelocityVector( BAND_COUNT, ROOF_VELOCITY_REDUCTION_FACTOR ) +BarAnalyzer::BarAnalyzer(QWidget* parent) + : Analyzer::Base(parent, 8) + //, m_bands( BAND_COUNT ) + //, barVector( BAND_COUNT, 0 ) + //, roofVector( BAND_COUNT, 50 ) + //, roofVelocityVector( BAND_COUNT, ROOF_VELOCITY_REDUCTION_FACTOR ) { - //roof pixmaps don't depend on size() so we do in the ctor - m_bg = parent->palette().color(QPalette::Background); + // roof pixmaps don't depend on size() so we do in the ctor + m_bg = parent->palette().color(QPalette::Background); - QColor fg( 0xff, 0x50, 0x70 ); + QColor fg(0xff, 0x50, 0x70); - double dr = double(m_bg.red() - fg.red()) / (NUM_ROOFS-1); //-1 because we start loop below at 0 - double dg = double(m_bg.green() - fg.green()) / (NUM_ROOFS-1); - double db = double(m_bg.blue() - fg.blue()) / (NUM_ROOFS-1); - - for ( uint i = 0; i < NUM_ROOFS; ++i ) - { - m_pixRoof[i] = QPixmap( COLUMN_WIDTH, 1 ); - m_pixRoof[i].fill( QColor( fg.red()+int(dr*i), fg.green()+int(dg*i), fg.blue()+int(db*i) ) ); - } + double dr = double(m_bg.red() - fg.red()) / + (NUM_ROOFS - 1); //-1 because we start loop below at 0 + double dg = double(m_bg.green() - fg.green()) / (NUM_ROOFS - 1); + double db = double(m_bg.blue() - fg.blue()) / (NUM_ROOFS - 1); + for (uint i = 0; i < NUM_ROOFS; ++i) { + m_pixRoof[i] = QPixmap(COLUMN_WIDTH, 1); + m_pixRoof[i].fill(QColor(fg.red() + int(dr * i), fg.green() + int(dg * i), + fg.blue() + int(db * i))); + } } -void BarAnalyzer::resizeEvent( QResizeEvent * e ) -{ - init(); -} +void BarAnalyzer::resizeEvent(QResizeEvent* e) { init(); } // METHODS ===================================================== -void BarAnalyzer::init() -{ - const double MAX_AMPLITUDE = 1.0; - const double F = double(height() - 2) / (log10( 255 ) * MAX_AMPLITUDE ); +void BarAnalyzer::init() { + const double MAX_AMPLITUDE = 1.0; + const double F = double(height() - 2) / (log10(255) * MAX_AMPLITUDE); + BAND_COUNT = width() / 5; + MAX_DOWN = int(0 - (qMax(1, height() / 50))); + MAX_UP = int(qMax(1, height() / 25)); - BAND_COUNT = width() / 5; - MAX_DOWN = int(0 -(qMax(1, height() / 50))); - MAX_UP = int(qMax(1, height() / 25)); + barVector.resize(BAND_COUNT, 0); + roofVector.resize(BAND_COUNT, height() - 5); + roofVelocityVector.resize(BAND_COUNT, ROOF_VELOCITY_REDUCTION_FACTOR); + m_roofMem.resize(BAND_COUNT); + m_scope.resize(BAND_COUNT); - barVector.resize( BAND_COUNT, 0 ); - roofVector.resize( BAND_COUNT, height() -5 ); - roofVelocityVector.resize( BAND_COUNT, ROOF_VELOCITY_REDUCTION_FACTOR ); - m_roofMem.resize(BAND_COUNT); - m_scope.resize(BAND_COUNT); + // generate a list of values that express amplitudes in range 0-MAX_AMP as + // ints from 0-height() on log scale + for (uint x = 0; x < 256; ++x) { + m_lvlMapper[x] = uint(F * log10(x + 1)); + } - //generate a list of values that express amplitudes in range 0-MAX_AMP as ints from 0-height() on log scale - for ( uint x = 0; x < 256; ++x ) - { - m_lvlMapper[x] = uint( F * log10( x+1 ) ); + m_pixBarGradient = QPixmap(height() * COLUMN_WIDTH, height()); + m_pixCompose = QPixmap(size()); + + QPainter p(&m_pixBarGradient); + for (int x = 0, r = 0x40, g = 0x30, b = 0xff, r2 = 255 - r; x < height(); + ++x) { + for (int y = x; y > 0; --y) { + const double fraction = (double)y / height(); + + // p.setPen( QColor( r + (int)(r2 * fraction), g, b - (int)(255 * + // fraction) ) ); + p.setPen(QColor(r + (int)(r2 * fraction), g, b)); + p.drawLine(x * COLUMN_WIDTH, height() - y, (x + 1) * COLUMN_WIDTH, + height() - y); } + } - m_pixBarGradient = QPixmap( height()*COLUMN_WIDTH, height() ); - m_pixCompose = QPixmap( size() ); - - QPainter p( &m_pixBarGradient ); - for ( int x=0, r=0x40, g=0x30, b=0xff, r2=255-r; - x < height(); ++x ) - { - for ( int y = x; y > 0; --y ) - { - const double fraction = (double)y / height(); - -// p.setPen( QColor( r + (int)(r2 * fraction), g, b - (int)(255 * fraction) ) ); - p.setPen( QColor( r + (int)(r2 * fraction), g, b ) ); - p.drawLine( x*COLUMN_WIDTH, height() - y, (x+1)*COLUMN_WIDTH, height() - y ); - } - } - - - setMinimumSize( QSize( BAND_COUNT * COLUMN_WIDTH, 10 ) ); + setMinimumSize(QSize(BAND_COUNT * COLUMN_WIDTH, 10)); } +void BarAnalyzer::analyze(QPainter& p, const Scope& s, bool new_frame) { + // Analyzer::interpolate( s, m_bands ); -void BarAnalyzer::analyze( QPainter& p, const Scope &s, bool new_frame) -{ - //Analyzer::interpolate( s, m_bands ); + Scope& v = m_scope; + Analyzer::interpolate(s, v); - Scope &v = m_scope; - Analyzer::interpolate( s, v ); + for (uint i = 0, x = 0, y2; i < v.size(); ++i, x += COLUMN_WIDTH + 1) { + // assign pre[log10]'d value + y2 = uint(v[i] * + 256); // 256 will be optimised to a bitshift //no, it's a float + y2 = m_lvlMapper[(y2 > 255) ? 255 : y2]; // lvlMapper is array of ints with + // values 0 to height() - for ( uint i = 0, x = 0, y2; i < v.size(); ++i, x+=COLUMN_WIDTH+1 ) - { - //assign pre[log10]'d value - y2 = uint(v[i] * 256); //256 will be optimised to a bitshift //no, it's a float - y2 = m_lvlMapper[ (y2 > 255) ? 255 : y2 ]; //lvlMapper is array of ints with values 0 to height() + int change = y2 - barVector[i]; - int change = y2 - barVector[i]; + // using the best of Markey's, piggz and Max's ideas on the way to shift the + // bars + // we have the following: + // 1. don't adjust shift when doing small up movements + // 2. shift large upwards with a bias towards last value + // 3. fall downwards at a constant pace - //using the best of Markey's, piggz and Max's ideas on the way to shift the bars - //we have the following: - // 1. don't adjust shift when doing small up movements - // 2. shift large upwards with a bias towards last value - // 3. fall downwards at a constant pace - - /*if ( change > MAX_UP ) //anything too much greater than 2 gives "jitter" + /*if ( change > MAX_UP ) //anything too much greater than 2 gives "jitter" //add some dynamics - makes the value slightly closer to what it was last time y2 = ( barVector[i] + MAX_UP ); //y2 = ( barVector[i] * 2 + y2 ) / 3; - else*/ if ( change < MAX_DOWN ) - y2 = barVector[i] + MAX_DOWN; + else*/ if (change < + MAX_DOWN) + y2 = barVector[i] + MAX_DOWN; - - if ( (int)y2 > roofVector[i] ) - { - roofVector[i] = (int)y2; - roofVelocityVector[i] = 1; - } - - //remember where we are - barVector[i] = y2; - - if ( m_roofMem[i].size() > NUM_ROOFS ) - m_roofMem[i].erase( m_roofMem[i].begin() ); - - //blt last n roofs, a.k.a motion blur - for ( uint c = 0; c < m_roofMem[i].size(); ++c ) - //bitBlt( m_pComposePixmap, x, m_roofMem[i]->at( c ), m_roofPixmaps[ c ] ); - //bitBlt( canvas(), x, m_roofMem[i][c], &m_pixRoof[ NUM_ROOFS - 1 - c ] ); - p.drawPixmap(x, m_roofMem[i][c], m_pixRoof[ NUM_ROOFS - 1 - c ]); - - //blt the bar - p.drawPixmap(x, height() - y2, - *gradient(), y2 * COLUMN_WIDTH, height() - y2, COLUMN_WIDTH, y2); - /*bitBlt( canvas(), x, height() - y2, - gradient(), y2 * COLUMN_WIDTH, height() - y2, COLUMN_WIDTH, y2, Qt::CopyROP );*/ - - m_roofMem[i].push_back( height() - roofVector[i] - 2 ); - - //set roof parameters for the NEXT draw - if ( roofVelocityVector[i] != 0 ) - { - if ( roofVelocityVector[i] > 32 ) //no reason to do == 32 - roofVector[i] -= (roofVelocityVector[i] - 32) / 20; //trivial calculation - - if ( roofVector[i] < 0 ) - { - roofVector[i] = 0; //not strictly necessary - roofVelocityVector[i] = 0; - } - else ++roofVelocityVector[i]; - } + if ((int)y2 > roofVector[i]) { + roofVector[i] = (int)y2; + roofVelocityVector[i] = 1; } + + // remember where we are + barVector[i] = y2; + + if (m_roofMem[i].size() > NUM_ROOFS) + m_roofMem[i].erase(m_roofMem[i].begin()); + + // blt last n roofs, a.k.a motion blur + for (uint c = 0; c < m_roofMem[i].size(); ++c) + // bitBlt( m_pComposePixmap, x, m_roofMem[i]->at( c ), m_roofPixmaps[ c ] + // ); + // bitBlt( canvas(), x, m_roofMem[i][c], &m_pixRoof[ NUM_ROOFS - 1 - c ] + // ); + p.drawPixmap(x, m_roofMem[i][c], m_pixRoof[NUM_ROOFS - 1 - c]); + + // blt the bar + p.drawPixmap(x, height() - y2, *gradient(), y2 * COLUMN_WIDTH, + height() - y2, COLUMN_WIDTH, y2); + /*bitBlt( canvas(), x, height() - y2, + gradient(), y2 * COLUMN_WIDTH, height() - y2, COLUMN_WIDTH, y2, + Qt::CopyROP );*/ + + m_roofMem[i].push_back(height() - roofVector[i] - 2); + + // set roof parameters for the NEXT draw + if (roofVelocityVector[i] != 0) { + if (roofVelocityVector[i] > 32) // no reason to do == 32 + roofVector[i] -= + (roofVelocityVector[i] - 32) / 20; // trivial calculation + + if (roofVector[i] < 0) { + roofVector[i] = 0; // not strictly necessary + roofVelocityVector[i] = 0; + } else + ++roofVelocityVector[i]; + } + } } diff --git a/src/analyzers/baranalyzer.h b/src/analyzers/baranalyzer.h index e3d8fdc75..d56fc4dee 100644 --- a/src/analyzers/baranalyzer.h +++ b/src/analyzers/baranalyzer.h @@ -10,51 +10,50 @@ typedef std::vector aroofMemVec; - -class BarAnalyzer : public Analyzer::Base -{ +class BarAnalyzer : public Analyzer::Base { Q_OBJECT - public: - Q_INVOKABLE BarAnalyzer( QWidget* ); + public: + Q_INVOKABLE BarAnalyzer(QWidget*); - void init(); - virtual void analyze( QPainter& p, const Scope&, bool new_frame); - //virtual void transform( Scope& ); + void init(); + virtual void analyze(QPainter& p, const Scope&, bool new_frame); + // virtual void transform( Scope& ); - /** - * Resizes the widget to a new geometry according to @p e - * @param e The resize-event - */ - void resizeEvent( QResizeEvent * e); + /** + * Resizes the widget to a new geometry according to @p e + * @param e The resize-event + */ + void resizeEvent(QResizeEvent* e); - uint BAND_COUNT; - int MAX_DOWN; - int MAX_UP; - static const uint ROOF_HOLD_TIME = 48; - static const int ROOF_VELOCITY_REDUCTION_FACTOR = 32; - static const uint NUM_ROOFS = 16; - static const uint COLUMN_WIDTH = 4; + uint BAND_COUNT; + int MAX_DOWN; + int MAX_UP; + static const uint ROOF_HOLD_TIME = 48; + static const int ROOF_VELOCITY_REDUCTION_FACTOR = 32; + static const uint NUM_ROOFS = 16; + static const uint COLUMN_WIDTH = 4; - static const char* kName; + static const char* kName; - protected: - QPixmap m_pixRoof[NUM_ROOFS]; - //vector m_roofMem[BAND_COUNT]; + protected: + QPixmap m_pixRoof[NUM_ROOFS]; + // vector m_roofMem[BAND_COUNT]; - //Scope m_bands; //copy of the Scope to prevent creating/destroying a Scope every iteration - uint m_lvlMapper[256]; - std::vector m_roofMem; - std::vector barVector; //positions of bars - std::vector roofVector; //positions of roofs - std::vector roofVelocityVector; //speed that roofs falls + // Scope m_bands; //copy of the Scope to prevent creating/destroying a Scope + // every iteration + uint m_lvlMapper[256]; + std::vector m_roofMem; + std::vector barVector; // positions of bars + std::vector roofVector; // positions of roofs + std::vector roofVelocityVector; // speed that roofs falls - const QPixmap *gradient() const { return &m_pixBarGradient; } + const QPixmap* gradient() const { return &m_pixBarGradient; } - private: - QPixmap m_pixBarGradient; - QPixmap m_pixCompose; - Scope m_scope; //so we don't create a vector every frame - QColor m_bg; + private: + QPixmap m_pixBarGradient; + QPixmap m_pixCompose; + Scope m_scope; // so we don't create a vector every frame + QColor m_bg; }; #endif diff --git a/src/analyzers/blockanalyzer.cpp b/src/analyzers/blockanalyzer.cpp index c36e3f032..f308c11ee 100644 --- a/src/analyzers/blockanalyzer.cpp +++ b/src/analyzers/blockanalyzer.cpp @@ -12,389 +12,392 @@ #include #include -const uint BlockAnalyzer::HEIGHT = 2; -const uint BlockAnalyzer::WIDTH = 4; -const uint BlockAnalyzer::MIN_ROWS = 3; //arbituary -const uint BlockAnalyzer::MIN_COLUMNS = 32; //arbituary -const uint BlockAnalyzer::MAX_COLUMNS = 256; //must be 2**n -const uint BlockAnalyzer::FADE_SIZE = 90; +const uint BlockAnalyzer::HEIGHT = 2; +const uint BlockAnalyzer::WIDTH = 4; +const uint BlockAnalyzer::MIN_ROWS = 3; // arbituary +const uint BlockAnalyzer::MIN_COLUMNS = 32; // arbituary +const uint BlockAnalyzer::MAX_COLUMNS = 256; // must be 2**n +const uint BlockAnalyzer::FADE_SIZE = 90; -const char* BlockAnalyzer::kName = QT_TRANSLATE_NOOP("AnalyzerContainer", "Block analyzer"); +const char* BlockAnalyzer::kName = + QT_TRANSLATE_NOOP("AnalyzerContainer", "Block analyzer"); -BlockAnalyzer::BlockAnalyzer( QWidget *parent ) - : Analyzer::Base( parent, 9 ) - , m_columns( 0 ) //uint - , m_rows( 0 ) //uint - , m_y( 0 ) //uint - , m_barPixmap( 1, 1 ) //null qpixmaps cause crashes - , m_topBarPixmap( WIDTH, HEIGHT ) - , m_scope( MIN_COLUMNS ) //Scope - , m_store( 1 << 8, 0 ) //vector - , m_fade_bars( FADE_SIZE ) //vector - , m_fade_pos( 1 << 8, 50 ) //vector - , m_fade_intensity( 1 << 8, 32 ) //vector +BlockAnalyzer::BlockAnalyzer(QWidget* parent) + : Analyzer::Base(parent, 9), + m_columns(0) // uint + , + m_rows(0) // uint + , + m_y(0) // uint + , + m_barPixmap(1, 1) // null qpixmaps cause crashes + , + m_topBarPixmap(WIDTH, HEIGHT), + m_scope(MIN_COLUMNS) // Scope + , + m_store(1 << 8, 0) // vector + , + m_fade_bars(FADE_SIZE) // vector + , + m_fade_pos(1 << 8, 50) // vector + , + m_fade_intensity(1 << 8, 32) // vector { - setMinimumSize( MIN_COLUMNS*(WIDTH+1) -1, MIN_ROWS*(HEIGHT+1) -1 ); //-1 is padding, no drawing takes place there - setMaximumWidth( MAX_COLUMNS*(WIDTH+1) -1 ); + setMinimumSize(MIN_COLUMNS * (WIDTH + 1) - 1, + MIN_ROWS * (HEIGHT + 1) - + 1); //-1 is padding, no drawing takes place there + setMaximumWidth(MAX_COLUMNS * (WIDTH + 1) - 1); - // mxcl says null pixmaps cause crashes, so let's play it safe - for ( uint i = 0; i < FADE_SIZE; ++i ) - m_fade_bars[i] = QPixmap( 1, 1 ); + // mxcl says null pixmaps cause crashes, so let's play it safe + for (uint i = 0; i < FADE_SIZE; ++i) m_fade_bars[i] = QPixmap(1, 1); } -BlockAnalyzer::~BlockAnalyzer() -{ +BlockAnalyzer::~BlockAnalyzer() {} + +void BlockAnalyzer::resizeEvent(QResizeEvent* e) { + QWidget::resizeEvent(e); + + m_background = QPixmap(size()); + + const uint oldRows = m_rows; + + // all is explained in analyze().. + //+1 to counter -1 in maxSizes, trust me we need this! + m_columns = qMax(uint(double(width() + 1) / (WIDTH + 1)), MAX_COLUMNS); + m_rows = uint(double(height() + 1) / (HEIGHT + 1)); + + // this is the y-offset for drawing from the top of the widget + m_y = (height() - (m_rows * (HEIGHT + 1)) + 2) / 2; + + m_scope.resize(m_columns); + + if (m_rows != oldRows) { + m_barPixmap = QPixmap(WIDTH, m_rows * (HEIGHT + 1)); + + for (uint i = 0; i < FADE_SIZE; ++i) + m_fade_bars[i] = QPixmap(WIDTH, m_rows * (HEIGHT + 1)); + + m_yscale.resize(m_rows + 1); + + const uint PRE = 1, + PRO = 1; // PRE and PRO allow us to restrict the range somewhat + + for (uint z = 0; z < m_rows; ++z) + m_yscale[z] = 1 - (log10(PRE + z) / log10(PRE + m_rows + PRO)); + + m_yscale[m_rows] = 0; + + determineStep(); + paletteChange(palette()); + } + + drawBackground(); } -void -BlockAnalyzer::resizeEvent( QResizeEvent *e ) -{ - QWidget::resizeEvent( e ); +void BlockAnalyzer::determineStep() { + // falltime is dependent on rowcount due to our digital resolution (ie we have + // boxes/blocks of pixels) + // I calculated the value 30 based on some trial and error - m_background = QPixmap(size()); - - const uint oldRows = m_rows; - - //all is explained in analyze().. - //+1 to counter -1 in maxSizes, trust me we need this! - m_columns = qMax( uint(double(width()+1) / (WIDTH+1)), MAX_COLUMNS ); - m_rows = uint(double(height()+1) / (HEIGHT+1)); - - //this is the y-offset for drawing from the top of the widget - m_y = (height() - (m_rows * (HEIGHT+1)) + 2) / 2; - - m_scope.resize( m_columns ); - - if( m_rows != oldRows ) { - m_barPixmap = QPixmap( WIDTH, m_rows*(HEIGHT+1) ); - - for ( uint i = 0; i < FADE_SIZE; ++i ) - m_fade_bars[i] = QPixmap( WIDTH, m_rows*(HEIGHT+1) ); - - m_yscale.resize( m_rows + 1 ); - - const uint PRE = 1, PRO = 1; //PRE and PRO allow us to restrict the range somewhat - - for( uint z = 0; z < m_rows; ++z ) - m_yscale[z] = 1 - (log10( PRE+z ) / log10( PRE+m_rows+PRO )); - - m_yscale[m_rows] = 0; - - determineStep(); - paletteChange( palette() ); - } - - - drawBackground(); + const double fallTime = 30 * m_rows; + m_step = double(m_rows * timeout()) / fallTime; } -void -BlockAnalyzer::determineStep() +void BlockAnalyzer::transform(Analyzer::Scope& s) // pure virtual { - // falltime is dependent on rowcount due to our digital resolution (ie we have boxes/blocks of pixels) - // I calculated the value 30 based on some trial and error + for (uint x = 0; x < s.size(); ++x) s[x] *= 2; - const double fallTime = 30 * m_rows; - m_step = double(m_rows * timeout()) / fallTime; + float* front = static_cast(&s.front()); + + m_fht->spectrum(front); + m_fht->scale(front, 1.0 / 20); + + // the second half is pretty dull, so only show it if the user has a large + // analyzer + // by setting to m_scope.size() if large we prevent interpolation of large + // analyzers, this is good! + s.resize(m_scope.size() <= MAX_COLUMNS / 2 ? MAX_COLUMNS / 2 + : m_scope.size()); } -void -BlockAnalyzer::transform( Analyzer::Scope &s ) //pure virtual -{ - for( uint x = 0; x < s.size(); ++x ) - s[x] *= 2; +void BlockAnalyzer::analyze(QPainter& p, const Analyzer::Scope& s, + bool new_frame) { + // y = 2 3 2 1 0 2 + // . . . . # . + // . . . # # . + // # . # # # # + // # # # # # # + // + // visual aid for how this analyzer works. + // y represents the number of blanks + // y starts from the top and increases in units of blocks - float *front = static_cast( &s.front() ); + // m_yscale looks similar to: { 0.7, 0.5, 0.25, 0.15, 0.1, 0 } + // if it contains 6 elements there are 5 rows in the analyzer - m_fht->spectrum( front ); - m_fht->scale( front, 1.0 / 20 ); + Analyzer::interpolate(s, m_scope); - //the second half is pretty dull, so only show it if the user has a large analyzer - //by setting to m_scope.size() if large we prevent interpolation of large analyzers, this is good! - s.resize( m_scope.size() <= MAX_COLUMNS/2 ? MAX_COLUMNS/2 : m_scope.size() ); -} + // Paint the background + p.drawPixmap(0, 0, m_background); -void -BlockAnalyzer::analyze( QPainter& p, const Analyzer::Scope &s, bool new_frame) -{ - // y = 2 3 2 1 0 2 - // . . . . # . - // . . . # # . - // # . # # # # - // # # # # # # - // - // visual aid for how this analyzer works. - // y represents the number of blanks - // y starts from the top and increases in units of blocks + for (uint y, x = 0; x < m_scope.size(); ++x) { + // determine y + for (y = 0; m_scope[x] < m_yscale[y]; ++y) + ; - // m_yscale looks similar to: { 0.7, 0.5, 0.25, 0.15, 0.1, 0 } - // if it contains 6 elements there are 5 rows in the analyzer + // this is opposite to what you'd think, higher than y + // means the bar is lower than y (physically) + if ((float)y > m_store[x]) + y = int(m_store[x] += m_step); + else + m_store[x] = y; - Analyzer::interpolate( s, m_scope ); - - // Paint the background - p.drawPixmap(0, 0, m_background); - - for( uint y, x = 0; x < m_scope.size(); ++x ) - { - // determine y - for( y = 0; m_scope[x] < m_yscale[y]; ++y ) - ; - - // this is opposite to what you'd think, higher than y - // means the bar is lower than y (physically) - if( (float)y > m_store[x] ) - y = int(m_store[x] += m_step); - else - m_store[x] = y; - - // if y is lower than m_fade_pos, then the bar has exceeded the height of the fadeout - // if the fadeout is quite faded now, then display the new one - if( y <= m_fade_pos[x] /*|| m_fade_intensity[x] < FADE_SIZE / 3*/ ) { - m_fade_pos[x] = y; - m_fade_intensity[x] = FADE_SIZE; - } - - if( m_fade_intensity[x] > 0 ) { - const uint offset = --m_fade_intensity[x]; - const uint y = m_y + (m_fade_pos[x] * (HEIGHT+1)); - p.drawPixmap(x*(WIDTH+1), y, m_fade_bars[offset], 0, 0, WIDTH, height() - y); - } - - if( m_fade_intensity[x] == 0 ) - m_fade_pos[x] = m_rows; - - //REMEMBER: y is a number from 0 to m_rows, 0 means all blocks are glowing, m_rows means none are - p.drawPixmap( x*(WIDTH+1), y*(HEIGHT+1) + m_y, *bar(), 0, y*(HEIGHT+1), bar()->width(), bar()->height() ); - } - - for( uint x = 0; x < m_store.size(); ++x ) - p.drawPixmap(x*(WIDTH+1), int(m_store[x])*(HEIGHT+1) + m_y, m_topBarPixmap ); -} - - - - - -static inline void -adjustToLimits( int &b, int &f, uint &amount ) -{ - // with a range of 0-255 and maximum adjustment of amount, - // maximise the difference between f and b - - if( b < f ) { - if( b > 255 - f ) { - amount -= f; - f = 0; - } else { - amount -= (255 - f); - f = 255; - } + // if y is lower than m_fade_pos, then the bar has exceeded the height of + // the fadeout + // if the fadeout is quite faded now, then display the new one + if (y <= m_fade_pos[x] /*|| m_fade_intensity[x] < FADE_SIZE / 3*/) { + m_fade_pos[x] = y; + m_fade_intensity[x] = FADE_SIZE; } - else { - if( f > 255 - b ) { - amount -= f; - f = 0; - } else { - amount -= (255 - f); - f = 255; - } + + if (m_fade_intensity[x] > 0) { + const uint offset = --m_fade_intensity[x]; + const uint y = m_y + (m_fade_pos[x] * (HEIGHT + 1)); + p.drawPixmap(x * (WIDTH + 1), y, m_fade_bars[offset], 0, 0, WIDTH, + height() - y); } + + if (m_fade_intensity[x] == 0) m_fade_pos[x] = m_rows; + + // REMEMBER: y is a number from 0 to m_rows, 0 means all blocks are glowing, + // m_rows means none are + p.drawPixmap(x * (WIDTH + 1), y * (HEIGHT + 1) + m_y, *bar(), 0, + y * (HEIGHT + 1), bar()->width(), bar()->height()); + } + + for (uint x = 0; x < m_store.size(); ++x) + p.drawPixmap(x * (WIDTH + 1), int(m_store[x]) * (HEIGHT + 1) + m_y, + m_topBarPixmap); +} + +static inline void adjustToLimits(int& b, int& f, uint& amount) { + // with a range of 0-255 and maximum adjustment of amount, + // maximise the difference between f and b + + if (b < f) { + if (b > 255 - f) { + amount -= f; + f = 0; + } else { + amount -= (255 - f); + f = 255; + } + } else { + if (f > 255 - b) { + amount -= f; + f = 0; + } else { + amount -= (255 - f); + f = 255; + } + } } /** * Clever contrast function * - * It will try to adjust the foreground color such that it contrasts well with the background + * It will try to adjust the foreground color such that it contrasts well with + *the background * It won't modify the hue of fg unless absolutely necessary * @return the adjusted form of fg */ -QColor -ensureContrast( const QColor &bg, const QColor &fg, uint _amount = 150 ) -{ - class OutputOnExit { - public: - OutputOnExit( const QColor &color ) : c( color ) {} - ~OutputOnExit() { int h,s,v; c.getHsv( &h, &s, &v ); } - private: - const QColor &c; - }; - - // hack so I don't have to cast everywhere - #define amount static_cast(_amount) -// #define STAMP debug() << (QValueList() << fh << fs << fv) << endl; -// #define STAMP1( string ) debug() << string << ": " << (QValueList() << fh << fs << fv) << endl; -// #define STAMP2( string, value ) debug() << string << "=" << value << ": " << (QValueList() << fh << fs << fv) << endl; - - OutputOnExit allocateOnTheStack( fg ); - - int bh, bs, bv; - int fh, fs, fv; - - bg.getHsv( &bh, &bs, &bv ); - fg.getHsv( &fh, &fs, &fv ); - - int dv = abs( bv - fv ); - -// STAMP2( "DV", dv ); - - // value is the best measure of contrast - // if there is enough difference in value already, return fg unchanged - if( dv > amount ) - return fg; - - int ds = abs( bs - fs ); - -// STAMP2( "DS", ds ); - - // saturation is good enough too. But not as good. TODO adapt this a little - if( ds > amount ) - return fg; - - int dh = abs( bh - fh ); - -// STAMP2( "DH", dh ); - - if( dh > 120 ) { - // a third of the colour wheel automatically guarentees contrast - // but only if the values are high enough and saturations significant enough - // to allow the colours to be visible and not be shades of grey or black - - // check the saturation for the two colours is sufficient that hue alone can - // provide sufficient contrast - if( ds > amount / 2 && (bs > 125 && fs > 125) ) -// STAMP1( "Sufficient saturation difference, and hues are compliemtary" ); - return fg; - else if( dv > amount / 2 && (bv > 125 && fv > 125) ) -// STAMP1( "Sufficient value difference, and hues are compliemtary" ); - return fg; - -// STAMP1( "Hues are complimentary but we must modify the value or saturation of the contrasting colour" ); - - //but either the colours are two desaturated, or too dark - //so we need to adjust the system, although not as much - ///_amount /= 2; +QColor ensureContrast(const QColor& bg, const QColor& fg, uint _amount = 150) { + class OutputOnExit { + public: + OutputOnExit(const QColor& color) : c(color) {} + ~OutputOnExit() { + int h, s, v; + c.getHsv(&h, &s, &v); } - if( fs < 50 && ds < 40 ) { - // low saturation on a low saturation is sad - const int tmp = 50 - fs; - fs = 50; - if( amount > tmp ) - _amount -= tmp; - else - _amount = 0; - } + private: + const QColor& c; + }; - // test that there is available value to honor our contrast requirement - if( 255 - dv < amount ) - { - // we have to modify the value and saturation of fg - //adjustToLimits( bv, fv, amount ); +// hack so I don't have to cast everywhere +#define amount static_cast(_amount) + // #define STAMP debug() << (QValueList() << fh << fs << fv) << endl; + // #define STAMP1( string ) debug() << string << ": " << + // (QValueList() << fh << fs << fv) << endl; + // #define STAMP2( string, value ) debug() << string << "=" << value << ": + // " << (QValueList() << fh << fs << fv) << endl; -// STAMP + OutputOnExit allocateOnTheStack(fg); - // see if we need to adjust the saturation - if( amount > 0 ) - adjustToLimits( bs, fs, _amount ); + int bh, bs, bv; + int fh, fs, fv; -// STAMP + bg.getHsv(&bh, &bs, &bv); + fg.getHsv(&fh, &fs, &fv); - // see if we need to adjust the hue - if( amount > 0 ) - fh += amount; // cycles around; + int dv = abs(bv - fv); -// STAMP + // STAMP2( "DV", dv ); - return QColor::fromHsv(fh, fs, fv); - } + // value is the best measure of contrast + // if there is enough difference in value already, return fg unchanged + if (dv > amount) return fg; -// STAMP + int ds = abs(bs - fs); - if( fv > bv && bv > amount ) - return QColor::fromHsv( fh, fs, bv - amount); + // STAMP2( "DS", ds ); -// STAMP + // saturation is good enough too. But not as good. TODO adapt this a little + if (ds > amount) return fg; - if( fv < bv && fv > amount ) - return QColor::fromHsv( fh, fs, fv - amount); + int dh = abs(bh - fh); -// STAMP + // STAMP2( "DH", dh ); - if( fv > bv && (255 - fv > amount) ) - return QColor::fromHsv( fh, fs, fv + amount); + if (dh > 120) { + // a third of the colour wheel automatically guarentees contrast + // but only if the values are high enough and saturations significant enough + // to allow the colours to be visible and not be shades of grey or black -// STAMP + // check the saturation for the two colours is sufficient that hue alone can + // provide sufficient contrast + if (ds > amount / 2 && (bs > 125 && fs > 125)) + // STAMP1( "Sufficient saturation difference, and hues are + // compliemtary" ); + return fg; + else if (dv > amount / 2 && (bv > 125 && fv > 125)) + // STAMP1( "Sufficient value difference, and hues are + // compliemtary" ); + return fg; - if( fv < bv && (255 - bv > amount ) ) - return QColor::fromHsv( fh, fs, bv + amount); + // STAMP1( "Hues are complimentary but we must modify the value or + // saturation of the contrasting colour" ); -// STAMP -// debug() << "Something went wrong!\n"; + // but either the colours are two desaturated, or too dark + // so we need to adjust the system, although not as much + ///_amount /= 2; + } - return Qt::blue; + if (fs < 50 && ds < 40) { + // low saturation on a low saturation is sad + const int tmp = 50 - fs; + fs = 50; + if (amount > tmp) + _amount -= tmp; + else + _amount = 0; + } - #undef amount -// #undef STAMP + // test that there is available value to honor our contrast requirement + if (255 - dv < amount) { + // we have to modify the value and saturation of fg + // adjustToLimits( bv, fv, amount ); + + // STAMP + + // see if we need to adjust the saturation + if (amount > 0) adjustToLimits(bs, fs, _amount); + + // STAMP + + // see if we need to adjust the hue + if (amount > 0) fh += amount; // cycles around; + + // STAMP + + return QColor::fromHsv(fh, fs, fv); + } + + // STAMP + + if (fv > bv && bv > amount) return QColor::fromHsv(fh, fs, bv - amount); + + // STAMP + + if (fv < bv && fv > amount) return QColor::fromHsv(fh, fs, fv - amount); + + // STAMP + + if (fv > bv && (255 - fv > amount)) + return QColor::fromHsv(fh, fs, fv + amount); + + // STAMP + + if (fv < bv && (255 - bv > amount)) + return QColor::fromHsv(fh, fs, bv + amount); + + // STAMP + // debug() << "Something went wrong!\n"; + + return Qt::blue; + +#undef amount + // #undef STAMP } -void -BlockAnalyzer::paletteChange( const QPalette& ) //virtual +void BlockAnalyzer::paletteChange(const QPalette&) // virtual { - const QColor bg = palette().color(QPalette::Background); - const QColor fg = ensureContrast( bg, palette().color(QPalette::Highlight) ); + const QColor bg = palette().color(QPalette::Background); + const QColor fg = ensureContrast(bg, palette().color(QPalette::Highlight)); - m_topBarPixmap.fill( fg ); + m_topBarPixmap.fill(fg); - const double dr = 15*double(bg.red() - fg.red()) / (m_rows*16); - const double dg = 15*double(bg.green() - fg.green()) / (m_rows*16); - const double db = 15*double(bg.blue() - fg.blue()) / (m_rows*16); - const int r = fg.red(), g = fg.green(), b = fg.blue(); + const double dr = 15 * double(bg.red() - fg.red()) / (m_rows * 16); + const double dg = 15 * double(bg.green() - fg.green()) / (m_rows * 16); + const double db = 15 * double(bg.blue() - fg.blue()) / (m_rows * 16); + const int r = fg.red(), g = fg.green(), b = fg.blue(); - bar()->fill( bg ); + bar()->fill(bg); - QPainter p( bar() ); - for( int y = 0; (uint)y < m_rows; ++y ) - //graduate the fg color - p.fillRect( 0, y*(HEIGHT+1), WIDTH, HEIGHT, QColor( r+int(dr*y), g+int(dg*y), b+int(db*y) ) ); + QPainter p(bar()); + for (int y = 0; (uint)y < m_rows; ++y) + // graduate the fg color + p.fillRect(0, y * (HEIGHT + 1), WIDTH, HEIGHT, + QColor(r + int(dr * y), g + int(dg * y), b + int(db * y))); - { - const QColor bg = palette().color(QPalette::Background).dark( 112 ); + { + const QColor bg = palette().color(QPalette::Background).dark(112); - //make a complimentary fadebar colour - //TODO dark is not always correct, dumbo! - int h,s,v; palette().color(QPalette::Background).dark( 150 ).getHsv( &h, &s, &v ); - const QColor fg( QColor::fromHsv(h + 120, s, v)); + // make a complimentary fadebar colour + // TODO dark is not always correct, dumbo! + int h, s, v; + palette().color(QPalette::Background).dark(150).getHsv(&h, &s, &v); + const QColor fg(QColor::fromHsv(h + 120, s, v)); - const double dr = fg.red() - bg.red(); - const double dg = fg.green() - bg.green(); - const double db = fg.blue() - bg.blue(); - const int r = bg.red(), g = bg.green(), b = bg.blue(); + const double dr = fg.red() - bg.red(); + const double dg = fg.green() - bg.green(); + const double db = fg.blue() - bg.blue(); + const int r = bg.red(), g = bg.green(), b = bg.blue(); - // Precalculate all fade-bar pixmaps - for( uint y = 0; y < FADE_SIZE; ++y ) { - m_fade_bars[y].fill( palette().color(QPalette::Background) ); - QPainter f( &m_fade_bars[y] ); - for( int z = 0; (uint)z < m_rows; ++z ) { - const double Y = 1.0 - (log10( FADE_SIZE - y ) / log10( FADE_SIZE )); - f.fillRect( 0, z*(HEIGHT+1), WIDTH, HEIGHT, QColor( r+int(dr*Y), g+int(dg*Y), b+int(db*Y) ) ); - } + // Precalculate all fade-bar pixmaps + for (uint y = 0; y < FADE_SIZE; ++y) { + m_fade_bars[y].fill(palette().color(QPalette::Background)); + QPainter f(&m_fade_bars[y]); + for (int z = 0; (uint)z < m_rows; ++z) { + const double Y = 1.0 - (log10(FADE_SIZE - y) / log10(FADE_SIZE)); + f.fillRect(0, z * (HEIGHT + 1), WIDTH, HEIGHT, + QColor(r + int(dr * Y), g + int(dg * Y), b + int(db * Y))); } - } + } + } - drawBackground(); + drawBackground(); } -void -BlockAnalyzer::drawBackground() -{ - const QColor bg = palette().color(QPalette::Background); - const QColor bgdark = bg.dark( 112 ); +void BlockAnalyzer::drawBackground() { + const QColor bg = palette().color(QPalette::Background); + const QColor bgdark = bg.dark(112); - m_background.fill( bg ); + m_background.fill(bg); - QPainter p( &m_background ); - for( int x = 0; (uint)x < m_columns; ++x ) - for( int y = 0; (uint)y < m_rows; ++y ) - p.fillRect( x*(WIDTH+1), y*(HEIGHT+1) + m_y, WIDTH, HEIGHT, bgdark ); + QPainter p(&m_background); + for (int x = 0; (uint)x < m_columns; ++x) + for (int y = 0; (uint)y < m_rows; ++y) + p.fillRect(x * (WIDTH + 1), y * (HEIGHT + 1) + m_y, WIDTH, HEIGHT, + bgdark); } diff --git a/src/analyzers/blockanalyzer.h b/src/analyzers/blockanalyzer.h index 5894844f3..55f4b3a56 100644 --- a/src/analyzers/blockanalyzer.h +++ b/src/analyzers/blockanalyzer.h @@ -12,54 +12,52 @@ class QResizeEvent; class QMouseEvent; class QPalette; - /** * @author Max Howell */ -class BlockAnalyzer : public Analyzer::Base -{ +class BlockAnalyzer : public Analyzer::Base { Q_OBJECT -public: - Q_INVOKABLE BlockAnalyzer( QWidget* ); - ~BlockAnalyzer(); + public: + Q_INVOKABLE BlockAnalyzer(QWidget*); + ~BlockAnalyzer(); - static const uint HEIGHT; - static const uint WIDTH; - static const uint MIN_ROWS; - static const uint MIN_COLUMNS; - static const uint MAX_COLUMNS; - static const uint FADE_SIZE; + static const uint HEIGHT; + static const uint WIDTH; + static const uint MIN_ROWS; + static const uint MIN_COLUMNS; + static const uint MAX_COLUMNS; + static const uint FADE_SIZE; - static const char* kName; + static const char* kName; -protected: - virtual void transform( Scope& ); - virtual void analyze( QPainter& p, const Scope&, bool new_frame); - virtual void resizeEvent( QResizeEvent* ); - virtual void paletteChange( const QPalette& ); + protected: + virtual void transform(Scope&); + virtual void analyze(QPainter& p, const Scope&, bool new_frame); + virtual void resizeEvent(QResizeEvent*); + virtual void paletteChange(const QPalette&); - void drawBackground(); - void determineStep(); + void drawBackground(); + void determineStep(); -private: - QPixmap* bar() { return &m_barPixmap; } + private: + QPixmap* bar() { return &m_barPixmap; } - uint m_columns, m_rows; //number of rows and columns of blocks - uint m_y; //y-offset from top of widget - QPixmap m_barPixmap; - QPixmap m_topBarPixmap; - QPixmap m_background; - Scope m_scope; //so we don't create a vector every frame - std::vector m_store; //current bar heights - std::vector m_yscale; + uint m_columns, m_rows; // number of rows and columns of blocks + uint m_y; // y-offset from top of widget + QPixmap m_barPixmap; + QPixmap m_topBarPixmap; + QPixmap m_background; + Scope m_scope; // so we don't create a vector every frame + std::vector m_store; // current bar heights + std::vector m_yscale; - //FIXME why can't I namespace these? c++ issue? - std::vector m_fade_bars; - std::vector m_fade_pos; - std::vector m_fade_intensity; + // FIXME why can't I namespace these? c++ issue? + std::vector m_fade_bars; + std::vector m_fade_pos; + std::vector m_fade_intensity; - float m_step; //rows to fall per frame + float m_step; // rows to fall per frame }; #endif diff --git a/src/analyzers/boomanalyzer.cpp b/src/analyzers/boomanalyzer.cpp index 6a8455312..07a40e24a 100644 --- a/src/analyzers/boomanalyzer.cpp +++ b/src/analyzers/boomanalyzer.cpp @@ -5,131 +5,110 @@ #include #include -const char* BoomAnalyzer::kName = QT_TRANSLATE_NOOP("AnalyzerContainer", "Boom analyzer"); +const char* BoomAnalyzer::kName = + QT_TRANSLATE_NOOP("AnalyzerContainer", "Boom analyzer"); -BoomAnalyzer::BoomAnalyzer( QWidget *parent ) - : Analyzer::Base( parent, 9 ) - , K_barHeight( 1.271 )//1.471 - , F_peakSpeed( 1.103 )//1.122 - , F( 1.0 ) - , bar_height( BAND_COUNT, 0 ) - , peak_height( BAND_COUNT, 0 ) - , peak_speed( BAND_COUNT, 0.01 ) - , barPixmap( COLUMN_WIDTH, 50 ) -{ +BoomAnalyzer::BoomAnalyzer(QWidget* parent) + : Analyzer::Base(parent, 9), + K_barHeight(1.271) // 1.471 + , + F_peakSpeed(1.103) // 1.122 + , + F(1.0), + bar_height(BAND_COUNT, 0), + peak_height(BAND_COUNT, 0), + peak_speed(BAND_COUNT, 0.01), + barPixmap(COLUMN_WIDTH, 50) {} + +void BoomAnalyzer::changeK_barHeight(int newValue) { + K_barHeight = (double)newValue / 1000; } -void -BoomAnalyzer::changeK_barHeight( int newValue ) -{ - K_barHeight = (double)newValue / 1000; +void BoomAnalyzer::changeF_peakSpeed(int newValue) { + F_peakSpeed = (double)newValue / 1000; } -void -BoomAnalyzer::changeF_peakSpeed( int newValue ) -{ - F_peakSpeed = (double)newValue / 1000; +void BoomAnalyzer::resizeEvent(QResizeEvent*) { init(); } + +void BoomAnalyzer::init() { + const uint HEIGHT = height() - 2; + const double h = 1.2 / HEIGHT; + + F = double(HEIGHT) / (log10(256) * 1.1 /*<- max. amplitude*/); + + barPixmap = QPixmap(COLUMN_WIDTH - 2, HEIGHT); + + QPainter p(&barPixmap); + for (uint y = 0; y < HEIGHT; ++y) { + const double F = (double)y * h; + + p.setPen(QColor(qMax(0, 255 - int(229.0 * F)), + qMax(0, 255 - int(229.0 * F)), + qMax(0, 255 - int(191.0 * F)))); + p.drawLine(0, y, COLUMN_WIDTH - 2, y); + } } -void BoomAnalyzer::resizeEvent(QResizeEvent *) { - init(); +void BoomAnalyzer::transform(Scope& s) { + float* front = static_cast(&s.front()); + + m_fht->spectrum(front); + m_fht->scale(front, 1.0 / 60); + + Scope scope(32, 0); + + const uint xscale[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 19, 24, 29, 36, + 43, 52, 63, 76, 91, 108, 129, 153, 182, 216, 255}; + + for (uint j, i = 0; i < 32; i++) + for (j = xscale[i]; j < xscale[i + 1]; j++) + if (s[j] > scope[i]) scope[i] = s[j]; + + s = scope; } -void -BoomAnalyzer::init() -{ - const uint HEIGHT = height() - 2; - const double h = 1.2 / HEIGHT; +void BoomAnalyzer::analyze(QPainter& p, const Scope& scope, bool new_frame) { + float h; + const uint MAX_HEIGHT = height() - 1; - F = double(HEIGHT) / (log10( 256 ) * 1.1 /*<- max. amplitude*/); + for (uint i = 0, x = 0, y; i < BAND_COUNT; ++i, x += COLUMN_WIDTH + 1) { + h = log10(scope[i] * 256.0) * F; - barPixmap = QPixmap( COLUMN_WIDTH-2, HEIGHT ); + if (h > MAX_HEIGHT) h = MAX_HEIGHT; - QPainter p( &barPixmap ); - for( uint y = 0; y < HEIGHT; ++y ) - { - const double F = (double)y * h; + if (h > bar_height[i]) { + bar_height[i] = h; - p.setPen(QColor( - qMax(0, 255 - int(229.0 * F)), - qMax(0, 255 - int(229.0 * F)), - qMax(0, 255 - int(191.0 * F)))); - p.drawLine( 0, y, COLUMN_WIDTH-2, y ); - } -} - -void -BoomAnalyzer::transform( Scope &s ) -{ - float *front = static_cast( &s.front() ); - - m_fht->spectrum( front ); - m_fht->scale( front, 1.0 / 60 ); - - Scope scope( 32, 0 ); - - const uint xscale[] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,19,24,29,36,43,52,63,76,91,108,129,153,182,216,255 }; - - for( uint j, i = 0; i < 32; i++ ) - for( j = xscale[i]; j < xscale[i + 1]; j++ ) - if ( s[j] > scope[i] ) - scope[i] = s[j]; - - s = scope; -} - -void -BoomAnalyzer::analyze( QPainter& p, const Scope& scope, bool new_frame) -{ - float h; - const uint MAX_HEIGHT = height() - 1; - - for( uint i = 0, x = 0, y; i < BAND_COUNT; ++i, x += COLUMN_WIDTH+1 ) - { - h = log10( scope[i]*256.0 ) * F; - - if( h > MAX_HEIGHT ) - h = MAX_HEIGHT; - - if( h > bar_height[i] ) - { - bar_height[i] = h; - - if( h > peak_height[i] ) - { - peak_height[i] = h; - peak_speed[i] = 0.01; - } - else goto peak_handling; - } - else - { - if( bar_height[i] > 0.0 ) - { - bar_height[i] -= K_barHeight; //1.4 - if( bar_height[i] < 0.0 ) bar_height[i] = 0.0; - } - - peak_handling: - - if( peak_height[i] > 0.0 ) - { - peak_height[i] -= peak_speed[i]; - peak_speed[i] *= F_peakSpeed; //1.12 - - if( peak_height[i] < bar_height[i] ) peak_height[i] = bar_height[i]; - if( peak_height[i] < 0.0 ) peak_height[i] = 0.0; - } - } - - y = height() - uint(bar_height[i]); - p.drawPixmap(x+1, y, barPixmap, 0, y, -1, -1); - p.setPen( palette().color(QPalette::Highlight) ); - if (bar_height[i] > 0) - p.drawRect( x, y, COLUMN_WIDTH - 1, height() - y - 1 ); - - y = height() - uint(peak_height[i]); - p.setPen( palette().color(QPalette::Base) ); - p.drawLine( x, y, x+COLUMN_WIDTH-1, y ); + if (h > peak_height[i]) { + peak_height[i] = h; + peak_speed[i] = 0.01; + } else + goto peak_handling; + } else { + if (bar_height[i] > 0.0) { + bar_height[i] -= K_barHeight; // 1.4 + if (bar_height[i] < 0.0) bar_height[i] = 0.0; + } + + peak_handling: + + if (peak_height[i] > 0.0) { + peak_height[i] -= peak_speed[i]; + peak_speed[i] *= F_peakSpeed; // 1.12 + + if (peak_height[i] < bar_height[i]) peak_height[i] = bar_height[i]; + if (peak_height[i] < 0.0) peak_height[i] = 0.0; + } } + + y = height() - uint(bar_height[i]); + p.drawPixmap(x + 1, y, barPixmap, 0, y, -1, -1); + p.setPen(palette().color(QPalette::Highlight)); + if (bar_height[i] > 0) p.drawRect(x, y, COLUMN_WIDTH - 1, height() - y - 1); + + y = height() - uint(peak_height[i]); + p.setPen(palette().color(QPalette::Base)); + p.drawLine(x, y, x + COLUMN_WIDTH - 1, y); + } } diff --git a/src/analyzers/boomanalyzer.h b/src/analyzers/boomanalyzer.h index a45007a75..e93b68d12 100644 --- a/src/analyzers/boomanalyzer.h +++ b/src/analyzers/boomanalyzer.h @@ -11,35 +11,34 @@ @author Max Howell */ -class BoomAnalyzer : public Analyzer::Base -{ -Q_OBJECT -public: - Q_INVOKABLE BoomAnalyzer( QWidget* ); +class BoomAnalyzer : public Analyzer::Base { + Q_OBJECT + public: + Q_INVOKABLE BoomAnalyzer(QWidget*); - static const char* kName; + static const char* kName; - virtual void init(); - virtual void transform( Scope &s ); - virtual void analyze( QPainter& p, const Scope&, bool new_frame); + virtual void init(); + virtual void transform(Scope& s); + virtual void analyze(QPainter& p, const Scope&, bool new_frame); -public slots: - void changeK_barHeight( int ); - void changeF_peakSpeed( int ); + public slots: + void changeK_barHeight(int); + void changeF_peakSpeed(int); -protected: - void resizeEvent( QResizeEvent * e); + protected: + void resizeEvent(QResizeEvent* e); - static const uint COLUMN_WIDTH = 4; - static const uint BAND_COUNT = 32; + static const uint COLUMN_WIDTH = 4; + static const uint BAND_COUNT = 32; - double K_barHeight, F_peakSpeed, F; + double K_barHeight, F_peakSpeed, F; - std::vector bar_height; - std::vector peak_height; - std::vector peak_speed; + std::vector bar_height; + std::vector peak_height; + std::vector peak_speed; - QPixmap barPixmap; + QPixmap barPixmap; }; #endif diff --git a/src/analyzers/glanalyzer.cpp b/src/analyzers/glanalyzer.cpp index ec8a6bc4f..32c0a5474 100644 --- a/src/analyzers/glanalyzer.cpp +++ b/src/analyzers/glanalyzer.cpp @@ -23,320 +23,295 @@ #include "glanalyzer.h" #include +GLAnalyzer::GLAnalyzer(QWidget* parent) + : Analyzer::Base3D(parent, 15), m_oldy(32, -10.0f), m_peaks(32) {} -GLAnalyzer::GLAnalyzer( QWidget *parent ) - : Analyzer::Base3D(parent, 15) - , m_oldy(32, -10.0f) - , m_peaks(32) -{} - -GLAnalyzer::~GLAnalyzer() -{} +GLAnalyzer::~GLAnalyzer() {} // METHODS ===================================================== -void GLAnalyzer::analyze( const Scope &s ) -{ - //kdDebug() << "Scope Size: " << s.size() << endl; - /* Scope t(32); - if (s.size() != 32) - { - Analyzer::interpolate(s, t); - } - else - { - t = s; - }*/ - uint offset = 0; - static float peak; - float mfactor = 0.0; - static int drawcount; +void GLAnalyzer::analyze(const Scope& s) { + // kdDebug() << "Scope Size: " << s.size() << endl; + /* Scope t(32); + if (s.size() != 32) + { + Analyzer::interpolate(s, t); + } + else + { + t = s; + }*/ + uint offset = 0; + static float peak; + float mfactor = 0.0; + static int drawcount; - if (s.size() == 64) - { - offset=8; - } + if (s.size() == 64) { + offset = 8; + } - glRotatef(0.25f, 0.0f, 1.0f, 0.5f); //Rotate the scene - drawFloor(); - drawcount++; - if (drawcount > 25) - { - drawcount = 0; - peak = 0.0; - } + glRotatef(0.25f, 0.0f, 1.0f, 0.5f); // Rotate the scene + drawFloor(); + drawcount++; + if (drawcount > 25) { + drawcount = 0; + peak = 0.0; + } - for ( uint i = 0; i < 32; i++ ) - { - if (s[i] > peak) - { - peak = s[i]; - } - } + for (uint i = 0; i < 32; i++) { + if (s[i] > peak) { + peak = s[i]; + } + } - mfactor = 20 / peak; - for ( uint i = 0; i < 32; i++ ) - { + mfactor = 20 / peak; + for (uint i = 0; i < 32; i++) { - //kdDebug() << "Scope item " << i << " value: " << s[i] << endl; + // kdDebug() << "Scope item " << i << " value: " << s[i] << endl; - // Calculate new horizontal position (x) depending on number of samples - x = -16.0f + i; + // Calculate new horizontal position (x) depending on number of samples + x = -16.0f + i; - // Calculating new vertical position (y) depending on the data passed by amarok - y = float(s[i+offset] * mfactor); //This make it kinda dynamically resize depending on the data + // Calculating new vertical position (y) depending on the data passed by + // amarok + y = float(s[i + offset] * mfactor); // This make it kinda dynamically + // resize depending on the data - //Some basic bounds checking - if (y > 30) - y = 30; - else if (y < 0) - y = 0; + // Some basic bounds checking + if (y > 30) + y = 30; + else if (y < 0) + y = 0; - if((y - m_oldy[i]) < -0.6f) // Going Down Too Much - { - y = m_oldy[i] - 0.7f; - } - if (y < 0.0f) - { - y = 0.0f; - } + if ((y - m_oldy[i]) < -0.6f) // Going Down Too Much + { + y = m_oldy[i] - 0.7f; + } + if (y < 0.0f) { + y = 0.0f; + } - m_oldy[i] = y; //Save value as last value + m_oldy[i] = y; // Save value as last value - //Peak Code - if (m_oldy[i] > m_peaks[i].level) - { - m_peaks[i].level = m_oldy[i]; - m_peaks[i].delay = 30; - } + // Peak Code + if (m_oldy[i] > m_peaks[i].level) { + m_peaks[i].level = m_oldy[i]; + m_peaks[i].delay = 30; + } - if (m_peaks[i].delay > 0) - { - m_peaks[i].delay--; - } + if (m_peaks[i].delay > 0) { + m_peaks[i].delay--; + } - if (m_peaks[i].level > 1.0f) - { - if (m_peaks[i].delay <= 0) - { - m_peaks[i].level-=0.4f; - } - } - // Draw the bar - drawBar(x,y); - drawPeak(x, m_peaks[i].level); + if (m_peaks[i].level > 1.0f) { + if (m_peaks[i].delay <= 0) { + m_peaks[i].level -= 0.4f; + } + } + // Draw the bar + drawBar(x, y); + drawPeak(x, m_peaks[i].level); + } - } - - updateGL(); + updateGL(); } -void GLAnalyzer::initializeGL() -{ - // Clear frame (next fading will be preferred to clearing) - glClearColor(0.0f, 0.0f, 0.0f, 1.0f);// Set clear color to black - glClear( GL_COLOR_BUFFER_BIT ); +void GLAnalyzer::initializeGL() { + // Clear frame (next fading will be preferred to clearing) + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set clear color to black + glClear(GL_COLOR_BUFFER_BIT); - // Set the shading model - glShadeModel(GL_SMOOTH); + // Set the shading model + glShadeModel(GL_SMOOTH); - // Set the polygon mode to fill - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + // Set the polygon mode to fill + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - // Enable depth testing for hidden line removal - glEnable(GL_DEPTH_TEST); + // Enable depth testing for hidden line removal + glEnable(GL_DEPTH_TEST); - // Set blend parameters for 'composting alpha' - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + // Set blend parameters for 'composting alpha' + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } -void GLAnalyzer::resizeGL( int w, int h ) -{ - glViewport( 0, 0, (GLint)w, (GLint)h ); - glMatrixMode( GL_PROJECTION ); - glLoadIdentity(); - glOrtho(-16.0f, 16.0f, -10.0f, 10.0f, -50.0f, 100.0f); - glMatrixMode( GL_MODELVIEW ); - glLoadIdentity(); +void GLAnalyzer::resizeGL(int w, int h) { + glViewport(0, 0, (GLint)w, (GLint)h); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(-16.0f, 16.0f, -10.0f, 10.0f, -50.0f, 100.0f); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); } -void GLAnalyzer::paintGL() -{ - glMatrixMode( GL_MODELVIEW ); +void GLAnalyzer::paintGL() { + glMatrixMode(GL_MODELVIEW); #if 0 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); #else - glEnable( GL_DEPTH_TEST ); - glEnable( GL_BLEND ); - glPushMatrix(); - glLoadIdentity(); - glBegin( GL_TRIANGLE_STRIP ); - glColor4f( 0.0f, 0.0f, 0.1f, 0.08f ); - glVertex2f( 20.0f, 10.0f ); - glVertex2f( -20.0f, 10.0f ); - glVertex2f( 20.0f, -10.0f ); - glVertex2f( -20.0f, -10.0f ); - glEnd(); - glPopMatrix(); - glDisable( GL_BLEND ); - glEnable( GL_DEPTH_TEST ); - glClear( GL_DEPTH_BUFFER_BIT ); + glEnable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glPushMatrix(); + glLoadIdentity(); + glBegin(GL_TRIANGLE_STRIP); + glColor4f(0.0f, 0.0f, 0.1f, 0.08f); + glVertex2f(20.0f, 10.0f); + glVertex2f(-20.0f, 10.0f); + glVertex2f(20.0f, -10.0f); + glVertex2f(-20.0f, -10.0f); + glEnd(); + glPopMatrix(); + glDisable(GL_BLEND); + glEnable(GL_DEPTH_TEST); + glClear(GL_DEPTH_BUFFER_BIT); #endif - //swapBuffers(); - - glFlush(); + // swapBuffers(); + glFlush(); } -void GLAnalyzer::drawBar(float xPos, float height) -{ - glPushMatrix(); +void GLAnalyzer::drawBar(float xPos, float height) { + glPushMatrix(); - //Sets color to blue - //Set the colour depending on the height of the bar - glColor3f((height/40) + 0.5f, (height/40) + 0.625f, 1.0f); - glTranslatef(xPos, -10.0f, 0.0f); + // Sets color to blue + // Set the colour depending on the height of the bar + glColor3f((height / 40) + 0.5f, (height / 40) + 0.625f, 1.0f); + glTranslatef(xPos, -10.0f, 0.0f); - glScalef(1.0f, height, 3.0f); - drawCube(); + glScalef(1.0f, height, 3.0f); + drawCube(); - //Set colour to full blue - //glColor3f(0.0f, 0.0f, 1.0f); - //drawFrame(); - glPopMatrix(); + // Set colour to full blue + // glColor3f(0.0f, 0.0f, 1.0f); + // drawFrame(); + glPopMatrix(); } -void GLAnalyzer::drawFloor() -{ - glPushMatrix(); +void GLAnalyzer::drawFloor() { + glPushMatrix(); - //Sets color to amarok blue - glColor3f( 0.5f, 0.625f, 1.0f); - glTranslatef(-16.0f,-11.0f, -4.0f); + // Sets color to amarok blue + glColor3f(0.5f, 0.625f, 1.0f); + glTranslatef(-16.0f, -11.0f, -4.0f); - glScalef(32.0f, 1.0f, 10.0f); - drawCube(); + glScalef(32.0f, 1.0f, 10.0f); + drawCube(); - //Set colour to full blue - glColor3f(0.0f, 0.0f, 1.0f); - drawFrame(); - glPopMatrix(); + // Set colour to full blue + glColor3f(0.0f, 0.0f, 1.0f); + drawFrame(); + glPopMatrix(); } -void GLAnalyzer::drawPeak(float xPos, float ypos) -{ - glPushMatrix(); +void GLAnalyzer::drawPeak(float xPos, float ypos) { + glPushMatrix(); - //Set the colour to red - glColor3f(1.0f, 0.0f, 0.0f); - glTranslatef(xPos, ypos - 10.0f, 0.0f); + // Set the colour to red + glColor3f(1.0f, 0.0f, 0.0f); + glTranslatef(xPos, ypos - 10.0f, 0.0f); - glScalef(1.0f, 1.0f, 3.0f); - drawCube(); + glScalef(1.0f, 1.0f, 3.0f); + drawCube(); - glPopMatrix(); + glPopMatrix(); } -void GLAnalyzer::drawCube() -{ - glPushMatrix(); - glBegin(GL_POLYGON); +void GLAnalyzer::drawCube() { + glPushMatrix(); + glBegin(GL_POLYGON); - //This is the top face - glVertex3f(0.0f, 1.0f, 0.0f); - glVertex3f(1.0f, 1.0f, 0.0f); - glVertex3f(1.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 0.0f); + // This is the top face + glVertex3f(0.0f, 1.0f, 0.0f); + glVertex3f(1.0f, 1.0f, 0.0f); + glVertex3f(1.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 0.0f); - //This is the front face - glVertex3f(0.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 1.0f, 0.0f); - glVertex3f(0.0f, 1.0f, 0.0f); - glVertex3f(0.0f, 0.0f, 0.0f); + // This is the front face + glVertex3f(0.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 1.0f, 0.0f); + glVertex3f(0.0f, 1.0f, 0.0f); + glVertex3f(0.0f, 0.0f, 0.0f); - //This is the right face - glVertex3f(1.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 1.0f); - glVertex3f(1.0f, 1.0f, 1.0f); - glVertex3f(1.0f, 1.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 0.0f); + // This is the right face + glVertex3f(1.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 1.0f); + glVertex3f(1.0f, 1.0f, 1.0f); + glVertex3f(1.0f, 1.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 0.0f); - //This is the left face - glVertex3f(0.0f, 0.0f, 0.0f); - glVertex3f(0.0f, 0.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 0.0f); - glVertex3f(0.0f, 0.0f, 0.0f); + // This is the left face + glVertex3f(0.0f, 0.0f, 0.0f); + glVertex3f(0.0f, 0.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 0.0f); + glVertex3f(0.0f, 0.0f, 0.0f); - //This is the bottom face - glVertex3f(0.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 1.0f); - glVertex3f(0.0f, 0.0f, 1.0f); - glVertex3f(0.0f, 0.0f, 0.0f); + // This is the bottom face + glVertex3f(0.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 1.0f); + glVertex3f(0.0f, 0.0f, 1.0f); + glVertex3f(0.0f, 0.0f, 0.0f); - //This is the back face - glVertex3f(0.0f, 0.0f, 1.0f); - glVertex3f(1.0f, 0.0f, 1.0f); - glVertex3f(1.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 0.0f, 1.0f); + // This is the back face + glVertex3f(0.0f, 0.0f, 1.0f); + glVertex3f(1.0f, 0.0f, 1.0f); + glVertex3f(1.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 0.0f, 1.0f); - glEnd(); - glPopMatrix(); + glEnd(); + glPopMatrix(); } -void GLAnalyzer::drawFrame() -{ - glPushMatrix(); - glBegin(GL_LINES); +void GLAnalyzer::drawFrame() { + glPushMatrix(); + glBegin(GL_LINES); + // This is the top face + glVertex3f(0.0f, 1.0f, 0.0f); + glVertex3f(1.0f, 1.0f, 0.0f); + glVertex3f(1.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 0.0f); - //This is the top face - glVertex3f(0.0f, 1.0f, 0.0f); - glVertex3f(1.0f, 1.0f, 0.0f); - glVertex3f(1.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 0.0f); + // This is the front face + glVertex3f(0.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 1.0f, 0.0f); + glVertex3f(0.0f, 1.0f, 0.0f); + glVertex3f(0.0f, 0.0f, 0.0f); - //This is the front face - glVertex3f(0.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 1.0f, 0.0f); - glVertex3f(0.0f, 1.0f, 0.0f); - glVertex3f(0.0f, 0.0f, 0.0f); + // This is the right face + glVertex3f(1.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 1.0f); + glVertex3f(1.0f, 1.0f, 1.0f); + glVertex3f(1.0f, 1.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 0.0f); - //This is the right face - glVertex3f(1.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 1.0f); - glVertex3f(1.0f, 1.0f, 1.0f); - glVertex3f(1.0f, 1.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 0.0f); + // This is the left face + glVertex3f(0.0f, 0.0f, 0.0f); + glVertex3f(0.0f, 0.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 0.0f); + glVertex3f(0.0f, 0.0f, 0.0f); - //This is the left face - glVertex3f(0.0f, 0.0f, 0.0f); - glVertex3f(0.0f, 0.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 0.0f); - glVertex3f(0.0f, 0.0f, 0.0f); + // This is the bottom face + glVertex3f(0.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 0.0f); + glVertex3f(1.0f, 0.0f, 1.0f); + glVertex3f(0.0f, 0.0f, 1.0f); + glVertex3f(0.0f, 0.0f, 0.0f); - //This is the bottom face - glVertex3f(0.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 0.0f); - glVertex3f(1.0f, 0.0f, 1.0f); - glVertex3f(0.0f, 0.0f, 1.0f); - glVertex3f(0.0f, 0.0f, 0.0f); + // This is the back face + glVertex3f(0.0f, 0.0f, 1.0f); + glVertex3f(1.0f, 0.0f, 1.0f); + glVertex3f(1.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 1.0f, 1.0f); + glVertex3f(0.0f, 0.0f, 1.0f); - //This is the back face - glVertex3f(0.0f, 0.0f, 1.0f); - glVertex3f(1.0f, 0.0f, 1.0f); - glVertex3f(1.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 1.0f, 1.0f); - glVertex3f(0.0f, 0.0f, 1.0f); - - glEnd(); - glPopMatrix(); + glEnd(); + glPopMatrix(); } #endif diff --git a/src/analyzers/glanalyzer.h b/src/analyzers/glanalyzer.h index 394c46384..3e8e29695 100644 --- a/src/analyzers/glanalyzer.h +++ b/src/analyzers/glanalyzer.h @@ -27,16 +27,13 @@ *@author piggz */ -typedef struct -{ +typedef struct { float level; uint delay; -} -peak_tx; +} peak_tx; -class GLAnalyzer : public Analyzer::Base3D -{ -private: +class GLAnalyzer : public Analyzer::Base3D { + private: std::vector m_oldy; std::vector m_peaks; @@ -47,14 +44,15 @@ private: void drawFloor(); GLfloat x, y; -public: - GLAnalyzer(QWidget *); + + public: + GLAnalyzer(QWidget*); ~GLAnalyzer(); - void analyze( const Scope & ); - -protected: + void analyze(const Scope&); + + protected: void initializeGL(); - void resizeGL( int w, int h ); + void resizeGL(int w, int h); void paintGL(); }; diff --git a/src/analyzers/glanalyzer2.cpp b/src/analyzers/glanalyzer2.cpp index 00c3095e4..7d76d1cc8 100644 --- a/src/analyzers/glanalyzer2.cpp +++ b/src/analyzers/glanalyzer2.cpp @@ -27,307 +27,267 @@ #include #include +GLAnalyzer2::GLAnalyzer2(QWidget* parent) : Analyzer::Base3D(parent, 15) { + // initialize openGL context before managing GL calls + makeCurrent(); + loadTexture(locate("data", "amarok/data/dot.png"), dotTexture); + loadTexture(locate("data", "amarok/data/wirl1.png"), w1Texture); + loadTexture(locate("data", "amarok/data/wirl2.png"), w2Texture); -GLAnalyzer2::GLAnalyzer2( QWidget *parent ): -Analyzer::Base3D(parent, 15) -{ - //initialize openGL context before managing GL calls - makeCurrent(); - loadTexture( locate("data","amarok/data/dot.png"), dotTexture ); - loadTexture( locate("data","amarok/data/wirl1.png"), w1Texture ); - loadTexture( locate("data","amarok/data/wirl2.png"), w2Texture ); - - show.paused = true; - show.pauseTimer = 0.0; - show.rotDegrees = 0.0; - frame.rotDegrees = 0.0; + show.paused = true; + show.pauseTimer = 0.0; + show.rotDegrees = 0.0; + frame.rotDegrees = 0.0; } -GLAnalyzer2::~GLAnalyzer2() -{ - freeTexture( dotTexture ); - freeTexture( w1Texture ); - freeTexture( w2Texture ); +GLAnalyzer2::~GLAnalyzer2() { + freeTexture(dotTexture); + freeTexture(w1Texture); + freeTexture(w2Texture); } -void GLAnalyzer2::initializeGL() -{ - // Set a smooth shade model - glShadeModel(GL_SMOOTH); +void GLAnalyzer2::initializeGL() { + // Set a smooth shade model + glShadeModel(GL_SMOOTH); - // Disable depth test (all is drawn on a 2d plane) - glDisable(GL_DEPTH_TEST); + // Disable depth test (all is drawn on a 2d plane) + glDisable(GL_DEPTH_TEST); - // Set blend parameters for 'composting alpha' - glBlendFunc( GL_SRC_ALPHA, GL_ONE ); //superpose - //glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); //fade - glEnable( GL_BLEND ); + // Set blend parameters for 'composting alpha' + glBlendFunc(GL_SRC_ALPHA, GL_ONE); // superpose + // glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); //fade + glEnable(GL_BLEND); - // Clear frame with a black background - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); - glClear( GL_COLOR_BUFFER_BIT ); + // Clear frame with a black background + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); } -void GLAnalyzer2::resizeGL( int w, int h ) -{ - // Setup screen. We're going to manually do the perspective projection - glViewport( 0, 0, (GLint)w, (GLint)h ); - glMatrixMode( GL_PROJECTION ); - glLoadIdentity(); - glOrtho( -10.0f, 10.0f, -10.0f, 10.0f, -5.0f, 5.0f ); +void GLAnalyzer2::resizeGL(int w, int h) { + // Setup screen. We're going to manually do the perspective projection + glViewport(0, 0, (GLint)w, (GLint)h); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(-10.0f, 10.0f, -10.0f, 10.0f, -5.0f, 5.0f); - // Get the aspect ratio of the screen to draw 'cicular' particles - float ratio = (float)w / (float)h, - eqPixH = 60, - eqPixW = 80; - if ( ratio >= (4.0/3.0) ) { - unitX = 10.0 / (eqPixH * ratio); - unitY = 10.0 / eqPixH; - } else { - unitX = 10.0 / eqPixW; - unitY = 10.0 / (eqPixW / ratio); + // Get the aspect ratio of the screen to draw 'cicular' particles + float ratio = (float)w / (float)h, eqPixH = 60, eqPixW = 80; + if (ratio >= (4.0 / 3.0)) { + unitX = 10.0 / (eqPixH * ratio); + unitY = 10.0 / eqPixH; + } else { + unitX = 10.0 / eqPixW; + unitY = 10.0 / (eqPixW / ratio); + } + + // Get current timestamp. + timeval tv; + gettimeofday(&tv, nullptr); + show.timeStamp = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; +} + +void GLAnalyzer2::paused() { analyze(Scope()); } + +void GLAnalyzer2::analyze(const Scope& s) { + bool haveNoData = s.empty(); + + // if we're going into pause mode, clear timers. + if (!show.paused && haveNoData) show.pauseTimer = 0.0; + + // if we have got data, interpolate it (asking myself why I'm doing it here..) + if (!(show.paused = haveNoData)) { + int bands = s.size(), lowbands = bands / 4, hibands = bands / 3, + midbands = bands - lowbands - hibands; + Q_UNUSED(midbands); + float currentEnergy = 0, currentMeanBand = 0, maxValue = 0; + for (int i = 0; i < bands; i++) { + float value = s[i]; + currentEnergy += value; + currentMeanBand += (float)i * value; + if (value > maxValue) maxValue = value; } - - // Get current timestamp. - timeval tv; - gettimeofday( &tv, nullptr ); - show.timeStamp = (double)tv.tv_sec + (double)tv.tv_usec/1000000.0; -} - -void GLAnalyzer2::paused() -{ - analyze( Scope() ); -} - -void GLAnalyzer2::analyze( const Scope &s ) -{ - bool haveNoData = s.empty(); - - // if we're going into pause mode, clear timers. - if ( !show.paused && haveNoData ) - show.pauseTimer = 0.0; - - // if we have got data, interpolate it (asking myself why I'm doing it here..) - if ( !(show.paused = haveNoData) ) - { - int bands = s.size(), - lowbands = bands / 4, - hibands = bands / 3, - midbands = bands - lowbands - hibands; Q_UNUSED( midbands ); - float currentEnergy = 0, - currentMeanBand = 0, - maxValue = 0; - for ( int i = 0; i < bands; i++ ) - { - float value = s[i]; - currentEnergy += value; - currentMeanBand += (float)i * value; - if ( value > maxValue ) - maxValue = value; - } - frame.silence = currentEnergy < 0.001; - if ( !frame.silence ) - { - frame.meanBand = 100.0 * currentMeanBand / (currentEnergy * bands); - currentEnergy = 100.0 * currentEnergy / (float)bands; - frame.dEnergy = currentEnergy - frame.energy; - frame.energy = currentEnergy; -// printf( "%d [%f :: %f ]\t%f \n", bands, frame.energy, frame.meanBand, maxValue ); - } else - frame.energy = 0.0; - } - - // update the frame - updateGL(); -} - -void GLAnalyzer2::paintGL() -{ - // Compute the dT since the last call to paintGL and update timings - timeval tv; - gettimeofday( &tv, nullptr ); - double currentTime = (double)tv.tv_sec + (double)tv.tv_usec/1000000.0; - show.dT = currentTime - show.timeStamp; - show.timeStamp = currentTime; - - // Clear frame - glClear( GL_COLOR_BUFFER_BIT ); - - // Shitch to MODEL matrix and reset it to default - glMatrixMode( GL_MODELVIEW ); - glLoadIdentity(); - - // Fade the previous drawings. -/* glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - glBegin( GL_TRIANGLE_STRIP ); - glColor4f( 0.0f, 0.0f, 0.0f, 0.2f ); - glVertex2f( 10.0f, 10.0f ); - glVertex2f( -10.0f, 10.0f ); - glVertex2f( 10.0f, -10.0f ); - glVertex2f( -10.0f, -10.0f ); - glEnd();*/ - - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - glEnable( GL_TEXTURE_2D ); - float alphaN = show.paused ? 0.2 : (frame.energy / 10.0), - alphaP = show.paused ? 1.0 : (1 - frame.energy / 20.0); - if ( alphaN > 1.0 ) - alphaN = 1.0; - if ( alphaP < 0.1 ) - alphaP = 0.1; - glBindTexture( GL_TEXTURE_2D, w2Texture ); - setTextureMatrix( show.rotDegrees, 0.707*alphaP ); - glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - glBegin( GL_TRIANGLE_STRIP ); - glTexCoord2f( 1.0, 1.0 ); - glVertex2f( 10.0f, 10.0f ); - glTexCoord2f( 0.0, 1.0 ); - glVertex2f( -10.0f, 10.0f ); - glTexCoord2f( 1.0, 0.0 ); - glVertex2f( 10.0f, -10.0f ); - glTexCoord2f( 0.0 , 0.0 ); - glVertex2f( -10.0f, -10.0f ); - glEnd(); - glBindTexture( GL_TEXTURE_2D, w1Texture ); - setTextureMatrix( -show.rotDegrees * 2, 0.707 ); - glColor4f( 1.0f, 1.0f, 1.0f, alphaN ); - glBegin( GL_TRIANGLE_STRIP ); - glTexCoord2f( 1.0, 1.0 ); - glVertex2f( 10.0f, 10.0f ); - glTexCoord2f( 0.0, 1.0 ); - glVertex2f( -10.0f, 10.0f ); - glTexCoord2f( 1.0, 0.0 ); - glVertex2f( 10.0f, -10.0f ); - glTexCoord2f( 0.0 , 0.0 ); - glVertex2f( -10.0f, -10.0f ); - glEnd(); - setTextureMatrix( 0.0, 0.0 ); - glDisable( GL_TEXTURE_2D ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE ); - - // Here begins the real draw loop - // some updates to the show - show.rotDegrees += 40.0 * show.dT; - frame.rotDegrees += 80.0 * show.dT; - - // handle the 'pause' status - if ( show.paused ) - { - if ( show.pauseTimer > 0.5 ) - { - if ( show.pauseTimer > 0.6 ) - show.pauseTimer -= 0.6; - drawFullDot( 0.0f, 0.4f, 0.8f, 1.0f ); - drawFullDot( 0.0f, 0.4f, 0.8f, 1.0f ); - } - show.pauseTimer += show.dT; - return; - } - - if ( dotTexture ) { - glEnable( GL_TEXTURE_2D ); - glBindTexture( GL_TEXTURE_2D, dotTexture ); + frame.silence = currentEnergy < 0.001; + if (!frame.silence) { + frame.meanBand = 100.0 * currentMeanBand / (currentEnergy * bands); + currentEnergy = 100.0 * currentEnergy / (float)bands; + frame.dEnergy = currentEnergy - frame.energy; + frame.energy = currentEnergy; + // printf( "%d [%f :: %f ]\t%f \n", bands, frame.energy, + // frame.meanBand, maxValue ); } else - glDisable( GL_TEXTURE_2D ); + frame.energy = 0.0; + } - glLoadIdentity(); -// glRotatef( -frame.rotDegrees, 0,0,1 ); - glBegin( GL_QUADS ); -// Particle * particle = particleList.first(); -// for (; particle; particle = particleList.next()) - { - glColor4f( 0.0f, 1.0f, 0.0f, 1.0f ); - drawDot( 0, 0, kMax(10.0,(10.0 * frame.energy)) ); - glColor4f( 1.0f, 0.0f, 0.0f, 1.0f ); - drawDot( 6, 0, kMax(10.0, (5.0 * frame.energy)) ); - glColor4f( 0.0f, 0.4f, 1.0f, 1.0f ); - drawDot( -6, 0, kMax(10.0, (5.0 * frame.energy)) ); + // update the frame + updateGL(); +} + +void GLAnalyzer2::paintGL() { + // Compute the dT since the last call to paintGL and update timings + timeval tv; + gettimeofday(&tv, nullptr); + double currentTime = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; + show.dT = currentTime - show.timeStamp; + show.timeStamp = currentTime; + + // Clear frame + glClear(GL_COLOR_BUFFER_BIT); + + // Shitch to MODEL matrix and reset it to default + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + // Fade the previous drawings. + /* glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glBegin( GL_TRIANGLE_STRIP ); + glColor4f( 0.0f, 0.0f, 0.0f, 0.2f ); + glVertex2f( 10.0f, 10.0f ); + glVertex2f( -10.0f, 10.0f ); + glVertex2f( 10.0f, -10.0f ); + glVertex2f( -10.0f, -10.0f ); + glEnd();*/ + + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glEnable(GL_TEXTURE_2D); + float alphaN = show.paused ? 0.2 : (frame.energy / 10.0), + alphaP = show.paused ? 1.0 : (1 - frame.energy / 20.0); + if (alphaN > 1.0) alphaN = 1.0; + if (alphaP < 0.1) alphaP = 0.1; + glBindTexture(GL_TEXTURE_2D, w2Texture); + setTextureMatrix(show.rotDegrees, 0.707 * alphaP); + glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(1.0, 1.0); + glVertex2f(10.0f, 10.0f); + glTexCoord2f(0.0, 1.0); + glVertex2f(-10.0f, 10.0f); + glTexCoord2f(1.0, 0.0); + glVertex2f(10.0f, -10.0f); + glTexCoord2f(0.0, 0.0); + glVertex2f(-10.0f, -10.0f); + glEnd(); + glBindTexture(GL_TEXTURE_2D, w1Texture); + setTextureMatrix(-show.rotDegrees * 2, 0.707); + glColor4f(1.0f, 1.0f, 1.0f, alphaN); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(1.0, 1.0); + glVertex2f(10.0f, 10.0f); + glTexCoord2f(0.0, 1.0); + glVertex2f(-10.0f, 10.0f); + glTexCoord2f(1.0, 0.0); + glVertex2f(10.0f, -10.0f); + glTexCoord2f(0.0, 0.0); + glVertex2f(-10.0f, -10.0f); + glEnd(); + setTextureMatrix(0.0, 0.0); + glDisable(GL_TEXTURE_2D); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + + // Here begins the real draw loop + // some updates to the show + show.rotDegrees += 40.0 * show.dT; + frame.rotDegrees += 80.0 * show.dT; + + // handle the 'pause' status + if (show.paused) { + if (show.pauseTimer > 0.5) { + if (show.pauseTimer > 0.6) show.pauseTimer -= 0.6; + drawFullDot(0.0f, 0.4f, 0.8f, 1.0f); + drawFullDot(0.0f, 0.4f, 0.8f, 1.0f); } - glEnd(); + show.pauseTimer += show.dT; + return; + } + + if (dotTexture) { + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, dotTexture); + } else + glDisable(GL_TEXTURE_2D); + + glLoadIdentity(); + // glRotatef( -frame.rotDegrees, 0,0,1 ); + glBegin(GL_QUADS); + // Particle * particle = particleList.first(); + // for (; particle; particle = particleList.next()) + { + glColor4f(0.0f, 1.0f, 0.0f, 1.0f); + drawDot(0, 0, kMax(10.0, (10.0 * frame.energy))); + glColor4f(1.0f, 0.0f, 0.0f, 1.0f); + drawDot(6, 0, kMax(10.0, (5.0 * frame.energy))); + glColor4f(0.0f, 0.4f, 1.0f, 1.0f); + drawDot(-6, 0, kMax(10.0, (5.0 * frame.energy))); + } + glEnd(); } -void GLAnalyzer2::drawDot( float x, float y, float size ) -{ - float sizeX = size * unitX, - sizeY = size * unitY, - pLeft = x - sizeX, - pTop = y + sizeY, - pRight = x + sizeX, - pBottom = y - sizeY; - glTexCoord2f( 0, 0 ); // Bottom Left - glVertex2f( pLeft, pBottom ); - glTexCoord2f( 0, 1 ); // Top Left - glVertex2f( pLeft, pTop ); - glTexCoord2f( 1, 1 ); // Top Right - glVertex2f( pRight, pTop ); - glTexCoord2f( 1, 0 ); // Bottom Right - glVertex2f( pRight, pBottom ); +void GLAnalyzer2::drawDot(float x, float y, float size) { + float sizeX = size * unitX, sizeY = size * unitY, pLeft = x - sizeX, + pTop = y + sizeY, pRight = x + sizeX, pBottom = y - sizeY; + glTexCoord2f(0, 0); // Bottom Left + glVertex2f(pLeft, pBottom); + glTexCoord2f(0, 1); // Top Left + glVertex2f(pLeft, pTop); + glTexCoord2f(1, 1); // Top Right + glVertex2f(pRight, pTop); + glTexCoord2f(1, 0); // Bottom Right + glVertex2f(pRight, pBottom); } -void GLAnalyzer2::drawFullDot( float r, float g, float b, float a ) -{ - glBindTexture( GL_TEXTURE_2D, dotTexture ); - glEnable( GL_TEXTURE_2D ); - glColor4f( r, g, b, a ); - glBegin( GL_TRIANGLE_STRIP ); - glTexCoord2f( 1.0, 1.0 ); - glVertex2f( 10.0f, 10.0f ); - glTexCoord2f( 0.0, 1.0 ); - glVertex2f( -10.0f, 10.0f ); - glTexCoord2f( 1.0, 0.0 ); - glVertex2f( 10.0f, -10.0f ); - glTexCoord2f( 0.0 , 0.0 ); - glVertex2f( -10.0f, -10.0f ); - glEnd(); - glDisable( GL_TEXTURE_2D ); +void GLAnalyzer2::drawFullDot(float r, float g, float b, float a) { + glBindTexture(GL_TEXTURE_2D, dotTexture); + glEnable(GL_TEXTURE_2D); + glColor4f(r, g, b, a); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(1.0, 1.0); + glVertex2f(10.0f, 10.0f); + glTexCoord2f(0.0, 1.0); + glVertex2f(-10.0f, 10.0f); + glTexCoord2f(1.0, 0.0); + glVertex2f(10.0f, -10.0f); + glTexCoord2f(0.0, 0.0); + glVertex2f(-10.0f, -10.0f); + glEnd(); + glDisable(GL_TEXTURE_2D); } - -void GLAnalyzer2::setTextureMatrix( float rot, float scale ) -{ - glMatrixMode( GL_TEXTURE); - glLoadIdentity(); - if ( rot != 0.0 || scale != 0.0 ) - { - glTranslatef( 0.5f, 0.5f, 0.0f ); - glRotatef( rot, 0.0f, 0.0f, 1.0f ); - glScalef( scale, scale, 1.0f ); - glTranslatef( -0.5f, -0.5f, 0.0f ); - } - glMatrixMode( GL_MODELVIEW ); +void GLAnalyzer2::setTextureMatrix(float rot, float scale) { + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + if (rot != 0.0 || scale != 0.0) { + glTranslatef(0.5f, 0.5f, 0.0f); + glRotatef(rot, 0.0f, 0.0f, 1.0f); + glScalef(scale, scale, 1.0f); + glTranslatef(-0.5f, -0.5f, 0.0f); + } + glMatrixMode(GL_MODELVIEW); } -bool GLAnalyzer2::loadTexture( QString fileName, GLuint& textureID ) -{ - //reset texture ID to the default EMPTY value - textureID = 0; +bool GLAnalyzer2::loadTexture(QString fileName, GLuint& textureID) { + // reset texture ID to the default EMPTY value + textureID = 0; - //load image - QImage tmp; - if ( !tmp.load( fileName ) ) - return false; + // load image + QImage tmp; + if (!tmp.load(fileName)) return false; - //convert it to suitable format (flipped RGBA) - QImage texture = QGLWidget::convertToGLFormat( tmp ); - if ( texture.isNull() ) - return false; + // convert it to suitable format (flipped RGBA) + QImage texture = QGLWidget::convertToGLFormat(tmp); + if (texture.isNull()) return false; - //get texture number and bind loaded image to that texture - glGenTextures( 1, &textureID ); - glBindTexture( GL_TEXTURE_2D, textureID ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), - 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); - return true; + // get texture number and bind loaded image to that texture + glGenTextures(1, &textureID); + glBindTexture(GL_TEXTURE_2D, textureID); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexImage2D(GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, + GL_RGBA, GL_UNSIGNED_BYTE, texture.bits()); + return true; } - -void GLAnalyzer2::freeTexture( GLuint & textureID ) -{ - if ( textureID > 0 ) - glDeleteTextures( 1, &textureID ); - textureID = 0; +void GLAnalyzer2::freeTexture(GLuint& textureID) { + if (textureID > 0) glDeleteTextures(1, &textureID); + textureID = 0; } #endif diff --git a/src/analyzers/glanalyzer2.h b/src/analyzers/glanalyzer2.h index 3aeb98ae6..d97886990 100644 --- a/src/analyzers/glanalyzer2.h +++ b/src/analyzers/glanalyzer2.h @@ -25,48 +25,46 @@ #include #include +class GLAnalyzer2 : public Analyzer::Base3D { + public: + GLAnalyzer2(QWidget*); + ~GLAnalyzer2(); + void analyze(const Scope&); + void paused(); -class GLAnalyzer2 : public Analyzer::Base3D -{ -public: - GLAnalyzer2(QWidget *); - ~GLAnalyzer2(); - void analyze( const Scope & ); - void paused(); + protected: + void initializeGL(); + void resizeGL(int w, int h); + void paintGL(); -protected: - void initializeGL(); - void resizeGL( int w, int h ); - void paintGL(); - -private: - struct ShowProperties { + private: + struct ShowProperties { bool paused; double timeStamp; double dT; double pauseTimer; float rotDegrees; - } show; + } show; - struct FrameProperties { + struct FrameProperties { float energy; float dEnergy; float meanBand; float rotDegrees; bool silence; - } frame; + } frame; - GLuint dotTexture; - GLuint w1Texture; - GLuint w2Texture; - float unitX, unitY; + GLuint dotTexture; + GLuint w1Texture; + GLuint w2Texture; + float unitX, unitY; - void drawDot( float x, float y, float size ); - void drawFullDot( float r, float g, float b, float a ); - void setTextureMatrix( float rot, float scale ); + void drawDot(float x, float y, float size); + void drawFullDot(float r, float g, float b, float a); + void setTextureMatrix(float rot, float scale); - bool loadTexture(QString file, GLuint& textureID); - void freeTexture(GLuint& textureID); + bool loadTexture(QString file, GLuint& textureID); + void freeTexture(GLuint& textureID); }; #endif diff --git a/src/analyzers/glanalyzer3.cpp b/src/analyzers/glanalyzer3.cpp index 0892f4d88..7a5947ed2 100644 --- a/src/analyzers/glanalyzer3.cpp +++ b/src/analyzers/glanalyzer3.cpp @@ -28,453 +28,400 @@ #include #ifndef HAVE_FABSF -inline float fabsf(float f) -{ - return f < 0.f ? -f : f; -} +inline float fabsf(float f) { return f < 0.f ? -f : f; } #endif - -class Ball -{ - public: - Ball() : x( drand48() - drand48() ), y( 1 - 2.0 * drand48() ), - z( drand48() ), vx( 0.0 ), vy( 0.0 ), vz( 0.0 ), - mass( 0.01 + drand48()/10.0 ) +class Ball { + public: + Ball() + : x(drand48() - drand48()), + y(1 - 2.0 * drand48()), + z(drand48()), + vx(0.0), + vy(0.0), + vz(0.0), + mass(0.01 + drand48() / 10.0) //,color( (float[3]) { 0.0, drand48()*0.5, 0.7 + drand48() * 0.3 } ) - { - //this is because GCC < 3.3 can't compile the above line, we aren't sure why though - color[0] = 0.0; color[1] = drand48()*0.5; color[2] = 0.7 + drand48() * 0.3; - }; + { + // this is because GCC < 3.3 can't compile the above line, we aren't sure + // why though + color[0] = 0.0; + color[1] = drand48() * 0.5; + color[2] = 0.7 + drand48() * 0.3; + }; - float x, y, z, vx, vy, vz, mass; - float color[3]; + float x, y, z, vx, vy, vz, mass; + float color[3]; - void updatePhysics( float dT ) - { - x += vx * dT; // position - y += vy * dT; // position - z += vz * dT; // position - if ( y < -0.8 ) vy = fabsf( vy ); - if ( y > 0.8 ) vy = -fabsf( vy ); - if ( z < 0.1 ) vz = fabsf( vz ); - if ( z > 0.9 ) vz = -fabsf( vz ); - vx += (( x > 0 ) ? 4.94 : -4.94) * dT; // G-force - vx *= (1 - 2.9 * dT); // air friction - vy *= (1 - 2.9 * dT); // air friction - vz *= (1 - 2.9 * dT); // air friction - } + void updatePhysics(float dT) { + x += vx * dT; // position + y += vy * dT; // position + z += vz * dT; // position + if (y < -0.8) vy = fabsf(vy); + if (y > 0.8) vy = -fabsf(vy); + if (z < 0.1) vz = fabsf(vz); + if (z > 0.9) vz = -fabsf(vz); + vx += ((x > 0) ? 4.94 : -4.94) * dT; // G-force + vx *= (1 - 2.9 * dT); // air friction + vy *= (1 - 2.9 * dT); // air friction + vz *= (1 - 2.9 * dT); // air friction + } }; -class Paddle -{ - public: - Paddle( float xPos ) : onLeft( xPos < 0 ), mass( 1.0 ), - X( xPos ), x( xPos ), vx( 0.0 ) {}; +class Paddle { + public: + Paddle(float xPos) + : onLeft(xPos < 0), mass(1.0), X(xPos), x(xPos), vx(0.0) {}; - void updatePhysics( float dT ) - { - x += vx * dT; // posision - vx += (1300 * (X - x) / mass) * dT; // elasticity - vx *= (1 - 4.0 * dT); // air friction + void updatePhysics(float dT) { + x += vx * dT; // posision + vx += (1300 * (X - x) / mass) * dT; // elasticity + vx *= (1 - 4.0 * dT); // air friction + } + + void renderGL() { + glBegin(GL_TRIANGLE_STRIP); + glColor3f(0.0f, 0.1f, 0.3f); + glVertex3f(x, -1.0f, 0.0); + glVertex3f(x, 1.0f, 0.0); + glColor3f(0.1f, 0.2f, 0.6f); + glVertex3f(x, -1.0f, 1.0); + glVertex3f(x, 1.0f, 1.0); + glEnd(); + } + + void bounce(Ball* ball) { + if (onLeft && ball->x < x) { + ball->vx = vx * mass / (mass + ball->mass) + fabsf(ball->vx); + ball->vy = (drand48() - drand48()) * 1.8; + ball->vz = (drand48() - drand48()) * 0.9; + ball->x = x; + } else if (!onLeft && ball->x > x) { + ball->vx = vx * mass / (mass + ball->mass) - fabsf(ball->vx); + ball->vy = (drand48() - drand48()) * 1.8; + ball->vz = (drand48() - drand48()) * 0.9; + ball->x = x; } + } - void renderGL() - { - glBegin( GL_TRIANGLE_STRIP ); - glColor3f( 0.0f, 0.1f, 0.3f ); - glVertex3f( x, -1.0f, 0.0 ); - glVertex3f( x, 1.0f, 0.0 ); - glColor3f( 0.1f, 0.2f, 0.6f ); - glVertex3f( x, -1.0f, 1.0 ); - glVertex3f( x, 1.0f, 1.0 ); - glEnd(); - } + void impulse(float strength) { + if ((onLeft && strength > vx) || (!onLeft && strength < vx)) vx += strength; + } - void bounce( Ball * ball ) - { - if ( onLeft && ball->x < x ) - { - ball->vx = vx * mass / (mass + ball->mass) + fabsf( ball->vx ); - ball->vy = (drand48() - drand48()) * 1.8; - ball->vz = (drand48() - drand48()) * 0.9; - ball->x = x; - } - else if ( !onLeft && ball->x > x ) - { - ball->vx = vx * mass / (mass + ball->mass) - fabsf( ball->vx ); - ball->vy = (drand48() - drand48()) * 1.8; - ball->vz = (drand48() - drand48()) * 0.9; - ball->x = x; - } - } - - void impulse( float strength ) - { - if ( (onLeft && strength > vx) || (!onLeft && strength < vx) ) - vx += strength; - } - - private: - bool onLeft; - float mass, X, x, vx; + private: + bool onLeft; + float mass, X, x, vx; }; +GLAnalyzer3::GLAnalyzer3(QWidget* parent) : Analyzer::Base3D(parent, 15) { + // initialize openGL context before managing GL calls + makeCurrent(); + loadTexture(locate("data", "amarok/data/ball.png"), ballTexture); + loadTexture(locate("data", "amarok/data/grid.png"), gridTexture); -GLAnalyzer3::GLAnalyzer3( QWidget *parent ): -Analyzer::Base3D(parent, 15) -{ - //initialize openGL context before managing GL calls - makeCurrent(); - loadTexture( locate("data","amarok/data/ball.png"), ballTexture ); - loadTexture( locate("data","amarok/data/grid.png"), gridTexture ); + balls.setAutoDelete(true); + leftPaddle = new Paddle(-1.0); + rightPaddle = new Paddle(1.0); + for (int i = 0; i < NUMBER_OF_BALLS; i++) balls.append(new Ball()); - balls.setAutoDelete( true ); - leftPaddle = new Paddle( -1.0 ); - rightPaddle = new Paddle( 1.0 ); - for ( int i = 0; i < NUMBER_OF_BALLS; i++ ) - balls.append( new Ball() ); - - show.colorK = 0.0; - show.gridScrollK = 0.0; - show.gridEnergyK = 0.0; - show.camRot = 0.0; - show.camRoll = 0.0; - show.peakEnergy = 1.0; - frame.silence = true; - frame.energy = 0.0; - frame.dEnergy = 0.0; + show.colorK = 0.0; + show.gridScrollK = 0.0; + show.gridEnergyK = 0.0; + show.camRot = 0.0; + show.camRoll = 0.0; + show.peakEnergy = 1.0; + frame.silence = true; + frame.energy = 0.0; + frame.dEnergy = 0.0; } -GLAnalyzer3::~GLAnalyzer3() -{ - freeTexture( ballTexture ); - freeTexture( gridTexture ); - delete leftPaddle; - delete rightPaddle; - balls.clear(); +GLAnalyzer3::~GLAnalyzer3() { + freeTexture(ballTexture); + freeTexture(gridTexture); + delete leftPaddle; + delete rightPaddle; + balls.clear(); } -void GLAnalyzer3::initializeGL() -{ - // Set a smooth shade model - glShadeModel(GL_SMOOTH); +void GLAnalyzer3::initializeGL() { + // Set a smooth shade model + glShadeModel(GL_SMOOTH); - // Disable depth test (all is drawn 'z-sorted') - glDisable( GL_DEPTH_TEST ); + // Disable depth test (all is drawn 'z-sorted') + glDisable(GL_DEPTH_TEST); - // Set blending function (Alpha addition) - glBlendFunc( GL_SRC_ALPHA, GL_ONE ); + // Set blending function (Alpha addition) + glBlendFunc(GL_SRC_ALPHA, GL_ONE); - // Clear frame with a black background - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + // Clear frame with a black background + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); } -void GLAnalyzer3::resizeGL( int w, int h ) -{ - // Setup screen. We're going to manually do the perspective projection - glViewport( 0, 0, (GLint)w, (GLint)h ); - glMatrixMode( GL_PROJECTION ); - glLoadIdentity(); - glFrustum( -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 4.5f ); +void GLAnalyzer3::resizeGL(int w, int h) { + // Setup screen. We're going to manually do the perspective projection + glViewport(0, 0, (GLint)w, (GLint)h); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glFrustum(-0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 4.5f); - // Get the aspect ratio of the screen to draw 'circular' particles - float ratio = (float)w / (float)h; - if ( ratio >= 1.0 ) { + // Get the aspect ratio of the screen to draw 'circular' particles + float ratio = (float)w / (float)h; + if (ratio >= 1.0) { unitX = 0.34 / ratio; unitY = 0.34; - } else { + } else { unitX = 0.34; unitY = 0.34 * ratio; - } + } - // Get current timestamp. - timeval tv; - gettimeofday( &tv, nullptr ); - show.timeStamp = (double)tv.tv_sec + (double)tv.tv_usec/1000000.0; + // Get current timestamp. + timeval tv; + gettimeofday(&tv, nullptr); + show.timeStamp = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; } -void GLAnalyzer3::paused() -{ - analyze( Scope() ); -} +void GLAnalyzer3::paused() { analyze(Scope()); } -void GLAnalyzer3::analyze( const Scope &s ) -{ - // compute the dTime since the last call - timeval tv; - gettimeofday( &tv, nullptr ); - double currentTime = (double)tv.tv_sec + (double)tv.tv_usec/1000000.0; - show.dT = currentTime - show.timeStamp; - show.timeStamp = currentTime; +void GLAnalyzer3::analyze(const Scope& s) { + // compute the dTime since the last call + timeval tv; + gettimeofday(&tv, nullptr); + double currentTime = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; + show.dT = currentTime - show.timeStamp; + show.timeStamp = currentTime; - // compute energy integrating frame's spectrum - if ( !s.empty() ) - { + // compute energy integrating frame's spectrum + if (!s.empty()) { int bands = s.size(); - float currentEnergy = 0, - maxValue = 0; + float currentEnergy = 0, maxValue = 0; // integrate spectrum -> energy - for ( int i = 0; i < bands; i++ ) - { - float value = s[i]; - currentEnergy += value; - if ( value > maxValue ) - maxValue = value; + for (int i = 0; i < bands; i++) { + float value = s[i]; + currentEnergy += value; + if (value > maxValue) maxValue = value; } currentEnergy *= 100.0 / (float)bands; // emulate a peak detector: currentEnergy -> peakEnergy (3tau = 30 seconds) - show.peakEnergy = 1.0 + ( show.peakEnergy - 1.0 ) * exp( - show.dT / 10.0 ); - if ( currentEnergy > show.peakEnergy ) - show.peakEnergy = currentEnergy; + show.peakEnergy = 1.0 + (show.peakEnergy - 1.0) * exp(-show.dT / 10.0); + if (currentEnergy > show.peakEnergy) show.peakEnergy = currentEnergy; // check for silence frame.silence = currentEnergy < 0.001; // normalize frame energy against peak energy and compute frame stats currentEnergy /= show.peakEnergy; frame.dEnergy = currentEnergy - frame.energy; frame.energy = currentEnergy; - } else + } else frame.silence = true; - // update the frame - updateGL(); + // update the frame + updateGL(); } -void GLAnalyzer3::paintGL() -{ - // limit max dT to 0.05 and update color and scroll constants - if ( show.dT > 0.05 ) - show.dT = 0.05; - show.colorK += show.dT * 0.4; - if ( show.colorK > 3.0 ) - show.colorK -= 3.0; - show.gridScrollK += 0.2 * show.peakEnergy * show.dT; +void GLAnalyzer3::paintGL() { + // limit max dT to 0.05 and update color and scroll constants + if (show.dT > 0.05) show.dT = 0.05; + show.colorK += show.dT * 0.4; + if (show.colorK > 3.0) show.colorK -= 3.0; + show.gridScrollK += 0.2 * show.peakEnergy * show.dT; - // Switch to MODEL matrix and clear screen - glMatrixMode( GL_MODELVIEW ); - glLoadIdentity(); - glClear( GL_COLOR_BUFFER_BIT ); + // Switch to MODEL matrix and clear screen + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glClear(GL_COLOR_BUFFER_BIT); - // Draw scrolling grid - if ( (show.gridEnergyK > 0.05) || (!frame.silence && frame.dEnergy < -0.3) ) - { - show.gridEnergyK *= exp( -show.dT / 0.1 ); - if ( -frame.dEnergy > show.gridEnergyK ) - show.gridEnergyK = -frame.dEnergy*2.0; - float gridColor[4] = { 0.0, 1.0, 0.6, show.gridEnergyK }; - drawScrollGrid( show.gridScrollK, gridColor ); - } + // Draw scrolling grid + if ((show.gridEnergyK > 0.05) || (!frame.silence && frame.dEnergy < -0.3)) { + show.gridEnergyK *= exp(-show.dT / 0.1); + if (-frame.dEnergy > show.gridEnergyK) + show.gridEnergyK = -frame.dEnergy * 2.0; + float gridColor[4] = {0.0, 1.0, 0.6, show.gridEnergyK}; + drawScrollGrid(show.gridScrollK, gridColor); + } - // Roll camera up/down handling the beat - show.camRot += show.camRoll * show.dT; // posision - show.camRoll -= 400 * show.camRot * show.dT; // elasticity - show.camRoll *= (1 - 2.0 * show.dT); // friction - if ( !frame.silence && frame.dEnergy > 0.4 ) - show.camRoll += show.peakEnergy*2.0; - glRotatef( show.camRoll / 2.0, 1,0,0 ); + // Roll camera up/down handling the beat + show.camRot += show.camRoll * show.dT; // posision + show.camRoll -= 400 * show.camRot * show.dT; // elasticity + show.camRoll *= (1 - 2.0 * show.dT); // friction + if (!frame.silence && frame.dEnergy > 0.4) + show.camRoll += show.peakEnergy * 2.0; + glRotatef(show.camRoll / 2.0, 1, 0, 0); - // Translate the drawing plane - glTranslatef( 0.0f, 0.0f, -1.8f ); + // Translate the drawing plane + glTranslatef(0.0f, 0.0f, -1.8f); - // Draw upper/lower planes and paddles - drawHFace( -1.0 ); - drawHFace( 1.0 ); - leftPaddle->renderGL(); - rightPaddle->renderGL(); + // Draw upper/lower planes and paddles + drawHFace(-1.0); + drawHFace(1.0); + leftPaddle->renderGL(); + rightPaddle->renderGL(); - // Draw Balls - if ( ballTexture ) { - glEnable( GL_TEXTURE_2D ); - glBindTexture( GL_TEXTURE_2D, ballTexture ); - } else - glDisable( GL_TEXTURE_2D ); - glEnable( GL_BLEND ); - Ball * ball = balls.first(); - for ( ; ball; ball = balls.next() ) - { - float color[3], - angle = show.colorK; + // Draw Balls + if (ballTexture) { + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, ballTexture); + } else + glDisable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + Ball* ball = balls.first(); + for (; ball; ball = balls.next()) { + float color[3], angle = show.colorK; // Rotate the color based on 'angle' value [0,3) - if ( angle < 1.0 ) - { - color[ 0 ] = ball->color[ 0 ] * (1 - angle) + ball->color[ 1 ] * angle; - color[ 1 ] = ball->color[ 1 ] * (1 - angle) + ball->color[ 2 ] * angle; - color[ 2 ] = ball->color[ 2 ] * (1 - angle) + ball->color[ 0 ] * angle; - } - else if ( angle < 2.0 ) - { - angle -= 1.0; - color[ 0 ] = ball->color[ 1 ] * (1 - angle) + ball->color[ 2 ] * angle; - color[ 1 ] = ball->color[ 2 ] * (1 - angle) + ball->color[ 0 ] * angle; - color[ 2 ] = ball->color[ 0 ] * (1 - angle) + ball->color[ 1 ] * angle; - } - else - { - angle -= 2.0; - color[ 0 ] = ball->color[ 2 ] * (1 - angle) + ball->color[ 0 ] * angle; - color[ 1 ] = ball->color[ 0 ] * (1 - angle) + ball->color[ 1 ] * angle; - color[ 2 ] = ball->color[ 1 ] * (1 - angle) + ball->color[ 2 ] * angle; + if (angle < 1.0) { + color[0] = ball->color[0] * (1 - angle) + ball->color[1] * angle; + color[1] = ball->color[1] * (1 - angle) + ball->color[2] * angle; + color[2] = ball->color[2] * (1 - angle) + ball->color[0] * angle; + } else if (angle < 2.0) { + angle -= 1.0; + color[0] = ball->color[1] * (1 - angle) + ball->color[2] * angle; + color[1] = ball->color[2] * (1 - angle) + ball->color[0] * angle; + color[2] = ball->color[0] * (1 - angle) + ball->color[1] * angle; + } else { + angle -= 2.0; + color[0] = ball->color[2] * (1 - angle) + ball->color[0] * angle; + color[1] = ball->color[0] * (1 - angle) + ball->color[1] * angle; + color[2] = ball->color[1] * (1 - angle) + ball->color[2] * angle; } // Draw the dot and update its physics also checking at bounces - glColor3fv( color ); - drawDot3s( ball->x, ball->y, ball->z, 1.0 ); - ball->updatePhysics( show.dT ); - if ( ball->x < 0 ) - leftPaddle->bounce( ball ); + glColor3fv(color); + drawDot3s(ball->x, ball->y, ball->z, 1.0); + ball->updatePhysics(show.dT); + if (ball->x < 0) + leftPaddle->bounce(ball); else - rightPaddle->bounce( ball ); - } - glDisable( GL_BLEND ); - glDisable( GL_TEXTURE_2D ); + rightPaddle->bounce(ball); + } + glDisable(GL_BLEND); + glDisable(GL_TEXTURE_2D); - // Update physics of paddles - leftPaddle->updatePhysics( show.dT ); - rightPaddle->updatePhysics( show.dT ); - if ( !frame.silence ) - { - leftPaddle->impulse( frame.energy*3.0 + frame.dEnergy*6.0 ); - rightPaddle->impulse( -frame.energy*3.0 - frame.dEnergy*6.0 ); - } + // Update physics of paddles + leftPaddle->updatePhysics(show.dT); + rightPaddle->updatePhysics(show.dT); + if (!frame.silence) { + leftPaddle->impulse(frame.energy * 3.0 + frame.dEnergy * 6.0); + rightPaddle->impulse(-frame.energy * 3.0 - frame.dEnergy * 6.0); + } } -void GLAnalyzer3::drawDot3s( float x, float y, float z, float size ) -{ - // Circular XY dot drawing functions - float sizeX = size * unitX, - sizeY = size * unitY, - pXm = x - sizeX, - pXM = x + sizeX, - pYm = y - sizeY, - pYM = y + sizeY; - // Draw the Dot - glBegin( GL_QUADS ); - glTexCoord2f( 0, 0 ); // Bottom Left - glVertex3f( pXm, pYm, z ); - glTexCoord2f( 0, 1 ); // Top Left - glVertex3f( pXm, pYM, z ); - glTexCoord2f( 1, 1 ); // Top Right - glVertex3f( pXM, pYM, z ); - glTexCoord2f( 1, 0 ); // Bottom Right - glVertex3f( pXM, pYm, z ); - glEnd(); +void GLAnalyzer3::drawDot3s(float x, float y, float z, float size) { + // Circular XY dot drawing functions + float sizeX = size * unitX, sizeY = size * unitY, pXm = x - sizeX, + pXM = x + sizeX, pYm = y - sizeY, pYM = y + sizeY; + // Draw the Dot + glBegin(GL_QUADS); + glTexCoord2f(0, 0); // Bottom Left + glVertex3f(pXm, pYm, z); + glTexCoord2f(0, 1); // Top Left + glVertex3f(pXm, pYM, z); + glTexCoord2f(1, 1); // Top Right + glVertex3f(pXM, pYM, z); + glTexCoord2f(1, 0); // Bottom Right + glVertex3f(pXM, pYm, z); + glEnd(); - // Shadow XZ drawing functions - float sizeZ = size / 10.0, - pZm = z - sizeZ, - pZM = z + sizeZ, - currentColor[4]; - glGetFloatv( GL_CURRENT_COLOR, currentColor ); - float alpha = currentColor[3], - topSide = (y + 1) / 4, - bottomSide = (1 - y) / 4; - // Draw the top shadow - currentColor[3] = topSide * topSide * alpha; - glColor4fv( currentColor ); - glBegin( GL_QUADS ); - glTexCoord2f( 0, 0 ); // Bottom Left - glVertex3f( pXm, 1, pZm ); - glTexCoord2f( 0, 1 ); // Top Left - glVertex3f( pXm, 1, pZM ); - glTexCoord2f( 1, 1 ); // Top Right - glVertex3f( pXM, 1, pZM ); - glTexCoord2f( 1, 0 ); // Bottom Right - glVertex3f( pXM, 1, pZm ); - glEnd(); - // Draw the bottom shadow - currentColor[3] = bottomSide * bottomSide * alpha; - glColor4fv( currentColor ); - glBegin( GL_QUADS ); - glTexCoord2f( 0, 0 ); // Bottom Left - glVertex3f( pXm, -1, pZm ); - glTexCoord2f( 0, 1 ); // Top Left - glVertex3f( pXm, -1, pZM ); - glTexCoord2f( 1, 1 ); // Top Right - glVertex3f( pXM, -1, pZM ); - glTexCoord2f( 1, 0 ); // Bottom Right - glVertex3f( pXM, -1, pZm ); - glEnd(); + // Shadow XZ drawing functions + float sizeZ = size / 10.0, pZm = z - sizeZ, pZM = z + sizeZ, currentColor[4]; + glGetFloatv(GL_CURRENT_COLOR, currentColor); + float alpha = currentColor[3], topSide = (y + 1) / 4, + bottomSide = (1 - y) / 4; + // Draw the top shadow + currentColor[3] = topSide * topSide * alpha; + glColor4fv(currentColor); + glBegin(GL_QUADS); + glTexCoord2f(0, 0); // Bottom Left + glVertex3f(pXm, 1, pZm); + glTexCoord2f(0, 1); // Top Left + glVertex3f(pXm, 1, pZM); + glTexCoord2f(1, 1); // Top Right + glVertex3f(pXM, 1, pZM); + glTexCoord2f(1, 0); // Bottom Right + glVertex3f(pXM, 1, pZm); + glEnd(); + // Draw the bottom shadow + currentColor[3] = bottomSide * bottomSide * alpha; + glColor4fv(currentColor); + glBegin(GL_QUADS); + glTexCoord2f(0, 0); // Bottom Left + glVertex3f(pXm, -1, pZm); + glTexCoord2f(0, 1); // Top Left + glVertex3f(pXm, -1, pZM); + glTexCoord2f(1, 1); // Top Right + glVertex3f(pXM, -1, pZM); + glTexCoord2f(1, 0); // Bottom Right + glVertex3f(pXM, -1, pZm); + glEnd(); } -void GLAnalyzer3::drawHFace( float y ) -{ - glBegin( GL_TRIANGLE_STRIP ); - glColor3f( 0.0f, 0.1f, 0.2f ); - glVertex3f( -1.0f, y, 0.0 ); - glVertex3f( 1.0f, y, 0.0 ); - glColor3f( 0.1f, 0.6f, 0.5f ); - glVertex3f( -1.0f, y, 2.0 ); - glVertex3f( 1.0f, y, 2.0 ); - glEnd(); +void GLAnalyzer3::drawHFace(float y) { + glBegin(GL_TRIANGLE_STRIP); + glColor3f(0.0f, 0.1f, 0.2f); + glVertex3f(-1.0f, y, 0.0); + glVertex3f(1.0f, y, 0.0); + glColor3f(0.1f, 0.6f, 0.5f); + glVertex3f(-1.0f, y, 2.0); + glVertex3f(1.0f, y, 2.0); + glEnd(); } -void GLAnalyzer3::drawScrollGrid( float scroll, float color[4] ) -{ - if ( !gridTexture ) - return; - glMatrixMode( GL_TEXTURE ); - glLoadIdentity(); - glTranslatef( 0.0, -scroll, 0.0 ); - glMatrixMode( GL_MODELVIEW ); - float backColor[4] = { 1.0, 1.0, 1.0, 0.0 }; - for ( int i = 0; i < 3; i++ ) - backColor[ i ] = color[ i ]; - glEnable( GL_TEXTURE_2D ); - glBindTexture( GL_TEXTURE_2D, gridTexture ); - glEnable( GL_BLEND ); - glBegin( GL_TRIANGLE_STRIP ); - glColor4fv( color ); // top face - glTexCoord2f( 0.0f, 1.0f ); - glVertex3f( -1.0f, 1.0f, -1.0f ); - glTexCoord2f( 1.0f, 1.0f ); - glVertex3f( 1.0f, 1.0f, -1.0f ); - glColor4fv( backColor ); // central points - glTexCoord2f( 0.0f, 0.0f ); - glVertex3f( -1.0f, 0.0f, -3.0f ); - glTexCoord2f( 1.0f, 0.0f ); - glVertex3f( 1.0f, 0.0f, -3.0f ); - glColor4fv( color ); // bottom face - glTexCoord2f( 0.0f, 1.0f ); - glVertex3f( -1.0f, -1.0f, -1.0f ); - glTexCoord2f( 1.0f, 1.0f ); - glVertex3f( 1.0f, -1.0f, -1.0f ); - glEnd(); - glDisable( GL_BLEND ); - glDisable( GL_TEXTURE_2D ); - glMatrixMode( GL_TEXTURE ); - glLoadIdentity(); - glMatrixMode( GL_MODELVIEW ); +void GLAnalyzer3::drawScrollGrid(float scroll, float color[4]) { + if (!gridTexture) return; + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + glTranslatef(0.0, -scroll, 0.0); + glMatrixMode(GL_MODELVIEW); + float backColor[4] = {1.0, 1.0, 1.0, 0.0}; + for (int i = 0; i < 3; i++) backColor[i] = color[i]; + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, gridTexture); + glEnable(GL_BLEND); + glBegin(GL_TRIANGLE_STRIP); + glColor4fv(color); // top face + glTexCoord2f(0.0f, 1.0f); + glVertex3f(-1.0f, 1.0f, -1.0f); + glTexCoord2f(1.0f, 1.0f); + glVertex3f(1.0f, 1.0f, -1.0f); + glColor4fv(backColor); // central points + glTexCoord2f(0.0f, 0.0f); + glVertex3f(-1.0f, 0.0f, -3.0f); + glTexCoord2f(1.0f, 0.0f); + glVertex3f(1.0f, 0.0f, -3.0f); + glColor4fv(color); // bottom face + glTexCoord2f(0.0f, 1.0f); + glVertex3f(-1.0f, -1.0f, -1.0f); + glTexCoord2f(1.0f, 1.0f); + glVertex3f(1.0f, -1.0f, -1.0f); + glEnd(); + glDisable(GL_BLEND); + glDisable(GL_TEXTURE_2D); + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); } -bool GLAnalyzer3::loadTexture( QString fileName, GLuint& textureID ) -{ - //reset texture ID to the default EMPTY value - textureID = 0; +bool GLAnalyzer3::loadTexture(QString fileName, GLuint& textureID) { + // reset texture ID to the default EMPTY value + textureID = 0; - //load image - QImage tmp; - if ( !tmp.load( fileName ) ) - return false; + // load image + QImage tmp; + if (!tmp.load(fileName)) return false; - //convert it to suitable format (flipped RGBA) - QImage texture = QGLWidget::convertToGLFormat( tmp ); - if ( texture.isNull() ) - return false; + // convert it to suitable format (flipped RGBA) + QImage texture = QGLWidget::convertToGLFormat(tmp); + if (texture.isNull()) return false; - //get texture number and bind loaded image to that texture - glGenTextures( 1, &textureID ); - glBindTexture( GL_TEXTURE_2D, textureID ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), - 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); - return true; + // get texture number and bind loaded image to that texture + glGenTextures(1, &textureID); + glBindTexture(GL_TEXTURE_2D, textureID); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexImage2D(GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, + GL_RGBA, GL_UNSIGNED_BYTE, texture.bits()); + return true; } -void GLAnalyzer3::freeTexture( GLuint& textureID ) -{ - if ( textureID > 0 ) - glDeleteTextures( 1, &textureID ); - textureID = 0; +void GLAnalyzer3::freeTexture(GLuint& textureID) { + if (textureID > 0) glDeleteTextures(1, &textureID); + textureID = 0; } #endif diff --git a/src/analyzers/glanalyzer3.h b/src/analyzers/glanalyzer3.h index 7abd7614b..643d01dea 100644 --- a/src/analyzers/glanalyzer3.h +++ b/src/analyzers/glanalyzer3.h @@ -1,9 +1,9 @@ /*************************************************************************** - glanalyzer3.h - description - ------------------- - begin : Feb 16 2004 - copyright : (C) 2004 by Enrico Ros - email : eros.kde@email.it + glanalyzer3.h - description + ------------------- + begin : Feb 16 2004 + copyright : (C) 2004 by Enrico Ros + email : eros.kde@email.it ***************************************************************************/ /*************************************************************************** @@ -29,51 +29,50 @@ class QWidget; class Ball; class Paddle; -class GLAnalyzer3 : public Analyzer::Base3D -{ -public: - GLAnalyzer3(QWidget *); - ~GLAnalyzer3(); - void analyze( const Scope & ); - void paused(); +class GLAnalyzer3 : public Analyzer::Base3D { + public: + GLAnalyzer3(QWidget*); + ~GLAnalyzer3(); + void analyze(const Scope&); + void paused(); -protected: - void initializeGL(); - void resizeGL( int w, int h ); - void paintGL(); + protected: + void initializeGL(); + void resizeGL(int w, int h); + void paintGL(); -private: - struct ShowProperties { - double timeStamp; - double dT; - float colorK; - float gridScrollK; - float gridEnergyK; - float camRot; - float camRoll; - float peakEnergy; - } show; + private: + struct ShowProperties { + double timeStamp; + double dT; + float colorK; + float gridScrollK; + float gridEnergyK; + float camRot; + float camRoll; + float peakEnergy; + } show; - struct FrameProperties { - bool silence; - float energy; - float dEnergy; - } frame; - - static const int NUMBER_OF_BALLS = 16; - - QPtrList balls; - Paddle * leftPaddle, * rightPaddle; - float unitX, unitY; - GLuint ballTexture; - GLuint gridTexture; + struct FrameProperties { + bool silence; + float energy; + float dEnergy; + } frame; - void drawDot3s( float x, float y, float z, float size ); - void drawHFace( float y ); - void drawScrollGrid( float scroll, float color[4] ); + static const int NUMBER_OF_BALLS = 16; - bool loadTexture(QString file, GLuint& textureID); - void freeTexture(GLuint& textureID); + QPtrList balls; + Paddle* leftPaddle, *rightPaddle; + float unitX, unitY; + GLuint ballTexture; + GLuint gridTexture; + + void drawDot3s(float x, float y, float z, float size); + void drawHFace(float y); + void drawScrollGrid(float scroll, float color[4]); + + bool loadTexture(QString file, GLuint& textureID); + void freeTexture(GLuint& textureID); }; #endif diff --git a/src/analyzers/nyancatanalyzer.cpp b/src/analyzers/nyancatanalyzer.cpp index 39ea101a0..760e97fb6 100644 --- a/src/analyzers/nyancatanalyzer.cpp +++ b/src/analyzers/nyancatanalyzer.cpp @@ -26,34 +26,31 @@ const char* NyanCatAnalyzer::kName = "Nyanalyzer cat"; const float NyanCatAnalyzer::kPixelScale = 0.02f; - NyanCatAnalyzer::NyanCatAnalyzer(QWidget* parent) - : Analyzer::Base(parent, 9), - cat_(":/nyancat.png"), - timer_id_(startTimer(kFrameIntervalMs)), - frame_(0), - current_buffer_(0), - available_rainbow_width_(0), - px_per_frame_(0), - x_offset_(0), - background_brush_(QColor(0x0f, 0x43, 0x73)) -{ + : Analyzer::Base(parent, 9), + cat_(":/nyancat.png"), + timer_id_(startTimer(kFrameIntervalMs)), + frame_(0), + current_buffer_(0), + available_rainbow_width_(0), + px_per_frame_(0), + x_offset_(0), + background_brush_(QColor(0x0f, 0x43, 0x73)) { memset(history_, 0, sizeof(history_)); - for (int i=0 ; ispectrum(&s.front()); -} +void NyanCatAnalyzer::transform(Scope& s) { m_fht->spectrum(&s.front()); } void NyanCatAnalyzer::timerEvent(QTimerEvent* e) { if (e->timerId() == timer_id_) { @@ -70,18 +67,19 @@ void NyanCatAnalyzer::resizeEvent(QResizeEvent* e) { buffer_[1] = QPixmap(); available_rainbow_width_ = width() - kCatWidth + kRainbowOverlap; - px_per_frame_ = float(available_rainbow_width_) / (kHistorySize-1) + 1; - x_offset_ = px_per_frame_ * (kHistorySize-1) - available_rainbow_width_; + px_per_frame_ = float(available_rainbow_width_) / (kHistorySize - 1) + 1; + x_offset_ = px_per_frame_ * (kHistorySize - 1) - available_rainbow_width_; } -void NyanCatAnalyzer::analyze(QPainter& p, const Analyzer::Scope& s, bool new_frame) { +void NyanCatAnalyzer::analyze(QPainter& p, const Analyzer::Scope& s, + bool new_frame) { // Discard the second half of the transform const int scope_size = s.size() / 2; if ((new_frame && is_playing_) || (buffer_[0].isNull() && buffer_[1].isNull())) { // Transform the music into rainbows! - for (int band=0 ; band=0 ; --band) { + for (int band = kRainbowBands - 1; band >= 0; --band) { buffer_painter.setPen(colors_[band]); - buffer_painter.drawPolyline(&polyline[band*kHistorySize], kHistorySize); - buffer_painter.drawPolyline(&polyline[band*kHistorySize], kHistorySize); + buffer_painter.drawPolyline(&polyline[band * kHistorySize], + kHistorySize); + buffer_painter.drawPolyline(&polyline[band * kHistorySize], + kHistorySize); } } else { const int last_buffer = current_buffer_; current_buffer_ = (current_buffer_ + 1) % 2; - // We can just shuffle the buffer along a bit and draw the new frame's data. + // We can just shuffle the buffer along a bit and draw the new frame's + // data. QPainter buffer_painter(&buffer_[current_buffer_]); buffer_painter.setRenderHint(QPainter::Antialiasing); - buffer_painter.drawPixmap(0, 0, buffer_[last_buffer], - px_per_frame_, 0, - x_offset_ + available_rainbow_width_ - px_per_frame_, 0); - buffer_painter.fillRect(x_offset_ + available_rainbow_width_ - px_per_frame_, 0, - kCatWidth - kRainbowOverlap + px_per_frame_, height(), - background_brush_); + buffer_painter.drawPixmap( + 0, 0, buffer_[last_buffer], px_per_frame_, 0, + x_offset_ + available_rainbow_width_ - px_per_frame_, 0); + buffer_painter.fillRect( + x_offset_ + available_rainbow_width_ - px_per_frame_, 0, + kCatWidth - kRainbowOverlap + px_per_frame_, height(), + background_brush_); - for (int band=kRainbowBands-1 ; band>=0 ; --band) { + for (int band = kRainbowBands - 1; band >= 0; --band) { buffer_painter.setPen(colors_[band]); - buffer_painter.drawPolyline(&polyline[(band+1)*kHistorySize - 3], 3); + buffer_painter.drawPolyline(&polyline[(band + 1) * kHistorySize - 3], + 3); } } } diff --git a/src/analyzers/nyancatanalyzer.h b/src/analyzers/nyancatanalyzer.h index afe6eec0b..8b16527b8 100644 --- a/src/analyzers/nyancatanalyzer.h +++ b/src/analyzers/nyancatanalyzer.h @@ -25,19 +25,19 @@ class NyanCatAnalyzer : public Analyzer::Base { Q_OBJECT -public: + public: Q_INVOKABLE NyanCatAnalyzer(QWidget* parent); static const char* kName; -protected: + protected: void transform(Scope&); void analyze(QPainter& p, const Analyzer::Scope&, bool new_frame); void timerEvent(QTimerEvent* e); void resizeEvent(QResizeEvent* e); -private: + private: static const int kCatHeight = 21; static const int kCatWidth = 34; static const int kCatFrameCount = 6; @@ -50,7 +50,7 @@ private: static const int kFrameIntervalMs = 150; -private: + private: inline QRect CatSourceRect() const { return QRect(0, kCatHeight * frame_, kCatWidth, kCatHeight); } @@ -60,8 +60,8 @@ private: } inline QRect CatDestRect() const { - return QRect(width() - kCatWidth, (height() - kCatHeight) / 2, - kCatWidth, kCatHeight); + return QRect(width() - kCatWidth, (height() - kCatHeight) / 2, kCatWidth, + kCatHeight); } inline QRect SleepingCatDestRect() const { @@ -69,7 +69,7 @@ private: kCatWidth, kSleepingCatHeight); } -private: + private: // "constants" that get initialised in the constructor float band_scale_[kRainbowBands]; QPen colors_[kRainbowBands]; @@ -102,4 +102,4 @@ private: QBrush background_brush_; }; -#endif // NYANCATANALYZER_H +#endif // NYANCATANALYZER_H diff --git a/src/analyzers/sonogram.cpp b/src/analyzers/sonogram.cpp index fbc99ecef..e067d32f6 100644 --- a/src/analyzers/sonogram.cpp +++ b/src/analyzers/sonogram.cpp @@ -15,76 +15,61 @@ #include -const char* Sonogram::kName = QT_TRANSLATE_NOOP("AnalyzerContainer", "Sonogram"); +const char* Sonogram::kName = + QT_TRANSLATE_NOOP("AnalyzerContainer", "Sonogram"); -Sonogram::Sonogram(QWidget *parent) : - Analyzer::Base(parent, 9) -{ -} +Sonogram::Sonogram(QWidget* parent) : Analyzer::Base(parent, 9) {} +Sonogram::~Sonogram() {} -Sonogram::~Sonogram() -{ -} +void Sonogram::resizeEvent(QResizeEvent* e) { + QWidget::resizeEvent(e); - -void Sonogram::resizeEvent(QResizeEvent *e) -{ - QWidget::resizeEvent(e); - -//only for gcc < 4.0 -#if !( __GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 0 ) ) - resizeForBands(height() < 128 ? 128 : height()); +// only for gcc < 4.0 +#if !(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 0)) + resizeForBands(height() < 128 ? 128 : height()); #endif - canvas_ = QPixmap(size()); - canvas_.fill(palette().color(QPalette::Background)); + canvas_ = QPixmap(size()); + canvas_.fill(palette().color(QPalette::Background)); } +void Sonogram::analyze(QPainter& p, const Scope& s, bool new_frame) { + int x = width() - 1; + QColor c; -void Sonogram::analyze(QPainter& p, const Scope &s, bool new_frame) -{ - int x = width() - 1; - QColor c; + QPainter canvas_painter(&canvas_); + canvas_painter.drawPixmap(0, 0, canvas_, 1, 0, x, -1); - QPainter canvas_painter(&canvas_); - canvas_painter.drawPixmap(0, 0, canvas_, 1, 0, x, -1); + Scope::const_iterator it = s.begin(), end = s.end(); + for (int y = height() - 1; y;) { + if (it >= end || *it < .005) + c = palette().color(QPalette::Background); + else if (*it < .05) + c.setHsv(95, 255, 255 - int(*it * 4000.0)); + else if (*it < 1.0) + c.setHsv(95 - int(*it * 90.0), 255, 255); + else + c = Qt::red; - Scope::const_iterator it = s.begin(), end = s.end(); - for (int y = height() - 1; y;) { - if (it >= end || *it < .005) - c = palette().color(QPalette::Background); - else if (*it < .05) - c.setHsv(95, 255, 255 - int(*it * 4000.0)); - else if (*it < 1.0) - c.setHsv(95 - int(*it * 90.0), 255, 255); - else - c = Qt::red; + canvas_painter.setPen(c); + canvas_painter.drawPoint(x, y--); - canvas_painter.setPen(c); - canvas_painter.drawPoint(x, y--); + if (it < end) ++it; + } - if (it < end) - ++it; - } + canvas_painter.end(); - canvas_painter.end(); - - p.drawPixmap(0, 0, canvas_); + p.drawPixmap(0, 0, canvas_); } - -void Sonogram::transform(Scope &scope) -{ - float *front = static_cast(&scope.front()); - m_fht->power2(front); - m_fht->scale(front, 1.0 / 256); - scope.resize( m_fht->size() / 2 ); +void Sonogram::transform(Scope& scope) { + float* front = static_cast(&scope.front()); + m_fht->power2(front); + m_fht->scale(front, 1.0 / 256); + scope.resize(m_fht->size() / 2); } - -void Sonogram::demo(QPainter& p) -{ - analyze(p, Scope(m_fht->size(), 0), new_frame_); +void Sonogram::demo(QPainter& p) { + analyze(p, Scope(m_fht->size(), 0), new_frame_); } - diff --git a/src/analyzers/sonogram.h b/src/analyzers/sonogram.h index dbd2a984a..35ce753cc 100644 --- a/src/analyzers/sonogram.h +++ b/src/analyzers/sonogram.h @@ -20,22 +20,21 @@ @author Melchior FRANZ */ -class Sonogram : public Analyzer::Base -{ +class Sonogram : public Analyzer::Base { Q_OBJECT -public: - Q_INVOKABLE Sonogram(QWidget*); - ~Sonogram(); + public: + Q_INVOKABLE Sonogram(QWidget*); + ~Sonogram(); - static const char* kName; + static const char* kName; -protected: - void analyze(QPainter& p, const Scope&, bool new_frame); - void transform(Scope&); - void demo(QPainter& p); - void resizeEvent(QResizeEvent*); + protected: + void analyze(QPainter& p, const Scope&, bool new_frame); + void transform(Scope&); + void demo(QPainter& p); + void resizeEvent(QResizeEvent*); - QPixmap canvas_; + QPixmap canvas_; }; #endif diff --git a/src/analyzers/turbine.cpp b/src/analyzers/turbine.cpp index ea45de137..63a7d0309 100644 --- a/src/analyzers/turbine.cpp +++ b/src/analyzers/turbine.cpp @@ -12,66 +12,57 @@ #include "turbine.h" -const char* TurbineAnalyzer::kName = QT_TRANSLATE_NOOP("AnalyzerContainer", "Turbine"); +const char* TurbineAnalyzer::kName = + QT_TRANSLATE_NOOP("AnalyzerContainer", "Turbine"); -void TurbineAnalyzer::analyze( QPainter& p, const Scope &scope, bool new_frame) -{ - float h; - const uint hd2 = height() / 2; - const uint MAX_HEIGHT = hd2 - 1; +void TurbineAnalyzer::analyze(QPainter& p, const Scope& scope, bool new_frame) { + float h; + const uint hd2 = height() / 2; + const uint MAX_HEIGHT = hd2 - 1; - for( uint i = 0, x = 0, y; i < BAND_COUNT; ++i, x += COLUMN_WIDTH+1 ) - { - h = log10( scope[i]*256.0 ) * F * 0.5; + for (uint i = 0, x = 0, y; i < BAND_COUNT; ++i, x += COLUMN_WIDTH + 1) { + h = log10(scope[i] * 256.0) * F * 0.5; - if( h > MAX_HEIGHT ) - h = MAX_HEIGHT; + if (h > MAX_HEIGHT) h = MAX_HEIGHT; - if( h > bar_height[i] ) - { - bar_height[i] = h; + if (h > bar_height[i]) { + bar_height[i] = h; - if( h > peak_height[i] ) - { - peak_height[i] = h; - peak_speed[i] = 0.01; - } - else goto peak_handling; - } - else - { - if( bar_height[i] > 0.0 ) - { - bar_height[i] -= K_barHeight; //1.4 - if( bar_height[i] < 0.0 ) bar_height[i] = 0.0; - } + if (h > peak_height[i]) { + peak_height[i] = h; + peak_speed[i] = 0.01; + } else + goto peak_handling; + } else { + if (bar_height[i] > 0.0) { + bar_height[i] -= K_barHeight; // 1.4 + if (bar_height[i] < 0.0) bar_height[i] = 0.0; + } - peak_handling: + peak_handling: - if( peak_height[i] > 0.0 ) - { - peak_height[i] -= peak_speed[i]; - peak_speed[i] *= F_peakSpeed; //1.12 + if (peak_height[i] > 0.0) { + peak_height[i] -= peak_speed[i]; + peak_speed[i] *= F_peakSpeed; // 1.12 - if( peak_height[i] < bar_height[i] ) peak_height[i] = bar_height[i]; - if( peak_height[i] < 0.0 ) peak_height[i] = 0.0; - } - } - - - y = hd2 - uint(bar_height[i]); - p.drawPixmap(x+1, y, barPixmap, 0, y, -1, -1); - p.drawPixmap(x+1, hd2, barPixmap, 0, int(bar_height[i]), -1, -1); - - p.setPen( palette().color(QPalette::Highlight) ); - if (bar_height[i] > 0) - p.drawRect( x, y, COLUMN_WIDTH-1, (int)bar_height[i]*2 -1 ); - - const uint x2 = x+COLUMN_WIDTH-1; - p.setPen( palette().color(QPalette::Base) ); - y = hd2 - uint(peak_height[i]); - p.drawLine( x, y, x2, y ); - y = hd2 + uint(peak_height[i]); - p.drawLine( x, y, x2, y ); + if (peak_height[i] < bar_height[i]) peak_height[i] = bar_height[i]; + if (peak_height[i] < 0.0) peak_height[i] = 0.0; + } } + + y = hd2 - uint(bar_height[i]); + p.drawPixmap(x + 1, y, barPixmap, 0, y, -1, -1); + p.drawPixmap(x + 1, hd2, barPixmap, 0, int(bar_height[i]), -1, -1); + + p.setPen(palette().color(QPalette::Highlight)); + if (bar_height[i] > 0) + p.drawRect(x, y, COLUMN_WIDTH - 1, (int)bar_height[i] * 2 - 1); + + const uint x2 = x + COLUMN_WIDTH - 1; + p.setPen(palette().color(QPalette::Base)); + y = hd2 - uint(peak_height[i]); + p.drawLine(x, y, x2, y); + y = hd2 + uint(peak_height[i]); + p.drawLine(x, y, x2, y); + } } diff --git a/src/analyzers/turbine.h b/src/analyzers/turbine.h index 819f1dd54..1175bff1f 100644 --- a/src/analyzers/turbine.h +++ b/src/analyzers/turbine.h @@ -11,15 +11,14 @@ #include "boomanalyzer.h" -class TurbineAnalyzer : public BoomAnalyzer -{ +class TurbineAnalyzer : public BoomAnalyzer { Q_OBJECT - public: - Q_INVOKABLE TurbineAnalyzer( QWidget *parent ) : BoomAnalyzer( parent ) {} + public: + Q_INVOKABLE TurbineAnalyzer(QWidget* parent) : BoomAnalyzer(parent) {} - void analyze( QPainter& p, const Scope&, bool new_frame); + void analyze(QPainter& p, const Scope&, bool new_frame); - static const char* kName; + static const char* kName; }; #endif diff --git a/src/core/appearance.cpp b/src/core/appearance.cpp index f9afdf9de..13c1c7525 100644 --- a/src/core/appearance.cpp +++ b/src/core/appearance.cpp @@ -27,24 +27,21 @@ const char* Appearance::kBackgroundColor = "background-color"; const QPalette Appearance::kDefaultPalette = QPalette(); -Appearance::Appearance(QObject* parent) - : QObject(parent) -{ +Appearance::Appearance(QObject* parent) : QObject(parent) { QSettings s; s.beginGroup(kSettingsGroup); QPalette p = QApplication::palette(); - background_color_ = s.value(kBackgroundColor, - p.color(QPalette::WindowText)).value(); - foreground_color_ = s.value(kForegroundColor, - p.color(QPalette::Window)).value(); + background_color_ = + s.value(kBackgroundColor, p.color(QPalette::WindowText)).value(); + foreground_color_ = + s.value(kForegroundColor, p.color(QPalette::Window)).value(); } void Appearance::LoadUserTheme() { QSettings s; s.beginGroup(kSettingsGroup); bool use_a_custom_color_set = s.value(kUseCustomColorSet).toBool(); - if (!use_a_custom_color_set) - return; + if (!use_a_custom_color_set) return; ChangeForegroundColor(foreground_color_); ChangeBackgroundColor(background_color_); diff --git a/src/core/appearance.h b/src/core/appearance.h index 31fffc677..7b44b83e3 100644 --- a/src/core/appearance.h +++ b/src/core/appearance.h @@ -22,24 +22,24 @@ #include class Appearance : public QObject { - public: - Appearance(QObject* parent = NULL); - // Load the user preferred theme, which could the default system theme or a - // custom set of colors that user has chosen - void LoadUserTheme(); - void ResetToSystemDefaultTheme(); - void ChangeForegroundColor(const QColor& color); - void ChangeBackgroundColor(const QColor& color); + public: + Appearance(QObject* parent = NULL); + // Load the user preferred theme, which could the default system theme or a + // custom set of colors that user has chosen + void LoadUserTheme(); + void ResetToSystemDefaultTheme(); + void ChangeForegroundColor(const QColor& color); + void ChangeBackgroundColor(const QColor& color); - static const char* kSettingsGroup; - static const char* kUseCustomColorSet; - static const char* kForegroundColor; - static const char* kBackgroundColor; - static const QPalette kDefaultPalette; + static const char* kSettingsGroup; + static const char* kUseCustomColorSet; + static const char* kForegroundColor; + static const char* kBackgroundColor; + static const QPalette kDefaultPalette; - private: - QColor foreground_color_; - QColor background_color_; + private: + QColor foreground_color_; + QColor background_color_; }; -#endif // APPEARANCE_H +#endif // APPEARANCE_H diff --git a/src/core/application.cpp b/src/core/application.cpp index 60238a63e..c8bf62d50 100644 --- a/src/core/application.cpp +++ b/src/core/application.cpp @@ -40,37 +40,36 @@ #include "podcasts/podcastupdater.h" #ifdef HAVE_MOODBAR -# include "moodbar/moodbarcontroller.h" -# include "moodbar/moodbarloader.h" +#include "moodbar/moodbarcontroller.h" +#include "moodbar/moodbarloader.h" #endif bool Application::kIsPortable = false; Application::Application(QObject* parent) - : QObject(parent), - tag_reader_client_(nullptr), - database_(nullptr), - album_cover_loader_(nullptr), - playlist_backend_(nullptr), - podcast_backend_(nullptr), - appearance_(nullptr), - cover_providers_(nullptr), - task_manager_(nullptr), - player_(nullptr), - playlist_manager_(nullptr), - current_art_loader_(nullptr), - global_search_(nullptr), - internet_model_(nullptr), - library_(nullptr), - device_manager_(nullptr), - podcast_updater_(nullptr), - podcast_downloader_(nullptr), - gpodder_sync_(nullptr), - moodbar_loader_(nullptr), - moodbar_controller_(nullptr), - network_remote_(nullptr), - network_remote_helper_(nullptr) -{ + : QObject(parent), + tag_reader_client_(nullptr), + database_(nullptr), + album_cover_loader_(nullptr), + playlist_backend_(nullptr), + podcast_backend_(nullptr), + appearance_(nullptr), + cover_providers_(nullptr), + task_manager_(nullptr), + player_(nullptr), + playlist_manager_(nullptr), + current_art_loader_(nullptr), + global_search_(nullptr), + internet_model_(nullptr), + library_(nullptr), + device_manager_(nullptr), + podcast_updater_(nullptr), + podcast_downloader_(nullptr), + gpodder_sync_(nullptr), + moodbar_loader_(nullptr), + moodbar_controller_(nullptr), + network_remote_(nullptr), + network_remote_helper_(nullptr) { tag_reader_client_ = new TagReaderClient(this); MoveToNewThread(tag_reader_client_); tag_reader_client_->Start(); @@ -111,7 +110,8 @@ Application::Application(QObject* parent) MoveToNewThread(network_remote_); // This must be before libraray_->Init(); - // In the constructor the helper waits for the signal PlaylistManagerInitialized + // In the constructor the helper waits for the signal + // PlaylistManagerInitialized // to start the remote. Without the playlist manager clementine can // crash when a client connects before the manager is initialized! network_remote_helper_ = new NetworkRemoteHelper(this); @@ -125,19 +125,14 @@ 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 library backends. - delete device_manager_; device_manager_ = nullptr; + delete device_manager_; + device_manager_ = nullptr; - foreach (QObject* object, objects_in_threads_) { - object->deleteLater(); - } + foreach(QObject * object, objects_in_threads_) { object->deleteLater(); } - foreach (QThread* thread, threads_) { - thread->quit(); - } + foreach(QThread * thread, threads_) { thread->quit(); } - foreach (QThread* thread, threads_) { - thread->wait(); - } + foreach(QThread * thread, threads_) { thread->wait(); } } void Application::MoveToNewThread(QObject* object) { @@ -155,9 +150,7 @@ void Application::MoveToThread(QObject* object, QThread* thread) { objects_in_threads_ << object; } -void Application::AddError(const QString& message) { - emit ErrorAdded(message); -} +void Application::AddError(const QString& message) { emit ErrorAdded(message); } QString Application::language_without_region() const { const int underscore = language_name_.indexOf('_'); @@ -171,13 +164,9 @@ LibraryBackend* Application::library_backend() const { return library()->backend(); } -LibraryModel* Application::library_model() const { - return library()->model(); -} +LibraryModel* Application::library_model() const { return library()->model(); } -void Application::ReloadSettings() { - emit SettingsChanged(); -} +void Application::ReloadSettings() { emit SettingsChanged(); } void Application::OpenSettingsDialogAtPage(SettingsDialog::Page page) { emit SettingsDialogRequested(page); diff --git a/src/core/application.h b/src/core/application.h index f414b12b5..c95543a9f 100644 --- a/src/core/application.h +++ b/src/core/application.h @@ -47,18 +47,18 @@ class PodcastUpdater; class TagReaderClient; class TaskManager; - class Application : public QObject { Q_OBJECT -public: + public: static bool kIsPortable; Application(QObject* parent = NULL); ~Application(); const QString& language_name() const { return language_name_; } - // Same as language_name, but remove the region code at the end if there is one + // Same as language_name, but remove the region code at the end if there is + // one QString language_without_region() const; void set_language_name(const QString& name) { language_name_ = name; } @@ -83,7 +83,9 @@ public: MoodbarLoader* moodbar_loader() const { return moodbar_loader_; } MoodbarController* moodbar_controller() const { return moodbar_controller_; } NetworkRemote* network_remote() const { return network_remote_; } - NetworkRemoteHelper* network_remote_helper() const { return network_remote_helper_; } + NetworkRemoteHelper* network_remote_helper() const { + return network_remote_helper_; + } LibraryBackend* library_backend() const; LibraryModel* library_model() const; @@ -91,7 +93,7 @@ public: void MoveToNewThread(QObject* object); void MoveToThread(QObject* object, QThread* thread); -public slots: + public slots: void AddError(const QString& message); void ReloadSettings(); void OpenSettingsDialogAtPage(SettingsDialog::Page page); @@ -101,7 +103,7 @@ signals: void SettingsChanged(); void SettingsDialogRequested(SettingsDialog::Page page); -private: + private: QString language_name_; TagReaderClient* tag_reader_client_; @@ -131,4 +133,4 @@ private: QList threads_; }; -#endif // APPLICATION_H +#endif // APPLICATION_H diff --git a/src/core/backgroundstreams.cpp b/src/core/backgroundstreams.cpp index a61ee3744..7e79df4bd 100644 --- a/src/core/backgroundstreams.cpp +++ b/src/core/backgroundstreams.cpp @@ -9,17 +9,14 @@ const char* BackgroundStreams::kSettingsGroup = "BackgroundStreams"; const char* BackgroundStreams::kHypnotoadUrl = "hypnotoad:///"; -const char* BackgroundStreams::kRainUrl = "http://data.clementine-player.org/rainymood"; +const char* BackgroundStreams::kRainUrl = + "http://data.clementine-player.org/rainymood"; const char* BackgroundStreams::kEnterpriseUrl = "enterprise:///"; BackgroundStreams::BackgroundStreams(EngineBase* engine, QObject* parent) - : QObject(parent), - engine_(engine) { -} + : QObject(parent), engine_(engine) {} -BackgroundStreams::~BackgroundStreams() { - SaveStreams(); -} +BackgroundStreams::~BackgroundStreams() { SaveStreams(); } void BackgroundStreams::LoadStreams() { QSettings s; @@ -39,8 +36,7 @@ void BackgroundStreams::LoadStreams() { int size = s.beginReadArray("streams"); for (int i = 0; i < size; ++i) { s.setArrayIndex(i); - AddStream(s.value("name").toString(), - s.value("url").toUrl(), + AddStream(s.value("name").toString(), s.value("url").toUrl(), s.value("volume").toInt()); } @@ -63,8 +59,7 @@ void BackgroundStreams::SaveStreams() { s.endArray(); } -void BackgroundStreams::AddStream(const QString& name, - const QUrl& url, +void BackgroundStreams::AddStream(const QString& name, const QUrl& url, int volume) { if (streams_.contains(name)) { return; @@ -134,7 +129,8 @@ bool BackgroundStreams::IsPlaying(const QString& name) const { void BackgroundStreams::AddAction(const QString& name, QAction* action) { if (!streams_.contains(name)) { - qLog(Error) << "Tried to add action for stream" << name << "which doesn't exist"; + qLog(Error) << "Tried to add action for stream" << name + << "which doesn't exist"; return; } @@ -156,7 +152,7 @@ void BackgroundStreams::StreamActionDestroyed() { return; } - foreach (Stream* stream, streams_.values()) { + foreach(Stream * stream, streams_.values()) { if (stream->action == action) { stream->action = nullptr; } @@ -169,7 +165,7 @@ void BackgroundStreams::StreamActionToggled(bool checked) { return; } - foreach (Stream* stream, streams_.values()) { + foreach(Stream * stream, streams_.values()) { if (stream->action == action) { EnableStream(stream->name, checked); } diff --git a/src/core/backgroundstreams.h b/src/core/backgroundstreams.h index 942f40dfa..208fe3c10 100644 --- a/src/core/backgroundstreams.h +++ b/src/core/backgroundstreams.h @@ -29,7 +29,7 @@ class BackgroundStreams : public QObject { void AddAction(const QString& name, QAction* action); - signals: +signals: void StreamStarted(const QString& name); void StreamStopped(const QString& name); diff --git a/src/core/boundfuturewatcher.h b/src/core/boundfuturewatcher.h index cd0a60d7a..5c68a06b3 100644 --- a/src/core/boundfuturewatcher.h +++ b/src/core/boundfuturewatcher.h @@ -9,12 +9,9 @@ template class BoundFutureWatcher : public QFutureWatcher, boost::noncopyable { public: BoundFutureWatcher(const D& data, QObject* parent = 0) - : QFutureWatcher(parent), - data_(data) { - } + : QFutureWatcher(parent), data_(data) {} - ~BoundFutureWatcher() { - } + ~BoundFutureWatcher() {} const D& data() const { return data_; } diff --git a/src/core/cachedlist.h b/src/core/cachedlist.h index 9f0c4c828..ca81c184e 100644 --- a/src/core/cachedlist.h +++ b/src/core/cachedlist.h @@ -23,7 +23,7 @@ template class CachedList { -public: + public: // Use a CachedList when you want to download and save a list of things from a // remote service, updating it only periodically. // T must be a registered metatype and must support being stored in @@ -34,10 +34,9 @@ public: CachedList(const QString& settings_group, const QString& name, int cache_duration_secs) - : settings_group_(settings_group), - name_(name), - cache_duration_secs_(cache_duration_secs) { - } + : settings_group_(settings_group), + name_(name), + cache_duration_secs_(cache_duration_secs) {} void Load() { QSettings s; @@ -47,7 +46,7 @@ public: data_.clear(); const int count = s.beginReadArray(name_ + "_data"); - for (int i=0 ; i(); } @@ -61,7 +60,7 @@ public: s.setValue("last_refreshed_" + name_, last_updated_); s.beginWriteArray(name_ + "_data", data_.size()); - for (int i=0 ; i cache_duration_secs_; + last_updated_.secsTo(QDateTime::currentDateTime()) > + cache_duration_secs_; } - void Sort() { - qSort(data_); - } + void Sort() { qSort(data_); } const ListType& Data() const { return data_; } operator ListType() const { return data_; } @@ -91,7 +89,7 @@ public: const_iterator begin() const { return data_.begin(); } const_iterator end() const { return data_.end(); } -private: + private: const QString settings_group_; const QString name_; const int cache_duration_secs_; @@ -100,4 +98,4 @@ private: ListType data_; }; -#endif // CACHEDLIST_H +#endif // CACHEDLIST_H diff --git a/src/core/commandlineoptions.cpp b/src/core/commandlineoptions.cpp index ae24a19fb..5869e6e40 100644 --- a/src/core/commandlineoptions.cpp +++ b/src/core/commandlineoptions.cpp @@ -28,7 +28,6 @@ #include #include - const char* CommandlineOptions::kHelpText = "%1: clementine [%2] [%3]\n" "\n" @@ -62,23 +61,21 @@ const char* CommandlineOptions::kHelpText = " --log-levels %29\n" " --version %30\n"; -const char* CommandlineOptions::kVersionText = - "Clementine %1"; +const char* CommandlineOptions::kVersionText = "Clementine %1"; CommandlineOptions::CommandlineOptions(int argc, char** argv) - : argc_(argc), - argv_(argv), - url_list_action_(UrlList_Append), - player_action_(Player_None), - set_volume_(-1), - volume_modifier_(0), - seek_to_(-1), - seek_by_(0), - play_track_at_(-1), - show_osd_(false), - toggle_pretty_osd_(false), - log_levels_(logging::kDefaultLogLevels) -{ + : argc_(argc), + argv_(argv), + url_list_action_(UrlList_Append), + player_action_(Player_None), + set_volume_(-1), + volume_modifier_(0), + seek_to_(-1), + seek_by_(0), + play_track_at_(-1), + show_osd_(false), + toggle_pretty_osd_(false), + log_levels_(logging::kDefaultLogLevels) { #ifdef Q_OS_DARWIN // Remove -psn_xxx option that Mac passes when opened from Finder. RemoveArg("-psn", 1); @@ -93,7 +90,7 @@ void CommandlineOptions::RemoveArg(const QString& starts_with, int count) { QString opt(argv_[i]); if (opt.startsWith(starts_with)) { for (int j = i; j < argc_ - count + 1; ++j) { - argv_[j] = argv_[j+count]; + argv_[j] = argv_[j + count]; } argc_ -= count; break; @@ -103,37 +100,32 @@ void CommandlineOptions::RemoveArg(const QString& starts_with, int count) { bool CommandlineOptions::Parse() { static const struct option kOptions[] = { - {"help", no_argument, 0, 'h'}, - - {"play", no_argument, 0, 'p'}, - {"play-pause", no_argument, 0, 't'}, - {"pause", no_argument, 0, 'u'}, - {"stop", no_argument, 0, 's'}, - {"previous", no_argument, 0, 'r'}, - {"next", no_argument, 0, 'f'}, - {"volume", required_argument, 0, 'v'}, - {"volume-up", no_argument, 0, VolumeUp}, - - {"volume-down", no_argument, 0, VolumeDown}, - {"volume-increase-by", required_argument, 0, VolumeIncreaseBy}, - {"volume-decrease-by", required_argument, 0, VolumeDecreaseBy}, - {"seek-to", required_argument, 0, SeekTo}, - {"seek-by", required_argument, 0, SeekBy}, - {"restart-or-previous", no_argument, 0, RestartOrPrevious}, - - {"append", no_argument, 0, 'a'}, - {"load", no_argument, 0, 'l'}, - {"play-track", required_argument, 0, 'k'}, - {"show-osd", no_argument, 0, 'o'}, - {"toggle-pretty-osd", no_argument, 0, 'y'}, - {"language", required_argument, 0, 'g'}, - {"quiet", no_argument, 0, Quiet}, - {"verbose", no_argument, 0, Verbose}, - {"log-levels", required_argument, 0, LogLevels}, - {"version", no_argument, 0, Version}, - - {0, 0, 0, 0} - }; + {"help", no_argument, 0, 'h'}, + {"play", no_argument, 0, 'p'}, + {"play-pause", no_argument, 0, 't'}, + {"pause", no_argument, 0, 'u'}, + {"stop", no_argument, 0, 's'}, + {"previous", no_argument, 0, 'r'}, + {"next", no_argument, 0, 'f'}, + {"volume", required_argument, 0, 'v'}, + {"volume-up", no_argument, 0, VolumeUp}, + {"volume-down", no_argument, 0, VolumeDown}, + {"volume-increase-by", required_argument, 0, VolumeIncreaseBy}, + {"volume-decrease-by", required_argument, 0, VolumeDecreaseBy}, + {"seek-to", required_argument, 0, SeekTo}, + {"seek-by", required_argument, 0, SeekBy}, + {"restart-or-previous", no_argument, 0, RestartOrPrevious}, + {"append", no_argument, 0, 'a'}, + {"load", no_argument, 0, 'l'}, + {"play-track", required_argument, 0, 'k'}, + {"show-osd", no_argument, 0, 'o'}, + {"toggle-pretty-osd", no_argument, 0, 'y'}, + {"language", required_argument, 0, 'g'}, + {"quiet", no_argument, 0, Quiet}, + {"verbose", no_argument, 0, Verbose}, + {"log-levels", required_argument, 0, LogLevels}, + {"version", no_argument, 0, Version}, + {0, 0, 0, 0}}; // Parse the arguments bool ok = false; @@ -141,62 +133,97 @@ bool CommandlineOptions::Parse() { int c = getopt_long(argc_, argv_, "hptusrfv:alk:oyg:", kOptions, nullptr); // End of the options - if (c == -1) - break; + if (c == -1) break; switch (c) { case 'h': { - QString translated_help_text = QString(kHelpText).arg( - tr("Usage"), tr("options"), tr("URL(s)"), tr("Player options"), - tr("Start the playlist currently playing"), - tr("Play if stopped, pause if playing"), - tr("Pause playback"), - tr("Stop playback"), - tr("Skip backwards in playlist")).arg( - tr("Skip forwards in playlist"), - tr("Set the volume to percent"), - tr("Increase the volume by 4%"), - tr("Decrease the volume by 4%"), - tr("Increase the volume by percent"), - tr("Decrease the volume by percent")).arg( - tr("Seek the currently playing track to an absolute position"), - tr("Seek the currently playing track by a relative amount"), - tr("Restart the track, or play the previous track if within 8 seconds of start."), - tr("Playlist options"), - tr("Append files/URLs to the playlist"), - tr("Loads files/URLs, replacing current playlist"), - tr("Play the th track in the playlist")).arg( - tr("Other options"), - tr("Display the on-screen-display"), - tr("Toggle visibility for the pretty on-screen-display"), - tr("Change the language"), - tr("Equivalent to --log-levels *:1"), - tr("Equivalent to --log-levels *:3"), - tr("Comma separated list of class:level, level is 0-3")).arg( - tr("Print out version information")); + QString translated_help_text = + QString(kHelpText) + .arg(tr("Usage"), tr("options"), tr("URL(s)"), + tr("Player options"), + tr("Start the playlist currently playing"), + tr("Play if stopped, pause if playing"), + tr("Pause playback"), tr("Stop playback"), + tr("Skip backwards in playlist")) + .arg(tr("Skip forwards in playlist"), + tr("Set the volume to percent"), + tr("Increase the volume by 4%"), + tr("Decrease the volume by 4%"), + tr("Increase the volume by percent"), + tr("Decrease the volume by percent")) + .arg(tr("Seek the currently playing track to an absolute " + "position"), + tr("Seek the currently playing track by a relative " + "amount"), + tr("Restart the track, or play the previous track if " + "within 8 seconds of start."), + tr("Playlist options"), + tr("Append files/URLs to the playlist"), + tr("Loads files/URLs, replacing current playlist"), + tr("Play the th track in the playlist")) + .arg(tr("Other options"), tr("Display the on-screen-display"), + tr("Toggle visibility for the pretty on-screen-display"), + tr("Change the language"), + tr("Equivalent to --log-levels *:1"), + tr("Equivalent to --log-levels *:3"), + tr("Comma separated list of class:level, level is 0-3")) + .arg(tr("Print out version information")); std::cout << translated_help_text.toLocal8Bit().constData(); return false; } - case 'p': player_action_ = Player_Play; break; - case 't': player_action_ = Player_PlayPause; break; - case 'u': player_action_ = Player_Pause; break; - case 's': player_action_ = Player_Stop; break; - case 'r': player_action_ = Player_Previous; break; - case 'f': player_action_ = Player_Next; break; - case 'a': url_list_action_ = UrlList_Append; break; - case 'l': url_list_action_ = UrlList_Load; break; - case 'o': show_osd_ = true; break; - case 'y': toggle_pretty_osd_ = true; break; - case 'g': language_ = QString(optarg); break; - case VolumeUp: volume_modifier_ = +4; break; - case VolumeDown: volume_modifier_ = -4; break; - case Quiet: log_levels_ = "1"; break; - case Verbose: log_levels_ = "3"; break; - case LogLevels: log_levels_ = QString(optarg); break; + case 'p': + player_action_ = Player_Play; + break; + case 't': + player_action_ = Player_PlayPause; + break; + case 'u': + player_action_ = Player_Pause; + break; + case 's': + player_action_ = Player_Stop; + break; + case 'r': + player_action_ = Player_Previous; + break; + case 'f': + player_action_ = Player_Next; + break; + case 'a': + url_list_action_ = UrlList_Append; + break; + case 'l': + url_list_action_ = UrlList_Load; + break; + case 'o': + show_osd_ = true; + break; + case 'y': + toggle_pretty_osd_ = true; + break; + case 'g': + language_ = QString(optarg); + break; + case VolumeUp: + volume_modifier_ = +4; + break; + case VolumeDown: + volume_modifier_ = -4; + break; + case Quiet: + log_levels_ = "1"; + break; + case Verbose: + log_levels_ = "3"; + break; + case LogLevels: + log_levels_ = QString(optarg); + break; case Version: { - QString version_text = QString(kVersionText).arg(CLEMENTINE_VERSION_DISPLAY); + QString version_text = + QString(kVersionText).arg(CLEMENTINE_VERSION_DISPLAY); std::cout << version_text.toLocal8Bit().constData() << std::endl; std::exit(0); } @@ -241,7 +268,7 @@ bool CommandlineOptions::Parse() { } // Get any filenames or URLs following the arguments - for (int i=optind ; i> *this; } -QString CommandlineOptions::tr(const char *source_text) { +QString CommandlineOptions::tr(const char* source_text) { return QObject::tr(source_text); } QDataStream& operator<<(QDataStream& s, const CommandlineOptions& a) { - s << qint32(a.player_action_) - << qint32(a.url_list_action_) - << a.set_volume_ - << a.volume_modifier_ - << a.seek_to_ - << a.seek_by_ - << a.play_track_at_ - << a.show_osd_ - << a.urls_ - << a.log_levels_ - << a.toggle_pretty_osd_; + s << qint32(a.player_action_) << qint32(a.url_list_action_) << a.set_volume_ + << a.volume_modifier_ << a.seek_to_ << a.seek_by_ << a.play_track_at_ + << a.show_osd_ << a.urls_ << a.log_levels_ << a.toggle_pretty_osd_; return s; } @@ -308,17 +322,9 @@ QDataStream& operator<<(QDataStream& s, const CommandlineOptions& a) { QDataStream& operator>>(QDataStream& s, CommandlineOptions& a) { quint32 player_action = 0; quint32 url_list_action = 0; - s >> player_action - >> url_list_action - >> a.set_volume_ - >> a.volume_modifier_ - >> a.seek_to_ - >> a.seek_by_ - >> a.play_track_at_ - >> a.show_osd_ - >> a.urls_ - >> a.log_levels_ - >> a.toggle_pretty_osd_; + s >> player_action >> url_list_action >> a.set_volume_ >> + a.volume_modifier_ >> a.seek_to_ >> a.seek_by_ >> a.play_track_at_ >> + a.show_osd_ >> a.urls_ >> a.log_levels_ >> a.toggle_pretty_osd_; a.player_action_ = CommandlineOptions::PlayerAction(player_action); a.url_list_action_ = CommandlineOptions::UrlListAction(url_list_action); diff --git a/src/core/commandlineoptions.h b/src/core/commandlineoptions.h index f6f72bc77..c03fcba76 100644 --- a/src/core/commandlineoptions.h +++ b/src/core/commandlineoptions.h @@ -27,17 +27,14 @@ class CommandlineOptions { friend QDataStream& operator>>(QDataStream& s, CommandlineOptions& a); public: - CommandlineOptions(int argc = 0, char** argv = NULL); + CommandlineOptions(int argc = 0, char* *argv = NULL); static const char* kHelpText; static const char* kVersionText; // Don't change the values or order, these get serialised and sent to // possibly a different version of Clementine - enum UrlListAction { - UrlList_Append = 0, - UrlList_Load = 1, - }; + enum UrlListAction { UrlList_Append = 0, UrlList_Load = 1, }; enum PlayerAction { Player_None = 0, Player_Play = 1, @@ -90,7 +87,6 @@ class CommandlineOptions { void RemoveArg(const QString& starts_with, int count); private: - int argc_; char** argv_; @@ -114,4 +110,4 @@ class CommandlineOptions { QDataStream& operator<<(QDataStream& s, const CommandlineOptions& a); QDataStream& operator>>(QDataStream& s, CommandlineOptions& a); -#endif // COMMANDLINEOPTIONS_H +#endif // COMMANDLINEOPTIONS_H diff --git a/src/core/crashreporting.cpp b/src/core/crashreporting.cpp index fb761e139..e461d91ec 100644 --- a/src/core/crashreporting.cpp +++ b/src/core/crashreporting.cpp @@ -31,25 +31,23 @@ #include #if defined(HAVE_BREAKPAD) and defined(Q_OS_LINUX) -# include "client/linux/handler/exception_handler.h" -# include "third_party/lss/linux_syscall_support.h" +#include "client/linux/handler/exception_handler.h" +#include "third_party/lss/linux_syscall_support.h" #endif - -const char* CrashSender::kUploadURL = "http://crashes.clementine-player.org/getuploadurl"; +const char* CrashSender::kUploadURL = + "http://crashes.clementine-player.org/getuploadurl"; const char* CrashReporting::kSendCrashReportOption = "--send-crash-report"; char* CrashReporting::sPath = nullptr; #if defined(HAVE_BREAKPAD) and defined(Q_OS_LINUX) CrashReporting::CrashReporting() - : handler_(new google_breakpad::ExceptionHandler( - QDir::tempPath().toLocal8Bit().constData(), nullptr, - CrashReporting::Handler, this, true)) { -} + : handler_(new google_breakpad::ExceptionHandler( + QDir::tempPath().toLocal8Bit().constData(), nullptr, + CrashReporting::Handler, this, true)) {} -CrashReporting::~CrashReporting() { -} +CrashReporting::~CrashReporting() {} bool CrashReporting::SendCrashReport(int argc, char** argv) { if (argc != 4 || strcmp(argv[1], kSendCrashReportOption) != 0) { @@ -76,21 +74,21 @@ void CrashReporting::Print(const char* message) { } } -bool CrashReporting::Handler(const char* dump_path, - const char* minidump_id, - void* context, - bool succeeded) { +bool CrashReporting::Handler(const char* dump_path, const char* minidump_id, + void* context, bool succeeded) { Print("Clementine has crashed! A crash report has been saved to:\n "); Print(dump_path); Print("/"); Print(minidump_id); - Print("\n\nPlease send this to the developers so they can fix the problem:\n" - " http://code.google.com/p/clementine-player/issues/entry\n\n"); + Print( + "\n\nPlease send this to the developers so they can fix the problem:\n" + " http://code.google.com/p/clementine-player/issues/entry\n\n"); if (sPath) { // We know the path to clementine, so exec it again to prompt the user to // upload the report. - const char* argv[] = {sPath, kSendCrashReportOption, dump_path, minidump_id, nullptr}; + const char* argv[] = {sPath, kSendCrashReportOption, dump_path, minidump_id, + nullptr}; sys_execv(sPath, argv); } @@ -99,11 +97,10 @@ bool CrashReporting::Handler(const char* dump_path, } CrashSender::CrashSender(const QString& path) - : network_(new QNetworkAccessManager(this)), - path_(path), - file_(new QFile(path_, this)), - progress_(nullptr) { -} + : network_(new QNetworkAccessManager(this)), + path_(path), + file_(new QFile(path_, this)), + progress_(nullptr) {} bool CrashSender::Start() { if (!file_->open(QIODevice::ReadOnly)) { @@ -112,10 +109,13 @@ bool CrashSender::Start() { } // No tr() here. - QMessageBox prompt(QMessageBox::Critical, "Clementine has crashed!", QString( - "A crash report has been created and saved to '%1'. With your permission " - "it can be automatically sent to our server so the developers can find " - "out what happened.").arg(path_)); + QMessageBox prompt(QMessageBox::Critical, "Clementine has crashed!", + QString( + "A crash report has been created and saved to '%1'. " + "With your permission " + "it can be automatically sent to our server so the " + "developers can find " + "out what happened.").arg(path_)); prompt.addButton("Don't send", QMessageBox::RejectRole); prompt.addButton("Send crash report", QMessageBox::AcceptRole); if (prompt.exec() == QDialog::Rejected) { @@ -141,7 +141,8 @@ void CrashSender::RedirectFinished() { reply->deleteLater(); - QUrl url = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); + QUrl url = + reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!url.isValid()) { progress_->close(); return; @@ -160,14 +161,17 @@ void CrashSender::RedirectFinished() { } QNetworkRequest req(url); - req.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary); + req.setHeader(QNetworkRequest::ContentTypeHeader, + "multipart/form-data; boundary=" + boundary); // Construct the multipart/form-data QByteArray form_data; form_data.reserve(file_data.size() + 1024); form_data.append("--"); form_data.append(boundary); - form_data.append("\nContent-Disposition: form-data; name=\"data\"; filename=\"data.dmp\"\n"); + form_data.append( + "\nContent-Disposition: form-data; name=\"data\"; " + "filename=\"data.dmp\"\n"); form_data.append("Content-Type: application/octet-stream\n\n"); form_data.append(file_data); form_data.append("\n--"); @@ -178,31 +182,25 @@ void CrashSender::RedirectFinished() { // Upload the data reply = network_->post(req, form_data); - connect(reply, SIGNAL(uploadProgress(qint64,qint64)), SLOT(UploadProgress(qint64))); + connect(reply, SIGNAL(uploadProgress(qint64, qint64)), + SLOT(UploadProgress(qint64))); connect(reply, SIGNAL(finished()), progress_, SLOT(close())); } -void CrashSender::UploadProgress(qint64 bytes) { - progress_->setValue(bytes); -} +void CrashSender::UploadProgress(qint64 bytes) { progress_->setValue(bytes); } -#else // HAVE_BREAKPAD +#else // HAVE_BREAKPAD namespace google_breakpad { - class ExceptionHandler {}; +class ExceptionHandler {}; } -CrashReporting::CrashReporting() { -} +CrashReporting::CrashReporting() {} -CrashReporting::~CrashReporting() { -} +CrashReporting::~CrashReporting() {} -bool CrashReporting::SendCrashReport(int, char**) { - return false; -} +bool CrashReporting::SendCrashReport(int, char**) { return false; } -void CrashReporting::SetApplicationPath(const QString&) { -} +void CrashReporting::SetApplicationPath(const QString&) {} -#endif // HAVE_BREAKPAD +#endif // HAVE_BREAKPAD diff --git a/src/core/crashreporting.h b/src/core/crashreporting.h index a627d0bb0..ec36d9bc5 100644 --- a/src/core/crashreporting.h +++ b/src/core/crashreporting.h @@ -27,14 +27,13 @@ class QNetworkAccessManager; class QProgressDialog; namespace google_breakpad { - class ExceptionHandler; +class ExceptionHandler; } - // Wraps google_breakpad::ExceptionHandler - while an instance of this class // is alive crashes will be handled. class CrashReporting { -public: + public: CrashReporting(); ~CrashReporting(); @@ -48,17 +47,15 @@ public: // --send-crash-report when a crash happens. static void SetApplicationPath(const QString& path); -private: + private: // Prints the message to stdout without using libc. static void Print(const char* message); // Breakpad callback. - static bool Handler(const char* dump_path, - const char* minidump_id, - void* context, - bool succeeded); + static bool Handler(const char* dump_path, const char* minidump_id, + void* context, bool succeeded); -private: + private: Q_DISABLE_COPY(CrashReporting); static const char* kSendCrashReportOption; @@ -67,24 +64,23 @@ private: std::unique_ptr handler_; }; - // Asks the user if he wants to send a crash report, and displays a progress // dialog while uploading it if he does. class CrashSender : public QObject { Q_OBJECT -public: + public: CrashSender(const QString& path); // Returns false if the user doesn't want to send the crash report (caller // should exit), or true if he does (caller should start the Qt event loop). bool Start(); -private slots: + private slots: void RedirectFinished(); void UploadProgress(qint64 bytes); -private: + private: static const char* kUploadURL; QNetworkAccessManager* network_; @@ -94,4 +90,4 @@ private: QProgressDialog* progress_; }; -#endif // CRASHREPORTING_H +#endif // CRASHREPORTING_H diff --git a/src/core/database.cpp b/src/core/database.cpp index a8183dce9..36821fb2d 100644 --- a/src/core/database.cpp +++ b/src/core/database.cpp @@ -46,65 +46,59 @@ int Database::sNextConnectionId = 1; QMutex Database::sNextConnectionIdMutex; Database::Token::Token(const QString& token, int start, int end) - : token(token), - start_offset(start), - end_offset(end) { -} + : token(token), start_offset(start), end_offset(end) {} struct sqlite3_tokenizer_module { int iVersion; - int (*xCreate)( - int argc, /* Size of argv array */ - const char *const*argv, /* Tokenizer argument strings */ - sqlite3_tokenizer **ppTokenizer); /* OUT: Created tokenizer */ + int (*xCreate)(int argc, /* Size of argv array */ + const char* const* argv, /* Tokenizer argument strings */ + sqlite3_tokenizer** ppTokenizer); /* OUT: Created tokenizer */ - int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + int (*xDestroy)(sqlite3_tokenizer* pTokenizer); int (*xOpen)( - sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ - const char *pInput, int nBytes, /* Input buffer */ - sqlite3_tokenizer_cursor **ppCursor);/* OUT: Created tokenizer cursor */ + sqlite3_tokenizer* pTokenizer, /* Tokenizer object */ + const char* pInput, int nBytes, /* Input buffer */ + sqlite3_tokenizer_cursor** ppCursor); /* OUT: Created tokenizer cursor */ - int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + int (*xClose)(sqlite3_tokenizer_cursor* pCursor); int (*xNext)( - sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ - const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ - int *piStartOffset, /* OUT: Byte offset of token in input buffer */ - int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ - int *piPosition); /* OUT: Number of tokens returned before this one */ + sqlite3_tokenizer_cursor* pCursor, /* Tokenizer cursor */ + const char** ppToken, int* pnBytes, /* OUT: Normalized text for token */ + int* piStartOffset, /* OUT: Byte offset of token in input buffer */ + int* piEndOffset, /* OUT: Byte offset of end of token in input buffer */ + int* piPosition); /* OUT: Number of tokens returned before this one */ }; struct sqlite3_tokenizer { - const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + const sqlite3_tokenizer_module* pModule; /* The module for this tokenizer */ /* Tokenizer implementations will typically add additional fields */ }; struct sqlite3_tokenizer_cursor { - sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + sqlite3_tokenizer* pTokenizer; /* Tokenizer for this cursor. */ /* Tokenizer implementations will typically add additional fields */ }; sqlite3_tokenizer_module* Database::sFTSTokenizer = nullptr; - -int Database::FTSCreate(int argc, const char* const* argv, sqlite3_tokenizer** tokenizer) { +int Database::FTSCreate(int argc, const char* const* argv, + sqlite3_tokenizer** tokenizer) { *tokenizer = reinterpret_cast(new UnicodeTokenizer); return SQLITE_OK; } int Database::FTSDestroy(sqlite3_tokenizer* tokenizer) { - UnicodeTokenizer* real_tokenizer = reinterpret_cast(tokenizer); + UnicodeTokenizer* real_tokenizer = + reinterpret_cast(tokenizer); delete real_tokenizer; return SQLITE_OK; } -int Database::FTSOpen( - sqlite3_tokenizer* pTokenizer, - const char* input, - int bytes, - sqlite3_tokenizer_cursor** cursor) { +int Database::FTSOpen(sqlite3_tokenizer* pTokenizer, const char* input, + int bytes, sqlite3_tokenizer_cursor** cursor) { UnicodeTokenizerCursor* new_cursor = new UnicodeTokenizerCursor; new_cursor->pTokenizer = pTokenizer; new_cursor->position = 0; @@ -163,20 +157,18 @@ int Database::FTSOpen( } int Database::FTSClose(sqlite3_tokenizer_cursor* cursor) { - UnicodeTokenizerCursor* real_cursor = reinterpret_cast(cursor); + UnicodeTokenizerCursor* real_cursor = + reinterpret_cast(cursor); delete real_cursor; return SQLITE_OK; } -int Database::FTSNext( - sqlite3_tokenizer_cursor* cursor, - const char** token, - int* bytes, - int* start_offset, - int* end_offset, - int* position) { - UnicodeTokenizerCursor* real_cursor = reinterpret_cast(cursor); +int Database::FTSNext(sqlite3_tokenizer_cursor* cursor, const char** token, + int* bytes, int* start_offset, int* end_offset, + int* position) { + UnicodeTokenizerCursor* real_cursor = + reinterpret_cast(cursor); QList tokens = real_cursor->tokens; if (real_cursor->position >= tokens.size()) { @@ -196,7 +188,6 @@ int Database::FTSNext( return SQLITE_OK; } - void Database::StaticInit() { sFTSTokenizer = new sqlite3_tokenizer_module; sFTSTokenizer->iVersion = 0; @@ -208,24 +199,24 @@ void Database::StaticInit() { return; } -Database::Database(Application* app, QObject* parent, const QString& database_name) - : QObject(parent), - app_(app), - mutex_(QMutex::Recursive), - injected_database_name_(database_name), - query_hash_(0), - startup_schema_version_(-1) -{ +Database::Database(Application* app, QObject* parent, + const QString& database_name) + : QObject(parent), + app_(app), + mutex_(QMutex::Recursive), + injected_database_name_(database_name), + query_hash_(0), + startup_schema_version_(-1) { { QMutexLocker l(&sNextConnectionIdMutex); connection_id_ = sNextConnectionId++; } - directory_ = QDir::toNativeSeparators( - Utilities::GetConfigPath(Utilities::Path_Root)); + directory_ = + QDir::toNativeSeparators(Utilities::GetConfigPath(Utilities::Path_Root)); attached_databases_["jamendo"] = AttachedDatabase( - directory_ + "/jamendo.db", ":/schema/jamendo.sql", false); + directory_ + "/jamendo.db", ":/schema/jamendo.sql", false); QMutexLocker l(&mutex_); Connect(); @@ -241,9 +232,8 @@ QSqlDatabase Database::Connect() { } } - const QString connection_id = - QString("%1_thread_%2").arg(connection_id_).arg( - reinterpret_cast(QThread::currentThread())); + const QString connection_id = QString("%1_thread_%2").arg(connection_id_).arg( + reinterpret_cast(QThread::currentThread())); // Try to find an existing connection for this thread QSqlDatabase db = QSqlDatabase::database(connection_id); @@ -269,8 +259,9 @@ QSqlDatabase Database::Connect() { { QSqlQuery set_fts_tokenizer("SELECT fts3_tokenizer(:name, :pointer)", db); set_fts_tokenizer.bindValue(":name", "unicode"); - set_fts_tokenizer.bindValue(":pointer", QByteArray( - reinterpret_cast(&sFTSTokenizer), sizeof(&sFTSTokenizer))); + set_fts_tokenizer.bindValue( + ":pointer", QByteArray(reinterpret_cast(&sFTSTokenizer), + sizeof(&sFTSTokenizer))); if (!set_fts_tokenizer.exec()) { qLog(Warning) << "Couldn't register FTS3 tokenizer"; } @@ -288,15 +279,15 @@ QSqlDatabase Database::Connect() { for (const QString& key : attached_databases_.keys()) { QString filename = attached_databases_[key].filename_; - if (!injected_database_name_.isNull()) - filename = injected_database_name_; + if (!injected_database_name_.isNull()) filename = injected_database_name_; // Attach the db QSqlQuery q("ATTACH DATABASE :filename AS :alias", db); q.bindValue(":filename", filename); q.bindValue(":alias", key); if (!q.exec()) { - qFatal("Couldn't attach external database '%s'", key.toAscii().constData()); + qFatal("Couldn't attach external database '%s'", + key.toAscii().constData()); } } @@ -311,8 +302,10 @@ QSqlDatabase Database::Connect() { attached_databases_[key].schema_.isEmpty()) continue; // Find out if there are any tables in this database - QSqlQuery q(QString("SELECT ROWID FROM %1.sqlite_master" - " WHERE type='table'").arg(key), db); + QSqlQuery q(QString( + "SELECT ROWID FROM %1.sqlite_master" + " WHERE type='table'").arg(key), + db); if (!q.exec() || !q.next()) { q.finish(); ExecSchemaCommandsFromFile(db, attached_databases_[key].schema_, 0); @@ -327,8 +320,7 @@ void Database::UpdateMainSchema(QSqlDatabase* db) { int schema_version = 0; { QSqlQuery q("SELECT version FROM schema_version", *db); - if (q.next()) - schema_version = q.value(0).toInt(); + if (q.next()) schema_version = q.value(0).toInt(); // Implicit invocation of ~QSqlQuery() when leaving the scope // to release any remaining database locks! } @@ -336,12 +328,13 @@ void Database::UpdateMainSchema(QSqlDatabase* db) { startup_schema_version_ = schema_version; if (schema_version > kSchemaVersion) { - qLog(Warning) << "The database schema (version" << schema_version << ") is newer than I was expecting"; + qLog(Warning) << "The database schema (version" << schema_version + << ") is newer than I was expecting"; return; } if (schema_version < kSchemaVersion) { // Update the schema - for (int v = schema_version+1; v <= kSchemaVersion; ++v) { + for (int v = schema_version + 1; v <= kSchemaVersion; ++v) { UpdateDatabaseSchema(v, *db); } } @@ -384,8 +377,8 @@ void Database::AttachDatabase(const QString& database_name, attached_databases_[database_name] = database; } -void Database::AttachDatabaseOnDbConnection(const QString &database_name, - const AttachedDatabase &database, +void Database::AttachDatabaseOnDbConnection(const QString& database_name, + const AttachedDatabase& database, QSqlDatabase& db) { AttachDatabase(database_name, database); @@ -394,7 +387,8 @@ void Database::AttachDatabaseOnDbConnection(const QString &database_name, q.bindValue(":filename", database.filename_); q.bindValue(":alias", database_name); if (!q.exec()) { - qFatal("Couldn't attach external database '%s'", database_name.toAscii().constData()); + qFatal("Couldn't attach external database '%s'", + database_name.toAscii().constData()); } } @@ -414,7 +408,7 @@ void Database::DetachDatabase(const QString& database_name) { attached_databases_.remove(database_name); } -void Database::UpdateDatabaseSchema(int version, QSqlDatabase &db) { +void Database::UpdateDatabaseSchema(int version, QSqlDatabase& db) { QString filename; if (version == 0) filename = ":/schema/schema.sql"; @@ -434,20 +428,22 @@ void Database::UpdateDatabaseSchema(int version, QSqlDatabase &db) { UrlEncodeFilenameColumn(table, db); } } - qLog(Debug) << "Applying database schema update" << version - << "from" << filename; + qLog(Debug) << "Applying database schema update" << version << "from" + << filename; ExecSchemaCommandsFromFile(db, filename, version - 1, true); t.Commit(); } else { - qLog(Debug) << "Applying database schema update" << version - << "from" << filename; + qLog(Debug) << "Applying database schema update" << version << "from" + << filename; ExecSchemaCommandsFromFile(db, filename, version - 1); } } void Database::UrlEncodeFilenameColumn(const QString& table, QSqlDatabase& db) { QSqlQuery select(QString("SELECT ROWID, filename FROM %1").arg(table), db); - QSqlQuery update(QString("UPDATE %1 SET filename=:filename WHERE ROWID=:id").arg(table), db); + QSqlQuery update( + QString("UPDATE %1 SET filename=:filename WHERE ROWID=:id").arg(table), + db); select.exec(); if (CheckErrors(select)) return; while (select.next()) { @@ -475,16 +471,12 @@ void Database::ExecSchemaCommandsFromFile(QSqlDatabase& db, QFile schema_file(filename); if (!schema_file.open(QIODevice::ReadOnly)) qFatal("Couldn't open schema file %s", filename.toUtf8().constData()); - ExecSchemaCommands(db, - QString::fromUtf8(schema_file.readAll()), - schema_version, - in_transaction); + ExecSchemaCommands(db, QString::fromUtf8(schema_file.readAll()), + schema_version, in_transaction); } -void Database::ExecSchemaCommands(QSqlDatabase& db, - const QString& schema, - int schema_version, - bool in_transaction) { +void Database::ExecSchemaCommands(QSqlDatabase& db, const QString& schema, + int schema_version, bool in_transaction) { // Run each command const QStringList commands(schema.split(QRegExp("; *\n\n"))); @@ -530,8 +522,7 @@ void Database::ExecSongTablesCommands(QSqlDatabase& db, } } else { QSqlQuery query(db.exec(command)); - if (CheckErrors(query)) - qFatal("Unable to update music library database"); + if (CheckErrors(query)) qFatal("Unable to update music library database"); } } } @@ -541,14 +532,17 @@ QStringList Database::SongsTables(QSqlDatabase& db, int schema_version) const { // look for the tables in the main db for (const QString& table : db.tables()) { - if (table == "songs" || table.endsWith("_songs")) - ret << table; + if (table == "songs" || table.endsWith("_songs")) ret << table; } // look for the tables in attached dbs for (const QString& key : attached_databases_.keys()) { - QSqlQuery q(QString("SELECT NAME FROM %1.sqlite_master" - " WHERE type='table' AND name='songs' OR name LIKE '%songs'").arg(key), db); + QSqlQuery q( + QString( + "SELECT NAME FROM %1.sqlite_master" + " WHERE type='table' AND name='songs' OR name LIKE '%songs'") + .arg(key), + db); if (q.exec()) { while (q.next()) { QString tab_name = key + "." + q.value(0).toString(); @@ -595,9 +589,11 @@ bool Database::IntegrityCheck(QSqlDatabase db) { break; } else { if (!error_reported) { - app_->AddError(tr("Database corruption detected. Please read " - "https://code.google.com/p/clementine-player/wiki/DatabaseCorruption " - "for instructions on how to recover your database")); + app_->AddError( + tr("Database corruption detected. Please read " + "https://code.google.com/p/clementine-player/wiki/" + "DatabaseCorruption " + "for instructions on how to recover your database")); } app_->AddError("Database: " + message); error_reported = true; @@ -621,17 +617,16 @@ void Database::DoBackup() { } } -bool Database::OpenDatabase(const QString& filename, sqlite3** connection) const { +bool Database::OpenDatabase(const QString& filename, + sqlite3** connection) const { int ret = sqlite3_open(filename.toUtf8(), connection); if (ret != 0) { if (*connection) { const char* error_message = sqlite3_errmsg(*connection); - qLog(Error) << "Failed to open database for backup:" - << filename + qLog(Error) << "Failed to open database for backup:" << filename << error_message; } else { - qLog(Error) << "Failed to open database for backup:" - << filename; + qLog(Error) << "Failed to open database for backup:" << filename; } return false; } @@ -641,7 +636,8 @@ bool Database::OpenDatabase(const QString& filename, sqlite3** connection) const void Database::BackupFile(const QString& filename) { qLog(Debug) << "Starting database backup"; QString dest_filename = QString("%1.bak").arg(filename); - const int task_id = app_->task_manager()->StartTask(tr("Backing up database")); + const int task_id = + app_->task_manager()->StartTask(tr("Backing up database")); sqlite3* source_connection = nullptr; sqlite3* dest_connection = nullptr; @@ -651,7 +647,8 @@ void Database::BackupFile(const QString& filename) { sqlite3_close(source_connection); sqlite3_close(dest_connection); app_->task_manager()->SetTaskFinished(task_id); - } BOOST_SCOPE_EXIT_END + } + BOOST_SCOPE_EXIT_END bool success = OpenDatabase(filename, &source_connection); if (!success) { @@ -663,9 +660,8 @@ void Database::BackupFile(const QString& filename) { return; } - sqlite3_backup* backup = sqlite3_backup_init( - dest_connection, "main", - source_connection, "main"); + sqlite3_backup* backup = + sqlite3_backup_init(dest_connection, "main", source_connection, "main"); if (!backup) { const char* error_message = sqlite3_errmsg(dest_connection); qLog(Error) << "Failed to start database backup:" << error_message; diff --git a/src/core/database.h b/src/core/database.h index a3fc8bcc0..36a6a9714 100644 --- a/src/core/database.h +++ b/src/core/database.h @@ -34,7 +34,6 @@ extern "C" { struct sqlite3_tokenizer; struct sqlite3_tokenizer_cursor; struct sqlite3_tokenizer_module; - } class Application; @@ -48,8 +47,9 @@ class Database : public QObject { struct AttachedDatabase { AttachedDatabase() {} - AttachedDatabase(const QString& filename, const QString& schema, bool is_temporary) - : filename_(filename), schema_(schema), is_temporary_(is_temporary) {} + AttachedDatabase(const QString& filename, const QString& schema, + bool is_temporary) + : filename_(filename), schema_(schema), is_temporary_(is_temporary) {} QString filename_; QString schema_; @@ -65,21 +65,20 @@ class Database : public QObject { QMutex* Mutex() { return &mutex_; } void RecreateAttachedDb(const QString& database_name); - void ExecSchemaCommands(QSqlDatabase& db, - const QString& schema, - int schema_version, - bool in_transaction = false); + void ExecSchemaCommands(QSqlDatabase& db, const QString& schema, + int schema_version, bool in_transaction = false); int startup_schema_version() const { return startup_schema_version_; } int current_schema_version() const { return kSchemaVersion; } - void AttachDatabase(const QString& database_name, const AttachedDatabase& database); + void AttachDatabase(const QString& database_name, + const AttachedDatabase& database); void AttachDatabaseOnDbConnection(const QString& database_name, const AttachedDatabase& database, QSqlDatabase& db); void DetachDatabase(const QString& database_name); - signals: +signals: void Error(const QString& message); public slots: @@ -88,12 +87,10 @@ class Database : public QObject { private: void UpdateMainSchema(QSqlDatabase* db); - void ExecSchemaCommandsFromFile(QSqlDatabase& db, - const QString& filename, + void ExecSchemaCommandsFromFile(QSqlDatabase& db, const QString& filename, int schema_version, bool in_transaction = false); - void ExecSongTablesCommands(QSqlDatabase& db, - const QStringList& song_tables, + void ExecSongTablesCommands(QSqlDatabase& db, const QStringList& song_tables, const QStringList& commands); void UpdateDatabaseSchema(int version, QSqlDatabase& db); @@ -137,26 +134,23 @@ class Database : public QObject { // Do static initialisation like loading sqlite functions. static void StaticInit(); - typedef int (*Sqlite3CreateFunc) ( - sqlite3*, const char*, int, int, void*, - void (*) (sqlite3_context*, int, sqlite3_value**), - void (*) (sqlite3_context*, int, sqlite3_value**), - void (*) (sqlite3_context*)); + typedef int (*Sqlite3CreateFunc)(sqlite3*, const char*, int, int, void*, + void (*)(sqlite3_context*, int, + sqlite3_value**), + void (*)(sqlite3_context*, int, + sqlite3_value**), + void (*)(sqlite3_context*)); static sqlite3_tokenizer_module* sFTSTokenizer; - static int FTSCreate(int argc, const char* const* argv, sqlite3_tokenizer** tokenizer); + static int FTSCreate(int argc, const char* const* argv, + sqlite3_tokenizer** tokenizer); static int FTSDestroy(sqlite3_tokenizer* tokenizer); - static int FTSOpen(sqlite3_tokenizer* tokenizer, - const char* input, - int bytes, + static int FTSOpen(sqlite3_tokenizer* tokenizer, const char* input, int bytes, sqlite3_tokenizer_cursor** cursor); static int FTSClose(sqlite3_tokenizer_cursor* cursor); - static int FTSNext(sqlite3_tokenizer_cursor* cursor, - const char** token, - int* bytes, - int* start_offset, - int* end_offset, + static int FTSNext(sqlite3_tokenizer_cursor* cursor, const char** token, + int* bytes, int* start_offset, int* end_offset, int* position); struct Token { Token(const QString& token, int start, int end); @@ -182,11 +176,11 @@ class Database : public QObject { class MemoryDatabase : public Database { public: MemoryDatabase(Application* app, QObject* parent = 0) - : Database(app, parent, ":memory:") {} + : Database(app, parent, ":memory:") {} ~MemoryDatabase() { // Make sure Qt doesn't reuse the same database QSqlDatabase::removeDatabase(Connect().connectionName()); } }; -#endif // DATABASE_H +#endif // DATABASE_H diff --git a/src/core/deletefiles.cpp b/src/core/deletefiles.cpp index 45db3f260..46d8e29f5 100644 --- a/src/core/deletefiles.cpp +++ b/src/core/deletefiles.cpp @@ -29,22 +29,19 @@ const int DeleteFiles::kBatchSize = 50; DeleteFiles::DeleteFiles(TaskManager* task_manager, std::shared_ptr storage) - : thread_(nullptr), - task_manager_(task_manager), - storage_(storage), - started_(false), - task_id_(0), - progress_(0) -{ + : thread_(nullptr), + task_manager_(task_manager), + storage_(storage), + started_(false), + task_id_(0), + progress_(0) { original_thread_ = thread(); } -DeleteFiles::~DeleteFiles() { -} +DeleteFiles::~DeleteFiles() {} void DeleteFiles::Start(const SongList& songs) { - if (thread_) - return; + if (thread_) return; songs_ = songs; @@ -60,7 +57,7 @@ void DeleteFiles::Start(const SongList& songs) { void DeleteFiles::Start(const QStringList& filenames) { SongList songs; - foreach (const QString& filename, filenames) { + foreach(const QString & filename, filenames) { Song song; song.set_url(QUrl::fromLocalFile(filename)); songs << song; @@ -98,7 +95,7 @@ void DeleteFiles::ProcessSomeFiles() { // We process files in batches so we can be cancelled part-way through. const int n = qMin(songs_.count(), progress_ + kBatchSize); - for ( ; progress_SetTaskProgress(task_id_, progress_, songs_.count()); const Song& song = songs_[progress_]; diff --git a/src/core/deletefiles.h b/src/core/deletefiles.h index 142c5a7b5..ddef77797 100644 --- a/src/core/deletefiles.h +++ b/src/core/deletefiles.h @@ -30,7 +30,7 @@ class TaskManager; class DeleteFiles : public QObject { Q_OBJECT -public: + public: DeleteFiles(TaskManager* task_manager, std::shared_ptr storage); ~DeleteFiles(); @@ -42,10 +42,10 @@ public: signals: void Finished(const SongList& songs_with_errors); -private slots: + private slots: void ProcessSomeFiles(); -private: + private: QThread* thread_; QThread* original_thread_; TaskManager* task_manager_; @@ -61,4 +61,4 @@ private: SongList songs_with_errors_; }; -#endif // DELETEFILES_H +#endif // DELETEFILES_H diff --git a/src/core/fht.cpp b/src/core/fht.cpp index 36d276edf..7f8d84759 100644 --- a/src/core/fht.cpp +++ b/src/core/fht.cpp @@ -22,221 +22,182 @@ #include #include "fht.h" +FHT::FHT(int n) : m_buf(0), m_tab(0), m_log(0) { + if (n < 3) { + m_num = 0; + m_exp2 = -1; + return; + } + m_exp2 = n; + m_num = 1 << n; + if (n > 3) { + m_buf = new float[m_num]; + m_tab = new float[m_num * 2]; + makeCasTable(); + } +} -FHT::FHT(int n) : - m_buf(0), - m_tab(0), - m_log(0) -{ - if (n < 3) { - m_num = 0; - m_exp2 = -1; - return; +FHT::~FHT() { + delete[] m_buf; + delete[] m_tab; + delete[] m_log; +} + +void FHT::makeCasTable(void) { + float d, *costab, *sintab; + int ul, ndiv2 = m_num / 2; + + for (costab = m_tab, sintab = m_tab + m_num / 2 + 1, ul = 0; ul < m_num; + ul++) { + d = M_PI * ul / ndiv2; + *costab = *sintab = cos(d); + + costab += 2, sintab += 2; + if (sintab > m_tab + m_num * 2) sintab = m_tab + 1; + } +} + +float* FHT::copy(float* d, float* s) { + return (float*)memcpy(d, s, m_num * sizeof(float)); +} + +float* FHT::clear(float* d) { + return (float*)memset(d, 0, m_num * sizeof(float)); +} + +void FHT::scale(float* p, float d) { + for (int i = 0; i < (m_num / 2); i++) *p++ *= d; +} + +void FHT::ewma(float* d, float* s, float w) { + for (int i = 0; i < (m_num / 2); i++, d++, s++) *d = *d * w + *s * (1 - w); +} + +void FHT::logSpectrum(float* out, float* p) { + int n = m_num / 2, i, j, k, *r; + if (!m_log) { + m_log = new int[n]; + float f = n / log10((double)n); + for (i = 0, r = m_log; i < n; i++, r++) { + j = int(rint(log10(i + 1.0) * f)); + *r = j >= n ? n - 1 : j; } - m_exp2 = n; - m_num = 1 << n; - if (n > 3) { - m_buf = new float[m_num]; - m_tab = new float[m_num * 2]; - makeCasTable(); + } + semiLogSpectrum(p); + *out++ = *p = *p / 100; + for (k = i = 1, r = m_log; i < n; i++) { + j = *r++; + if (i == j) + *out++ = p[i]; + else { + float base = p[k - 1]; + float step = (p[j] - base) / (j - (k - 1)); + for (float corr = 0; k <= j; k++, corr += step) *out++ = base + corr; } + } } - -FHT::~FHT() -{ - delete[] m_buf; - delete[] m_tab; - delete[] m_log; +void FHT::semiLogSpectrum(float* p) { + float e; + power2(p); + for (int i = 0; i < (m_num / 2); i++, p++) { + e = 10.0 * log10(sqrt(*p * .5)); + *p = e < 0 ? 0 : e; + } } - -void FHT::makeCasTable(void) -{ - float d, *costab, *sintab; - int ul, ndiv2 = m_num / 2; - - for (costab = m_tab, sintab = m_tab + m_num / 2 + 1, ul = 0; ul < m_num; ul++) { - d = M_PI * ul / ndiv2; - *costab = *sintab = cos(d); - - costab += 2, sintab += 2; - if (sintab > m_tab + m_num * 2) - sintab = m_tab + 1; - } +void FHT::spectrum(float* p) { + power2(p); + for (int i = 0; i < (m_num / 2); i++, p++) *p = (float)sqrt(*p * .5); } - -float* FHT::copy(float *d, float *s) -{ - return (float *)memcpy(d, s, m_num * sizeof(float)); +void FHT::power(float* p) { + power2(p); + for (int i = 0; i < (m_num / 2); i++) *p++ *= .5; } +void FHT::power2(float* p) { + int i; + float* q; + _transform(p, m_num, 0); -float* FHT::clear(float *d) -{ - return (float *)memset(d, 0, m_num * sizeof(float)); + *p = (*p * *p), *p += *p, p++; + + for (i = 1, q = p + m_num - 2; i < (m_num / 2); i++, --q) + *p = (*p * *p) + (*q * *q), p++; } - -void FHT::scale(float *p, float d) -{ - for (int i = 0; i < (m_num / 2); i++) - *p++ *= d; -} - - -void FHT::ewma(float *d, float *s, float w) -{ - for (int i = 0; i < (m_num / 2); i++, d++, s++) - *d = *d * w + *s * (1 - w); -} - - -void FHT::logSpectrum(float *out, float *p) -{ - int n = m_num / 2, i, j, k, *r; - if (!m_log) { - m_log = new int[n]; - float f = n / log10((double)n); - for (i = 0, r = m_log; i < n; i++, r++) { - j = int(rint(log10(i + 1.0) * f)); - *r = j >= n ? n - 1 : j; - } - } - semiLogSpectrum(p); - *out++ = *p = *p / 100; - for (k = i = 1, r = m_log; i < n; i++) { - j = *r++; - if (i == j) - *out++ = p[i]; - else { - float base = p[k - 1]; - float step = (p[j] - base) / (j - (k - 1)); - for (float corr = 0; k <= j; k++, corr += step) - *out++ = base + corr; - } - } -} - - -void FHT::semiLogSpectrum(float *p) -{ - float e; - power2(p); - for (int i = 0; i < (m_num / 2); i++, p++) { - e = 10.0 * log10(sqrt(*p * .5)); - *p = e < 0 ? 0 : e; - } -} - - -void FHT::spectrum(float *p) -{ - power2(p); - for (int i = 0; i < (m_num / 2); i++, p++) - *p = (float)sqrt(*p * .5); -} - - -void FHT::power(float *p) -{ - power2(p); - for (int i = 0; i < (m_num / 2); i++) - *p++ *= .5; -} - - -void FHT::power2(float *p) -{ - int i; - float *q; +void FHT::transform(float* p) { + if (m_num == 8) + transform8(p); + else _transform(p, m_num, 0); - - *p = (*p * *p), *p += *p, p++; - - for (i = 1, q = p + m_num - 2; i < (m_num / 2); i++, --q) - *p = (*p * *p) + (*q * *q), p++; } +void FHT::transform8(float* p) { + float a, b, c, d, e, f, g, h, b_f2, d_h2; + float a_c_eg, a_ce_g, ac_e_g, aceg, b_df_h, bdfh; -void FHT::transform(float *p) -{ - if (m_num == 8) - transform8(p); - else - _transform(p, m_num, 0); + a = *p++, b = *p++, c = *p++, d = *p++; + e = *p++, f = *p++, g = *p++, h = *p; + b_f2 = (b - f) * M_SQRT2; + d_h2 = (d - h) * M_SQRT2; + + a_c_eg = a - c - e + g; + a_ce_g = a - c + e - g; + ac_e_g = a + c - e - g; + aceg = a + c + e + g; + + b_df_h = b - d + f - h; + bdfh = b + d + f + h; + + *p = a_c_eg - d_h2; + *--p = a_ce_g - b_df_h; + *--p = ac_e_g - b_f2; + *--p = aceg - bdfh; + *--p = a_c_eg + d_h2; + *--p = a_ce_g + b_df_h; + *--p = ac_e_g + b_f2; + *--p = aceg + bdfh; } +void FHT::_transform(float* p, int n, int k) { + if (n == 8) { + transform8(p + k); + return; + } -void FHT::transform8(float *p) -{ - float a, b, c, d, e, f, g, h, b_f2, d_h2; - float a_c_eg, a_ce_g, ac_e_g, aceg, b_df_h, bdfh; + int i, j, ndiv2 = n / 2; + float a, *t1, *t2, *t3, *t4, *ptab, *pp; - a = *p++, b = *p++, c = *p++, d = *p++; - e = *p++, f = *p++, g = *p++, h = *p; - b_f2 = (b - f) * M_SQRT2; - d_h2 = (d - h) * M_SQRT2; + for (i = 0, t1 = m_buf, t2 = m_buf + ndiv2, pp = &p[k]; i < ndiv2; i++) + *t1++ = *pp++, *t2++ = *pp++; - a_c_eg = a - c - e + g; - a_ce_g = a - c + e - g; - ac_e_g = a + c - e - g; - aceg = a + c + e + g; + memcpy(p + k, m_buf, sizeof(float) * n); - b_df_h = b - d + f - h; - bdfh = b + d + f + h; + _transform(p, ndiv2, k); + _transform(p, ndiv2, k + ndiv2); - *p = a_c_eg - d_h2; - *--p = a_ce_g - b_df_h; - *--p = ac_e_g - b_f2; - *--p = aceg - bdfh; - *--p = a_c_eg + d_h2; - *--p = a_ce_g + b_df_h; - *--p = ac_e_g + b_f2; - *--p = aceg + bdfh; -} + j = m_num / ndiv2 - 1; + t1 = m_buf; + t2 = t1 + ndiv2; + t3 = p + k + ndiv2; + ptab = m_tab; + pp = p + k; + a = *ptab++ * *t3++; + a += *ptab * *pp; + ptab += j; -void FHT::_transform(float *p, int n, int k) -{ - if (n == 8) { - transform8(p + k); - return; - } - - int i, j, ndiv2 = n / 2; - float a, *t1, *t2, *t3, *t4, *ptab, *pp; - - for (i = 0, t1 = m_buf, t2 = m_buf + ndiv2, pp = &p[k]; i < ndiv2; i++) - *t1++ = *pp++, *t2++ = *pp++; - - memcpy(p + k, m_buf, sizeof(float) * n); - - _transform(p, ndiv2, k); - _transform(p, ndiv2, k + ndiv2); - - j = m_num / ndiv2 - 1; - t1 = m_buf; - t2 = t1 + ndiv2; - t3 = p + k + ndiv2; - ptab = m_tab; - pp = p + k; + *t1++ = *pp + a; + *t2++ = *pp++ - a; + for (i = 1, t4 = p + k + n; i < ndiv2; i++, ptab += j) { a = *ptab++ * *t3++; - a += *ptab * *pp; - ptab += j; + a += *ptab * *--t4; *t1++ = *pp + a; *t2++ = *pp++ - a; - - for (i = 1, t4 = p + k + n; i < ndiv2; i++, ptab += j) { - a = *ptab++ * *t3++; - a += *ptab * *--t4; - - *t1++ = *pp + a; - *t2++ = *pp++ - a; - } - memcpy(p + k, m_buf, sizeof(float) * n); + } + memcpy(p + k, m_buf, sizeof(float) * n); } - diff --git a/src/core/fht.h b/src/core/fht.h index 059fb4299..73c5daa6a 100644 --- a/src/core/fht.h +++ b/src/core/fht.h @@ -29,91 +29,90 @@ * * [1] Computer in Physics, Vol. 9, No. 4, Jul/Aug 1995 pp 373-379 */ -class FHT -{ - int m_exp2; - int m_num; - float *m_buf; - float *m_tab; - int *m_log; +class FHT { + int m_exp2; + int m_num; + float* m_buf; + float* m_tab; + int* m_log; - /** - * Create a table of "cas" (cosine and sine) values. - * Has only to be done in the constructor and saves from - * calculating the same values over and over while transforming. - */ - void makeCasTable(); + /** + * Create a table of "cas" (cosine and sine) values. + * Has only to be done in the constructor and saves from + * calculating the same values over and over while transforming. + */ + void makeCasTable(); - /** - * Recursive in-place Hartley transform. For internal use only! - */ - void _transform(float *, int, int); + /** + * Recursive in-place Hartley transform. For internal use only! + */ + void _transform(float*, int, int); - public: - /** - * Prepare transform for data sets with @f$2^n@f$ numbers, whereby @f$n@f$ - * should be at least 3. Values of more than 3 need a trigonometry table. - * @see makeCasTable() - */ - FHT(int); + public: + /** + * Prepare transform for data sets with @f$2^n@f$ numbers, whereby @f$n@f$ + * should be at least 3. Values of more than 3 need a trigonometry table. + * @see makeCasTable() + */ + FHT(int); - ~FHT(); - inline int sizeExp() const { return m_exp2; } - inline int size() const { return m_num; } - float *copy(float *, float *); - float *clear(float *); - void scale(float *, float); + ~FHT(); + inline int sizeExp() const { return m_exp2; } + inline int size() const { return m_num; } + float* copy(float*, float*); + float* clear(float*); + void scale(float*, float); - /** - * Exponentially Weighted Moving Average (EWMA) filter. - * @param d is the filtered data. - * @param s is fresh input. - * @param w is the weighting factor. - */ - void ewma(float *d, float *s, float w); + /** + * Exponentially Weighted Moving Average (EWMA) filter. + * @param d is the filtered data. + * @param s is fresh input. + * @param w is the weighting factor. + */ + void ewma(float* d, float* s, float w); - /** - * Logarithmic audio spectrum. Maps semi-logarithmic spectrum - * to logarithmic frequency scale, interpolates missing values. - * A logarithmic index map is calculated at the first run only. - * @param p is the input array. - * @param out is the spectrum. - */ - void logSpectrum(float *out, float *p); + /** + * Logarithmic audio spectrum. Maps semi-logarithmic spectrum + * to logarithmic frequency scale, interpolates missing values. + * A logarithmic index map is calculated at the first run only. + * @param p is the input array. + * @param out is the spectrum. + */ + void logSpectrum(float* out, float* p); - /** - * Semi-logarithmic audio spectrum. - */ - void semiLogSpectrum(float *); + /** + * Semi-logarithmic audio spectrum. + */ + void semiLogSpectrum(float*); - /** - * Fourier spectrum. - */ - void spectrum(float *); + /** + * Fourier spectrum. + */ + void spectrum(float*); - /** - * Calculates a mathematically correct FFT power spectrum. - * If further scaling is applied later, use power2 instead - * and factor the 0.5 in the final scaling factor. - * @see FHT::power2() - */ - void power(float *); + /** + * Calculates a mathematically correct FFT power spectrum. + * If further scaling is applied later, use power2 instead + * and factor the 0.5 in the final scaling factor. + * @see FHT::power2() + */ + void power(float*); - /** - * Calculates an FFT power spectrum with doubled values as a - * result. The values need to be multiplied by 0.5 to be exact. - * Note that you only get @f$2^{n-1}@f$ power values for a data set - * of @f$2^n@f$ input values. This is the fastest transform. - * @see FHT::power() - */ - void power2(float *); + /** + * Calculates an FFT power spectrum with doubled values as a + * result. The values need to be multiplied by 0.5 to be exact. + * Note that you only get @f$2^{n-1}@f$ power values for a data set + * of @f$2^n@f$ input values. This is the fastest transform. + * @see FHT::power() + */ + void power2(float*); - /** - * Discrete Hartley transform of data sets with 8 values. - */ - void transform8(float *); + /** + * Discrete Hartley transform of data sets with 8 values. + */ + void transform8(float*); - void transform(float *); + void transform(float*); }; #endif diff --git a/src/core/filesystemmusicstorage.cpp b/src/core/filesystemmusicstorage.cpp index 968134483..1c7213f5c 100644 --- a/src/core/filesystemmusicstorage.cpp +++ b/src/core/filesystemmusicstorage.cpp @@ -23,17 +23,14 @@ #include FilesystemMusicStorage::FilesystemMusicStorage(const QString& root) - : root_(root) -{ -} + : root_(root) {} bool FilesystemMusicStorage::CopyToStorage(const CopyJob& job) { const QFileInfo src = QFileInfo(job.source_); - const QFileInfo dest = QFileInfo(root_ + "/" + job.destination_ ); + const QFileInfo dest = QFileInfo(root_ + "/" + job.destination_); // Don't do anything if the destination is the same as the source - if (src == dest) - return true; + if (src == dest) return true; // Create directories as required QDir dir; @@ -43,8 +40,7 @@ bool FilesystemMusicStorage::CopyToStorage(const CopyJob& job) { } // Remove the destination file if it exists and we want to overwrite - if (job.overwrite_ && dest.exists()) - QFile::remove(dest.absoluteFilePath()); + if (job.overwrite_ && dest.exists()) QFile::remove(dest.absoluteFilePath()); // Copy or move if (job.remove_original_) diff --git a/src/core/filesystemmusicstorage.h b/src/core/filesystemmusicstorage.h index 9c7ee20d8..71cae43dc 100644 --- a/src/core/filesystemmusicstorage.h +++ b/src/core/filesystemmusicstorage.h @@ -21,7 +21,7 @@ #include "musicstorage.h" class FilesystemMusicStorage : public virtual MusicStorage { -public: + public: FilesystemMusicStorage(const QString& root); ~FilesystemMusicStorage() {} @@ -30,8 +30,8 @@ public: bool CopyToStorage(const CopyJob& job); bool DeleteFromStorage(const DeleteJob& job); -private: + private: QString root_; }; -#endif // FILESYSTEMMUSICSTORAGE_H +#endif // FILESYSTEMMUSICSTORAGE_H diff --git a/src/core/filesystemwatcherinterface.cpp b/src/core/filesystemwatcherinterface.cpp index b6afcb0af..29d8f0cbd 100644 --- a/src/core/filesystemwatcherinterface.cpp +++ b/src/core/filesystemwatcherinterface.cpp @@ -24,10 +24,10 @@ #endif FileSystemWatcherInterface::FileSystemWatcherInterface(QObject* parent) - : QObject(parent) { -} + : QObject(parent) {} -FileSystemWatcherInterface* FileSystemWatcherInterface::Create(QObject* parent) { +FileSystemWatcherInterface* FileSystemWatcherInterface::Create( + QObject* parent) { FileSystemWatcherInterface* ret; #ifdef Q_OS_DARWIN ret = new MacFSListener(parent); diff --git a/src/core/filesystemwatcherinterface.h b/src/core/filesystemwatcherinterface.h index f451f2644..78bacf055 100644 --- a/src/core/filesystemwatcherinterface.h +++ b/src/core/filesystemwatcherinterface.h @@ -31,7 +31,7 @@ class FileSystemWatcherInterface : public QObject { static FileSystemWatcherInterface* Create(QObject* parent = 0); - signals: +signals: void PathChanged(const QString& path); }; diff --git a/src/core/globalshortcutbackend.cpp b/src/core/globalshortcutbackend.cpp index 80086ed59..b06d9d70c 100644 --- a/src/core/globalshortcutbackend.cpp +++ b/src/core/globalshortcutbackend.cpp @@ -20,16 +20,11 @@ #include "globalshortcuts.h" GlobalShortcutBackend::GlobalShortcutBackend(GlobalShortcuts* parent) - : QObject(parent), - manager_(parent), - active_(false) -{ -} + : QObject(parent), manager_(parent), active_(false) {} bool GlobalShortcutBackend::Register() { bool ret = DoRegister(); - if (ret) - active_ = true; + if (ret) active_ = true; return ret; } diff --git a/src/core/globalshortcutbackend.h b/src/core/globalshortcutbackend.h index 5666dca17..96a305633 100644 --- a/src/core/globalshortcutbackend.h +++ b/src/core/globalshortcutbackend.h @@ -25,7 +25,7 @@ class GlobalShortcuts; class GlobalShortcutBackend : public QObject { Q_OBJECT -public: + public: GlobalShortcutBackend(GlobalShortcuts* parent = 0); virtual ~GlobalShortcutBackend() {} @@ -37,7 +37,7 @@ public: signals: void RegisterFinished(bool success); -protected: + protected: virtual bool DoRegister() = 0; virtual void DoUnregister() = 0; @@ -45,4 +45,4 @@ protected: bool active_; }; -#endif // GLOBALSHORTCUTBACKEND_H +#endif // GLOBALSHORTCUTBACKEND_H diff --git a/src/core/globalshortcuts.cpp b/src/core/globalshortcuts.cpp index 42bec58d7..596a6d5bf 100644 --- a/src/core/globalshortcuts.cpp +++ b/src/core/globalshortcuts.cpp @@ -28,28 +28,32 @@ #include #ifdef QT_DBUS_LIB -# include +#include #endif const char* GlobalShortcuts::kSettingsGroup = "Shortcuts"; -GlobalShortcuts::GlobalShortcuts(QWidget *parent) - : QWidget(parent), - gnome_backend_(nullptr), - system_backend_(nullptr), - use_gnome_(false), - rating_signals_mapper_(new QSignalMapper(this)) -{ +GlobalShortcuts::GlobalShortcuts(QWidget* parent) + : QWidget(parent), + gnome_backend_(nullptr), + system_backend_(nullptr), + use_gnome_(false), + rating_signals_mapper_(new QSignalMapper(this)) { settings_.beginGroup(kSettingsGroup); // Create actions AddShortcut("play", tr("Play"), SIGNAL(Play())); AddShortcut("pause", tr("Pause"), SIGNAL(Pause())); - AddShortcut("play_pause", tr("Play/Pause"), SIGNAL(PlayPause()), QKeySequence(Qt::Key_MediaPlay)); - AddShortcut("stop", tr("Stop"), SIGNAL(Stop()), QKeySequence(Qt::Key_MediaStop)); - AddShortcut("stop_after", tr("Stop playing after current track"), SIGNAL(StopAfter())); - AddShortcut("next_track", tr("Next track"), SIGNAL(Next()), QKeySequence(Qt::Key_MediaNext)); - AddShortcut("prev_track", tr("Previous track"), SIGNAL(Previous()), QKeySequence(Qt::Key_MediaPrevious)); + AddShortcut("play_pause", tr("Play/Pause"), SIGNAL(PlayPause()), + QKeySequence(Qt::Key_MediaPlay)); + AddShortcut("stop", tr("Stop"), SIGNAL(Stop()), + QKeySequence(Qt::Key_MediaStop)); + AddShortcut("stop_after", tr("Stop playing after current track"), + SIGNAL(StopAfter())); + AddShortcut("next_track", tr("Next track"), SIGNAL(Next()), + QKeySequence(Qt::Key_MediaNext)); + AddShortcut("prev_track", tr("Previous track"), SIGNAL(Previous()), + QKeySequence(Qt::Key_MediaPrevious)); AddShortcut("inc_volume", tr("Increase volume"), SIGNAL(IncVolume())); AddShortcut("dec_volume", tr("Decrease volume"), SIGNAL(DecVolume())); AddShortcut("mute", tr("Mute"), SIGNAL(Mute())); @@ -57,19 +61,32 @@ GlobalShortcuts::GlobalShortcuts(QWidget *parent) AddShortcut("seek_backward", tr("Seek backward"), SIGNAL(SeekBackward())); AddShortcut("show_hide", tr("Show/Hide"), SIGNAL(ShowHide())); AddShortcut("show_osd", tr("Show OSD"), SIGNAL(ShowOSD())); - AddShortcut("toggle_pretty_osd", tr("Toggle Pretty OSD"), SIGNAL(TogglePrettyOSD())); // Toggling possible only for pretty OSD - AddShortcut("shuffle_mode", tr("Change shuffle mode"), SIGNAL(CycleShuffleMode())); - AddShortcut("repeat_mode", tr("Change repeat mode"), SIGNAL(CycleRepeatMode())); - AddShortcut("toggle_last_fm_scrobbling", tr("Enable/disable Last.fm scrobbling"), SIGNAL(ToggleScrobbling())); + AddShortcut( + "toggle_pretty_osd", tr("Toggle Pretty OSD"), + SIGNAL(TogglePrettyOSD())); // Toggling possible only for pretty OSD + AddShortcut("shuffle_mode", tr("Change shuffle mode"), + SIGNAL(CycleShuffleMode())); + AddShortcut("repeat_mode", tr("Change repeat mode"), + SIGNAL(CycleRepeatMode())); + AddShortcut("toggle_last_fm_scrobbling", + tr("Enable/disable Last.fm scrobbling"), + SIGNAL(ToggleScrobbling())); - AddRatingShortcut("rate_zero_star", tr("Rate the current song 0 stars"), rating_signals_mapper_, 0); - AddRatingShortcut("rate_one_star", tr("Rate the current song 1 star"), rating_signals_mapper_, 1); - AddRatingShortcut("rate_two_star", tr("Rate the current song 2 stars"), rating_signals_mapper_, 2); - AddRatingShortcut("rate_three_star", tr("Rate the current song 3 stars"), rating_signals_mapper_, 3); - AddRatingShortcut("rate_four_star", tr("Rate the current song 4 stars"), rating_signals_mapper_, 4); - AddRatingShortcut("rate_five_star", tr("Rate the current song 5 stars"), rating_signals_mapper_, 5); + AddRatingShortcut("rate_zero_star", tr("Rate the current song 0 stars"), + rating_signals_mapper_, 0); + AddRatingShortcut("rate_one_star", tr("Rate the current song 1 star"), + rating_signals_mapper_, 1); + AddRatingShortcut("rate_two_star", tr("Rate the current song 2 stars"), + rating_signals_mapper_, 2); + AddRatingShortcut("rate_three_star", tr("Rate the current song 3 stars"), + rating_signals_mapper_, 3); + AddRatingShortcut("rate_four_star", tr("Rate the current song 4 stars"), + rating_signals_mapper_, 4); + AddRatingShortcut("rate_five_star", tr("Rate the current song 5 stars"), + rating_signals_mapper_, 5); - connect(rating_signals_mapper_, SIGNAL(mapped(int)), SIGNAL(RateCurrentSong(int))); + connect(rating_signals_mapper_, SIGNAL(mapped(int)), + SIGNAL(RateCurrentSong(int))); // Create backends - these do the actual shortcut registration gnome_backend_ = new GnomeGlobalShortcutBackend(this); @@ -98,8 +115,8 @@ void GlobalShortcuts::AddRatingShortcut(const QString& id, const QString& name, mapper->setMapping(shortcut.action, rating); } -GlobalShortcuts::Shortcut GlobalShortcuts::AddShortcut(const QString& id, const QString& name, - const QKeySequence& default_key) { +GlobalShortcuts::Shortcut GlobalShortcuts::AddShortcut( + const QString& id, const QString& name, const QKeySequence& default_key) { Shortcut shortcut; shortcut.action = new QAction(name, this); QKeySequence key_sequence = QKeySequence::fromString( @@ -122,7 +139,7 @@ bool GlobalShortcuts::IsGsdAvailable() const { #ifdef QT_DBUS_LIB return QDBusConnection::sessionBus().interface()->isServiceRegistered( GnomeGlobalShortcutBackend::kGsdService); -#else // QT_DBUS_LIB +#else // QT_DBUS_LIB return false; #endif } @@ -137,21 +154,19 @@ void GlobalShortcuts::ReloadSettings() { } void GlobalShortcuts::Unregister() { - if (gnome_backend_->is_active()) - gnome_backend_->Unregister(); - if (system_backend_->is_active()) - system_backend_->Unregister(); + if (gnome_backend_->is_active()) gnome_backend_->Unregister(); + if (system_backend_->is_active()) system_backend_->Unregister(); } void GlobalShortcuts::Register() { - if (use_gnome_ && gnome_backend_->Register()) - return; + if (use_gnome_ && gnome_backend_->Register()) return; system_backend_->Register(); } bool GlobalShortcuts::IsMacAccessibilityEnabled() const { #ifdef Q_OS_MAC - return static_cast(system_backend_)->IsAccessibilityEnabled(); + return static_cast(system_backend_) + ->IsAccessibilityEnabled(); #else return true; #endif @@ -159,6 +174,7 @@ bool GlobalShortcuts::IsMacAccessibilityEnabled() const { void GlobalShortcuts::ShowMacAccessibilityDialog() { #ifdef Q_OS_MAC - static_cast(system_backend_)->ShowAccessibilityDialog(); + static_cast(system_backend_) + ->ShowAccessibilityDialog(); #endif } diff --git a/src/core/globalshortcuts.h b/src/core/globalshortcuts.h index ff6f97563..1dcaf9d3c 100644 --- a/src/core/globalshortcuts.h +++ b/src/core/globalshortcuts.h @@ -32,7 +32,7 @@ class QSignalMapper; class GlobalShortcuts : public QWidget { Q_OBJECT -public: + public: GlobalShortcuts(QWidget* parent = 0); static const char* kSettingsGroup; @@ -48,7 +48,7 @@ public: bool IsGsdAvailable() const; bool IsMacAccessibilityEnabled() const; -public slots: + public slots: void ReloadSettings(); void ShowMacAccessibilityDialog(); @@ -76,14 +76,16 @@ signals: void CycleRepeatMode(); void ToggleScrobbling(); -private: + private: void AddShortcut(const QString& id, const QString& name, const char* signal, const QKeySequence& default_key = QKeySequence(0)); - void AddRatingShortcut(const QString& id, const QString& name, QSignalMapper* mapper, - int rating, const QKeySequence& default_key = QKeySequence(0)); - Shortcut AddShortcut(const QString& id, const QString& name, const QKeySequence& default_key); + void AddRatingShortcut(const QString& id, const QString& name, + QSignalMapper* mapper, int rating, + const QKeySequence& default_key = QKeySequence(0)); + Shortcut AddShortcut(const QString& id, const QString& name, + const QKeySequence& default_key); -private: + private: GlobalShortcutBackend* gnome_backend_; GlobalShortcutBackend* system_backend_; diff --git a/src/core/gnomeglobalshortcutbackend.cpp b/src/core/gnomeglobalshortcutbackend.cpp index 9bd68a3ee..46f924516 100644 --- a/src/core/gnomeglobalshortcutbackend.cpp +++ b/src/core/gnomeglobalshortcutbackend.cpp @@ -21,7 +21,7 @@ #include "core/logging.h" #ifdef QT_DBUS_LIB -# include "dbus/gnomesettingsdaemon.h" +#include "dbus/gnomesettingsdaemon.h" #endif #include @@ -30,26 +30,27 @@ #include #ifdef QT_DBUS_LIB -# include +#include #endif -const char* GnomeGlobalShortcutBackend::kGsdService = "org.gnome.SettingsDaemon"; -const char* GnomeGlobalShortcutBackend::kGsdPath = "/org/gnome/SettingsDaemon/MediaKeys"; -const char* GnomeGlobalShortcutBackend::kGsdInterface = "org.gnome.SettingsDaemon.MediaKeys"; +const char* GnomeGlobalShortcutBackend::kGsdService = + "org.gnome.SettingsDaemon"; +const char* GnomeGlobalShortcutBackend::kGsdPath = + "/org/gnome/SettingsDaemon/MediaKeys"; +const char* GnomeGlobalShortcutBackend::kGsdInterface = + "org.gnome.SettingsDaemon.MediaKeys"; GnomeGlobalShortcutBackend::GnomeGlobalShortcutBackend(GlobalShortcuts* parent) - : GlobalShortcutBackend(parent), - interface_(nullptr), - is_connected_(false) -{ -} - + : GlobalShortcutBackend(parent), + interface_(nullptr), + is_connected_(false) {} bool GnomeGlobalShortcutBackend::DoRegister() { #ifdef QT_DBUS_LIB qLog(Debug) << "registering"; // Check if the GSD service is available - if (!QDBusConnection::sessionBus().interface()->isServiceRegistered(kGsdService)) { + if (!QDBusConnection::sessionBus().interface()->isServiceRegistered( + kGsdService)) { qLog(Warning) << "gnome settings daemon not registered"; return false; } @@ -64,56 +65,57 @@ bool GnomeGlobalShortcutBackend::DoRegister() { QDateTime::currentDateTime().toTime_t()); QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(reply, this); - NewClosure(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - this, SLOT(RegisterFinished(QDBusPendingCallWatcher*)), - watcher); + NewClosure(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, + SLOT(RegisterFinished(QDBusPendingCallWatcher*)), watcher); return true; -#else // QT_DBUS_LIB +#else // QT_DBUS_LIB qLog(Warning) << "dbus not available"; return false; #endif } -void GnomeGlobalShortcutBackend::RegisterFinished(QDBusPendingCallWatcher* watcher) { +void GnomeGlobalShortcutBackend::RegisterFinished( + QDBusPendingCallWatcher* watcher) { #ifdef QT_DBUS_LIB QDBusMessage reply = watcher->reply(); watcher->deleteLater(); if (reply.type() == QDBusMessage::ErrorMessage) { - qLog(Warning) << "Failed to grab media keys" - << reply.errorName() <isServiceRegistered(kGsdService)) - return; - if (!interface_ || !is_connected_) + if (!QDBusConnection::sessionBus().interface()->isServiceRegistered( + kGsdService)) return; + if (!interface_ || !is_connected_) return; is_connected_ = false; interface_->ReleaseMediaPlayerKeys(QCoreApplication::applicationName()); - disconnect(interface_, SIGNAL(MediaPlayerKeyPressed(QString,QString)), - this, SLOT(GnomeMediaKeyPressed(QString,QString))); + disconnect(interface_, SIGNAL(MediaPlayerKeyPressed(QString, QString)), this, + SLOT(GnomeMediaKeyPressed(QString, QString))); #endif } -void GnomeGlobalShortcutBackend::GnomeMediaKeyPressed(const QString&, const QString& key) { - if (key == "Play") manager_->shortcuts()["play_pause"].action->trigger(); - if (key == "Stop") manager_->shortcuts()["stop"].action->trigger(); - if (key == "Next") manager_->shortcuts()["next_track"].action->trigger(); +void GnomeGlobalShortcutBackend::GnomeMediaKeyPressed(const QString&, + const QString& key) { + if (key == "Play") manager_->shortcuts()["play_pause"].action->trigger(); + if (key == "Stop") manager_->shortcuts()["stop"].action->trigger(); + if (key == "Next") manager_->shortcuts()["next_track"].action->trigger(); if (key == "Previous") manager_->shortcuts()["prev_track"].action->trigger(); } diff --git a/src/core/gnomeglobalshortcutbackend.h b/src/core/gnomeglobalshortcutbackend.h index eec34fe5e..6127648bb 100644 --- a/src/core/gnomeglobalshortcutbackend.h +++ b/src/core/gnomeglobalshortcutbackend.h @@ -27,26 +27,26 @@ class QDBusPendingCallWatcher; class GnomeGlobalShortcutBackend : public GlobalShortcutBackend { Q_OBJECT -public: + public: GnomeGlobalShortcutBackend(GlobalShortcuts* parent); static const char* kGsdService; static const char* kGsdPath; static const char* kGsdInterface; -protected: + protected: bool RegisterInNewThread() const { return true; } bool DoRegister(); void DoUnregister(); -private slots: + private slots: void RegisterFinished(QDBusPendingCallWatcher* watcher); void GnomeMediaKeyPressed(const QString& application, const QString& key); -private: + private: OrgGnomeSettingsDaemonMediaKeysInterface* interface_; bool is_connected_; }; -#endif // GNOMEGLOBALSHORTCUTBACKEND_H +#endif // GNOMEGLOBALSHORTCUTBACKEND_H diff --git a/src/core/mac_delegate.h b/src/core/mac_delegate.h index f646cf1c1..8a5aaf5a5 100644 --- a/src/core/mac_delegate.h +++ b/src/core/mac_delegate.h @@ -7,11 +7,10 @@ #import #endif - class PlatformInterface; @class SPMediaKeyTap; -@interface AppDelegate :NSObject { +@interface AppDelegate : NSObject { PlatformInterface* application_handler_; NSMenu* dock_menu_; MacGlobalShortcutBackend* shortcut_handler_; @@ -22,21 +21,23 @@ class PlatformInterface; #endif } -- (id) initWithHandler: (PlatformInterface*)handler; +- (id)initWithHandler:(PlatformInterface*)handler; // NSApplicationDelegate -- (BOOL) applicationShouldHandleReopen: (NSApplication*)app hasVisibleWindows:(BOOL)flag; -- (NSMenu*) applicationDockMenu: (NSApplication*)sender; +- (BOOL)applicationShouldHandleReopen:(NSApplication*)app + hasVisibleWindows:(BOOL)flag; +- (NSMenu*)applicationDockMenu:(NSApplication*)sender; - (void)applicationDidFinishLaunching:(NSNotification*)aNotification; -- (NSApplicationTerminateReply) applicationShouldTerminate:(NSApplication*)sender; +- (NSApplicationTerminateReply)applicationShouldTerminate: + (NSApplication*)sender; // NSUserNotificationCenterDelegate -- (BOOL) userNotificationCenter: (id)center - shouldPresentNotification: (id)notification; +- (BOOL)userNotificationCenter:(id)center + shouldPresentNotification:(id)notification; -- (void) setDockMenu: (NSMenu*)menu; -- (MacGlobalShortcutBackend*) shortcut_handler; -- (void) setShortcutHandler: (MacGlobalShortcutBackend*)backend; -- (void) mediaKeyTap: (SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event; +- (void)setDockMenu:(NSMenu*)menu; +- (MacGlobalShortcutBackend*)shortcut_handler; +- (void)setShortcutHandler:(MacGlobalShortcutBackend*)backend; +- (void)mediaKeyTap:(SPMediaKeyTap*)keyTap + receivedMediaKeyEvent:(NSEvent*)event; @end - diff --git a/src/core/mac_utilities.h b/src/core/mac_utilities.h index fadaab0fd..21df859cf 100644 --- a/src/core/mac_utilities.h +++ b/src/core/mac_utilities.h @@ -30,5 +30,4 @@ namespace mac { QKeySequence KeySequenceFromNSEvent(NSEvent* event); void DumpDictionary(CFDictionaryRef dict); float GetDevicePixelRatio(QWidget* widget); - } diff --git a/src/core/macfslistener.h b/src/core/macfslistener.h index be83de5dd..327fa0c09 100644 --- a/src/core/macfslistener.h +++ b/src/core/macfslistener.h @@ -36,7 +36,7 @@ class MacFSListener : public FileSystemWatcherInterface { void RemovePath(const QString& path); void Clear(); - signals: +signals: void PathChanged(const QString& path); private slots: @@ -45,13 +45,10 @@ class MacFSListener : public FileSystemWatcherInterface { private: void UpdateStreamAsync(); - static void EventStreamCallback( - ConstFSEventStreamRef stream, - void* user_data, - size_t num_events, - void* event_paths, - const FSEventStreamEventFlags event_flags[], - const FSEventStreamEventId event_ids[]); + static void EventStreamCallback(ConstFSEventStreamRef stream, void* user_data, + size_t num_events, void* event_paths, + const FSEventStreamEventFlags event_flags[], + const FSEventStreamEventId event_ids[]); CFRunLoopRef run_loop_; FSEventStreamRef stream_; diff --git a/src/core/macglobalshortcutbackend.h b/src/core/macglobalshortcutbackend.h index 9abcf8e98..49ef44aac 100644 --- a/src/core/macglobalshortcutbackend.h +++ b/src/core/macglobalshortcutbackend.h @@ -31,7 +31,7 @@ class QAction; class MacGlobalShortcutBackend : public GlobalShortcutBackend { Q_OBJECT -public: + public: MacGlobalShortcutBackend(GlobalShortcuts* parent); virtual ~MacGlobalShortcutBackend(); @@ -40,11 +40,11 @@ public: void MacMediaKeyPressed(int key); -protected: + protected: bool DoRegister(); void DoUnregister(); -private: + private: bool KeyPressed(const QKeySequence& sequence); QMap shortcuts_; @@ -53,4 +53,4 @@ private: std::unique_ptr p_; }; -#endif // MACGLOBALSHORTCUTBACKEND_H +#endif // MACGLOBALSHORTCUTBACKEND_H diff --git a/src/core/mergedproxymodel.cpp b/src/core/mergedproxymodel.cpp index 8c7578a6d..fd3b77fe9 100644 --- a/src/core/mergedproxymodel.cpp +++ b/src/core/mergedproxymodel.cpp @@ -39,15 +39,12 @@ using boost::multi_index::multi_index_container; using boost::multi_index::ordered_unique; using boost::multi_index::tag; -std::size_t hash_value(const QModelIndex& index) { - return qHash(index); -} +std::size_t hash_value(const QModelIndex& index) { return qHash(index); } namespace { struct Mapping { - Mapping(const QModelIndex& _source_index) - : source_index(_source_index) {} + Mapping(const QModelIndex& _source_index) : source_index(_source_index) {} QModelIndex source_index; }; @@ -60,28 +57,23 @@ struct tag_by_pointer {}; class MergedProxyModelPrivate { private: typedef multi_index_container< - Mapping*, - indexed_by< - hashed_unique, - member >, - ordered_unique, - identity > - > - > MappingContainer; + Mapping*, + indexed_by< + hashed_unique, + member >, + ordered_unique, identity > > > + MappingContainer; public: MappingContainer mappings_; }; MergedProxyModel::MergedProxyModel(QObject* parent) - : QAbstractProxyModel(parent), - resetting_model_(nullptr), - p_(new MergedProxyModelPrivate) { -} + : QAbstractProxyModel(parent), + resetting_model_(nullptr), + p_(new MergedProxyModelPrivate) {} -MergedProxyModel::~MergedProxyModel() { - DeleteAllMappings(); -} +MergedProxyModel::~MergedProxyModel() { DeleteAllMappings(); } void MergedProxyModel::DeleteAllMappings() { const auto& begin = p_->mappings_.get().begin(); @@ -92,30 +84,28 @@ void MergedProxyModel::DeleteAllMappings() { void MergedProxyModel::AddSubModel(const QModelIndex& source_parent, QAbstractItemModel* submodel) { connect(submodel, SIGNAL(modelReset()), this, SLOT(SubModelReset())); - connect(submodel, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), - this, SLOT(RowsAboutToBeInserted(QModelIndex,int,int))); - connect(submodel, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), - this, SLOT(RowsAboutToBeRemoved(QModelIndex,int,int))); - connect(submodel, SIGNAL(rowsInserted(QModelIndex,int,int)), - this, SLOT(RowsInserted(QModelIndex,int,int))); - connect(submodel, SIGNAL(rowsRemoved(QModelIndex,int,int)), - this, SLOT(RowsRemoved(QModelIndex,int,int))); - connect(submodel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), - this, SLOT(DataChanged(QModelIndex,QModelIndex))); + connect(submodel, SIGNAL(rowsAboutToBeInserted(QModelIndex, int, int)), this, + SLOT(RowsAboutToBeInserted(QModelIndex, int, int))); + connect(submodel, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int)), this, + SLOT(RowsAboutToBeRemoved(QModelIndex, int, int))); + connect(submodel, SIGNAL(rowsInserted(QModelIndex, int, int)), this, + SLOT(RowsInserted(QModelIndex, int, int))); + connect(submodel, SIGNAL(rowsRemoved(QModelIndex, int, int)), this, + SLOT(RowsRemoved(QModelIndex, int, int))); + connect(submodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, + SLOT(DataChanged(QModelIndex, QModelIndex))); QModelIndex proxy_parent = mapFromSource(source_parent); const int rows = submodel->rowCount(); - if (rows) - beginInsertRows(proxy_parent, 0, rows-1); + if (rows) beginInsertRows(proxy_parent, 0, rows - 1); merge_points_.insert(submodel, source_parent); - if (rows) - endInsertRows(); + if (rows) endInsertRows(); } -void MergedProxyModel::RemoveSubModel(const QModelIndex &source_parent) { +void MergedProxyModel::RemoveSubModel(const QModelIndex& source_parent) { // Find the submodel that the parent corresponded to QAbstractItemModel* submodel = merge_points_.key(source_parent); merge_points_.remove(submodel); @@ -147,40 +137,42 @@ void MergedProxyModel::RemoveSubModel(const QModelIndex &source_parent) { void MergedProxyModel::setSourceModel(QAbstractItemModel* source_model) { if (sourceModel()) { - disconnect(sourceModel(), SIGNAL(modelReset()), this, SLOT(SourceModelReset())); - disconnect(sourceModel(), SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), - this, SLOT(RowsAboutToBeInserted(QModelIndex,int,int))); - disconnect(sourceModel(), SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), - this, SLOT(RowsAboutToBeRemoved(QModelIndex,int,int))); - disconnect(sourceModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), - this, SLOT(RowsInserted(QModelIndex,int,int))); - disconnect(sourceModel(), SIGNAL(rowsRemoved(QModelIndex,int,int)), - this, SLOT(RowsRemoved(QModelIndex,int,int))); - disconnect(sourceModel(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), - this, SLOT(DataChanged(QModelIndex,QModelIndex))); - disconnect(sourceModel(), SIGNAL(layoutAboutToBeChanged()), - this, SLOT(LayoutAboutToBeChanged())); - disconnect(sourceModel(), SIGNAL(layoutChanged()), - this, SLOT(LayoutChanged())); + disconnect(sourceModel(), SIGNAL(modelReset()), this, + SLOT(SourceModelReset())); + disconnect(sourceModel(), + SIGNAL(rowsAboutToBeInserted(QModelIndex, int, int)), this, + SLOT(RowsAboutToBeInserted(QModelIndex, int, int))); + disconnect(sourceModel(), + SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int)), this, + SLOT(RowsAboutToBeRemoved(QModelIndex, int, int))); + disconnect(sourceModel(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, + SLOT(RowsInserted(QModelIndex, int, int))); + disconnect(sourceModel(), SIGNAL(rowsRemoved(QModelIndex, int, int)), this, + SLOT(RowsRemoved(QModelIndex, int, int))); + disconnect(sourceModel(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), + this, SLOT(DataChanged(QModelIndex, QModelIndex))); + disconnect(sourceModel(), SIGNAL(layoutAboutToBeChanged()), this, + SLOT(LayoutAboutToBeChanged())); + disconnect(sourceModel(), SIGNAL(layoutChanged()), this, + SLOT(LayoutChanged())); } QAbstractProxyModel::setSourceModel(source_model); connect(sourceModel(), SIGNAL(modelReset()), this, SLOT(SourceModelReset())); - connect(sourceModel(), SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), - this, SLOT(RowsAboutToBeInserted(QModelIndex,int,int))); - connect(sourceModel(), SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), - this, SLOT(RowsAboutToBeRemoved(QModelIndex,int,int))); - connect(sourceModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), - this, SLOT(RowsInserted(QModelIndex,int,int))); - connect(sourceModel(), SIGNAL(rowsRemoved(QModelIndex,int,int)), - this, SLOT(RowsRemoved(QModelIndex,int,int))); - connect(sourceModel(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), - this, SLOT(DataChanged(QModelIndex,QModelIndex))); - connect(sourceModel(), SIGNAL(layoutAboutToBeChanged()), - this, SLOT(LayoutAboutToBeChanged())); - connect(sourceModel(), SIGNAL(layoutChanged()), - this, SLOT(LayoutChanged())); + connect(sourceModel(), SIGNAL(rowsAboutToBeInserted(QModelIndex, int, int)), + this, SLOT(RowsAboutToBeInserted(QModelIndex, int, int))); + connect(sourceModel(), SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int)), + this, SLOT(RowsAboutToBeRemoved(QModelIndex, int, int))); + connect(sourceModel(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, + SLOT(RowsInserted(QModelIndex, int, int))); + connect(sourceModel(), SIGNAL(rowsRemoved(QModelIndex, int, int)), this, + SLOT(RowsRemoved(QModelIndex, int, int))); + connect(sourceModel(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, + SLOT(DataChanged(QModelIndex, QModelIndex))); + connect(sourceModel(), SIGNAL(layoutAboutToBeChanged()), this, + SLOT(LayoutAboutToBeChanged())); + connect(sourceModel(), SIGNAL(layoutChanged()), this, SLOT(LayoutChanged())); } void MergedProxyModel::SourceModelReset() { @@ -227,15 +219,15 @@ void MergedProxyModel::SubModelReset() { // "Insert" items from the newly reset submodel int count = submodel->rowCount(); if (count) { - beginInsertRows(proxy_parent, 0, count-1); + beginInsertRows(proxy_parent, 0, count - 1); endInsertRows(); } emit SubModelReset(proxy_parent, submodel); } -QModelIndex MergedProxyModel::GetActualSourceParent(const QModelIndex& source_parent, - QAbstractItemModel* model) const { +QModelIndex MergedProxyModel::GetActualSourceParent( + const QModelIndex& source_parent, QAbstractItemModel* model) const { if (!source_parent.isValid() && model != sourceModel()) return merge_points_.value(model); return source_parent; @@ -243,8 +235,9 @@ QModelIndex MergedProxyModel::GetActualSourceParent(const QModelIndex& source_pa void MergedProxyModel::RowsAboutToBeInserted(const QModelIndex& source_parent, int start, int end) { - beginInsertRows(mapFromSource(GetActualSourceParent( - source_parent, static_cast(sender()))), + beginInsertRows( + mapFromSource(GetActualSourceParent( + source_parent, static_cast(sender()))), start, end); } @@ -254,8 +247,9 @@ void MergedProxyModel::RowsInserted(const QModelIndex&, int, int) { void MergedProxyModel::RowsAboutToBeRemoved(const QModelIndex& source_parent, int start, int end) { - beginRemoveRows(mapFromSource(GetActualSourceParent( - source_parent, static_cast(sender()))), + beginRemoveRows( + mapFromSource(GetActualSourceParent( + source_parent, static_cast(sender()))), start, end); } @@ -263,29 +257,26 @@ void MergedProxyModel::RowsRemoved(const QModelIndex&, int, int) { endRemoveRows(); } -QModelIndex MergedProxyModel::mapToSource(const QModelIndex& proxy_index) const { - if (!proxy_index.isValid()) - return QModelIndex(); +QModelIndex MergedProxyModel::mapToSource(const QModelIndex& proxy_index) + const { + if (!proxy_index.isValid()) return QModelIndex(); Mapping* mapping = static_cast(proxy_index.internalPointer()); if (p_->mappings_.get().find(mapping) == p_->mappings_.get().end()) return QModelIndex(); - if (mapping->source_index.model() == resetting_model_) - return QModelIndex(); + if (mapping->source_index.model() == resetting_model_) return QModelIndex(); return mapping->source_index; } -QModelIndex MergedProxyModel::mapFromSource(const QModelIndex& source_index) const { - if (!source_index.isValid()) - return QModelIndex(); - if (source_index.model() == resetting_model_) - return QModelIndex(); +QModelIndex MergedProxyModel::mapFromSource(const QModelIndex& source_index) + const { + if (!source_index.isValid()) return QModelIndex(); + if (source_index.model() == resetting_model_) return QModelIndex(); // Add a mapping if we don't have one already - const auto& it = - p_->mappings_.get().find(source_index); + const auto& it = p_->mappings_.get().find(source_index); Mapping* mapping; if (it != p_->mappings_.get().end()) { mapping = *it; @@ -297,7 +288,8 @@ QModelIndex MergedProxyModel::mapFromSource(const QModelIndex& source_index) con return createIndex(source_index.row(), source_index.column(), mapping); } -QModelIndex MergedProxyModel::index(int row, int column, const QModelIndex &parent) const { +QModelIndex MergedProxyModel::index(int row, int column, + const QModelIndex& parent) const { QModelIndex source_index; if (!parent.isValid()) { @@ -315,26 +307,23 @@ QModelIndex MergedProxyModel::index(int row, int column, const QModelIndex &pare return mapFromSource(source_index); } -QModelIndex MergedProxyModel::parent(const QModelIndex &child) const { +QModelIndex MergedProxyModel::parent(const QModelIndex& child) const { QModelIndex source_child = mapToSource(child); if (source_child.model() == sourceModel()) return mapFromSource(source_child.parent()); - if (!IsKnownModel(source_child.model())) - return QModelIndex(); + if (!IsKnownModel(source_child.model())) return QModelIndex(); if (!source_child.parent().isValid()) return mapFromSource(merge_points_.value(GetModel(source_child))); return mapFromSource(source_child.parent()); } -int MergedProxyModel::rowCount(const QModelIndex &parent) const { - if (!parent.isValid()) - return sourceModel()->rowCount(QModelIndex()); +int MergedProxyModel::rowCount(const QModelIndex& parent) const { + if (!parent.isValid()) return sourceModel()->rowCount(QModelIndex()); QModelIndex source_parent = mapToSource(parent); - if (!IsKnownModel(source_parent.model())) - return 0; + if (!IsKnownModel(source_parent.model())) return 0; const QAbstractItemModel* child_model = merge_points_.key(source_parent); if (child_model) { @@ -348,27 +337,22 @@ int MergedProxyModel::rowCount(const QModelIndex &parent) const { return source_parent.model()->rowCount(source_parent); } -int MergedProxyModel::columnCount(const QModelIndex &parent) const { - if (!parent.isValid()) - return sourceModel()->columnCount(QModelIndex()); +int MergedProxyModel::columnCount(const QModelIndex& parent) const { + if (!parent.isValid()) return sourceModel()->columnCount(QModelIndex()); QModelIndex source_parent = mapToSource(parent); - if (!IsKnownModel(source_parent.model())) - return 0; + if (!IsKnownModel(source_parent.model())) return 0; const QAbstractItemModel* child_model = merge_points_.key(source_parent); - if (child_model) - return child_model->columnCount(QModelIndex()); + if (child_model) return child_model->columnCount(QModelIndex()); return source_parent.model()->columnCount(source_parent); } -bool MergedProxyModel::hasChildren(const QModelIndex &parent) const { - if (!parent.isValid()) - return sourceModel()->hasChildren(QModelIndex()); +bool MergedProxyModel::hasChildren(const QModelIndex& parent) const { + if (!parent.isValid()) return sourceModel()->hasChildren(QModelIndex()); QModelIndex source_parent = mapToSource(parent); - if (!IsKnownModel(source_parent.model())) - return false; + if (!IsKnownModel(source_parent.model())) return false; const QAbstractItemModel* child_model = merge_points_.key(source_parent); @@ -380,29 +364,27 @@ bool MergedProxyModel::hasChildren(const QModelIndex &parent) const { QVariant MergedProxyModel::data(const QModelIndex& proxyIndex, int role) const { QModelIndex source_index = mapToSource(proxyIndex); - if (!IsKnownModel(source_index.model())) - return QVariant(); + if (!IsKnownModel(source_index.model())) return QVariant(); return source_index.model()->data(source_index, role); } -QMap MergedProxyModel::itemData(const QModelIndex& proxy_index) const { +QMap MergedProxyModel::itemData(const QModelIndex& proxy_index) + const { QModelIndex source_index = mapToSource(proxy_index); - if (!source_index.isValid()) - return sourceModel()->itemData(QModelIndex()); + if (!source_index.isValid()) return sourceModel()->itemData(QModelIndex()); return source_index.model()->itemData(source_index); } -Qt::ItemFlags MergedProxyModel::flags(const QModelIndex &index) const { +Qt::ItemFlags MergedProxyModel::flags(const QModelIndex& index) const { QModelIndex source_index = mapToSource(index); - if (!source_index.isValid()) - return sourceModel()->flags(QModelIndex()); + if (!source_index.isValid()) return sourceModel()->flags(QModelIndex()); return source_index.model()->flags(source_index); } -bool MergedProxyModel::setData(const QModelIndex &index, const QVariant &value, +bool MergedProxyModel::setData(const QModelIndex& index, const QVariant& value, int role) { QModelIndex source_index = mapToSource(index); @@ -415,16 +397,15 @@ QStringList MergedProxyModel::mimeTypes() const { QStringList ret; ret << sourceModel()->mimeTypes(); - foreach (const QAbstractItemModel* model, merge_points_.keys()) { + foreach(const QAbstractItemModel * model, merge_points_.keys()) { ret << model->mimeTypes(); } return ret; } -QMimeData* MergedProxyModel::mimeData(const QModelIndexList &indexes) const { - if (indexes.isEmpty()) - return 0; +QMimeData* MergedProxyModel::mimeData(const QModelIndexList& indexes) const { + if (indexes.isEmpty()) return 0; // Only ask the first index's model const QAbstractItemModel* model = mapToSource(indexes[0]).model(); @@ -435,17 +416,18 @@ QMimeData* MergedProxyModel::mimeData(const QModelIndexList &indexes) const { // Only ask about the indexes that are actually in that model QModelIndexList indexes_in_model; - foreach (const QModelIndex& proxy_index, indexes) { + foreach(const QModelIndex & proxy_index, indexes) { QModelIndex source_index = mapToSource(proxy_index); - if (source_index.model() != model) - continue; + if (source_index.model() != model) continue; indexes_in_model << source_index; } return model->mimeData(indexes_in_model); } -bool MergedProxyModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) { +bool MergedProxyModel::dropMimeData(const QMimeData* data, + Qt::DropAction action, int row, int column, + const QModelIndex& parent) { if (!parent.isValid()) { return false; } @@ -453,17 +435,16 @@ bool MergedProxyModel::dropMimeData(const QMimeData* data, Qt::DropAction action return sourceModel()->dropMimeData(data, action, row, column, parent); } -QModelIndex MergedProxyModel::FindSourceParent(const QModelIndex& proxy_index) const { - if (!proxy_index.isValid()) - return QModelIndex(); +QModelIndex MergedProxyModel::FindSourceParent(const QModelIndex& proxy_index) + const { + if (!proxy_index.isValid()) return QModelIndex(); QModelIndex source_index = mapToSource(proxy_index); - if (source_index.model() == sourceModel()) - return source_index; + if (source_index.model() == sourceModel()) return source_index; return merge_points_.value(GetModel(source_index)); } -bool MergedProxyModel::canFetchMore(const QModelIndex &parent) const { +bool MergedProxyModel::canFetchMore(const QModelIndex& parent) const { QModelIndex source_index = mapToSource(parent); if (!source_index.isValid()) @@ -480,34 +461,33 @@ void MergedProxyModel::fetchMore(const QModelIndex& parent) { GetModel(source_index)->fetchMore(source_index); } -QAbstractItemModel* MergedProxyModel::GetModel(const QModelIndex& source_index) const { +QAbstractItemModel* MergedProxyModel::GetModel(const QModelIndex& source_index) + const { // This is essentially const_cast(source_index.model()), // but without the const_cast const QAbstractItemModel* const_model = source_index.model(); - if (const_model == sourceModel()) - return sourceModel(); - foreach (QAbstractItemModel* submodel, merge_points_.keys()) { - if (submodel == const_model) - return submodel; + if (const_model == sourceModel()) return sourceModel(); + foreach(QAbstractItemModel * submodel, merge_points_.keys()) { + if (submodel == const_model) return submodel; } return nullptr; } -void MergedProxyModel::DataChanged(const QModelIndex& top_left, const QModelIndex& bottom_right) { +void MergedProxyModel::DataChanged(const QModelIndex& top_left, + const QModelIndex& bottom_right) { emit dataChanged(mapFromSource(top_left), mapFromSource(bottom_right)); } void MergedProxyModel::LayoutAboutToBeChanged() { old_merge_points_.clear(); - foreach (QAbstractItemModel* key, merge_points_.keys()) { + foreach(QAbstractItemModel * key, merge_points_.keys()) { old_merge_points_[key] = merge_points_.value(key); } } void MergedProxyModel::LayoutChanged() { - foreach (QAbstractItemModel* key, merge_points_.keys()) { - if (!old_merge_points_.contains(key)) - continue; + foreach(QAbstractItemModel * key, merge_points_.keys()) { + if (!old_merge_points_.contains(key)) continue; const int old_row = old_merge_points_[key].row(); const int new_row = merge_points_[key].row(); @@ -526,17 +506,19 @@ bool MergedProxyModel::IsKnownModel(const QAbstractItemModel* model) const { return false; } -QModelIndexList MergedProxyModel::mapFromSource(const QModelIndexList& source_indexes) const { +QModelIndexList MergedProxyModel::mapFromSource( + const QModelIndexList& source_indexes) const { QModelIndexList ret; - foreach (const QModelIndex& index, source_indexes) { + foreach(const QModelIndex & index, source_indexes) { ret << mapFromSource(index); } return ret; } -QModelIndexList MergedProxyModel::mapToSource(const QModelIndexList& proxy_indexes) const { +QModelIndexList MergedProxyModel::mapToSource( + const QModelIndexList& proxy_indexes) const { QModelIndexList ret; - foreach (const QModelIndex& index, proxy_indexes) { + foreach(const QModelIndex & index, proxy_indexes) { ret << mapToSource(index); } return ret; diff --git a/src/core/mergedproxymodel.h b/src/core/mergedproxymodel.h index 95d8b249a..b24e49c59 100644 --- a/src/core/mergedproxymodel.h +++ b/src/core/mergedproxymodel.h @@ -34,7 +34,8 @@ class MergedProxyModel : public QAbstractProxyModel { ~MergedProxyModel(); // Make another model appear as a child of the given item in the source model. - void AddSubModel(const QModelIndex& source_parent, QAbstractItemModel* submodel); + void AddSubModel(const QModelIndex& source_parent, + QAbstractItemModel* submodel); void RemoveSubModel(const QModelIndex& source_parent); // Find the item in the source model that is the parent of the model @@ -43,45 +44,50 @@ class MergedProxyModel : public QAbstractProxyModel { QModelIndex FindSourceParent(const QModelIndex& proxy_index) const; // QAbstractItemModel - QModelIndex index(int row, int column, const QModelIndex &parent) const; - QModelIndex parent(const QModelIndex &child) const; - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &proxyIndex, int role = Qt::DisplayRole) const; - bool hasChildren(const QModelIndex &parent) const; - QMap itemData(const QModelIndex &proxyIndex) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - bool setData(const QModelIndex &index, const QVariant &value, int role); + QModelIndex index(int row, int column, const QModelIndex& parent) const; + QModelIndex parent(const QModelIndex& child) const; + int rowCount(const QModelIndex& parent) const; + int columnCount(const QModelIndex& parent) const; + QVariant data(const QModelIndex& proxyIndex, + int role = Qt::DisplayRole) const; + bool hasChildren(const QModelIndex& parent) const; + QMap itemData(const QModelIndex& proxyIndex) const; + Qt::ItemFlags flags(const QModelIndex& index) const; + bool setData(const QModelIndex& index, const QVariant& value, int role); QStringList mimeTypes() const; - QMimeData* mimeData(const QModelIndexList &indexes) const; - bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); - bool canFetchMore(const QModelIndex &parent) const; + QMimeData* mimeData(const QModelIndexList& indexes) const; + bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, + int column, const QModelIndex& parent); + bool canFetchMore(const QModelIndex& parent) const; void fetchMore(const QModelIndex& parent); // QAbstractProxyModel // Note that these implementations of map{To,From}Source will not always // give you an index in sourceModel(), you might get an index in one of the // child models instead. - QModelIndex mapFromSource(const QModelIndex &sourceIndex) const; - QModelIndex mapToSource(const QModelIndex &proxyIndex) const; - void setSourceModel(QAbstractItemModel *sourceModel); + QModelIndex mapFromSource(const QModelIndex& sourceIndex) const; + QModelIndex mapToSource(const QModelIndex& proxyIndex) const; + void setSourceModel(QAbstractItemModel* sourceModel); // Convenience functions that call map{To,From}Source multiple times. QModelIndexList mapFromSource(const QModelIndexList& source_indexes) const; QModelIndexList mapToSource(const QModelIndexList& proxy_indexes) const; - signals: +signals: void SubModelReset(const QModelIndex& root, QAbstractItemModel* model); private slots: void SourceModelReset(); void SubModelReset(); - void RowsAboutToBeInserted(const QModelIndex& source_parent, int start, int end); + void RowsAboutToBeInserted(const QModelIndex& source_parent, int start, + int end); void RowsInserted(const QModelIndex& source_parent, int start, int end); - void RowsAboutToBeRemoved(const QModelIndex& source_parent, int start, int end); + void RowsAboutToBeRemoved(const QModelIndex& source_parent, int start, + int end); void RowsRemoved(const QModelIndex& source_parent, int start, int end); - void DataChanged(const QModelIndex& top_left, const QModelIndex& bottom_right); + void DataChanged(const QModelIndex& top_left, + const QModelIndex& bottom_right); void LayoutAboutToBeChanged(); void LayoutChanged(); @@ -93,7 +99,6 @@ class MergedProxyModel : public QAbstractProxyModel { void DeleteAllMappings(); bool IsKnownModel(const QAbstractItemModel* model) const; - QMap merge_points_; QAbstractItemModel* resetting_model_; @@ -102,4 +107,4 @@ class MergedProxyModel : public QAbstractProxyModel { std::unique_ptr p_; }; -#endif // MERGEDPROXYMODEL_H +#endif // MERGEDPROXYMODEL_H diff --git a/src/core/metatypes.cpp b/src/core/metatypes.cpp index ee0151cc7..5d907e46c 100644 --- a/src/core/metatypes.cpp +++ b/src/core/metatypes.cpp @@ -32,7 +32,8 @@ void RegisterMetaTypes() { qRegisterMetaType("const char*"); qRegisterMetaType("CoverSearchResult"); qRegisterMetaType("CoverSearchResults"); - qRegisterMetaType("DigitallyImportedClient::Channel"); + qRegisterMetaType( + "DigitallyImportedClient::Channel"); qRegisterMetaType("Directory"); qRegisterMetaType("DirectoryList"); qRegisterMetaType("Engine::SimpleMetaBundle"); @@ -49,8 +50,10 @@ void RegisterMetaTypes() { qRegisterMetaType("PodcastList"); qRegisterMetaType >("QList"); qRegisterMetaType >("QList"); - qRegisterMetaType("PlaylistSequence::RepeatMode"); - qRegisterMetaType("PlaylistSequence::ShuffleMode"); + qRegisterMetaType( + "PlaylistSequence::RepeatMode"); + qRegisterMetaType( + "PlaylistSequence::ShuffleMode"); qRegisterMetaType >("QList"); qRegisterMetaType >("QList"); qRegisterMetaType >("QList"); @@ -60,14 +63,17 @@ void RegisterMetaTypes() { qRegisterMetaType("QNetworkReply**"); qRegisterMetaType("SearchProvider::ResultList"); qRegisterMetaType("SearchProvider::Result"); - qRegisterMetaType("smart_playlists::GeneratorPtr"); + qRegisterMetaType( + "smart_playlists::GeneratorPtr"); qRegisterMetaType("SomaFMService::Stream"); qRegisterMetaType("SongList"); qRegisterMetaType("Song"); - qRegisterMetaTypeStreamOperators("DigitallyImportedClient::Channel"); + qRegisterMetaTypeStreamOperators( + "DigitallyImportedClient::Channel"); qRegisterMetaTypeStreamOperators("Equalizer::Params"); qRegisterMetaTypeStreamOperators >("ColumnAlignmentMap"); - qRegisterMetaTypeStreamOperators("SomaFMService::Stream"); + qRegisterMetaTypeStreamOperators( + "SomaFMService::Stream"); qRegisterMetaType("SubdirectoryList"); qRegisterMetaType("Subdirectory"); qRegisterMetaType >("QList"); diff --git a/src/core/mimedata.h b/src/core/mimedata.h index 53c5ed835..e8136aed4 100644 --- a/src/core/mimedata.h +++ b/src/core/mimedata.h @@ -23,16 +23,16 @@ class MimeData : public QMimeData { Q_OBJECT -public: - MimeData(bool clear = false, bool play_now = false, - bool enqueue = false, bool open_in_new_playlist = false) - : override_user_settings_(false), - clear_first_(clear), - play_now_(play_now), - enqueue_now_(enqueue), - open_in_new_playlist_(open_in_new_playlist), - name_for_new_playlist_(QString()), - from_doubleclick_(false) {} + public: + MimeData(bool clear = false, bool play_now = false, bool enqueue = false, + bool open_in_new_playlist = false) + : override_user_settings_(false), + clear_first_(clear), + play_now_(play_now), + enqueue_now_(enqueue), + open_in_new_playlist_(open_in_new_playlist), + name_for_new_playlist_(QString()), + from_doubleclick_(false) {} // If this is set then MainWindow will not touch any of the other flags. bool override_user_settings_; @@ -43,7 +43,8 @@ public: // If this is set then the first item that is inserted will start playing // immediately. Note: this is always overridden with the user's preference - // if the MimeData goes via MainWindow, unless you set override_user_settings_. + // if the MimeData goes via MainWindow, unless you set + // override_user_settings_. bool play_now_; // If this is set then the items are added to the queue after being inserted. @@ -60,12 +61,15 @@ public: // the defaults set by the user. bool from_doubleclick_; - // Returns a pretty name for a playlist containing songs described by this MimeData - // object. By pretty name we mean the value of 'name_for_new_playlist_' or generic + // Returns a pretty name for a playlist containing songs described by this + // MimeData + // object. By pretty name we mean the value of 'name_for_new_playlist_' or + // generic // "Playlist" string if the 'name_for_new_playlist_' attribute is empty. QString get_name_for_new_playlist() { - return name_for_new_playlist_.isEmpty() ? tr("Playlist") : name_for_new_playlist_; + return name_for_new_playlist_.isEmpty() ? tr("Playlist") + : name_for_new_playlist_; } }; -#endif // MIMEDATA_H +#endif // MIMEDATA_H diff --git a/src/core/modelfuturewatcher.h b/src/core/modelfuturewatcher.h index 388a6dcca..ea97c9889 100644 --- a/src/core/modelfuturewatcher.h +++ b/src/core/modelfuturewatcher.h @@ -8,18 +8,14 @@ template class ModelFutureWatcher : public QFutureWatcher { public: ModelFutureWatcher(const QModelIndex& index, QObject* parent = 0) - : QFutureWatcher(parent), - index_(index) { - } + : QFutureWatcher(parent), index_(index) {} - ~ModelFutureWatcher() { - } + ~ModelFutureWatcher() {} const QPersistentModelIndex& index() const { return index_; } private: QPersistentModelIndex index_; - }; #endif diff --git a/src/core/mpris.cpp b/src/core/mpris.cpp index da297cec7..191dd9198 100644 --- a/src/core/mpris.cpp +++ b/src/core/mpris.cpp @@ -22,11 +22,10 @@ namespace mpris { Mpris::Mpris(Application* app, QObject* parent) - : QObject(parent), - mpris1_(new mpris::Mpris1(app, this)), - mpris2_(new mpris::Mpris2(app, mpris1_, this)) -{ + : QObject(parent), + mpris1_(new mpris::Mpris1(app, this)), + mpris2_(new mpris::Mpris2(app, mpris1_, this)) { connect(mpris2_, SIGNAL(RaiseMainWindow()), SIGNAL(RaiseMainWindow())); } -} // namespace mpris +} // namespace mpris diff --git a/src/core/mpris.h b/src/core/mpris.h index f858168b1..b613b5aa3 100644 --- a/src/core/mpris.h +++ b/src/core/mpris.h @@ -30,17 +30,17 @@ class Mpris2; class Mpris : public QObject { Q_OBJECT -public: + public: Mpris(Application* app, QObject* parent = 0); signals: void RaiseMainWindow(); -private: + private: Mpris1* mpris1_; Mpris2* mpris2_; }; -} // namespace mpris +} // namespace mpris -#endif // MPRIS_H +#endif // MPRIS_H diff --git a/src/core/mpris1.cpp b/src/core/mpris1.cpp index 56f330320..cef1ff7a5 100644 --- a/src/core/mpris1.cpp +++ b/src/core/mpris1.cpp @@ -39,12 +39,11 @@ const char* Mpris1::kDefaultDbusServiceName = "org.mpris.clementine"; Mpris1::Mpris1(Application* app, QObject* parent, const QString& dbus_service_name) - : QObject(parent), - dbus_service_name_(dbus_service_name), - root_(nullptr), - player_(nullptr), - tracklist_(nullptr) -{ + : QObject(parent), + dbus_service_name_(dbus_service_name), + root_(nullptr), + player_(nullptr), + tracklist_(nullptr) { qDBusRegisterMetaType(); qDBusRegisterMetaType(); @@ -53,7 +52,8 @@ Mpris1::Mpris1(Application* app, QObject* parent, } if (!QDBusConnection::sessionBus().registerService(dbus_service_name_)) { - qLog(Warning) << "Failed to register" << dbus_service_name_ << "on the session bus"; + qLog(Warning) << "Failed to register" << dbus_service_name_ + << "on the session bus"; return; } @@ -61,8 +61,10 @@ Mpris1::Mpris1(Application* app, QObject* parent, player_ = new Mpris1Player(app, this); tracklist_ = new Mpris1TrackList(app, this); - connect(app->current_art_loader(), SIGNAL(ArtLoaded(const Song&, const QString&, const QImage&)), - player_, SLOT(CurrentSongChanged(const Song&, const QString&, const QImage&))); + connect(app->current_art_loader(), + SIGNAL(ArtLoaded(const Song&, const QString&, const QImage&)), + player_, + SLOT(CurrentSongChanged(const Song&, const QString&, const QImage&))); } Mpris1::~Mpris1() { @@ -70,27 +72,29 @@ Mpris1::~Mpris1() { } Mpris1Root::Mpris1Root(Application* app, QObject* parent) - : QObject(parent), - app_(app) { + : QObject(parent), app_(app) { new MprisRoot(this); QDBusConnection::sessionBus().registerObject("/", this); } Mpris1Player::Mpris1Player(Application* app, QObject* parent) - : QObject(parent), - app_(app) { + : QObject(parent), app_(app) { new MprisPlayer(this); QDBusConnection::sessionBus().registerObject("/Player", this); - connect(app_->player()->engine(), SIGNAL(StateChanged(Engine::State)), SLOT(EngineStateChanged(Engine::State))); - connect(app_->playlist_manager(), SIGNAL(PlaylistManagerInitialized()), SLOT(PlaylistManagerInitialized())); + connect(app_->player()->engine(), SIGNAL(StateChanged(Engine::State)), + SLOT(EngineStateChanged(Engine::State))); + connect(app_->playlist_manager(), SIGNAL(PlaylistManagerInitialized()), + SLOT(PlaylistManagerInitialized())); } // when PlaylistManager gets it ready, we connect PlaylistSequence with this void Mpris1Player::PlaylistManagerInitialized() { - connect(app_->playlist_manager()->sequence(), SIGNAL(ShuffleModeChanged(PlaylistSequence::ShuffleMode)), + connect(app_->playlist_manager()->sequence(), + SIGNAL(ShuffleModeChanged(PlaylistSequence::ShuffleMode)), SLOT(ShuffleModeChanged())); - connect(app_->playlist_manager()->sequence(), SIGNAL(RepeatModeChanged(PlaylistSequence::RepeatMode)), + connect(app_->playlist_manager()->sequence(), + SIGNAL(RepeatModeChanged(PlaylistSequence::RepeatMode)), SLOT(RepeatModeChanged())); } @@ -99,22 +103,23 @@ Mpris1TrackList::Mpris1TrackList(Application* app, QObject* parent) new MprisTrackList(this); QDBusConnection::sessionBus().registerObject("/TrackList", this); - connect(app_->playlist_manager(), SIGNAL(PlaylistChanged(Playlist*)), SLOT(PlaylistChanged(Playlist*))); + connect(app_->playlist_manager(), SIGNAL(PlaylistChanged(Playlist*)), + SLOT(PlaylistChanged(Playlist*))); } void Mpris1TrackList::PlaylistChanged(Playlist* playlist) { emit TrackListChange(playlist->rowCount()); } -// we use the state from event and don't try to obtain it from Player +// we use the state from event and don't try to obtain it from Player // later because only the event's version is really the current one void Mpris1Player::EngineStateChanged(Engine::State state) { emit StatusChange(GetStatus(state)); emit CapsChange(GetCaps(state)); } -void Mpris1Player::CurrentSongChanged( - const Song& song, const QString& art_uri, const QImage&) { +void Mpris1Player::CurrentSongChanged(const Song& song, const QString& art_uri, + const QImage&) { last_metadata_ = Mpris1::GetMetadata(song); if (!art_uri.isEmpty()) { @@ -126,11 +131,9 @@ void Mpris1Player::CurrentSongChanged( emit CapsChange(GetCaps()); } - QString Mpris1Root::Identity() { - return QString("%1 %2").arg( - QCoreApplication::applicationName(), - QCoreApplication::applicationVersion()); + return QString("%1 %2").arg(QCoreApplication::applicationName(), + QCoreApplication::applicationVersion()); } Version Mpris1Root::MprisVersion() { @@ -140,42 +143,26 @@ Version Mpris1Root::MprisVersion() { return version; } -void Mpris1Root::Quit() { - qApp->quit(); -} +void Mpris1Root::Quit() { qApp->quit(); } -void Mpris1Player::Pause() { - app_->player()->PlayPause(); -} +void Mpris1Player::Pause() { app_->player()->PlayPause(); } -void Mpris1Player::Stop() { - app_->player()->Stop(); -} +void Mpris1Player::Stop() { app_->player()->Stop(); } -void Mpris1Player::Prev() { - app_->player()->Previous(); -} +void Mpris1Player::Prev() { app_->player()->Previous(); } -void Mpris1Player::Play() { - app_->player()->Play(); -} +void Mpris1Player::Play() { app_->player()->Play(); } -void Mpris1Player::Next() { - app_->player()->Next(); -} +void Mpris1Player::Next() { app_->player()->Next(); } void Mpris1Player::Repeat(bool repeat) { app_->playlist_manager()->sequence()->SetRepeatMode( repeat ? PlaylistSequence::Repeat_Track : PlaylistSequence::Repeat_Off); } -void Mpris1Player::ShuffleModeChanged() { - emit StatusChange(GetStatus()); -} +void Mpris1Player::ShuffleModeChanged() { emit StatusChange(GetStatus()); } -void Mpris1Player::RepeatModeChanged() { - emit StatusChange(GetStatus()); -} +void Mpris1Player::RepeatModeChanged() { emit StatusChange(GetStatus()); } DBusStatus Mpris1Player::GetStatus() const { return GetStatus(app_->player()->GetState()); @@ -199,25 +186,27 @@ DBusStatus Mpris1Player::GetStatus(Engine::State state) const { if (app_->playlist_manager()->sequence()) { PlaylistManagerInterface* playlists_ = app_->playlist_manager(); - PlaylistSequence::RepeatMode repeat_mode = playlists_->sequence()->repeat_mode(); - - status.random = playlists_->sequence()->shuffle_mode() == PlaylistSequence::Shuffle_Off ? 0 : 1; + PlaylistSequence::RepeatMode repeat_mode = + playlists_->sequence()->repeat_mode(); + + status.random = + playlists_->sequence()->shuffle_mode() == PlaylistSequence::Shuffle_Off + ? 0 + : 1; status.repeat = repeat_mode == PlaylistSequence::Repeat_Track ? 1 : 0; - status.repeat_playlist = (repeat_mode == PlaylistSequence::Repeat_Album || - repeat_mode == PlaylistSequence::Repeat_Playlist || - repeat_mode == PlaylistSequence::Repeat_Track) ? 1 : 0; + status.repeat_playlist = + (repeat_mode == PlaylistSequence::Repeat_Album || + repeat_mode == PlaylistSequence::Repeat_Playlist || + repeat_mode == PlaylistSequence::Repeat_Track) + ? 1 + : 0; } return status; - } -void Mpris1Player::VolumeSet(int volume) { - app_->player()->SetVolume(volume); -} +void Mpris1Player::VolumeSet(int volume) { app_->player()->SetVolume(volume); } -int Mpris1Player::VolumeGet() const { - return app_->player()->GetVolume(); -} +int Mpris1Player::VolumeGet() const { return app_->player()->GetVolume(); } void Mpris1Player::PositionSet(int pos_msec) { app_->player()->SeekTo(pos_msec / kMsecPerSec); @@ -227,9 +216,7 @@ int Mpris1Player::PositionGet() const { return app_->player()->engine()->position_nanosec() / kNsecPerMsec; } -QVariantMap Mpris1Player::GetMetadata() const { - return last_metadata_; -} +QVariantMap Mpris1Player::GetMetadata() const { return last_metadata_; } int Mpris1Player::GetCaps() const { return GetCaps(app_->player()->GetState()); @@ -241,12 +228,15 @@ int Mpris1Player::GetCaps(Engine::State state) const { PlaylistManagerInterface* playlists = app_->playlist_manager(); if (playlists->active()) { - // play is disabled when playlist is empty or when last.fm stream is already playing - if (playlists->active() && playlists->active()->rowCount() != 0 - && !(state == Engine::Playing && (app_->player()->GetCurrentItem()->options() & PlaylistItem::LastFMControls))) { + // play is disabled when playlist is empty or when last.fm stream is already + // playing + if (playlists->active() && playlists->active()->rowCount() != 0 && + !(state == Engine::Playing && + (app_->player()->GetCurrentItem()->options() & + PlaylistItem::LastFMControls))) { caps |= CAN_PLAY; } - + if (playlists->active()->next_row() != -1) { caps |= CAN_GO_NEXT; } @@ -257,7 +247,8 @@ int Mpris1Player::GetCaps(Engine::State state) const { if (current_item) { caps |= CAN_PROVIDE_METADATA; - if (state == Engine::Playing && !(current_item->options() & PlaylistItem::PauseDisabled)) { + if (state == Engine::Playing && + !(current_item->options() & PlaylistItem::PauseDisabled)) { caps |= CAN_PAUSE; } if (state != Engine::Empty && !current_item->Metadata().is_stream()) { @@ -268,25 +259,17 @@ int Mpris1Player::GetCaps(Engine::State state) const { return caps; } -void Mpris1Player::VolumeUp(int change) { - VolumeSet(VolumeGet() + change); -} +void Mpris1Player::VolumeUp(int change) { VolumeSet(VolumeGet() + change); } -void Mpris1Player::VolumeDown(int change) { - VolumeSet(VolumeGet() - change); -} +void Mpris1Player::VolumeDown(int change) { VolumeSet(VolumeGet() - change); } -void Mpris1Player::Mute() { - app_->player()->Mute(); -} +void Mpris1Player::Mute() { app_->player()->Mute(); } -void Mpris1Player::ShowOSD() { - app_->player()->ShowOSD(); -} +void Mpris1Player::ShowOSD() { app_->player()->ShowOSD(); } int Mpris1TrackList::AddTrack(const QString& track, bool play) { - app_->playlist_manager()->active()->InsertUrls( - QList() << QUrl(track), -1, play); + app_->playlist_manager()->active()->InsertUrls(QList() << QUrl(track), + -1, play); return 0; } @@ -304,15 +287,15 @@ int Mpris1TrackList::GetLength() const { QVariantMap Mpris1TrackList::GetMetadata(int pos) const { PlaylistItemPtr item = app_->player()->GetItemAt(pos); - if (!item) - return QVariantMap(); + if (!item) return QVariantMap(); return Mpris1::GetMetadata(item->Metadata()); } void Mpris1TrackList::SetLoop(bool enable) { app_->playlist_manager()->active()->sequence()->SetRepeatMode( - enable ? PlaylistSequence::Repeat_Playlist : PlaylistSequence::Repeat_Off); + enable ? PlaylistSequence::Repeat_Playlist + : PlaylistSequence::Repeat_Off); } void Mpris1TrackList::SetRandom(bool enable) { @@ -351,24 +334,23 @@ QVariantMap Mpris1::GetMetadata(const Song& song) { return ret; } -} // namespace mpris +} // namespace mpris - -QDBusArgument& operator<< (QDBusArgument& arg, const Version& version) { +QDBusArgument& operator<<(QDBusArgument& arg, const Version& version) { arg.beginStructure(); arg << version.major << version.minor; arg.endStructure(); return arg; } -const QDBusArgument& operator>> (const QDBusArgument& arg, Version& version) { +const QDBusArgument& operator>>(const QDBusArgument& arg, Version& version) { arg.beginStructure(); arg >> version.major >> version.minor; arg.endStructure(); return arg; } -QDBusArgument& operator<< (QDBusArgument& arg, const DBusStatus& status) { +QDBusArgument& operator<<(QDBusArgument& arg, const DBusStatus& status) { arg.beginStructure(); arg << status.play; arg << status.random; @@ -378,7 +360,7 @@ QDBusArgument& operator<< (QDBusArgument& arg, const DBusStatus& status) { return arg; } -const QDBusArgument& operator>> (const QDBusArgument& arg, DBusStatus& status) { +const QDBusArgument& operator>>(const QDBusArgument& arg, DBusStatus& status) { arg.beginStructure(); arg >> status.play; arg >> status.random; diff --git a/src/core/mpris1.h b/src/core/mpris1.h index 9e344b69e..62cf2bdf8 100644 --- a/src/core/mpris1.h +++ b/src/core/mpris1.h @@ -27,18 +27,15 @@ class Application; class Playlist; -struct DBusStatus { // From Amarok. +struct DBusStatus { // From Amarok. DBusStatus() - : play(Mpris_Stopped), - random(0), - repeat(0), - repeat_playlist(0) - {} - - int play; // Playing = 0, Paused = 1, Stopped = 2 - int random; // Linearly = 0, Randomly = 1 - int repeat; // Go_To_Next = 0, Repeat_Current = 1 - int repeat_playlist; // Stop_When_Finished = 0, Never_Give_Up_Playing = 1, Never_Let_You_Down = 42 + : play(Mpris_Stopped), random(0), repeat(0), repeat_playlist(0) {} + + int play; // Playing = 0, Paused = 1, Stopped = 2 + int random; // Linearly = 0, Randomly = 1 + int repeat; // Go_To_Next = 0, Repeat_Current = 1 + int repeat_playlist; // Stop_When_Finished = 0, Never_Give_Up_Playing = 1, + // Never_Let_You_Down = 42 enum MprisPlayState { Mpris_Playing = 0, @@ -48,9 +45,8 @@ struct DBusStatus { // From Amarok. }; Q_DECLARE_METATYPE(DBusStatus); -QDBusArgument& operator <<(QDBusArgument& arg, const DBusStatus& status); -const QDBusArgument& operator >>(const QDBusArgument& arg, DBusStatus& status); - +QDBusArgument& operator<<(QDBusArgument& arg, const DBusStatus& status); +const QDBusArgument& operator>>(const QDBusArgument& arg, DBusStatus& status); struct Version { quint16 minor; @@ -58,31 +54,30 @@ struct Version { }; Q_DECLARE_METATYPE(Version); -QDBusArgument& operator <<(QDBusArgument& arg, const Version& version); -const QDBusArgument& operator >>(const QDBusArgument& arg, Version& version); +QDBusArgument& operator<<(QDBusArgument& arg, const Version& version); +const QDBusArgument& operator>>(const QDBusArgument& arg, Version& version); namespace mpris { enum DBusCaps { - NONE = 0, - CAN_GO_NEXT = 1 << 0, - CAN_GO_PREV = 1 << 1, - CAN_PAUSE = 1 << 2, - CAN_PLAY = 1 << 3, - CAN_SEEK = 1 << 4, + NONE = 0, + CAN_GO_NEXT = 1 << 0, + CAN_GO_PREV = 1 << 1, + CAN_PAUSE = 1 << 2, + CAN_PLAY = 1 << 3, + CAN_SEEK = 1 << 4, CAN_PROVIDE_METADATA = 1 << 5, - CAN_HAS_TRACKLIST = 1 << 6, + CAN_HAS_TRACKLIST = 1 << 6, }; class Mpris1Root; class Mpris1Player; class Mpris1TrackList; - class Mpris1 : public QObject { Q_OBJECT -public: + public: Mpris1(Application* app, QObject* parent = 0, const QString& dbus_service_name = QString()); ~Mpris1(); @@ -93,7 +88,7 @@ public: Mpris1Player* player() const { return player_; } Mpris1TrackList* tracklist() const { return tracklist_; } -private: + private: static const char* kDefaultDbusServiceName; QString dbus_service_name_; @@ -103,26 +98,24 @@ private: Mpris1TrackList* tracklist_; }; - class Mpris1Root : public QObject { Q_OBJECT -public: + public: Mpris1Root(Application* app, QObject* parent = 0); QString Identity(); void Quit(); Version MprisVersion(); -private: + private: Application* app_; }; - class Mpris1Player : public QObject { Q_OBJECT -public: + public: Mpris1Player(Application* app, QObject* parent = 0); void Pause(); @@ -132,7 +125,8 @@ public: void Next(); void Repeat(bool); - // those methods will use engine's state obtained with player->GetState() method + // those methods will use engine's state obtained with player->GetState() + // method DBusStatus GetStatus() const; int GetCaps() const; // those methods will use engine's state provided as an argument @@ -151,33 +145,32 @@ public: void Mute(); void ShowOSD(); -public slots: - void CurrentSongChanged( - const Song& song, const QString& art_uri, const QImage&); + public slots: + void CurrentSongChanged(const Song& song, const QString& art_uri, + const QImage&); signals: void CapsChange(int); void TrackChange(const QVariantMap&); void StatusChange(DBusStatus); -private slots: + private slots: void PlaylistManagerInitialized(); void EngineStateChanged(Engine::State state); void ShuffleModeChanged(); void RepeatModeChanged(); -private: + private: Application* app_; QVariantMap last_metadata_; }; - class Mpris1TrackList : public QObject { Q_OBJECT -public: + public: Mpris1TrackList(Application* app, QObject* parent = 0); int AddTrack(const QString&, bool); @@ -194,13 +187,13 @@ public: signals: void TrackListChange(int i); -private slots: + private slots: void PlaylistChanged(Playlist* playlist); -private: + private: Application* app_; }; -} // namespace mpris +} // namespace mpris -#endif // MPRIS1_H +#endif // MPRIS1_H diff --git a/src/core/mpris2.cpp b/src/core/mpris2.cpp index d433a6161..3b2c46c11 100644 --- a/src/core/mpris2.cpp +++ b/src/core/mpris2.cpp @@ -41,22 +41,22 @@ #include #include -QDBusArgument& operator<< (QDBusArgument& arg, const MprisPlaylist& playlist) { +QDBusArgument& operator<<(QDBusArgument& arg, const MprisPlaylist& playlist) { arg.beginStructure(); arg << playlist.id << playlist.name << playlist.icon; arg.endStructure(); return arg; } -const QDBusArgument& operator>> ( - const QDBusArgument& arg, MprisPlaylist& playlist) { +const QDBusArgument& operator>>(const QDBusArgument& arg, + MprisPlaylist& playlist) { arg.beginStructure(); arg >> playlist.id >> playlist.name >> playlist.icon; arg.endStructure(); return arg; } -QDBusArgument& operator<< (QDBusArgument& arg, const MaybePlaylist& playlist) { +QDBusArgument& operator<<(QDBusArgument& arg, const MaybePlaylist& playlist) { arg.beginStructure(); arg << playlist.valid; arg << playlist.playlist; @@ -64,8 +64,8 @@ QDBusArgument& operator<< (QDBusArgument& arg, const MaybePlaylist& playlist) { return arg; } -const QDBusArgument& operator>> ( - const QDBusArgument& arg, MaybePlaylist& playlist) { +const QDBusArgument& operator>>(const QDBusArgument& arg, + MaybePlaylist& playlist) { arg.beginStructure(); arg >> playlist.valid >> playlist.playlist; arg.endStructure(); @@ -79,121 +79,115 @@ const char* Mpris2::kServiceName = "org.mpris.MediaPlayer2.clementine"; const char* Mpris2::kFreedesktopPath = "org.freedesktop.DBus.Properties"; Mpris2::Mpris2(Application* app, Mpris1* mpris1, QObject* parent) - : QObject(parent), - app_(app), - mpris1_(mpris1) -{ + : QObject(parent), app_(app), mpris1_(mpris1) { new Mpris2Root(this); new Mpris2TrackList(this); new Mpris2Player(this); new Mpris2Playlists(this); if (!QDBusConnection::sessionBus().registerService(kServiceName)) { - qLog(Warning) << "Failed to register" << QString(kServiceName) << "on the session bus"; + qLog(Warning) << "Failed to register" << QString(kServiceName) + << "on the session bus"; return; } QDBusConnection::sessionBus().registerObject(kMprisObjectPath, this); - connect(app_->current_art_loader(), SIGNAL(ArtLoaded(Song,QString,QImage)), SLOT(ArtLoaded(Song,QString))); + connect(app_->current_art_loader(), SIGNAL(ArtLoaded(Song, QString, QImage)), + SLOT(ArtLoaded(Song, QString))); - connect(app_->player()->engine(), SIGNAL(StateChanged(Engine::State)), SLOT(EngineStateChanged(Engine::State))); + connect(app_->player()->engine(), SIGNAL(StateChanged(Engine::State)), + SLOT(EngineStateChanged(Engine::State))); connect(app_->player(), SIGNAL(VolumeChanged(int)), SLOT(VolumeChanged())); connect(app_->player(), SIGNAL(Seeked(qlonglong)), SIGNAL(Seeked(qlonglong))); - connect(app_->playlist_manager(), SIGNAL(PlaylistManagerInitialized()), SLOT(PlaylistManagerInitialized())); - connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), SLOT(CurrentSongChanged(Song))); - connect(app_->playlist_manager(), SIGNAL(PlaylistChanged(Playlist*)), SLOT(PlaylistChanged(Playlist*))); - connect(app_->playlist_manager(), SIGNAL(CurrentChanged(Playlist*)), SLOT(PlaylistCollectionChanged(Playlist*))); + connect(app_->playlist_manager(), SIGNAL(PlaylistManagerInitialized()), + SLOT(PlaylistManagerInitialized())); + connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), + SLOT(CurrentSongChanged(Song))); + connect(app_->playlist_manager(), SIGNAL(PlaylistChanged(Playlist*)), + SLOT(PlaylistChanged(Playlist*))); + connect(app_->playlist_manager(), SIGNAL(CurrentChanged(Playlist*)), + SLOT(PlaylistCollectionChanged(Playlist*))); } // when PlaylistManager gets it ready, we connect PlaylistSequence with this void Mpris2::PlaylistManagerInitialized() { - connect(app_->playlist_manager()->sequence(), SIGNAL(ShuffleModeChanged(PlaylistSequence::ShuffleMode)), + connect(app_->playlist_manager()->sequence(), + SIGNAL(ShuffleModeChanged(PlaylistSequence::ShuffleMode)), SLOT(ShuffleModeChanged())); - connect(app_->playlist_manager()->sequence(), SIGNAL(RepeatModeChanged(PlaylistSequence::RepeatMode)), + connect(app_->playlist_manager()->sequence(), + SIGNAL(RepeatModeChanged(PlaylistSequence::RepeatMode)), SLOT(RepeatModeChanged())); } void Mpris2::EngineStateChanged(Engine::State newState) { - if(newState != Engine::Playing && newState != Engine::Paused) { - last_metadata_= QVariantMap(); + if (newState != Engine::Playing && newState != Engine::Paused) { + last_metadata_ = QVariantMap(); EmitNotification("Metadata"); } EmitNotification("PlaybackStatus", PlaybackStatus(newState)); } -void Mpris2::VolumeChanged() { - EmitNotification("Volume"); -} +void Mpris2::VolumeChanged() { EmitNotification("Volume"); } -void Mpris2::ShuffleModeChanged() { - EmitNotification("Shuffle"); -} +void Mpris2::ShuffleModeChanged() { EmitNotification("Shuffle"); } -void Mpris2::RepeatModeChanged() { - EmitNotification("LoopStatus"); -} +void Mpris2::RepeatModeChanged() { EmitNotification("LoopStatus"); } void Mpris2::EmitNotification(const QString& name, const QVariant& val) { EmitNotification(name, val, "org.mpris.MediaPlayer2.Player"); } -void Mpris2::EmitNotification(const QString& name, const QVariant& val, const QString& mprisEntity) { +void Mpris2::EmitNotification(const QString& name, const QVariant& val, + const QString& mprisEntity) { QDBusMessage msg = QDBusMessage::createSignal( - kMprisObjectPath, kFreedesktopPath, "PropertiesChanged"); + kMprisObjectPath, kFreedesktopPath, "PropertiesChanged"); QVariantMap map; map.insert(name, val); - QVariantList args = QVariantList() - << mprisEntity - << map - << QStringList(); + QVariantList args = QVariantList() << mprisEntity << map << QStringList(); msg.setArguments(args); QDBusConnection::sessionBus().send(msg); } void Mpris2::EmitNotification(const QString& name) { QVariant value; - if (name == "PlaybackStatus") value = PlaybackStatus(); - else if (name == "LoopStatus") value = LoopStatus(); - else if (name == "Shuffle") value = Shuffle(); - else if (name == "Metadata") value = Metadata(); - else if (name == "Volume") value = Volume(); - else if (name == "Position") value = Position(); + if (name == "PlaybackStatus") + value = PlaybackStatus(); + else if (name == "LoopStatus") + value = LoopStatus(); + else if (name == "Shuffle") + value = Shuffle(); + else if (name == "Metadata") + value = Metadata(); + else if (name == "Volume") + value = Volume(); + else if (name == "Position") + value = Position(); - if (value.isValid()) - EmitNotification(name, value); + if (value.isValid()) EmitNotification(name, value); } //------------------Root Interface--------------------------// -bool Mpris2::CanQuit() const { - return true; -} +bool Mpris2::CanQuit() const { return true; } -bool Mpris2::CanRaise() const { - return true; -} +bool Mpris2::CanRaise() const { return true; } -bool Mpris2::HasTrackList() const { - return true; -} +bool Mpris2::HasTrackList() const { return true; } -QString Mpris2::Identity() const { - return QCoreApplication::applicationName(); -} +QString Mpris2::Identity() const { return QCoreApplication::applicationName(); } QString Mpris2::DesktopEntryAbsolutePath() const { QStringList xdg_data_dirs = QString(getenv("XDG_DATA_DIRS")).split(":"); xdg_data_dirs.append("/usr/local/share/"); xdg_data_dirs.append("/usr/share/"); - foreach (const QString& directory, xdg_data_dirs) { - QString path = QString("%1/applications/%2.desktop"). - arg(directory, QApplication::applicationName().toLower()); - if (QFile::exists(path)) - return path; + foreach(const QString & directory, xdg_data_dirs) { + QString path = QString("%1/applications/%2.desktop").arg( + directory, QApplication::applicationName().toLower()); + if (QFile::exists(path)) return path; } return QString(); } @@ -203,52 +197,46 @@ QString Mpris2::DesktopEntry() const { } QStringList Mpris2::SupportedUriSchemes() const { - static QStringList res = QStringList() - << "file" - << "http" - << "cdda" - << "smb" - << "sftp"; + static QStringList res = QStringList() << "file" + << "http" + << "cdda" + << "smb" + << "sftp"; return res; } QStringList Mpris2::SupportedMimeTypes() const { - static QStringList res = QStringList() - << "application/ogg" - << "application/x-ogg" - << "application/x-ogm-audio" - << "audio/aac" - << "audio/mp4" - << "audio/mpeg" - << "audio/mpegurl" - << "audio/ogg" - << "audio/vnd.rn-realaudio" - << "audio/vorbis" - << "audio/x-flac" - << "audio/x-mp3" - << "audio/x-mpeg" - << "audio/x-mpegurl" - << "audio/x-ms-wma" - << "audio/x-musepack" - << "audio/x-oggflac" - << "audio/x-pn-realaudio" - << "audio/x-scpls" - << "audio/x-speex" - << "audio/x-vorbis" - << "audio/x-vorbis+ogg" - << "audio/x-wav" - << "video/x-ms-asf" - << "x-content/audio-player"; + static QStringList res = QStringList() << "application/ogg" + << "application/x-ogg" + << "application/x-ogm-audio" + << "audio/aac" + << "audio/mp4" + << "audio/mpeg" + << "audio/mpegurl" + << "audio/ogg" + << "audio/vnd.rn-realaudio" + << "audio/vorbis" + << "audio/x-flac" + << "audio/x-mp3" + << "audio/x-mpeg" + << "audio/x-mpegurl" + << "audio/x-ms-wma" + << "audio/x-musepack" + << "audio/x-oggflac" + << "audio/x-pn-realaudio" + << "audio/x-scpls" + << "audio/x-speex" + << "audio/x-vorbis" + << "audio/x-vorbis+ogg" + << "audio/x-wav" + << "video/x-ms-asf" + << "x-content/audio-player"; return res; } -void Mpris2::Raise() { - emit RaiseMainWindow(); -} +void Mpris2::Raise() { emit RaiseMainWindow(); } -void Mpris2::Quit() { - qApp->quit(); -} +void Mpris2::Quit() { qApp->quit(); } QString Mpris2::PlaybackStatus() const { return PlaybackStatus(app_->player()->GetState()); @@ -256,9 +244,12 @@ QString Mpris2::PlaybackStatus() const { QString Mpris2::PlaybackStatus(Engine::State state) const { switch (state) { - case Engine::Playing: return "Playing"; - case Engine::Paused: return "Paused"; - default: return "Stopped"; + case Engine::Playing: + return "Playing"; + case Engine::Paused: + return "Paused"; + default: + return "Stopped"; } } @@ -266,12 +257,15 @@ QString Mpris2::LoopStatus() const { if (!app_->playlist_manager()->sequence()) { return "None"; } - + switch (app_->playlist_manager()->sequence()->repeat_mode()) { case PlaylistSequence::Repeat_Album: - case PlaylistSequence::Repeat_Playlist: return "Playlist"; - case PlaylistSequence::Repeat_Track: return "Track"; - default: return "None"; + case PlaylistSequence::Repeat_Playlist: + return "Playlist"; + case PlaylistSequence::Repeat_Track: + return "Track"; + default: + return "None"; } } @@ -289,12 +283,10 @@ void Mpris2::SetLoopStatus(const QString& value) { app_->playlist_manager()->active()->sequence()->SetRepeatMode(mode); } -double Mpris2::Rate() const { - return 1.0; -} +double Mpris2::Rate() const { return 1.0; } void Mpris2::SetRate(double rate) { - if(rate == 0) { + if (rate == 0) { if (mpris1_->player()) { mpris1_->player()->Pause(); } @@ -315,24 +307,20 @@ void Mpris2::SetShuffle(bool value) { } } -QVariantMap Mpris2::Metadata() const { - return last_metadata_; -} +QVariantMap Mpris2::Metadata() const { return last_metadata_; } QString Mpris2::current_track_id() const { if (!mpris1_->tracklist()) { return QString(); } - return QString("/org/mpris/MediaPlayer2/Track/%1").arg( - QString::number(mpris1_->tracklist()->GetCurrentTrack())); + return QString("/org/mpris/MediaPlayer2/Track/%1") + .arg(QString::number(mpris1_->tracklist()->GetCurrentTrack())); } // We send Metadata change notification as soon as the process of // changing song starts... -void Mpris2::CurrentSongChanged(const Song& song) { - ArtLoaded(song, ""); -} +void Mpris2::CurrentSongChanged(const Song& song) { ArtLoaded(song, ""); } // ... and we add the cover information later, when it's available. void Mpris2::ArtLoaded(const Song& song, const QString& art_uri) { @@ -363,21 +351,15 @@ double Mpris2::Volume() const { } } -void Mpris2::SetVolume(double value) { - app_->player()->SetVolume(value * 100); -} +void Mpris2::SetVolume(double value) { app_->player()->SetVolume(value * 100); } qlonglong Mpris2::Position() const { return app_->player()->engine()->position_nanosec() / kNsecPerUsec; } -double Mpris2::MaximumRate() const { - return 1.0; -} +double Mpris2::MaximumRate() const { return 1.0; } -double Mpris2::MinimumRate() const { - return 1.0; -} +double Mpris2::MinimumRate() const { return 1.0; } bool Mpris2::CanGoNext() const { if (mpris1_->player()) { @@ -395,17 +377,14 @@ bool Mpris2::CanGoPrevious() const { } } -bool Mpris2::CanPlay() const { - return mpris1_->player()->GetCaps() & CAN_PLAY; -} +bool Mpris2::CanPlay() const { return mpris1_->player()->GetCaps() & CAN_PLAY; } // This one's a bit different than MPRIS 1 - we want this to be true even when // the song is already paused or stopped. bool Mpris2::CanPause() const { if (mpris1_->player()) { - return mpris1_->player()->GetCaps() & CAN_PAUSE - || PlaybackStatus() == "Paused" - || PlaybackStatus() == "Stopped"; + return mpris1_->player()->GetCaps() & CAN_PAUSE || + PlaybackStatus() == "Paused" || PlaybackStatus() == "Stopped"; } else { return true; } @@ -419,24 +398,22 @@ bool Mpris2::CanSeek() const { } } -bool Mpris2::CanControl() const { - return true; -} +bool Mpris2::CanControl() const { return true; } void Mpris2::Next() { - if(CanGoNext()) { + if (CanGoNext()) { app_->player()->Next(); } } void Mpris2::Previous() { - if(CanGoPrevious()) { + if (CanGoPrevious()) { app_->player()->Previous(); } } void Mpris2::Pause() { - if(CanPause() && app_->player()->GetState() != Engine::Paused) { + if (CanPause() && app_->player()->GetState() != Engine::Paused) { app_->player()->Pause(); } } @@ -447,20 +424,19 @@ void Mpris2::PlayPause() { } } -void Mpris2::Stop() { - app_->player()->Stop(); -} +void Mpris2::Stop() { app_->player()->Stop(); } void Mpris2::Play() { - if(CanPlay()) { + if (CanPlay()) { app_->player()->Play(); } } void Mpris2::Seek(qlonglong offset) { - if(CanSeek()) { - app_->player()->SeekTo(app_->player()->engine()->position_nanosec() / kNsecPerSec + - offset / kUsecPerSec); + if (CanSeek()) { + app_->player()->SeekTo(app_->player()->engine()->position_nanosec() / + kNsecPerSec + + offset / kUsecPerSec); } } @@ -468,7 +444,8 @@ void Mpris2::SetPosition(const QDBusObjectPath& trackId, qlonglong offset) { if (CanSeek() && trackId.path() == current_track_id() && offset >= 0) { offset *= kNsecPerUsec; - if(offset < app_->player()->GetCurrentItem()->Metadata().length_nanosec()) { + if (offset < + app_->player()->GetCurrentItem()->Metadata().length_nanosec()) { app_->player()->SeekTo(offset / kNsecPerSec); } } @@ -481,46 +458,42 @@ void Mpris2::OpenUri(const QString& uri) { } TrackIds Mpris2::Tracks() const { - //TODO + // TODO return TrackIds(); } -bool Mpris2::CanEditTracks() const { - return false; -} +bool Mpris2::CanEditTracks() const { return false; } -TrackMetadata Mpris2::GetTracksMetadata(const TrackIds &tracks) const { - //TODO +TrackMetadata Mpris2::GetTracksMetadata(const TrackIds& tracks) const { + // TODO return TrackMetadata(); } -void Mpris2::AddTrack(const QString &uri, const QDBusObjectPath &afterTrack, bool setAsCurrent) { - //TODO +void Mpris2::AddTrack(const QString& uri, const QDBusObjectPath& afterTrack, + bool setAsCurrent) { + // TODO } -void Mpris2::RemoveTrack(const QDBusObjectPath &trackId) { - //TODO +void Mpris2::RemoveTrack(const QDBusObjectPath& trackId) { + // TODO } -void Mpris2::GoTo(const QDBusObjectPath &trackId) { - //TODO +void Mpris2::GoTo(const QDBusObjectPath& trackId) { + // TODO } quint32 Mpris2::PlaylistCount() const { return app_->playlist_manager()->GetAllPlaylists().size(); } -QStringList Mpris2::Orderings() const { - return QStringList() << "User"; -} +QStringList Mpris2::Orderings() const { return QStringList() << "User"; } namespace { QDBusObjectPath MakePlaylistPath(int id) { - return QDBusObjectPath(QString( - "/org/mpris/MediaPlayer2/Playlists/%1").arg(id)); + return QDBusObjectPath( + QString("/org/mpris/MediaPlayer2/Playlists/%1").arg(id)); } - } MaybePlaylist Mpris2::ActivePlaylist() const { @@ -557,10 +530,11 @@ void Mpris2::ActivatePlaylist(const QDBusObjectPath& playlist_id) { } // TODO: Support sort orders. -MprisPlaylistList Mpris2::GetPlaylists( - quint32 index, quint32 max_count, const QString& order, bool reverse_order) { +MprisPlaylistList Mpris2::GetPlaylists(quint32 index, quint32 max_count, + const QString& order, + bool reverse_order) { MprisPlaylistList ret; - foreach (Playlist* p, app_->playlist_manager()->GetAllPlaylists()) { + foreach(Playlist * p, app_->playlist_manager()->GetAllPlaylists()) { MprisPlaylist mpris_playlist; mpris_playlist.id = MakePlaylistPath(p->id()); mpris_playlist.name = app_->playlist_manager()->GetPlaylistName(p->id()); @@ -577,7 +551,8 @@ MprisPlaylistList Mpris2::GetPlaylists( void Mpris2::PlaylistChanged(Playlist* playlist) { MprisPlaylist mpris_playlist; mpris_playlist.id = MakePlaylistPath(playlist->id()); - mpris_playlist.name = app_->playlist_manager()->GetPlaylistName(playlist->id()); + mpris_playlist.name = + app_->playlist_manager()->GetPlaylistName(playlist->id()); emit PlaylistChanged(mpris_playlist); } @@ -585,4 +560,4 @@ void Mpris2::PlaylistCollectionChanged(Playlist* playlist) { EmitNotification("PlaylistCount", "", "org.mpris.MediaPlayer2.Playlists"); } -} // namespace mpris +} // namespace mpris diff --git a/src/core/mpris2.h b/src/core/mpris2.h index 259ee5e06..1ced809ff 100644 --- a/src/core/mpris2.h +++ b/src/core/mpris2.h @@ -47,14 +47,13 @@ struct MaybePlaylist { }; Q_DECLARE_METATYPE(MaybePlaylist); -QDBusArgument& operator<< (QDBusArgument& arg, const MprisPlaylist& playlist); -const QDBusArgument& operator>> ( - const QDBusArgument& arg, MprisPlaylist& playlist); - -QDBusArgument& operator<< (QDBusArgument& arg, const MaybePlaylist& playlist); -const QDBusArgument& operator>> ( - const QDBusArgument& arg, MaybePlaylist& playlist); +QDBusArgument& operator<<(QDBusArgument& arg, const MprisPlaylist& playlist); +const QDBusArgument& operator>>(const QDBusArgument& arg, + MprisPlaylist& playlist); +QDBusArgument& operator<<(QDBusArgument& arg, const MaybePlaylist& playlist); +const QDBusArgument& operator>>(const QDBusArgument& arg, + MaybePlaylist& playlist); namespace mpris { @@ -64,44 +63,44 @@ class Mpris2 : public QObject { Q_OBJECT public: - //org.mpris.MediaPlayer2 MPRIS 2.0 Root interface - Q_PROPERTY( bool CanQuit READ CanQuit ) - Q_PROPERTY( bool CanRaise READ CanRaise ) - Q_PROPERTY( bool HasTrackList READ HasTrackList ) - Q_PROPERTY( QString Identity READ Identity ) - Q_PROPERTY( QString DesktopEntry READ DesktopEntry ) - Q_PROPERTY( QStringList SupportedUriSchemes READ SupportedUriSchemes ) - Q_PROPERTY( QStringList SupportedMimeTypes READ SupportedMimeTypes ) + // org.mpris.MediaPlayer2 MPRIS 2.0 Root interface + Q_PROPERTY(bool CanQuit READ CanQuit) + Q_PROPERTY(bool CanRaise READ CanRaise) + Q_PROPERTY(bool HasTrackList READ HasTrackList) + Q_PROPERTY(QString Identity READ Identity) + Q_PROPERTY(QString DesktopEntry READ DesktopEntry) + Q_PROPERTY(QStringList SupportedUriSchemes READ SupportedUriSchemes) + Q_PROPERTY(QStringList SupportedMimeTypes READ SupportedMimeTypes) - //org.mpris.MediaPlayer2 MPRIS 2.2 Root interface - Q_PROPERTY( bool CanSetFullscreen READ CanSetFullscreen ) - Q_PROPERTY( bool Fullscreen READ Fullscreen WRITE SetFullscreen ) + // org.mpris.MediaPlayer2 MPRIS 2.2 Root interface + Q_PROPERTY(bool CanSetFullscreen READ CanSetFullscreen) + Q_PROPERTY(bool Fullscreen READ Fullscreen WRITE SetFullscreen) - //org.mpris.MediaPlayer2.Player MPRIS 2.0 Player interface - Q_PROPERTY( QString PlaybackStatus READ PlaybackStatus ) - Q_PROPERTY( QString LoopStatus READ LoopStatus WRITE SetLoopStatus ) - Q_PROPERTY( double Rate READ Rate WRITE SetRate ) - Q_PROPERTY( bool Shuffle READ Shuffle WRITE SetShuffle ) - Q_PROPERTY( QVariantMap Metadata READ Metadata ) - Q_PROPERTY( double Volume READ Volume WRITE SetVolume ) - Q_PROPERTY( qlonglong Position READ Position ) - Q_PROPERTY( double MinimumRate READ MinimumRate ) - Q_PROPERTY( double MaximumRate READ MaximumRate ) - Q_PROPERTY( bool CanGoNext READ CanGoNext ) - Q_PROPERTY( bool CanGoPrevious READ CanGoPrevious ) - Q_PROPERTY( bool CanPlay READ CanPlay ) - Q_PROPERTY( bool CanPause READ CanPause ) - Q_PROPERTY( bool CanSeek READ CanSeek ) - Q_PROPERTY( bool CanControl READ CanControl ) + // org.mpris.MediaPlayer2.Player MPRIS 2.0 Player interface + Q_PROPERTY(QString PlaybackStatus READ PlaybackStatus) + Q_PROPERTY(QString LoopStatus READ LoopStatus WRITE SetLoopStatus) + Q_PROPERTY(double Rate READ Rate WRITE SetRate) + Q_PROPERTY(bool Shuffle READ Shuffle WRITE SetShuffle) + Q_PROPERTY(QVariantMap Metadata READ Metadata) + Q_PROPERTY(double Volume READ Volume WRITE SetVolume) + Q_PROPERTY(qlonglong Position READ Position) + Q_PROPERTY(double MinimumRate READ MinimumRate) + Q_PROPERTY(double MaximumRate READ MaximumRate) + Q_PROPERTY(bool CanGoNext READ CanGoNext) + Q_PROPERTY(bool CanGoPrevious READ CanGoPrevious) + Q_PROPERTY(bool CanPlay READ CanPlay) + Q_PROPERTY(bool CanPause READ CanPause) + Q_PROPERTY(bool CanSeek READ CanSeek) + Q_PROPERTY(bool CanControl READ CanControl) - //org.mpris.MediaPlayer2.TrackList MPRIS 2.0 Player interface - Q_PROPERTY( TrackIds Tracks READ Tracks ) - Q_PROPERTY( bool CanEditTracks READ CanEditTracks ) + // org.mpris.MediaPlayer2.TrackList MPRIS 2.0 Player interface + Q_PROPERTY(TrackIds Tracks READ Tracks) + Q_PROPERTY(bool CanEditTracks READ CanEditTracks) - //org.mpris.MediaPlayer2.Playlists MPRIS 2.1 Playlists interface - Q_PROPERTY( quint32 PlaylistCount READ PlaylistCount ) - Q_PROPERTY( QStringList Orderings READ Orderings ) - Q_PROPERTY( MaybePlaylist ActivePlaylist READ ActivePlaylist ) + // org.mpris.MediaPlayer2.Playlists MPRIS 2.1 Playlists interface + Q_PROPERTY(quint32 PlaylistCount READ PlaylistCount) + Q_PROPERTY(QStringList Orderings READ Orderings) + Q_PROPERTY(MaybePlaylist ActivePlaylist READ ActivePlaylist) Mpris2(Application* app, Mpris1* mpris1, QObject* parent = 0); @@ -161,7 +160,8 @@ class Mpris2 : public QObject { // Methods TrackMetadata GetTracksMetadata(const TrackIds& tracks) const; - void AddTrack(const QString& uri, const QDBusObjectPath& afterTrack, bool setAsCurrent); + void AddTrack(const QString& uri, const QDBusObjectPath& afterTrack, + bool setAsCurrent); void RemoveTrack(const QDBusObjectPath& trackId); void GoTo(const QDBusObjectPath& trackId); @@ -172,8 +172,8 @@ class Mpris2 : public QObject { // Methods void ActivatePlaylist(const QDBusObjectPath& playlist_id); - QList GetPlaylists( - quint32 index, quint32 max_count, const QString& order, bool reverse_order); + QList GetPlaylists(quint32 index, quint32 max_count, + const QString& order, bool reverse_order); signals: // Player @@ -183,14 +183,15 @@ signals: void TrackListReplaced(const TrackIds& Tracks, QDBusObjectPath CurrentTrack); void TrackAdded(const TrackMetadata& Metadata, QDBusObjectPath AfterTrack); void TrackRemoved(const QDBusObjectPath& trackId); - void TrackMetadataChanged(const QDBusObjectPath& trackId, const TrackMetadata& metadata); + void TrackMetadataChanged(const QDBusObjectPath& trackId, + const TrackMetadata& metadata); void RaiseMainWindow(); // Playlist void PlaylistChanged(const MprisPlaylist& playlist); -private slots: + private slots: void ArtLoaded(const Song& song, const QString& art_uri); void EngineStateChanged(Engine::State newState); void VolumeChanged(); @@ -202,10 +203,11 @@ private slots: void PlaylistChanged(Playlist* playlist); void PlaylistCollectionChanged(Playlist* playlist); -private: + private: void EmitNotification(const QString& name); void EmitNotification(const QString& name, const QVariant& val); - void EmitNotification(const QString& name, const QVariant& val, const QString& mprisEntity); + void EmitNotification(const QString& name, const QVariant& val, + const QString& mprisEntity); QString PlaybackStatus(Engine::State state) const; @@ -213,7 +215,7 @@ private: QString DesktopEntryAbsolutePath() const; -private: + private: static const char* kMprisObjectPath; static const char* kServiceName; static const char* kFreedesktopPath; @@ -224,6 +226,6 @@ private: Mpris1* mpris1_; }; -} // namespace mpris +} // namespace mpris #endif diff --git a/src/core/mpris_common.h b/src/core/mpris_common.h index b65dc7e4d..329010a0d 100644 --- a/src/core/mpris_common.h +++ b/src/core/mpris_common.h @@ -25,34 +25,37 @@ namespace mpris { -inline void AddMetadata(const QString& key, const QString& metadata, QVariantMap* map) { - if (!metadata.isEmpty()) (*map)[key] = metadata; +inline void AddMetadata(const QString& key, const QString& metadata, + QVariantMap* map) { + if (!metadata.isEmpty()) (*map)[key] = metadata; } -inline void AddMetadataAsList(const QString& key, const QString& metadata, QVariantMap* map) { - if (!metadata.isEmpty()) (*map)[key] = QStringList() << metadata; +inline void AddMetadataAsList(const QString& key, const QString& metadata, + QVariantMap* map) { + if (!metadata.isEmpty()) (*map)[key] = QStringList() << metadata; } inline void AddMetadata(const QString& key, int metadata, QVariantMap* map) { - if (metadata > 0) (*map)[key] = metadata; + if (metadata > 0) (*map)[key] = metadata; } inline void AddMetadata(const QString& key, qint64 metadata, QVariantMap* map) { - if (metadata > 0) (*map)[key] = metadata; + if (metadata > 0) (*map)[key] = metadata; } inline void AddMetadata(const QString& key, double metadata, QVariantMap* map) { - if (metadata != 0.0) (*map)[key] = metadata; + if (metadata != 0.0) (*map)[key] = metadata; } -inline void AddMetadata(const QString& key, const QDateTime& metadata, QVariantMap* map) { - if (metadata.isValid()) (*map)[key] = metadata; +inline void AddMetadata(const QString& key, const QDateTime& metadata, + QVariantMap* map) { + if (metadata.isValid()) (*map)[key] = metadata; } inline QString AsMPRISDateTimeType(uint time) { return time != -1 ? QDateTime::fromTime_t(time).toString(Qt::ISODate) : ""; } -} // namespace mpris +} // namespace mpris -#endif // MPRIS_COMMON_H +#endif // MPRIS_COMMON_H diff --git a/src/core/multisortfilterproxy.cpp b/src/core/multisortfilterproxy.cpp index 903e58072..1fb1d92d7 100644 --- a/src/core/multisortfilterproxy.cpp +++ b/src/core/multisortfilterproxy.cpp @@ -6,9 +6,7 @@ #include MultiSortFilterProxy::MultiSortFilterProxy(QObject* parent) - : QSortFilterProxyModel(parent) -{ -} + : QSortFilterProxyModel(parent) {} void MultiSortFilterProxy::AddSortSpec(int role, Qt::SortOrder order) { sorting_ << SortSpec(role, order); @@ -16,7 +14,7 @@ void MultiSortFilterProxy::AddSortSpec(int role, Qt::SortOrder order) { bool MultiSortFilterProxy::lessThan(const QModelIndex& left, const QModelIndex& right) const { - foreach (const SortSpec& spec, sorting_) { + foreach(const SortSpec & spec, sorting_) { const int ret = Compare(left.data(spec.first), right.data(spec.first)); if (ret < 0) { @@ -31,29 +29,38 @@ bool MultiSortFilterProxy::lessThan(const QModelIndex& left, template static inline int DoCompare(T left, T right) { - if (left < right) - return -1; - if (left > right) - return 1; + if (left < right) return -1; + if (left > right) return 1; return 0; } -int MultiSortFilterProxy::Compare(const QVariant& left, const QVariant& right) const { +int MultiSortFilterProxy::Compare(const QVariant& left, + const QVariant& right) const { // Copied from the QSortFilterProxyModel::lessThan implementation, but returns // -1, 0 or 1 instead of true or false. switch (left.userType()) { case QVariant::Invalid: return (right.type() != QVariant::Invalid) ? -1 : 0; - case QVariant::Int: return DoCompare(left.toInt(), right.toInt()); - case QVariant::UInt: return DoCompare(left.toUInt(), right.toUInt()); - case QVariant::LongLong: return DoCompare(left.toLongLong(), right.toLongLong()); - case QVariant::ULongLong: return DoCompare(left.toULongLong(), right.toULongLong()); - case QMetaType::Float: return DoCompare(left.toFloat(), right.toFloat()); - case QVariant::Double: return DoCompare(left.toDouble(), right.toDouble()); - case QVariant::Char: return DoCompare(left.toChar(), right.toChar()); - case QVariant::Date: return DoCompare(left.toDate(), right.toDate()); - case QVariant::Time: return DoCompare(left.toTime(), right.toTime()); - case QVariant::DateTime: return DoCompare(left.toDateTime(), right.toDateTime()); + case QVariant::Int: + return DoCompare(left.toInt(), right.toInt()); + case QVariant::UInt: + return DoCompare(left.toUInt(), right.toUInt()); + case QVariant::LongLong: + return DoCompare(left.toLongLong(), right.toLongLong()); + case QVariant::ULongLong: + return DoCompare(left.toULongLong(), right.toULongLong()); + case QMetaType::Float: + return DoCompare(left.toFloat(), right.toFloat()); + case QVariant::Double: + return DoCompare(left.toDouble(), right.toDouble()); + case QVariant::Char: + return DoCompare(left.toChar(), right.toChar()); + case QVariant::Date: + return DoCompare(left.toDate(), right.toDate()); + case QVariant::Time: + return DoCompare(left.toTime(), right.toTime()); + case QVariant::DateTime: + return DoCompare(left.toDateTime(), right.toDateTime()); case QVariant::String: default: if (isSortLocaleAware()) diff --git a/src/core/multisortfilterproxy.h b/src/core/multisortfilterproxy.h index edc4dd3d3..9bc98107a 100644 --- a/src/core/multisortfilterproxy.h +++ b/src/core/multisortfilterproxy.h @@ -4,19 +4,19 @@ #include class MultiSortFilterProxy : public QSortFilterProxyModel { -public: + public: MultiSortFilterProxy(QObject* parent = NULL); void AddSortSpec(int role, Qt::SortOrder order = Qt::AscendingOrder); -protected: + protected: bool lessThan(const QModelIndex& left, const QModelIndex& right) const; -private: + private: int Compare(const QVariant& left, const QVariant& right) const; typedef QPair SortSpec; QList sorting_; }; -#endif // MULTISORTFILTERPROXY_H +#endif // MULTISORTFILTERPROXY_H diff --git a/src/core/musicstorage.cpp b/src/core/musicstorage.cpp index e6a23906a..9c76bdfd4 100644 --- a/src/core/musicstorage.cpp +++ b/src/core/musicstorage.cpp @@ -17,6 +17,4 @@ #include "musicstorage.h" -MusicStorage::MusicStorage() -{ -} +MusicStorage::MusicStorage() {} diff --git a/src/core/musicstorage.h b/src/core/musicstorage.h index 4127c9304..dc6655aa5 100644 --- a/src/core/musicstorage.h +++ b/src/core/musicstorage.h @@ -26,7 +26,7 @@ #include class MusicStorage { -public: + public: MusicStorage(); virtual ~MusicStorage() {} @@ -44,7 +44,7 @@ public: Transcode_Unsupported = 3, }; - typedef std::function ProgressFunction; + typedef std::function ProgressFunction; struct CopyJob { QString source_; @@ -62,10 +62,16 @@ public: virtual QString LocalPath() const { return QString(); } virtual TranscodeMode GetTranscodeMode() const { return Transcode_Never; } - virtual Song::FileType GetTranscodeFormat() const { return Song::Type_Unknown; } - virtual bool GetSupportedFiletypes(QList* ret) { return true; } + virtual Song::FileType GetTranscodeFormat() const { + return Song::Type_Unknown; + } + virtual bool GetSupportedFiletypes(QList* ret) { + return true; + } - virtual bool StartCopy(QList* supported_types) { return true;} + virtual bool StartCopy(QList* supported_types) { + return true; + } virtual bool CopyToStorage(const CopyJob& job) = 0; virtual void FinishCopy(bool success) {} @@ -79,4 +85,4 @@ public: Q_DECLARE_METATYPE(MusicStorage*); Q_DECLARE_METATYPE(std::shared_ptr); -#endif // MUSICSTORAGE_H +#endif // MUSICSTORAGE_H diff --git a/src/core/network.cpp b/src/core/network.cpp index 4015b8b20..bd315ba3d 100644 --- a/src/core/network.cpp +++ b/src/core/network.cpp @@ -29,12 +29,12 @@ QMutex ThreadSafeNetworkDiskCache::sMutex; QNetworkDiskCache* ThreadSafeNetworkDiskCache::sCache = nullptr; - ThreadSafeNetworkDiskCache::ThreadSafeNetworkDiskCache(QObject* parent) { QMutexLocker l(&sMutex); if (!sCache) { sCache = new QNetworkDiskCache; - sCache->setCacheDirectory(Utilities::GetConfigPath(Utilities::Path_NetworkCache)); + sCache->setCacheDirectory( + Utilities::GetConfigPath(Utilities::Path_NetworkCache)); } } @@ -58,7 +58,8 @@ QNetworkCacheMetaData ThreadSafeNetworkDiskCache::metaData(const QUrl& url) { return sCache->metaData(url); } -QIODevice* ThreadSafeNetworkDiskCache::prepare(const QNetworkCacheMetaData& metaData) { +QIODevice* ThreadSafeNetworkDiskCache::prepare( + const QNetworkCacheMetaData& metaData) { QMutexLocker l(&sMutex); return sCache->prepare(metaData); } @@ -68,7 +69,8 @@ bool ThreadSafeNetworkDiskCache::remove(const QUrl& url) { return sCache->remove(url); } -void ThreadSafeNetworkDiskCache::updateMetaData(const QNetworkCacheMetaData& metaData) { +void ThreadSafeNetworkDiskCache::updateMetaData( + const QNetworkCacheMetaData& metaData) { QMutexLocker l(&sMutex); sCache->updateMetaData(metaData); } @@ -78,18 +80,17 @@ void ThreadSafeNetworkDiskCache::clear() { sCache->clear(); } - NetworkAccessManager::NetworkAccessManager(QObject* parent) - : QNetworkAccessManager(parent) -{ + : QNetworkAccessManager(parent) { setCache(new ThreadSafeNetworkDiskCache(this)); } QNetworkReply* NetworkAccessManager::createRequest( Operation op, const QNetworkRequest& request, QIODevice* outgoingData) { - QByteArray user_agent = QString("%1 %2").arg( - QCoreApplication::applicationName(), - QCoreApplication::applicationVersion()).toUtf8(); + QByteArray user_agent = QString("%1 %2") + .arg(QCoreApplication::applicationName(), + QCoreApplication::applicationVersion()) + .toUtf8(); if (request.hasRawHeader("User-Agent")) { // Append the existing user-agent set by a client library (such as @@ -107,8 +108,8 @@ QNetworkReply* NetworkAccessManager::createRequest( } // Prefer the cache unless the caller has changed the setting already - if (request.attribute(QNetworkRequest::CacheLoadControlAttribute).toInt() - == QNetworkRequest::PreferNetwork) { + if (request.attribute(QNetworkRequest::CacheLoadControlAttribute).toInt() == + QNetworkRequest::PreferNetwork) { new_request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); } @@ -116,14 +117,11 @@ QNetworkReply* NetworkAccessManager::createRequest( return QNetworkAccessManager::createRequest(op, new_request, outgoingData); } - NetworkTimeouts::NetworkTimeouts(int timeout_msec, QObject* parent) - : timeout_msec_(timeout_msec) { -} + : timeout_msec_(timeout_msec) {} void NetworkTimeouts::AddReply(QNetworkReply* reply) { - if (timers_.contains(reply)) - return; + if (timers_.contains(reply)) return; connect(reply, SIGNAL(destroyed()), SLOT(ReplyFinished())); connect(reply, SIGNAL(finished()), SLOT(ReplyFinished())); @@ -167,25 +165,29 @@ void NetworkTimeouts::timerEvent(QTimerEvent* e) { } } - -RedirectFollower::RedirectFollower(QNetworkReply* first_reply, int max_redirects) - : QObject(nullptr), - current_reply_(first_reply), - redirects_remaining_(max_redirects) { +RedirectFollower::RedirectFollower(QNetworkReply* first_reply, + int max_redirects) + : QObject(nullptr), + current_reply_(first_reply), + redirects_remaining_(max_redirects) { ConnectReply(first_reply); } void RedirectFollower::ConnectReply(QNetworkReply* reply) { connect(reply, SIGNAL(readyRead()), SLOT(ReadyRead())); - connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SIGNAL(error(QNetworkReply::NetworkError))); - connect(reply, SIGNAL(downloadProgress(qint64,qint64)), SIGNAL(downloadProgress(qint64,qint64))); - connect(reply, SIGNAL(uploadProgress(qint64,qint64)), SIGNAL(uploadProgress(qint64,qint64))); + connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), + SIGNAL(error(QNetworkReply::NetworkError))); + connect(reply, SIGNAL(downloadProgress(qint64, qint64)), + SIGNAL(downloadProgress(qint64, qint64))); + connect(reply, SIGNAL(uploadProgress(qint64, qint64)), + SIGNAL(uploadProgress(qint64, qint64))); connect(reply, SIGNAL(finished()), SLOT(ReplyFinished())); } void RedirectFollower::ReadyRead() { // Don't re-emit this signal for redirect replies. - if (current_reply_->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid()) { + if (current_reply_->attribute(QNetworkRequest::RedirectionTargetAttribute) + .isValid()) { return; } @@ -195,14 +197,16 @@ void RedirectFollower::ReadyRead() { void RedirectFollower::ReplyFinished() { current_reply_->deleteLater(); - if (current_reply_->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid()) { + if (current_reply_->attribute(QNetworkRequest::RedirectionTargetAttribute) + .isValid()) { if (redirects_remaining_-- == 0) { emit finished(); return; } const QUrl next_url = current_reply_->url().resolved( - current_reply_->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl()); + current_reply_->attribute(QNetworkRequest::RedirectionTargetAttribute) + .toUrl()); QNetworkRequest req(current_reply_->request()); req.setUrl(next_url); diff --git a/src/core/network.h b/src/core/network.h index d5f7f4cd4..588e84f69 100644 --- a/src/core/network.h +++ b/src/core/network.h @@ -26,7 +26,7 @@ class QNetworkDiskCache; class ThreadSafeNetworkDiskCache : public QAbstractNetworkCache { -public: + public: ThreadSafeNetworkDiskCache(QObject* parent); qint64 cacheSize() const; @@ -39,28 +39,26 @@ public: void clear(); -private: + private: static QMutex sMutex; static QNetworkDiskCache* sCache; }; - class NetworkAccessManager : public QNetworkAccessManager { Q_OBJECT -public: + public: NetworkAccessManager(QObject* parent = 0); -protected: + protected: QNetworkReply* createRequest(Operation op, const QNetworkRequest& request, QIODevice* outgoingData); }; - class RedirectFollower : public QObject { Q_OBJECT -public: + public: RedirectFollower(QNetworkReply* first_reply, int max_redirects = 5); bool hit_redirect_limit() const { return redirects_remaining_ < 0; } @@ -69,8 +67,12 @@ public: // These are all forwarded to the current reply. QNetworkReply::NetworkError error() const { return current_reply_->error(); } QString errorString() const { return current_reply_->errorString(); } - QVariant attribute(QNetworkRequest::Attribute code) const { return current_reply_->attribute(code); } - QVariant header(QNetworkRequest::KnownHeaders header) const { return current_reply_->header(header); } + QVariant attribute(QNetworkRequest::Attribute code) const { + return current_reply_->attribute(code); + } + QVariant header(QNetworkRequest::KnownHeaders header) const { + return current_reply_->header(header); + } qint64 bytesAvailable() const { return current_reply_->bytesAvailable(); } QUrl url() const { return current_reply_->url(); } QByteArray readAll() { return current_reply_->readAll(); } @@ -86,23 +88,22 @@ signals: // This is NOT emitted when a request that has a redirect finishes. void finished(); -private slots: + private slots: void ReadyRead(); void ReplyFinished(); -private: + private: void ConnectReply(QNetworkReply* reply); -private: + private: QNetworkReply* current_reply_; int redirects_remaining_; }; - class NetworkTimeouts : public QObject { Q_OBJECT -public: + public: NetworkTimeouts(int timeout_msec, QObject* parent = 0); // TODO: Template this to avoid code duplication. @@ -110,17 +111,17 @@ public: void AddReply(RedirectFollower* reply); void SetTimeout(int msec) { timeout_msec_ = msec; } -protected: + protected: void timerEvent(QTimerEvent* e); -private slots: + private slots: void ReplyFinished(); void RedirectFinished(RedirectFollower* redirect); -private: + private: int timeout_msec_; QMap timers_; QMap redirect_timers_; }; -#endif // NETWORK_H +#endif // NETWORK_H diff --git a/src/core/networkproxyfactory.cpp b/src/core/networkproxyfactory.cpp index 095462b0a..518029f7a 100644 --- a/src/core/networkproxyfactory.cpp +++ b/src/core/networkproxyfactory.cpp @@ -12,11 +12,10 @@ NetworkProxyFactory* NetworkProxyFactory::sInstance = nullptr; const char* NetworkProxyFactory::kSettingsGroup = "Proxy"; NetworkProxyFactory::NetworkProxyFactory() - : mode_(Mode_System), - type_(QNetworkProxy::HttpProxy), - port_(8080), - use_authentication_(false) -{ + : mode_(Mode_System), + type_(QNetworkProxy::HttpProxy), + port_(8080), + use_authentication_(false) { #ifdef Q_OS_LINUX // Linux uses environment variables to pass proxy configuration information, // which systemProxyForQuery doesn't support for some reason. @@ -29,9 +28,8 @@ NetworkProxyFactory::NetworkProxyFactory() qLog(Debug) << "Detected system proxy URLs:" << urls; - foreach (const QString& url_str, urls) { - if (url_str.isEmpty()) - continue; + foreach(const QString & url_str, urls) { + if (url_str.isEmpty()) continue; env_url_ = QUrl(url_str); break; @@ -56,7 +54,8 @@ void NetworkProxyFactory::ReloadSettings() { s.beginGroup(kSettingsGroup); mode_ = Mode(s.value("mode", Mode_System).toInt()); - type_ = QNetworkProxy::ProxyType(s.value("type", QNetworkProxy::HttpProxy).toInt()); + type_ = QNetworkProxy::ProxyType( + s.value("type", QNetworkProxy::HttpProxy).toInt()); hostname_ = s.value("hostname").toString(); port_ = s.value("port", 8080).toInt(); use_authentication_ = s.value("use_authentication", false).toBool(); @@ -71,41 +70,41 @@ QList NetworkProxyFactory::queryProxy( QNetworkProxy ret; switch (mode_) { - case Mode_System: + case Mode_System: #ifdef Q_OS_LINUX - Q_UNUSED(query); + Q_UNUSED(query); - if (env_url_.isEmpty()) { - ret.setType(QNetworkProxy::NoProxy); - } else { - ret.setHostName(env_url_.host()); - ret.setPort(env_url_.port()); - ret.setUser(env_url_.userName()); - ret.setPassword(env_url_.password()); - if (env_url_.scheme().startsWith("http")) - ret.setType(QNetworkProxy::HttpProxy); - else - ret.setType(QNetworkProxy::Socks5Proxy); - qLog(Debug) << "Using proxy URL:" << env_url_; - } - break; + if (env_url_.isEmpty()) { + ret.setType(QNetworkProxy::NoProxy); + } else { + ret.setHostName(env_url_.host()); + ret.setPort(env_url_.port()); + ret.setUser(env_url_.userName()); + ret.setPassword(env_url_.password()); + if (env_url_.scheme().startsWith("http")) + ret.setType(QNetworkProxy::HttpProxy); + else + ret.setType(QNetworkProxy::Socks5Proxy); + qLog(Debug) << "Using proxy URL:" << env_url_; + } + break; #else - return systemProxyForQuery(query); + return systemProxyForQuery(query); #endif - case Mode_Direct: - ret.setType(QNetworkProxy::NoProxy); - break; + case Mode_Direct: + ret.setType(QNetworkProxy::NoProxy); + break; - case Mode_Manual: - ret.setType(type_); - ret.setHostName(hostname_); - ret.setPort(port_); - if (use_authentication_) { - ret.setUser(username_); - ret.setPassword(password_); - } - break; + case Mode_Manual: + ret.setType(type_); + ret.setHostName(hostname_); + ret.setPort(port_); + if (use_authentication_) { + ret.setUser(username_); + ret.setPassword(password_); + } + break; } return QList() << ret; diff --git a/src/core/networkproxyfactory.h b/src/core/networkproxyfactory.h index 78030e772..882f0554b 100644 --- a/src/core/networkproxyfactory.h +++ b/src/core/networkproxyfactory.h @@ -6,13 +6,9 @@ #include class NetworkProxyFactory : public QNetworkProxyFactory { -public: + public: // These values are persisted - enum Mode { - Mode_System = 0, - Mode_Direct = 1, - Mode_Manual = 2, - }; + enum Mode { Mode_System = 0, Mode_Direct = 1, Mode_Manual = 2, }; static NetworkProxyFactory* Instance(); static const char* kSettingsGroup; @@ -21,7 +17,7 @@ public: void ReloadSettings(); QList queryProxy(const QNetworkProxyQuery& query); -private: + private: NetworkProxyFactory(); static NetworkProxyFactory* sInstance; @@ -41,4 +37,4 @@ private: #endif }; -#endif // NETWORKPROXYFACTORY_H +#endif // NETWORKPROXYFACTORY_H diff --git a/src/core/organise.cpp b/src/core/organise.cpp index b46583b2f..6f18417f6 100644 --- a/src/core/organise.cpp +++ b/src/core/organise.cpp @@ -38,23 +38,22 @@ const int Organise::kTranscodeProgressInterval = 500; Organise::Organise(TaskManager* task_manager, std::shared_ptr destination, - const OrganiseFormat &format, bool copy, bool overwrite, + const OrganiseFormat& format, bool copy, bool overwrite, const NewSongInfoList& songs_info, bool eject_after) - : thread_(nullptr), - task_manager_(task_manager), - transcoder_(new Transcoder(this)), - destination_(destination), - format_(format), - copy_(copy), - overwrite_(overwrite), - eject_after_(eject_after), - task_count_(songs_info.count()), - transcode_suffix_(1), - tasks_complete_(0), - started_(false), - task_id_(0), - current_copy_progress_(0) -{ + : thread_(nullptr), + task_manager_(task_manager), + transcoder_(new Transcoder(this)), + destination_(destination), + format_(format), + copy_(copy), + overwrite_(overwrite), + eject_after_(eject_after), + task_count_(songs_info.count()), + transcode_suffix_(1), + tasks_complete_(0), + started_(false), + task_id_(0), + current_copy_progress_(0) { original_thread_ = thread(); for (const NewSongInfo& song_info : songs_info) { @@ -63,15 +62,15 @@ Organise::Organise(TaskManager* task_manager, } void Organise::Start() { - if (thread_) - return; + if (thread_) return; task_id_ = task_manager_->StartTask(tr("Organising files")); task_manager_->SetTaskBlocksLibraryScans(true); thread_ = new QThread; connect(thread_, SIGNAL(started()), SLOT(ProcessSomeFiles())); - connect(transcoder_, SIGNAL(JobComplete(QString, bool)), SLOT(FileTranscoded(QString, bool))); + connect(transcoder_, SIGNAL(JobComplete(QString, bool)), + SLOT(FileTranscoded(QString, bool))); moveToThread(thread_); thread_->start(); @@ -102,8 +101,7 @@ void Organise::ProcessSomeFiles() { UpdateProgress(); destination_->FinishCopy(files_with_errors_.isEmpty()); - if (eject_after_) - destination_->Eject(); + if (eject_after_) destination_->Eject(); task_manager_->SetTaskFinished(task_id_); @@ -123,16 +121,14 @@ void Organise::ProcessSomeFiles() { for (int i = 0; i < kBatchSize; ++i) { SetSongProgress(0); - if (tasks_pending_.isEmpty()) - break; + if (tasks_pending_.isEmpty()) break; Task task = tasks_pending_.takeFirst(); qLog(Info) << "Processing" << task.song_info_.song_.url().toLocalFile(); // Use a Song instead of a tag reader Song song = task.song_info_.song_; - if (!song.is_valid()) - continue; + if (!song.is_valid()) continue; // Maybe this file is one that's been transcoded already? if (!task.transcoded_filename_.isEmpty()) { @@ -142,10 +138,13 @@ void Organise::ProcessSomeFiles() { song.set_filetype(task.new_filetype_); // Fiddle the filename extension as well to match the new type - song.set_url(QUrl::fromLocalFile(Utilities::FiddleFileExtension(song.basefilename(), task.new_extension_))); - song.set_basefilename(Utilities::FiddleFileExtension(song.basefilename(), task.new_extension_)); + song.set_url(QUrl::fromLocalFile(Utilities::FiddleFileExtension( + song.basefilename(), task.new_extension_))); + song.set_basefilename(Utilities::FiddleFileExtension( + song.basefilename(), task.new_extension_)); - // Have to set this to the size of the new file or else funny stuff happens + // Have to set this to the size of the new file or else funny stuff + // happens song.set_filesize(QFileInfo(task.transcoded_filename_).size()); } else { // Figure out if we need to transcode it @@ -167,21 +166,23 @@ void Organise::ProcessSomeFiles() { // Start the transcoding - this will happen in the background and // FileTranscoded() will get called when it's done. At that point the // task will get re-added to the pending queue with the new filename. - transcoder_->AddJob(task.song_info_.song_.url().toLocalFile(), preset, task.transcoded_filename_); + transcoder_->AddJob(task.song_info_.song_.url().toLocalFile(), preset, + task.transcoded_filename_); transcoder_->Start(); continue; } } MusicStorage::CopyJob job; - job.source_ = task.transcoded_filename_.isEmpty() ? - task.song_info_.song_.url().toLocalFile() : task.transcoded_filename_; + job.source_ = task.transcoded_filename_.isEmpty() + ? task.song_info_.song_.url().toLocalFile() + : task.transcoded_filename_; job.destination_ = task.song_info_.new_filename_; job.metadata_ = song; job.overwrite_ = overwrite_; job.remove_original_ = !copy_; - job.progress_ = std::bind(&Organise::SetSongProgress, - this, _1, !task.transcoded_filename_.isEmpty()); + job.progress_ = std::bind(&Organise::SetSongProgress, this, _1, + !task.transcoded_filename_.isEmpty()); if (!destination_->CopyToStorage(job)) { files_with_errors_ << task.song_info_.song_.basefilename(); @@ -199,8 +200,7 @@ void Organise::ProcessSomeFiles() { } Song::FileType Organise::CheckTranscode(Song::FileType original_type) const { - if (original_type == Song::Type_Stream) - return Song::Type_Unknown; + if (original_type == Song::Type_Stream) return Song::Type_Unknown; const MusicStorage::TranscodeMode mode = destination_->GetTranscodeMode(); const Song::FileType format = destination_->GetTranscodeFormat(); @@ -210,16 +210,15 @@ Song::FileType Organise::CheckTranscode(Song::FileType original_type) const { return Song::Type_Unknown; case MusicStorage::Transcode_Always: - if (original_type == format) - return Song::Type_Unknown; + if (original_type == format) return Song::Type_Unknown; return format; case MusicStorage::Transcode_Unsupported: - if (supported_filetypes_.isEmpty() || supported_filetypes_.contains(original_type)) + if (supported_filetypes_.isEmpty() || + supported_filetypes_.contains(original_type)) return Song::Type_Unknown; - if (format != Song::Type_Unknown) - return format; + if (format != Song::Type_Unknown) return format; // The user hasn't visited the device properties page yet to set a // preferred format for the device, so we have to pick the best @@ -232,7 +231,7 @@ Song::FileType Organise::CheckTranscode(Song::FileType original_type) const { void Organise::SetSongProgress(float progress, bool transcoded) { const int max = transcoded ? 50 : 100; current_copy_progress_ = (transcoded ? 50 : 0) + - qBound(0, static_cast(progress * max), max-1); + qBound(0, static_cast(progress * max), max - 1); UpdateProgress(); } @@ -242,9 +241,9 @@ void Organise::UpdateProgress() { // Update transcoding progress QMap transcode_progress = transcoder_->GetProgress(); for (const QString& filename : transcode_progress.keys()) { - if (!tasks_transcoding_.contains(filename)) - continue; - tasks_transcoding_[filename].transcode_progress_ = transcode_progress[filename]; + if (!tasks_transcoding_.contains(filename)) continue; + tasks_transcoding_[filename].transcode_progress_ = + transcode_progress[filename]; } // Count the progress of all tasks that are in the queue. Files that need diff --git a/src/core/organise.h b/src/core/organise.h index eba134750..9961c8be8 100644 --- a/src/core/organise.h +++ b/src/core/organise.h @@ -33,18 +33,17 @@ class TaskManager; class Organise : public QObject { Q_OBJECT -public: - + public: struct NewSongInfo { - NewSongInfo(const Song& song = Song(), const QString& new_filename = QString()) - : song_(song), new_filename_(new_filename) {} + NewSongInfo(const Song& song = Song(), + const QString& new_filename = QString()) + : song_(song), new_filename_(new_filename) {} Song song_; QString new_filename_; }; typedef QList NewSongInfoList; - Organise(TaskManager* task_manager, - std::shared_ptr destination, + Organise(TaskManager* task_manager, std::shared_ptr destination, const OrganiseFormat& format, bool copy, bool overwrite, const NewSongInfoList& songs, bool eject_after); @@ -56,22 +55,22 @@ public: signals: void Finished(const QStringList& files_with_errors); -protected: + protected: void timerEvent(QTimerEvent* e); -private slots: + private slots: void ProcessSomeFiles(); void FileTranscoded(const QString& filename, bool success); -private: + private: void SetSongProgress(float progress, bool transcoded = false); void UpdateProgress(); Song::FileType CheckTranscode(Song::FileType original_type) const; -private: + private: struct Task { explicit Task(const NewSongInfo& song_info = NewSongInfo()) - : song_info_(song_info), transcode_progress_(0.0) {} + : song_info_(song_info), transcode_progress_(0.0) {} NewSongInfo song_info_; @@ -110,4 +109,4 @@ private: QStringList files_with_errors_; }; -#endif // ORGANISE_H +#endif // ORGANISE_H diff --git a/src/core/organiseformat.cpp b/src/core/organiseformat.cpp index e8be2030a..b0e650c10 100644 --- a/src/core/organiseformat.cpp +++ b/src/core/organiseformat.cpp @@ -27,11 +27,24 @@ const char* OrganiseFormat::kTagPattern = "\\%([a-zA-Z]*)"; const char* OrganiseFormat::kBlockPattern = "\\{([^{}]+)\\}"; -const QStringList OrganiseFormat::kKnownTags = QStringList() - << "title" << "album" << "artist" << "artistinitial" << "albumartist" - << "composer" << "track" << "disc" << "bpm" << "year" << "genre" - << "comment" << "length" << "bitrate" << "samplerate" << "extension" - << "performer" << "grouping"; +const QStringList OrganiseFormat::kKnownTags = QStringList() << "title" + << "album" + << "artist" + << "artistinitial" + << "albumartist" + << "composer" + << "track" + << "disc" + << "bpm" + << "year" + << "genre" + << "comment" + << "length" + << "bitrate" + << "samplerate" + << "extension" + << "performer" + << "grouping"; // From http://en.wikipedia.org/wiki/8.3_filename#Directory_table const char* OrganiseFormat::kInvalidFatCharacters = "\"*/\\:<>?|"; @@ -52,14 +65,13 @@ const QRgb OrganiseFormat::SyntaxHighlighter::kInvalidTagColorDark = const QRgb OrganiseFormat::SyntaxHighlighter::kBlockColorDark = qRgb(64, 64, 64); -OrganiseFormat::OrganiseFormat(const QString &format) - : format_(format), - replace_non_ascii_(false), - replace_spaces_(false), - replace_the_(false) { -} +OrganiseFormat::OrganiseFormat(const QString& format) + : format_(format), + replace_non_ascii_(false), + replace_spaces_(false), + replace_the_(false) {} -void OrganiseFormat::set_format(const QString &v) { +void OrganiseFormat::set_format(const QString& v) { format_ = v; format_.replace('\\', '/'); } @@ -72,23 +84,24 @@ bool OrganiseFormat::IsValid() const { return v.validate(format_copy, pos) == QValidator::Acceptable; } -QString OrganiseFormat::GetFilenameForSong(const Song &song) const { +QString OrganiseFormat::GetFilenameForSong(const Song& song) const { QString filename = ParseBlock(format_, song); if (QFileInfo(filename).completeBaseName().isEmpty()) { // Avoid having empty filenames, or filenames with extension only: in this // case, keep the original filename. - // We remove the extension from "filename" if it exists, as song.basefilename() + // We remove the extension from "filename" if it exists, as + // song.basefilename() // also contains the extension. - filename = Utilities::PathWithoutFilenameExtension(filename) + song.basefilename(); + filename = + Utilities::PathWithoutFilenameExtension(filename) + song.basefilename(); } - if (replace_spaces_) - filename.replace(QRegExp("\\s"), "_"); + if (replace_spaces_) filename.replace(QRegExp("\\s"), "_"); if (replace_non_ascii_) { QString stripped; - for (int i = 0 ; i < filename.length(); ++i) { + for (int i = 0; i < filename.length(); ++i) { const QCharRef c = filename[i]; if (c < 128) { stripped.append(c); @@ -117,8 +130,7 @@ QString OrganiseFormat::ParseBlock(QString block, const Song& song, // Recursively parse the block bool empty = false; QString value = ParseBlock(block_regexp.cap(1), song, &empty); - if (empty) - value = ""; + if (empty) value = ""; // Replace the block's value block.replace(pos, block_regexp.matchedLength(), value); @@ -130,89 +142,95 @@ QString OrganiseFormat::ParseBlock(QString block, const Song& song, pos = 0; while ((pos = tag_regexp.indexIn(block, pos)) != -1) { QString value = TagValue(tag_regexp.cap(1), song); - if (value.isEmpty()) - empty = true; + if (value.isEmpty()) empty = true; block.replace(pos, tag_regexp.matchedLength(), value); pos += value.length(); } - if (any_empty) - *any_empty = empty; + if (any_empty) *any_empty = empty; return block; } -QString OrganiseFormat::TagValue(const QString &tag, const Song &song) const { +QString OrganiseFormat::TagValue(const QString& tag, const Song& song) const { QString value; - if (tag == "title") value = song.title(); - else if (tag == "album") value = song.album(); - else if (tag == "artist") value = song.artist(); - else if (tag == "composer") value = song.composer(); - else if (tag == "performer") value = song.performer(); - else if (tag == "grouping") value = song.grouping(); - else if (tag == "genre") value = song.genre(); - else if (tag == "comment") value = song.comment(); - else if (tag == "year") value = QString::number(song.year()); - else if (tag == "track") value = QString::number(song.track()); - else if (tag == "disc") value = QString::number(song.disc()); - else if (tag == "bpm") value = QString::number(song.bpm()); - else if (tag == "length") value = - QString::number(song.length_nanosec() / kNsecPerSec); - else if (tag == "bitrate") value = QString::number(song.bitrate()); - else if (tag == "samplerate") value = QString::number(song.samplerate()); - else if (tag == "extension") value = QFileInfo(song.url().toLocalFile()).suffix(); + if (tag == "title") + value = song.title(); + else if (tag == "album") + value = song.album(); + else if (tag == "artist") + value = song.artist(); + else if (tag == "composer") + value = song.composer(); + else if (tag == "performer") + value = song.performer(); + else if (tag == "grouping") + value = song.grouping(); + else if (tag == "genre") + value = song.genre(); + else if (tag == "comment") + value = song.comment(); + else if (tag == "year") + value = QString::number(song.year()); + else if (tag == "track") + value = QString::number(song.track()); + else if (tag == "disc") + value = QString::number(song.disc()); + else if (tag == "bpm") + value = QString::number(song.bpm()); + else if (tag == "length") + value = QString::number(song.length_nanosec() / kNsecPerSec); + else if (tag == "bitrate") + value = QString::number(song.bitrate()); + else if (tag == "samplerate") + value = QString::number(song.samplerate()); + else if (tag == "extension") + value = QFileInfo(song.url().toLocalFile()).suffix(); else if (tag == "artistinitial") { value = song.effective_albumartist().trimmed(); if (replace_the_ && !value.isEmpty()) value.replace(QRegExp("^the\\s+", Qt::CaseInsensitive), ""); if (!value.isEmpty()) value = value[0].toUpper(); } else if (tag == "albumartist") { - value = song.is_compilation() - ? "Various Artists" - : song.effective_albumartist(); + value = song.is_compilation() ? "Various Artists" + : song.effective_albumartist(); } if (replace_the_ && (tag == "artist" || tag == "albumartist")) value.replace(QRegExp("^the\\s+", Qt::CaseInsensitive), ""); - if (value == "0" || value == "-1") - value = ""; + if (value == "0" || value == "-1") value = ""; // Prepend a 0 to single-digit track numbers - if (tag == "track" && value.length() == 1) - value.prepend('0'); + if (tag == "track" && value.length() == 1) value.prepend('0'); // Replace characters that really shouldn't be in paths - for (int i = 0 ; i < kInvalidFatCharactersCount; ++i) { + for (int i = 0; i < kInvalidFatCharactersCount; ++i) { value.replace(kInvalidFatCharacters[i], '_'); } return value; } +OrganiseFormat::Validator::Validator(QObject* parent) : QValidator(parent) {} -OrganiseFormat::Validator::Validator(QObject *parent) - : QValidator(parent) {} - -QValidator::State OrganiseFormat::Validator::validate( - QString& input, int&) const { +QValidator::State OrganiseFormat::Validator::validate(QString& input, + int&) const { QRegExp tag_regexp(kTagPattern); // Make sure all the blocks match up int block_level = 0; - for (int i = 0 ; i < input.length(); ++i) { + for (int i = 0; i < input.length(); ++i) { if (input[i] == '{') block_level++; else if (input[i] == '}') block_level--; - if (block_level < 0 || block_level > 1) - return QValidator::Invalid; + if (block_level < 0 || block_level > 1) return QValidator::Invalid; } - if (block_level != 0) - return QValidator::Invalid; + if (block_level != 0) return QValidator::Invalid; // Make sure the tags are valid int pos = 0; @@ -226,15 +244,14 @@ QValidator::State OrganiseFormat::Validator::validate( return QValidator::Acceptable; } - -OrganiseFormat::SyntaxHighlighter::SyntaxHighlighter(QObject *parent) - : QSyntaxHighlighter(parent) {} +OrganiseFormat::SyntaxHighlighter::SyntaxHighlighter(QObject* parent) + : QSyntaxHighlighter(parent) {} OrganiseFormat::SyntaxHighlighter::SyntaxHighlighter(QTextEdit* parent) - : QSyntaxHighlighter(parent) {} + : QSyntaxHighlighter(parent) {} OrganiseFormat::SyntaxHighlighter::SyntaxHighlighter(QTextDocument* parent) - : QSyntaxHighlighter(parent) {} + : QSyntaxHighlighter(parent) {} void OrganiseFormat::SyntaxHighlighter::highlightBlock(const QString& text) { const bool light = @@ -267,11 +284,10 @@ void OrganiseFormat::SyntaxHighlighter::highlightBlock(const QString& text) { QTextCharFormat f = format(pos); f.setForeground( QColor(OrganiseFormat::kKnownTags.contains(tag_regexp.cap(1)) - ? valid_tag_color - : invalid_tag_color)); + ? valid_tag_color + : invalid_tag_color)); setFormat(pos, tag_regexp.matchedLength(), f); pos += tag_regexp.matchedLength(); } } - diff --git a/src/core/organiseformat.h b/src/core/organiseformat.h index 65c60ebbc..2b4f3febe 100644 --- a/src/core/organiseformat.h +++ b/src/core/organiseformat.h @@ -46,7 +46,6 @@ class OrganiseFormat { bool IsValid() const; QString GetFilenameForSong(const Song& song) const; - class Validator : public QValidator { public: explicit Validator(QObject* parent = 0); @@ -69,8 +68,8 @@ class OrganiseFormat { }; private: - QString ParseBlock( - QString block, const Song& song, bool* any_empty = NULL) const; + QString ParseBlock(QString block, const Song& song, + bool* any_empty = NULL) const; QString TagValue(const QString& tag, const Song& song) const; QString format_; diff --git a/src/core/player.cpp b/src/core/player.cpp index 86990b115..269272021 100644 --- a/src/core/player.cpp +++ b/src/core/player.cpp @@ -35,43 +35,43 @@ #include "playlist/playlistmanager.h" #ifdef HAVE_LIBLASTFM -# include "internet/lastfmservice.h" +#include "internet/lastfmservice.h" #endif using std::shared_ptr; Player::Player(Application* app, QObject* parent) - : PlayerInterface(parent), - app_(app), - lastfm_(nullptr), - engine_(new GstEngine(app_->task_manager())), - stream_change_type_(Engine::First), - last_state_(Engine::Empty), - nb_errors_received_(0), - volume_before_mute_(50) -{ + : PlayerInterface(parent), + app_(app), + lastfm_(nullptr), + engine_(new GstEngine(app_->task_manager())), + stream_change_type_(Engine::First), + last_state_(Engine::Empty), + nb_errors_received_(0), + volume_before_mute_(50) { settings_.beginGroup("Player"); SetVolume(settings_.value("volume", 50).toInt()); connect(engine_.get(), SIGNAL(Error(QString)), SIGNAL(Error(QString))); - connect(engine_.get(), SIGNAL(ValidSongRequested(QUrl)), SLOT(ValidSongRequested(QUrl))); - connect(engine_.get(), SIGNAL(InvalidSongRequested(QUrl)), SLOT(InvalidSongRequested(QUrl))); + connect(engine_.get(), SIGNAL(ValidSongRequested(QUrl)), + SLOT(ValidSongRequested(QUrl))); + connect(engine_.get(), SIGNAL(InvalidSongRequested(QUrl)), + SLOT(InvalidSongRequested(QUrl))); } -Player::~Player() { -} +Player::~Player() {} void Player::Init() { - if (!engine_->Init()) - qFatal("Error initialising audio engine"); + if (!engine_->Init()) qFatal("Error initialising audio engine"); - connect(engine_.get(), SIGNAL(StateChanged(Engine::State)), SLOT(EngineStateChanged(Engine::State))); + connect(engine_.get(), SIGNAL(StateChanged(Engine::State)), + SLOT(EngineStateChanged(Engine::State))); connect(engine_.get(), SIGNAL(TrackAboutToEnd()), SLOT(TrackAboutToEnd())); connect(engine_.get(), SIGNAL(TrackEnded()), SLOT(TrackEnded())); connect(engine_.get(), SIGNAL(MetaData(Engine::SimpleMetaBundle)), - SLOT(EngineMetadataReceived(Engine::SimpleMetaBundle))); + SLOT(EngineMetadataReceived(Engine::SimpleMetaBundle))); engine_->SetVolume(settings_.value("volume", 50).toInt()); @@ -80,76 +80,69 @@ void Player::Init() { #endif } -void Player::ReloadSettings() { - engine_->ReloadSettings(); -} +void Player::ReloadSettings() { engine_->ReloadSettings(); } void Player::HandleLoadResult(const UrlHandler::LoadResult& result) { switch (result.type_) { - case UrlHandler::LoadResult::NoMoreTracks: - qLog(Debug) << "URL handler for" << result.original_url_ - << "said no more tracks"; + case UrlHandler::LoadResult::NoMoreTracks: + qLog(Debug) << "URL handler for" << result.original_url_ + << "said no more tracks"; - loading_async_ = QUrl(); - NextItem(stream_change_type_); - break; + loading_async_ = QUrl(); + NextItem(stream_change_type_); + break; - case UrlHandler::LoadResult::TrackAvailable: { - // Might've been an async load, so check we're still on the same item - int current_index = app_->playlist_manager()->active()->current_row(); - if (current_index == -1) - return; + case UrlHandler::LoadResult::TrackAvailable: { + // Might've been an async load, so check we're still on the same item + int current_index = app_->playlist_manager()->active()->current_row(); + if (current_index == -1) return; - shared_ptr item = app_->playlist_manager()->active()->item_at(current_index); - if (!item || item->Url() != result.original_url_) - return; + shared_ptr item = + app_->playlist_manager()->active()->item_at(current_index); + if (!item || item->Url() != result.original_url_) return; - qLog(Debug) << "URL handler for" << result.original_url_ - << "returned" << result.media_url_; + qLog(Debug) << "URL handler for" << result.original_url_ << "returned" + << result.media_url_; - // If there was no length info in song's metadata, use the one provided by - // URL handler, if there is one - if (item->Metadata().length_nanosec() <= 0 && result.length_nanosec_ != -1) { - Song song = item->Metadata(); - song.set_length_nanosec(result.length_nanosec_); - item->SetTemporaryMetadata(song); - app_->playlist_manager()->active()->InformOfCurrentSongChange(); + // If there was no length info in song's metadata, use the one provided by + // URL handler, if there is one + if (item->Metadata().length_nanosec() <= 0 && + result.length_nanosec_ != -1) { + Song song = item->Metadata(); + song.set_length_nanosec(result.length_nanosec_); + item->SetTemporaryMetadata(song); + app_->playlist_manager()->active()->InformOfCurrentSongChange(); + } + engine_->Play( + result.media_url_, stream_change_type_, item->Metadata().has_cue(), + item->Metadata().beginning_nanosec(), item->Metadata().end_nanosec()); + + current_item_ = item; + loading_async_ = QUrl(); + break; } - engine_->Play(result.media_url_, stream_change_type_, - item->Metadata().has_cue(), - item->Metadata().beginning_nanosec(), - item->Metadata().end_nanosec()); - current_item_ = item; - loading_async_ = QUrl(); - break; - } + case UrlHandler::LoadResult::WillLoadAsynchronously: + qLog(Debug) << "URL handler for" << result.original_url_ + << "is loading asynchronously"; - case UrlHandler::LoadResult::WillLoadAsynchronously: - qLog(Debug) << "URL handler for" << result.original_url_ - << "is loading asynchronously"; - - // We'll get called again later with either NoMoreTracks or TrackAvailable - loading_async_ = result.original_url_; - break; + // We'll get called again later with either NoMoreTracks or TrackAvailable + loading_async_ = result.original_url_; + break; } } -void Player::Next() { - NextInternal(Engine::Manual); -} +void Player::Next() { NextInternal(Engine::Manual); } void Player::NextInternal(Engine::TrackChangeFlags change) { - if (HandleStopAfter()) - return; + if (HandleStopAfter()) return; if (app_->playlist_manager()->active()->current_item()) { const QUrl url = app_->playlist_manager()->active()->current_item()->Url(); if (url_handlers_.contains(url.scheme())) { // The next track is already being loaded - if (url == loading_async_) - return; + if (url == loading_async_) return; stream_change_type_ = change; HandleLoadResult(url_handlers_[url.scheme()]->LoadNext(url)); @@ -168,8 +161,10 @@ void Player::NextItem(Engine::TrackChangeFlags change) { const PlaylistSequence::RepeatMode repeat_mode = active_playlist->sequence()->repeat_mode(); if (repeat_mode != PlaylistSequence::Repeat_Off) { - if ((repeat_mode == PlaylistSequence::Repeat_Track && nb_errors_received_ >= 3) || - (nb_errors_received_ >= app_->playlist_manager()->active()->proxy()->rowCount())) { + if ((repeat_mode == PlaylistSequence::Repeat_Track && + nb_errors_received_ >= 3) || + (nb_errors_received_ >= + app_->playlist_manager()->active()->proxy()->rowCount())) { // We received too many "Error" state changes: probably looping over a // playlist which contains only unavailable elements: stop now. nb_errors_received_ = 0; @@ -211,13 +206,13 @@ bool Player::HandleStopAfter() { } void Player::TrackEnded() { - if (HandleStopAfter()) - return; + if (HandleStopAfter()) return; if (current_item_ && current_item_->IsLocalLibraryItem() && current_item_->Metadata().id() != -1 && !app_->playlist_manager()->active()->have_incremented_playcount() && - app_->playlist_manager()->active()->get_lastfm_status() != Playlist::LastFM_Seeked) { + app_->playlist_manager()->active()->get_lastfm_status() != + Playlist::LastFM_Seeked) { // The track finished before its scrobble point (30 seconds), so increment // the play count now. app_->playlist_manager()->library_backend()->IncrementPlayCountAsync( @@ -229,42 +224,42 @@ void Player::TrackEnded() { void Player::PlayPause() { switch (engine_->state()) { - case Engine::Paused: - engine_->Unpause(); - break; - - case Engine::Playing: { - // We really shouldn't pause last.fm streams - // Stopping seems like a reasonable thing to do (especially on mac where there - // is no media key for stop). - if (current_item_->options() & PlaylistItem::PauseDisabled) { - Stop(); - } else { - engine_->Pause(); - } - break; - } - - case Engine::Empty: - case Engine::Error: - case Engine::Idle: { - app_->playlist_manager()->SetActivePlaylist(app_->playlist_manager()->current_id()); - if (app_->playlist_manager()->active()->rowCount() == 0) + case Engine::Paused: + engine_->Unpause(); break; - int i = app_->playlist_manager()->active()->current_row(); - if (i == -1) i = app_->playlist_manager()->active()->last_played_row(); - if (i == -1) i = 0; + case Engine::Playing: { + // We really shouldn't pause last.fm streams + // Stopping seems like a reasonable thing to do (especially on mac where + // there + // is no media key for stop). + if (current_item_->options() & PlaylistItem::PauseDisabled) { + Stop(); + } else { + engine_->Pause(); + } + break; + } - PlayAt(i, Engine::First, true); - break; - } + case Engine::Empty: + case Engine::Error: + case Engine::Idle: { + app_->playlist_manager()->SetActivePlaylist( + app_->playlist_manager()->current_id()); + if (app_->playlist_manager()->active()->rowCount() == 0) break; + + int i = app_->playlist_manager()->active()->current_row(); + if (i == -1) i = app_->playlist_manager()->active()->last_played_row(); + if (i == -1) i = 0; + + PlayAt(i, Engine::First, true); + break; + } } } void Player::RestartOrPrevious() { - if (engine_->position_nanosec() < 8*kNsecPerSec) - return Previous(); + if (engine_->position_nanosec() < 8 * kNsecPerSec) return Previous(); SeekTo(0); } @@ -276,12 +271,11 @@ void Player::Stop() { } void Player::StopAfterCurrent() { - app_->playlist_manager()->active()->StopAfter(app_->playlist_manager()->active()->current_row()); + app_->playlist_manager()->active()->StopAfter( + app_->playlist_manager()->active()->current_row()); } -void Player::Previous() { - PreviousItem(Engine::Manual); -} +void Player::Previous() { PreviousItem(Engine::Manual); } void Player::PreviousItem(Engine::TrackChangeFlags change) { const bool ignore_repeat_track = change & Engine::Manual; @@ -304,11 +298,17 @@ void Player::EngineStateChanged(Engine::State state) { } switch (state) { - case Engine::Paused: emit Paused(); break; - case Engine::Playing: emit Playing(); break; + case Engine::Paused: + emit Paused(); + break; + case Engine::Playing: + emit Playing(); + break; case Engine::Error: case Engine::Empty: - case Engine::Idle: emit Stopped(); break; + case Engine::Idle: + emit Stopped(); + break; } last_state_ = state; } @@ -320,18 +320,17 @@ void Player::SetVolume(int value) { settings_.setValue("volume", volume); engine_->SetVolume(volume); - if (volume != old_volume){ + if (volume != old_volume) { emit VolumeChanged(volume); } - } -int Player::GetVolume() const { - return engine_->volume(); -} +int Player::GetVolume() const { return engine_->volume(); } -void Player::PlayAt(int index, Engine::TrackChangeFlags change, bool reshuffle) { - if (change == Engine::Manual && engine_->position_nanosec() != engine_->length_nanosec()) { +void Player::PlayAt(int index, Engine::TrackChangeFlags change, + bool reshuffle) { + if (change == Engine::Manual && + engine_->position_nanosec() != engine_->length_nanosec()) { emit TrackSkipped(current_item_); const QUrl& url = current_item_->Url(); if (url_handlers_.contains(url.scheme())) { @@ -339,15 +338,13 @@ void Player::PlayAt(int index, Engine::TrackChangeFlags change, bool reshuffle) } } - if (current_item_ && - app_->playlist_manager()->active()->has_item_at(index) && + if (current_item_ && app_->playlist_manager()->active()->has_item_at(index) && current_item_->Metadata().IsOnSameAlbum( - app_->playlist_manager()->active()->item_at(index)->Metadata())) { + app_->playlist_manager()->active()->item_at(index)->Metadata())) { change |= Engine::SameAlbum; } - if (reshuffle) - app_->playlist_manager()->active()->ReshuffleIndices(); + if (reshuffle) app_->playlist_manager()->active()->ReshuffleIndices(); app_->playlist_manager()->active()->set_current_row(index); if (app_->playlist_manager()->active()->current_row() == -1) { @@ -360,8 +357,7 @@ void Player::PlayAt(int index, Engine::TrackChangeFlags change, bool reshuffle) if (url_handlers_.contains(url.scheme())) { // It's already loading - if (url == loading_async_) - return; + if (url == loading_async_) return; stream_change_type_ = change; HandleLoadResult(url_handlers_[url.scheme()]->StartLoading(url)); @@ -391,21 +387,23 @@ void Player::CurrentMetadataChanged(const Song& metadata) { void Player::SeekTo(int seconds) { const qint64 length_nanosec = engine_->length_nanosec(); - + // If the length is 0 then either there is no song playing, or the song isn't // seekable. if (length_nanosec <= 0) { return; } - - const qint64 nanosec = qBound(0ll, qint64(seconds) * kNsecPerSec, - length_nanosec); + + const qint64 nanosec = + qBound(0ll, qint64(seconds) * kNsecPerSec, length_nanosec); engine_->Seek(nanosec); // If we seek the track we don't want to submit it to last.fm qLog(Info) << "Track seeked to" << nanosec << "ns - not scrobbling"; - if (app_->playlist_manager()->active()->get_lastfm_status() == Playlist::LastFM_New) { - app_->playlist_manager()->active()->set_lastfm_status(Playlist::LastFM_Seeked); + if (app_->playlist_manager()->active()->get_lastfm_status() == + Playlist::LastFM_New) { + app_->playlist_manager()->active()->set_lastfm_status( + Playlist::LastFM_Seeked); } emit Seeked(nanosec / 1000); @@ -421,8 +419,7 @@ void Player::SeekBackward() { void Player::EngineMetadataReceived(const Engine::SimpleMetaBundle& bundle) { PlaylistItemPtr item = app_->playlist_manager()->active()->current_item(); - if (!item) - return; + if (!item) return; Engine::SimpleMetaBundle bundle_copy = bundle; @@ -434,10 +431,10 @@ void Player::EngineMetadataReceived(const Engine::SimpleMetaBundle& bundle) { const int space_dash_pos = bundle_copy.title.indexOf(" - "); if (space_dash_pos != -1) { bundle_copy.artist = bundle_copy.title.left(space_dash_pos).trimmed(); - bundle_copy.title = bundle_copy.title.mid(space_dash_pos + 3).trimmed(); + bundle_copy.title = bundle_copy.title.mid(space_dash_pos + 3).trimmed(); } else { bundle_copy.artist = bundle_copy.title.left(dash_pos).trimmed(); - bundle_copy.title = bundle_copy.title.mid(dash_pos + 1).trimmed(); + bundle_copy.title = bundle_copy.title.mid(dash_pos + 1).trimmed(); } } @@ -445,8 +442,7 @@ void Player::EngineMetadataReceived(const Engine::SimpleMetaBundle& bundle) { song.MergeFromSimpleMetaBundle(bundle_copy); // Ignore useless metadata - if (song.title().isEmpty() && song.artist().isEmpty()) - return; + if (song.title().isEmpty() && song.artist().isEmpty()) return; app_->playlist_manager()->active()->SetStreamMetadata(item->Url(), song); } @@ -468,9 +464,7 @@ void Player::Mute() { } } -void Player::Pause() { - engine_->Pause(); -} +void Player::Pause() { engine_->Pause(); } void Player::Play() { switch (GetState()) { @@ -487,13 +481,11 @@ void Player::Play() { } void Player::ShowOSD() { - if (current_item_) - emit ForceShowOSD(current_item_->Metadata(), false); + if (current_item_) emit ForceShowOSD(current_item_->Metadata(), false); } void Player::TogglePrettyOSD() { - if (current_item_) - emit ForceShowOSD(current_item_->Metadata(), true); + if (current_item_) emit ForceShowOSD(current_item_->Metadata(), true); } void Player::TrackAboutToEnd() { @@ -509,11 +501,13 @@ void Player::TrackAboutToEnd() { } } - const bool has_next_row = app_->playlist_manager()->active()->next_row() != -1; + const bool has_next_row = + app_->playlist_manager()->active()->next_row() != -1; PlaylistItemPtr next_item; if (has_next_row) { - next_item = app_->playlist_manager()->active()->item_at(app_->playlist_manager()->active()->next_row()); + next_item = app_->playlist_manager()->active()->item_at( + app_->playlist_manager()->active()->next_row()); } if (engine_->is_autocrossfade_enabled()) { @@ -522,15 +516,12 @@ void Player::TrackAboutToEnd() { // But, if there's no next track and we don't want to fade out, then do // nothing and just let the track finish to completion. - if (!engine_->is_fadeout_enabled() && !has_next_row) - return; + if (!engine_->is_fadeout_enabled() && !has_next_row) return; // If the next track is on the same album (or same cue file), and the // user doesn't want to crossfade between tracks on the same album, then // don't do this automatic crossfading. - if (engine_->crossfade_same_album() || - !has_next_row || - !next_item || + if (engine_->crossfade_same_album() || !has_next_row || !next_item || !current_item_->Metadata().IsOnSameAlbum(next_item->Metadata())) { TrackEnded(); return; @@ -539,8 +530,7 @@ void Player::TrackAboutToEnd() { // Crossfade is off, so start preloading the next track so we don't get a // gap between songs. - if (!has_next_row || !next_item) - return; + if (!has_next_row || !next_item) return; QUrl url = next_item->Url(); @@ -548,16 +538,16 @@ void Player::TrackAboutToEnd() { if (url_handlers_.contains(url.scheme())) { UrlHandler::LoadResult result = url_handlers_[url.scheme()]->LoadNext(url); switch (result.type_) { - case UrlHandler::LoadResult::NoMoreTracks: - return; + case UrlHandler::LoadResult::NoMoreTracks: + return; - case UrlHandler::LoadResult::WillLoadAsynchronously: - loading_async_ = url; - return; + case UrlHandler::LoadResult::WillLoadAsynchronously: + loading_async_ = url; + return; - case UrlHandler::LoadResult::TrackAvailable: - url = result.media_url_; - break; + case UrlHandler::LoadResult::TrackAvailable: + url = result.media_url_; + break; } } engine_->StartPreloading(url, next_item->Metadata().has_cue(), @@ -588,7 +578,8 @@ void Player::RegisterUrlHandler(UrlHandler* handler) { qLog(Info) << "Registered URL handler for" << scheme; url_handlers_.insert(scheme, handler); - connect(handler, SIGNAL(destroyed(QObject*)), SLOT(UrlHandlerDestroyed(QObject*))); + connect(handler, SIGNAL(destroyed(QObject*)), + SLOT(UrlHandlerDestroyed(QObject*))); connect(handler, SIGNAL(AsyncLoadComplete(UrlHandler::LoadResult)), SLOT(HandleLoadResult(UrlHandler::LoadResult))); } @@ -596,20 +587,22 @@ void Player::RegisterUrlHandler(UrlHandler* handler) { void Player::UnregisterUrlHandler(UrlHandler* handler) { const QString scheme = url_handlers_.key(handler); if (scheme.isEmpty()) { - qLog(Warning) << "Tried to unregister a URL handler for" << handler->scheme() - << "that wasn't registered"; + qLog(Warning) << "Tried to unregister a URL handler for" + << handler->scheme() << "that wasn't registered"; return; } qLog(Info) << "Unregistered URL handler for" << scheme; url_handlers_.remove(scheme); - disconnect(handler, SIGNAL(destroyed(QObject*)), this, SLOT(UrlHandlerDestroyed(QObject*))); - disconnect(handler, SIGNAL(AsyncLoadComplete(UrlHandler::LoadResult)), - this, SLOT(HandleLoadResult(UrlHandler::LoadResult))); + disconnect(handler, SIGNAL(destroyed(QObject*)), this, + SLOT(UrlHandlerDestroyed(QObject*))); + disconnect(handler, SIGNAL(AsyncLoadComplete(UrlHandler::LoadResult)), this, + SLOT(HandleLoadResult(UrlHandler::LoadResult))); } const UrlHandler* Player::HandlerForUrl(const QUrl& url) const { - QMap::const_iterator it = url_handlers_.constFind(url.scheme()); + QMap::const_iterator it = + url_handlers_.constFind(url.scheme()); if (it == url_handlers_.constEnd()) { return nullptr; } diff --git a/src/core/player.h b/src/core/player.h index c8df58c98..257d11256 100644 --- a/src/core/player.h +++ b/src/core/player.h @@ -33,11 +33,10 @@ class Application; class LastFMService; - class PlayerInterface : public QObject { Q_OBJECT -public: + public: PlayerInterface(QObject* parent = 0) : QObject(parent) {} virtual EngineBase* engine() const = 0; @@ -50,11 +49,12 @@ public: virtual void RegisterUrlHandler(UrlHandler* handler) = 0; virtual void UnregisterUrlHandler(UrlHandler* handler) = 0; -public slots: + public slots: virtual void ReloadSettings() = 0; // Manual track change to the specified track - virtual void PlayAt(int i, Engine::TrackChangeFlags change, bool reshuffle) = 0; + virtual void PlayAt(int i, Engine::TrackChangeFlags change, + bool reshuffle) = 0; // If there's currently a song playing, pause it, otherwise play the track // that was playing last, or the first one on the playlist @@ -93,18 +93,20 @@ signals: // Emitted when there's a manual change to the current's track position. void Seeked(qlonglong microseconds); - // Emitted when Player has processed a request to play another song. This contains + // Emitted when Player has processed a request to play another song. This + // contains // the URL of the song and a flag saying whether it was able to play the song. void SongChangeRequestProcessed(const QUrl& url, bool valid); - // The toggle parameter is true when user requests to toggle visibility for Pretty OSD + // The toggle parameter is true when user requests to toggle visibility for + // Pretty OSD void ForceShowOSD(Song, bool toogle); }; class Player : public PlayerInterface { Q_OBJECT -public: + public: Player(Application* app, QObject* parent = 0); ~Player(); @@ -122,7 +124,7 @@ public: const UrlHandler* HandlerForUrl(const QUrl& url) const; -public slots: + public slots: void ReloadSettings(); void PlayAt(int i, Engine::TrackChangeFlags change, bool reshuffle); @@ -188,4 +190,4 @@ public slots: int volume_before_mute_; }; -#endif // PLAYER_H +#endif // PLAYER_H diff --git a/src/core/potranslator.h b/src/core/potranslator.h index dbb81cb87..e6077173b 100644 --- a/src/core/potranslator.h +++ b/src/core/potranslator.h @@ -26,11 +26,12 @@ class PoTranslator : public QTranslator { public: - QString translate(const char* context, const char* source_text, const char* disambiguation = 0) const { + QString translate(const char* context, const char* source_text, + const char* disambiguation = 0) const { QString ret = QTranslator::translate(context, source_text, disambiguation); if (!ret.isEmpty()) return ret; return QTranslator::translate(NULL, source_text, disambiguation); } }; -#endif // POTRANSLATOR_H +#endif // POTRANSLATOR_H diff --git a/src/core/qhash_qurl.h b/src/core/qhash_qurl.h index f7bdeada1..bc8a9c79d 100644 --- a/src/core/qhash_qurl.h +++ b/src/core/qhash_qurl.h @@ -21,9 +21,7 @@ #include #if QT_VERSION < 0x040700 -inline uint qHash(const QUrl& url) { - return qHash(url.toEncoded()); -} +inline uint qHash(const QUrl& url) { return qHash(url.toEncoded()); } #endif -#endif // QHASH_QURL_H +#endif // QHASH_QURL_H diff --git a/src/core/qtfslistener.cpp b/src/core/qtfslistener.cpp index 9a94a0c32..4c5802dda 100644 --- a/src/core/qtfslistener.cpp +++ b/src/core/qtfslistener.cpp @@ -20,15 +20,12 @@ #include QtFSListener::QtFSListener(QObject* parent) - : FileSystemWatcherInterface(parent), - watcher_(this) { + : FileSystemWatcherInterface(parent), watcher_(this) { connect(&watcher_, SIGNAL(directoryChanged(const QString&)), - SIGNAL(PathChanged(const QString&))); + SIGNAL(PathChanged(const QString&))); } -void QtFSListener::AddPath(const QString& path) { - watcher_.addPath(path); -} +void QtFSListener::AddPath(const QString& path) { watcher_.addPath(path); } void QtFSListener::RemovePath(const QString& path) { watcher_.removePath(path); diff --git a/src/core/qtfslistener.h b/src/core/qtfslistener.h index dd84ca5c6..8800e9bf6 100644 --- a/src/core/qtfslistener.h +++ b/src/core/qtfslistener.h @@ -32,7 +32,6 @@ class QtFSListener : public FileSystemWatcherInterface { private: QFileSystemWatcher watcher_; - }; #endif diff --git a/src/core/qxtglobalshortcutbackend.cpp b/src/core/qxtglobalshortcutbackend.cpp index 583bd6045..08f048b35 100644 --- a/src/core/qxtglobalshortcutbackend.cpp +++ b/src/core/qxtglobalshortcutbackend.cpp @@ -23,14 +23,13 @@ #include #include -QxtGlobalShortcutBackend::QxtGlobalShortcutBackend(GlobalShortcuts *parent) - : GlobalShortcutBackend(parent) -{ -} +QxtGlobalShortcutBackend::QxtGlobalShortcutBackend(GlobalShortcuts* parent) + : GlobalShortcutBackend(parent) {} bool QxtGlobalShortcutBackend::DoRegister() { qLog(Debug) << "registering"; - foreach (const GlobalShortcuts::Shortcut& shortcut, manager_->shortcuts().values()) { + foreach(const GlobalShortcuts::Shortcut & shortcut, + manager_->shortcuts().values()) { AddShortcut(shortcut.action); } @@ -38,8 +37,7 @@ bool QxtGlobalShortcutBackend::DoRegister() { } void QxtGlobalShortcutBackend::AddShortcut(QAction* action) { - if (action->shortcut().isEmpty()) - return; + if (action->shortcut().isEmpty()) return; QxtGlobalShortcut* shortcut = new QxtGlobalShortcut(action->shortcut(), this); connect(shortcut, SIGNAL(activated()), action, SLOT(trigger())); diff --git a/src/core/qxtglobalshortcutbackend.h b/src/core/qxtglobalshortcutbackend.h index 0a6447c8c..4a51f840e 100644 --- a/src/core/qxtglobalshortcutbackend.h +++ b/src/core/qxtglobalshortcutbackend.h @@ -23,16 +23,16 @@ class QxtGlobalShortcut; class QxtGlobalShortcutBackend : public GlobalShortcutBackend { -public: + public: QxtGlobalShortcutBackend(GlobalShortcuts* parent = 0); -protected: + protected: bool DoRegister(); void DoUnregister(); -private: + private: void AddShortcut(QAction* action); QList shortcuts_; }; -#endif // QXTGLOBALSHORTCUTBACKEND_H +#endif // QXTGLOBALSHORTCUTBACKEND_H diff --git a/src/core/scoped_cftyperef.h b/src/core/scoped_cftyperef.h index b516de217..57d817d5f 100644 --- a/src/core/scoped_cftyperef.h +++ b/src/core/scoped_cftyperef.h @@ -17,41 +17,29 @@ // caller must own the object it gives to ScopedCFTypeRef<>, and relinquishes // an ownership claim to that object. ScopedCFTypeRef<> does not call // CFRetain(). -template +template class ScopedCFTypeRef { public: typedef CFT element_type; - explicit ScopedCFTypeRef(CFT object = NULL) - : object_(object) { - } + explicit ScopedCFTypeRef(CFT object = NULL) : object_(object) {} ~ScopedCFTypeRef() { - if (object_) - CFRelease(object_); + if (object_) CFRelease(object_); } void reset(CFT object = NULL) { - if (object_) - CFRelease(object_); + if (object_) CFRelease(object_); object_ = object; } - bool operator==(CFT that) const { - return object_ == that; - } + bool operator==(CFT that) const { return object_ == that; } - bool operator!=(CFT that) const { - return object_ != that; - } + bool operator!=(CFT that) const { return object_ != that; } - operator CFT() const { - return object_; - } + operator CFT() const { return object_; } - CFT get() const { - return object_; - } + CFT get() const { return object_; } void swap(ScopedCFTypeRef& that) { CFT temp = that.object_; diff --git a/src/core/scoped_nsautorelease_pool.h b/src/core/scoped_nsautorelease_pool.h index fb8a79d56..82f1ff9a2 100644 --- a/src/core/scoped_nsautorelease_pool.h +++ b/src/core/scoped_nsautorelease_pool.h @@ -9,7 +9,7 @@ #if defined(__OBJC__) @class NSAutoreleasePool; -#else // __OBJC__ +#else // __OBJC__ class NSAutoreleasePool; #endif // __OBJC__ @@ -28,6 +28,7 @@ class ScopedNSAutoreleasePool { // Only use then when you're certain the items currently in the pool are // no longer needed. void Recycle(); + private: NSAutoreleasePool* autorelease_pool_; diff --git a/src/core/scoped_nsobject.h b/src/core/scoped_nsobject.h index cd8271399..0b6f07be9 100644 --- a/src/core/scoped_nsobject.h +++ b/src/core/scoped_nsobject.h @@ -23,16 +23,12 @@ // scoped_nsautorelease_pool.h instead. // We check for bad uses of scoped_nsobject and NSAutoreleasePool at compile // time with a template specialization (see below). -template +template class scoped_nsobject { public: - explicit scoped_nsobject(NST* object = nil) - : object_(object) { - } + explicit scoped_nsobject(NST* object = nil) : object_(object) {} - ~scoped_nsobject() { - [object_ release]; - } + ~scoped_nsobject() { [object_ release]; } void reset(NST* object = nil) { // We intentionally do not check that object != object_ as the caller must @@ -47,13 +43,9 @@ class scoped_nsobject { bool operator==(NST* that) const { return object_ == that; } bool operator!=(NST* that) const { return object_ != that; } - operator NST*() const { - return object_; - } + operator NST*() const { return object_; } - NST* get() const { - return object_; - } + NST* get() const { return object_; } void swap(scoped_nsobject& that) { NST* temp = that.object_; @@ -92,18 +84,13 @@ bool operator!=(C* p1, const scoped_nsobject& p2) { return p1 != p2.get(); } - // Specialization to make scoped_nsobject work. -template<> +template <> class scoped_nsobject { public: - explicit scoped_nsobject(id object = nil) - : object_(object) { - } + explicit scoped_nsobject(id object = nil) : object_(object) {} - ~scoped_nsobject() { - [object_ release]; - } + ~scoped_nsobject() { [object_ release]; } void reset(id object = nil) { // We intentionally do not check that object != object_ as the caller must @@ -118,13 +105,9 @@ class scoped_nsobject { bool operator==(id that) const { return object_ == that; } bool operator!=(id that) const { return object_ != that; } - operator id() const { - return object_; - } + operator id() const { return object_; } - id get() const { - return object_; - } + id get() const { return object_; } void swap(scoped_nsobject& that) { id temp = that.object_; @@ -150,7 +133,7 @@ class scoped_nsobject { // Do not use scoped_nsobject for NSAutoreleasePools, use // ScopedNSAutoreleasePool instead. This is a compile time check. See details // at top of header. -template<> +template <> class scoped_nsobject { private: explicit scoped_nsobject(NSAutoreleasePool* object = nil); diff --git a/src/core/scopedgobject.h b/src/core/scopedgobject.h index 260a8783c..1fcad5573 100644 --- a/src/core/scopedgobject.h +++ b/src/core/scopedgobject.h @@ -22,49 +22,44 @@ #include - template class ScopedGObject { -public: + public: ScopedGObject() : object_(NULL) {} explicit ScopedGObject(const ScopedGObject& other) : object_(NULL) { reset(other.object_); } - ~ScopedGObject() { - reset(); - } + ~ScopedGObject() { reset(); } - ScopedGObject& operator =(const ScopedGObject& other) { + ScopedGObject& operator=(const ScopedGObject& other) { reset(other.object_); return *this; } void reset(T* new_object = NULL) { - if (new_object) - g_object_ref(new_object); + if (new_object) g_object_ref(new_object); reset_without_add(new_object); } void reset_without_add(T* new_object = NULL) { - if (object_) - g_object_unref(object_); + if (object_) g_object_unref(object_); object_ = new_object; } T* get() const { return object_; } operator T*() const { return get(); } - T* operator *() const { return get(); } + T* operator*() const { return get(); } operator bool() const { return get(); } - bool operator ==(const ScopedGObject& other) const { + bool operator==(const ScopedGObject& other) const { return object_ == other.object_; } -private: + private: T* object_; }; -#endif // SCOPEDGOBJECT_H +#endif // SCOPEDGOBJECT_H diff --git a/src/core/scopedtransaction.cpp b/src/core/scopedtransaction.cpp index 5a2e8b11b..b6240b40b 100644 --- a/src/core/scopedtransaction.cpp +++ b/src/core/scopedtransaction.cpp @@ -22,9 +22,7 @@ #include ScopedTransaction::ScopedTransaction(QSqlDatabase* db) - : db_(db), - pending_(true) -{ + : db_(db), pending_(true) { db->transaction(); } diff --git a/src/core/scopedtransaction.h b/src/core/scopedtransaction.h index ded08d64f..b084411a4 100644 --- a/src/core/scopedtransaction.h +++ b/src/core/scopedtransaction.h @@ -37,4 +37,4 @@ class ScopedTransaction : boost::noncopyable { bool pending_; }; -#endif // SCOPEDTRANSACTION_H +#endif // SCOPEDTRANSACTION_H diff --git a/src/core/settingsprovider.cpp b/src/core/settingsprovider.cpp index e39d5c2ed..b4fc3b9f6 100644 --- a/src/core/settingsprovider.cpp +++ b/src/core/settingsprovider.cpp @@ -17,26 +17,23 @@ #include "settingsprovider.h" -SettingsProvider::SettingsProvider() { -} +SettingsProvider::SettingsProvider() {} -DefaultSettingsProvider::DefaultSettingsProvider() { -} +DefaultSettingsProvider::DefaultSettingsProvider() {} -void DefaultSettingsProvider::set_group(const char *group) { - while (!backend_.group().isEmpty()) - backend_.endGroup(); +void DefaultSettingsProvider::set_group(const char* group) { + while (!backend_.group().isEmpty()) backend_.endGroup(); backend_.beginGroup(group); } -QVariant DefaultSettingsProvider::value( - const QString &key, const QVariant &default_value) const { +QVariant DefaultSettingsProvider::value(const QString& key, + const QVariant& default_value) const { return backend_.value(key, default_value); } -void DefaultSettingsProvider::setValue( - const QString &key, const QVariant &value) { +void DefaultSettingsProvider::setValue(const QString& key, + const QVariant& value) { backend_.setValue(key, value); } @@ -52,6 +49,4 @@ void DefaultSettingsProvider::setArrayIndex(int i) { backend_.setArrayIndex(i); } -void DefaultSettingsProvider::endArray() { - backend_.endArray(); -} +void DefaultSettingsProvider::endArray() { backend_.endArray(); } diff --git a/src/core/settingsprovider.h b/src/core/settingsprovider.h index 475ca3fc1..ef6ef6585 100644 --- a/src/core/settingsprovider.h +++ b/src/core/settingsprovider.h @@ -55,4 +55,4 @@ class DefaultSettingsProvider : public SettingsProvider { QSettings backend_; }; -#endif // SETTINGSPROVIDER_H +#endif // SETTINGSPROVIDER_H diff --git a/src/core/signalchecker.cpp b/src/core/signalchecker.cpp index 8496c49f5..c2710ef1a 100644 --- a/src/core/signalchecker.cpp +++ b/src/core/signalchecker.cpp @@ -19,16 +19,13 @@ #include "core/logging.h" -bool CheckedGConnect( - gpointer source, - const char* signal, - GCallback callback, - gpointer data, - const int callback_param_count) { +bool CheckedGConnect(gpointer source, const char* signal, GCallback callback, + gpointer data, const int callback_param_count) { guint signal_id = 0; GQuark detail = 0; - if (!g_signal_parse_name(signal, G_OBJECT_TYPE(source), &signal_id, &detail, false)) { + if (!g_signal_parse_name(signal, G_OBJECT_TYPE(source), &signal_id, &detail, + false)) { qFatal("Connecting to invalid signal: %s", signal); return false; } diff --git a/src/core/signalchecker.h b/src/core/signalchecker.h index aacfde5f7..224513e33 100644 --- a/src/core/signalchecker.h +++ b/src/core/signalchecker.h @@ -24,16 +24,14 @@ #include // Do not call this directly, use CHECKED_GCONNECT instead. -bool CheckedGConnect( - gpointer source, - const char* signal, - GCallback callback, - gpointer data, - const int callback_param_count); +bool CheckedGConnect(gpointer source, const char* signal, GCallback callback, + gpointer data, const int callback_param_count); -#define FUNCTION_ARITY(callback) boost::function_types::function_arity::value +#define FUNCTION_ARITY(callback) \ + boost::function_types::function_arity::value -#define CHECKED_GCONNECT(source, signal, callback, data) \ - CheckedGConnect(source, signal, G_CALLBACK(callback), data, FUNCTION_ARITY(callback)); +#define CHECKED_GCONNECT(source, signal, callback, data) \ + CheckedGConnect(source, signal, G_CALLBACK(callback), data, \ + FUNCTION_ARITY(callback)); #endif // SIGNALCHECKER_H diff --git a/src/core/simpletreeitem.h b/src/core/simpletreeitem.h index b1efc1baa..95263f3a1 100644 --- a/src/core/simpletreeitem.h +++ b/src/core/simpletreeitem.h @@ -26,7 +26,7 @@ template class SimpleTreeItem { public: - SimpleTreeItem(int _type, SimpleTreeModel* _model); // For the root item + SimpleTreeItem(int _type, SimpleTreeModel* _model); // For the root item SimpleTreeItem(int _type, const QString& _key, T* _parent = NULL); SimpleTreeItem(int _type, T* _parent = NULL); virtual ~SimpleTreeItem(); @@ -39,7 +39,9 @@ class SimpleTreeItem { void Delete(int child_row); T* ChildByKey(const QString& key) const; - QString DisplayText() const { return display_text.isNull() ? key : display_text; } + QString DisplayText() const { + return display_text.isNull() ? key : display_text; + } QString SortText() const { return sort_text.isNull() ? key : sort_text; } int type; @@ -59,24 +61,21 @@ class SimpleTreeItem { template SimpleTreeItem::SimpleTreeItem(int _type, SimpleTreeModel* _model) - : type(_type), - row(0), - lazy_loaded(true), - parent(NULL), - child_model(NULL), - model(_model) -{ -} + : type(_type), + row(0), + lazy_loaded(true), + parent(NULL), + child_model(NULL), + model(_model) {} template SimpleTreeItem::SimpleTreeItem(int _type, const QString& _key, T* _parent) - : type(_type), - key(_key), - lazy_loaded(false), - parent(_parent), - child_model(NULL), - model(_parent ? _parent->model : NULL) -{ + : type(_type), + key(_key), + lazy_loaded(false), + parent(_parent), + child_model(NULL), + model(_parent ? _parent->model : NULL) { if (parent) { row = parent->children.count(); parent->children << static_cast(this); @@ -85,19 +84,17 @@ SimpleTreeItem::SimpleTreeItem(int _type, const QString& _key, T* _parent) template SimpleTreeItem::SimpleTreeItem(int _type, T* _parent) - : type(_type), - lazy_loaded(false), - parent(_parent), - child_model(NULL), - model(_parent ? _parent->model : NULL) -{ + : type(_type), + lazy_loaded(false), + parent(_parent), + child_model(NULL), + model(_parent ? _parent->model : NULL) { if (parent) { row = parent->children.count(); parent->children << static_cast(this); } } - template void SimpleTreeItem::InsertNotify(T* _parent) { parent = _parent; @@ -115,8 +112,7 @@ void SimpleTreeItem::DeleteNotify(int child_row) { delete children.takeAt(child_row); // Adjust row numbers of those below it :( - for (int i=child_row ; irow --; + for (int i = child_row; i < children.count(); ++i) children[i]->row--; model->EndDelete(); } @@ -147,17 +143,15 @@ void SimpleTreeItem::Delete(int child_row) { delete children.takeAt(child_row); // Adjust row numbers of those below it :( - for (int i=child_row ; irow --; + for (int i = child_row; i < children.count(); ++i) children[i]->row--; } template T* SimpleTreeItem::ChildByKey(const QString& key) const { - foreach (T* child, children) { - if (child->key == key) - return child; + foreach(T * child, children) { + if (child->key == key) return child; } return NULL; } -#endif // SIMPLETREEITEM_H +#endif // SIMPLETREEITEM_H diff --git a/src/core/simpletreemodel.h b/src/core/simpletreemodel.h index 6cc272293..8dc0e3998 100644 --- a/src/core/simpletreemodel.h +++ b/src/core/simpletreemodel.h @@ -30,7 +30,8 @@ class SimpleTreeModel : public QAbstractItemModel { // QAbstractItemModel int columnCount(const QModelIndex& parent) const; - QModelIndex index(int row, int, const QModelIndex& parent = QModelIndex()) const; + QModelIndex index(int row, int, + const QModelIndex& parent = QModelIndex()) const; QModelIndex parent(const QModelIndex& index) const; int rowCount(const QModelIndex& parent) const; bool hasChildren(const QModelIndex& parent) const; @@ -54,35 +55,30 @@ class SimpleTreeModel : public QAbstractItemModel { T* root_; }; - template SimpleTreeModel::SimpleTreeModel(T* root, QObject* parent) - : QAbstractItemModel(parent), - root_(root) -{ -} + : QAbstractItemModel(parent), root_(root) {} template T* SimpleTreeModel::IndexToItem(const QModelIndex& index) const { - if (!index.isValid()) - return root_; + if (!index.isValid()) return root_; return reinterpret_cast(index.internalPointer()); } template QModelIndex SimpleTreeModel::ItemToIndex(T* item) const { - if (!item || !item->parent) - return QModelIndex(); + if (!item || !item->parent) return QModelIndex(); return createIndex(item->row, 0, item); } template -int SimpleTreeModel::columnCount(const QModelIndex &) const { +int SimpleTreeModel::columnCount(const QModelIndex&) const { return 1; } template -QModelIndex SimpleTreeModel::index(int row, int, const QModelIndex& parent) const { +QModelIndex SimpleTreeModel::index(int row, int, + const QModelIndex& parent) const { T* parent_item = IndexToItem(parent); if (!parent_item || row < 0 || parent_item->children.count() <= row) return QModelIndex(); @@ -96,13 +92,13 @@ QModelIndex SimpleTreeModel::parent(const QModelIndex& index) const { } template -int SimpleTreeModel::rowCount(const QModelIndex & parent) const { +int SimpleTreeModel::rowCount(const QModelIndex& parent) const { T* item = IndexToItem(parent); return item->children.count(); } template -bool SimpleTreeModel::hasChildren(const QModelIndex &parent) const { +bool SimpleTreeModel::hasChildren(const QModelIndex& parent) const { T* item = IndexToItem(parent); if (item->lazy_loaded) return !item->children.isEmpty(); @@ -147,9 +143,9 @@ void SimpleTreeModel::EndDelete() { } template - void SimpleTreeModel::EmitDataChanged(T *item) { +void SimpleTreeModel::EmitDataChanged(T* item) { QModelIndex index(ItemToIndex(item)); emit dataChanged(index, index); } -#endif // SIMPLETREEMODEL_H +#endif // SIMPLETREEMODEL_H diff --git a/src/core/song.cpp b/src/core/song.cpp index 0dfce9995..693bbe735 100644 --- a/src/core/song.cpp +++ b/src/core/song.cpp @@ -32,22 +32,22 @@ #include #ifdef HAVE_LIBLASTFM - #include "internet/fixlastfm.h" - #ifdef HAVE_LIBLASTFM1 - #include - #else - #include - #endif +#include "internet/fixlastfm.h" +#ifdef HAVE_LIBLASTFM1 +#include +#else +#include +#endif #endif #include #ifdef HAVE_LIBGPOD -# include +#include #endif #ifdef HAVE_LIBMTP -# include +#include #endif #include "core/application.h" @@ -62,35 +62,71 @@ #include "tagreadermessages.pb.h" #include "widgets/trackslider.h" - -const QStringList Song::kColumns = QStringList() - << "title" << "album" << "artist" << "albumartist" << "composer" << "track" - << "disc" << "bpm" << "year" << "genre" << "comment" << "compilation" - << "bitrate" << "samplerate" << "directory" << "filename" - << "mtime" << "ctime" << "filesize" << "sampler" << "art_automatic" - << "art_manual" << "filetype" << "playcount" << "lastplayed" << "rating" - << "forced_compilation_on" << "forced_compilation_off" - << "effective_compilation" << "skipcount" << "score" << "beginning" << "length" - << "cue_path" << "unavailable" << "effective_albumartist" << "etag" - << "performer" << "grouping"; +const QStringList Song::kColumns = QStringList() << "title" + << "album" + << "artist" + << "albumartist" + << "composer" + << "track" + << "disc" + << "bpm" + << "year" + << "genre" + << "comment" + << "compilation" + << "bitrate" + << "samplerate" + << "directory" + << "filename" + << "mtime" + << "ctime" + << "filesize" + << "sampler" + << "art_automatic" + << "art_manual" + << "filetype" + << "playcount" + << "lastplayed" + << "rating" + << "forced_compilation_on" + << "forced_compilation_off" + << "effective_compilation" + << "skipcount" + << "score" + << "beginning" + << "length" + << "cue_path" + << "unavailable" + << "effective_albumartist" + << "etag" + << "performer" + << "grouping"; const QString Song::kColumnSpec = Song::kColumns.join(", "); -const QString Song::kBindSpec = Utilities::Prepend(":", Song::kColumns).join(", "); -const QString Song::kUpdateSpec = Utilities::Updateify(Song::kColumns).join(", "); +const QString Song::kBindSpec = + Utilities::Prepend(":", Song::kColumns).join(", "); +const QString Song::kUpdateSpec = + Utilities::Updateify(Song::kColumns).join(", "); - -const QStringList Song::kFtsColumns = QStringList() - << "ftstitle" << "ftsalbum" << "ftsartist" << "ftsalbumartist" - << "ftscomposer" << "ftsperformer" << "ftsgrouping" << "ftsgenre" << "ftscomment"; +const QStringList Song::kFtsColumns = QStringList() << "ftstitle" + << "ftsalbum" + << "ftsartist" + << "ftsalbumartist" + << "ftscomposer" + << "ftsperformer" + << "ftsgrouping" + << "ftsgenre" + << "ftscomment"; const QString Song::kFtsColumnSpec = Song::kFtsColumns.join(", "); -const QString Song::kFtsBindSpec = Utilities::Prepend(":", Song::kFtsColumns).join(", "); -const QString Song::kFtsUpdateSpec = Utilities::Updateify(Song::kFtsColumns).join(", "); +const QString Song::kFtsBindSpec = + Utilities::Prepend(":", Song::kFtsColumns).join(", "); +const QString Song::kFtsUpdateSpec = + Utilities::Updateify(Song::kFtsColumns).join(", "); const QString Song::kManuallyUnsetCover = "(unset)"; const QString Song::kEmbeddedCover = "(embedded)"; - struct Song::Private : public QSharedData { Private(); @@ -110,12 +146,12 @@ struct Song::Private : public QSharedData { int year_; QString genre_; QString comment_; - bool compilation_; // From the file tag - bool sampler_; // From the library scanner - bool forced_compilation_on_; // Set by the user - bool forced_compilation_off_; // Set by the user + bool compilation_; // From the file tag + bool sampler_; // From the library scanner + bool forced_compilation_on_; // Set by the user + bool forced_compilation_off_; // Set by the user - // A unique album ID + // A unique album ID // Used to distinguish between albums from providers that have multiple // versions of a given album with the same title (e.g. Spotify). // This is never persisted, it is only stored temporarily for global search @@ -156,14 +192,15 @@ struct Song::Private : public QSharedData { QString cue_path_; // Filenames to album art for this song. - QString art_automatic_; // Guessed by LibraryWatcher - QString art_manual_; // Set by the user - should take priority + QString art_automatic_; // Guessed by LibraryWatcher + QString art_manual_; // Set by the user - should take priority QImage image_; // Whether this song was loaded from a file using taglib. bool init_from_file_; - // Whether our encoding guesser thinks these tags might be incorrectly encoded. + // Whether our encoding guesser thinks these tags might be incorrectly + // encoded. bool suspicious_tags_; // Whether the song does not exist on the file system anymore, but is still @@ -173,54 +210,43 @@ struct Song::Private : public QSharedData { QString etag_; }; - Song::Private::Private() - : valid_(false), - id_(-1), - track_(-1), - disc_(-1), - bpm_(-1), - year_(-1), - compilation_(false), - sampler_(false), - forced_compilation_on_(false), - forced_compilation_off_(false), - album_id_(-1), - rating_(-1.0), - playcount_(0), - skipcount_(0), - lastplayed_(-1), - score_(0), - beginning_(0), - end_(-1), - bitrate_(-1), - samplerate_(-1), - directory_id_(-1), - mtime_(-1), - ctime_(-1), - filesize_(-1), - filetype_(Type_Unknown), - init_from_file_(false), - suspicious_tags_(false), - unavailable_(false) -{ -} + : valid_(false), + id_(-1), + track_(-1), + disc_(-1), + bpm_(-1), + year_(-1), + compilation_(false), + sampler_(false), + forced_compilation_on_(false), + forced_compilation_off_(false), + album_id_(-1), + rating_(-1.0), + playcount_(0), + skipcount_(0), + lastplayed_(-1), + score_(0), + beginning_(0), + end_(-1), + bitrate_(-1), + samplerate_(-1), + directory_id_(-1), + mtime_(-1), + ctime_(-1), + filesize_(-1), + filetype_(Type_Unknown), + init_from_file_(false), + suspicious_tags_(false), + unavailable_(false) {} +Song::Song() : d(new Private) {} -Song::Song() - : d(new Private) -{ -} +Song::Song(const Song& other) : d(other.d) {} -Song::Song(const Song &other) - : d(other.d) -{ -} +Song::~Song() {} -Song::~Song() { -} - -Song& Song::operator =(const Song& other) { +Song& Song::operator=(const Song& other) { d = other.d; return *this; } @@ -232,8 +258,12 @@ const QString& Song::title() const { return d->title_; } const QString& Song::album() const { return d->album_; } const QString& Song::artist() const { return d->artist_; } const QString& Song::albumartist() const { return d->albumartist_; } -const QString& Song::effective_albumartist() const { return d->albumartist_.isEmpty() ? d->artist_ : d->albumartist_; } -const QString& Song::playlist_albumartist() const { return is_compilation() ? d->albumartist_ : effective_albumartist(); } +const QString& Song::effective_albumartist() const { + return d->albumartist_.isEmpty() ? d->artist_ : d->albumartist_; +} +const QString& Song::playlist_albumartist() const { + return is_compilation() ? d->albumartist_ : effective_albumartist(); +} const QString& Song::composer() const { return d->composer_; } const QString& Song::performer() const { return d->performer_; } const QString& Song::grouping() const { return d->grouping_; } @@ -244,8 +274,8 @@ int Song::year() const { return d->year_; } const QString& Song::genre() const { return d->genre_; } const QString& Song::comment() const { return d->comment_; } bool Song::is_compilation() const { - return (d->compilation_ || d->sampler_ || d->forced_compilation_on_) - && ! d->forced_compilation_off_; + return (d->compilation_ || d->sampler_ || d->forced_compilation_on_) && + !d->forced_compilation_off_; } float Song::rating() const { return d->rating_; } int Song::playcount() const { return d->playcount_; } @@ -272,9 +302,13 @@ bool Song::is_cdda() const { return d->filetype_ == Type_Cdda; } const QString& Song::art_automatic() const { return d->art_automatic_; } const QString& Song::art_manual() const { return d->art_manual_; } const QString& Song::etag() const { return d->etag_; } -bool Song::has_manually_unset_cover() const { return d->art_manual_ == kManuallyUnsetCover; } +bool Song::has_manually_unset_cover() const { + return d->art_manual_ == kManuallyUnsetCover; +} void Song::manually_unset_cover() { d->art_manual_ = kManuallyUnsetCover; } -bool Song::has_embedded_cover() const { return d->art_automatic_ == kEmbeddedCover; } +bool Song::has_embedded_cover() const { + return d->art_automatic_ == kEmbeddedCover; +} void Song::set_embedded_cover() { d->art_automatic_ = kEmbeddedCover; } const QImage& Song::image() const { return d->image_; } void Song::set_id(int id) { d->id_ = id; } @@ -308,7 +342,9 @@ void Song::set_art_automatic(const QString& v) { d->art_automatic_ = v; } void Song::set_art_manual(const QString& v) { d->art_manual_ = v; } void Song::set_image(const QImage& i) { d->image_ = i; } void Song::set_forced_compilation_on(bool v) { d->forced_compilation_on_ = v; } -void Song::set_forced_compilation_off(bool v) { d->forced_compilation_off_ = v; } +void Song::set_forced_compilation_off(bool v) { + d->forced_compilation_off_ = v; +} void Song::set_rating(float v) { d->rating_ = v; } void Song::set_playcount(int v) { d->playcount_ = v; } void Song::set_skipcount(int v) { d->skipcount_ = v; } @@ -320,7 +356,8 @@ void Song::set_etag(const QString& etag) { d->etag_ = etag; } void Song::set_url(const QUrl& v) { if (Application::kIsPortable) { - QUrl base = QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + "/"); + QUrl base = + QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + "/"); d->url_ = base.resolved(v); } else { d->url_ = v; @@ -336,21 +373,35 @@ QString Song::JoinSpec(const QString& table) { QString Song::TextForFiletype(FileType type) { switch (type) { - case Song::Type_Asf: return QObject::tr("Windows Media audio"); - case Song::Type_Flac: return QObject::tr("Flac"); - case Song::Type_Mp4: return QObject::tr("MP4 AAC"); - case Song::Type_Mpc: return QObject::tr("MPC"); - case Song::Type_Mpeg: return QObject::tr("MP3"); // Not technically correct - case Song::Type_OggFlac: return QObject::tr("Ogg Flac"); - case Song::Type_OggSpeex: return QObject::tr("Ogg Speex"); - case Song::Type_OggVorbis: return QObject::tr("Ogg Vorbis"); - case Song::Type_OggOpus: return QObject::tr("Ogg Opus"); - case Song::Type_Aiff: return QObject::tr("AIFF"); - case Song::Type_Wav: return QObject::tr("Wav"); - case Song::Type_TrueAudio: return QObject::tr("TrueAudio"); - case Song::Type_Cdda: return QObject::tr("CDDA"); + case Song::Type_Asf: + return QObject::tr("Windows Media audio"); + case Song::Type_Flac: + return QObject::tr("Flac"); + case Song::Type_Mp4: + return QObject::tr("MP4 AAC"); + case Song::Type_Mpc: + return QObject::tr("MPC"); + case Song::Type_Mpeg: + return QObject::tr("MP3"); // Not technically correct + case Song::Type_OggFlac: + return QObject::tr("Ogg Flac"); + case Song::Type_OggSpeex: + return QObject::tr("Ogg Speex"); + case Song::Type_OggVorbis: + return QObject::tr("Ogg Vorbis"); + case Song::Type_OggOpus: + return QObject::tr("Ogg Opus"); + case Song::Type_Aiff: + return QObject::tr("AIFF"); + case Song::Type_Wav: + return QObject::tr("Wav"); + case Song::Type_TrueAudio: + return QObject::tr("TrueAudio"); + case Song::Type_Cdda: + return QObject::tr("CDDA"); - case Song::Type_Stream: return QObject::tr("Stream"); + case Song::Type_Stream: + return QObject::tr("Stream"); case Song::Type_Unknown: default: @@ -359,7 +410,8 @@ QString Song::TextForFiletype(FileType type) { } int CompareSongsName(const Song& song1, const Song& song2) { - return song1.PrettyTitleWithArtist().localeAwareCompare(song2.PrettyTitleWithArtist()) < 0; + return song1.PrettyTitleWithArtist().localeAwareCompare( + song2.PrettyTitleWithArtist()) < 0; } void Song::SortSongsListAlphabetically(SongList* songs) { @@ -486,10 +538,10 @@ void Song::InitFromQuery(const SqlRow& q, bool reliable_metadata, int col) { d->valid_ = true; d->init_from_file_ = reliable_metadata; - #define tostr(n) (q.value(n).isNull() ? QString::null : q.value(n).toString()) - #define toint(n) (q.value(n).isNull() ? -1 : q.value(n).toInt()) - #define tolonglong(n) (q.value(n).isNull() ? -1 : q.value(n).toLongLong()) - #define tofloat(n) (q.value(n).isNull() ? -1 : q.value(n).toDouble()) +#define tostr(n) (q.value(n).isNull() ? QString::null : q.value(n).toString()) +#define toint(n) (q.value(n).isNull() ? -1 : q.value(n).toInt()) +#define tolonglong(n) (q.value(n).isNull() ? -1 : q.value(n).toLongLong()) +#define tofloat(n) (q.value(n).isNull() ? -1 : q.value(n).toDouble()) d->id_ = toint(col + 0); d->title_ = tostr(col + 1); @@ -535,7 +587,8 @@ void Song::InitFromQuery(const SqlRow& q, bool reliable_metadata, int col) { // do not move those statements - beginning must be initialized before // length is! - d->beginning_ = q.value(col + 32).isNull() ? 0 : q.value(col + 32).toLongLong(); + d->beginning_ = + q.value(col + 32).isNull() ? 0 : q.value(col + 32).toLongLong(); set_length_nanosec(tolonglong(col + 33)); d->cue_path_ = tostr(col + 34); @@ -549,10 +602,10 @@ void Song::InitFromQuery(const SqlRow& q, bool reliable_metadata, int col) { InitArtManual(); - #undef tostr - #undef toint - #undef tolonglong - #undef tofloat +#undef tostr +#undef toint +#undef tolonglong +#undef tofloat } void Song::InitFromFilePartial(const QString& filename) { @@ -564,9 +617,10 @@ void Song::InitFromFilePartial(const QString& filename) { QFileInfo info(filename); d->basefilename_ = info.fileName(); QString suffix = info.suffix().toLower(); - if (suffix == "mp3" || suffix == "ogg" || suffix == "flac" || suffix == "mpc" - || suffix == "m4a" || suffix == "aac" || suffix == "wma" || suffix == "mp4" - || suffix == "spx" || suffix == "wav" || suffix == "opus") { + if (suffix == "mp3" || suffix == "ogg" || suffix == "flac" || + suffix == "mpc" || suffix == "m4a" || suffix == "aac" || + suffix == "wma" || suffix == "mp4" || suffix == "spx" || + suffix == "wav" || suffix == "opus") { d->valid_ = true; } else { d->valid_ = false; @@ -576,7 +630,8 @@ void Song::InitFromFilePartial(const QString& filename) { void Song::InitArtManual() { // If we don't have an art, check if we have one in the cache if (d->art_manual_.isEmpty() && d->art_automatic_.isEmpty()) { - QString filename(Utilities::Sha1CoverHash(d->artist_, d->album_).toHex() + ".jpg"); + QString filename(Utilities::Sha1CoverHash(d->artist_, d->album_).toHex() + + ".jpg"); QString path(AlbumCoverLoader::ImageCacheDir() + "/" + filename); if (QFile::exists(path)) { d->art_manual_ = path; @@ -596,158 +651,192 @@ void Song::InitFromLastFM(const lastfm::Track& track) { set_length_nanosec(track.duration() * kNsecPerSec); } -#endif // HAVE_LIBLASTFM +#endif // HAVE_LIBLASTFM #ifdef HAVE_LIBGPOD - void Song::InitFromItdb(const Itdb_Track* track, const QString& prefix) { - d->valid_ = true; +void Song::InitFromItdb(const Itdb_Track* track, const QString& prefix) { + d->valid_ = true; - d->title_ = QString::fromUtf8(track->title); - d->album_ = QString::fromUtf8(track->album); - d->artist_ = QString::fromUtf8(track->artist); - d->albumartist_ = QString::fromUtf8(track->albumartist); - d->composer_ = QString::fromUtf8(track->composer); - d->grouping_ = QString::fromUtf8(track->grouping); - d->track_ = track->track_nr; - d->disc_ = track->cd_nr; - d->bpm_ = track->BPM; - d->year_ = track->year; - d->genre_ = QString::fromUtf8(track->genre); - d->comment_ = QString::fromUtf8(track->comment); - d->compilation_ = track->compilation; - set_length_nanosec(track->tracklen * kNsecPerMsec); - d->bitrate_ = track->bitrate; - d->samplerate_ = track->samplerate; - d->mtime_ = track->time_modified; - d->ctime_ = track->time_added; - d->filesize_ = track->size; - d->filetype_ = track->type2 ? Type_Mpeg : Type_Mp4; - d->rating_ = float(track->rating) / 100; // 100 = 20 * 5 stars - d->playcount_ = track->playcount; - d->skipcount_ = track->skipcount; - d->lastplayed_ = track->time_played; + d->title_ = QString::fromUtf8(track->title); + d->album_ = QString::fromUtf8(track->album); + d->artist_ = QString::fromUtf8(track->artist); + d->albumartist_ = QString::fromUtf8(track->albumartist); + d->composer_ = QString::fromUtf8(track->composer); + d->grouping_ = QString::fromUtf8(track->grouping); + d->track_ = track->track_nr; + d->disc_ = track->cd_nr; + d->bpm_ = track->BPM; + d->year_ = track->year; + d->genre_ = QString::fromUtf8(track->genre); + d->comment_ = QString::fromUtf8(track->comment); + d->compilation_ = track->compilation; + set_length_nanosec(track->tracklen * kNsecPerMsec); + d->bitrate_ = track->bitrate; + d->samplerate_ = track->samplerate; + d->mtime_ = track->time_modified; + d->ctime_ = track->time_added; + d->filesize_ = track->size; + d->filetype_ = track->type2 ? Type_Mpeg : Type_Mp4; + d->rating_ = float(track->rating) / 100; // 100 = 20 * 5 stars + d->playcount_ = track->playcount; + d->skipcount_ = track->skipcount; + d->lastplayed_ = track->time_played; - QString filename = QString::fromLocal8Bit(track->ipod_path); - filename.replace(':', '/'); + QString filename = QString::fromLocal8Bit(track->ipod_path); + filename.replace(':', '/'); - if (prefix.contains("://")) { - set_url(QUrl(prefix + filename)); - } else { - set_url(QUrl::fromLocalFile(prefix + filename)); - } - - d->basefilename_ = QFileInfo(filename).fileName(); + if (prefix.contains("://")) { + set_url(QUrl(prefix + filename)); + } else { + set_url(QUrl::fromLocalFile(prefix + filename)); } - void Song::ToItdb(Itdb_Track *track) const { - track->title = strdup(d->title_.toUtf8().constData()); - track->album = strdup(d->album_.toUtf8().constData()); - track->artist = strdup(d->artist_.toUtf8().constData()); - track->albumartist = strdup(d->albumartist_.toUtf8().constData()); - track->composer = strdup(d->composer_.toUtf8().constData()); - track->grouping = strdup(d->grouping_.toUtf8().constData()); - track->track_nr = d->track_; - track->cd_nr = d->disc_; - track->BPM = d->bpm_; - track->year = d->year_; - track->genre = strdup(d->genre_.toUtf8().constData()); - track->comment = strdup(d->comment_.toUtf8().constData()); - track->compilation = d->compilation_; - track->tracklen = length_nanosec() / kNsecPerMsec; - track->bitrate = d->bitrate_; - track->samplerate = d->samplerate_; - track->time_modified = d->mtime_; - track->time_added = d->ctime_; - track->size = d->filesize_; - track->type1 = 0; - track->type2 = d->filetype_ == Type_Mp4 ? 0 : 1; - track->mediatype = 1; // Audio - track->rating = d->rating_ * 100; // 100 = 20 * 5 stars - track->playcount = d->playcount_; - track->skipcount = d->skipcount_; - track->time_played = d->lastplayed_; - } + d->basefilename_ = QFileInfo(filename).fileName(); +} + +void Song::ToItdb(Itdb_Track* track) const { + track->title = strdup(d->title_.toUtf8().constData()); + track->album = strdup(d->album_.toUtf8().constData()); + track->artist = strdup(d->artist_.toUtf8().constData()); + track->albumartist = strdup(d->albumartist_.toUtf8().constData()); + track->composer = strdup(d->composer_.toUtf8().constData()); + track->grouping = strdup(d->grouping_.toUtf8().constData()); + track->track_nr = d->track_; + track->cd_nr = d->disc_; + track->BPM = d->bpm_; + track->year = d->year_; + track->genre = strdup(d->genre_.toUtf8().constData()); + track->comment = strdup(d->comment_.toUtf8().constData()); + track->compilation = d->compilation_; + track->tracklen = length_nanosec() / kNsecPerMsec; + track->bitrate = d->bitrate_; + track->samplerate = d->samplerate_; + track->time_modified = d->mtime_; + track->time_added = d->ctime_; + track->size = d->filesize_; + track->type1 = 0; + track->type2 = d->filetype_ == Type_Mp4 ? 0 : 1; + track->mediatype = 1; // Audio + track->rating = d->rating_ * 100; // 100 = 20 * 5 stars + track->playcount = d->playcount_; + track->skipcount = d->skipcount_; + track->time_played = d->lastplayed_; +} #endif #ifdef HAVE_LIBMTP - void Song::InitFromMTP(const LIBMTP_track_t* track, const QString& host) { - d->valid_ = true; +void Song::InitFromMTP(const LIBMTP_track_t* track, const QString& host) { + d->valid_ = true; - d->title_ = QString::fromUtf8(track->title); - d->artist_ = QString::fromUtf8(track->artist); - d->album_ = QString::fromUtf8(track->album); - d->composer_ = QString::fromUtf8(track->composer); - d->genre_ = QString::fromUtf8(track->genre); - d->url_ = QUrl(QString("mtp://%1/%2").arg(host, track->item_id)); - d->basefilename_ = QString::number(track->item_id); + d->title_ = QString::fromUtf8(track->title); + d->artist_ = QString::fromUtf8(track->artist); + d->album_ = QString::fromUtf8(track->album); + d->composer_ = QString::fromUtf8(track->composer); + d->genre_ = QString::fromUtf8(track->genre); + d->url_ = QUrl(QString("mtp://%1/%2").arg(host, track->item_id)); + d->basefilename_ = QString::number(track->item_id); - d->track_ = track->tracknumber; - set_length_nanosec(track->duration * kNsecPerMsec); - d->samplerate_ = track->samplerate; - d->bitrate_ = track->bitrate; - d->filesize_ = track->filesize; - d->mtime_ = track->modificationdate; - d->ctime_ = track->modificationdate; + d->track_ = track->tracknumber; + set_length_nanosec(track->duration * kNsecPerMsec); + d->samplerate_ = track->samplerate; + d->bitrate_ = track->bitrate; + d->filesize_ = track->filesize; + d->mtime_ = track->modificationdate; + d->ctime_ = track->modificationdate; - d->rating_ = float(track->rating) / 100; - d->playcount_ = track->usecount; + d->rating_ = float(track->rating) / 100; + d->playcount_ = track->usecount; - switch (track->filetype) { - case LIBMTP_FILETYPE_WAV: d->filetype_ = Type_Wav; break; - case LIBMTP_FILETYPE_MP3: d->filetype_ = Type_Mpeg; break; - case LIBMTP_FILETYPE_WMA: d->filetype_ = Type_Asf; break; - case LIBMTP_FILETYPE_OGG: d->filetype_ = Type_OggVorbis; break; - case LIBMTP_FILETYPE_MP4: d->filetype_ = Type_Mp4; break; - case LIBMTP_FILETYPE_AAC: d->filetype_ = Type_Mp4; break; - case LIBMTP_FILETYPE_FLAC: d->filetype_ = Type_OggFlac; break; - case LIBMTP_FILETYPE_MP2: d->filetype_ = Type_Mpeg; break; - case LIBMTP_FILETYPE_M4A: d->filetype_ = Type_Mp4; break; - default: d->filetype_ = Type_Unknown; break; - } + switch (track->filetype) { + case LIBMTP_FILETYPE_WAV: + d->filetype_ = Type_Wav; + break; + case LIBMTP_FILETYPE_MP3: + d->filetype_ = Type_Mpeg; + break; + case LIBMTP_FILETYPE_WMA: + d->filetype_ = Type_Asf; + break; + case LIBMTP_FILETYPE_OGG: + d->filetype_ = Type_OggVorbis; + break; + case LIBMTP_FILETYPE_MP4: + d->filetype_ = Type_Mp4; + break; + case LIBMTP_FILETYPE_AAC: + d->filetype_ = Type_Mp4; + break; + case LIBMTP_FILETYPE_FLAC: + d->filetype_ = Type_OggFlac; + break; + case LIBMTP_FILETYPE_MP2: + d->filetype_ = Type_Mpeg; + break; + case LIBMTP_FILETYPE_M4A: + d->filetype_ = Type_Mp4; + break; + default: + d->filetype_ = Type_Unknown; + break; } +} - void Song::ToMTP(LIBMTP_track_t* track) const { - track->item_id = 0; - track->parent_id = 0; - track->storage_id = 0; +void Song::ToMTP(LIBMTP_track_t* track) const { + track->item_id = 0; + track->parent_id = 0; + track->storage_id = 0; - track->title = strdup(d->title_.toUtf8().constData()); - track->artist = strdup(d->artist_.toUtf8().constData()); - track->album = strdup(d->album_.toUtf8().constData()); - track->composer = strdup(d->composer_.toUtf8().constData()); - track->genre = strdup(d->genre_.toUtf8().constData()); - track->title = strdup(d->title_.toUtf8().constData()); - track->date = nullptr; + track->title = strdup(d->title_.toUtf8().constData()); + track->artist = strdup(d->artist_.toUtf8().constData()); + track->album = strdup(d->album_.toUtf8().constData()); + track->composer = strdup(d->composer_.toUtf8().constData()); + track->genre = strdup(d->genre_.toUtf8().constData()); + track->title = strdup(d->title_.toUtf8().constData()); + track->date = nullptr; - track->filename = strdup(d->basefilename_.toUtf8().constData()); + track->filename = strdup(d->basefilename_.toUtf8().constData()); - track->tracknumber = d->track_; - track->duration = length_nanosec() / kNsecPerMsec; - track->samplerate = d->samplerate_; - track->nochannels = 0; - track->wavecodec = 0; - track->bitrate = d->bitrate_; - track->bitratetype = 0; - track->rating = d->rating_ * 100; - track->usecount = d->playcount_; - track->filesize = d->filesize_; - track->modificationdate = d->mtime_; + track->tracknumber = d->track_; + track->duration = length_nanosec() / kNsecPerMsec; + track->samplerate = d->samplerate_; + track->nochannels = 0; + track->wavecodec = 0; + track->bitrate = d->bitrate_; + track->bitratetype = 0; + track->rating = d->rating_ * 100; + track->usecount = d->playcount_; + track->filesize = d->filesize_; + track->modificationdate = d->mtime_; - switch (d->filetype_) { - case Type_Asf: track->filetype = LIBMTP_FILETYPE_ASF; break; - case Type_Mp4: track->filetype = LIBMTP_FILETYPE_MP4; break; - case Type_Mpeg: track->filetype = LIBMTP_FILETYPE_MP3; break; - case Type_Flac: - case Type_OggFlac: track->filetype = LIBMTP_FILETYPE_FLAC; break; - case Type_OggSpeex: - case Type_OggVorbis: track->filetype = LIBMTP_FILETYPE_OGG; break; - case Type_Wav: track->filetype = LIBMTP_FILETYPE_WAV; break; - default: track->filetype = LIBMTP_FILETYPE_UNDEF_AUDIO; break; - } + switch (d->filetype_) { + case Type_Asf: + track->filetype = LIBMTP_FILETYPE_ASF; + break; + case Type_Mp4: + track->filetype = LIBMTP_FILETYPE_MP4; + break; + case Type_Mpeg: + track->filetype = LIBMTP_FILETYPE_MP3; + break; + case Type_Flac: + case Type_OggFlac: + track->filetype = LIBMTP_FILETYPE_FLAC; + break; + case Type_OggSpeex: + case Type_OggVorbis: + track->filetype = LIBMTP_FILETYPE_OGG; + break; + case Type_Wav: + track->filetype = LIBMTP_FILETYPE_WAV; + break; + default: + track->filetype = LIBMTP_FILETYPE_UNDEF_AUDIO; + break; } +} #endif -void Song::MergeFromSimpleMetaBundle(const Engine::SimpleMetaBundle &bundle) { +void Song::MergeFromSimpleMetaBundle(const Engine::SimpleMetaBundle& bundle) { if (d->init_from_file_ || d->url_.scheme() == "file") { // This Song was already loaded using taglib. Our tags are probably better // than the engine's. Note: init_from_file_ is used for non-file:// URLs @@ -768,10 +857,10 @@ void Song::MergeFromSimpleMetaBundle(const Engine::SimpleMetaBundle &bundle) { if (!bundle.tracknr.isEmpty()) d->track_ = bundle.tracknr.toInt(); } -void Song::BindToQuery(QSqlQuery *query) const { - #define strval(x) (x.isNull() ? "" : x) - #define intval(x) (x <= 0 ? -1 : x) - #define notnullintval(x) (x == -1 ? QVariant() : x) +void Song::BindToQuery(QSqlQuery* query) const { +#define strval(x) (x.isNull() ? "" : x) +#define intval(x) (x <= 0 ? -1 : x) +#define notnullintval(x) (x == -1 ? QVariant() : x) // Remember to bind these in the same order as kBindSpec @@ -793,9 +882,10 @@ void Song::BindToQuery(QSqlQuery *query) const { query->bindValue(":directory", notnullintval(d->directory_id_)); - if (Application::kIsPortable - && Utilities::UrlOnSameDriveAsClementine(d->url_)) { - query->bindValue(":filename", Utilities::GetRelativePathToClementineBin(d->url_)); + if (Application::kIsPortable && + Utilities::UrlOnSameDriveAsClementine(d->url_)) { + query->bindValue(":filename", + Utilities::GetRelativePathToClementineBin(d->url_)); } else { query->bindValue(":filename", d->url_.toEncoded()); } @@ -814,7 +904,8 @@ void Song::BindToQuery(QSqlQuery *query) const { query->bindValue(":rating", intval(d->rating_)); query->bindValue(":forced_compilation_on", d->forced_compilation_on_ ? 1 : 0); - query->bindValue(":forced_compilation_off", d->forced_compilation_off_ ? 1 : 0); + query->bindValue(":forced_compilation_off", + d->forced_compilation_off_ ? 1 : 0); query->bindValue(":effective_compilation", is_compilation() ? 1 : 0); @@ -833,12 +924,12 @@ void Song::BindToQuery(QSqlQuery *query) const { query->bindValue(":performer", strval(d->performer_)); query->bindValue(":grouping", strval(d->grouping_)); - #undef intval - #undef notnullintval - #undef strval +#undef intval +#undef notnullintval +#undef strval } -void Song::BindToFtsQuery(QSqlQuery *query) const { +void Song::BindToFtsQuery(QSqlQuery* query) const { query->bindValue(":ftstitle", d->title_); query->bindValue(":ftsalbum", d->album_); query->bindValue(":ftsartist", d->artist_); @@ -870,25 +961,21 @@ void Song::ToLastFM(lastfm::Track* track, bool prefer_album_artist) const { mtrack.setSource(lastfm::Track::Player); } } -#endif // HAVE_LIBLASTFM +#endif // HAVE_LIBLASTFM QString Song::PrettyRating() const { float rating = d->rating_; - if (rating == -1.0f) - return "0"; + if (rating == -1.0f) return "0"; return QString::number(static_cast(rating * 100)); } - QString Song::PrettyTitle() const { QString title(d->title_); - if (title.isEmpty()) - title = d->basefilename_; - if (title.isEmpty()) - title = d->url_.toString(); + if (title.isEmpty()) title = d->basefilename_; + if (title.isEmpty()) title = d->url_.toString(); return title; } @@ -896,25 +983,21 @@ QString Song::PrettyTitle() const { QString Song::PrettyTitleWithArtist() const { QString title(d->title_); - if (title.isEmpty()) - title = d->basefilename_; + if (title.isEmpty()) title = d->basefilename_; - if (!d->artist_.isEmpty()) - title = d->artist_ + " - " + title; + if (!d->artist_.isEmpty()) title = d->artist_ + " - " + title; return title; } QString Song::PrettyLength() const { - if (length_nanosec() == -1) - return QString::null; + if (length_nanosec() == -1) return QString::null; return Utilities::PrettyTimeNanosec(length_nanosec()); } QString Song::PrettyYear() const { - if (d->year_ == -1) - return QString::null; + if (d->year_ == -1) return QString::null; return QString::number(d->year_); } @@ -922,28 +1005,24 @@ QString Song::PrettyYear() const { QString Song::TitleWithCompilationArtist() const { QString title(d->title_); - if (title.isEmpty()) - title = d->basefilename_; + if (title.isEmpty()) title = d->basefilename_; - if (is_compilation() && !d->artist_.isEmpty() && !d->artist_.toLower().contains("various")) + if (is_compilation() && !d->artist_.isEmpty() && + !d->artist_.toLower().contains("various")) title = d->artist_ + " - " + title; return title; } bool Song::IsMetadataEqual(const Song& other) const { - return d->title_ == other.d->title_ && - d->album_ == other.d->album_ && + return d->title_ == other.d->title_ && d->album_ == other.d->album_ && d->artist_ == other.d->artist_ && d->albumartist_ == other.d->albumartist_ && d->composer_ == other.d->composer_ && d->performer_ == other.d->performer_ && - d->grouping_ == other.d->grouping_ && - d->track_ == other.d->track_ && - d->disc_ == other.d->disc_ && - qFuzzyCompare(d->bpm_, other.d->bpm_) && - d->year_ == other.d->year_ && - d->genre_ == other.d->genre_ && + d->grouping_ == other.d->grouping_ && d->track_ == other.d->track_ && + d->disc_ == other.d->disc_ && qFuzzyCompare(d->bpm_, other.d->bpm_) && + d->year_ == other.d->year_ && d->genre_ == other.d->genre_ && d->comment_ == other.d->comment_ && d->compilation_ == other.d->compilation_ && d->beginning_ == other.d->beginning_ && @@ -982,23 +1061,19 @@ uint HashSimilar(const Song& song) { } bool Song::IsOnSameAlbum(const Song& other) const { - if (is_compilation() != other.is_compilation()) - return false; + if (is_compilation() != other.is_compilation()) return false; if (has_cue() && other.has_cue() && cue_path() == other.cue_path()) return true; - if (is_compilation() && album() == other.album()) - return true; + if (is_compilation() && album() == other.album()) return true; return album() == other.album() && artist() == other.artist(); } QString Song::AlbumKey() const { - return QString("%1|%2|%3").arg( - is_compilation() ? "_compilation" : artist(), - has_cue() ? cue_path() : "", - album()); + return QString("%1|%2|%3").arg(is_compilation() ? "_compilation" : artist(), + has_cue() ? cue_path() : "", album()); } void Song::ToXesam(QVariantMap* map) const { diff --git a/src/core/song.h b/src/core/song.h index 49d64a4c6..7d298b416 100644 --- a/src/core/song.h +++ b/src/core/song.h @@ -37,22 +37,21 @@ class QSqlQuery; class QUrl; #ifdef HAVE_LIBGPOD - struct _Itdb_Track; +struct _Itdb_Track; #endif #ifdef HAVE_LIBMTP - struct LIBMTP_track_struct; +struct LIBMTP_track_struct; #endif #ifdef HAVE_LIBLASTFM - namespace lastfm { - class Track; - } +namespace lastfm { +class Track; +} #endif class SqlRow; - class Song { public: Song(); @@ -91,7 +90,6 @@ class Song { Type_TrueAudio = 11, Type_Cdda = 12, Type_OggOpus = 13, - Type_Stream = 99, }; static QString TextForFiletype(FileType type); @@ -101,12 +99,16 @@ class Song { static void SortSongsListAlphabetically(QList* songs); // Constructors - void Init(const QString& title, const QString& artist, const QString& album, qint64 length_nanosec); - void Init(const QString& title, const QString& artist, const QString& album, qint64 beginning, qint64 end); + void Init(const QString& title, const QString& artist, const QString& album, + qint64 length_nanosec); + void Init(const QString& title, const QString& artist, const QString& album, + qint64 beginning, qint64 end); void InitFromProtobuf(const pb::tagreader::SongMetadata& pb); void InitFromQuery(const SqlRow& query, bool reliable_metadata, int col = 0); - void InitFromFilePartial(const QString& filename); // Just store the filename: incomplete but fast - void InitArtManual(); // Check if there is already a art in the cache and store the filename in art_manual + void InitFromFilePartial( + const QString& filename); // Just store the filename: incomplete but fast + void InitArtManual(); // Check if there is already a art in the cache and + // store the filename in art_manual #ifdef HAVE_LIBLASTFM void InitFromLastFM(const lastfm::Track& track); #endif @@ -149,7 +151,8 @@ class Song { const QString& artist() const; const QString& albumartist() const; const QString& effective_albumartist() const; - // Playlist views are special because you don't want to fill in album artists automatically for + // Playlist views are special because you don't want to fill in album artists + // automatically for // compilations, but you do for normal albums: const QString& playlist_albumartist() const; const QString& composer() const; @@ -296,4 +299,4 @@ uint qHash(const Song& song); // Hash function using field checked in IsSimilar function uint HashSimilar(const Song& song); -#endif // SONG_H +#endif // SONG_H diff --git a/src/core/songloader.cpp b/src/core/songloader.cpp index 57c83a0fe..209b21902 100644 --- a/src/core/songloader.cpp +++ b/src/core/songloader.cpp @@ -28,7 +28,7 @@ #include #ifdef HAVE_AUDIOCD -# include +#include #endif #include "config.h" @@ -55,25 +55,31 @@ using std::placeholders::_1; QSet SongLoader::sRawUriSchemes; const int SongLoader::kDefaultTimeout = 5000; -SongLoader::SongLoader(LibraryBackendInterface* library, - const Player* player, - QObject *parent) - : QObject(parent), - timeout_timer_(new QTimer(this)), - playlist_parser_(new PlaylistParser(library, this)), - podcast_parser_(new PodcastParser), - cue_parser_(new CueParser(library, this)), - timeout_(kDefaultTimeout), - state_(WaitingForType), - success_(false), - parser_(nullptr), - is_podcast_(false), - library_(library), - player_(player) -{ +SongLoader::SongLoader(LibraryBackendInterface* library, const Player* player, + QObject* parent) + : QObject(parent), + timeout_timer_(new QTimer(this)), + playlist_parser_(new PlaylistParser(library, this)), + podcast_parser_(new PodcastParser), + cue_parser_(new CueParser(library, this)), + timeout_(kDefaultTimeout), + state_(WaitingForType), + success_(false), + parser_(nullptr), + is_podcast_(false), + library_(library), + player_(player) { if (sRawUriSchemes.isEmpty()) { - sRawUriSchemes << "udp" << "mms" << "mmsh" << "mmst" << "mmsu" << "rtsp" - << "rtspu" << "rtspt" << "rtsph" << "spotify"; + sRawUriSchemes << "udp" + << "mms" + << "mmsh" + << "mmst" + << "mmsu" + << "rtsp" + << "rtspu" + << "rtspt" + << "rtsph" + << "spotify"; } timeout_timer_->setSingleShot(true); @@ -121,23 +127,24 @@ SongLoader::Result SongLoader::LoadLocalPartial(const QString& filename) { } Song song; song.InitFromFilePartial(filename); - if (song.is_valid()) - songs_ << song; + if (song.is_valid()) songs_ << song; return Success; } SongLoader::Result SongLoader::LoadAudioCD() { #ifdef HAVE_AUDIOCD // Create gstreamer cdda element - GstElement* cdda = gst_element_make_from_uri (GST_URI_SRC, "cdda://", nullptr); + GstElement* cdda = gst_element_make_from_uri(GST_URI_SRC, "cdda://", nullptr); if (cdda == nullptr) { qLog(Error) << "Error while creating CDDA GstElement"; return Error; } // Change the element's state to ready and paused, to be able to query it - if (gst_element_set_state(cdda, GST_STATE_READY) == GST_STATE_CHANGE_FAILURE || - gst_element_set_state(cdda, GST_STATE_PAUSED) == GST_STATE_CHANGE_FAILURE) { + if (gst_element_set_state(cdda, GST_STATE_READY) == + GST_STATE_CHANGE_FAILURE || + gst_element_set_state(cdda, GST_STATE_PAUSED) == + GST_STATE_CHANGE_FAILURE) { qLog(Error) << "Error while changing CDDA GstElement's state"; gst_element_set_state(cdda, GST_STATE_NULL); gst_object_unref(GST_OBJECT(cdda)); @@ -145,10 +152,11 @@ SongLoader::Result SongLoader::LoadAudioCD() { } // Get number of tracks - GstFormat fmt = gst_format_get_by_nick ("track"); + GstFormat fmt = gst_format_get_by_nick("track"); GstFormat out_fmt = fmt; gint64 num_tracks = 0; - if (!gst_element_query_duration (cdda, &out_fmt, &num_tracks) || out_fmt != fmt) { + if (!gst_element_query_duration(cdda, &out_fmt, &num_tracks) || + out_fmt != fmt) { qLog(Error) << "Error while querying cdda GstElement"; gst_object_unref(GST_OBJECT(cdda)); return Error; @@ -159,8 +167,9 @@ SongLoader::Result SongLoader::LoadAudioCD() { Song song; guint64 duration = 0; // quint64 == ulonglong and guint64 == ulong, therefore we must cast - if (gst_tag_list_get_uint64 (GST_CDDA_BASE_SRC(cdda)->tracks[track_number-1].tags, - GST_TAG_DURATION, &duration)) { + if (gst_tag_list_get_uint64( + GST_CDDA_BASE_SRC(cdda)->tracks[track_number - 1].tags, + GST_TAG_DURATION, &duration)) { song.set_length_nanosec((quint64)duration); } song.set_valid(true); @@ -173,48 +182,50 @@ SongLoader::Result SongLoader::LoadAudioCD() { // Generate MusicBrainz DiscId gst_tag_register_musicbrainz_tags(); - GstElement *pipe = gst_pipeline_new ("pipeline"); - gst_bin_add (GST_BIN (pipe), cdda); - gst_element_set_state (pipe, GST_STATE_READY); - gst_element_set_state (pipe, GST_STATE_PAUSED); - GstMessage *msg = gst_bus_timed_pop_filtered (GST_ELEMENT_BUS (pipe), - GST_CLOCK_TIME_NONE, - GST_MESSAGE_TAG); - GstTagList *tags = nullptr; - gst_message_parse_tag (msg, &tags); - char *string_mb = nullptr; - if (gst_tag_list_get_string (tags, GST_TAG_CDDA_MUSICBRAINZ_DISCID, &string_mb)) { + GstElement* pipe = gst_pipeline_new("pipeline"); + gst_bin_add(GST_BIN(pipe), cdda); + gst_element_set_state(pipe, GST_STATE_READY); + gst_element_set_state(pipe, GST_STATE_PAUSED); + GstMessage* msg = gst_bus_timed_pop_filtered( + GST_ELEMENT_BUS(pipe), GST_CLOCK_TIME_NONE, GST_MESSAGE_TAG); + GstTagList* tags = nullptr; + gst_message_parse_tag(msg, &tags); + char* string_mb = nullptr; + if (gst_tag_list_get_string(tags, GST_TAG_CDDA_MUSICBRAINZ_DISCID, + &string_mb)) { QString musicbrainz_discid(string_mb); qLog(Info) << "MusicBrainz discid: " << musicbrainz_discid; - MusicBrainzClient *musicbrainz_client = new MusicBrainzClient(this); - connect(musicbrainz_client, - SIGNAL(Finished(const QString&, const QString&, MusicBrainzClient::ResultList)), - SLOT(AudioCDTagsLoaded(const QString&, const QString&, MusicBrainzClient::ResultList))); + MusicBrainzClient* musicbrainz_client = new MusicBrainzClient(this); + connect(musicbrainz_client, SIGNAL(Finished(const QString&, const QString&, + MusicBrainzClient::ResultList)), + SLOT(AudioCDTagsLoaded(const QString&, const QString&, + MusicBrainzClient::ResultList))); musicbrainz_client->StartDiscIdRequest(musicbrainz_discid); g_free(string_mb); } - + // Clean all the Gstreamer objects we have used: we don't need them anymore gst_object_unref(GST_OBJECT(cdda)); - gst_element_set_state (pipe, GST_STATE_NULL); + gst_element_set_state(pipe, GST_STATE_NULL); gst_object_unref(GST_OBJECT(pipe)); gst_object_unref(GST_OBJECT(msg)); gst_object_unref(GST_OBJECT(tags)); return Success; -#else // HAVE_AUDIOCD +#else // HAVE_AUDIOCD return Error; #endif } -void SongLoader::AudioCDTagsLoaded(const QString& artist, const QString& album, - const MusicBrainzClient::ResultList& results) { +void SongLoader::AudioCDTagsLoaded( + const QString& artist, const QString& album, + const MusicBrainzClient::ResultList& results) { // Remove previously added songs metadata, because there are not needed // and that we are going to fill it with new (more complete) ones songs_.clear(); int track_number = 1; - foreach (const MusicBrainzClient::Result& ret, results) { + foreach(const MusicBrainzClient::Result & ret, results) { Song song; song.set_artist(artist); song.set_album(album); @@ -222,7 +233,8 @@ void SongLoader::AudioCDTagsLoaded(const QString& artist, const QString& album, song.set_length_nanosec(ret.duration_msec_ * kNsecPerMsec); song.set_track(track_number); song.set_year(ret.year_); - // We need to set url: that's how playlist will find the correct item to update + // We need to set url: that's how playlist will find the correct item to + // update song.set_url(QUrl(QString("cdda://%1").arg(track_number++))); songs_ << song; } @@ -235,7 +247,8 @@ SongLoader::Result SongLoader::LoadLocal(const QString& filename) { // First check to see if it's a directory - if so we can load all the songs // inside right away. if (QFileInfo(filename).isDir()) { - ConcurrentRun::Run(&thread_pool_, + ConcurrentRun::Run( + &thread_pool_, std::bind(&SongLoader::LoadLocalDirectoryAndEmit, this, filename)); return WillLoadAsync; } @@ -243,8 +256,7 @@ SongLoader::Result SongLoader::LoadLocal(const QString& filename) { // It's a local file, so check if it looks like a playlist. // Read the first few bytes. QFile file(filename); - if (!file.open(QIODevice::ReadOnly)) - return Error; + if (!file.open(QIODevice::ReadOnly)) return Error; QByteArray data(file.read(PlaylistParser::kMagicSize)); ParserBase* parser = playlist_parser_->ParserForMagic(data); @@ -258,7 +270,8 @@ SongLoader::Result SongLoader::LoadLocal(const QString& filename) { qLog(Debug) << "Parsing using" << parser->name(); // It's a playlist! - ConcurrentRun::Run(&thread_pool_, + ConcurrentRun::Run( + &thread_pool_, std::bind(&SongLoader::LoadPlaylistAndEmit, this, parser, filename)); return WillLoadAsync; } @@ -279,7 +292,7 @@ SongLoader::Result SongLoader::LoadLocal(const QString& filename) { song.InitFromQuery(query, true); song_list << song; - } while(query.Next()); + } while (query.Next()); } else { QString matching_cue = filename.section('.', 0, -2) + ".cue"; @@ -288,19 +301,19 @@ SongLoader::Result SongLoader::LoadLocal(const QString& filename) { QFile cue(matching_cue); cue.open(QIODevice::ReadOnly); - song_list = cue_parser_->Load(&cue, matching_cue, QDir(filename.section('/', 0, -2))); + song_list = cue_parser_->Load(&cue, matching_cue, + QDir(filename.section('/', 0, -2))); } else { // it's a normal media file, load it asynchronously. TagReaderReply* reply = TagReaderClient::Instance()->ReadFile(filename); - NewClosure(reply, SIGNAL(Finished(bool)), - this, SLOT(LocalFileLoaded(TagReaderReply*)), - reply); + NewClosure(reply, SIGNAL(Finished(bool)), this, + SLOT(LocalFileLoaded(TagReaderReply*)), reply); return WillLoadAsync; } } - foreach (const Song& song, song_list) { + foreach(const Song & song, song_list) { if (song.is_valid()) { songs_ << song; } @@ -329,8 +342,7 @@ void SongLoader::EffectiveSongsLoad() { } void SongLoader::EffectiveSongLoad(Song* song) { - if (!song) - return; + if (!song) return; if (song->filetype() != Song::Type_Unknown) { // Maybe we loaded the metadata already, for example from a cuesheet. @@ -348,7 +360,8 @@ void SongLoader::EffectiveSongLoad(Song* song) { } } -void SongLoader::LoadPlaylistAndEmit(ParserBase* parser, const QString& filename) { +void SongLoader::LoadPlaylistAndEmit(ParserBase* parser, + const QString& filename) { LoadPlaylist(parser, filename); emit LoadFinished(true); } @@ -391,8 +404,7 @@ void SongLoader::LoadLocalDirectory(const QString& filename) { // one in our list to be fully loaded, so if the user has the "Start playing // when adding to playlist" preference behaviour set, it can enjoy the first // song being played (seek it, have moodbar, etc.) - if (!songs_.isEmpty()) - EffectiveSongLoad(&(*songs_.begin())); + if (!songs_.isEmpty()) EffectiveSongLoad(&(*songs_.begin())); } void SongLoader::AddAsRawStream() { @@ -462,14 +474,15 @@ SongLoader::Result SongLoader::LoadRemote() { // rest of the file, parse the playlist and return success. // 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, _1)); + std::shared_ptr pipeline(gst_pipeline_new(nullptr), + std::bind(&gst_object_unref, _1)); // Create the source element automatically based on the URL GstElement* source = gst_element_make_from_uri( GST_URI_SRC, url_.toEncoded().constData(), nullptr); if (!source) { - qLog(Warning) << "Couldn't create gstreamer source element for" << url_.toString(); + qLog(Warning) << "Couldn't create gstreamer source element for" + << url_.toString(); return Error; } @@ -477,7 +490,8 @@ SongLoader::Result SongLoader::LoadRemote() { GstElement* typefind = gst_element_factory_make("typefind", nullptr); GstElement* fakesink = gst_element_factory_make("fakesink", nullptr); - gst_bin_add_many(GST_BIN(pipeline.get()), source, typefind, fakesink, nullptr); + gst_bin_add_many(GST_BIN(pipeline.get()), source, typefind, fakesink, + nullptr); gst_element_link_many(source, typefind, fakesink, nullptr); // Connect callbacks @@ -500,15 +514,16 @@ SongLoader::Result SongLoader::LoadRemote() { void SongLoader::TypeFound(GstElement*, uint, GstCaps* caps, void* self) { SongLoader* instance = static_cast(self); - if (instance->state_ != WaitingForType) - return; + if (instance->state_ != WaitingForType) return; // Check the mimetype - instance->mime_type_ = gst_structure_get_name(gst_caps_get_structure(caps, 0)); + instance->mime_type_ = + gst_structure_get_name(gst_caps_get_structure(caps, 0)); qLog(Debug) << "Mime type is" << instance->mime_type_; if (instance->mime_type_ == "text/plain" || instance->mime_type_ == "text/uri-list" || - instance->podcast_parser_->supported_mime_types().contains(instance->mime_type_)) { + instance->podcast_parser_->supported_mime_types().contains( + instance->mime_type_)) { // Yeah it might be a playlist, let's get some data and have a better look instance->state_ = WaitingForMagic; return; @@ -521,8 +536,7 @@ void SongLoader::TypeFound(GstElement*, uint, GstCaps* caps, void* self) { gboolean SongLoader::DataReady(GstPad*, GstBuffer* buf, void* self) { SongLoader* instance = static_cast(self); - if (instance->state_ == Finished) - return true; + if (instance->state_ == Finished) return true; // Append the data to the buffer instance->buffer_.append(reinterpret_cast(GST_BUFFER_DATA(buf)), @@ -554,7 +568,8 @@ gboolean SongLoader::BusCallback(GstBus*, GstMessage* msg, gpointer self) { return TRUE; } -GstBusSyncReply SongLoader::BusCallbackSync(GstBus*, GstMessage* msg, gpointer self) { +GstBusSyncReply SongLoader::BusCallbackSync(GstBus*, GstMessage* msg, + gpointer self) { SongLoader* instance = reinterpret_cast(self); switch (GST_MESSAGE_TYPE(msg)) { @@ -573,8 +588,7 @@ GstBusSyncReply SongLoader::BusCallbackSync(GstBus*, GstMessage* msg, gpointer s } void SongLoader::ErrorMessageReceived(GstMessage* msg) { - if (state_ == Finished) - return; + if (state_ == Finished) return; GError* error; gchar* debugs; @@ -589,8 +603,8 @@ void SongLoader::ErrorMessageReceived(GstMessage* msg) { free(debugs); if (state_ == WaitingForType && - message_str == gst_error_get_message( - GST_STREAM_ERROR, GST_STREAM_ERROR_TYPE_NOT_FOUND)) { + message_str == gst_error_get_message(GST_STREAM_ERROR, + GST_STREAM_ERROR_TYPE_NOT_FOUND)) { // Don't give up - assume it's a playlist and see if one of our parsers can // read it. state_ = WaitingForMagic; @@ -603,25 +617,24 @@ void SongLoader::ErrorMessageReceived(GstMessage* msg) { void SongLoader::EndOfStreamReached() { qLog(Debug) << Q_FUNC_INFO << state_; switch (state_) { - case Finished: - break; - - case WaitingForMagic: - // Do the magic on the data we have already - MagicReady(); - if (state_ == Finished) + case Finished: break; + + case WaitingForMagic: + // Do the magic on the data we have already + MagicReady(); + if (state_ == Finished) break; // It looks like a playlist, so parse it // fallthrough - case WaitingForData: - // It's a playlist and we've got all the data - finish and parse it - StopTypefindAsync(true); - break; + case WaitingForData: + // It's a playlist and we've got all the data - finish and parse it + StopTypefindAsync(true); + break; - case WaitingForType: - StopTypefindAsync(false); - break; + case WaitingForType: + StopTypefindAsync(false); + break; } } @@ -636,7 +649,8 @@ void SongLoader::MagicReady() { is_podcast_ = true; qLog(Debug) << "Looks like a podcast"; } else { - qLog(Warning) << url_.toString() << "is text, but not a recognised playlist"; + qLog(Warning) << url_.toString() + << "is text, but not a recognised playlist"; // It doesn't look like a playlist, so just finish StopTypefindAsync(false); return; @@ -648,7 +662,8 @@ void SongLoader::MagicReady() { if (!is_podcast_) { qLog(Debug) << "Magic says" << parser_->name(); if (parser_->name() == "ASX/INI" && url_.scheme() == "http") { - // This is actually a weird MS-WMSP stream. Changing the protocol to MMS from + // This is actually a weird MS-WMSP stream. Changing the protocol to MMS + // from // HTTP makes it playable. parser_ = nullptr; url_.setScheme("mms"); @@ -666,7 +681,8 @@ void SongLoader::MagicReady() { 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_.get(), &state, + &pending_state, GST_SECOND); if (ret == GST_STATE_CHANGE_ASYNC && pending_state == GST_STATE_PLAYING) { // We're still on the way to playing diff --git a/src/core/songloader.h b/src/core/songloader.h index 7b4753fc5..1eafe353b 100644 --- a/src/core/songloader.h +++ b/src/core/songloader.h @@ -39,16 +39,12 @@ class PodcastParser; class SongLoader : public QObject { Q_OBJECT -public: + public: SongLoader(LibraryBackendInterface* library, const Player* player, QObject* parent = 0); ~SongLoader(); - enum Result { - Success, - Error, - WillLoadAsync, - }; + enum Result { Success, Error, WillLoadAsync, }; static const int kDefaultTimeout; @@ -74,20 +70,15 @@ public: signals: void LoadFinished(bool success); -private slots: + private slots: void Timeout(); void StopTypefind(); void AudioCDTagsLoaded(const QString& artist, const QString& album, const MusicBrainzClient::ResultList& results); void LocalFileLoaded(TagReaderReply* reply); -private: - enum State { - WaitingForType, - WaitingForMagic, - WaitingForData, - Finished, - }; + private: + enum State { WaitingForType, WaitingForMagic, WaitingForData, Finished, }; Result LoadLocal(const QString& filename); Result LoadLocalPartial(const QString& filename); @@ -101,7 +92,8 @@ private: Result LoadRemote(); // GStreamer callbacks - static void TypeFound(GstElement* typefind, uint probability, GstCaps* caps, void* self); + static void TypeFound(GstElement* typefind, uint probability, GstCaps* caps, + void* self); static gboolean DataReady(GstPad*, GstBuffer* buf, void* self); static GstBusSyncReply BusCallbackSync(GstBus*, GstMessage*, gpointer); static gboolean BusCallback(GstBus*, GstMessage*, gpointer); @@ -112,7 +104,7 @@ private: void MagicReady(); bool IsPipelinePlaying(); -private: + private: static QSet sRawUriSchemes; QUrl url_; @@ -139,4 +131,4 @@ private: QThreadPool thread_pool_; }; -#endif // SONGLOADER_H +#endif // SONGLOADER_H diff --git a/src/core/stylesheetloader.cpp b/src/core/stylesheetloader.cpp index 415bf7ac3..353ddc1c5 100644 --- a/src/core/stylesheetloader.cpp +++ b/src/core/stylesheetloader.cpp @@ -21,18 +21,15 @@ #include #include -StyleSheetLoader::StyleSheetLoader(QObject* parent) - : QObject(parent) -{ -} +StyleSheetLoader::StyleSheetLoader(QObject* parent) : QObject(parent) {} -void StyleSheetLoader::SetStyleSheet(QWidget* widget, const QString &filename) { +void StyleSheetLoader::SetStyleSheet(QWidget* widget, const QString& filename) { filenames_[widget] = filename; widget->installEventFilter(this); UpdateStyleSheet(widget); } -void StyleSheetLoader::UpdateStyleSheet(QWidget *widget) { +void StyleSheetLoader::UpdateStyleSheet(QWidget* widget) { QString filename(filenames_[widget]); // Load the file @@ -43,14 +40,16 @@ void StyleSheetLoader::UpdateStyleSheet(QWidget *widget) { } QString contents(file.readAll()); - // Replace %palette-role with actual colours QPalette p(widget->palette()); QColor alt = p.color(QPalette::AlternateBase); alt.setAlpha(50); contents.replace("%palette-alternate-base", QString("rgba(%1,%2,%3,%4%)") - .arg(alt.red()).arg(alt.green()).arg(alt.blue()).arg(alt.alpha())); + .arg(alt.red()) + .arg(alt.green()) + .arg(alt.blue()) + .arg(alt.alpha())); ReplaceColor(&contents, "Window", p, QPalette::Window); ReplaceColor(&contents, "Background", p, QPalette::Background); @@ -88,17 +87,15 @@ void StyleSheetLoader::ReplaceColor(QString* css, const QString& name, palette.color(role).lighter().name(), Qt::CaseInsensitive); css->replace("%palette-" + name + "-darker", palette.color(role).darker().name(), Qt::CaseInsensitive); - css->replace("%palette-" + name, - palette.color(role).name(), Qt::CaseInsensitive); + css->replace("%palette-" + name, palette.color(role).name(), + Qt::CaseInsensitive); } bool StyleSheetLoader::eventFilter(QObject* obj, QEvent* event) { - if (event->type() != QEvent::PaletteChange) - return false; + if (event->type() != QEvent::PaletteChange) return false; QWidget* widget = qobject_cast(obj); - if (!widget || !filenames_.contains(widget)) - return false; + if (!widget || !filenames_.contains(widget)) return false; UpdateStyleSheet(widget); return false; diff --git a/src/core/stylesheetloader.h b/src/core/stylesheetloader.h index 1fd462058..622e0c9c8 100644 --- a/src/core/stylesheetloader.h +++ b/src/core/stylesheetloader.h @@ -45,4 +45,4 @@ class StyleSheetLoader : public QObject { QMap filenames_; }; -#endif // STYLESHEETLOADER_H +#endif // STYLESHEETLOADER_H diff --git a/src/core/tagreaderclient.cpp b/src/core/tagreaderclient.cpp index 61f082ecd..66bcfd0c4 100644 --- a/src/core/tagreaderclient.cpp +++ b/src/core/tagreaderclient.cpp @@ -24,24 +24,20 @@ #include #include - const char* TagReaderClient::kWorkerExecutableName = "clementine-tagreader"; TagReaderClient* TagReaderClient::sInstance = nullptr; TagReaderClient::TagReaderClient(QObject* parent) - : QObject(parent), - worker_pool_(new WorkerPool(this)) -{ + : QObject(parent), worker_pool_(new WorkerPool(this)) { sInstance = this; worker_pool_->SetExecutableName(kWorkerExecutableName); worker_pool_->SetWorkerCount(QThread::idealThreadCount()); - connect(worker_pool_, SIGNAL(WorkerFailedToStart()), SLOT(WorkerFailedToStart())); + connect(worker_pool_, SIGNAL(WorkerFailedToStart()), + SLOT(WorkerFailedToStart())); } -void TagReaderClient::Start() { - worker_pool_->Start(); -} +void TagReaderClient::Start() { worker_pool_->Start(); } void TagReaderClient::WorkerFailedToStart() { qLog(Error) << "The" << kWorkerExecutableName << "executable was not found" @@ -58,7 +54,8 @@ TagReaderReply* TagReaderClient::ReadFile(const QString& filename) { return worker_pool_->SendMessageWithReply(&message); } -TagReaderReply* TagReaderClient::SaveFile(const QString& filename, const Song& metadata) { +TagReaderReply* TagReaderClient::SaveFile(const QString& filename, + const Song& metadata) { pb::tagreader::Message message; pb::tagreader::SaveFileRequest* req = message.mutable_save_file_request(); @@ -80,7 +77,7 @@ TagReaderReply* TagReaderClient::UpdateSongStatistics(const Song& metadata) { } void TagReaderClient::UpdateSongsStatistics(const SongList& songs) { - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { TagReaderReply* reply = UpdateSongStatistics(song); connect(reply, SIGNAL(Finished(bool)), reply, SLOT(deleteLater())); } @@ -98,7 +95,7 @@ TagReaderReply* TagReaderClient::UpdateSongRating(const Song& metadata) { } void TagReaderClient::UpdateSongsRating(const SongList& songs) { - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { TagReaderReply* reply = UpdateSongRating(song); connect(reply, SIGNAL(Finished(bool)), reply, SLOT(deleteLater())); } @@ -106,7 +103,8 @@ void TagReaderClient::UpdateSongsRating(const SongList& songs) { TagReaderReply* TagReaderClient::IsMediaFile(const QString& filename) { pb::tagreader::Message message; - pb::tagreader::IsMediaFileRequest* req = message.mutable_is_media_file_request(); + pb::tagreader::IsMediaFileRequest* req = + message.mutable_is_media_file_request(); req->set_filename(DataCommaSizeFromQString(filename)); @@ -115,18 +113,17 @@ TagReaderReply* TagReaderClient::IsMediaFile(const QString& filename) { TagReaderReply* TagReaderClient::LoadEmbeddedArt(const QString& filename) { pb::tagreader::Message message; - pb::tagreader::LoadEmbeddedArtRequest* req = message.mutable_load_embedded_art_request(); + pb::tagreader::LoadEmbeddedArtRequest* req = + message.mutable_load_embedded_art_request(); req->set_filename(DataCommaSizeFromQString(filename)); return worker_pool_->SendMessageWithReply(&message); } -TagReaderReply* TagReaderClient::ReadCloudFile(const QUrl& download_url, - const QString& title, - int size, - const QString& mime_type, - const QString& authorisation_header) { +TagReaderReply* TagReaderClient::ReadCloudFile( + const QUrl& download_url, const QString& title, int size, + const QString& mime_type, const QString& authorisation_header) { pb::tagreader::Message message; pb::tagreader::ReadCloudFileRequest* req = message.mutable_read_cloud_file_request(); @@ -151,7 +148,8 @@ void TagReaderClient::ReadFileBlocking(const QString& filename, Song* song) { reply->deleteLater(); } -bool TagReaderClient::SaveFileBlocking(const QString& filename, const Song& metadata) { +bool TagReaderClient::SaveFileBlocking(const QString& filename, + const Song& metadata) { Q_ASSERT(QThread::currentThread() != thread()); bool ret = false; diff --git a/src/core/tagreaderclient.h b/src/core/tagreaderclient.h index 20e99b44a..7a83aa324 100644 --- a/src/core/tagreaderclient.h +++ b/src/core/tagreaderclient.h @@ -31,7 +31,7 @@ class QProcess; class TagReaderClient : public QObject { Q_OBJECT -public: + public: TagReaderClient(QObject* parent = 0); typedef AbstractMessageHandler HandlerType; @@ -47,10 +47,8 @@ public: ReplyType* UpdateSongRating(const Song& metadata); ReplyType* IsMediaFile(const QString& filename); ReplyType* LoadEmbeddedArt(const QString& filename); - ReplyType* ReadCloudFile(const QUrl& download_url, - const QString& title, - int size, - const QString& mime_type, + ReplyType* ReadCloudFile(const QUrl& download_url, const QString& title, + int size, const QString& mime_type, const QString& authorisation_header); // Convenience functions that call the above functions and wait for a @@ -66,14 +64,14 @@ public: // TODO: Make this not a singleton static TagReaderClient* Instance() { return sInstance; } -public slots: + public slots: void UpdateSongsStatistics(const SongList& songs); void UpdateSongsRating(const SongList& songs); -private slots: + private slots: void WorkerFailedToStart(); -private: + private: static TagReaderClient* sInstance; WorkerPool* worker_pool_; @@ -82,4 +80,4 @@ private: typedef TagReaderClient::ReplyType TagReaderReply; -#endif // TAGREADERCLIENT_H +#endif // TAGREADERCLIENT_H diff --git a/src/core/taskmanager.cpp b/src/core/taskmanager.cpp index bfd853f34..0ab5ff3d2 100644 --- a/src/core/taskmanager.cpp +++ b/src/core/taskmanager.cpp @@ -17,11 +17,7 @@ #include "taskmanager.h" -TaskManager::TaskManager(QObject *parent) - : QObject(parent), - next_task_id_(1) -{ -} +TaskManager::TaskManager(QObject* parent) : QObject(parent), next_task_id_(1) {} int TaskManager::StartTask(const QString& name) { Task t; @@ -32,7 +28,7 @@ int TaskManager::StartTask(const QString& name) { { QMutexLocker l(&mutex_); - t.id = next_task_id_ ++; + t.id = next_task_id_++; tasks_[t.id] = t; } @@ -54,8 +50,7 @@ QList TaskManager::GetTasks() { void TaskManager::SetTaskBlocksLibraryScans(int id) { { QMutexLocker l(&mutex_); - if (!tasks_.contains(id)) - return; + if (!tasks_.contains(id)) return; Task& t = tasks_[id]; t.blocks_library_scans = true; @@ -68,13 +63,11 @@ void TaskManager::SetTaskBlocksLibraryScans(int id) { void TaskManager::SetTaskProgress(int id, int progress, int max) { { QMutexLocker l(&mutex_); - if (!tasks_.contains(id)) - return; + if (!tasks_.contains(id)) return; Task& t = tasks_[id]; t.progress = progress; - if (max) - t.progress_max = max; + if (max) t.progress_max = max; } emit TasksChanged(); @@ -83,13 +76,11 @@ void TaskManager::SetTaskProgress(int id, int progress, int max) { void TaskManager::IncreaseTaskProgress(int id, int progress, int max) { { QMutexLocker l(&mutex_); - if (!tasks_.contains(id)) - return; + if (!tasks_.contains(id)) return; Task& t = tasks_[id]; t.progress += progress; - if (max) - t.progress_max = max; + if (max) t.progress_max = max; } emit TasksChanged(); @@ -100,12 +91,11 @@ void TaskManager::SetTaskFinished(int id) { { QMutexLocker l(&mutex_); - if (!tasks_.contains(id)) - return; + if (!tasks_.contains(id)) return; if (tasks_[id].blocks_library_scans) { resume_library_watchers = true; - foreach (const Task& task, tasks_.values()) { + foreach(const Task & task, tasks_.values()) { if (task.id != id && task.blocks_library_scans) { resume_library_watchers = false; break; @@ -117,15 +107,13 @@ void TaskManager::SetTaskFinished(int id) { } emit TasksChanged(); - if (resume_library_watchers) - emit ResumeLibraryWatchers(); + if (resume_library_watchers) emit ResumeLibraryWatchers(); } int TaskManager::GetTaskProgress(int id) { { QMutexLocker l(&mutex_); - if (!tasks_.contains(id)) - return 0; + if (!tasks_.contains(id)) return 0; return tasks_[id].progress; } } diff --git a/src/core/taskmanager.h b/src/core/taskmanager.h index 4a240c1b5..b743f4777 100644 --- a/src/core/taskmanager.h +++ b/src/core/taskmanager.h @@ -25,7 +25,7 @@ class TaskManager : public QObject { Q_OBJECT -public: + public: TaskManager(QObject* parent = 0); struct Task { @@ -39,13 +39,9 @@ public: class ScopedTask { public: ScopedTask(const int task_id, TaskManager* task_manager) - : task_id_(task_id), - task_manager_(task_manager) { - } + : task_id_(task_id), task_manager_(task_manager) {} - ~ScopedTask() { - task_manager_->SetTaskFinished(task_id_); - } + ~ScopedTask() { task_manager_->SetTaskFinished(task_id_); } private: const int task_id_; @@ -70,7 +66,7 @@ signals: void PauseLibraryWatchers(); void ResumeLibraryWatchers(); -private: + private: QMutex mutex_; QMap tasks_; int next_task_id_; @@ -78,4 +74,4 @@ private: Q_DISABLE_COPY(TaskManager); }; -#endif // TASKMANAGER_H +#endif // TASKMANAGER_H diff --git a/src/core/timeconstants.h b/src/core/timeconstants.h index 96242d659..8a79d5397 100644 --- a/src/core/timeconstants.h +++ b/src/core/timeconstants.h @@ -24,13 +24,13 @@ #include // Use these to convert between time units -const qint64 kMsecPerSec = 1000ll; +const qint64 kMsecPerSec = 1000ll; const qint64 kUsecPerMsec = 1000ll; -const qint64 kUsecPerSec = 1000000ll; +const qint64 kUsecPerSec = 1000000ll; const qint64 kNsecPerUsec = 1000ll; const qint64 kNsecPerMsec = 1000000ll; -const qint64 kNsecPerSec = 1000000000ll; +const qint64 kNsecPerSec = 1000000000ll; -const qint64 kSecsPerDay = 24 * 60 * 60; +const qint64 kSecsPerDay = 24 * 60 * 60; -#endif // TIMECONSTANTS_H +#endif // TIMECONSTANTS_H diff --git a/src/core/ubuntuunityhack.cpp b/src/core/ubuntuunityhack.cpp index d5c253622..f75647b2b 100644 --- a/src/core/ubuntuunityhack.cpp +++ b/src/core/ubuntuunityhack.cpp @@ -21,13 +21,11 @@ #include #include -const char* UbuntuUnityHack::kGSettingsFileName = "gsettings"; -const char* UbuntuUnityHack::kUnityPanel = "com.canonical.Unity.Panel"; +const char* UbuntuUnityHack::kGSettingsFileName = "gsettings"; +const char* UbuntuUnityHack::kUnityPanel = "com.canonical.Unity.Panel"; const char* UbuntuUnityHack::kUnitySystrayWhitelist = "systray-whitelist"; -UbuntuUnityHack::UbuntuUnityHack(QObject* parent) - : QObject(parent) -{ +UbuntuUnityHack::UbuntuUnityHack(QObject* parent) : QObject(parent) { // Check if we're on Ubuntu first. QFile lsb_release("/etc/lsb-release"); if (lsb_release.open(QIODevice::ReadOnly)) { @@ -43,8 +41,8 @@ UbuntuUnityHack::UbuntuUnityHack(QObject* parent) QProcess* get = new QProcess(this); connect(get, SIGNAL(finished(int)), SLOT(GetFinished(int))); connect(get, SIGNAL(error(QProcess::ProcessError)), SLOT(GetError())); - get->start(kGSettingsFileName, QStringList() - << "get" << kUnityPanel << kUnitySystrayWhitelist); + get->start(kGSettingsFileName, QStringList() << "get" << kUnityPanel + << kUnitySystrayWhitelist); } void UbuntuUnityHack::GetError() { @@ -85,10 +83,11 @@ void UbuntuUnityHack::GetFinished(int exit_code) { QProcess* set = new QProcess(this); connect(set, SIGNAL(finished(int)), set, SLOT(deleteLater())); - set->start(kGSettingsFileName, QStringList() - << "set" << kUnityPanel << kUnitySystrayWhitelist << whitelist); + set->start(kGSettingsFileName, QStringList() << "set" << kUnityPanel + << kUnitySystrayWhitelist + << whitelist); - qLog(Info) << "Clementine has added itself to the Unity system tray" << - "whitelist, but this won't take effect until the next time" << - "you log out and log back in."; + qLog(Info) << "Clementine has added itself to the Unity system tray" + << "whitelist, but this won't take effect until the next time" + << "you log out and log back in."; } diff --git a/src/core/ubuntuunityhack.h b/src/core/ubuntuunityhack.h index 5ce8077a1..324f96731 100644 --- a/src/core/ubuntuunityhack.h +++ b/src/core/ubuntuunityhack.h @@ -24,17 +24,17 @@ class QProcess; class UbuntuUnityHack : public QObject { Q_OBJECT -public: + public: UbuntuUnityHack(QObject* parent = NULL); -private slots: + private slots: void GetFinished(int exit_code); void GetError(); -private: + private: static const char* kGSettingsFileName; static const char* kUnityPanel; static const char* kUnitySystrayWhitelist; }; -#endif // UBUNTUUNITYHACK_H +#endif // UBUNTUUNITYHACK_H diff --git a/src/core/urlhandler.cpp b/src/core/urlhandler.cpp index c8e78a50e..e238c0fbb 100644 --- a/src/core/urlhandler.cpp +++ b/src/core/urlhandler.cpp @@ -17,17 +17,13 @@ #include "urlhandler.h" -UrlHandler::LoadResult::LoadResult( - const QUrl& original_url, Type type, const QUrl& media_url, qint64 length_nanosec) - : original_url_(original_url), type_(type), media_url_(media_url), length_nanosec_(length_nanosec) -{ -} +UrlHandler::LoadResult::LoadResult(const QUrl& original_url, Type type, + const QUrl& media_url, qint64 length_nanosec) + : original_url_(original_url), + type_(type), + media_url_(media_url), + length_nanosec_(length_nanosec) {} -UrlHandler::UrlHandler(QObject* parent) - : QObject(parent) -{ -} +UrlHandler::UrlHandler(QObject* parent) : QObject(parent) {} -QIcon UrlHandler::icon() const { - return QIcon(); -} +QIcon UrlHandler::icon() const { return QIcon(); } diff --git a/src/core/urlhandler.h b/src/core/urlhandler.h index 157e76ced..649426f8f 100644 --- a/src/core/urlhandler.h +++ b/src/core/urlhandler.h @@ -25,7 +25,7 @@ class UrlHandler : public QObject { Q_OBJECT -public: + public: UrlHandler(QObject* parent = 0); // The URL scheme that this handler handles. @@ -49,10 +49,8 @@ public: TrackAvailable, }; - LoadResult(const QUrl& original_url = QUrl(), - Type type = NoMoreTracks, - const QUrl& media_url = QUrl(), - qint64 length_nanosec_ = -1); + LoadResult(const QUrl& original_url = QUrl(), Type type = NoMoreTracks, + const QUrl& media_url = QUrl(), qint64 length_nanosec_ = -1); // The url that the playlist item has in Url(). // Might be something unplayable like lastfm://... @@ -75,12 +73,13 @@ public: // get another track to play. virtual LoadResult LoadNext(const QUrl& url) { return LoadResult(url); } - // Functions to be warned when something happen to a track handled by UrlHandler. - virtual void TrackAboutToEnd() { }; - virtual void TrackSkipped() { }; + // Functions to be warned when something happen to a track handled by + // UrlHandler. + virtual void TrackAboutToEnd() {}; + virtual void TrackSkipped() {}; signals: void AsyncLoadComplete(const UrlHandler::LoadResult& result); }; -#endif // URLHANDLER_H +#endif // URLHANDLER_H diff --git a/src/core/utilities.cpp b/src/core/utilities.cpp index cb9a94d0e..f8f149f33 100644 --- a/src/core/utilities.cpp +++ b/src/core/utilities.cpp @@ -45,28 +45,28 @@ #include "sha2.h" #if defined(Q_OS_UNIX) -# include +#include #elif defined(Q_OS_WIN32) -# include -# include +#include +#include #endif #ifdef Q_OS_LINUX -# include -# include +#include +#include #endif #ifdef Q_OS_DARWIN -# include +#include #endif #ifdef Q_OS_DARWIN -# include "core/mac_startup.h" -# include "core/mac_utilities.h" -# include "core/scoped_cftyperef.h" -# include "CoreServices/CoreServices.h" -# include "IOKit/ps/IOPowerSources.h" -# include "IOKit/ps/IOPSKeys.h" -# include +#include "core/mac_startup.h" +#include "core/mac_utilities.h" +#include "core/scoped_cftyperef.h" +#include "CoreServices/CoreServices.h" +#include "IOKit/ps/IOPowerSources.h" +#include "IOKit/ps/IOPSKeys.h" +#include #endif namespace Utilities { @@ -84,7 +84,7 @@ QString PrettyTime(int seconds) { // negative times. seconds = qAbs(seconds); - int hours = seconds / (60*60); + int hours = seconds / (60 * 60); int minutes = (seconds / 60) % 60; seconds %= 60; @@ -102,14 +102,13 @@ QString PrettyTimeNanosec(qint64 nanoseconds) { } QString WordyTime(quint64 seconds) { - quint64 days = seconds / (60*60*24); + quint64 days = seconds / (60 * 60 * 24); // TODO: Make the plural rules translatable QStringList parts; - if (days) - parts << (days == 1 ? tr("1 day") : tr("%1 days").arg(days)); - parts << PrettyTime(seconds - days*60*60*24); + if (days) parts << (days == 1 ? tr("1 day") : tr("%1 days").arg(days)); + parts << PrettyTime(seconds - days * 60 * 60 * 24); return parts.join(" "); } @@ -122,14 +121,12 @@ QString Ago(int seconds_since_epoch, const QLocale& locale) { const QDateTime now = QDateTime::currentDateTime(); const QDateTime then = QDateTime::fromTime_t(seconds_since_epoch); const int days_ago = then.date().daysTo(now.date()); - const QString time = then.time().toString(locale.timeFormat(QLocale::ShortFormat)); + const QString time = + then.time().toString(locale.timeFormat(QLocale::ShortFormat)); - if (days_ago == 0) - return tr("Today") + " " + time; - if (days_ago == 1) - return tr("Yesterday") + " " + time; - if (days_ago <= 7) - return tr("%1 days ago").arg(days_ago); + if (days_ago == 0) return tr("Today") + " " + time; + if (days_ago == 1) return tr("Yesterday") + " " + time; + if (days_ago <= 7) return tr("%1 days ago").arg(days_ago); return then.date().toString(locale.dateFormat(QLocale::ShortFormat)); } @@ -138,16 +135,11 @@ QString PrettyFutureDate(const QDate& date) { const QDate now = QDate::currentDate(); const int delta_days = now.daysTo(date); - if (delta_days < 0) - return QString(); - if (delta_days == 0) - return tr("Today"); - if (delta_days == 1) - return tr("Tomorrow"); - if (delta_days <= 7) - return tr("In %1 days").arg(delta_days); - if (delta_days <= 14) - return tr("Next week"); + if (delta_days < 0) return QString(); + if (delta_days == 0) return tr("Today"); + if (delta_days == 1) return tr("Tomorrow"); + if (delta_days <= 7) return tr("In %1 days").arg(delta_days); + if (delta_days <= 14) return tr("Next week"); return tr("In %1 weeks").arg(delta_days / 7); } @@ -158,12 +150,12 @@ QString PrettySize(quint64 bytes) { if (bytes > 0) { if (bytes <= 1000) ret = QString::number(bytes) + " bytes"; - else if (bytes <= 1000*1000) + else if (bytes <= 1000 * 1000) ret.sprintf("%.1f KB", float(bytes) / 1000); - else if (bytes <= 1000*1000*1000) - ret.sprintf("%.1f MB", float(bytes) / (1000*1000)); + else if (bytes <= 1000 * 1000 * 1000) + ret.sprintf("%.1f MB", float(bytes) / (1000 * 1000)); else - ret.sprintf("%.1f GB", float(bytes) / (1000*1000*1000)); + ret.sprintf("%.1f GB", float(bytes) / (1000 * 1000 * 1000)); } return ret; } @@ -175,8 +167,9 @@ quint64 FileSystemCapacity(const QString& path) { return quint64(fs_info.f_blocks) * quint64(fs_info.f_bsize); #elif defined(Q_OS_WIN32) _ULARGE_INTEGER ret; - if (GetDiskFreeSpaceEx(QDir::toNativeSeparators(path).toLocal8Bit().constData(), - nullptr, &ret, nullptr) != 0) + if (GetDiskFreeSpaceEx( + QDir::toNativeSeparators(path).toLocal8Bit().constData(), nullptr, + &ret, nullptr) != 0) return ret.QuadPart; #endif @@ -190,8 +183,9 @@ quint64 FileSystemFreeSpace(const QString& path) { return quint64(fs_info.f_bavail) * quint64(fs_info.f_bsize); #elif defined(Q_OS_WIN32) _ULARGE_INTEGER ret; - if (GetDiskFreeSpaceEx(QDir::toNativeSeparators(path).toLocal8Bit().constData(), - &ret, nullptr, nullptr) != 0) + if (GetDiskFreeSpaceEx( + QDir::toNativeSeparators(path).toLocal8Bit().constData(), &ret, + nullptr, nullptr) != 0) return ret.QuadPart; #endif @@ -202,8 +196,7 @@ QString MakeTempDir(const QString template_name) { QString path; { QTemporaryFile tempfile; - if (!template_name.isEmpty()) - tempfile.setFileTemplate(template_name); + if (!template_name.isEmpty()) tempfile.setFileTemplate(template_name); tempfile.open(); path = tempfile.fileName(); @@ -228,11 +221,13 @@ QString GetTemporaryFileName() { void RemoveRecursive(const QString& path) { QDir dir(path); - foreach (const QString& child, dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden)) - RemoveRecursive(path + "/" + child); + foreach(const QString & child, + dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden)) + RemoveRecursive(path + "/" + child); - foreach (const QString& child, dir.entryList(QDir::NoDotAndDotDot | QDir::Files | QDir::Hidden)) - QFile::remove(path + "/" + child); + foreach(const QString & child, + dir.entryList(QDir::NoDotAndDotDot | QDir::Files | QDir::Hidden)) + QFile::remove(path + "/" + child); dir.rmdir(path); } @@ -244,16 +239,20 @@ bool CopyRecursive(const QString& source, const QString& destination) { QDir().mkpath(dest_path); QDir dir(source); - foreach (const QString& child, dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs)) { + foreach(const QString & child, + dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs)) { if (!CopyRecursive(source + "/" + child, dest_path)) { - qLog(Warning) << "Failed to copy dir" << source + "/" + child << "to" << dest_path; + qLog(Warning) << "Failed to copy dir" << source + "/" + child << "to" + << dest_path; return false; } } - foreach (const QString& child, dir.entryList(QDir::NoDotAndDotDot | QDir::Files)) { + foreach(const QString & child, + dir.entryList(QDir::NoDotAndDotDot | QDir::Files)) { if (!QFile::copy(source + "/" + child, dest_path + "/" + child)) { - qLog(Warning) << "Failed to copy file" << source + "/" + child << "to" << dest_path; + qLog(Warning) << "Failed to copy file" << source + "/" + child << "to" + << dest_path; return false; } } @@ -261,11 +260,9 @@ bool CopyRecursive(const QString& source, const QString& destination) { } bool Copy(QIODevice* source, QIODevice* destination) { - if (!source->open(QIODevice::ReadOnly)) - return false; + if (!source->open(QIODevice::ReadOnly)) return false; - if (!destination->open(QIODevice::WriteOnly)) - return false; + if (!destination->open(QIODevice::WriteOnly)) return false; const qint64 bytes = source->size(); std::unique_ptr data(new char[bytes]); @@ -274,8 +271,7 @@ bool Copy(QIODevice* source, QIODevice* destination) { qint64 bytes_read; do { bytes_read = source->read(data.get() + pos, bytes - pos); - if (bytes_read == -1) - return false; + if (bytes_read == -1) return false; pos += bytes_read; } while (bytes_read > 0 && pos != bytes); @@ -284,8 +280,7 @@ bool Copy(QIODevice* source, QIODevice* destination) { qint64 bytes_written; do { bytes_written = destination->write(data.get() + pos, bytes - pos); - if (bytes_written == -1) - return false; + if (bytes_written == -1) return false; pos += bytes_written; } while (bytes_written > 0 && pos != bytes); @@ -295,7 +290,10 @@ bool Copy(QIODevice* source, QIODevice* destination) { QString ColorToRgba(const QColor& c) { return QString("rgba(%1, %2, %3, %4)") - .arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha()); + .arg(c.red()) + .arg(c.green()) + .arg(c.blue()) + .arg(c.alpha()); } QString GetConfigPath(ConfigPath config) { @@ -304,30 +302,31 @@ QString GetConfigPath(ConfigPath config) { if (Application::kIsPortable) { return QString("%1/data").arg(QCoreApplication::applicationDirPath()); } - #ifdef Q_OS_DARWIN - return mac::GetApplicationSupportPath() + "/" + QCoreApplication::organizationName(); - #else - return QString("%1/.config/%2").arg(QDir::homePath(), QCoreApplication::organizationName()); - #endif - } - break; +#ifdef Q_OS_DARWIN + return mac::GetApplicationSupportPath() + "/" + + QCoreApplication::organizationName(); +#else + return QString("%1/.config/%2") + .arg(QDir::homePath(), QCoreApplication::organizationName()); +#endif + } break; case Path_CacheRoot: { if (Application::kIsPortable) { return GetConfigPath(Path_Root) + "/cache"; } - #if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN) - char* xdg = getenv("XDG_CACHE_HOME"); - if (!xdg || !*xdg) { - return QString("%1/.cache/%2").arg(QDir::homePath(), QCoreApplication::organizationName()); - } else { - return QString("%1/%2").arg(xdg, QCoreApplication::organizationName()); - } - #else - return GetConfigPath(Path_Root); - #endif - } - break; +#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN) + char* xdg = getenv("XDG_CACHE_HOME"); + if (!xdg || !*xdg) { + return QString("%1/.cache/%2") + .arg(QDir::homePath(), QCoreApplication::organizationName()); + } else { + return QString("%1/%2").arg(xdg, QCoreApplication::organizationName()); + } +#else + return GetConfigPath(Path_Root); +#endif + } break; case Path_AlbumCovers: return GetConfigPath(Path_Root) + "/albumcovers"; @@ -340,14 +339,15 @@ QString GetConfigPath(ConfigPath config) { case Path_GstreamerRegistry: return GetConfigPath(Path_Root) + - QString("/gst-registry-%1-bin").arg(QCoreApplication::applicationVersion()); + QString("/gst-registry-%1-bin") + .arg(QCoreApplication::applicationVersion()); case Path_DefaultMusicLibrary: - #ifdef Q_OS_DARWIN - return mac::GetMusicDirectory(); - #else - return QDir::homePath(); - #endif +#ifdef Q_OS_DARWIN + return mac::GetMusicDirectory(); +#else + return QDir::homePath(); +#endif case Path_LocalSpotifyBlob: return GetConfigPath(Path_Root) + "/spotifyblob"; @@ -373,26 +373,25 @@ void RevealFileInFinder(QString const& path) { #ifdef Q_OS_WIN void ShowFileInExplorer(QString const& path) { - QProcess::execute("explorer.exe", QStringList() << "/select," - << QDir::toNativeSeparators(path)); + QProcess::execute("explorer.exe", QStringList() + << "/select," + << QDir::toNativeSeparators(path)); } #endif void OpenInFileBrowser(const QList& urls) { QSet dirs; - foreach (const QUrl& url, urls) { + foreach(const QUrl & url, urls) { if (url.scheme() != "file") { continue; } QString path = url.toLocalFile(); - if (!QFile::exists(path)) - continue; + if (!QFile::exists(path)) continue; const QString directory = QFileInfo(path).dir().path(); - if (dirs.contains(directory)) - continue; + if (dirs.contains(directory)) continue; dirs.insert(directory); qLog(Debug) << path; #ifdef Q_OS_DARWIN @@ -407,28 +406,29 @@ void OpenInFileBrowser(const QList& urls) { } } -QByteArray Hmac(const QByteArray& key, const QByteArray& data, HashFunction method) { - const int kBlockSize = 64; // bytes +QByteArray Hmac(const QByteArray& key, const QByteArray& data, + HashFunction method) { + const int kBlockSize = 64; // bytes Q_ASSERT(key.length() <= kBlockSize); QByteArray inner_padding(kBlockSize, char(0x36)); QByteArray outer_padding(kBlockSize, char(0x5c)); - for (int i=0 ; i(ret.data()), &context); + clementine_sha2::SHA256_Final(reinterpret_cast(ret.data()), + &context); return ret; } // File must not be open and will be closed afterwards! -QByteArray Sha1File(QFile &file) { +QByteArray Sha1File(QFile& file) { file.open(QIODevice::ReadOnly); QCryptographicHash hash(QCryptographicHash::Sha1); QByteArray data; - while(!file.atEnd()) { - data = file.read(1000000); // 1 mib + while (!file.atEnd()) { + data = file.read(1000000); // 1 mib hash.addData(data.data(), data.length()); data.clear(); } @@ -485,8 +485,7 @@ QByteArray Sha1CoverHash(const QString& artist, const QString& album) { } QString PrettySize(const QSize& size) { - return QString::number(size.width()) + "x" + - QString::number(size.height()); + return QString::number(size.width()) + "x" + QString::number(size.height()); } void ForwardMouseEvent(const QMouseEvent* e, QWidget* target) { @@ -515,9 +514,14 @@ void ConsumeCurrentElement(QXmlStreamReader* reader) { int level = 1; while (level != 0 && !reader->atEnd()) { switch (reader->readNext()) { - case QXmlStreamReader::StartElement: ++level; break; - case QXmlStreamReader::EndElement: --level; break; - default: break; + case QXmlStreamReader::StartElement: + ++level; + break; + case QXmlStreamReader::EndElement: + --level; + break; + default: + break; } } } @@ -542,37 +546,36 @@ QDateTime ParseRFC822DateTime(const QString& text) { // This sucks but we need it because some podcasts don't quite follow the // spec properly - they might have 1-digit hour numbers for example. - QRegExp re("([a-zA-Z]{3}),? (\\d{1,2}) ([a-zA-Z]{3}) (\\d{4}) (\\d{1,2}):(\\d{1,2}):(\\d{1,2})"); - if (re.indexIn(text) == -1) - return QDateTime(); + QRegExp re( + "([a-zA-Z]{3}),? (\\d{1,2}) ([a-zA-Z]{3}) (\\d{4}) " + "(\\d{1,2}):(\\d{1,2}):(\\d{1,2})"); + if (re.indexIn(text) == -1) return QDateTime(); return QDateTime( - QDate::fromString(QString("%1 %2 %3 %4").arg(re.cap(1), re.cap(3), re.cap(2), re.cap(4)), Qt::TextDate), - QTime(re.cap(5).toInt(), re.cap(6).toInt(), re.cap(7).toInt())); + QDate::fromString(QString("%1 %2 %3 %4") + .arg(re.cap(1), re.cap(3), re.cap(2), re.cap(4)), + Qt::TextDate), + QTime(re.cap(5).toInt(), re.cap(6).toInt(), re.cap(7).toInt())); } const char* EnumToString(const QMetaObject& meta, const char* name, int value) { int index = meta.indexOfEnumerator(name); - if (index == -1) - return "[UnknownEnum]"; + if (index == -1) return "[UnknownEnum]"; QMetaEnum metaenum = meta.enumerator(index); const char* result = metaenum.valueToKey(value); - if (result == 0) - return "[UnknownEnumValue]"; + if (result == 0) return "[UnknownEnumValue]"; return result; } QStringList Prepend(const QString& text, const QStringList& list) { QStringList ret(list); - for (int i=0 ; i power_sources(IOPSCopyPowerSourcesInfo()); ScopedCFTypeRef power_source_list( IOPSCopyPowerSourcesList(power_sources.get())); for (CFIndex i = 0; i < CFArrayGetCount(power_source_list.get()); ++i) { CFTypeRef ps = CFArrayGetValueAtIndex(power_source_list.get(), i); - CFDictionaryRef description = IOPSGetPowerSourceDescription( - power_sources.get(), ps); + CFDictionaryRef description = + IOPSGetPowerSourceDescription(power_sources.get(), ps); if (CFDictionaryContainsKey(description, CFSTR(kIOPSBatteryHealthKey))) { return true; @@ -637,8 +642,9 @@ bool IsLaptop() { QString SystemLanguageName() { #if QT_VERSION >= 0x040800 - QString system_language = QLocale::system().uiLanguages().empty() ? - QLocale::system().name() : QLocale::system().uiLanguages().first(); + QString system_language = QLocale::system().uiLanguages().empty() + ? QLocale::system().name() + : QLocale::system().uiLanguages().first(); // uiLanguages returns strings with "-" as separators for language/region; // however QTranslator needs "_" separators system_language.replace("-", "_"); @@ -649,9 +655,8 @@ QString SystemLanguageName() { return system_language; } -bool UrlOnSameDriveAsClementine(const QUrl &url) { - if (url.scheme() != "file") - return false; +bool UrlOnSameDriveAsClementine(const QUrl& url) { + if (url.scheme() != "file") return false; #ifdef Q_OS_WIN QUrl appUrl = QUrl::fromLocalFile(QCoreApplication::applicationDirPath()); @@ -676,17 +681,15 @@ QString PathWithoutFilenameExtension(const QString& filename) { return filename; } -QString FiddleFileExtension(const QString& filename, const QString& new_extension) { +QString FiddleFileExtension(const QString& filename, + const QString& new_extension) { return PathWithoutFilenameExtension(filename) + "." + new_extension; } } // namespace Utilities - ScopedWCharArray::ScopedWCharArray(const QString& str) - : chars_(str.length()), - data_(new wchar_t[chars_ + 1]) -{ + : chars_(str.length()), data_(new wchar_t[chars_ + 1]) { str.toWCharArray(data_.get()); data_[chars_] = '\0'; } diff --git a/src/core/utilities.h b/src/core/utilities.h index a926e154d..8211f0d6e 100644 --- a/src/core/utilities.h +++ b/src/core/utilities.h @@ -34,129 +34,121 @@ class QXmlStreamReader; struct QMetaObject; namespace Utilities { - QString PrettyTime(int seconds); - QString PrettyTimeDelta(int seconds); - QString PrettyTimeNanosec(qint64 nanoseconds); - QString PrettySize(quint64 bytes); - QString PrettySize(const QSize& size); - QString WordyTime(quint64 seconds); - QString WordyTimeNanosec(qint64 nanoseconds); - QString Ago(int seconds_since_epoch, const QLocale& locale); - QString PrettyFutureDate(const QDate& date); +QString PrettyTime(int seconds); +QString PrettyTimeDelta(int seconds); +QString PrettyTimeNanosec(qint64 nanoseconds); +QString PrettySize(quint64 bytes); +QString PrettySize(const QSize& size); +QString WordyTime(quint64 seconds); +QString WordyTimeNanosec(qint64 nanoseconds); +QString Ago(int seconds_since_epoch, const QLocale& locale); +QString PrettyFutureDate(const QDate& date); - QString ColorToRgba(const QColor& color); +QString ColorToRgba(const QColor& color); - quint64 FileSystemCapacity(const QString& path); - quint64 FileSystemFreeSpace(const QString& path); +quint64 FileSystemCapacity(const QString& path); +quint64 FileSystemFreeSpace(const QString& path); - QString MakeTempDir(const QString template_name = QString()); - QString GetTemporaryFileName(); - void RemoveRecursive(const QString& path); - bool CopyRecursive(const QString& source, const QString& destination); - bool Copy(QIODevice* source, QIODevice* destination); +QString MakeTempDir(const QString template_name = QString()); +QString GetTemporaryFileName(); +void RemoveRecursive(const QString& path); +bool CopyRecursive(const QString& source, const QString& destination); +bool Copy(QIODevice* source, QIODevice* destination); - void OpenInFileBrowser(const QList& filenames); +void OpenInFileBrowser(const QList& filenames); - enum HashFunction { - Md5_Algo, - Sha256_Algo, - Sha1_Algo, - }; - QByteArray Hmac(const QByteArray& key, const QByteArray& data, HashFunction algo); - QByteArray HmacMd5(const QByteArray& key, const QByteArray& data); - QByteArray HmacSha256(const QByteArray& key, const QByteArray& data); - QByteArray HmacSha1(const QByteArray& key, const QByteArray& data); - QByteArray Sha256(const QByteArray& data); - QByteArray Sha1File(QFile& file); - QByteArray Sha1CoverHash(const QString& artist, const QString& album); +enum HashFunction { Md5_Algo, Sha256_Algo, Sha1_Algo, }; +QByteArray Hmac(const QByteArray& key, const QByteArray& data, + HashFunction algo); +QByteArray HmacMd5(const QByteArray& key, const QByteArray& data); +QByteArray HmacSha256(const QByteArray& key, const QByteArray& data); +QByteArray HmacSha1(const QByteArray& key, const QByteArray& data); +QByteArray Sha256(const QByteArray& data); +QByteArray Sha1File(QFile& file); +QByteArray Sha1CoverHash(const QString& artist, const QString& album); +// Picks an unused ephemeral port number. Doesn't hold the port open so +// there's the obvious race condition +quint16 PickUnusedPort(); - // Picks an unused ephemeral port number. Doesn't hold the port open so - // there's the obvious race condition - quint16 PickUnusedPort(); +// Forwards a mouse event to a different widget, remapping the event's widget +// coordinates relative to those of the target widget. +void ForwardMouseEvent(const QMouseEvent* e, QWidget* target); +// Checks if the mouse event was inside the widget's rectangle. +bool IsMouseEventInWidget(const QMouseEvent* e, const QWidget* widget); - // Forwards a mouse event to a different widget, remapping the event's widget - // coordinates relative to those of the target widget. - void ForwardMouseEvent(const QMouseEvent* e, QWidget* target); +// Reads all children of the current element, and returns with the stream +// reader either on the EndElement for the current element, or the end of the +// file - whichever came first. +void ConsumeCurrentElement(QXmlStreamReader* reader); - // Checks if the mouse event was inside the widget's rectangle. - bool IsMouseEventInWidget(const QMouseEvent* e, const QWidget* widget); +// Advances the stream reader until it finds an element with the given name. +// Returns false if the end of the document was reached before finding a +// matching element. +bool ParseUntilElement(QXmlStreamReader* reader, const QString& name); - // Reads all children of the current element, and returns with the stream - // reader either on the EndElement for the current element, or the end of the - // file - whichever came first. - void ConsumeCurrentElement(QXmlStreamReader* reader); +// Parses a string containing an RFC822 time and date. +QDateTime ParseRFC822DateTime(const QString& text); - // Advances the stream reader until it finds an element with the given name. - // Returns false if the end of the document was reached before finding a - // matching element. - bool ParseUntilElement(QXmlStreamReader* reader, const QString& name); +// Replaces some HTML entities with their normal characters. +QString DecodeHtmlEntities(const QString& text); - // Parses a string containing an RFC822 time and date. - QDateTime ParseRFC822DateTime(const QString& text); +// Shortcut for getting a Qt-aware enum value as a string. +// Pass in the QMetaObject of the class that owns the enum, the string name of +// the enum and a valid value from that enum. +const char* EnumToString(const QMetaObject& meta, const char* name, int value); - // Replaces some HTML entities with their normal characters. - QString DecodeHtmlEntities(const QString& text); +QStringList Prepend(const QString& text, const QStringList& list); +QStringList Updateify(const QStringList& list); - // Shortcut for getting a Qt-aware enum value as a string. - // Pass in the QMetaObject of the class that owns the enum, the string name of - // the enum and a valid value from that enum. - const char* EnumToString(const QMetaObject& meta, const char* name, int value); +// Check if two urls are on the same drive (mainly for windows) +bool UrlOnSameDriveAsClementine(const QUrl& url); - QStringList Prepend(const QString& text, const QStringList& list); - QStringList Updateify(const QStringList& list); +// Get relative path to clementine binary +QUrl GetRelativePathToClementineBin(const QUrl& url); - // Check if two urls are on the same drive (mainly for windows) - bool UrlOnSameDriveAsClementine(const QUrl& url); +// Get the path without the filename extension +QString PathWithoutFilenameExtension(const QString& filename); +QString FiddleFileExtension(const QString& filename, + const QString& new_extension); - // Get relative path to clementine binary - QUrl GetRelativePathToClementineBin(const QUrl& url); +enum ConfigPath { + Path_Root, + Path_AlbumCovers, + Path_NetworkCache, + Path_GstreamerRegistry, + Path_DefaultMusicLibrary, + Path_LocalSpotifyBlob, + Path_MoodbarCache, + Path_CacheRoot, +}; +QString GetConfigPath(ConfigPath config); - // Get the path without the filename extension - QString PathWithoutFilenameExtension(const QString& filename); - QString FiddleFileExtension(const QString& filename, const QString& new_extension); +// Returns the minor version of OS X (ie. 6 for Snow Leopard, 7 for Lion). +qint32 GetMacVersion(); - enum ConfigPath { - Path_Root, - Path_AlbumCovers, - Path_NetworkCache, - Path_GstreamerRegistry, - Path_DefaultMusicLibrary, - Path_LocalSpotifyBlob, - Path_MoodbarCache, - Path_CacheRoot, - }; - QString GetConfigPath(ConfigPath config); +// Borrowed from schedutils +enum IoPriority { + IOPRIO_CLASS_NONE = 0, + IOPRIO_CLASS_RT, + IOPRIO_CLASS_BE, + IOPRIO_CLASS_IDLE, +}; +enum { IOPRIO_WHO_PROCESS = 1, IOPRIO_WHO_PGRP, IOPRIO_WHO_USER, }; +static const int IOPRIO_CLASS_SHIFT = 13; - // Returns the minor version of OS X (ie. 6 for Snow Leopard, 7 for Lion). - qint32 GetMacVersion(); +int SetThreadIOPriority(IoPriority priority); +int GetThreadId(); - // Borrowed from schedutils - enum IoPriority { - IOPRIO_CLASS_NONE = 0, - IOPRIO_CLASS_RT, - IOPRIO_CLASS_BE, - IOPRIO_CLASS_IDLE, - }; - enum { - IOPRIO_WHO_PROCESS = 1, - IOPRIO_WHO_PGRP, - IOPRIO_WHO_USER, - }; - static const int IOPRIO_CLASS_SHIFT = 13; +// Returns true if this machine has a battery. +bool IsLaptop(); - int SetThreadIOPriority(IoPriority priority); - int GetThreadId(); - - // Returns true if this machine has a battery. - bool IsLaptop(); - - QString SystemLanguageName(); +QString SystemLanguageName(); } class ScopedWCharArray { -public: + public: ScopedWCharArray(const QString& str); QString ToString() const { return QString::fromWCharArray(data_.get()); } @@ -167,11 +159,11 @@ public: int characters() const { return chars_; } int bytes() const { return (chars_ + 1) * sizeof(wchar_t); } -private: + private: Q_DISABLE_COPY(ScopedWCharArray); int chars_; std::unique_ptr data_; }; -#endif // UTILITIES_H +#endif // UTILITIES_H diff --git a/src/covers/albumcoverexporter.cpp b/src/covers/albumcoverexporter.cpp index 1e5255f01..0e283c661 100644 --- a/src/covers/albumcoverexporter.cpp +++ b/src/covers/albumcoverexporter.cpp @@ -29,12 +29,12 @@ AlbumCoverExporter::AlbumCoverExporter(QObject* parent) thread_pool_(new QThreadPool(this)), exported_(0), skipped_(0), - all_(0) -{ + all_(0) { thread_pool_->setMaxThreadCount(kMaxConcurrentRequests); } -void AlbumCoverExporter::SetDialogResult(const AlbumCoverExport::DialogResult &dialog_result) { +void AlbumCoverExporter::SetDialogResult( + const AlbumCoverExport::DialogResult& dialog_result) { dialog_result_ = dialog_result; } @@ -43,9 +43,7 @@ void AlbumCoverExporter::AddExportRequest(Song song) { all_ = requests_.count(); } -void AlbumCoverExporter::Cancel() { - requests_.clear(); -} +void AlbumCoverExporter::Cancel() { requests_.clear(); } void AlbumCoverExporter::StartExporting() { exported_ = 0; @@ -54,8 +52,8 @@ void AlbumCoverExporter::StartExporting() { } void AlbumCoverExporter::AddJobsToPool() { - while (!requests_.isEmpty() - && thread_pool_->activeThreadCount() < thread_pool_->maxThreadCount()) { + while (!requests_.isEmpty() && + thread_pool_->activeThreadCount() < thread_pool_->maxThreadCount()) { CoverExportRunnable* runnable = requests_.dequeue(); connect(runnable, SIGNAL(CoverExported()), SLOT(CoverExported())); diff --git a/src/covers/albumcoverexporter.h b/src/covers/albumcoverexporter.h index 53593bf2e..2194f94bc 100644 --- a/src/covers/albumcoverexporter.h +++ b/src/covers/albumcoverexporter.h @@ -44,7 +44,7 @@ class AlbumCoverExporter : public QObject { int request_count() { return requests_.size(); } - signals: +signals: void AlbumCoversExportUpdate(int exported, int skipped, int all); private slots: diff --git a/src/covers/albumcoverfetcher.cpp b/src/covers/albumcoverfetcher.cpp index 7418d78fc..0600d17d2 100644 --- a/src/covers/albumcoverfetcher.cpp +++ b/src/covers/albumcoverfetcher.cpp @@ -23,15 +23,14 @@ const int AlbumCoverFetcher::kMaxConcurrentRequests = 5; - AlbumCoverFetcher::AlbumCoverFetcher(CoverProviders* cover_providers, - QObject* parent, QNetworkAccessManager* network) + QObject* parent, + QNetworkAccessManager* network) : QObject(parent), cover_providers_(cover_providers), network_(network ? network : new NetworkAccessManager(this)), next_id_(0), - request_starter_(new QTimer(this)) -{ + request_starter_(new QTimer(this)) { request_starter_->setInterval(1000); connect(request_starter_, SIGNAL(timeout()), SLOT(StartRequests())); } @@ -42,7 +41,7 @@ quint64 AlbumCoverFetcher::FetchAlbumCover(const QString& artist, request.artist = artist; request.album = album; request.search = false; - request.id = next_id_ ++; + request.id = next_id_++; AddRequest(request); return request.id; @@ -54,7 +53,7 @@ quint64 AlbumCoverFetcher::SearchForCovers(const QString& artist, request.artist = artist; request.album = album; request.search = true; - request.id = next_id_ ++; + request.id = next_id_++; AddRequest(request); return request.id; @@ -63,17 +62,15 @@ quint64 AlbumCoverFetcher::SearchForCovers(const QString& artist, void AlbumCoverFetcher::AddRequest(const CoverSearchRequest& req) { queued_requests_.enqueue(req); - if (!request_starter_->isActive()) - request_starter_->start(); + if (!request_starter_->isActive()) request_starter_->start(); - if (active_requests_.size() < kMaxConcurrentRequests) - StartRequests(); + if (active_requests_.size() < kMaxConcurrentRequests) StartRequests(); } void AlbumCoverFetcher::Clear() { queued_requests_.clear(); - foreach (AlbumCoverFetcherSearch* search, active_requests_.values()) { + foreach(AlbumCoverFetcherSearch * search, active_requests_.values()) { search->Cancel(); search->deleteLater(); } @@ -91,34 +88,35 @@ void AlbumCoverFetcher::StartRequests() { CoverSearchRequest request = queued_requests_.dequeue(); - // search objects are this fetcher's children so worst case scenario - they get + // search objects are this fetcher's children so worst case scenario - they + // get // deleted with it - AlbumCoverFetcherSearch* search = new AlbumCoverFetcherSearch( - request, network_, this); + AlbumCoverFetcherSearch* search = + new AlbumCoverFetcherSearch(request, network_, this); active_requests_.insert(request.id, search); connect(search, SIGNAL(SearchFinished(quint64, CoverSearchResults)), - SLOT(SingleSearchFinished(quint64, CoverSearchResults))); + SLOT(SingleSearchFinished(quint64, CoverSearchResults))); connect(search, SIGNAL(AlbumCoverFetched(quint64, const QImage&)), - SLOT(SingleCoverFetched(quint64, const QImage&))); + SLOT(SingleCoverFetched(quint64, const QImage&))); search->Start(cover_providers_); } } -void AlbumCoverFetcher::SingleSearchFinished(quint64 request_id, CoverSearchResults results) { +void AlbumCoverFetcher::SingleSearchFinished(quint64 request_id, + CoverSearchResults results) { AlbumCoverFetcherSearch* search = active_requests_.take(request_id); - if (!search) - return; + if (!search) return; search->deleteLater(); emit SearchFinished(request_id, results, search->statistics()); } -void AlbumCoverFetcher::SingleCoverFetched(quint64 request_id, const QImage& image) { +void AlbumCoverFetcher::SingleCoverFetched(quint64 request_id, + const QImage& image) { AlbumCoverFetcherSearch* search = active_requests_.take(request_id); - if (!search) - return; + if (!search) return; search->deleteLater(); emit AlbumCoverFetched(request_id, image, search->statistics()); diff --git a/src/covers/albumcoverfetcher.h b/src/covers/albumcoverfetcher.h index 034ddddfb..4b4cb0b8c 100644 --- a/src/covers/albumcoverfetcher.h +++ b/src/covers/albumcoverfetcher.h @@ -36,7 +36,7 @@ class AlbumCoverFetcherSearch; class CoverProviders; // This class represents a single search-for-cover request. It identifies -// and describes the request. +// and describes the request. struct CoverSearchRequest { // an unique (for one AlbumCoverFetcher) request identifier quint64 id; @@ -50,7 +50,8 @@ struct CoverSearchRequest { bool search; }; -// This structure represents a single result of some album's cover search request. +// This structure represents a single result of some album's cover search +// request. // It contains an URL that leads to a found cover plus its description (usually // the "artist - album" string). struct CoverSearchResult { @@ -66,21 +67,19 @@ struct CoverSearchResult { }; Q_DECLARE_METATYPE(CoverSearchResult); - // This is a complete result of a single search request (a list of results, each // describing one image, actually). typedef QList CoverSearchResults; Q_DECLARE_METATYPE(QList); - // This class searches for album covers for a given query or artist/album and // returns URLs. It's NOT thread-safe. class AlbumCoverFetcher : public QObject { Q_OBJECT public: - AlbumCoverFetcher(CoverProviders* cover_providers, - QObject* parent = 0, QNetworkAccessManager* network = 0); + AlbumCoverFetcher(CoverProviders* cover_providers, QObject* parent = 0, + QNetworkAccessManager* network = 0); virtual ~AlbumCoverFetcher() {} static const int kMaxConcurrentRequests; @@ -90,7 +89,7 @@ class AlbumCoverFetcher : public QObject { void Clear(); - signals: +signals: void AlbumCoverFetched(quint64, const QImage& cover, const CoverSearchStatistics& statistics); void SearchFinished(quint64, const CoverSearchResults& results, diff --git a/src/covers/albumcoverfetchersearch.cpp b/src/covers/albumcoverfetchersearch.cpp index 3ab54f1ab..d2c2d16ea 100644 --- a/src/covers/albumcoverfetchersearch.cpp +++ b/src/covers/albumcoverfetchersearch.cpp @@ -36,22 +36,22 @@ const int AlbumCoverFetcherSearch::kImageLoadTimeoutMs = 2500; const int AlbumCoverFetcherSearch::kTargetSize = 500; const float AlbumCoverFetcherSearch::kGoodScore = 1.85; -AlbumCoverFetcherSearch::AlbumCoverFetcherSearch(const CoverSearchRequest& request, - QNetworkAccessManager* network, - QObject* parent) - : QObject(parent), - request_(request), - image_load_timeout_(new NetworkTimeouts(kImageLoadTimeoutMs, this)), - network_(network), - cancel_requested_(false) -{ - // we will terminate the search after kSearchTimeoutMs miliseconds if we are not +AlbumCoverFetcherSearch::AlbumCoverFetcherSearch( + const CoverSearchRequest& request, QNetworkAccessManager* network, + QObject* parent) + : QObject(parent), + request_(request), + image_load_timeout_(new NetworkTimeouts(kImageLoadTimeoutMs, this)), + network_(network), + cancel_requested_(false) { + // we will terminate the search after kSearchTimeoutMs miliseconds if we are + // not // able to find all of the results before that point in time QTimer::singleShot(kSearchTimeoutMs, this, SLOT(TerminateSearch())); } void AlbumCoverFetcherSearch::TerminateSearch() { - foreach (int id, pending_requests_.keys()) { + foreach(int id, pending_requests_.keys()) { pending_requests_.take(id)->CancelSearch(id); } @@ -59,21 +59,21 @@ void AlbumCoverFetcherSearch::TerminateSearch() { } void AlbumCoverFetcherSearch::Start(CoverProviders* cover_providers) { - foreach(CoverProvider* provider, cover_providers->List()) { - connect(provider, SIGNAL(SearchFinished(int,QList)), - SLOT(ProviderSearchFinished(int,QList))); + foreach(CoverProvider * provider, cover_providers->List()) { + connect(provider, SIGNAL(SearchFinished(int, QList)), + SLOT(ProviderSearchFinished(int, QList))); const int id = cover_providers->NextId(); - const bool success = provider->StartSearch( - request_.artist, request_.album, id); + const bool success = + provider->StartSearch(request_.artist, request_.album, id); if (success) { pending_requests_[id] = provider; - statistics_.network_requests_made_ ++; + statistics_.network_requests_made_++; } } // end this search before it even began if there are no providers... - if(pending_requests_.isEmpty()) { + if (pending_requests_.isEmpty()) { TerminateSearch(); } } @@ -85,23 +85,22 @@ static bool CompareProviders(const CoverSearchResult& a, void AlbumCoverFetcherSearch::ProviderSearchFinished( int id, const QList& results) { - if (!pending_requests_.contains(id)) - return; + if (!pending_requests_.contains(id)) return; CoverProvider* provider = pending_requests_.take(id); CoverSearchResults results_copy(results); // Set categories on the results - for (int i=0 ; iname(); } // Add results from the current provider to our pool results_.append(results_copy); - statistics_.total_images_by_provider_[provider->name()] ++; + statistics_.total_images_by_provider_[provider->name()]++; // do we have more providers left? - if(!pending_requests_.isEmpty()) { + if (!pending_requests_.isEmpty()) { return; } @@ -121,7 +120,7 @@ void AlbumCoverFetcherSearch::AllProvidersFinished() { // no results? if (results_.isEmpty()) { - statistics_.missing_images_ ++; + statistics_.missing_images_++; emit AlbumCoverFetched(request_.id, QImage()); return; } @@ -138,7 +137,7 @@ void AlbumCoverFetcherSearch::AllProvidersFinished() { void AlbumCoverFetcherSearch::FetchMoreImages() { // Try the first one in each category. QString last_provider; - for (int i=0 ; iget(QNetworkRequest(result.image_url))); + RedirectFollower* image_reply = + new RedirectFollower(network_->get(QNetworkRequest(result.image_url))); NewClosure(image_reply, SIGNAL(finished()), this, - SLOT(ProviderCoverFetchFinished(RedirectFollower*)), image_reply); + SLOT(ProviderCoverFetchFinished(RedirectFollower*)), + image_reply); pending_image_loads_[image_reply] = result.provider; image_load_timeout_->AddReply(image_reply); - statistics_.network_requests_made_ ++; + statistics_.network_requests_made_++; } if (pending_image_loads_.isEmpty()) { @@ -164,7 +164,8 @@ void AlbumCoverFetcherSearch::FetchMoreImages() { } } -void AlbumCoverFetcherSearch::ProviderCoverFetchFinished(RedirectFollower* reply) { +void AlbumCoverFetcherSearch::ProviderCoverFetchFinished( + RedirectFollower* reply) { reply->deleteLater(); const QString provider = pending_image_loads_.take(reply); @@ -213,11 +214,12 @@ float AlbumCoverFetcherSearch::ScoreImage(const QImage& image) const { } // A 500x500px image scores 1.0, bigger scores higher - const float size_score = std::sqrt(float(image.width() * image.height())) / kTargetSize; + const float size_score = + std::sqrt(float(image.width() * image.height())) / kTargetSize; // A 1:1 image scores 1.0, anything else scores less const float aspect_score = 1.0 - float(image.height() - image.width()) / - std::max(image.height(), image.width()); + std::max(image.height(), image.width()); return size_score + aspect_score; } @@ -229,12 +231,12 @@ void AlbumCoverFetcherSearch::SendBestImage() { const CandidateImage best_image = candidate_images_.values().back(); image = best_image.second; - statistics_.chosen_images_by_provider_[best_image.first] ++; - statistics_.chosen_images_ ++; + statistics_.chosen_images_by_provider_[best_image.first]++; + statistics_.chosen_images_++; statistics_.chosen_width_ += image.width(); statistics_.chosen_height_ += image.height(); } else { - statistics_.missing_images_ ++; + statistics_.missing_images_++; } emit AlbumCoverFetched(request_.id, image); @@ -246,7 +248,7 @@ void AlbumCoverFetcherSearch::Cancel() { if (!pending_requests_.isEmpty()) { TerminateSearch(); } else if (!pending_image_loads_.isEmpty()) { - foreach (RedirectFollower* reply, pending_image_loads_.keys()) { + foreach(RedirectFollower * reply, pending_image_loads_.keys()) { reply->abort(); } pending_image_loads_.clear(); diff --git a/src/covers/albumcoverfetchersearch.h b/src/covers/albumcoverfetchersearch.h index 4e89502de..e8b88ca30 100644 --- a/src/covers/albumcoverfetchersearch.h +++ b/src/covers/albumcoverfetchersearch.h @@ -55,19 +55,19 @@ signals: // It's the end of search and we've fetched a cover. void AlbumCoverFetched(quint64, const QImage& cover); -private slots: + private slots: void ProviderSearchFinished(int id, const QList& results); void ProviderCoverFetchFinished(RedirectFollower* reply); void TerminateSearch(); -private: + private: void AllProvidersFinished(); void FetchMoreImages(); float ScoreImage(const QImage& image) const; void SendBestImage(); -private: + private: static const int kSearchTimeoutMs; static const int kImageLoadTimeoutMs; static const int kTargetSize; diff --git a/src/covers/albumcoverloader.cpp b/src/covers/albumcoverloader.cpp index a4c4241a4..00150e418 100644 --- a/src/covers/albumcoverloader.cpp +++ b/src/covers/albumcoverloader.cpp @@ -32,16 +32,12 @@ #include "internet/internetmodel.h" #include "internet/spotifyservice.h" - - AlbumCoverLoader::AlbumCoverLoader(QObject* parent) - : QObject(parent), - stop_requested_(false), - next_id_(1), - network_(new NetworkAccessManager(this)), - connected_spotify_(false) -{ -} + : QObject(parent), + stop_requested_(false), + next_id_(1), + network_(new NetworkAccessManager(this)), + connected_spotify_(false) {} QString AlbumCoverLoader::ImageCacheDir() { return Utilities::GetConfigPath(Utilities::Path_AlbumCovers); @@ -49,7 +45,7 @@ QString AlbumCoverLoader::ImageCacheDir() { void AlbumCoverLoader::CancelTask(quint64 id) { QMutexLocker l(&mutex_); - for (QQueue::iterator it = tasks_.begin() ; it != tasks_.end() ; ++it) { + for (QQueue::iterator it = tasks_.begin(); it != tasks_.end(); ++it) { if (it->id == id) { tasks_.erase(it); break; @@ -59,7 +55,7 @@ void AlbumCoverLoader::CancelTask(quint64 id) { void AlbumCoverLoader::CancelTasks(const QSet& ids) { QMutexLocker l(&mutex_); - for (QQueue::iterator it = tasks_.begin() ; it != tasks_.end() ; ) { + for (QQueue::iterator it = tasks_.begin(); it != tasks_.end();) { if (ids.contains(it->id)) { it = tasks_.erase(it); } else { @@ -83,7 +79,7 @@ quint64 AlbumCoverLoader::LoadImageAsync(const AlbumCoverLoaderOptions& options, { QMutexLocker l(&mutex_); - task.id = next_id_ ++; + task.id = next_id_++; tasks_.enqueue(task); } @@ -98,8 +94,7 @@ void AlbumCoverLoader::ProcessTasks() { Task task; { QMutexLocker l(&mutex_); - if (tasks_.isEmpty()) - return; + if (tasks_.isEmpty()) return; task = tasks_.dequeue(); } @@ -107,7 +102,7 @@ void AlbumCoverLoader::ProcessTasks() { } } -void AlbumCoverLoader::ProcessTask(Task *task) { +void AlbumCoverLoader::ProcessTask(Task* task) { TryLoadResult result = TryLoadImage(*task); if (result.started_async) { // The image is being loaded from a remote URL, we'll carry on later @@ -142,12 +137,17 @@ AlbumCoverLoader::TryLoadResult AlbumCoverLoader::TryLoadImage( const Task& task) { // An image embedded in the song itself takes priority if (!task.embedded_image.isNull()) - return TryLoadResult(false, true, ScaleAndPad(task.options, task.embedded_image)); + return TryLoadResult(false, true, + ScaleAndPad(task.options, task.embedded_image)); QString filename; switch (task.state) { - case State_TryingAuto: filename = task.art_automatic; break; - case State_TryingManual: filename = task.art_manual; break; + case State_TryingAuto: + filename = task.art_automatic; + break; + case State_TryingManual: + filename = task.art_manual; + break; } if (filename == Song::kManuallyUnsetCover) @@ -155,10 +155,12 @@ AlbumCoverLoader::TryLoadResult AlbumCoverLoader::TryLoadImage( if (filename == Song::kEmbeddedCover && !task.song_filename.isEmpty()) { const QImage taglib_image = - TagReaderClient::Instance()->LoadEmbeddedArtBlocking(task.song_filename); + TagReaderClient::Instance()->LoadEmbeddedArtBlocking( + task.song_filename); if (!taglib_image.isNull()) - return TryLoadResult(false, true, ScaleAndPad(task.options, taglib_image)); + return TryLoadResult(false, true, + ScaleAndPad(task.options, taglib_image)); } if (filename.toLower().startsWith("http://")) { @@ -174,8 +176,8 @@ AlbumCoverLoader::TryLoadResult AlbumCoverLoader::TryLoadImage( SpotifyService* spotify = InternetModel::Service(); if (!connected_spotify_) { - connect(spotify, SIGNAL(ImageLoaded(QString,QImage)), - SLOT(SpotifyImageLoaded(QString,QImage))); + connect(spotify, SIGNAL(ImageLoaded(QString, QImage)), + SLOT(SpotifyImageLoaded(QString, QImage))); connected_spotify_ = true; } @@ -192,13 +194,14 @@ AlbumCoverLoader::TryLoadResult AlbumCoverLoader::TryLoadImage( } QImage image(filename); - return TryLoadResult(false, !image.isNull(), - image.isNull() ? task.options.default_output_image_: image); + return TryLoadResult( + false, !image.isNull(), + image.isNull() ? task.options.default_output_image_ : image); } -void AlbumCoverLoader::SpotifyImageLoaded(const QString& id, const QImage& image) { - if (!remote_spotify_tasks_.contains(id)) - return; +void AlbumCoverLoader::SpotifyImageLoaded(const QString& id, + const QImage& image) { + if (!remote_spotify_tasks_.contains(id)) return; Task task = remote_spotify_tasks_.take(id); QImage scaled = ScaleAndPad(task.options, image); @@ -212,7 +215,8 @@ void AlbumCoverLoader::RemoteFetchFinished(QNetworkReply* reply) { Task task = remote_tasks_.take(reply); // Handle redirects. - QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); + QVariant redirect = + reply->attribute(QNetworkRequest::RedirectionTargetAttribute); if (redirect.isValid()) { if (++task.redirects > kMaxRedirects) { return; // Give up. @@ -243,8 +247,7 @@ void AlbumCoverLoader::RemoteFetchFinished(QNetworkReply* reply) { QImage AlbumCoverLoader::ScaleAndPad(const AlbumCoverLoaderOptions& options, const QImage& image) { - if (image.isNull()) - return image; + if (image.isNull()) return image; // Scale the image down QImage copy; @@ -255,8 +258,7 @@ QImage AlbumCoverLoader::ScaleAndPad(const AlbumCoverLoaderOptions& options, copy = image; } - if (!options.pad_output_image_) - return copy; + if (!options.pad_output_image_) return copy; // Pad the image to height_ x height_ QImage padded_image(options.desired_height_, options.desired_height_, @@ -265,8 +267,7 @@ QImage AlbumCoverLoader::ScaleAndPad(const AlbumCoverLoaderOptions& options, QPainter p(&padded_image); p.drawImage((options.desired_height_ - copy.width()) / 2, - (options.desired_height_ - copy.height()) / 2, - copy); + (options.desired_height_ - copy.height()) / 2, copy); p.end(); return padded_image; @@ -276,14 +277,12 @@ QPixmap AlbumCoverLoader::TryLoadPixmap(const QString& automatic, const QString& manual, const QString& filename) { QPixmap ret; - if (manual == Song::kManuallyUnsetCover) - return ret; - if (!manual.isEmpty()) - ret.load(manual); + if (manual == Song::kManuallyUnsetCover) return ret; + if (!manual.isEmpty()) ret.load(manual); if (ret.isNull()) { if (automatic == Song::kEmbeddedCover && !filename.isNull()) ret = QPixmap::fromImage( - TagReaderClient::Instance()->LoadEmbeddedArtBlocking(filename)); + TagReaderClient::Instance()->LoadEmbeddedArtBlocking(filename)); else if (!automatic.isEmpty()) ret.load(automatic); } @@ -291,8 +290,7 @@ QPixmap AlbumCoverLoader::TryLoadPixmap(const QString& automatic, } quint64 AlbumCoverLoader::LoadImageAsync(const AlbumCoverLoaderOptions& options, - const Song &song) { - return LoadImageAsync(options, - song.art_automatic(), song.art_manual(), + const Song& song) { + return LoadImageAsync(options, song.art_automatic(), song.art_manual(), song.url().toLocalFile(), song.image()); } diff --git a/src/covers/albumcoverloader.h b/src/covers/albumcoverloader.h index 987be6676..0ff4a384a 100644 --- a/src/covers/albumcoverloader.h +++ b/src/covers/albumcoverloader.h @@ -40,22 +40,23 @@ class AlbumCoverLoader : public QObject { static QString ImageCacheDir(); - quint64 LoadImageAsync(const AlbumCoverLoaderOptions& options, const Song& song); - virtual quint64 LoadImageAsync( - const AlbumCoverLoaderOptions& options, - const QString& art_automatic, - const QString& art_manual, - const QString& song_filename = QString(), - const QImage& embedded_image = QImage()); + quint64 LoadImageAsync(const AlbumCoverLoaderOptions& options, + const Song& song); + virtual quint64 LoadImageAsync(const AlbumCoverLoaderOptions& options, + const QString& art_automatic, + const QString& art_manual, + const QString& song_filename = QString(), + const QImage& embedded_image = QImage()); void CancelTask(quint64 id); void CancelTasks(const QSet& ids); static QPixmap TryLoadPixmap(const QString& automatic, const QString& manual, const QString& filename = QString()); - static QImage ScaleAndPad(const AlbumCoverLoaderOptions& options, const QImage& image); + static QImage ScaleAndPad(const AlbumCoverLoaderOptions& options, + const QImage& image); - signals: +signals: void ImageLoaded(quint64 id, const QImage& image); void ImageLoaded(quint64 id, const QImage& scaled, const QImage& original); @@ -65,10 +66,7 @@ class AlbumCoverLoader : public QObject { void SpotifyImageLoaded(const QString& url, const QImage& image); protected: - enum State { - State_TryingManual, - State_TryingAuto, - }; + enum State { State_TryingManual, State_TryingAuto, }; struct Task { Task() : redirects(0) {} @@ -86,7 +84,7 @@ class AlbumCoverLoader : public QObject { struct TryLoadResult { TryLoadResult(bool async, bool success, const QImage& i) - : started_async(async), loaded_success(success), image(i) {} + : started_async(async), loaded_success(success), image(i) {} bool started_async; bool loaded_success; @@ -112,4 +110,4 @@ class AlbumCoverLoader : public QObject { static const int kMaxRedirects = 3; }; -#endif // ALBUMCOVERLOADER_H +#endif // ALBUMCOVERLOADER_H diff --git a/src/covers/albumcoverloaderoptions.cpp b/src/covers/albumcoverloaderoptions.cpp index e3a522f1d..f0d8b6b1d 100644 --- a/src/covers/albumcoverloaderoptions.cpp +++ b/src/covers/albumcoverloaderoptions.cpp @@ -1,19 +1,18 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ #include "albumcoverloaderoptions.h" - diff --git a/src/covers/albumcoverloaderoptions.h b/src/covers/albumcoverloaderoptions.h index 33faccc15..70d21a178 100644 --- a/src/covers/albumcoverloaderoptions.h +++ b/src/covers/albumcoverloaderoptions.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -22,10 +22,9 @@ struct AlbumCoverLoaderOptions { AlbumCoverLoaderOptions() - : desired_height_(120), - scale_output_image_(true), - pad_output_image_(true) - {} + : desired_height_(120), + scale_output_image_(true), + pad_output_image_(true) {} int desired_height_; bool scale_output_image_; @@ -33,4 +32,4 @@ struct AlbumCoverLoaderOptions { QImage default_output_image_; }; -#endif // ALBUMCOVERLOADEROPTIONS_H +#endif // ALBUMCOVERLOADEROPTIONS_H diff --git a/src/covers/amazoncoverprovider.cpp b/src/covers/amazoncoverprovider.cpp index 18b31235f..0ce4c064c 100644 --- a/src/covers/amazoncoverprovider.cpp +++ b/src/covers/amazoncoverprovider.cpp @@ -35,12 +35,11 @@ const char* AmazonCoverProvider::kUrl = "http://ecs.amazonaws.com/onca/xml"; const char* AmazonCoverProvider::kAssociateTag = "clemmusiplay-20"; AmazonCoverProvider::AmazonCoverProvider(QObject* parent) - : CoverProvider("Amazon", parent), - network_(new NetworkAccessManager(this)) -{ -} + : CoverProvider("Amazon", parent), + network_(new NetworkAccessManager(this)) {} -bool AmazonCoverProvider::StartSearch(const QString& artist, const QString& album, int id) { +bool AmazonCoverProvider::StartSearch(const QString& artist, + const QString& album, int id) { typedef QPair Arg; typedef QList ArgList; @@ -48,22 +47,22 @@ bool AmazonCoverProvider::StartSearch(const QString& artist, const QString& albu typedef QList EncodedArgList; // Must be sorted by parameter name - ArgList args = ArgList() - << Arg("AWSAccessKeyId", QByteArray::fromBase64(kAccessKeyB64)) - << Arg("AssociateTag", kAssociateTag) - << Arg("Keywords", artist + " " + album) - << Arg("Operation", "ItemSearch") - << Arg("ResponseGroup", "Images") - << Arg("SearchIndex", "All") - << Arg("Service", "AWSECommerceService") - << Arg("Timestamp", QDateTime::currentDateTime().toString("yyyy-MM-ddThh:mm:ss.zzzZ")) - << Arg("Version", "2009-11-01"); + ArgList args = + ArgList() << Arg("AWSAccessKeyId", QByteArray::fromBase64(kAccessKeyB64)) + << Arg("AssociateTag", kAssociateTag) + << Arg("Keywords", artist + " " + album) + << Arg("Operation", "ItemSearch") + << Arg("ResponseGroup", "Images") << Arg("SearchIndex", "All") + << Arg("Service", "AWSECommerceService") + << Arg("Timestamp", QDateTime::currentDateTime().toString( + "yyyy-MM-ddThh:mm:ss.zzzZ")) + << Arg("Version", "2009-11-01"); EncodedArgList encoded_args; QStringList query_items; // Encode the arguments - foreach (const Arg& arg, args) { + foreach(const Arg & arg, args) { EncodedArg encoded_arg(QUrl::toPercentEncoding(arg.first), QUrl::toPercentEncoding(arg.second)); encoded_args << encoded_arg; @@ -73,19 +72,21 @@ bool AmazonCoverProvider::StartSearch(const QString& artist, const QString& albu // Sign the request QUrl url(kUrl); - const QByteArray data_to_sign = QString("GET\n%1\n%2\n%3").arg( - url.host(), url.path(), query_items.join("&")).toAscii(); + const QByteArray data_to_sign = + QString("GET\n%1\n%2\n%3") + .arg(url.host(), url.path(), query_items.join("&")) + .toAscii(); const QByteArray signature(Utilities::HmacSha256( - QByteArray::fromBase64(kSecretAccessKeyB64), data_to_sign)); + QByteArray::fromBase64(kSecretAccessKeyB64), data_to_sign)); // Add the signature to the request - encoded_args << EncodedArg("Signature", QUrl::toPercentEncoding(signature.toBase64())); + encoded_args << EncodedArg("Signature", + QUrl::toPercentEncoding(signature.toBase64())); url.setEncodedQueryItems(encoded_args); QNetworkReply* reply = network_->get(QNetworkRequest(url)); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(QueryFinished(QNetworkReply*, int)), - reply, id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(QueryFinished(QNetworkReply*, int)), reply, id); return true; } @@ -107,44 +108,46 @@ void AmazonCoverProvider::QueryFinished(QNetworkReply* reply, int id) { emit SearchFinished(id, results); } -void AmazonCoverProvider::ReadItem(QXmlStreamReader* reader, CoverSearchResults* results) { +void AmazonCoverProvider::ReadItem(QXmlStreamReader* reader, + CoverSearchResults* results) { while (!reader->atEnd()) { switch (reader->readNext()) { - case QXmlStreamReader::StartElement: - if (reader->name() == "LargeImage") { - ReadLargeImage(reader, results); - } else { - reader->skipCurrentElement(); - } - break; + case QXmlStreamReader::StartElement: + if (reader->name() == "LargeImage") { + ReadLargeImage(reader, results); + } else { + reader->skipCurrentElement(); + } + break; - case QXmlStreamReader::EndElement: - return; + case QXmlStreamReader::EndElement: + return; - default: - break; + default: + break; } } } -void AmazonCoverProvider::ReadLargeImage(QXmlStreamReader* reader, CoverSearchResults* results) { +void AmazonCoverProvider::ReadLargeImage(QXmlStreamReader* reader, + CoverSearchResults* results) { while (!reader->atEnd()) { switch (reader->readNext()) { - case QXmlStreamReader::StartElement: - if (reader->name() == "URL") { - CoverSearchResult result; - result.image_url = QUrl(reader->readElementText()); - results->append(result); - } else { - reader->skipCurrentElement(); - } - break; + case QXmlStreamReader::StartElement: + if (reader->name() == "URL") { + CoverSearchResult result; + result.image_url = QUrl(reader->readElementText()); + results->append(result); + } else { + reader->skipCurrentElement(); + } + break; - case QXmlStreamReader::EndElement: - return; + case QXmlStreamReader::EndElement: + return; - default: - break; + default: + break; } } } diff --git a/src/covers/amazoncoverprovider.h b/src/covers/amazoncoverprovider.h index 766a6746d..73fa94691 100644 --- a/src/covers/amazoncoverprovider.h +++ b/src/covers/amazoncoverprovider.h @@ -24,11 +24,10 @@ class QNetworkAccessManager; - class AmazonCoverProvider : public CoverProvider { Q_OBJECT -public: + public: AmazonCoverProvider(QObject* parent = NULL); static const char* kAccessKeyB64; @@ -38,15 +37,15 @@ public: bool StartSearch(const QString& artist, const QString& album, int id); -private slots: + private slots: void QueryFinished(QNetworkReply* reply, int id); -private: + private: void ReadItem(QXmlStreamReader* reader, CoverSearchResults* results); void ReadLargeImage(QXmlStreamReader* reader, CoverSearchResults* results); -private: + private: QNetworkAccessManager* network_; }; -#endif // AMAZONCOVERPROVIDER_H +#endif // AMAZONCOVERPROVIDER_H diff --git a/src/covers/coverexportrunnable.cpp b/src/covers/coverexportrunnable.cpp index 600e816fc..9b5d30d67 100644 --- a/src/covers/coverexportrunnable.cpp +++ b/src/covers/coverexportrunnable.cpp @@ -22,39 +22,36 @@ #include #include -CoverExportRunnable::CoverExportRunnable(const AlbumCoverExport::DialogResult& dialog_result, - const Song& song) - : dialog_result_(dialog_result), - song_(song) -{ -} +CoverExportRunnable::CoverExportRunnable( + const AlbumCoverExport::DialogResult& dialog_result, const Song& song) + : dialog_result_(dialog_result), song_(song) {} void CoverExportRunnable::run() { QString cover_path = GetCoverPath(); // manually unset? - if(cover_path.isEmpty()) { + if (cover_path.isEmpty()) { EmitCoverSkipped(); } else { - if(dialog_result_.RequiresCoverProcessing()) { + if (dialog_result_.RequiresCoverProcessing()) { ProcessAndExportCover(); } else { ExportCover(); } - } } QString CoverExportRunnable::GetCoverPath() { - if(song_.has_manually_unset_cover()) { + if (song_.has_manually_unset_cover()) { return QString(); - // Export downloaded covers? - } else if(!song_.art_manual().isEmpty() && dialog_result_.export_downloaded_) { + // Export downloaded covers? + } else if (!song_.art_manual().isEmpty() && + dialog_result_.export_downloaded_) { return song_.art_manual(); - // Export embedded covers? - } else if(!song_.art_automatic().isEmpty() - && song_.art_automatic() == Song::kEmbeddedCover - && dialog_result_.export_embedded_) { + // Export embedded covers? + } else if (!song_.art_automatic().isEmpty() && + song_.art_automatic() == Song::kEmbeddedCover && + dialog_result_.export_embedded_) { return song_.art_automatic(); } else { return QString(); @@ -78,10 +75,11 @@ void CoverExportRunnable::ProcessAndExportCover() { QImage disk_cover; // load embedded cover if any - if(song_.has_embedded_cover()) { - embedded_cover = TagReaderClient::Instance()->LoadEmbeddedArtBlocking(song_.url().toLocalFile()); + if (song_.has_embedded_cover()) { + embedded_cover = TagReaderClient::Instance()->LoadEmbeddedArtBlocking( + song_.url().toLocalFile()); - if(embedded_cover.isNull()) { + if (embedded_cover.isNull()) { EmitCoverSkipped(); return; } @@ -91,8 +89,8 @@ void CoverExportRunnable::ProcessAndExportCover() { // load a file cover which iss mandatory if there's no embedded cover disk_cover.load(cover_path); - if(embedded_cover.isNull()) { - if(disk_cover.isNull()) { + if (embedded_cover.isNull()) { + if (disk_cover.isNull()) { EmitCoverSkipped(); return; } @@ -100,49 +98,51 @@ void CoverExportRunnable::ProcessAndExportCover() { } // rescale if necessary - if(dialog_result_.IsSizeForced()) { - cover = cover.scaled(QSize(dialog_result_.width_, dialog_result_.height_), Qt::IgnoreAspectRatio); + if (dialog_result_.IsSizeForced()) { + cover = cover.scaled(QSize(dialog_result_.width_, dialog_result_.height_), + Qt::IgnoreAspectRatio); } QString dir = song_.url().toLocalFile().section('/', 0, -2); QString extension = cover_path.section('.', -1); QString new_file = dir + '/' + dialog_result_.fileName_ + '.' + - (cover_path == Song::kEmbeddedCover - ? "jpg" - : extension); + (cover_path == Song::kEmbeddedCover ? "jpg" : extension); // If the file exists, do not override! - if(dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode_None && QFile::exists(new_file)) { + if (dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode_None && + QFile::exists(new_file)) { EmitCoverSkipped(); return; } - // we're handling overwrite as remove + copy so we need to delete the old file first - if(QFile::exists(new_file) && dialog_result_.overwrite_ != AlbumCoverExport::OverwriteMode_None) { + // we're handling overwrite as remove + copy so we need to delete the old file + // first + if (QFile::exists(new_file) && + dialog_result_.overwrite_ != AlbumCoverExport::OverwriteMode_None) { // if the mode is "overwrite smaller" then skip the cover if a bigger one // is already available in the folder - if(dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode_Smaller) { + if (dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode_Smaller) { QImage existing; existing.load(new_file); - if(existing.isNull() || existing.size().height() >= cover.size().height() - || existing.size().width() >= cover.size().width()) { + if (existing.isNull() || + existing.size().height() >= cover.size().height() || + existing.size().width() >= cover.size().width()) { EmitCoverSkipped(); return; - } } - if(!QFile::remove(new_file)) { + if (!QFile::remove(new_file)) { EmitCoverSkipped(); return; } } - if(cover.save(new_file)) { + if (cover.save(new_file)) { EmitCoverExported(); } else { EmitCoverSkipped(); @@ -157,34 +157,36 @@ void CoverExportRunnable::ExportCover() { QString extension = cover_path.section('.', -1); QString new_file = dir + '/' + dialog_result_.fileName_ + '.' + - (cover_path == Song::kEmbeddedCover - ? "jpg" - : extension); + (cover_path == Song::kEmbeddedCover ? "jpg" : extension); // If the file exists, do not override! - if(dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode_None && QFile::exists(new_file)) { + if (dialog_result_.overwrite_ == AlbumCoverExport::OverwriteMode_None && + QFile::exists(new_file)) { EmitCoverSkipped(); return; } - // we're handling overwrite as remove + copy so we need to delete the old file first - if(dialog_result_.overwrite_ != AlbumCoverExport::OverwriteMode_None && QFile::exists(new_file)) { - if(!QFile::remove(new_file)) { + // we're handling overwrite as remove + copy so we need to delete the old file + // first + if (dialog_result_.overwrite_ != AlbumCoverExport::OverwriteMode_None && + QFile::exists(new_file)) { + if (!QFile::remove(new_file)) { EmitCoverSkipped(); return; } } - if(cover_path == Song::kEmbeddedCover) { + if (cover_path == Song::kEmbeddedCover) { // an embedded cover - QImage embedded = TagReaderClient::Instance()->LoadEmbeddedArtBlocking(song_.url().toLocalFile()); - if(!embedded.save(new_file)) { + QImage embedded = TagReaderClient::Instance()->LoadEmbeddedArtBlocking( + song_.url().toLocalFile()); + if (!embedded.save(new_file)) { EmitCoverSkipped(); return; } } else { // automatic or manual cover, available in an image file - if(!QFile::copy(cover_path, new_file)) { + if (!QFile::copy(cover_path, new_file)) { EmitCoverSkipped(); return; } @@ -192,11 +194,6 @@ void CoverExportRunnable::ExportCover() { EmitCoverExported(); } -void CoverExportRunnable::EmitCoverExported() { - emit CoverExported(); -} +void CoverExportRunnable::EmitCoverExported() { emit CoverExported(); } - -void CoverExportRunnable::EmitCoverSkipped() { - emit CoverSkipped(); -} +void CoverExportRunnable::EmitCoverSkipped() { emit CoverSkipped(); } diff --git a/src/covers/coverexportrunnable.h b/src/covers/coverexportrunnable.h index 89e70e5f1..0b929e942 100644 --- a/src/covers/coverexportrunnable.h +++ b/src/covers/coverexportrunnable.h @@ -27,7 +27,7 @@ class AlbumCoverExporter; class CoverExportRunnable : public QObject, public QRunnable { - Q_OBJECT + Q_OBJECT public: CoverExportRunnable(const AlbumCoverExport::DialogResult& dialog_result, @@ -36,7 +36,7 @@ class CoverExportRunnable : public QObject, public QRunnable { void run(); - signals: +signals: void CoverExported(); void CoverSkipped(); diff --git a/src/covers/coverprovider.cpp b/src/covers/coverprovider.cpp index 10738baed..f87bcd9af 100644 --- a/src/covers/coverprovider.cpp +++ b/src/covers/coverprovider.cpp @@ -18,7 +18,4 @@ #include "coverprovider.h" CoverProvider::CoverProvider(const QString& name, QObject* parent) - : QObject(parent), - name_(name) -{ -} + : QObject(parent), name_(name) {} diff --git a/src/covers/coverprovider.h b/src/covers/coverprovider.h index c3d509b33..d3aec5545 100644 --- a/src/covers/coverprovider.h +++ b/src/covers/coverprovider.h @@ -31,7 +31,7 @@ class QNetworkReply; class CoverProvider : public QObject { Q_OBJECT -public: + public: CoverProvider(const QString& name, QObject* parent); // A name (very short description) of this provider, like "last.fm". @@ -40,15 +40,16 @@ public: // Starts searching for covers matching the given query text. Returns true // if the query has been started, or false if an error occurred. The provider // should remember the ID and emit it along with the result when it finishes. - virtual bool StartSearch(const QString& artist, const QString& album, int id) = 0; + virtual bool StartSearch(const QString& artist, const QString& album, + int id) = 0; virtual void CancelSearch(int id) {} signals: void SearchFinished(int id, const QList& results); -private: + private: QString name_; }; -#endif // COVERPROVIDER_H +#endif // COVERPROVIDER_H diff --git a/src/covers/coverproviders.cpp b/src/covers/coverproviders.cpp index b81d4f8dd..5475e0b3a 100644 --- a/src/covers/coverproviders.cpp +++ b/src/covers/coverproviders.cpp @@ -20,9 +20,7 @@ #include "coverproviders.h" #include "core/logging.h" -CoverProviders::CoverProviders(QObject* parent) - : QObject(parent) { -} +CoverProviders::CoverProviders(QObject* parent) : QObject(parent) {} void CoverProviders::AddProvider(CoverProvider* provider) { { @@ -35,8 +33,7 @@ void CoverProviders::AddProvider(CoverProvider* provider) { } void CoverProviders::RemoveProvider(CoverProvider* provider) { - if (!provider) - return; + if (!provider) return; // It's not safe to dereference provider at this pointbecause it might have // already been destroyed. @@ -60,6 +57,4 @@ void CoverProviders::ProviderDestroyed() { RemoveProvider(provider); } -int CoverProviders::NextId() { - return next_id_.fetchAndAddRelaxed(1); -} +int CoverProviders::NextId() { return next_id_.fetchAndAddRelaxed(1); } diff --git a/src/covers/coverproviders.h b/src/covers/coverproviders.h index 61ed702b4..f56ea3b80 100644 --- a/src/covers/coverproviders.h +++ b/src/covers/coverproviders.h @@ -31,7 +31,7 @@ class CoverProvider; class CoverProviders : public QObject { Q_OBJECT -public: + public: CoverProviders(QObject* parent = NULL); // Lets a cover provider register itself in the repository. @@ -46,10 +46,10 @@ public: int NextId(); -private slots: + private slots: void ProviderDestroyed(); -private: + private: Q_DISABLE_COPY(CoverProviders); QMap cover_providers_; @@ -58,4 +58,4 @@ private: QAtomicInt next_id_; }; -#endif // COVERPROVIDERS_H +#endif // COVERPROVIDERS_H diff --git a/src/covers/coversearchstatistics.cpp b/src/covers/coversearchstatistics.cpp index 5a3bae616..bcd428d5a 100644 --- a/src/covers/coversearchstatistics.cpp +++ b/src/covers/coversearchstatistics.cpp @@ -18,23 +18,22 @@ #include "coversearchstatistics.h" CoverSearchStatistics::CoverSearchStatistics() - : network_requests_made_(0), - bytes_transferred_(0), - chosen_images_(0), - missing_images_(0), - chosen_width_(0), - chosen_height_(0) -{ -} + : network_requests_made_(0), + bytes_transferred_(0), + chosen_images_(0), + missing_images_(0), + chosen_width_(0), + chosen_height_(0) {} -CoverSearchStatistics& CoverSearchStatistics::operator +=(const CoverSearchStatistics& other) { +CoverSearchStatistics& CoverSearchStatistics::operator+=( + const CoverSearchStatistics& other) { network_requests_made_ += other.network_requests_made_; bytes_transferred_ += other.bytes_transferred_; - foreach (const QString& key, other.chosen_images_by_provider_.keys()) { + foreach(const QString & key, other.chosen_images_by_provider_.keys()) { chosen_images_by_provider_[key] += other.chosen_images_by_provider_[key]; } - foreach (const QString& key, other.total_images_by_provider_.keys()) { + foreach(const QString & key, other.total_images_by_provider_.keys()) { total_images_by_provider_[key] += other.total_images_by_provider_[key]; } diff --git a/src/covers/coversearchstatistics.h b/src/covers/coversearchstatistics.h index 90b4b67d8..5e4dd58c2 100644 --- a/src/covers/coversearchstatistics.h +++ b/src/covers/coversearchstatistics.h @@ -24,7 +24,7 @@ struct CoverSearchStatistics { CoverSearchStatistics(); - CoverSearchStatistics& operator +=(const CoverSearchStatistics& other); + CoverSearchStatistics& operator+=(const CoverSearchStatistics& other); quint64 network_requests_made_; quint64 bytes_transferred_; @@ -40,4 +40,4 @@ struct CoverSearchStatistics { QString AverageDimensions() const; }; -#endif // COVERSEARCHSTATISTICS_H +#endif // COVERSEARCHSTATISTICS_H diff --git a/src/covers/coversearchstatisticsdialog.cpp b/src/covers/coversearchstatisticsdialog.cpp index 449ad2f8a..f85cfe1fb 100644 --- a/src/covers/coversearchstatisticsdialog.cpp +++ b/src/covers/coversearchstatisticsdialog.cpp @@ -19,44 +19,41 @@ #include "ui_coversearchstatisticsdialog.h" #include "core/utilities.h" -CoverSearchStatisticsDialog::CoverSearchStatisticsDialog(QWidget *parent) - : QDialog(parent), - ui_(new Ui_CoverSearchStatisticsDialog) -{ +CoverSearchStatisticsDialog::CoverSearchStatisticsDialog(QWidget* parent) + : QDialog(parent), ui_(new Ui_CoverSearchStatisticsDialog) { ui_->setupUi(this); details_layout_ = new QVBoxLayout(ui_->details); details_layout_->setSpacing(0); setStyleSheet( - "#details {" - " background-color: palette(base);" - "}" - "#details QLabel[type=\"label\"] {" - " border: 2px solid transparent;" - " border-right: 2px solid palette(midlight);" - " margin-right: 10px;" - "}" - "#details QLabel[type=\"value\"] {" - " font-weight: bold;" - " max-width: 100px;" - "}" - ); + "#details {" + " background-color: palette(base);" + "}" + "#details QLabel[type=\"label\"] {" + " border: 2px solid transparent;" + " border-right: 2px solid palette(midlight);" + " margin-right: 10px;" + "}" + "#details QLabel[type=\"value\"] {" + " font-weight: bold;" + " max-width: 100px;" + "}"); } -CoverSearchStatisticsDialog::~CoverSearchStatisticsDialog() { - delete ui_; -} +CoverSearchStatisticsDialog::~CoverSearchStatisticsDialog() { delete ui_; } -void CoverSearchStatisticsDialog::Show(const CoverSearchStatistics& statistics) { +void CoverSearchStatisticsDialog::Show( + const CoverSearchStatistics& statistics) { QStringList providers(statistics.total_images_by_provider_.keys()); qSort(providers); - ui_->summary->setText(tr("Got %1 covers out of %2 (%3 failed)") - .arg(statistics.chosen_images_) - .arg(statistics.chosen_images_ + statistics.missing_images_) - .arg(statistics.missing_images_)); + ui_->summary->setText( + tr("Got %1 covers out of %2 (%3 failed)") + .arg(statistics.chosen_images_) + .arg(statistics.chosen_images_ + statistics.missing_images_) + .arg(statistics.missing_images_)); - foreach (const QString& provider, providers) { + foreach(const QString & provider, providers) { AddLine(tr("Covers from %1").arg(provider), QString::number(statistics.chosen_images_by_provider_[provider])); } @@ -70,15 +67,16 @@ void CoverSearchStatisticsDialog::Show(const CoverSearchStatistics& statistics) AddLine(tr("Average image size"), statistics.AverageDimensions()); AddLine(tr("Total bytes transferred"), statistics.bytes_transferred_ - ? Utilities::PrettySize(statistics.bytes_transferred_) - : "0 bytes"); + ? Utilities::PrettySize(statistics.bytes_transferred_) + : "0 bytes"); details_layout_->addStretch(); show(); } -void CoverSearchStatisticsDialog::AddLine(const QString& label, const QString& value) { +void CoverSearchStatisticsDialog::AddLine(const QString& label, + const QString& value) { QLabel* label1 = new QLabel(label); QLabel* label2 = new QLabel(value); diff --git a/src/covers/coversearchstatisticsdialog.h b/src/covers/coversearchstatisticsdialog.h index 6f53e0b18..f3e552ad1 100644 --- a/src/covers/coversearchstatisticsdialog.h +++ b/src/covers/coversearchstatisticsdialog.h @@ -29,19 +29,19 @@ class QVBoxLayout; class CoverSearchStatisticsDialog : public QDialog { Q_OBJECT -public: + public: CoverSearchStatisticsDialog(QWidget* parent = 0); ~CoverSearchStatisticsDialog(); void Show(const CoverSearchStatistics& statistics); -private: + private: void AddLine(const QString& label, const QString& value); void AddSpacer(); -private: + private: Ui_CoverSearchStatisticsDialog* ui_; QVBoxLayout* details_layout_; }; -#endif // COVERSEARCHSTATISTICSDIALOG_H +#endif // COVERSEARCHSTATISTICSDIALOG_H diff --git a/src/covers/currentartloader.cpp b/src/covers/currentartloader.cpp index d0dd47a9c..0567e6357 100644 --- a/src/covers/currentartloader.cpp +++ b/src/covers/currentartloader.cpp @@ -25,24 +25,22 @@ #include CurrentArtLoader::CurrentArtLoader(Application* app, QObject* parent) - : QObject(parent), - app_(app), - temp_file_pattern_(QDir::tempPath() + "/clementine-art-XXXXXX.jpg"), - id_(0) -{ + : QObject(parent), + app_(app), + temp_file_pattern_(QDir::tempPath() + "/clementine-art-XXXXXX.jpg"), + id_(0) { options_.scale_output_image_ = false; options_.pad_output_image_ = false; options_.default_output_image_ = QImage(":nocover.png"); - connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64,QImage)), - SLOT(TempArtLoaded(quint64,QImage))); + connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)), + SLOT(TempArtLoaded(quint64, QImage))); connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), SLOT(LoadArt(Song))); } -CurrentArtLoader::~CurrentArtLoader() { -} +CurrentArtLoader::~CurrentArtLoader() {} void CurrentArtLoader::LoadArt(const Song& song) { last_song_ = song; @@ -50,8 +48,7 @@ void CurrentArtLoader::LoadArt(const Song& song) { } void CurrentArtLoader::TempArtLoaded(quint64 id, const QImage& image) { - if (id != id_) - return; + if (id != id_) return; id_ = 0; QString uri; diff --git a/src/covers/currentartloader.h b/src/covers/currentartloader.h index 5b24e71fd..cea049325 100644 --- a/src/covers/currentartloader.h +++ b/src/covers/currentartloader.h @@ -33,24 +33,25 @@ class QTemporaryFile; class CurrentArtLoader : public QObject { Q_OBJECT -public: + public: CurrentArtLoader(Application* app, QObject* parent = 0); ~CurrentArtLoader(); const AlbumCoverLoaderOptions& options() const { return options_; } const Song& last_song() const { return last_song_; } -public slots: + public slots: void LoadArt(const Song& song); signals: void ArtLoaded(const Song& song, const QString& uri, const QImage& image); - void ThumbnailLoaded(const Song& song, const QString& uri, const QImage& image); + void ThumbnailLoaded(const Song& song, const QString& uri, + const QImage& image); -private slots: + private slots: void TempArtLoaded(quint64 id, const QImage& image); -private: + private: Application* app_; AlbumCoverLoaderOptions options_; @@ -63,4 +64,4 @@ private: Song last_song_; }; -#endif // CURRENTARTLOADER_H +#endif // CURRENTARTLOADER_H diff --git a/src/covers/discogscoverprovider.cpp b/src/covers/discogscoverprovider.cpp index c061e155d..1d29ed47f 100644 --- a/src/covers/discogscoverprovider.cpp +++ b/src/covers/discogscoverprovider.cpp @@ -24,15 +24,15 @@ #include #include -const char* DiscogsCoverProvider::kSearchUrl = "http://api.discogs.com/database/search"; +const char* DiscogsCoverProvider::kSearchUrl = + "http://api.discogs.com/database/search"; DiscogsCoverProvider::DiscogsCoverProvider(QObject* parent) - : CoverProvider("Discogs", parent), - network_(new NetworkAccessManager(this)) -{ -} + : CoverProvider("Discogs", parent), + network_(new NetworkAccessManager(this)) {} -bool DiscogsCoverProvider::StartSearch(const QString& artist, const QString& album, int id) { +bool DiscogsCoverProvider::StartSearch(const QString& artist, + const QString& album, int id) { DiscogsCoverSearchContext* ctx = new DiscogsCoverSearchContext; ctx->id = id; ctx->artist = artist; @@ -61,17 +61,17 @@ void DiscogsCoverProvider::SendSearchRequest(DiscogsCoverSearchContext* ctx) { QString type; switch (ctx->state) { - case DiscogsCoverSearchContext::State_Init: - type = "master"; - ctx->state = DiscogsCoverSearchContext::State_MastersRequested; - break; - case DiscogsCoverSearchContext::State_MastersRequested: - type = "release"; - ctx->state = DiscogsCoverSearchContext::State_ReleasesRequested; - break; - default: - EndSearch(ctx); - return; + case DiscogsCoverSearchContext::State_Init: + type = "master"; + ctx->state = DiscogsCoverSearchContext::State_MastersRequested; + break; + case DiscogsCoverSearchContext::State_MastersRequested: + type = "release"; + ctx->state = DiscogsCoverSearchContext::State_ReleasesRequested; + break; + default: + EndSearch(ctx); + return; } ArgList args = ArgList(); @@ -85,7 +85,7 @@ void DiscogsCoverProvider::SendSearchRequest(DiscogsCoverSearchContext* ctx) { EncodedArgList encoded_args; - foreach (const Arg& arg, args) { + foreach(const Arg & arg, args) { EncodedArg encoded_arg(QUrl::toPercentEncoding(arg.first), QUrl::toPercentEncoding(arg.second)); encoded_args << encoded_arg; @@ -93,12 +93,12 @@ void DiscogsCoverProvider::SendSearchRequest(DiscogsCoverSearchContext* ctx) { url.setEncodedQueryItems(encoded_args); - qLog(Debug) << "Discogs: send search request for id:" << ctx->id << "url: " << url; + qLog(Debug) << "Discogs: send search request for id:" << ctx->id + << "url: " << url; QNetworkReply* reply = network_->get(QNetworkRequest(url)); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(HandleSearchReply(QNetworkReply*, int)), - reply, ctx->id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(HandleSearchReply(QNetworkReply*, int)), reply, ctx->id); } // Parse the reply from a search @@ -126,7 +126,7 @@ void DiscogsCoverProvider::HandleSearchReply(QNetworkReply* reply, int id) { QVariantList results = reply_map["results"].toList(); - foreach (const QVariant& result, results) { + foreach(const QVariant & result, results) { QVariantMap result_map = result.toMap(); // In order to use less round-trips, we cheat here. Instead of // following the "resource_url", and then scan all images in the @@ -134,7 +134,8 @@ void DiscogsCoverProvider::HandleSearchReply(QNetworkReply* reply, int id) { // constructing the primary image's url from the thmub's url. if (result_map.contains("thumb")) { CoverSearchResult cover_result; - cover_result.image_url = QUrl(result_map["thumb"].toString().replace("R-90-", "R-")); + cover_result.image_url = + QUrl(result_map["thumb"].toString().replace("R-90-", "R-")); if (result_map.contains("title")) { cover_result.description = result_map["title"].toString(); } @@ -160,7 +161,7 @@ void DiscogsCoverProvider::HandleSearchReply(QNetworkReply* reply, int id) { } void DiscogsCoverProvider::EndSearch(DiscogsCoverSearchContext* ctx) { - (void) pending_requests_.remove(ctx->id); + (void)pending_requests_.remove(ctx->id); emit SearchFinished(ctx->id, ctx->results); delete ctx; } diff --git a/src/covers/discogscoverprovider.h b/src/covers/discogscoverprovider.h index 85dfd3889..cae51b0ce 100644 --- a/src/covers/discogscoverprovider.h +++ b/src/covers/discogscoverprovider.h @@ -24,14 +24,10 @@ class QNetworkAccessManager; // This struct represents a single search-for-cover request. It identifies -// and describes the request. +// and describes the request. struct DiscogsCoverSearchContext { - enum State { - State_Init, - State_MastersRequested, - State_ReleasesRequested - }; - + enum State { State_Init, State_MastersRequested, State_ReleasesRequested }; + // the unique request identifier int id; @@ -48,7 +44,7 @@ Q_DECLARE_METATYPE(DiscogsCoverSearchContext) class DiscogsCoverProvider : public CoverProvider { Q_OBJECT -public: + public: DiscogsCoverProvider(QObject* parent = NULL); static const char* kSearchUrl; @@ -56,10 +52,10 @@ public: bool StartSearch(const QString& artist, const QString& album, int id); void CancelSearch(int id); -private slots: + private slots: void HandleSearchReply(QNetworkReply* reply, int id); -private: + private: QNetworkAccessManager* network_; QHash pending_requests_; @@ -67,4 +63,4 @@ private: void EndSearch(DiscogsCoverSearchContext* ctx); }; -#endif // DISCOGSCOVERPROVIDER_H +#endif // DISCOGSCOVERPROVIDER_H diff --git a/src/covers/kittenloader.cpp b/src/covers/kittenloader.cpp index 3c9027968..c7f746dc7 100644 --- a/src/covers/kittenloader.cpp +++ b/src/covers/kittenloader.cpp @@ -19,19 +19,13 @@ const char* KittenLoader::kFlickrKittenUrl = const char* KittenLoader::kFlickrPhotoUrl = "https://farm%1.static.flickr.com/%2/%3_%4_m.jpg"; -KittenLoader::KittenLoader(QObject* parent) - : AlbumCoverLoader(parent) { -} +KittenLoader::KittenLoader(QObject* parent) : AlbumCoverLoader(parent) {} quint64 KittenLoader::LoadKitten(const AlbumCoverLoaderOptions& options) { if (!kitten_urls_.isEmpty()) { QUrl url = kitten_urls_.dequeue(); return AlbumCoverLoader::LoadImageAsync( - options, - QString::null, - url.toString(), - QString::null, - QImage()); + options, QString::null, url.toString(), QString::null, QImage()); } Task task; @@ -68,10 +62,10 @@ void KittenLoader::KittensRetrieved(QNetworkReply* reply) { QStringRef secret = attrs.value("secret"); QStringRef server = attrs.value("server"); QString photo_url = QString(kFlickrPhotoUrl) - .arg(farm_id.toString()) - .arg(server.toString()) - .arg(photo_id.toString()) - .arg(secret.toString()); + .arg(farm_id.toString()) + .arg(server.toString()) + .arg(photo_id.toString()) + .arg(secret.toString()); kitten_urls_ << QUrl(photo_url); } } diff --git a/src/covers/lastfmcoverprovider.cpp b/src/covers/lastfmcoverprovider.cpp index a84aea365..1ab2078db 100644 --- a/src/covers/lastfmcoverprovider.cpp +++ b/src/covers/lastfmcoverprovider.cpp @@ -25,11 +25,10 @@ #include "internet/lastfmcompat.h" LastFmCoverProvider::LastFmCoverProvider(QObject* parent) - : CoverProvider("last.fm", parent) -{ -} + : CoverProvider("last.fm", parent) {} -bool LastFmCoverProvider::StartSearch(const QString& artist, const QString& album, int id) { +bool LastFmCoverProvider::StartSearch(const QString& artist, + const QString& album, int id) { QMap params; params["method"] = "album.search"; params["album"] = album + " " + artist; @@ -49,11 +48,13 @@ void LastFmCoverProvider::QueryFinished(QNetworkReply* reply, int id) { lastfm::XmlQuery query(lastfm::compat::EmptyXmlQuery()); if (lastfm::compat::ParseQuery(reply->readAll(), &query)) { // parse the list of search results - QList elements = query["results"]["albummatches"].children("album"); + QList elements = + query["results"]["albummatches"].children("album"); - foreach (const lastfm::XmlQuery& element, elements) { + foreach(const lastfm::XmlQuery & element, elements) { CoverSearchResult result; - result.description = element["artist"].text() + " - " + element["name"].text(); + result.description = + element["artist"].text() + " - " + element["name"].text(); result.image_url = QUrl(element["image size=extralarge"].text()); results << result; } diff --git a/src/covers/lastfmcoverprovider.h b/src/covers/lastfmcoverprovider.h index 2ba8405d5..fbf77fa59 100644 --- a/src/covers/lastfmcoverprovider.h +++ b/src/covers/lastfmcoverprovider.h @@ -30,16 +30,16 @@ class QNetworkReply; class LastFmCoverProvider : public CoverProvider { Q_OBJECT -public: + public: LastFmCoverProvider(QObject* parent); bool StartSearch(const QString& artist, const QString& album, int id); -private slots: + private slots: void QueryFinished(QNetworkReply* reply, int id); -private: + private: QMap pending_queries_; }; -#endif // LASTFMCOVERPROVIDER_H +#endif // LASTFMCOVERPROVIDER_H diff --git a/src/covers/musicbrainzcoverprovider.cpp b/src/covers/musicbrainzcoverprovider.cpp index 3e054b4c0..2cacb20bd 100644 --- a/src/covers/musicbrainzcoverprovider.cpp +++ b/src/covers/musicbrainzcoverprovider.cpp @@ -29,44 +29,36 @@ using std::mem_fun; namespace { -static const char* kReleaseSearchUrl = - "https://musicbrainz.org/ws/2/release/"; +static const char* kReleaseSearchUrl = "https://musicbrainz.org/ws/2/release/"; static const char* kAlbumCoverUrl = "https://coverartarchive.org/release/%1/front"; } // namespace - MusicbrainzCoverProvider::MusicbrainzCoverProvider(QObject* parent) : CoverProvider("MusicBrainz", parent), - network_(new NetworkAccessManager(this)) { -} + network_(new NetworkAccessManager(this)) {} -bool MusicbrainzCoverProvider::StartSearch( - const QString& artist, const QString& album, int id) { +bool MusicbrainzCoverProvider::StartSearch(const QString& artist, + const QString& album, int id) { // Find release information. QUrl url(kReleaseSearchUrl); QString query = QString("release:\"%1\" AND artist:\"%2\"") - .arg(album.trimmed().replace('"', "\\\"")) - .arg(artist.trimmed().replace('"', "\\\"")); + .arg(album.trimmed().replace('"', "\\\"")) + .arg(artist.trimmed().replace('"', "\\\"")); url.addQueryItem("query", query); url.addQueryItem("limit", "5"); QNetworkRequest request(url); QNetworkReply* reply = network_->get(request); - NewClosure( - reply, - SIGNAL(finished()), - this, - SLOT(ReleaseSearchFinished(QNetworkReply*, int)), - reply, - id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(ReleaseSearchFinished(QNetworkReply*, int)), reply, id); cover_names_[id] = QString("%1 - %2").arg(artist, album); return true; } -void MusicbrainzCoverProvider::ReleaseSearchFinished( - QNetworkReply* reply, int id) { +void MusicbrainzCoverProvider::ReleaseSearchFinished(QNetworkReply* reply, + int id) { reply->deleteLater(); QList releases; @@ -74,8 +66,7 @@ void MusicbrainzCoverProvider::ReleaseSearchFinished( QXmlStreamReader reader(reply); while (!reader.atEnd()) { QXmlStreamReader::TokenType type = reader.readNext(); - if (type == QXmlStreamReader::StartElement && - reader.name() == "release") { + if (type == QXmlStreamReader::StartElement && reader.name() == "release") { QStringRef release_id = reader.attributes().value("id"); if (!release_id.isEmpty()) { releases.append(release_id.toString()); @@ -83,30 +74,26 @@ void MusicbrainzCoverProvider::ReleaseSearchFinished( } } - foreach (const QString& release_id, releases) { + foreach(const QString & release_id, releases) { QUrl url(QString(kAlbumCoverUrl).arg(release_id)); QNetworkReply* reply = network_->head(QNetworkRequest(url)); image_checks_.insert(id, reply); - NewClosure( - reply, - SIGNAL(finished()), - this, - SLOT(ImageCheckFinished(int)), - id); + NewClosure(reply, SIGNAL(finished()), this, SLOT(ImageCheckFinished(int)), + id); } } void MusicbrainzCoverProvider::ImageCheckFinished(int id) { QList replies = image_checks_.values(id); - int finished_count = std::count_if( - replies.constBegin(), replies.constEnd(), - mem_fun(&QNetworkReply::isFinished)); + int finished_count = std::count_if(replies.constBegin(), replies.constEnd(), + mem_fun(&QNetworkReply::isFinished)); if (finished_count == replies.size()) { QString cover_name = cover_names_.take(id); QList results; - foreach (QNetworkReply* reply, replies) { + foreach(QNetworkReply * reply, replies) { reply->deleteLater(); - if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() < 400) { + if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() < + 400) { CoverSearchResult result; result.description = cover_name; result.image_url = reply->url(); @@ -120,7 +107,7 @@ void MusicbrainzCoverProvider::ImageCheckFinished(int id) { void MusicbrainzCoverProvider::CancelSearch(int id) { QList replies = image_checks_.values(id); - foreach (QNetworkReply* reply, replies) { + foreach(QNetworkReply * reply, replies) { reply->abort(); reply->deleteLater(); } diff --git a/src/devices/cddadevice.cpp b/src/devices/cddadevice.cpp index 637022174..edb0049e2 100644 --- a/src/devices/cddadevice.cpp +++ b/src/devices/cddadevice.cpp @@ -25,39 +25,39 @@ #include "cddadevice.h" CddaDevice::CddaDevice(const QUrl& url, DeviceLister* lister, - const QString& unique_id, DeviceManager* manager, - Application* app, - int database_id, bool first_time) - : ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time), - cdda_(nullptr), - cdio_(nullptr) -{ -} + const QString& unique_id, DeviceManager* manager, + Application* app, int database_id, bool first_time) + : ConnectedDevice(url, lister, unique_id, manager, app, database_id, + first_time), + cdda_(nullptr), + cdio_(nullptr) {} -CddaDevice::~CddaDevice(){ - if (cdio_) - cdio_destroy(cdio_); +CddaDevice::~CddaDevice() { + if (cdio_) cdio_destroy(cdio_); } void CddaDevice::Init() { QMutexLocker locker(&mutex_init_); - song_count_ = 0; // Reset song count, in case it was already set - cdio_ = cdio_open (url_.path().toLocal8Bit().constData(), DRIVER_DEVICE); + song_count_ = 0; // Reset song count, in case it was already set + cdio_ = cdio_open(url_.path().toLocal8Bit().constData(), DRIVER_DEVICE); if (cdio_ == nullptr) { return; } // Create gstreamer cdda element - cdda_ = gst_element_make_from_uri (GST_URI_SRC, "cdda://", nullptr); + cdda_ = gst_element_make_from_uri(GST_URI_SRC, "cdda://", nullptr); if (cdda_ == nullptr) { model_->Reset(); return; } - GST_CDDA_BASE_SRC(cdda_)->device = g_strdup (url_.path().toLocal8Bit().constData()); + GST_CDDA_BASE_SRC(cdda_)->device = + g_strdup(url_.path().toLocal8Bit().constData()); // Change the element's state to ready and paused, to be able to query it - if (gst_element_set_state(cdda_, GST_STATE_READY) == GST_STATE_CHANGE_FAILURE || - gst_element_set_state(cdda_, GST_STATE_PAUSED) == GST_STATE_CHANGE_FAILURE) { + if (gst_element_set_state(cdda_, GST_STATE_READY) == + GST_STATE_CHANGE_FAILURE || + gst_element_set_state(cdda_, GST_STATE_PAUSED) == + GST_STATE_CHANGE_FAILURE) { model_->Reset(); gst_element_set_state(cdda_, GST_STATE_NULL); gst_object_unref(GST_OBJECT(cdda_)); @@ -65,10 +65,11 @@ void CddaDevice::Init() { } // Get number of tracks - GstFormat fmt = gst_format_get_by_nick ("track"); + GstFormat fmt = gst_format_get_by_nick("track"); GstFormat out_fmt = fmt; gint64 num_tracks = 0; - if (!gst_element_query_duration (cdda_, &out_fmt, &num_tracks) || out_fmt != fmt) { + if (!gst_element_query_duration(cdda_, &out_fmt, &num_tracks) || + out_fmt != fmt) { qLog(Error) << "Error while querying cdda GstElement"; model_->Reset(); gst_object_unref(GST_OBJECT(cdda_)); @@ -81,64 +82,69 @@ void CddaDevice::Init() { Song song; guint64 duration = 0; // quint64 == ulonglong and guint64 == ulong, therefore we must cast - if (gst_tag_list_get_uint64 (GST_CDDA_BASE_SRC(cdda_)->tracks[track_number-1].tags, - GST_TAG_DURATION, &duration)) { + if (gst_tag_list_get_uint64( + GST_CDDA_BASE_SRC(cdda_)->tracks[track_number - 1].tags, + GST_TAG_DURATION, &duration)) { song.set_length_nanosec((quint64)duration); } song.set_id(track_number); song.set_valid(true); song.set_filetype(Song::Type_Cdda); - song.set_url(QUrl(QString("cdda://%1/%2").arg(url_.path()).arg(track_number))); + song.set_url( + QUrl(QString("cdda://%1/%2").arg(url_.path()).arg(track_number))); song.set_title(QString("Track %1").arg(track_number)); song.set_track(track_number); songs << song; } song_count_ = num_tracks; - connect(this, SIGNAL(SongsDiscovered(const SongList&)), model_, SLOT(SongsDiscovered(const SongList&))); + connect(this, SIGNAL(SongsDiscovered(const SongList&)), model_, + SLOT(SongsDiscovered(const SongList&))); emit SongsDiscovered(songs); // Generate MusicBrainz DiscId gst_tag_register_musicbrainz_tags(); - GstElement *pipe = gst_pipeline_new ("pipeline"); - gst_bin_add (GST_BIN (pipe), cdda_); - gst_element_set_state (pipe, GST_STATE_READY); - gst_element_set_state (pipe, GST_STATE_PAUSED); - GstMessage *msg = gst_bus_timed_pop_filtered (GST_ELEMENT_BUS (pipe), - GST_CLOCK_TIME_NONE, - GST_MESSAGE_TAG); - GstTagList *tags = nullptr; - gst_message_parse_tag (msg, &tags); - char *string_mb = nullptr; - if (gst_tag_list_get_string (tags, GST_TAG_CDDA_MUSICBRAINZ_DISCID, &string_mb)) { + GstElement* pipe = gst_pipeline_new("pipeline"); + gst_bin_add(GST_BIN(pipe), cdda_); + gst_element_set_state(pipe, GST_STATE_READY); + gst_element_set_state(pipe, GST_STATE_PAUSED); + GstMessage* msg = gst_bus_timed_pop_filtered( + GST_ELEMENT_BUS(pipe), GST_CLOCK_TIME_NONE, GST_MESSAGE_TAG); + GstTagList* tags = nullptr; + gst_message_parse_tag(msg, &tags); + char* string_mb = nullptr; + if (gst_tag_list_get_string(tags, GST_TAG_CDDA_MUSICBRAINZ_DISCID, + &string_mb)) { QString musicbrainz_discid(string_mb); qLog(Info) << "MusicBrainz discid: " << musicbrainz_discid; - MusicBrainzClient *musicbrainz_client = new MusicBrainzClient(this); - connect(musicbrainz_client, - SIGNAL(Finished(const QString&, const QString&, MusicBrainzClient::ResultList)), - SLOT(AudioCDTagsLoaded(const QString&, const QString&, MusicBrainzClient::ResultList))); + MusicBrainzClient* musicbrainz_client = new MusicBrainzClient(this); + connect(musicbrainz_client, SIGNAL(Finished(const QString&, const QString&, + MusicBrainzClient::ResultList)), + SLOT(AudioCDTagsLoaded(const QString&, const QString&, + MusicBrainzClient::ResultList))); musicbrainz_client->StartDiscIdRequest(musicbrainz_discid); g_free(string_mb); } // Clean all the Gstreamer objects we have used: we don't need them anymore - gst_element_set_state (pipe, GST_STATE_NULL); + gst_element_set_state(pipe, GST_STATE_NULL); // This will also cause cdda_ to be unref'd. gst_object_unref(GST_OBJECT(pipe)); gst_object_unref(GST_OBJECT(msg)); gst_tag_list_free(tags); } -void CddaDevice::AudioCDTagsLoaded(const QString& artist, const QString& album, - const MusicBrainzClient::ResultList& results) { - MusicBrainzClient *musicbrainz_client = qobject_cast(sender()); +void CddaDevice::AudioCDTagsLoaded( + const QString& artist, const QString& album, + const MusicBrainzClient::ResultList& results) { + MusicBrainzClient* musicbrainz_client = + qobject_cast(sender()); musicbrainz_client->deleteLater(); SongList songs; int track_number = 1; - if (results.size() == 0) - return; + if (results.size() == 0) return; model_->Reset(); - foreach (const MusicBrainzClient::Result& ret, results) { + foreach(const MusicBrainzClient::Result & ret, results) { Song song; song.set_artist(artist); song.set_album(album); @@ -147,18 +153,22 @@ void CddaDevice::AudioCDTagsLoaded(const QString& artist, const QString& album, song.set_track(track_number); song.set_year(ret.year_); song.set_id(track_number); - // We need to set url: that's how playlist will find the correct item to update - song.set_url(QUrl(QString("cdda://%1/%2").arg(unique_id()).arg(track_number++))); + // We need to set url: that's how playlist will find the correct item to + // update + song.set_url( + QUrl(QString("cdda://%1/%2").arg(unique_id()).arg(track_number++))); songs << song; } - connect(this, SIGNAL(SongsDiscovered(const SongList&)), model_, SLOT(SongsDiscovered(const SongList&))); + connect(this, SIGNAL(SongsDiscovered(const SongList&)), model_, + SLOT(SongsDiscovered(const SongList&))); emit SongsDiscovered(songs); song_count_ = songs.size(); } void CddaDevice::Refresh() { - if ((cdio_ && cdda_) && /* already init... */ - cdio_get_media_changed(cdio_) != 1 /* ...and hasn't change since last time */) { + if ((cdio_ && cdda_) && /* already init... */ + cdio_get_media_changed(cdio_) != + 1 /* ...and hasn't change since last time */) { return; } // Check if mutex is already token (i.e. init is already taking place) diff --git a/src/devices/cddadevice.h b/src/devices/cddadevice.h index ceae9567d..4e5b11604 100644 --- a/src/devices/cddadevice.h +++ b/src/devices/cddadevice.h @@ -28,14 +28,13 @@ #include "core/song.h" #include "musicbrainz/musicbrainzclient.h" -class CddaDevice: public ConnectedDevice { +class CddaDevice : public ConnectedDevice { Q_OBJECT -public: + public: Q_INVOKABLE CddaDevice(const QUrl& url, DeviceLister* lister, - const QString& unique_id, DeviceManager* manager, - Application* app, - int database_id, bool first_time); + const QString& unique_id, DeviceManager* manager, + Application* app, int database_id, bool first_time); ~CddaDevice(); void Init(); @@ -48,15 +47,14 @@ public: signals: void SongsDiscovered(const SongList& songs); -private slots: + private slots: void AudioCDTagsLoaded(const QString& artist, const QString& album, const MusicBrainzClient::ResultList& results); -private: - GstElement *cdda_; - CdIo_t *cdio_; + private: + GstElement* cdda_; + CdIo_t* cdio_; QMutex mutex_init_; - }; #endif diff --git a/src/devices/cddalister.cpp b/src/devices/cddalister.cpp index 7b82d512c..9d7bbe5b6 100644 --- a/src/devices/cddalister.cpp +++ b/src/devices/cddalister.cpp @@ -27,9 +27,7 @@ #include "core/logging.h" #include "core/song.h" -QStringList CddaLister::DeviceUniqueIDs() { - return devices_list_; -} +QStringList CddaLister::DeviceUniqueIDs() { return devices_list_; } QVariantList CddaLister::DeviceIcons(const QString&) { QVariantList icons; @@ -38,7 +36,7 @@ QVariantList CddaLister::DeviceIcons(const QString&) { } QString CddaLister::DeviceManufacturer(const QString& id) { - CdIo_t *cdio = cdio_open (id.toLocal8Bit().constData(), DRIVER_DEVICE); + CdIo_t* cdio = cdio_open(id.toLocal8Bit().constData(), DRIVER_DEVICE); cdio_hwinfo_t cd_info; if (cdio_get_hwinfo(cdio, &cd_info)) { cdio_destroy(cdio); @@ -49,7 +47,7 @@ QString CddaLister::DeviceManufacturer(const QString& id) { } QString CddaLister::DeviceModel(const QString& id) { - CdIo_t *cdio = cdio_open (id.toLocal8Bit().constData(), DRIVER_DEVICE); + CdIo_t* cdio = cdio_open(id.toLocal8Bit().constData(), DRIVER_DEVICE); cdio_hwinfo_t cd_info; if (cdio_get_hwinfo(cdio, &cd_info)) { cdio_destroy(cdio); @@ -59,20 +57,16 @@ QString CddaLister::DeviceModel(const QString& id) { return QString(); } -quint64 CddaLister::DeviceCapacity(const QString&) { - return 0; -} +quint64 CddaLister::DeviceCapacity(const QString&) { return 0; } -quint64 CddaLister::DeviceFreeSpace(const QString&) { - return 0; -} +quint64 CddaLister::DeviceFreeSpace(const QString&) { return 0; } QVariantMap CddaLister::DeviceHardwareInfo(const QString&) { return QVariantMap(); } QString CddaLister::MakeFriendlyName(const QString& id) { - CdIo_t *cdio = cdio_open (id.toLocal8Bit().constData(), DRIVER_DEVICE); + CdIo_t* cdio = cdio_open(id.toLocal8Bit().constData(), DRIVER_DEVICE); cdio_hwinfo_t cd_info; if (cdio_get_hwinfo(cdio, &cd_info)) { cdio_destroy(cdio); @@ -90,8 +84,7 @@ void CddaLister::UnmountDevice(const QString& id) { cdio_eject_media_drive(id.toLocal8Bit().constData()); } -void CddaLister::UpdateDeviceFreeSpace(const QString&) { -} +void CddaLister::UpdateDeviceFreeSpace(const QString&) {} void CddaLister::Init() { cdio_init(); @@ -100,7 +93,7 @@ void CddaLister::Init() { qLog(Error) << "libcdio was compiled without support for OS X!"; } #endif - char **devices = cdio_get_devices(DRIVER_DEVICE); + char** devices = cdio_get_devices(DRIVER_DEVICE); if (!devices) { qLog(Debug) << "No CD devices found"; return; @@ -112,7 +105,8 @@ void CddaLister::Init() { device = device_info.symLinkTarget(); } #ifdef Q_OS_DARWIN - // Every track is detected as a separate device on Darwin. The raw disk looks + // Every track is detected as a separate device on Darwin. The raw disk + // looks // like /dev/rdisk1 if (!device.contains(QRegExp("^/dev/rdisk[0-9]$"))) { continue; @@ -124,4 +118,3 @@ void CddaLister::Init() { } } } - diff --git a/src/devices/cddalister.h b/src/devices/cddalister.h index dd6c728d9..47718826a 100644 --- a/src/devices/cddalister.h +++ b/src/devices/cddalister.h @@ -27,7 +27,7 @@ class CddaLister : public DeviceLister { Q_OBJECT -public: + public: CddaLister() {} QStringList DeviceUniqueIDs(); @@ -44,9 +44,7 @@ public: void UpdateDeviceFreeSpace(const QString&); void Init(); -private: + private: QStringList devices_list_; - }; -#endif // CDDALISTER_H - +#endif // CDDALISTER_H diff --git a/src/devices/connecteddevice.cpp b/src/devices/connecteddevice.cpp index e294417c9..8d4031714 100644 --- a/src/devices/connecteddevice.cpp +++ b/src/devices/connecteddevice.cpp @@ -28,31 +28,30 @@ #include ConnectedDevice::ConnectedDevice(const QUrl& url, DeviceLister* lister, - const QString& unique_id, DeviceManager* manager, - Application* app, + const QString& unique_id, + DeviceManager* manager, Application* app, int database_id, bool first_time) - : QObject(manager), - app_(app), - url_(url), - first_time_(first_time), - lister_(lister), - unique_id_(unique_id), - database_id_(database_id), - manager_(manager), - backend_(nullptr), - model_(nullptr), - song_count_(0) -{ + : QObject(manager), + app_(app), + url_(url), + first_time_(first_time), + lister_(lister), + unique_id_(unique_id), + database_id_(database_id), + manager_(manager), + backend_(nullptr), + model_(nullptr), + song_count_(0) { qLog(Info) << "connected" << url << unique_id << first_time; // Create the backend in the database thread. backend_ = new LibraryBackend(); backend_->moveToThread(app_->database()->thread()); - connect(backend_, SIGNAL(TotalSongCountUpdated(int)), SLOT(BackendTotalSongCountUpdated(int))); + connect(backend_, SIGNAL(TotalSongCountUpdated(int)), + SLOT(BackendTotalSongCountUpdated(int))); - backend_->Init(app_->database(), - QString("device_%1_songs").arg(database_id), + backend_->Init(app_->database(), QString("device_%1_songs").arg(database_id), QString("device_%1_directories").arg(database_id), QString("device_%1_subdirectories").arg(database_id), QString("device_%1_fts").arg(database_id)); @@ -61,12 +60,10 @@ ConnectedDevice::ConnectedDevice(const QUrl& url, DeviceLister* lister, model_ = new LibraryModel(backend_, app_, this); } -ConnectedDevice::~ConnectedDevice() { - backend_->deleteLater(); -} +ConnectedDevice::~ConnectedDevice() { backend_->deleteLater(); } -void ConnectedDevice::InitBackendDirectory( - const QString& mount_point, bool first_time, bool rewrite_path) { +void ConnectedDevice::InitBackendDirectory(const QString& mount_point, + bool first_time, bool rewrite_path) { if (first_time || backend_->GetAllDirectories().isEmpty()) { backend_->AddDirectory(mount_point); } else { diff --git a/src/devices/connecteddevice.h b/src/devices/connecteddevice.h index 663e5253d..8a347fa9f 100644 --- a/src/devices/connecteddevice.h +++ b/src/devices/connecteddevice.h @@ -34,21 +34,21 @@ class DeviceManager; class LibraryBackend; class LibraryModel; -class ConnectedDevice : public QObject, public virtual MusicStorage, +class ConnectedDevice : public QObject, + public virtual MusicStorage, public std::enable_shared_from_this { Q_OBJECT -public: + public: ConnectedDevice(const QUrl& url, DeviceLister* lister, const QString& unique_id, DeviceManager* manager, - Application* app, - int database_id, bool first_time); + Application* app, int database_id, bool first_time); ~ConnectedDevice(); virtual void Init() = 0; // For some devices (e.g. CD devices) we don't have callbacks to be notified // when something change: we can call this method to refresh device's state - virtual void Refresh() { } + virtual void Refresh() {} virtual TranscodeMode GetTranscodeMode() const; virtual Song::FileType GetTranscodeFormat() const; @@ -68,10 +68,11 @@ signals: void TaskStarted(int id); void SongCountUpdated(int count); -protected: - void InitBackendDirectory(const QString& mount_point, bool first_time, bool rewrite_path = true); + protected: + void InitBackendDirectory(const QString& mount_point, bool first_time, + bool rewrite_path = true); -protected: + protected: Application* app_; QUrl url_; @@ -86,8 +87,8 @@ protected: int song_count_; -private slots: + private slots: void BackendTotalSongCountUpdated(int count); }; -#endif // CONNECTEDDEVICE_H +#endif // CONNECTEDDEVICE_H diff --git a/src/devices/devicedatabasebackend.cpp b/src/devices/devicedatabasebackend.cpp index 7c83978e8..14f28ed66 100644 --- a/src/devices/devicedatabasebackend.cpp +++ b/src/devices/devicedatabasebackend.cpp @@ -25,14 +25,10 @@ const int DeviceDatabaseBackend::kDeviceSchemaVersion = 0; -DeviceDatabaseBackend::DeviceDatabaseBackend(QObject *parent) - : QObject(parent) -{ -} +DeviceDatabaseBackend::DeviceDatabaseBackend(QObject* parent) + : QObject(parent) {} -void DeviceDatabaseBackend::Init(Database* db) { - db_ = db; -} +void DeviceDatabaseBackend::Init(Database* db) { db_ = db; } DeviceDatabaseBackend::DeviceList DeviceDatabaseBackend::GetAllDevices() { QMutexLocker l(db_->Mutex()); @@ -40,9 +36,11 @@ DeviceDatabaseBackend::DeviceList DeviceDatabaseBackend::GetAllDevices() { DeviceList ret; - QSqlQuery q("SELECT ROWID, unique_id, friendly_name, size, icon," - " transcode_mode, transcode_format" - " FROM devices", db); + QSqlQuery q( + "SELECT ROWID, unique_id, friendly_name, size, icon," + " transcode_mode, transcode_format" + " FROM devices", + db); q.exec(); if (db_->CheckErrors(q)) return ret; @@ -67,11 +65,13 @@ int DeviceDatabaseBackend::AddDevice(const Device& device) { ScopedTransaction t(&db); // Insert the device into the devices table - QSqlQuery q("INSERT INTO devices (" - " unique_id, friendly_name, size, icon," - " transcode_mode, transcode_format)" - " VALUES (:unique_id, :friendly_name, :size, :icon," - " :transcode_mode, :transcode_format)", db); + QSqlQuery q( + "INSERT INTO devices (" + " unique_id, friendly_name, size, icon," + " transcode_mode, transcode_format)" + " VALUES (:unique_id, :friendly_name, :size, :icon," + " :transcode_mode, :transcode_format)", + db); q.bindValue(":unique_id", device.unique_id_); q.bindValue(":friendly_name", device.friendly_name_); q.bindValue(":size", device.size_); @@ -118,17 +118,21 @@ void DeviceDatabaseBackend::RemoveDevice(int id) { } void DeviceDatabaseBackend::SetDeviceOptions(int id, - const QString &friendly_name, const QString &icon_name, - MusicStorage::TranscodeMode mode, Song::FileType format) { + const QString& friendly_name, + const QString& icon_name, + MusicStorage::TranscodeMode mode, + Song::FileType format) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q("UPDATE devices" - " SET friendly_name=:friendly_name," - " icon=:icon_name," - " transcode_mode=:transcode_mode," - " transcode_format=:transcode_format" - " WHERE ROWID=:id", db); + QSqlQuery q( + "UPDATE devices" + " SET friendly_name=:friendly_name," + " icon=:icon_name," + " transcode_mode=:transcode_mode," + " transcode_format=:transcode_format" + " WHERE ROWID=:id", + db); q.bindValue(":friendly_name", friendly_name); q.bindValue(":icon_name", icon_name); q.bindValue(":transcode_mode", mode); diff --git a/src/devices/devicedatabasebackend.h b/src/devices/devicedatabasebackend.h index 1e008c896..ca0d2fd88 100644 --- a/src/devices/devicedatabasebackend.h +++ b/src/devices/devicedatabasebackend.h @@ -28,7 +28,7 @@ class Database; class DeviceDatabaseBackend : public QObject { Q_OBJECT -public: + public: Q_INVOKABLE DeviceDatabaseBackend(QObject* parent = 0); struct Device { @@ -54,13 +54,13 @@ public: int AddDevice(const Device& device); void RemoveDevice(int id); - void SetDeviceOptions(int id, - const QString& friendly_name, const QString& icon_name, - MusicStorage::TranscodeMode mode, Song::FileType format); + void SetDeviceOptions(int id, const QString& friendly_name, + const QString& icon_name, + MusicStorage::TranscodeMode mode, + Song::FileType format); -private: + private: Database* db_; - }; -#endif // DEVICEDATABASEBACKEND_H +#endif // DEVICEDATABASEBACKEND_H diff --git a/src/devices/devicekitlister.cpp b/src/devices/devicekitlister.cpp index c77246d21..0db3c2b54 100644 --- a/src/devices/devicekitlister.cpp +++ b/src/devices/devicekitlister.cpp @@ -24,23 +24,21 @@ #include "dbus/udisksdevice.h" #ifdef HAVE_LIBGPOD -# include "gpoddevice.h" +#include "gpoddevice.h" #endif #include #include -DeviceKitLister::DeviceKitLister() -{ -} +DeviceKitLister::DeviceKitLister() {} -DeviceKitLister::~DeviceKitLister() { - qLog(Debug) << __PRETTY_FUNCTION__; -} +DeviceKitLister::~DeviceKitLister() { qLog(Debug) << __PRETTY_FUNCTION__; } QString DeviceKitLister::DeviceData::unique_id() const { - return QString("DeviceKit/%1/%2/%3/%4").arg(drive_serial, drive_vendor, drive_model).arg(device_size); + return QString("DeviceKit/%1/%2/%3/%4") + .arg(drive_serial, drive_vendor, drive_model) + .arg(device_size); } void DeviceKitLister::Init() { @@ -49,26 +47,30 @@ void DeviceKitLister::Init() { "/org/freedesktop/UDisks", QDBusConnection::systemBus())); // Get all the devices currently attached - QDBusPendingReply > reply = interface_->EnumerateDevices(); + QDBusPendingReply > reply = + interface_->EnumerateDevices(); reply.waitForFinished(); if (!reply.isValid()) { - qLog(Warning) << "Error enumerating DeviceKit-disks devices:" << reply.error().name() << reply.error().message(); + qLog(Warning) << "Error enumerating DeviceKit-disks devices:" + << reply.error().name() << reply.error().message(); interface_.reset(); return; } // Listen for changes - connect(interface_.get(), SIGNAL(DeviceAdded(QDBusObjectPath)), SLOT(DBusDeviceAdded(QDBusObjectPath))); - connect(interface_.get(), SIGNAL(DeviceRemoved(QDBusObjectPath)), SLOT(DBusDeviceRemoved(QDBusObjectPath))); - connect(interface_.get(), SIGNAL(DeviceChanged(QDBusObjectPath)), SLOT(DBusDeviceChanged(QDBusObjectPath))); + connect(interface_.get(), SIGNAL(DeviceAdded(QDBusObjectPath)), + SLOT(DBusDeviceAdded(QDBusObjectPath))); + connect(interface_.get(), SIGNAL(DeviceRemoved(QDBusObjectPath)), + SLOT(DBusDeviceRemoved(QDBusObjectPath))); + connect(interface_.get(), SIGNAL(DeviceChanged(QDBusObjectPath)), + SLOT(DBusDeviceChanged(QDBusObjectPath))); // Get information about each one QMap device_data; - foreach (const QDBusObjectPath& path, reply.value()) { + foreach(const QDBusObjectPath & path, reply.value()) { DeviceData data = ReadDeviceData(path); - if (data.suitable) - device_data[data.unique_id()] = data; + if (data.suitable) device_data[data.unique_id()] = data; } // Update the internal cache @@ -78,9 +80,7 @@ void DeviceKitLister::Init() { } // Notify about the changes - foreach (const QString& id, device_data.keys()) { - emit DeviceAdded(id); - } + foreach(const QString & id, device_data.keys()) { emit DeviceAdded(id); } } QStringList DeviceKitLister::DeviceUniqueIDs() { @@ -88,36 +88,36 @@ QStringList DeviceKitLister::DeviceUniqueIDs() { return device_data_.keys(); } -QVariantList DeviceKitLister::DeviceIcons(const QString &id) { +QVariantList DeviceKitLister::DeviceIcons(const QString& id) { QString path = LockAndGetDeviceInfo(id, &DeviceData::device_mount_paths)[0]; - return QVariantList() - << GuessIconForPath(path) - << GuessIconForModel(DeviceManufacturer(id), DeviceModel(id)) - << LockAndGetDeviceInfo(id, &DeviceData::device_presentation_icon_name); + return QVariantList() << GuessIconForPath(path) + << GuessIconForModel(DeviceManufacturer(id), + DeviceModel(id)) + << LockAndGetDeviceInfo( + id, &DeviceData::device_presentation_icon_name); } -QString DeviceKitLister::DeviceManufacturer(const QString &id) { +QString DeviceKitLister::DeviceManufacturer(const QString& id) { return LockAndGetDeviceInfo(id, &DeviceData::drive_vendor); } -QString DeviceKitLister::DeviceModel(const QString &id) { +QString DeviceKitLister::DeviceModel(const QString& id) { return LockAndGetDeviceInfo(id, &DeviceData::drive_model); } -quint64 DeviceKitLister::DeviceCapacity(const QString &id) { +quint64 DeviceKitLister::DeviceCapacity(const QString& id) { return LockAndGetDeviceInfo(id, &DeviceData::device_size); } -quint64 DeviceKitLister::DeviceFreeSpace(const QString &id) { +quint64 DeviceKitLister::DeviceFreeSpace(const QString& id) { return LockAndGetDeviceInfo(id, &DeviceData::free_space); } -QVariantMap DeviceKitLister::DeviceHardwareInfo(const QString &id) { +QVariantMap DeviceKitLister::DeviceHardwareInfo(const QString& id) { QVariantMap ret; QMutexLocker l(&mutex_); - if (!device_data_.contains(id)) - return ret; + if (!device_data_.contains(id)) return ret; const DeviceData& data = device_data_[id]; ret[QT_TR_NOOP("DBus path")] = data.dbus_path; @@ -127,38 +127,35 @@ QVariantMap DeviceKitLister::DeviceHardwareInfo(const QString &id) { return ret; } -QString DeviceKitLister::MakeFriendlyName(const QString &id) { +QString DeviceKitLister::MakeFriendlyName(const QString& id) { QMutexLocker l(&mutex_); - if (!device_data_.contains(id)) - return QString(); + if (!device_data_.contains(id)) return QString(); const DeviceData& data = device_data_[id]; if (!data.device_presentation_name.isEmpty()) return data.device_presentation_name; if (!data.drive_model.isEmpty() && !data.drive_vendor.isEmpty()) return data.drive_vendor + " " + data.drive_model; - if (!data.drive_model.isEmpty()) - return data.drive_model; + if (!data.drive_model.isEmpty()) return data.drive_model; return data.drive_serial; } DeviceKitLister::DeviceData DeviceKitLister::ReadDeviceData( - const QDBusObjectPath &path) const { + const QDBusObjectPath& path) const { DeviceData ret; OrgFreedesktopUDisksDeviceInterface device( - OrgFreedesktopUDisksInterface::staticInterfaceName(), - path.path(), QDBusConnection::systemBus()); + OrgFreedesktopUDisksInterface::staticInterfaceName(), path.path(), + QDBusConnection::systemBus()); if (!device.isValid()) { - qLog(Warning) << "Error connecting to the device interface on" << path.path(); + qLog(Warning) << "Error connecting to the device interface on" + << path.path(); return ret; } // Don't do anything with internal drives, hidden drives, or partition tables - if (device.deviceIsSystemInternal() || - device.devicePresentationHide() || - device.deviceMountPaths().isEmpty() || - device.deviceIsPartitionTable()) { + if (device.deviceIsSystemInternal() || device.devicePresentationHide() || + device.deviceMountPaths().isEmpty() || device.deviceIsPartitionTable()) { return ret; } @@ -180,10 +177,9 @@ DeviceKitLister::DeviceData DeviceKitLister::ReadDeviceData( return ret; } -void DeviceKitLister::DBusDeviceAdded(const QDBusObjectPath &path) { +void DeviceKitLister::DBusDeviceAdded(const QDBusObjectPath& path) { DeviceData data = ReadDeviceData(path); - if (!data.suitable) - return; + if (!data.suitable) return; { QMutexLocker l(&mutex_); @@ -193,13 +189,12 @@ void DeviceKitLister::DBusDeviceAdded(const QDBusObjectPath &path) { emit DeviceAdded(data.unique_id()); } -void DeviceKitLister::DBusDeviceRemoved(const QDBusObjectPath &path) { +void DeviceKitLister::DBusDeviceRemoved(const QDBusObjectPath& path) { QString id; { QMutexLocker l(&mutex_); id = FindUniqueIdByPath(path); - if (id.isNull()) - return; + if (id.isNull()) return; device_data_.remove(id); } @@ -207,7 +202,7 @@ void DeviceKitLister::DBusDeviceRemoved(const QDBusObjectPath &path) { emit DeviceRemoved(id); } -void DeviceKitLister::DBusDeviceChanged(const QDBusObjectPath &path) { +void DeviceKitLister::DBusDeviceChanged(const QDBusObjectPath& path) { bool already_known = false; { QMutexLocker l(&mutex_); @@ -229,17 +224,16 @@ void DeviceKitLister::DBusDeviceChanged(const QDBusObjectPath &path) { } } -QString DeviceKitLister::FindUniqueIdByPath(const QDBusObjectPath &path) const { - foreach (const DeviceData& data, device_data_) { - if (data.dbus_path == path.path()) - return data.unique_id(); +QString DeviceKitLister::FindUniqueIdByPath(const QDBusObjectPath& path) const { + foreach(const DeviceData & data, device_data_) { + if (data.dbus_path == path.path()) return data.unique_id(); } return QString(); } QList DeviceKitLister::MakeDeviceUrls(const QString& id) { - QString mount_point = LockAndGetDeviceInfo( - id, &DeviceData::device_mount_paths)[0]; + QString mount_point = + LockAndGetDeviceInfo(id, &DeviceData::device_mount_paths)[0]; return QList() << MakeUrlFromLocalPath(mount_point); } @@ -248,8 +242,8 @@ void DeviceKitLister::UnmountDevice(const QString& id) { QString path = LockAndGetDeviceInfo(id, &DeviceData::dbus_path); OrgFreedesktopUDisksDeviceInterface device( - OrgFreedesktopUDisksInterface::staticInterfaceName(), - path, QDBusConnection::systemBus()); + OrgFreedesktopUDisksInterface::staticInterfaceName(), path, + QDBusConnection::systemBus()); if (!device.isValid()) { qLog(Warning) << "Error connecting to the device interface on" << path; return; @@ -258,8 +252,8 @@ void DeviceKitLister::UnmountDevice(const QString& id) { // Get the device's parent drive QString drive_path = device.partitionSlave().path(); OrgFreedesktopUDisksDeviceInterface drive( - OrgFreedesktopUDisksInterface::staticInterfaceName(), - drive_path, QDBusConnection::systemBus()); + OrgFreedesktopUDisksInterface::staticInterfaceName(), drive_path, + QDBusConnection::systemBus()); if (!drive.isValid()) { qLog(Warning) << "Error connecting to the drive interface on" << drive_path; return; @@ -277,12 +271,12 @@ void DeviceKitLister::UnmountDevice(const QString& id) { void DeviceKitLister::UpdateDeviceFreeSpace(const QString& id) { { QMutexLocker l(&mutex_); - if (!device_data_.contains(id)) - return; + if (!device_data_.contains(id)) return; DeviceData& data = device_data_[id]; if (!data.device_mount_paths.isEmpty()) - data.free_space = Utilities::FileSystemFreeSpace(data.device_mount_paths[0]); + data.free_space = + Utilities::FileSystemFreeSpace(data.device_mount_paths[0]); } emit DeviceChanged(id); diff --git a/src/devices/devicekitlister.h b/src/devices/devicekitlister.h index 201e9b74b..0fcbcbcd5 100644 --- a/src/devices/devicekitlister.h +++ b/src/devices/devicekitlister.h @@ -32,7 +32,7 @@ class QDBusObjectPath; class DeviceKitLister : public DeviceLister { Q_OBJECT -public: + public: DeviceKitLister(); ~DeviceKitLister(); @@ -44,23 +44,23 @@ public: quint64 DeviceFreeSpace(const QString& id); QVariantMap DeviceHardwareInfo(const QString& id); - QString MakeFriendlyName(const QString &id); - QList MakeDeviceUrls(const QString &id); + QString MakeFriendlyName(const QString& id); + QList MakeDeviceUrls(const QString& id); - void UnmountDevice(const QString &id); + void UnmountDevice(const QString& id); -public slots: + public slots: void UpdateDeviceFreeSpace(const QString& id); -protected: + protected: void Init(); -private slots: + private slots: void DBusDeviceAdded(const QDBusObjectPath& path); void DBusDeviceRemoved(const QDBusObjectPath& path); void DBusDeviceChanged(const QDBusObjectPath& path); -private: + private: struct DeviceData { DeviceData() : suitable(false), device_size(0), free_space(0) {} @@ -87,7 +87,7 @@ private: template T LockAndGetDeviceInfo(const QString& id, T DeviceData::*field); -private: + private: std::unique_ptr interface_; QMutex mutex_; @@ -95,12 +95,12 @@ private: }; template -T DeviceKitLister::LockAndGetDeviceInfo(const QString& id, T DeviceData::*field) { +T DeviceKitLister::LockAndGetDeviceInfo(const QString& id, + T DeviceData::*field) { QMutexLocker l(&mutex_); - if (!device_data_.contains(id)) - return T(); + if (!device_data_.contains(id)) return T(); return device_data_[id].*field; } -#endif // DEVICEKITLISTER_H +#endif // DEVICEKITLISTER_H diff --git a/src/devices/devicelister.cpp b/src/devices/devicelister.cpp index fb00d8ca7..79fefd437 100644 --- a/src/devices/devicelister.cpp +++ b/src/devices/devicelister.cpp @@ -28,10 +28,7 @@ #include #endif -DeviceLister::DeviceLister() - : thread_(nullptr) -{ -} +DeviceLister::DeviceLister() : thread_(nullptr) {} DeviceLister::~DeviceLister() { if (thread_) { @@ -48,9 +45,7 @@ void DeviceLister::Start() { thread_->start(); } -void DeviceLister::ThreadStarted() { - Init(); -} +void DeviceLister::ThreadStarted() { Init(); } namespace { @@ -155,7 +150,6 @@ QString GetIpodModel(Itdb_IpodModel model) { } #endif - } QUrl DeviceLister::MakeUrlFromLocalPath(const QString& path) const { @@ -204,7 +198,8 @@ QStringList DeviceLister::GuessIconForPath(const QString& path) { return ret; } -QStringList DeviceLister::GuessIconForModel(const QString& vendor, const QString& model) { +QStringList DeviceLister::GuessIconForModel(const QString& vendor, + const QString& model) { QStringList ret; if (vendor.startsWith("Google") && model.contains("Nexus")) { ret << "phone-google-nexus-one"; @@ -213,7 +208,7 @@ QStringList DeviceLister::GuessIconForModel(const QString& vendor, const QString } int DeviceLister::MountDevice(const QString& id) { - const int ret = next_mount_request_id_ ++; + const int ret = next_mount_request_id_++; emit DeviceMounted(id, ret, true); return ret; } diff --git a/src/devices/devicelister.h b/src/devices/devicelister.h index 5791968ab..ee0f7a3d3 100644 --- a/src/devices/devicelister.h +++ b/src/devices/devicelister.h @@ -27,7 +27,7 @@ class DeviceManager; class DeviceLister : public QObject { Q_OBJECT -public: + public: DeviceLister(); virtual ~DeviceLister(); @@ -39,7 +39,8 @@ public: // taken from the one with the highest priority. virtual int priority() const { return 100; } - // Query information about the devices that are available. Must be thread-safe. + // Query information about the devices that are available. Must be + // thread-safe. virtual QStringList DeviceUniqueIDs() = 0; virtual QVariantList DeviceIcons(const QString& id) = 0; virtual QString DeviceManufacturer(const QString& id) = 0; @@ -63,7 +64,7 @@ public: // Do whatever needs to be done to safely remove the device. virtual void UnmountDevice(const QString& id) = 0; -public slots: + public slots: virtual void UpdateDeviceFreeSpace(const QString& id) = 0; virtual void ShutDown() {} @@ -73,7 +74,7 @@ signals: void DeviceChanged(const QString& id); void DeviceMounted(const QString& id, int request_id, bool success); -protected: + protected: virtual void Init() = 0; QUrl MakeUrlFromLocalPath(const QString& path) const; bool IsIpod(const QString& path) const; @@ -81,12 +82,12 @@ protected: QStringList GuessIconForPath(const QString& path); QStringList GuessIconForModel(const QString& vendor, const QString& model); -protected: + protected: QThread* thread_; int next_mount_request_id_; -private slots: + private slots: void ThreadStarted(); }; -#endif // DEVICELISTER_H +#endif // DEVICELISTER_H diff --git a/src/devices/devicemanager.cpp b/src/devices/devicemanager.cpp index 09706b435..b1fc14d31 100644 --- a/src/devices/devicemanager.cpp +++ b/src/devices/devicemanager.cpp @@ -43,21 +43,21 @@ #include "ui/iconloader.h" #ifdef HAVE_AUDIOCD -# include "cddalister.h" -# include "cddadevice.h" +#include "cddalister.h" +#include "cddadevice.h" #endif #ifdef Q_OS_DARWIN -# include "macdevicelister.h" +#include "macdevicelister.h" #endif #ifdef HAVE_LIBGPOD -# include "gpoddevice.h" +#include "gpoddevice.h" #endif #ifdef HAVE_GIO -# include "giolister.h" +#include "giolister.h" #endif #ifdef HAVE_LIBMTP -# include "mtpdevice.h" +#include "mtpdevice.h" #endif using std::bind; @@ -65,14 +65,11 @@ using std::bind; const int DeviceManager::kDeviceIconSize = 32; const int DeviceManager::kDeviceIconOverlaySize = 16; - DeviceManager::DeviceInfo::DeviceInfo() - : database_id_(-1), - transcode_mode_(MusicStorage::Transcode_Unsupported), - transcode_format_(Song::Type_Unknown), - task_percentage_(-1) -{ -} + : database_id_(-1), + transcode_mode_(MusicStorage::Transcode_Unsupported), + transcode_format_(Song::Type_Unknown), + task_percentage_(-1) {} DeviceDatabaseBackend::Device DeviceManager::DeviceInfo::SaveToDb() const { DeviceDatabaseBackend::Device ret; @@ -84,7 +81,7 @@ DeviceDatabaseBackend::Device DeviceManager::DeviceInfo::SaveToDb() const { ret.transcode_format_ = transcode_format_; QStringList unique_ids; - foreach (const Backend& backend, backends_) { + foreach(const Backend & backend, backends_) { unique_ids << backend.unique_id_; } ret.unique_id_ = unique_ids.join(","); @@ -92,7 +89,8 @@ DeviceDatabaseBackend::Device DeviceManager::DeviceInfo::SaveToDb() const { return ret; } -void DeviceManager::DeviceInfo::InitFromDb(const DeviceDatabaseBackend::Device& dev) { +void DeviceManager::DeviceInfo::InitFromDb( + const DeviceDatabaseBackend::Device& dev) { database_id_ = dev.id_; friendly_name_ = dev.friendly_name_; size_ = dev.size_; @@ -101,19 +99,16 @@ void DeviceManager::DeviceInfo::InitFromDb(const DeviceDatabaseBackend::Device& QStringList icon_names = dev.icon_name_.split(','); QVariantList icons; - foreach (const QString& icon_name, icon_names) { - icons << icon_name; - } + foreach(const QString & icon_name, icon_names) { icons << icon_name; } LoadIcon(icons, friendly_name_); QStringList unique_ids = dev.unique_id_.split(','); - foreach (const QString& id, unique_ids) { - backends_ << Backend(nullptr, id); - } + foreach(const QString & id, unique_ids) { backends_ << Backend(nullptr, id); } } -void DeviceManager::DeviceInfo::LoadIcon(const QVariantList& icons, const QString& name_hint) { +void DeviceManager::DeviceInfo::LoadIcon(const QVariantList& icons, + const QString& name_hint) { if (icons.isEmpty()) { icon_name_ = "drive-removable-media-usb-pendrive"; icon_ = IconLoader::Load(icon_name_); @@ -121,7 +116,7 @@ void DeviceManager::DeviceInfo::LoadIcon(const QVariantList& icons, const QStrin } // Try to load the icon with that exact name first - foreach (const QVariant& icon, icons) { + foreach(const QVariant & icon, icons) { if (!icon.value().isNull()) { icon_ = QIcon(icon.value()); return; @@ -147,28 +142,27 @@ void DeviceManager::DeviceInfo::LoadIcon(const QVariantList& icons, const QStrin icon_ = IconLoader::Load(icon_name_); } -const DeviceManager::DeviceInfo::Backend* DeviceManager::DeviceInfo::BestBackend() const { +const DeviceManager::DeviceInfo::Backend* +DeviceManager::DeviceInfo::BestBackend() const { int best_priority = -1; const Backend* ret = nullptr; - for (int i=0 ; ipriority() > best_priority) { + for (int i = 0; i < backends_.count(); ++i) { + if (backends_[i].lister_ && + backends_[i].lister_->priority() > best_priority) { best_priority = backends_[i].lister_->priority(); ret = &(backends_[i]); } } - if (!ret && !backends_.isEmpty()) - return &(backends_[0]); + if (!ret && !backends_.isEmpty()) return &(backends_[0]); return ret; } - -DeviceManager::DeviceManager(Application* app, QObject *parent) - : QAbstractListModel(parent), - app_(app), - not_connected_overlay_(IconLoader::Load("edit-delete")) -{ +DeviceManager::DeviceManager(Application* app, QObject* parent) + : QAbstractListModel(parent), + app_(app), + not_connected_overlay_(IconLoader::Load("edit-delete")) { thread_pool_.setMaxThreadCount(1); connect(app_->task_manager(), SIGNAL(TasksChanged()), SLOT(TasksChanged())); @@ -179,13 +173,14 @@ DeviceManager::DeviceManager(Application* app, QObject *parent) // This reads from the database and contends on the database mutex, which can // be very slow on startup. - ConcurrentRun::Run(&thread_pool_, bind(&DeviceManager::LoadAllDevices, this)); + ConcurrentRun::Run(&thread_pool_, + bind(&DeviceManager::LoadAllDevices, this)); // This proxy model only shows connected devices connected_devices_model_ = new DeviceStateFilterModel(this); connected_devices_model_->setSourceModel(this); - // CD devices are detected via the DiskArbitration framework instead on Darwin. +// CD devices are detected via the DiskArbitration framework instead on Darwin. #if defined(HAVE_AUDIOCD) && !defined(Q_OS_DARWIN) AddLister(new CddaLister); #endif @@ -215,7 +210,7 @@ DeviceManager::DeviceManager(Application* app, QObject *parent) } DeviceManager::~DeviceManager() { - foreach (DeviceLister* lister, listers_) { + foreach(DeviceLister * lister, listers_) { lister->ShutDown(); delete lister; } @@ -226,7 +221,7 @@ DeviceManager::~DeviceManager() { void DeviceManager::LoadAllDevices() { Q_ASSERT(QThread::currentThread() != qApp->thread()); DeviceDatabaseBackend::DeviceList devices = backend_->GetAllDevices(); - foreach (const DeviceDatabaseBackend::Device& device, devices) { + foreach(const DeviceDatabaseBackend::Device & device, devices) { DeviceInfo info; info.InitFromDb(device); devices_ << info; @@ -238,8 +233,7 @@ int DeviceManager::rowCount(const QModelIndex&) const { } QVariant DeviceManager::data(const QModelIndex& index, int role) const { - if (!index.isValid() || index.column() != 0) - return QVariant(); + if (!index.isValid() || index.column() != 0) return QVariant(); const DeviceInfo& info = devices_[index.row()]; @@ -253,8 +247,7 @@ QVariant DeviceManager::data(const QModelIndex& index, int role) const { if (info.size_) text = text + QString(" (%1)").arg(Utilities::PrettySize(info.size_)); - if (info.device_.get()) - info.device_->Refresh(); + if (info.device_.get()) info.device_->Refresh(); return text; } @@ -287,66 +280,65 @@ QVariant DeviceManager::data(const QModelIndex& index, int role) const { case Role_FreeSpace: case MusicStorage::Role_FreeSpace: - return info.BestBackend()->lister_ ? - info.BestBackend()->lister_->DeviceFreeSpace(info.BestBackend()->unique_id_) : - QVariant(); + return info.BestBackend()->lister_ + ? info.BestBackend()->lister_->DeviceFreeSpace( + info.BestBackend()->unique_id_) + : QVariant(); case Role_State: - if (info.device_) - return State_Connected; + if (info.device_) return State_Connected; if (info.BestBackend()->lister_) { - if (info.BestBackend()->lister_->DeviceNeedsMount(info.BestBackend()->unique_id_)) + if (info.BestBackend()->lister_->DeviceNeedsMount( + info.BestBackend()->unique_id_)) return State_NotMounted; return State_NotConnected; } return State_Remembered; case Role_UpdatingPercentage: - if (info.task_percentage_ == -1) - return QVariant(); + if (info.task_percentage_ == -1) return QVariant(); return info.task_percentage_; case MusicStorage::Role_Storage: if (!info.device_ && info.database_id_ != -1) const_cast(this)->Connect(index.row()); - if (!info.device_) - return QVariant(); + if (!info.device_) return QVariant(); return QVariant::fromValue>(info.device_); case MusicStorage::Role_StorageForceConnect: if (!info.device_) { if (info.database_id_ == -1 && - !info.BestBackend()->lister_->DeviceNeedsMount(info.BestBackend()->unique_id_)) { + !info.BestBackend()->lister_->DeviceNeedsMount( + info.BestBackend()->unique_id_)) { - if (info.BestBackend()->lister_->AskForScan(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. Clementine will now scan the device to find music files - this may take some time."), + tr("This is the first time you have connected this device. " + "Clementine will now scan the device to find music files - " + "this may take some time."), QMessageBox::Cancel)); - QPushButton* connect = - dialog->addButton(tr("Connect device"), QMessageBox::AcceptRole); + QPushButton* connect = dialog->addButton(tr("Connect device"), + QMessageBox::AcceptRole); dialog->exec(); - if (dialog->clickedButton() != connect) - return QVariant(); + if (dialog->clickedButton() != connect) return QVariant(); } } const_cast(this)->Connect(index.row()); } - if (!info.device_) - return QVariant(); + if (!info.device_) return QVariant(); return QVariant::fromValue>(info.device_); case Role_MountPath: { - if (!info.device_) - return QVariant(); + if (!info.device_) return QVariant(); QString ret = info.device_->url().path(); -# ifdef Q_OS_WIN32 - if (ret.startsWith('/')) - ret.remove(0, 1); -# endif +#ifdef Q_OS_WIN32 + if (ret.startsWith('/')) ret.remove(0, 1); +#endif return QDir::toNativeSeparators(ret); } @@ -357,8 +349,7 @@ QVariant DeviceManager::data(const QModelIndex& index, int role) const { return info.transcode_format_; case Role_SongCount: - if (!info.device_) - return QVariant(); + if (!info.device_) return QVariant(); return info.device_->song_count(); default: @@ -366,45 +357,45 @@ QVariant DeviceManager::data(const QModelIndex& index, int role) const { } } -void DeviceManager::AddLister(DeviceLister *lister) { +void DeviceManager::AddLister(DeviceLister* lister) { listers_ << lister; - connect(lister, SIGNAL(DeviceAdded(QString)), SLOT(PhysicalDeviceAdded(QString))); - connect(lister, SIGNAL(DeviceRemoved(QString)), SLOT(PhysicalDeviceRemoved(QString))); - connect(lister, SIGNAL(DeviceChanged(QString)), SLOT(PhysicalDeviceChanged(QString))); + connect(lister, SIGNAL(DeviceAdded(QString)), + SLOT(PhysicalDeviceAdded(QString))); + connect(lister, SIGNAL(DeviceRemoved(QString)), + SLOT(PhysicalDeviceRemoved(QString))); + connect(lister, SIGNAL(DeviceChanged(QString)), + SLOT(PhysicalDeviceChanged(QString))); lister->Start(); } -int DeviceManager::FindDeviceById(const QString &id) const { - for (int i=0 ; i& urls) const { - if (urls.isEmpty()) - return -1; + if (urls.isEmpty()) return -1; - for (int i=0 ; i device_urls = backend.lister_->MakeDeviceUrls(backend.unique_id_); - foreach (const QUrl& url, device_urls) { - if (urls.contains(url)) - return i; + QList device_urls = + backend.lister_->MakeDeviceUrls(backend.unique_id_); + foreach(const QUrl & url, device_urls) { + if (urls.contains(url)) return i; } } } return -1; } -void DeviceManager::PhysicalDeviceAdded(const QString &id) { +void DeviceManager::PhysicalDeviceAdded(const QString& id) { DeviceLister* lister = qobject_cast(sender()); qLog(Info) << "Device added:" << id; @@ -413,7 +404,8 @@ void DeviceManager::PhysicalDeviceAdded(const QString &id) { int i = FindDeviceById(id); if (i != -1) { DeviceInfo& info = devices_[i]; - for (int backend_index = 0 ; backend_index < info.backends_.count() ; ++backend_index) { + for (int backend_index = 0; backend_index < info.backends_.count(); + ++backend_index) { if (info.backends_[backend_index].unique_id_ == id) { info.backends_[backend_index].lister_ = lister; break; @@ -453,7 +445,7 @@ void DeviceManager::PhysicalDeviceAdded(const QString &id) { } } -void DeviceManager::PhysicalDeviceRemoved(const QString &id) { +void DeviceManager::PhysicalDeviceRemoved(const QString& id) { DeviceLister* lister = qobject_cast(sender()); qLog(Info) << "Device removed:" << id; @@ -468,23 +460,23 @@ void DeviceManager::PhysicalDeviceRemoved(const QString &id) { if (info.database_id_ != -1) { // Keep the structure around, but just "disconnect" it - for (int backend_index = 0 ; backend_index < info.backends_.count() ; ++backend_index) { + for (int backend_index = 0; backend_index < info.backends_.count(); + ++backend_index) { if (info.backends_[backend_index].unique_id_ == id) { info.backends_[backend_index].lister_ = nullptr; break; } } - if (info.device_ && info.device_->lister() == lister) - info.device_.reset(); + if (info.device_ && info.device_->lister() == lister) info.device_.reset(); - if (!info.device_) - emit DeviceDisconnected(i); + if (!info.device_) emit DeviceDisconnected(i); emit dataChanged(index(i, 0), index(i, 0)); } else { // If this was the last lister for the device then remove it from the model - for (int backend_index = 0 ; backend_index < info.backends_.count() ; ++backend_index) { + for (int backend_index = 0; backend_index < info.backends_.count(); + ++backend_index) { if (info.backends_[backend_index].unique_id_ == id) { info.backends_.removeAt(backend_index); break; @@ -495,11 +487,11 @@ void DeviceManager::PhysicalDeviceRemoved(const QString &id) { beginRemoveRows(QModelIndex(), i, i); devices_.removeAt(i); - foreach (const QModelIndex& idx, persistentIndexList()) { + foreach(const QModelIndex & idx, persistentIndexList()) { if (idx.row() == i) changePersistentIndex(idx, QModelIndex()); else if (idx.row() > i) - changePersistentIndex(idx, index(idx.row()-1, idx.column())); + changePersistentIndex(idx, index(idx.row() - 1, idx.column())); } endRemoveRows(); @@ -507,7 +499,7 @@ void DeviceManager::PhysicalDeviceRemoved(const QString &id) { } } -void DeviceManager::PhysicalDeviceChanged(const QString &id) { +void DeviceManager::PhysicalDeviceChanged(const QString& id) { DeviceLister* lister = qobject_cast(sender()); Q_UNUSED(lister); @@ -522,15 +514,16 @@ void DeviceManager::PhysicalDeviceChanged(const QString &id) { std::shared_ptr DeviceManager::Connect(int row) { DeviceInfo& info = devices_[row]; - if (info.device_) // Already connected + if (info.device_) // Already connected return info.device_; std::shared_ptr ret; - if (!info.BestBackend()->lister_) // Not physically connected + if (!info.BestBackend()->lister_) // Not physically connected return ret; - if (info.BestBackend()->lister_->DeviceNeedsMount(info.BestBackend()->unique_id_)) { + if (info.BestBackend()->lister_->DeviceNeedsMount( + info.BestBackend()->unique_id_)) { // Mount the device info.BestBackend()->lister_->MountDevice(info.BestBackend()->unique_id_); return ret; @@ -545,12 +538,11 @@ std::shared_ptr DeviceManager::Connect(int row) { // Get the device URLs QList urls = info.BestBackend()->lister_->MakeDeviceUrls( info.BestBackend()->unique_id_); - if (urls.isEmpty()) - return ret; + if (urls.isEmpty()) return ret; // Take the first URL that we have a handler for QUrl device_url; - foreach (const QUrl& url, urls) { + foreach(const QUrl & url, urls) { qLog(Info) << "Connecting" << url; // Find a device class for this URL's scheme @@ -563,18 +555,24 @@ std::shared_ptr DeviceManager::Connect(int row) { // was "ipod" or "mtp" then the user compiled out support and the device // won't work properly. if (url.scheme() == "mtp" || url.scheme() == "gphoto2") { - if (QMessageBox::critical(nullptr, tr("This device will not work properly"), - tr("This is an MTP device, but you compiled Clementine without libmtp support.") + " " + - tr("If you continue, this device will work slowly and songs copied to it may not work."), - QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort) + if (QMessageBox::critical( + nullptr, tr("This device will not work properly"), + tr("This is an MTP device, but you compiled Clementine without " + "libmtp support.") + + " " + tr("If you continue, this device will work slowly and " + "songs copied to it may not work."), + QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort) return ret; } if (url.scheme() == "ipod") { - if (QMessageBox::critical(nullptr, tr("This device will not work properly"), - tr("This is an iPod, but you compiled Clementine without libgpod support.") + " " + - tr("If you continue, this device will work slowly and songs copied to it may not work."), - QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort) + if (QMessageBox::critical( + nullptr, tr("This device will not work properly"), + tr("This is an iPod, but you compiled Clementine without libgpod " + "support.") + + " " + tr("If you continue, this device will work slowly and " + "songs copied to it may not work."), + QMessageBox::Abort, QMessageBox::Ignore) == QMessageBox::Abort) return ret; } } @@ -582,17 +580,19 @@ std::shared_ptr DeviceManager::Connect(int row) { if (device_url.isEmpty()) { // Munge the URL list into a string list QStringList url_strings; - foreach (const QUrl& url, urls) { url_strings << url.toString(); } + foreach(const QUrl & url, urls) { url_strings << url.toString(); } - app_->AddError(tr("This type of device is not supported: %1").arg(url_strings.join(", "))); + app_->AddError(tr("This type of device is not supported: %1") + .arg(url_strings.join(", "))); return ret; } QMetaObject meta_object = device_classes_.value(device_url.scheme()); QObject* instance = meta_object.newInstance( - Q_ARG(QUrl, device_url), Q_ARG(DeviceLister*, info.BestBackend()->lister_), - Q_ARG(QString, info.BestBackend()->unique_id_), Q_ARG(DeviceManager*, this), - Q_ARG(Application*, app_), + Q_ARG(QUrl, device_url), + Q_ARG(DeviceLister*, info.BestBackend()->lister_), + Q_ARG(QString, info.BestBackend()->unique_id_), + Q_ARG(DeviceManager*, this), Q_ARG(Application*, app_), Q_ARG(int, info.database_id_), Q_ARG(bool, first_time)); ret.reset(static_cast(instance)); @@ -603,8 +603,10 @@ std::shared_ptr DeviceManager::Connect(int row) { info.device_ = ret; emit dataChanged(index(row), index(row)); - connect(info.device_.get(), SIGNAL(TaskStarted(int)), SLOT(DeviceTaskStarted(int))); - connect(info.device_.get(), SIGNAL(SongCountUpdated(int)), SLOT(DeviceSongCountUpdated(int))); + connect(info.device_.get(), SIGNAL(TaskStarted(int)), + SLOT(DeviceTaskStarted(int))); + connect(info.device_.get(), SIGNAL(SongCountUpdated(int)), + SLOT(DeviceSongCountUpdated(int))); } emit DeviceConnected(row); @@ -612,7 +614,8 @@ std::shared_ptr DeviceManager::Connect(int row) { return ret; } -std::shared_ptr DeviceManager::GetConnectedDevice(int row) const { +std::shared_ptr DeviceManager::GetConnectedDevice(int row) + const { return devices_[row].device_; } @@ -626,7 +629,7 @@ DeviceLister* DeviceManager::GetLister(int row) const { void DeviceManager::Disconnect(int row) { DeviceInfo& info = devices_[row]; - if (!info.device_) // Already disconnected + if (!info.device_) // Already disconnected return; info.device_.reset(); @@ -636,11 +639,9 @@ void DeviceManager::Disconnect(int row) { void DeviceManager::Forget(int row) { DeviceInfo& info = devices_[row]; - if (info.database_id_ == -1) - return; + if (info.database_id_ == -1) return; - if (info.device_) - Disconnect(row); + if (info.device_) Disconnect(row); backend_->RemoveDevice(info.database_id_); info.database_id_ = -1; @@ -650,11 +651,11 @@ void DeviceManager::Forget(int row) { beginRemoveRows(QModelIndex(), row, row); devices_.removeAt(row); - foreach (const QModelIndex& idx, persistentIndexList()) { + foreach(const QModelIndex & idx, persistentIndexList()) { if (idx.row() == row) changePersistentIndex(idx, QModelIndex()); else if (idx.row() > row) - changePersistentIndex(idx, index(idx.row()-1, idx.column())); + changePersistentIndex(idx, index(idx.row() - 1, idx.column())); } endRemoveRows(); @@ -664,15 +665,17 @@ void DeviceManager::Forget(int row) { const QString id = info.BestBackend()->unique_id_; info.friendly_name_ = info.BestBackend()->lister_->MakeFriendlyName(id); - info.LoadIcon(info.BestBackend()->lister_->DeviceIcons(id), info.friendly_name_); + info.LoadIcon(info.BestBackend()->lister_->DeviceIcons(id), + info.friendly_name_); dataChanged(index(row, 0), index(row, 0)); } } -void DeviceManager::SetDeviceOptions(int row, - const QString& friendly_name, const QString& icon_name, - MusicStorage::TranscodeMode mode, Song::FileType format) { +void DeviceManager::SetDeviceOptions(int row, const QString& friendly_name, + const QString& icon_name, + MusicStorage::TranscodeMode mode, + Song::FileType format) { DeviceInfo& info = devices_[row]; info.friendly_name_ = friendly_name; info.LoadIcon(QVariantList() << icon_name, friendly_name); @@ -688,10 +691,9 @@ void DeviceManager::SetDeviceOptions(int row, void DeviceManager::DeviceTaskStarted(int id) { ConnectedDevice* device = qobject_cast(sender()); - if (!device) - return; + if (!device) return; - for (int i=0 ; i tasks = app_->task_manager()->GetTasks(); QList finished_tasks = active_tasks_.values(); - foreach (const TaskManager::Task& task, tasks) { - if (!active_tasks_.contains(task.id)) - continue; + foreach(const TaskManager::Task & task, tasks) { + if (!active_tasks_.contains(task.id)) continue; QPersistentModelIndex index = active_tasks_[task.id]; - if (!index.isValid()) - continue; + if (!index.isValid()) continue; DeviceInfo& info = devices_[index.row()]; if (task.progress_max) @@ -723,9 +723,8 @@ void DeviceManager::TasksChanged() { finished_tasks.removeAll(index); } - foreach (const QPersistentModelIndex& index, finished_tasks) { - if (!index.isValid()) - continue; + foreach(const QPersistentModelIndex & index, finished_tasks) { + if (!index.isValid()) continue; DeviceInfo& info = devices_[index.row()]; info.task_percentage_ = -1; @@ -741,11 +740,9 @@ void DeviceManager::UnmountAsync(int row) { void DeviceManager::Unmount(int row) { DeviceInfo& info = devices_[row]; - if (info.database_id_ != -1 && !info.device_) - return; + if (info.database_id_ != -1 && !info.device_) return; - if (info.device_) - Disconnect(row); + if (info.device_) Disconnect(row); if (info.BestBackend()->lister_) info.BestBackend()->lister_->UnmountDevice(info.BestBackend()->unique_id_); @@ -753,12 +750,10 @@ void DeviceManager::Unmount(int row) { void DeviceManager::DeviceSongCountUpdated(int count) { ConnectedDevice* device = qobject_cast(sender()); - if (!device) - return; + if (!device) return; int row = FindDeviceById(device->unique_id()); - if (row == -1) - return; + if (row == -1) return; emit dataChanged(index(row), index(row)); } diff --git a/src/devices/devicemanager.h b/src/devices/devicemanager.h index 6f20b0159..39b70aa3a 100644 --- a/src/devices/devicemanager.h +++ b/src/devices/devicemanager.h @@ -38,7 +38,7 @@ class TaskManager; class DeviceManager : public QAbstractListModel { Q_OBJECT -public: + public: DeviceManager(Application* app, QObject* parent = 0); ~DeviceManager(); @@ -54,7 +54,6 @@ public: Role_TranscodeMode, Role_TranscodeFormat, Role_SongCount, - LastRole, }; @@ -68,7 +67,9 @@ public: static const int kDeviceIconSize; static const int kDeviceIconOverlaySize; - DeviceStateFilterModel* connected_devices_model() const { return connected_devices_model_; } + DeviceStateFilterModel* connected_devices_model() const { + return connected_devices_model_; + } // Get info about devices int GetDatabaseId(int row) const; @@ -84,22 +85,23 @@ public: void Forget(int row); void UnmountAsync(int row); - void SetDeviceOptions(int row, - const QString& friendly_name, const QString& icon_name, - MusicStorage::TranscodeMode mode, Song::FileType format); + void SetDeviceOptions(int row, const QString& friendly_name, + const QString& icon_name, + MusicStorage::TranscodeMode mode, + Song::FileType format); // QAbstractListModel - int rowCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; + int rowCount(const QModelIndex& parent) const; + QVariant data(const QModelIndex& index, int role) const; -public slots: + public slots: void Unmount(int row); signals: void DeviceConnected(int row); void DeviceDisconnected(int row); -private slots: + private slots: void PhysicalDeviceAdded(const QString& id); void PhysicalDeviceRemoved(const QString& id); void PhysicalDeviceChanged(const QString& id); @@ -108,7 +110,7 @@ private slots: void DeviceSongCountUpdated(int count); void LoadAllDevices(); -private: + private: // Devices can be in three different states: // 1) Remembered in the database but not physically connected at the moment. // database_id valid, lister null, device null @@ -126,9 +128,9 @@ private: // the device will have multiple "backends". struct Backend { Backend(DeviceLister* lister = NULL, const QString& id = QString()) - : lister_(lister), unique_id_(id) {} + : lister_(lister), unique_id_(id) {} - DeviceLister* lister_; // NULL if not physically connected + DeviceLister* lister_; // NULL if not physically connected QString unique_id_; }; @@ -142,9 +144,9 @@ private: // Gets the best backend available (the one with the highest priority) const Backend* BestBackend() const; - - int database_id_; // -1 if not remembered in the database - std::shared_ptr device_; // NULL if not connected to clementine + int database_id_; // -1 if not remembered in the database + std::shared_ptr + device_; // NULL if not connected to clementine QList backends_; QString friendly_name_; @@ -160,11 +162,13 @@ private: }; void AddLister(DeviceLister* lister); - template void AddDeviceClass(); + template + void AddDeviceClass(); - DeviceDatabaseBackend::Device InfoToDatabaseDevice(const DeviceInfo& info) const; + DeviceDatabaseBackend::Device InfoToDatabaseDevice(const DeviceInfo& info) + const; -private: + private: Application* app_; DeviceDatabaseBackend* backend_; @@ -183,16 +187,14 @@ private: QThreadPool thread_pool_; }; - - template void DeviceManager::AddDeviceClass() { QStringList schemes = T::url_schemes(); QMetaObject obj = T::staticMetaObject; - foreach (const QString& scheme, schemes) { + foreach(const QString & scheme, schemes) { device_classes_.insert(scheme, obj); } } -#endif // DEVICEMANAGER_H +#endif // DEVICEMANAGER_H diff --git a/src/devices/deviceproperties.cpp b/src/devices/deviceproperties.cpp index 68e52b225..3dd1a8323 100644 --- a/src/devices/deviceproperties.cpp +++ b/src/devices/deviceproperties.cpp @@ -32,66 +32,67 @@ #include "transcoder/transcoder.h" #include "ui/iconloader.h" -DeviceProperties::DeviceProperties(QWidget *parent) - : QDialog(parent), - ui_(new Ui_DeviceProperties), - manager_(nullptr), - updating_formats_(false) -{ +DeviceProperties::DeviceProperties(QWidget* parent) + : QDialog(parent), + ui_(new Ui_DeviceProperties), + manager_(nullptr), + updating_formats_(false) { ui_->setupUi(this); connect(ui_->open_device, SIGNAL(clicked()), SLOT(OpenDevice())); // Maximum height of the icon widget - ui_->icon->setMaximumHeight(ui_->icon->iconSize().height() + - ui_->icon->horizontalScrollBar()->sizeHint().height() + - ui_->icon->spacing() * 2 + 5); + ui_->icon->setMaximumHeight( + ui_->icon->iconSize().height() + + ui_->icon->horizontalScrollBar()->sizeHint().height() + + ui_->icon->spacing() * 2 + 5); } -DeviceProperties::~DeviceProperties() { - delete ui_; -} +DeviceProperties::~DeviceProperties() { delete ui_; } -void DeviceProperties::SetDeviceManager(DeviceManager *manager) { +void DeviceProperties::SetDeviceManager(DeviceManager* manager) { manager_ = manager; - connect(manager_, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(ModelChanged())); - connect(manager_, SIGNAL(rowsInserted(QModelIndex,int,int)), SLOT(ModelChanged())); - connect(manager_, SIGNAL(rowsRemoved(QModelIndex,int,int)), SLOT(ModelChanged())); + connect(manager_, SIGNAL(dataChanged(QModelIndex, QModelIndex)), + SLOT(ModelChanged())); + connect(manager_, SIGNAL(rowsInserted(QModelIndex, int, int)), + SLOT(ModelChanged())); + connect(manager_, SIGNAL(rowsRemoved(QModelIndex, int, int)), + SLOT(ModelChanged())); } void DeviceProperties::ShowDevice(int row) { if (ui_->icon->count() == 0) { // Only load the icons the first time the dialog is shown QStringList icon_names = QStringList() - << "drive-removable-media-usb-pendrive" - << "multimedia-player-ipod-mini-blue" - << "multimedia-player-ipod-mini-gold" - << "multimedia-player-ipod-mini-green" - << "multimedia-player-ipod-mini-pink" - << "multimedia-player-ipod-mini-silver" - << "multimedia-player-ipod-nano-black" - << "multimedia-player-ipod-nano-white" - << "multimedia-player-ipod-nano-green" - << "multimedia-player-ipod-shuffle" - << "multimedia-player-ipod-standard-color" - << "multimedia-player-ipod-standard-monochrome" - << "multimedia-player-ipod-U2-color" - << "multimedia-player-ipod-U2-monochrome" - << "ipodtouchicon" - << "phone" - << "phone-google-nexus-one" - << "phone-htc-g1-white" - << "phone-nokia-n900" - << "phone-palm-pre"; + << "drive-removable-media-usb-pendrive" + << "multimedia-player-ipod-mini-blue" + << "multimedia-player-ipod-mini-gold" + << "multimedia-player-ipod-mini-green" + << "multimedia-player-ipod-mini-pink" + << "multimedia-player-ipod-mini-silver" + << "multimedia-player-ipod-nano-black" + << "multimedia-player-ipod-nano-white" + << "multimedia-player-ipod-nano-green" + << "multimedia-player-ipod-shuffle" + << "multimedia-player-ipod-standard-color" + << "multimedia-player-ipod-standard-monochrome" + << "multimedia-player-ipod-U2-color" + << "multimedia-player-ipod-U2-monochrome" + << "ipodtouchicon" + << "phone" + << "phone-google-nexus-one" + << "phone-htc-g1-white" + << "phone-nokia-n900" + << "phone-palm-pre"; - foreach (const QString& icon_name, icon_names) { - QListWidgetItem* item = new QListWidgetItem( - IconLoader::Load(icon_name), QString(), ui_->icon); + foreach(const QString & icon_name, icon_names) { + QListWidgetItem* item = new QListWidgetItem(IconLoader::Load(icon_name), + QString(), ui_->icon); item->setData(Qt::UserRole, icon_name); } // Load the transcode formats the first time the dialog is shown - foreach (const TranscoderPreset& preset, Transcoder::GetAllPresets()) { + foreach(const TranscoderPreset & preset, Transcoder::GetAllPresets()) { ui_->transcode_format->addItem(preset.name_, preset.type_); } ui_->transcode_format->model()->sort(0); @@ -104,7 +105,7 @@ void DeviceProperties::ShowDevice(int row) { // Find the right icon QString icon_name = index_.data(DeviceManager::Role_IconName).toString(); - for (int i=0 ; iicon->count() ; ++i) { + for (int i = 0; i < ui_->icon->count(); ++i) { if (ui_->icon->item(i)->data(Qt::UserRole).toString() == icon_name) { ui_->icon->setCurrentRow(i); break; @@ -117,17 +118,17 @@ void DeviceProperties::ShowDevice(int row) { show(); } -void DeviceProperties::AddHardwareInfo(int row, const QString &key, const QString &value) { +void DeviceProperties::AddHardwareInfo(int row, const QString& key, + const QString& value) { ui_->hardware_info->setItem(row, 0, new QTableWidgetItem(key)); ui_->hardware_info->setItem(row, 1, new QTableWidgetItem(value)); } void DeviceProperties::ModelChanged() { - if (!isVisible()) - return; + if (!isVisible()) return; if (!index_.isValid()) - reject(); // Device went away + reject(); // Device went away else { UpdateHardwareInfo(); UpdateFormats(); @@ -141,7 +142,7 @@ void DeviceProperties::UpdateHardwareInfo() { QVariantMap info = lister->DeviceHardwareInfo(id); // Remove empty items - foreach (const QString& key, info.keys()) { + foreach(const QString & key, info.keys()) { if (info[key].isNull() || info[key].toString().isEmpty()) info.remove(key); } @@ -153,13 +154,14 @@ void DeviceProperties::UpdateHardwareInfo() { int row = 0; AddHardwareInfo(row++, tr("Model"), lister->DeviceModel(id)); AddHardwareInfo(row++, tr("Manufacturer"), lister->DeviceManufacturer(id)); - foreach (const QString& key, info.keys()) { + foreach(const QString & key, info.keys()) { AddHardwareInfo(row++, tr(key.toAscii()), info[key].toString()); } ui_->hardware_info->sortItems(0); } else { - ui_->hardware_info_stack->setCurrentWidget(ui_->hardware_info_not_connected_page); + ui_->hardware_info_stack->setCurrentWidget( + ui_->hardware_info_not_connected_page); } // Size @@ -246,17 +248,16 @@ void DeviceProperties::accept() { mode = MusicStorage::Transcode_Unsupported; // Transcode format - Song::FileType format = Song::FileType(ui_->transcode_format->itemData( - ui_->transcode_format->currentIndex()).toInt()); + Song::FileType format = Song::FileType( + ui_->transcode_format->itemData(ui_->transcode_format->currentIndex()) + .toInt()); - manager_->SetDeviceOptions(index_.row(), - ui_->name->text(), ui_->icon->currentItem()->data(Qt::UserRole).toString(), - mode, format); + manager_->SetDeviceOptions( + index_.row(), ui_->name->text(), + ui_->icon->currentItem()->data(Qt::UserRole).toString(), mode, format); } -void DeviceProperties::OpenDevice() { - manager_->Connect(index_.row()); -} +void DeviceProperties::OpenDevice() { manager_->Connect(index_.row()); } void DeviceProperties::UpdateFormatsFinished() { QFutureWatcher* watcher = static_cast*>(sender()); @@ -277,21 +278,23 @@ void DeviceProperties::UpdateFormatsFinished() { // Populate supported types list ui_->supported_formats->clear(); - foreach (Song::FileType type, supported_formats_) { + foreach(Song::FileType type, supported_formats_) { QListWidgetItem* item = new QListWidgetItem(Song::TextForFiletype(type)); ui_->supported_formats->addItem(item); } ui_->supported_formats->sortItems(); // Set the format combobox item - TranscoderPreset preset = Transcoder::PresetForFileType(Song::FileType( - index_.data(DeviceManager::Role_TranscodeFormat).toInt())); + TranscoderPreset preset = Transcoder::PresetForFileType( + Song::FileType(index_.data(DeviceManager::Role_TranscodeFormat).toInt())); if (preset.type_ == Song::Type_Unknown) { // The user hasn't chosen a format for this device yet, so work our way down // a list of some preferred formats, picking the first one that is supported - preset = Transcoder::PresetForFileType(Transcoder::PickBestFormat(supported_formats_)); + preset = Transcoder::PresetForFileType( + Transcoder::PickBestFormat(supported_formats_)); } - ui_->transcode_format->setCurrentIndex(ui_->transcode_format->findText(preset.name_)); + ui_->transcode_format->setCurrentIndex( + ui_->transcode_format->findText(preset.name_)); ui_->formats_stack->setCurrentWidget(ui_->formats_page); } diff --git a/src/devices/deviceproperties.h b/src/devices/deviceproperties.h index eac5b0333..e797cdb5c 100644 --- a/src/devices/deviceproperties.h +++ b/src/devices/deviceproperties.h @@ -29,27 +29,27 @@ class Ui_DeviceProperties; class DeviceProperties : public QDialog { Q_OBJECT -public: + public: DeviceProperties(QWidget* parent = 0); ~DeviceProperties(); void SetDeviceManager(DeviceManager* manager); void ShowDevice(int row); -public slots: + public slots: void accept(); -private: + private: void UpdateHardwareInfo(); void AddHardwareInfo(int row, const QString& key, const QString& value); void UpdateFormats(); -private slots: + private slots: void ModelChanged(); void OpenDevice(); void UpdateFormatsFinished(); -private: + private: Ui_DeviceProperties* ui_; DeviceManager* manager_; @@ -59,4 +59,4 @@ private: QList supported_formats_; }; -#endif // DEVICEPROPERTIES_H +#endif // DEVICEPROPERTIES_H diff --git a/src/devices/devicestatefiltermodel.cpp b/src/devices/devicestatefiltermodel.cpp index c0aa057db..bf132c3fa 100644 --- a/src/devices/devicestatefiltermodel.cpp +++ b/src/devices/devicestatefiltermodel.cpp @@ -17,19 +17,20 @@ #include "devicestatefiltermodel.h" -DeviceStateFilterModel::DeviceStateFilterModel(QObject *parent, +DeviceStateFilterModel::DeviceStateFilterModel(QObject* parent, DeviceManager::State state) - : QSortFilterProxyModel(parent), - state_(state) -{ - connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), SLOT(ProxyRowCountChanged())); - connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), SLOT(ProxyRowCountChanged())); + : QSortFilterProxyModel(parent), state_(state) { + connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)), + SLOT(ProxyRowCountChanged())); + connect(this, SIGNAL(rowsRemoved(QModelIndex, int, int)), + SLOT(ProxyRowCountChanged())); connect(this, SIGNAL(modelReset()), SLOT(ProxyRowCountChanged())); } -bool DeviceStateFilterModel::filterAcceptsRow(int row, const QModelIndex&) const { - return sourceModel()->index(row, 0).data(DeviceManager::Role_State).toInt() - != state_; +bool DeviceStateFilterModel::filterAcceptsRow(int row, + const QModelIndex&) const { + return sourceModel()->index(row, 0).data(DeviceManager::Role_State).toInt() != + state_; } void DeviceStateFilterModel::ProxyRowCountChanged() { diff --git a/src/devices/devicestatefiltermodel.h b/src/devices/devicestatefiltermodel.h index be3ea8b74..33a3ab2f9 100644 --- a/src/devices/devicestatefiltermodel.h +++ b/src/devices/devicestatefiltermodel.h @@ -25,23 +25,23 @@ class DeviceStateFilterModel : public QSortFilterProxyModel { Q_OBJECT -public: - DeviceStateFilterModel(QObject* parent, - DeviceManager::State state = DeviceManager::State_Remembered); + public: + DeviceStateFilterModel(QObject* parent, DeviceManager::State state = + DeviceManager::State_Remembered); void setSourceModel(QAbstractItemModel* sourceModel); signals: void IsEmptyChanged(bool is_empty); -protected: + protected: bool filterAcceptsRow(int row, const QModelIndex& parent) const; -private slots: + private slots: void ProxyRowCountChanged(); -private: + private: DeviceManager::State state_; }; -#endif // DEVICESTATEFILTERMODEL_H +#endif // DEVICESTATEFILTERMODEL_H diff --git a/src/devices/deviceview.cpp b/src/devices/deviceview.cpp index 2e8190880..8fa2b9220 100644 --- a/src/devices/deviceview.cpp +++ b/src/devices/deviceview.cpp @@ -44,12 +44,11 @@ const int DeviceItemDelegate::kIconPadding = 6; -DeviceItemDelegate::DeviceItemDelegate(QObject *parent) - : LibraryItemDelegate(parent) -{ -} +DeviceItemDelegate::DeviceItemDelegate(QObject* parent) + : LibraryItemDelegate(parent) {} -void DeviceItemDelegate::paint(QPainter* p, const QStyleOptionViewItem& opt, const QModelIndex& index) const { +void DeviceItemDelegate::paint(QPainter* p, const QStyleOptionViewItem& opt, + const QModelIndex& index) const { // Is it a device or a library item? if (index.data(DeviceManager::Role_State).isNull()) { LibraryItemDelegate::paint(p, opt, index); @@ -57,7 +56,8 @@ void DeviceItemDelegate::paint(QPainter* p, const QStyleOptionViewItem& opt, con } // Draw the background - const QStyleOptionViewItemV3* vopt = qstyleoption_cast(&opt); + const QStyleOptionViewItemV3* vopt = + qstyleoption_cast(&opt); const QWidget* widget = vopt->widget; QStyle* style = widget->style() ? widget->style() : QApplication::style(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, p, widget); @@ -73,8 +73,8 @@ void DeviceItemDelegate::paint(QPainter* p, const QStyleOptionViewItem& opt, con status_font.setPointSize(status_font.pointSize() - 2); #endif - const int text_height = QFontMetrics(opt.font).height() + - QFontMetrics(status_font).height(); + const int text_height = + QFontMetrics(opt.font).height() + QFontMetrics(status_font).height(); QRect line1(opt.rect); QRect line2(opt.rect); @@ -89,14 +89,15 @@ void DeviceItemDelegate::paint(QPainter* p, const QStyleOptionViewItem& opt, con } // Draw the icon - p->drawPixmap(opt.rect.topLeft(), index.data(Qt::DecorationRole).value()); + p->drawPixmap(opt.rect.topLeft(), + index.data(Qt::DecorationRole).value()); // Draw the first line (device name) p->drawText(line1, Qt::AlignLeft | Qt::AlignTop, index.data().toString()); // Draw the second line (status) - DeviceManager::State state = - static_cast(index.data(DeviceManager::Role_State).toInt()); + DeviceManager::State state = static_cast( + index.data(DeviceManager::Role_State).toInt()); QVariant progress = index.data(DeviceManager::Role_UpdatingPercentage); QString status_text; @@ -120,7 +121,7 @@ void DeviceItemDelegate::paint(QPainter* p, const QStyleOptionViewItem& opt, con QVariant song_count = index.data(DeviceManager::Role_SongCount); if (song_count.isValid()) { int count = song_count.toInt(); - if (count == 1) // TODO: Fix this properly + if (count == 1) // TODO: Fix this properly status_text = tr("%1 song").arg(count); else status_text = tr("%1 songs").arg(count); @@ -142,17 +143,14 @@ void DeviceItemDelegate::paint(QPainter* p, const QStyleOptionViewItem& opt, con p->restore(); } - - DeviceView::DeviceView(QWidget* parent) - : AutoExpandingTreeView(parent), - app_(nullptr), - merged_model_(nullptr), - sort_model_(nullptr), - properties_dialog_(new DeviceProperties), - device_menu_(nullptr), - library_menu_(nullptr) -{ + : AutoExpandingTreeView(parent), + app_(nullptr), + merged_model_(nullptr), + sort_model_(nullptr), + properties_dialog_(new DeviceProperties), + device_menu_(nullptr), + library_menu_(nullptr) { setItemDelegate(new DeviceItemDelegate(this)); SetExpandOnReset(false); setAttribute(Qt::WA_MacShowFocusRect, false); @@ -163,15 +161,16 @@ DeviceView::DeviceView(QWidget* parent) setSelectionMode(QAbstractItemView::ExtendedSelection); } -DeviceView::~DeviceView() { -} +DeviceView::~DeviceView() {} void DeviceView::SetApplication(Application* app) { Q_ASSERT(app_ == nullptr); app_ = app; - connect(app_->device_manager(), SIGNAL(DeviceConnected(int)), SLOT(DeviceConnected(int))); - connect(app_->device_manager(), SIGNAL(DeviceDisconnected(int)), SLOT(DeviceDisconnected(int))); + connect(app_->device_manager(), SIGNAL(DeviceConnected(int)), + SLOT(DeviceConnected(int))); + connect(app_->device_manager(), SIGNAL(DeviceDisconnected(int)), + SLOT(DeviceDisconnected(int))); sort_model_ = new QSortFilterProxyModel(this); sort_model_->setSourceModel(app_->device_manager()); @@ -183,14 +182,15 @@ void DeviceView::SetApplication(Application* app) { merged_model_->setSourceModel(sort_model_); connect(merged_model_, - SIGNAL(SubModelReset(QModelIndex,QAbstractItemModel*)), + SIGNAL(SubModelReset(QModelIndex, QAbstractItemModel*)), SLOT(RecursivelyExpand(QModelIndex))); setModel(merged_model_); properties_dialog_->SetDeviceManager(app_->device_manager()); organise_dialog_.reset(new OrganiseDialog(app_->task_manager())); - organise_dialog_->SetDestinationModel(app_->library_model()->directory_model()); + organise_dialog_->SetDestinationModel( + app_->library_model()->directory_model()); } void DeviceView::contextMenuEvent(QContextMenuEvent* e) { @@ -199,26 +199,34 @@ void DeviceView::contextMenuEvent(QContextMenuEvent* e) { library_menu_ = new QMenu(this); // Device menu - eject_action_ = device_menu_->addAction( - IconLoader::Load("media-eject"), tr("Safely remove device"), this, SLOT(Unmount())); - forget_action_ = device_menu_->addAction( - IconLoader::Load("list-remove"), tr("Forget device"), this, SLOT(Forget())); + eject_action_ = device_menu_->addAction(IconLoader::Load("media-eject"), + tr("Safely remove device"), this, + SLOT(Unmount())); + forget_action_ = + device_menu_->addAction(IconLoader::Load("list-remove"), + tr("Forget device"), this, SLOT(Forget())); device_menu_->addSeparator(); - properties_action_ = device_menu_->addAction( - IconLoader::Load("configure"), tr("Device properties..."), this, SLOT(Properties())); + properties_action_ = device_menu_->addAction(IconLoader::Load("configure"), + tr("Device properties..."), + this, SLOT(Properties())); // Library menu - add_to_playlist_action_ = library_menu_->addAction(IconLoader::Load("media-playback-start"), + add_to_playlist_action_ = library_menu_->addAction( + IconLoader::Load("media-playback-start"), tr("Append to current playlist"), this, SLOT(AddToPlaylist())); - load_action_ = library_menu_->addAction(IconLoader::Load("media-playback-start"), + load_action_ = library_menu_->addAction( + IconLoader::Load("media-playback-start"), tr("Replace current playlist"), this, SLOT(Load())); - open_in_new_playlist_ = library_menu_->addAction(IconLoader::Load("document-new"), - tr("Open in new playlist"), this, SLOT(OpenInNewPlaylist())); + open_in_new_playlist_ = library_menu_->addAction( + IconLoader::Load("document-new"), tr("Open in new playlist"), this, + SLOT(OpenInNewPlaylist())); library_menu_->addSeparator(); organise_action_ = library_menu_->addAction(IconLoader::Load("edit-copy"), - tr("Copy to library..."), this, SLOT(Organise())); + tr("Copy to library..."), this, + SLOT(Organise())); delete_action_ = library_menu_->addAction(IconLoader::Load("edit-delete"), - tr("Delete from device..."), this, SLOT(Delete())); + tr("Delete from device..."), this, + SLOT(Delete())); } menu_index_ = currentIndex(); @@ -227,8 +235,10 @@ void DeviceView::contextMenuEvent(QContextMenuEvent* e) { const QModelIndex library_index = MapToLibrary(menu_index_); if (device_index.isValid()) { - const bool is_plugged_in = app_->device_manager()->GetLister(device_index.row()); - const bool is_remembered = app_->device_manager()->GetDatabaseId(device_index.row()) != -1; + const bool is_plugged_in = + app_->device_manager()->GetLister(device_index.row()); + const bool is_remembered = + app_->device_manager()->GetDatabaseId(device_index.row()) != -1; forget_action_->setEnabled(is_remembered); eject_action_->setEnabled(is_plugged_in); @@ -241,8 +251,7 @@ void DeviceView::contextMenuEvent(QContextMenuEvent* e) { if (parent_device_index.isValid()) { std::shared_ptr device = app_->device_manager()->GetConnectedDevice(parent_device_index.row()); - if (device && !device->LocalPath().isEmpty()) - is_filesystem_device = true; + if (device && !device->LocalPath().isEmpty()) is_filesystem_device = true; } organise_action_->setEnabled(is_filesystem_device); @@ -251,26 +260,28 @@ void DeviceView::contextMenuEvent(QContextMenuEvent* e) { } } -QModelIndex DeviceView::MapToDevice(const QModelIndex& merged_model_index) const { +QModelIndex DeviceView::MapToDevice(const QModelIndex& merged_model_index) + const { QModelIndex sort_model_index = merged_model_->mapToSource(merged_model_index); - if (sort_model_index.model() != sort_model_) - return QModelIndex(); + if (sort_model_index.model() != sort_model_) return QModelIndex(); return sort_model_->mapToSource(sort_model_index); } -QModelIndex DeviceView::FindParentDevice(const QModelIndex& merged_model_index) const { +QModelIndex DeviceView::FindParentDevice(const QModelIndex& merged_model_index) + const { QModelIndex index = merged_model_->FindSourceParent(merged_model_index); - if (index.model() != sort_model_) - return QModelIndex(); + if (index.model() != sort_model_) return QModelIndex(); return sort_model_->mapToSource(index); } -QModelIndex DeviceView::MapToLibrary(const QModelIndex& merged_model_index) const { +QModelIndex DeviceView::MapToLibrary(const QModelIndex& merged_model_index) + const { QModelIndex sort_model_index = merged_model_->mapToSource(merged_model_index); if (const QSortFilterProxyModel* sort_model = - qobject_cast(sort_model_index.model())) { + qobject_cast( + sort_model_index.model())) { return sort_model->mapToSource(sort_model_index); } @@ -279,18 +290,20 @@ QModelIndex DeviceView::MapToLibrary(const QModelIndex& merged_model_index) cons void DeviceView::Connect() { QModelIndex device_idx = MapToDevice(menu_index_); - app_->device_manager()->data(device_idx, MusicStorage::Role_StorageForceConnect); + app_->device_manager()->data(device_idx, + MusicStorage::Role_StorageForceConnect); } void DeviceView::DeviceConnected(int row) { std::shared_ptr device = app_->device_manager()->GetConnectedDevice(row); - if (!device) - return; + if (!device) return; - QModelIndex sort_idx = sort_model_->mapFromSource(app_->device_manager()->index(row)); + QModelIndex sort_idx = + sort_model_->mapFromSource(app_->device_manager()->index(row)); - QSortFilterProxyModel* sort_model = new QSortFilterProxyModel(device->model()); + QSortFilterProxyModel* sort_model = + new QSortFilterProxyModel(device->model()); sort_model->setSourceModel(device->model()); sort_model->setSortRole(LibraryModel::Role_SortText); sort_model->setDynamicSortFilter(true); @@ -301,24 +314,28 @@ void DeviceView::DeviceConnected(int row) { } void DeviceView::DeviceDisconnected(int row) { - merged_model_->RemoveSubModel(sort_model_->mapFromSource(app_->device_manager()->index(row))); + merged_model_->RemoveSubModel( + sort_model_->mapFromSource(app_->device_manager()->index(row))); } void DeviceView::Forget() { QModelIndex device_idx = MapToDevice(menu_index_); - QString unique_id = app_->device_manager()->data(device_idx, DeviceManager::Role_UniqueId).toString(); + QString unique_id = app_->device_manager() + ->data(device_idx, DeviceManager::Role_UniqueId) + .toString(); if (app_->device_manager()->GetLister(device_idx.row()) && - app_->device_manager()->GetLister(device_idx.row())->AskForScan(unique_id)) { + app_->device_manager()->GetLister(device_idx.row())->AskForScan( + unique_id)) { std::unique_ptr dialog(new QMessageBox( QMessageBox::Question, tr("Forget device"), - tr("Forgetting a device will remove it from this list and Clementine will have to rescan all the songs again next time you connect it."), + tr("Forgetting a device will remove it from this list and Clementine " + "will have to rescan all the songs again next time you connect it."), QMessageBox::Cancel, this)); QPushButton* forget = dialog->addButton(tr("Forget device"), QMessageBox::DestructiveRole); dialog->exec(); - if (dialog->clickedButton() != forget) - return; + if (dialog->clickedButton() != forget) return; } app_->device_manager()->Forget(device_idx.row()); @@ -328,7 +345,7 @@ void DeviceView::Properties() { properties_dialog_->ShowDevice(MapToDevice(menu_index_).row()); } -void DeviceView::mouseDoubleClickEvent(QMouseEvent *event) { +void DeviceView::mouseDoubleClickEvent(QMouseEvent* event) { AutoExpandingTreeView::mouseDoubleClickEvent(event); QModelIndex merged_index = indexAt(event->pos()); @@ -344,15 +361,13 @@ void DeviceView::mouseDoubleClickEvent(QMouseEvent *event) { SongList DeviceView::GetSelectedSongs() const { QModelIndexList selected_merged_indexes = selectionModel()->selectedRows(); SongList songs; - foreach (const QModelIndex& merged_index, selected_merged_indexes) { + foreach(const QModelIndex & merged_index, selected_merged_indexes) { QModelIndex library_index = MapToLibrary(merged_index); - if (!library_index.isValid()) - continue; + if (!library_index.isValid()) continue; - const LibraryModel* library = qobject_cast( - library_index.model()); - if (!library) - continue; + const LibraryModel* library = + qobject_cast(library_index.model()); + if (!library) continue; songs << library->GetChildSongs(library_index); } @@ -380,33 +395,33 @@ void DeviceView::OpenInNewPlaylist() { } void DeviceView::Delete() { - if (selectedIndexes().isEmpty()) - return; + if (selectedIndexes().isEmpty()) return; // Take the device of the first selected item QModelIndex device_index = FindParentDevice(selectedIndexes()[0]); - if (!device_index.isValid()) - return; + if (!device_index.isValid()) return; if (QMessageBox::question(this, tr("Delete files"), - tr("These files will be deleted from the device, are you sure you want to continue?"), - QMessageBox::Yes, QMessageBox::Cancel) != QMessageBox::Yes) + tr("These files will be deleted from the device, " + "are you sure you want to continue?"), + QMessageBox::Yes, + QMessageBox::Cancel) != QMessageBox::Yes) return; std::shared_ptr storage = - device_index.data(MusicStorage::Role_Storage).value>(); + device_index.data(MusicStorage::Role_Storage) + .value>(); DeleteFiles* delete_files = new DeleteFiles(app_->task_manager(), storage); - connect(delete_files, SIGNAL(Finished(SongList)), SLOT(DeleteFinished(SongList))); + connect(delete_files, SIGNAL(Finished(SongList)), + SLOT(DeleteFinished(SongList))); delete_files->Start(GetSelectedSongs()); } void DeviceView::Organise() { SongList songs = GetSelectedSongs(); QStringList filenames; - foreach (const Song& song, songs) { - filenames << song.url().toLocalFile(); - } + foreach(const Song & song, songs) { filenames << song.url().toLocalFile(); } organise_dialog_->SetCopy(true); organise_dialog_->SetFilenames(filenames); @@ -419,8 +434,7 @@ void DeviceView::Unmount() { } void DeviceView::DeleteFinished(const SongList& songs_with_errors) { - if (songs_with_errors.isEmpty()) - return; + if (songs_with_errors.isEmpty()) return; OrganiseErrorDialog* dialog = new OrganiseErrorDialog(this); dialog->Show(OrganiseErrorDialog::Type_Delete, songs_with_errors); diff --git a/src/devices/deviceview.h b/src/devices/deviceview.h index f64592e6e..b2025cdde 100644 --- a/src/devices/deviceview.h +++ b/src/devices/deviceview.h @@ -35,29 +35,29 @@ class LibraryModel; class MergedProxyModel; class DeviceItemDelegate : public LibraryItemDelegate { -public: + public: DeviceItemDelegate(QObject* parent); static const int kIconPadding; - void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const; }; - class DeviceView : public AutoExpandingTreeView { Q_OBJECT -public: + public: DeviceView(QWidget* parent = 0); ~DeviceView(); void SetApplication(Application* app); -protected: - void contextMenuEvent(QContextMenuEvent *); - void mouseDoubleClickEvent(QMouseEvent *event); + protected: + void contextMenuEvent(QContextMenuEvent*); + void mouseDoubleClickEvent(QMouseEvent* event); -private slots: + private slots: // Device menu actions void Connect(); void Unmount(); @@ -79,13 +79,13 @@ private slots: // AutoExpandingTreeView bool CanRecursivelyExpand(const QModelIndex& index) const; -private: + private: QModelIndex MapToDevice(const QModelIndex& merged_model_index) const; QModelIndex MapToLibrary(const QModelIndex& merged_model_index) const; QModelIndex FindParentDevice(const QModelIndex& merged_model_index) const; SongList GetSelectedSongs() const; -private: + private: Application* app_; MergedProxyModel* merged_model_; QSortFilterProxyModel* sort_model_; @@ -108,4 +108,4 @@ private: QModelIndex menu_index_; }; -#endif // DEVICEVIEW_H +#endif // DEVICEVIEW_H diff --git a/src/devices/deviceviewcontainer.cpp b/src/devices/deviceviewcontainer.cpp index eb2de1926..4acd77367 100644 --- a/src/devices/deviceviewcontainer.cpp +++ b/src/devices/deviceviewcontainer.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -19,10 +19,8 @@ #include "ui_deviceviewcontainer.h" #include "ui/iconloader.h" -DeviceViewContainer::DeviceViewContainer(QWidget *parent) - : QWidget(parent), - ui_(new Ui::DeviceViewContainer), - loaded_icons_(false) { +DeviceViewContainer::DeviceViewContainer(QWidget* parent) + : QWidget(parent), ui_(new Ui::DeviceViewContainer), loaded_icons_(false) { ui_->setupUi(this); QPalette palette(ui_->windows_is_broken_frame->palette()); @@ -36,9 +34,7 @@ DeviceViewContainer::DeviceViewContainer(QWidget *parent) #endif } -DeviceViewContainer::~DeviceViewContainer() { - delete ui_; -} +DeviceViewContainer::~DeviceViewContainer() { delete ui_; } void DeviceViewContainer::showEvent(QShowEvent* e) { if (!loaded_icons_) { @@ -51,6 +47,4 @@ void DeviceViewContainer::showEvent(QShowEvent* e) { QWidget::showEvent(e); } -DeviceView* DeviceViewContainer::view() const { - return ui_->view; -} +DeviceView* DeviceViewContainer::view() const { return ui_->view; } diff --git a/src/devices/deviceviewcontainer.h b/src/devices/deviceviewcontainer.h index ae28b8ecc..897f6f0d2 100644 --- a/src/devices/deviceviewcontainer.h +++ b/src/devices/deviceviewcontainer.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -21,14 +21,14 @@ #include namespace Ui { - class DeviceViewContainer; +class DeviceViewContainer; } class DeviceView; class DeviceViewContainer : public QWidget { Q_OBJECT - + public: explicit DeviceViewContainer(QWidget* parent = 0); ~DeviceViewContainer(); @@ -37,10 +37,10 @@ class DeviceViewContainer : public QWidget { protected: void showEvent(QShowEvent*); - + private: Ui::DeviceViewContainer* ui_; bool loaded_icons_; }; -#endif // DEVICEVIEWCONTAINER_H +#endif // DEVICEVIEWCONTAINER_H diff --git a/src/devices/filesystemdevice.cpp b/src/devices/filesystemdevice.cpp index 8575e5fef..4805cab86 100644 --- a/src/devices/filesystemdevice.cpp +++ b/src/devices/filesystemdevice.cpp @@ -26,40 +26,40 @@ #include #include -FilesystemDevice::FilesystemDevice( - const QUrl& url, DeviceLister* lister, - const QString& unique_id, DeviceManager* manager, - Application* app, - int database_id, bool first_time) - : FilesystemMusicStorage(url.toLocalFile()), - ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time), - watcher_(new LibraryWatcher), - watcher_thread_(new QThread(this)) -{ +FilesystemDevice::FilesystemDevice(const QUrl& url, DeviceLister* lister, + const QString& unique_id, + DeviceManager* manager, Application* app, + int database_id, bool first_time) + : FilesystemMusicStorage(url.toLocalFile()), + ConnectedDevice(url, lister, unique_id, manager, app, database_id, + first_time), + watcher_(new LibraryWatcher), + watcher_thread_(new QThread(this)) { watcher_->moveToThread(watcher_thread_); watcher_thread_->start(QThread::IdlePriority); - watcher_->set_device_name(manager->data(manager->index( - manager->FindDeviceById(unique_id)), DeviceManager::Role_FriendlyName).toString()); + watcher_->set_device_name( + manager->data(manager->index(manager->FindDeviceById(unique_id)), + DeviceManager::Role_FriendlyName).toString()); watcher_->set_backend(backend_); watcher_->set_task_manager(app_->task_manager()); - connect(backend_, SIGNAL(DirectoryDiscovered(Directory,SubdirectoryList)), - watcher_, SLOT(AddDirectory(Directory,SubdirectoryList))); - connect(backend_, SIGNAL(DirectoryDeleted(Directory)), - watcher_, SLOT(RemoveDirectory(Directory))); - connect(watcher_, SIGNAL(NewOrUpdatedSongs(SongList)), - backend_, SLOT(AddOrUpdateSongs(SongList))); - connect(watcher_, SIGNAL(SongsMTimeUpdated(SongList)), - backend_, SLOT(UpdateMTimesOnly(SongList))); - connect(watcher_, SIGNAL(SongsDeleted(SongList)), - backend_, SLOT(DeleteSongs(SongList))); - connect(watcher_, SIGNAL(SubdirsDiscovered(SubdirectoryList)), - backend_, SLOT(AddOrUpdateSubdirs(SubdirectoryList))); - connect(watcher_, SIGNAL(SubdirsMTimeUpdated(SubdirectoryList)), - backend_, SLOT(AddOrUpdateSubdirs(SubdirectoryList))); - connect(watcher_, SIGNAL(CompilationsNeedUpdating()), - backend_, SLOT(UpdateCompilations())); + connect(backend_, SIGNAL(DirectoryDiscovered(Directory, SubdirectoryList)), + watcher_, SLOT(AddDirectory(Directory, SubdirectoryList))); + connect(backend_, SIGNAL(DirectoryDeleted(Directory)), watcher_, + SLOT(RemoveDirectory(Directory))); + connect(watcher_, SIGNAL(NewOrUpdatedSongs(SongList)), backend_, + SLOT(AddOrUpdateSongs(SongList))); + connect(watcher_, SIGNAL(SongsMTimeUpdated(SongList)), backend_, + SLOT(UpdateMTimesOnly(SongList))); + connect(watcher_, SIGNAL(SongsDeleted(SongList)), backend_, + SLOT(DeleteSongs(SongList))); + connect(watcher_, SIGNAL(SubdirsDiscovered(SubdirectoryList)), backend_, + SLOT(AddOrUpdateSubdirs(SubdirectoryList))); + connect(watcher_, SIGNAL(SubdirsMTimeUpdated(SubdirectoryList)), backend_, + SLOT(AddOrUpdateSubdirs(SubdirectoryList))); + connect(watcher_, SIGNAL(CompilationsNeedUpdating()), backend_, + SLOT(UpdateCompilations())); connect(watcher_, SIGNAL(ScanStarted(int)), SIGNAL(TaskStarted(int))); } diff --git a/src/devices/filesystemdevice.h b/src/devices/filesystemdevice.h index f56d32e81..2f855c9ef 100644 --- a/src/devices/filesystemdevice.h +++ b/src/devices/filesystemdevice.h @@ -24,24 +24,24 @@ class DeviceManager; class LibraryWatcher; -class FilesystemDevice : public ConnectedDevice, public virtual FilesystemMusicStorage { +class FilesystemDevice : public ConnectedDevice, + public virtual FilesystemMusicStorage { Q_OBJECT -public: - Q_INVOKABLE FilesystemDevice( - const QUrl& url, DeviceLister* lister, - const QString& unique_id, DeviceManager* manager, - Application* app, - int database_id, bool first_time); + public: + Q_INVOKABLE FilesystemDevice(const QUrl& url, DeviceLister* lister, + const QString& unique_id, DeviceManager* manager, + Application* app, int database_id, + bool first_time); ~FilesystemDevice(); void Init(); static QStringList url_schemes() { return QStringList() << "file"; } -private: + private: LibraryWatcher* watcher_; QThread* watcher_thread_; }; -#endif // FILESYSTEMDEVICE_H +#endif // FILESYSTEMDEVICE_H diff --git a/src/devices/giolister.cpp b/src/devices/giolister.cpp index 3c116d470..2f07a25da 100644 --- a/src/devices/giolister.cpp +++ b/src/devices/giolister.cpp @@ -33,30 +33,26 @@ using std::placeholders::_3; QString GioLister::DeviceInfo::unique_id() const { if (mount) - return QString("Gio/%1/%2/%3").arg(mount_uuid, filesystem_type).arg(filesystem_size); + return QString("Gio/%1/%2/%3").arg(mount_uuid, filesystem_type).arg( + filesystem_size); return QString("Gio/unmounted/%1").arg((qulonglong)volume.get()); } bool GioLister::DeviceInfo::is_suitable() const { - if (!volume) - return false; // This excludes smb or ssh mounts + if (!volume) return false; // This excludes smb or ssh mounts - if (drive && !drive_removable) - return false; // This excludes internal drives + if (drive && !drive_removable) return false; // This excludes internal drives - if (filesystem_type.isEmpty()) - return true; + if (filesystem_type.isEmpty()) return true; - return filesystem_type != "udf" && - filesystem_type != "smb" && - filesystem_type != "cifs" && - filesystem_type != "ssh" && + return filesystem_type != "udf" && filesystem_type != "smb" && + filesystem_type != "cifs" && filesystem_type != "ssh" && filesystem_type != "isofs"; } template -void OperationFinished(F f, GObject *object, GAsyncResult *result) { +void OperationFinished(F f, GObject* object, GAsyncResult* result) { T* obj = reinterpret_cast(object); GError* error = nullptr; @@ -68,9 +64,10 @@ void OperationFinished(F f, GObject *object, GAsyncResult *result) { } } -void GioLister::VolumeMountFinished(GObject* object, GAsyncResult* result, gpointer) { - OperationFinished(std::bind( - g_volume_mount_finish, _1, _2, _3), object, result); +void GioLister::VolumeMountFinished(GObject* object, GAsyncResult* result, + gpointer) { + OperationFinished(std::bind(g_volume_mount_finish, _1, _2, _3), + object, result); } void GioLister::Init() { @@ -78,7 +75,7 @@ void GioLister::Init() { // Get existing volumes GList* const volumes = g_volume_monitor_get_volumes(monitor_); - for (GList* p=volumes; p; p=p->next) { + for (GList* p = volumes; p; p = p->next) { GVolume* volume = static_cast(p->data); VolumeAdded(volume); @@ -88,7 +85,7 @@ void GioLister::Init() { // Get existing mounts GList* const mounts = g_volume_monitor_get_mounts(monitor_); - for (GList* p=mounts; p; p=p->next) { + for (GList* p = mounts; p; p = p->next) { GMount* mount = static_cast(p->data); MountAdded(mount); @@ -109,11 +106,10 @@ QStringList GioLister::DeviceUniqueIDs() { return devices_.keys(); } -QVariantList GioLister::DeviceIcons(const QString &id) { +QVariantList GioLister::DeviceIcons(const QString& id) { QVariantList ret; QMutexLocker l(&mutex_); - if (!devices_.contains(id)) - return ret; + if (!devices_.contains(id)) return ret; const DeviceInfo& info = devices_[id]; @@ -127,37 +123,33 @@ QVariantList GioLister::DeviceIcons(const QString &id) { return ret; } -QString GioLister::DeviceManufacturer(const QString &id) { - return QString(); -} +QString GioLister::DeviceManufacturer(const QString& id) { return QString(); } -QString GioLister::DeviceModel(const QString &id) { +QString GioLister::DeviceModel(const QString& id) { QMutexLocker l(&mutex_); - if (!devices_.contains(id)) - return QString(); + if (!devices_.contains(id)) return QString(); const DeviceInfo& info = devices_[id]; return info.drive_name.isEmpty() ? info.volume_name : info.drive_name; } -quint64 GioLister::DeviceCapacity(const QString &id) { +quint64 GioLister::DeviceCapacity(const QString& id) { return LockAndGetDeviceInfo(id, &DeviceInfo::filesystem_size); } -quint64 GioLister::DeviceFreeSpace(const QString &id) { +quint64 GioLister::DeviceFreeSpace(const QString& id) { return LockAndGetDeviceInfo(id, &DeviceInfo::filesystem_free); } -QString GioLister::MakeFriendlyName(const QString &id) { +QString GioLister::MakeFriendlyName(const QString& id) { return DeviceModel(id); } -QVariantMap GioLister::DeviceHardwareInfo(const QString &id) { +QVariantMap GioLister::DeviceHardwareInfo(const QString& id) { QVariantMap ret; QMutexLocker l(&mutex_); - if (!devices_.contains(id)) - return ret; + if (!devices_.contains(id)) return ret; const DeviceInfo& info = devices_[id]; ret[QT_TR_NOOP("Mount point")] = info.mount_path; @@ -226,8 +218,7 @@ void GioLister::VolumeAdded(GVolume* volume) { #endif info.ReadDriveInfo(g_volume_get_drive(volume)); info.ReadMountInfo(g_volume_get_mount(volume)); - if (!info.is_suitable()) - return; + if (!info.is_suitable()) return; { QMutexLocker l(&mutex_); @@ -242,8 +233,7 @@ void GioLister::VolumeRemoved(GVolume* volume) { { QMutexLocker l(&mutex_); id = FindUniqueIdByVolume(volume); - if (id.isNull()) - return; + if (id.isNull()) return; devices_.remove(id); } @@ -263,15 +253,14 @@ void GioLister::MountAdded(GMount* mount) { #endif info.ReadMountInfo(mount); info.ReadDriveInfo(g_mount_get_drive(mount)); - if (!info.is_suitable()) - return; + if (!info.is_suitable()) return; QString old_id; { QMutexLocker l(&mutex_); // The volume might already exist - either mounted or unmounted. - foreach (const QString& id, devices_.keys()) { + foreach(const QString & id, devices_.keys()) { if (devices_[id].volume == info.volume) { old_id = id; break; @@ -301,8 +290,7 @@ void GioLister::MountChanged(GMount* mount) { { QMutexLocker l(&mutex_); id = FindUniqueIdByMount(mount); - if (id.isNull()) - return; + if (id.isNull()) return; g_object_ref(mount); @@ -314,7 +302,8 @@ void GioLister::MountChanged(GMount* mount) { // Ignore the change if the new info is useless if (new_info.invalid_enclosing_mount || (devices_[id].filesystem_size != 0 && new_info.filesystem_size == 0) || - (!devices_[id].filesystem_type.isEmpty() && new_info.filesystem_type.isEmpty())) + (!devices_[id].filesystem_type.isEmpty() && + new_info.filesystem_type.isEmpty())) return; devices_[id] = new_info; @@ -323,13 +312,12 @@ void GioLister::MountChanged(GMount* mount) { emit DeviceChanged(id); } -void GioLister::MountRemoved(GMount *mount) { +void GioLister::MountRemoved(GMount* mount) { QString id; { QMutexLocker l(&mutex_); id = FindUniqueIdByMount(mount); - if (id.isNull()) - return; + if (id.isNull()) return; devices_.remove(id); } @@ -337,7 +325,7 @@ void GioLister::MountRemoved(GMount *mount) { emit DeviceRemoved(id); } -QString GioLister::DeviceInfo::ConvertAndFree(char *str) { +QString GioLister::DeviceInfo::ConvertAndFree(char* str) { QString ret = QString::fromUtf8(str); g_free(str); return ret; @@ -346,8 +334,7 @@ QString GioLister::DeviceInfo::ConvertAndFree(char *str) { void GioLister::DeviceInfo::ReadMountInfo(GMount* mount) { // Get basic information this->mount.reset_without_add(mount); - if (!mount) - return; + if (!mount) return; mount_name = ConvertAndFree(g_mount_get_name(mount)); @@ -355,8 +342,8 @@ void GioLister::DeviceInfo::ReadMountInfo(GMount* mount) { mount_icon_names.clear(); GIcon* icon = g_mount_get_icon(mount); if (G_IS_THEMED_ICON(icon)) { - const char* const * icons = g_themed_icon_get_names(G_THEMED_ICON(icon)); - for (const char* const * p = icons ; *p ; ++p) { + const char* const* icons = g_themed_icon_get_names(G_THEMED_ICON(icon)); + for (const char* const* p = icons; *p; ++p) { mount_icon_names << QString::fromUtf8(*p); } } @@ -382,9 +369,10 @@ void GioLister::DeviceInfo::ReadMountInfo(GMount* mount) { // Query the filesystem info for size, free space, and type error = nullptr; - GFileInfo* info = g_file_query_filesystem_info(root, - G_FILE_ATTRIBUTE_FILESYSTEM_SIZE "," G_FILE_ATTRIBUTE_FILESYSTEM_FREE "," - G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, nullptr, &error); + GFileInfo* info = g_file_query_filesystem_info( + root, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE + "," G_FILE_ATTRIBUTE_FILESYSTEM_FREE "," G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, + nullptr, &error); if (error) { qLog(Warning) << error->message; g_error_free(error); @@ -419,13 +407,12 @@ void GioLister::DeviceInfo::ReadMountInfo(GMount* mount) { void GioLister::DeviceInfo::ReadVolumeInfo(GVolume* volume) { this->volume.reset_without_add(volume); - if (!volume) - return; + if (!volume) return; volume_name = ConvertAndFree(g_volume_get_name(volume)); volume_uuid = ConvertAndFree(g_volume_get_uuid(volume)); - volume_unix_device = ConvertAndFree(g_volume_get_identifier( - volume, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE)); + volume_unix_device = ConvertAndFree( + g_volume_get_identifier(volume, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE)); GFile* root = g_volume_get_activation_root(volume); if (root) { @@ -436,63 +423,60 @@ void GioLister::DeviceInfo::ReadVolumeInfo(GVolume* volume) { void GioLister::DeviceInfo::ReadDriveInfo(GDrive* drive) { this->drive.reset_without_add(drive); - if (!drive) - return; + if (!drive) return; drive_name = ConvertAndFree(g_drive_get_name(drive)); drive_removable = g_drive_is_media_removable(drive); } -QString GioLister::FindUniqueIdByMount(GMount *mount) const { - foreach (const DeviceInfo& info, devices_) { - if (info.mount == mount) - return info.unique_id(); +QString GioLister::FindUniqueIdByMount(GMount* mount) const { + foreach(const DeviceInfo & info, devices_) { + if (info.mount == mount) return info.unique_id(); } return QString(); } QString GioLister::FindUniqueIdByVolume(GVolume* volume) const { - foreach (const DeviceInfo& info, devices_) { - if (info.volume == volume) - return info.unique_id(); + foreach(const DeviceInfo & info, devices_) { + if (info.volume == volume) return info.unique_id(); } return QString(); } -void GioLister::VolumeEjectFinished(GObject *object, GAsyncResult *result, gpointer) { - OperationFinished(std::bind( - g_volume_eject_with_operation_finish, _1, _2, _3), object, result); +void GioLister::VolumeEjectFinished(GObject* object, GAsyncResult* result, + gpointer) { + OperationFinished( + std::bind(g_volume_eject_with_operation_finish, _1, _2, _3), object, + result); } -void GioLister::MountEjectFinished(GObject *object, GAsyncResult *result, gpointer) { - OperationFinished(std::bind( - g_mount_eject_with_operation_finish, _1, _2, _3), object, result); +void GioLister::MountEjectFinished(GObject* object, GAsyncResult* result, + gpointer) { + OperationFinished( + std::bind(g_mount_eject_with_operation_finish, _1, _2, _3), object, + result); } -void GioLister::MountUnmountFinished(GObject *object, GAsyncResult *result, gpointer) { - OperationFinished(std::bind( - g_mount_unmount_with_operation_finish, _1, _2, _3), object, result); +void GioLister::MountUnmountFinished(GObject* object, GAsyncResult* result, + gpointer) { + OperationFinished( + std::bind(g_mount_unmount_with_operation_finish, _1, _2, _3), object, + result); } -void GioLister::UnmountDevice(const QString &id) { +void GioLister::UnmountDevice(const QString& id) { QMutexLocker l(&mutex_); - if (!devices_.contains(id)) - return; + if (!devices_.contains(id)) return; const DeviceInfo& info = devices_[id]; - if (!info.mount) - return; + if (!info.mount) return; if (info.volume) { if (g_volume_can_eject(info.volume)) { g_volume_eject_with_operation( - info.volume, - G_MOUNT_UNMOUNT_NONE, - nullptr, - nullptr, - (GAsyncReadyCallback) VolumeEjectFinished, - nullptr); + info.volume, G_MOUNT_UNMOUNT_NONE, nullptr, nullptr, + (GAsyncReadyCallback)VolumeEjectFinished, nullptr); g_object_unref(info.volume); return; } @@ -500,28 +484,19 @@ void GioLister::UnmountDevice(const QString &id) { if (g_mount_can_eject(info.mount)) { g_mount_eject_with_operation( - info.mount, - G_MOUNT_UNMOUNT_NONE, - nullptr, - nullptr, - (GAsyncReadyCallback) MountEjectFinished, - nullptr); + info.mount, G_MOUNT_UNMOUNT_NONE, nullptr, nullptr, + (GAsyncReadyCallback)MountEjectFinished, nullptr); } else if (g_mount_can_unmount(info.mount)) { g_mount_unmount_with_operation( - info.mount, - G_MOUNT_UNMOUNT_NONE, - nullptr, - nullptr, - (GAsyncReadyCallback) MountUnmountFinished, - nullptr); + info.mount, G_MOUNT_UNMOUNT_NONE, nullptr, nullptr, + (GAsyncReadyCallback)MountUnmountFinished, nullptr); } } void GioLister::UpdateDeviceFreeSpace(const QString& id) { { QMutexLocker l(&mutex_); - if (!devices_.contains(id)) - return; + if (!devices_.contains(id)) return; DeviceInfo& device_info = devices_[id]; @@ -551,7 +526,7 @@ bool GioLister::DeviceNeedsMount(const QString& id) { } int GioLister::MountDevice(const QString& id) { - const int request_id = next_mount_request_id_ ++; + const int request_id = next_mount_request_id_++; metaObject()->invokeMethod(this, "DoMountDevice", Qt::QueuedConnection, Q_ARG(QString, id), Q_ARG(int, request_id)); return request_id; diff --git a/src/devices/giolister.h b/src/devices/giolister.h index 14b8e0855..eafa69dc6 100644 --- a/src/devices/giolister.h +++ b/src/devices/giolister.h @@ -23,7 +23,7 @@ // Work around compile issue with glib >= 2.25 #ifdef signals -# undef signals +#undef signals #endif #include @@ -34,7 +34,7 @@ class GioLister : public DeviceLister { Q_OBJECT -public: + public: GioLister() {} int priority() const { return 50; } @@ -48,22 +48,25 @@ public: QVariantMap DeviceHardwareInfo(const QString& id); bool DeviceNeedsMount(const QString& id); - QString MakeFriendlyName(const QString &id); - QList MakeDeviceUrls(const QString &id); + QString MakeFriendlyName(const QString& id); + QList MakeDeviceUrls(const QString& id); int MountDevice(const QString& id); - void UnmountDevice(const QString &id); + void UnmountDevice(const QString& id); -public slots: + public slots: void UpdateDeviceFreeSpace(const QString& id); -protected: + protected: void Init(); -private: + private: struct DeviceInfo { - DeviceInfo() : drive_removable(false), filesystem_size(0), - filesystem_free(0), invalid_enclosing_mount(false) {} + DeviceInfo() + : drive_removable(false), + filesystem_size(0), + filesystem_free(0), + invalid_enclosing_mount(false) {} QString unique_id() const; bool is_suitable() const; @@ -113,10 +116,14 @@ private: static void MountChangedCallback(GVolumeMonitor*, GMount*, gpointer); static void MountRemovedCallback(GVolumeMonitor*, GMount*, gpointer); - static void VolumeMountFinished(GObject* object, GAsyncResult* result, gpointer); - static void VolumeEjectFinished(GObject* object, GAsyncResult* result, gpointer); - static void MountEjectFinished(GObject* object, GAsyncResult* result, gpointer); - static void MountUnmountFinished(GObject* object, GAsyncResult* result, gpointer); + static void VolumeMountFinished(GObject* object, GAsyncResult* result, + gpointer); + static void VolumeEjectFinished(GObject* object, GAsyncResult* result, + gpointer); + static void MountEjectFinished(GObject* object, GAsyncResult* result, + gpointer); + static void MountUnmountFinished(GObject* object, GAsyncResult* result, + gpointer); // You MUST hold the mutex while calling this function QString FindUniqueIdByMount(GMount* mount) const; @@ -125,10 +132,10 @@ private: template T LockAndGetDeviceInfo(const QString& id, T DeviceInfo::*field); -private slots: + private slots: void DoMountDevice(const QString& id, int request_id); -private: + private: ScopedGObject monitor_; QMutex mutex_; @@ -138,10 +145,9 @@ private: template T GioLister::LockAndGetDeviceInfo(const QString& id, T DeviceInfo::*field) { QMutexLocker l(&mutex_); - if (!devices_.contains(id)) - return T(); + if (!devices_.contains(id)) return T(); return devices_[id].*field; } -#endif // GIOLISTER_H +#endif // GIOLISTER_H diff --git a/src/devices/gpoddevice.cpp b/src/devices/gpoddevice.cpp index 8460c5f41..2a0429243 100644 --- a/src/devices/gpoddevice.cpp +++ b/src/devices/gpoddevice.cpp @@ -30,17 +30,14 @@ #include -GPodDevice::GPodDevice( - const QUrl& url, DeviceLister* lister, - const QString& unique_id, DeviceManager* manager, - Application* app, - int database_id, bool first_time) - : ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time), - loader_thread_(new QThread(this)), - loader_(nullptr), - db_(nullptr) -{ -} +GPodDevice::GPodDevice(const QUrl& url, DeviceLister* lister, + const QString& unique_id, DeviceManager* manager, + Application* app, int database_id, bool first_time) + : ConnectedDevice(url, lister, unique_id, manager, app, database_id, + first_time), + loader_thread_(new QThread(this)), + loader_(nullptr), + db_(nullptr) {} void GPodDevice::Init() { InitBackendDirectory(url_.path(), first_time_); @@ -52,13 +49,13 @@ void GPodDevice::Init() { connect(loader_, SIGNAL(Error(QString)), SIGNAL(Error(QString))); connect(loader_, SIGNAL(TaskStarted(int)), SIGNAL(TaskStarted(int))); - connect(loader_, SIGNAL(LoadFinished(Itdb_iTunesDB*)), SLOT(LoadFinished(Itdb_iTunesDB*))); + connect(loader_, SIGNAL(LoadFinished(Itdb_iTunesDB*)), + SLOT(LoadFinished(Itdb_iTunesDB*))); connect(loader_thread_, SIGNAL(started()), loader_, SLOT(LoadDatabase())); loader_thread_->start(); } -GPodDevice::~GPodDevice() { -} +GPodDevice::~GPodDevice() {} void GPodDevice::LoadFinished(Itdb_iTunesDB* db) { QMutexLocker l(&db_mutex_); @@ -73,15 +70,13 @@ bool GPodDevice::StartCopy(QList* supported_filetypes) { { // Wait for the database to be loaded QMutexLocker l(&db_mutex_); - if (!db_) - db_wait_cond_.wait(&db_mutex_); + if (!db_) db_wait_cond_.wait(&db_mutex_); } // Ensure only one "organise files" can be active at any one time db_busy_.lock(); - if (supported_filetypes) - GetSupportedFiletypes(supported_filetypes); + if (supported_filetypes) GetSupportedFiletypes(supported_filetypes); return true; } @@ -114,8 +109,9 @@ bool GPodDevice::CopyToStorage(const CopyJob& job) { // Copy the file GError* error = nullptr; - itdb_cp_track_to_ipod(track, QDir::toNativeSeparators(job.source_) - .toLocal8Bit().constData(), &error); + itdb_cp_track_to_ipod( + track, QDir::toNativeSeparators(job.source_).toLocal8Bit().constData(), + &error); if (error) { qLog(Error) << "copying failed:" << error->message; app_->AddError(QString::fromUtf8(error->message)); @@ -149,10 +145,8 @@ void GPodDevice::WriteDatabase(bool success) { FinaliseDatabase(); // Update the library model - if (!songs_to_add_.isEmpty()) - backend_->AddOrUpdateSongs(songs_to_add_); - if (!songs_to_remove_.isEmpty()) - backend_->DeleteSongs(songs_to_remove_); + if (!songs_to_add_.isEmpty()) backend_->AddOrUpdateSongs(songs_to_add_); + if (!songs_to_remove_.isEmpty()) backend_->DeleteSongs(songs_to_remove_); } } @@ -166,20 +160,20 @@ void GPodDevice::FinishCopy(bool success) { ConnectedDevice::FinishCopy(success); } -void GPodDevice::StartDelete() { - StartCopy(nullptr); -} +void GPodDevice::StartDelete() { StartCopy(nullptr); } -bool GPodDevice::RemoveTrackFromITunesDb(const QString& path, const QString& relative_to) { +bool GPodDevice::RemoveTrackFromITunesDb(const QString& path, + const QString& relative_to) { QString ipod_filename = path; if (!relative_to.isEmpty() && path.startsWith(relative_to)) - ipod_filename.remove(0, relative_to.length() + (relative_to.endsWith('/') ? -1 : 0)); + ipod_filename.remove( + 0, relative_to.length() + (relative_to.endsWith('/') ? -1 : 0)); ipod_filename.replace('/', ':'); // Find the track in the itdb, identify it by its filename Itdb_Track* track = nullptr; - for (GList* tracks = db_->tracks ; tracks != nullptr ; tracks = tracks->next) { + for (GList* tracks = db_->tracks; tracks != nullptr; tracks = tracks->next) { Itdb_Track* t = static_cast(tracks->data); if (t->ipod_path == ipod_filename) { @@ -194,7 +188,8 @@ bool GPodDevice::RemoveTrackFromITunesDb(const QString& path, const QString& rel } // Remove the track from all playlists - for (GList* playlists = db_->playlists ; playlists != nullptr ; playlists = playlists->next) { + for (GList* playlists = db_->playlists; playlists != nullptr; + playlists = playlists->next) { Itdb_Playlist* playlist = static_cast(playlists->data); if (itdb_playlist_contains_track(playlist, track)) { @@ -215,8 +210,7 @@ bool GPodDevice::DeleteFromStorage(const DeleteJob& job) { return false; // Remove the file - if (!QFile::remove(job.metadata_.url().toLocalFile())) - return false; + if (!QFile::remove(job.metadata_.url().toLocalFile())) return false; // Remove it from our library model songs_to_remove_ << job.metadata_; diff --git a/src/devices/gpoddevice.h b/src/devices/gpoddevice.h index e163e0574..b40333053 100644 --- a/src/devices/gpoddevice.h +++ b/src/devices/gpoddevice.h @@ -31,12 +31,10 @@ class GPodLoader; 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, - int database_id, bool first_time); + public: + Q_INVOKABLE GPodDevice(const QUrl& url, DeviceLister* lister, + const QString& unique_id, DeviceManager* manager, + Application* app, int database_id, bool first_time); ~GPodDevice(); void Init(); @@ -53,20 +51,20 @@ public: bool DeleteFromStorage(const DeleteJob& job); void FinishDelete(bool success); -protected slots: + protected slots: void LoadFinished(Itdb_iTunesDB* db); -protected: + protected: Itdb_Track* AddTrackToITunesDb(const Song& metadata); void AddTrackToModel(Itdb_Track* track, const QString& prefix); bool RemoveTrackFromITunesDb(const QString& path, const QString& relative_to = QString()); virtual void FinaliseDatabase() {} -private: + private: void WriteDatabase(bool success); -protected: + protected: QThread* loader_thread_; GPodLoader* loader_; @@ -79,4 +77,4 @@ protected: SongList songs_to_remove_; }; -#endif // GPODDEVICE_H +#endif // GPODDEVICE_H diff --git a/src/devices/gpodloader.cpp b/src/devices/gpodloader.cpp index 742c24ac8..b57596fc0 100644 --- a/src/devices/gpodloader.cpp +++ b/src/devices/gpodloader.cpp @@ -27,21 +27,19 @@ #include #include -GPodLoader::GPodLoader( - const QString& mount_point, TaskManager* task_manager, - LibraryBackend* backend, std::shared_ptr device) - : QObject(nullptr), - device_(device), - mount_point_(mount_point), - type_(Song::Type_Unknown), - task_manager_(task_manager), - backend_(backend) -{ +GPodLoader::GPodLoader(const QString& mount_point, TaskManager* task_manager, + LibraryBackend* backend, + std::shared_ptr device) + : QObject(nullptr), + device_(device), + mount_point_(mount_point), + type_(Song::Type_Unknown), + task_manager_(task_manager), + backend_(backend) { original_thread_ = thread(); } -GPodLoader::~GPodLoader() { -} +GPodLoader::~GPodLoader() {} void GPodLoader::LoadDatabase() { int task_id = task_manager_->StartTask(tr("Loading iPod database")); @@ -49,8 +47,8 @@ void GPodLoader::LoadDatabase() { // Load the iTunes database GError* error = nullptr; - Itdb_iTunesDB* db = itdb_parse( - QDir::toNativeSeparators(mount_point_).toLocal8Bit(), &error); + Itdb_iTunesDB* db = + itdb_parse(QDir::toNativeSeparators(mount_point_).toLocal8Bit(), &error); // Check for errors if (!db) { @@ -68,18 +66,18 @@ void GPodLoader::LoadDatabase() { // Convert all the tracks from libgpod structs into Song classes const QString prefix = path_prefix_.isEmpty() - ? QDir::fromNativeSeparators(mount_point_) : path_prefix_; + ? QDir::fromNativeSeparators(mount_point_) + : path_prefix_; SongList songs; - for (GList* tracks = db->tracks ; tracks != nullptr ; tracks = tracks->next) { + for (GList* tracks = db->tracks; tracks != nullptr; tracks = tracks->next) { Itdb_Track* track = static_cast(tracks->data); Song song; song.InitFromItdb(track, prefix); song.set_directory_id(1); - if (type_ != Song::Type_Unknown) - song.set_filetype(type_); + if (type_ != Song::Type_Unknown) song.set_filetype(type_); songs << song; } diff --git a/src/devices/gpodloader.h b/src/devices/gpodloader.h index e3c2f74f6..3b8b273ba 100644 --- a/src/devices/gpodloader.h +++ b/src/devices/gpodloader.h @@ -33,7 +33,7 @@ class TaskManager; class GPodLoader : public QObject { Q_OBJECT -public: + public: GPodLoader(const QString& mount_point, TaskManager* task_manager, LibraryBackend* backend, std::shared_ptr device); ~GPodLoader(); @@ -41,7 +41,7 @@ public: void set_music_path_prefix(const QString& prefix) { path_prefix_ = prefix; } void set_song_type(Song::FileType type) { type_ = type; } -public slots: + public slots: void LoadDatabase(); signals: @@ -49,7 +49,7 @@ signals: void TaskStarted(int task_id); void LoadFinished(Itdb_iTunesDB* db); -private: + private: std::shared_ptr device_; QThread* original_thread_; @@ -60,4 +60,4 @@ private: LibraryBackend* backend_; }; -#endif // GPODLOADER_H +#endif // GPODLOADER_H diff --git a/src/devices/macdevicelister.h b/src/devices/macdevicelister.h index daf70af7c..8fdb7411e 100644 --- a/src/devices/macdevicelister.h +++ b/src/devices/macdevicelister.h @@ -28,7 +28,7 @@ class MacDeviceLister : public DeviceLister { virtual QString MakeFriendlyName(const QString& id); virtual QList MakeDeviceUrls(const QString& id); - virtual void UnmountDevice(const QString &id); + virtual void UnmountDevice(const QString& id); virtual void UpdateDeviceFreeSpace(const QString& id); struct MTPDevice { @@ -57,8 +57,8 @@ class MacDeviceLister : public DeviceLister { static void USBDeviceAddedCallback(void* refcon, io_iterator_t it); static void USBDeviceRemovedCallback(void* refcon, io_iterator_t it); - static void DiskUnmountCallback( - DADiskRef disk, DADissenterRef dissenter, void* context); + static void DiskUnmountCallback(DADiskRef disk, DADissenterRef dissenter, + void* context); void FoundMTPDevice(const MTPDevice& device, const QString& serial); void RemovedMTPDevice(const QString& serial); @@ -81,9 +81,9 @@ class MacDeviceLister : public DeviceLister { }; uint qHash(const MacDeviceLister::MTPDevice& device); -inline bool operator==(const MacDeviceLister::MTPDevice& a, const MacDeviceLister::MTPDevice& b) { - return (a.vendor_id == b.vendor_id) && - (a.product_id == b.product_id); +inline bool operator==(const MacDeviceLister::MTPDevice& a, + const MacDeviceLister::MTPDevice& b) { + return (a.vendor_id == b.vendor_id) && (a.product_id == b.product_id); } #endif diff --git a/src/devices/mtpconnection.cpp b/src/devices/mtpconnection.cpp index 2aba31c28..009aad5eb 100644 --- a/src/devices/mtpconnection.cpp +++ b/src/devices/mtpconnection.cpp @@ -21,9 +21,7 @@ #include #include -MtpConnection::MtpConnection(const QUrl& url) - : device_(nullptr) -{ +MtpConnection::MtpConnection(const QUrl& url) : device_(nullptr) { QString hostname = url.host(); // Parse the URL QRegExp host_re("^usb-(\\d+)-(\\d+)$"); @@ -37,12 +35,18 @@ MtpConnection::MtpConnection(const QUrl& url) const unsigned int device_num = host_re.cap(2).toInt(); if (url.hasQueryItem("vendor")) { - LIBMTP_raw_device_t* raw_device = (LIBMTP_raw_device_t*)malloc(sizeof(LIBMTP_raw_device_t)); - raw_device->device_entry.vendor = url.queryItemValue("vendor").toAscii().data(); - raw_device->device_entry.product = url.queryItemValue("product").toAscii().data(); - raw_device->device_entry.vendor_id = url.queryItemValue("vendor_id").toUShort(); - raw_device->device_entry.product_id = url.queryItemValue("product_id").toUShort(); - raw_device->device_entry.device_flags = url.queryItemValue("quirks").toUInt(); + LIBMTP_raw_device_t* raw_device = + (LIBMTP_raw_device_t*)malloc(sizeof(LIBMTP_raw_device_t)); + raw_device->device_entry.vendor = + url.queryItemValue("vendor").toAscii().data(); + raw_device->device_entry.product = + url.queryItemValue("product").toAscii().data(); + raw_device->device_entry.vendor_id = + url.queryItemValue("vendor_id").toUShort(); + raw_device->device_entry.product_id = + url.queryItemValue("product_id").toUShort(); + raw_device->device_entry.device_flags = + url.queryItemValue("quirks").toUInt(); raw_device->bus_location = bus_location; raw_device->devnum = device_num; @@ -61,7 +65,7 @@ MtpConnection::MtpConnection(const QUrl& url) } LIBMTP_raw_device_t* raw_device = nullptr; - for (int i=0 ; i class MtpConnection { -public: + public: MtpConnection(const QUrl& url); ~MtpConnection(); bool is_valid() const { return device_; } LIBMTP_mtpdevice_t* device() const { return device_; } -private: + private: Q_DISABLE_COPY(MtpConnection); LIBMTP_mtpdevice_t* device_; }; -#endif // MTPCONNECTION_H +#endif // MTPCONNECTION_H diff --git a/src/devices/mtpdevice.cpp b/src/devices/mtpdevice.cpp index a858d48c9..252289fa9 100644 --- a/src/devices/mtpdevice.cpp +++ b/src/devices/mtpdevice.cpp @@ -33,27 +33,25 @@ bool MtpDevice::sInitialisedLibMTP = false; MtpDevice::MtpDevice(const QUrl& url, DeviceLister* lister, const QString& unique_id, DeviceManager* manager, - Application* app, - int database_id, bool first_time) - : ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time), - loader_thread_(new QThread(this)), - loader_(nullptr) -{ + Application* app, int database_id, bool first_time) + : ConnectedDevice(url, lister, unique_id, manager, app, database_id, + first_time), + loader_thread_(new QThread(this)), + loader_(nullptr) { if (!sInitialisedLibMTP) { LIBMTP_Init(); sInitialisedLibMTP = true; } } -MtpDevice::~MtpDevice() { -} +MtpDevice::~MtpDevice() {} void MtpDevice::Init() { InitBackendDirectory("/", first_time_, false); model_->Init(); - loader_ = new MtpLoader(url_, app_->task_manager(), backend_, - shared_from_this()); + loader_ = + new MtpLoader(url_, app_->task_manager(), backend_, shared_from_this()); loader_->moveToThread(loader_thread_); connect(loader_, SIGNAL(Error(QString)), SIGNAL(Error(QString))); @@ -90,7 +88,7 @@ bool MtpDevice::StartCopy(QList* supported_types) { } static int ProgressCallback(uint64_t const sent, uint64_t const total, - void const* const data) { + void const* const data) { const MusicStorage::CopyJob* job = reinterpret_cast(data); job->progress_(float(sent) / total); @@ -99,19 +97,17 @@ static int ProgressCallback(uint64_t const sent, uint64_t const total, } bool MtpDevice::CopyToStorage(const CopyJob& job) { - if (!connection_->is_valid()) - return false; + if (!connection_->is_valid()) return false; // Convert metadata LIBMTP_track_t track; job.metadata_.ToMTP(&track); // Send the file - int ret = LIBMTP_Send_Track_From_File( - connection_->device(), job.source_.toUtf8().constData(), &track, - ProgressCallback, &job); - if (ret != 0) - return false; + int ret = LIBMTP_Send_Track_From_File(connection_->device(), + job.source_.toUtf8().constData(), + &track, ProgressCallback, &job); + if (ret != 0) return false; // Add it to our LibraryModel Song metadata_on_device; @@ -121,8 +117,7 @@ bool MtpDevice::CopyToStorage(const CopyJob& job) { // Remove the original if requested if (job.remove_original_) { - if (!QFile::remove(job.source_)) - return false; + if (!QFile::remove(job.source_)) return false; } return true; @@ -130,10 +125,8 @@ bool MtpDevice::CopyToStorage(const CopyJob& job) { void MtpDevice::FinishCopy(bool success) { if (success) { - if (!songs_to_add_.isEmpty()) - backend_->AddOrUpdateSongs(songs_to_add_); - if (!songs_to_remove_.isEmpty()) - backend_->DeleteSongs(songs_to_remove_); + if (!songs_to_add_.isEmpty()) backend_->AddOrUpdateSongs(songs_to_add_); + if (!songs_to_remove_.isEmpty()) backend_->DeleteSongs(songs_to_remove_); } songs_to_add_.clear(); @@ -146,9 +139,7 @@ void MtpDevice::FinishCopy(bool success) { ConnectedDevice::FinishCopy(success); } -void MtpDevice::StartDelete() { - StartCopy(nullptr); -} +void MtpDevice::StartDelete() { StartCopy(nullptr); } bool MtpDevice::DeleteFromStorage(const DeleteJob& job) { // Extract the ID from the song's URL @@ -157,13 +148,11 @@ bool MtpDevice::DeleteFromStorage(const DeleteJob& job) { bool ok = false; uint32_t id = filename.toUInt(&ok); - if (!ok) - return false; + if (!ok) return false; // Remove the file int ret = LIBMTP_Delete_Object(connection_->device(), id); - if (ret != 0) - return false; + if (ret != 0) return false; // Remove it from our library model songs_to_remove_ << job.metadata_; @@ -171,38 +160,46 @@ bool MtpDevice::DeleteFromStorage(const DeleteJob& job) { return true; } -void MtpDevice::FinishDelete(bool success) { - FinishCopy(success); -} +void MtpDevice::FinishDelete(bool success) { FinishCopy(success); } bool MtpDevice::GetSupportedFiletypes(QList* ret) { QMutexLocker l(&db_busy_); MtpConnection connection(url_); if (!connection.is_valid()) { - qLog(Warning) << "Error connecting to MTP device, couldn't get list of supported filetypes"; + qLog(Warning) << "Error connecting to MTP device, couldn't get list of " + "supported filetypes"; return false; } return GetSupportedFiletypes(ret, connection.device()); } -bool MtpDevice::GetSupportedFiletypes(QList* ret, LIBMTP_mtpdevice_t* device) { +bool MtpDevice::GetSupportedFiletypes(QList* ret, + LIBMTP_mtpdevice_t* device) { uint16_t* list = nullptr; uint16_t length = 0; - if (LIBMTP_Get_Supported_Filetypes(device, &list, &length) - || !list || !length) + if (LIBMTP_Get_Supported_Filetypes(device, &list, &length) || !list || + !length) return false; - for (int i=0 ; i* ret, LIBMTP_mtpdevi *ret << Song::Type_OggFlac; break; default: - qLog(Error) << "Unknown MTP file format" << - LIBMTP_Get_Filetype_Description(LIBMTP_filetype_t(list[i])); + qLog(Error) << "Unknown MTP file format" + << LIBMTP_Get_Filetype_Description( + LIBMTP_filetype_t(list[i])); break; } } diff --git a/src/devices/mtpdevice.h b/src/devices/mtpdevice.h index 7317ea5e6..c3577cfc4 100644 --- a/src/devices/mtpdevice.h +++ b/src/devices/mtpdevice.h @@ -33,14 +33,16 @@ class MtpLoader; class MtpDevice : public ConnectedDevice { Q_OBJECT -public: + public: Q_INVOKABLE MtpDevice(const QUrl& url, DeviceLister* lister, const QString& unique_id, DeviceManager* manager, - Application* app, - int database_id, bool first_time); + Application* app, int database_id, bool first_time); ~MtpDevice(); - static QStringList url_schemes() { return QStringList() << "mtp" << "gphoto2"; } + static QStringList url_schemes() { + return QStringList() << "mtp" + << "gphoto2"; + } void Init(); @@ -56,15 +58,16 @@ public: bool DeleteFromStorage(const DeleteJob& job); void FinishDelete(bool success); -private slots: + private slots: void LoadFinished(); -private: - bool GetSupportedFiletypes(QList* ret, LIBMTP_mtpdevice_struct* device); + private: + bool GetSupportedFiletypes(QList* ret, + LIBMTP_mtpdevice_struct* device); int GetFreeSpace(LIBMTP_mtpdevice_struct* device); int GetCapacity(LIBMTP_mtpdevice_struct* device); -private: + private: static bool sInitialisedLibMTP; QThread* loader_thread_; @@ -77,4 +80,4 @@ private: std::unique_ptr connection_; }; -#endif // MTPDEVICE_H +#endif // MTPDEVICE_H diff --git a/src/devices/mtploader.cpp b/src/devices/mtploader.cpp index 99cfcc2c9..61247b0fe 100644 --- a/src/devices/mtploader.cpp +++ b/src/devices/mtploader.cpp @@ -25,20 +25,18 @@ #include "core/taskmanager.h" #include "library/librarybackend.h" -MtpLoader::MtpLoader( - const QUrl& url, TaskManager* task_manager, - LibraryBackend* backend, std::shared_ptr device) - : QObject(nullptr), - device_(device), - url_(url), - task_manager_(task_manager), - backend_(backend) -{ +MtpLoader::MtpLoader(const QUrl& url, TaskManager* task_manager, + LibraryBackend* backend, + std::shared_ptr device) + : QObject(nullptr), + device_(device), + url_(url), + task_manager_(task_manager), + backend_(backend) { original_thread_ = thread(); } -MtpLoader::~MtpLoader() { -} +MtpLoader::~MtpLoader() {} void MtpLoader::LoadDatabase() { int task_id = task_manager_->StartTask(tr("Loading MTP device")); @@ -61,8 +59,8 @@ bool MtpLoader::TryLoad() { // Load the list of songs on the device SongList songs; - LIBMTP_track_t* tracks = LIBMTP_Get_Tracklisting_With_Callback( - dev.device(), nullptr, nullptr); + LIBMTP_track_t* tracks = + LIBMTP_Get_Tracklisting_With_Callback(dev.device(), nullptr, nullptr); while (tracks) { LIBMTP_track_t* track = tracks; diff --git a/src/devices/mtploader.h b/src/devices/mtploader.h index 357597d41..a723aee0f 100644 --- a/src/devices/mtploader.h +++ b/src/devices/mtploader.h @@ -30,12 +30,12 @@ class TaskManager; class MtpLoader : public QObject { Q_OBJECT -public: - MtpLoader(const QUrl& url, TaskManager* task_manager, - LibraryBackend* backend, std::shared_ptr device); + public: + MtpLoader(const QUrl& url, TaskManager* task_manager, LibraryBackend* backend, + std::shared_ptr device); ~MtpLoader(); -public slots: + public slots: void LoadDatabase(); signals: @@ -43,10 +43,10 @@ signals: void TaskStarted(int task_id); void LoadFinished(); -private: + private: bool TryLoad(); -private: + private: std::shared_ptr device_; QThread* original_thread_; @@ -55,4 +55,4 @@ private: LibraryBackend* backend_; }; -#endif // MTPLOADER_H +#endif // MTPLOADER_H diff --git a/src/engines/bufferconsumer.h b/src/engines/bufferconsumer.h index c005b4414..349b98821 100644 --- a/src/engines/bufferconsumer.h +++ b/src/engines/bufferconsumer.h @@ -23,7 +23,7 @@ class GstEnginePipeline; class BufferConsumer { -public: + public: virtual ~BufferConsumer() {} // This is called in some unspecified GStreamer thread. @@ -32,4 +32,4 @@ public: virtual void ConsumeBuffer(GstBuffer* buffer, int pipeline_id) = 0; }; -#endif // BUFFERCONSUMER_H +#endif // BUFFERCONSUMER_H diff --git a/src/engines/engine_fwd.h b/src/engines/engine_fwd.h index 5c70ff613..31377e618 100644 --- a/src/engines/engine_fwd.h +++ b/src/engines/engine_fwd.h @@ -3,35 +3,35 @@ #include -/// Used by eg engineobserver.h, and thus we reduce header dependencies on enginebase.h +/// Used by eg engineobserver.h, and thus we reduce header dependencies on +/// enginebase.h -namespace Engine -{ - struct SimpleMetaBundle; - class Base; +namespace Engine { +struct SimpleMetaBundle; +class Base; - /** - * You should return: - * Playing when playing, - * Paused when paused - * Idle when you still have a URL loaded (ie you have not been told to stop()) - * Empty when you have been told to stop(), - * Error when an error occurred and you stopped yourself - * - * It is vital to be Idle just after the track has ended! - */ - enum State { Empty, Idle, Playing, Paused, Error }; +/** + * You should return: + * Playing when playing, + * Paused when paused + * Idle when you still have a URL loaded (ie you have not been told to stop()) + * Empty when you have been told to stop(), + * Error when an error occurred and you stopped yourself + * + * It is vital to be Idle just after the track has ended! + */ +enum State { Empty, Idle, Playing, Paused, Error }; - enum TrackChangeType { - // One of: - First = 0x01, - Manual = 0x02, - Auto = 0x04, +enum TrackChangeType { + // One of: + First = 0x01, + Manual = 0x02, + Auto = 0x04, - // Any of: - SameAlbum = 0x10, - }; - Q_DECLARE_FLAGS(TrackChangeFlags, TrackChangeType); + // Any of: + SameAlbum = 0x10, +}; +Q_DECLARE_FLAGS(TrackChangeFlags, TrackChangeType); } typedef Engine::Base EngineBase; diff --git a/src/engines/enginebase.cpp b/src/engines/enginebase.cpp index 8f3b74ab5..a6b6da15c 100644 --- a/src/engines/enginebase.cpp +++ b/src/engines/enginebase.cpp @@ -15,9 +15,9 @@ along with Clementine. If not, see . */ -//Copyright: (C) 2003 Mark Kretschmann +// Copyright: (C) 2003 Mark Kretschmann // (C) 2004,2005 Max Howell, -//License: See COPYING +// License: See COPYING #include "enginebase.h" #include "core/timeconstants.h" @@ -29,26 +29,23 @@ const char* Engine::Base::kSettingsGroup = "Player"; Engine::Base::Base() - : volume_(50), - beginning_nanosec_(0), - end_nanosec_(0), - scope_(kScopeSize), - fadeout_enabled_(true), - fadeout_duration_nanosec_(2 * kNsecPerSec), // 2s - crossfade_enabled_(true), - autocrossfade_enabled_(false), - crossfade_same_album_(false), - next_background_stream_id_(0), - about_to_end_emitted_(false) -{ -} + : volume_(50), + beginning_nanosec_(0), + end_nanosec_(0), + scope_(kScopeSize), + fadeout_enabled_(true), + fadeout_duration_nanosec_(2 * kNsecPerSec), // 2s + crossfade_enabled_(true), + autocrossfade_enabled_(false), + crossfade_same_album_(false), + next_background_stream_id_(0), + about_to_end_emitted_(false) {} -Engine::Base::~Base() { -} +Engine::Base::~Base() {} bool Engine::Base::Load(const QUrl& url, TrackChangeFlags, - bool force_stop_at_end, - quint64 beginning_nanosec, qint64 end_nanosec) { + bool force_stop_at_end, quint64 beginning_nanosec, + qint64 end_nanosec) { Q_UNUSED(force_stop_at_end); url_ = url; @@ -67,7 +64,8 @@ void Engine::Base::SetVolume(uint value) { uint Engine::Base::MakeVolumeLogarithmic(uint volume) { // We're using a logarithmic function to make the volume ramp more natural. - return static_cast( 100 - 100.0 * std::log10( ( 100 - volume ) * 0.09 + 1.0 ) ); + return static_cast(100 - + 100.0 * std::log10((100 - volume) * 0.09 + 1.0)); } void Engine::Base::ReloadSettings() { @@ -75,29 +73,28 @@ void Engine::Base::ReloadSettings() { s.beginGroup(kSettingsGroup); fadeout_enabled_ = s.value("FadeoutEnabled", true).toBool(); - fadeout_duration_nanosec_ = s.value("FadeoutDuration", 2000).toLongLong() * kNsecPerMsec; + fadeout_duration_nanosec_ = + s.value("FadeoutDuration", 2000).toLongLong() * kNsecPerMsec; crossfade_enabled_ = s.value("CrossfadeEnabled", true).toBool(); autocrossfade_enabled_ = s.value("AutoCrossfadeEnabled", false).toBool(); crossfade_same_album_ = !s.value("NoCrossfadeSameAlbum", true).toBool(); fadeout_pause_enabled_ = s.value("FadeoutPauseEnabled", false).toBool(); - fadeout_pause_duration_nanosec_ = s.value("FadeoutPauseDuration", 250).toLongLong() * kNsecPerMsec; + fadeout_pause_duration_nanosec_ = + s.value("FadeoutPauseDuration", 250).toLongLong() * kNsecPerMsec; } void Engine::Base::EmitAboutToEnd() { - if (about_to_end_emitted_) - return; + if (about_to_end_emitted_) return; about_to_end_emitted_ = true; emit TrackAboutToEnd(); } -int Engine::Base::AddBackgroundStream(const QUrl& url) { - return -1; -} +int Engine::Base::AddBackgroundStream(const QUrl& url) { return -1; } bool Engine::Base::Play(const QUrl& u, TrackChangeFlags c, - bool force_stop_at_end, - quint64 beginning_nanosec, qint64 end_nanosec) { + bool force_stop_at_end, quint64 beginning_nanosec, + qint64 end_nanosec) { if (!Load(u, c, force_stop_at_end, beginning_nanosec, end_nanosec)) return false; diff --git a/src/engines/enginebase.h b/src/engines/enginebase.h index d998639e1..29c199f73 100644 --- a/src/engines/enginebase.h +++ b/src/engines/enginebase.h @@ -15,9 +15,9 @@ along with Clementine. If not, see . */ -//Copyright: (C) 2003 Mark Kretschmann +// Copyright: (C) 2003 Mark Kretschmann // (C) 2004 Max Howell, -//License: See COPYING +// License: See COPYING #ifndef AMAROK_ENGINEBASE_H #define AMAROK_ENGINEBASE_H @@ -63,8 +63,8 @@ class Base : public QObject { // Subclasses should respect given markers (beginning and end) which are // in miliseconds. virtual bool Load(const QUrl& url, TrackChangeFlags change, - bool force_stop_at_end, - quint64 beginning_nanosec, qint64 end_nanosec); + bool force_stop_at_end, quint64 beginning_nanosec, + qint64 end_nanosec); // Sets new values for the beginning and end markers of the currently playing // song. // This doesn't change the state of engine or the stream's current position. @@ -73,19 +73,19 @@ class Base : public QObject { end_nanosec_ = end_nanosec; } - // Plays a media stream represented with the URL 'u' from the given 'beginning' + // Plays a media stream represented with the URL 'u' from the given + // 'beginning' // to the given 'end' (usually from 0 to a song's length). Both markers // should be passed in nanoseconds. 'end' can be negative, indicating that the // real length of 'u' stream is unknown. - bool Play(const QUrl& u, TrackChangeFlags c, - bool force_stop_at_end, + bool Play(const QUrl& u, TrackChangeFlags c, bool force_stop_at_end, quint64 beginning_nanosec, qint64 end_nanosec); void SetVolume(uint value); // Simple accessors inline uint volume() const { return volume_; } - virtual const Scope &scope() { return scope_; } + virtual const Scope& scope() { return scope_; } bool is_fadeout_enabled() const { return fadeout_enabled_; } bool is_crossfade_enabled() const { return crossfade_enabled_; } bool is_autocrossfade_enabled() const { return autocrossfade_enabled_; } @@ -98,10 +98,11 @@ class Base : public QObject { virtual void ReloadSettings(); virtual void SetEqualizerEnabled(bool) {} - virtual void SetEqualizerParameters(int preamp, const QList& bandGains) {} + virtual void SetEqualizerParameters(int preamp, const QList& bandGains) { + } virtual void SetStereoBalance(float value) {} - signals: +signals: // Emitted when crossfading is enabled and the track is crossfade_duration_ // away from finishing void TrackAboutToEnd(); @@ -115,13 +116,14 @@ class Base : public QObject { // Emitted when Engine was unable to play a song with the given QUrl. void InvalidSongRequested(const QUrl&); - // Emitted when Engine successfully started playing a song with the + // Emitted when Engine successfully started playing a song with the // given QUrl. void ValidSongRequested(const QUrl&); void MetaData(const Engine::SimpleMetaBundle&); - // Signals that the engine's state has changed (a stream was stopped for example). + // Signals that the engine's state has changed (a stream was stopped for + // example). // Always use the state from event, because it's not guaranteed that immediate // subsequent call to state() won't return a stale value. void StateChanged(Engine::State); @@ -129,8 +131,8 @@ class Base : public QObject { protected: Base(); - virtual void SetVolumeSW( uint percent ) = 0; - static uint MakeVolumeLogarithmic( uint volume ); + virtual void SetVolumeSW(uint percent) = 0; + static uint MakeVolumeLogarithmic(uint volume); void EmitAboutToEnd(); protected: @@ -154,7 +156,6 @@ class Base : public QObject { Q_DISABLE_COPY(Base); }; - struct SimpleMetaBundle { QString title; QString artist; @@ -168,6 +169,6 @@ struct SimpleMetaBundle { QString tracknr; }; -} // namespace +} // namespace #endif diff --git a/src/engines/gstelementdeleter.cpp b/src/engines/gstelementdeleter.cpp index 6598931da..84dd516db 100644 --- a/src/engines/gstelementdeleter.cpp +++ b/src/engines/gstelementdeleter.cpp @@ -19,10 +19,7 @@ #include -GstElementDeleter::GstElementDeleter(QObject* parent) - : QObject(parent) -{ -} +GstElementDeleter::GstElementDeleter(QObject* parent) : QObject(parent) {} void GstElementDeleter::DeleteElementLater(GstElement* element) { metaObject()->invokeMethod(this, "DeleteElement", Qt::QueuedConnection, diff --git a/src/engines/gstelementdeleter.h b/src/engines/gstelementdeleter.h index 28e313db1..4b08262e0 100644 --- a/src/engines/gstelementdeleter.h +++ b/src/engines/gstelementdeleter.h @@ -25,7 +25,7 @@ class GstElementDeleter : public QObject { Q_OBJECT -public: + public: GstElementDeleter(QObject* parent = 0); // If you call this function with any gstreamer element, the element will get @@ -36,8 +36,8 @@ public: // deleted later regardless. void DeleteElementLater(GstElement* element); -private slots: + private slots: void DeleteElement(GstElement* element); }; -#endif // GSTBINDELETER_H +#endif // GSTBINDELETER_H diff --git a/src/engines/gstengine.cpp b/src/engines/gstengine.cpp index 36e2728ee..4b6d40113 100644 --- a/src/engines/gstengine.cpp +++ b/src/engines/gstengine.cpp @@ -46,7 +46,7 @@ #include "core/utilities.h" #ifdef HAVE_MOODBAR -# include "gst/moodbar/spectrum.h" +#include "gst/moodbar/spectrum.h" #endif using std::shared_ptr; @@ -55,35 +55,34 @@ using std::vector; const char* GstEngine::kSettingsGroup = "GstEngine"; const char* GstEngine::kAutoSink = "autoaudiosink"; const char* GstEngine::kHypnotoadPipeline = - "audiotestsrc wave=6 ! " - "audioecho intensity=1 delay=50000000 ! " - "audioecho intensity=1 delay=25000000 ! " - "equalizer-10bands " - "band0=-24 band1=-3 band2=7.5 band3=12 band4=8 " - "band5=6 band6=5 band7=6 band8=0 band9=-24"; + "audiotestsrc wave=6 ! " + "audioecho intensity=1 delay=50000000 ! " + "audioecho intensity=1 delay=25000000 ! " + "equalizer-10bands " + "band0=-24 band1=-3 band2=7.5 band3=12 band4=8 " + "band5=6 band6=5 band7=6 band8=0 band9=-24"; const char* GstEngine::kEnterprisePipeline = - "audiotestsrc wave=5 ! " - "audiocheblimit mode=0 cutoff=120"; + "audiotestsrc wave=5 ! " + "audiocheblimit mode=0 cutoff=120"; GstEngine::GstEngine(TaskManager* task_manager) - : Engine::Base(), - task_manager_(task_manager), - buffering_task_id_(-1), - latest_buffer_(nullptr), - equalizer_enabled_(false), - stereo_balance_(0.0f), - rg_enabled_(false), - rg_mode_(0), - rg_preamp_(0.0), - rg_compression_(true), - buffer_duration_nanosec_(1 * kNsecPerSec), // 1s - mono_playback_(false), - seek_timer_(new QTimer(this)), - timer_id_(-1), - next_element_id_(0), - is_fading_out_to_pause_(false), - has_faded_out_(false) -{ + : Engine::Base(), + task_manager_(task_manager), + buffering_task_id_(-1), + latest_buffer_(nullptr), + equalizer_enabled_(false), + stereo_balance_(0.0f), + rg_enabled_(false), + rg_mode_(0), + rg_preamp_(0.0), + rg_compression_(true), + buffer_duration_nanosec_(1 * kNsecPerSec), // 1s + mono_playback_(false), + seek_timer_(new QTimer(this)), + timer_id_(-1), + next_element_id_(0), + is_fading_out_to_pause_(false), + has_faded_out_(false) { seek_timer_->setSingleShot(true); seek_timer_->setInterval(kSeekDelayNanosec / kNsecPerMsec); connect(seek_timer_, SIGNAL(timeout()), SLOT(SeekNow())); @@ -122,46 +121,47 @@ void GstEngine::ReloadSettings() { sink_ = s.value("sink", kAutoSink).toString(); device_ = s.value("device").toString(); - if (sink_.isEmpty()) - sink_ = kAutoSink; + if (sink_.isEmpty()) sink_ = kAutoSink; rg_enabled_ = s.value("rgenabled", false).toBool(); rg_mode_ = s.value("rgmode", 0).toInt(); rg_preamp_ = s.value("rgpreamp", 0.0).toDouble(); rg_compression_ = s.value("rgcompression", true).toBool(); - buffer_duration_nanosec_ = s.value("bufferduration", 4000).toLongLong() * kNsecPerMsec; + buffer_duration_nanosec_ = + s.value("bufferduration", 4000).toLongLong() * kNsecPerMsec; mono_playback_ = s.value("monoplayback", false).toBool(); } - qint64 GstEngine::position_nanosec() const { - if (!current_pipeline_) - return 0; + if (!current_pipeline_) return 0; qint64 result = current_pipeline_->position() - beginning_nanosec_; return qint64(qMax(0ll, result)); } qint64 GstEngine::length_nanosec() const { - if (!current_pipeline_) - return 0; + if (!current_pipeline_) return 0; qint64 result = end_nanosec_ - beginning_nanosec_; return qint64(qMax(0ll, result)); } Engine::State GstEngine::state() const { - if (!current_pipeline_) - return url_.isEmpty() ? Engine::Empty : Engine::Idle; + if (!current_pipeline_) return url_.isEmpty() ? Engine::Empty : Engine::Idle; switch (current_pipeline_->state()) { - case GST_STATE_NULL: return Engine::Empty; - case GST_STATE_READY: return Engine::Idle; - case GST_STATE_PLAYING: return Engine::Playing; - case GST_STATE_PAUSED: return Engine::Paused; - default: return Engine::Empty; + case GST_STATE_NULL: + return Engine::Empty; + case GST_STATE_READY: + return Engine::Idle; + case GST_STATE_PLAYING: + return Engine::Playing; + case GST_STATE_PAUSED: + return Engine::Paused; + default: + return Engine::Empty; } } @@ -199,21 +199,20 @@ void GstEngine::UpdateScope() { typedef Engine::Scope::value_type sample_type; // determine the number of channels - GstStructure* structure = gst_caps_get_structure( - GST_BUFFER_CAPS(latest_buffer_), 0); + GstStructure* structure = + gst_caps_get_structure(GST_BUFFER_CAPS(latest_buffer_), 0); int channels = 2; gst_structure_get_int(structure, "channels", &channels); // scope does not support >2 channels - if (channels > 2) - return; + if (channels > 2) return; - const sample_type* source = reinterpret_cast( - GST_BUFFER_DATA(latest_buffer_)); + const sample_type* source = + reinterpret_cast(GST_BUFFER_DATA(latest_buffer_)); sample_type* dest = scope_.data(); const int bytes = qMin( - static_cast(GST_BUFFER_SIZE(latest_buffer_)), - scope_.size() * sizeof(sample_type)); + static_cast(GST_BUFFER_SIZE(latest_buffer_)), + scope_.size() * sizeof(sample_type)); memcpy(dest, source, bytes); @@ -231,7 +230,7 @@ void GstEngine::StartPreloading(const QUrl& url, bool force_stop_at_end, // pipeline and get gapless playback (hopefully) if (current_pipeline_) current_pipeline_->SetNextUrl(gst_url, beginning_nanosec, - force_stop_at_end ? end_nanosec : 0); + force_stop_at_end ? end_nanosec : 0); } QUrl GstEngine::FixupUrl(const QUrl& url) { @@ -249,19 +248,21 @@ QUrl GstEngine::FixupUrl(const QUrl& url) { } bool GstEngine::Load(const QUrl& url, Engine::TrackChangeFlags change, - bool force_stop_at_end, - quint64 beginning_nanosec, qint64 end_nanosec) { + bool force_stop_at_end, quint64 beginning_nanosec, + qint64 end_nanosec) { EnsureInitialised(); - Engine::Base::Load(url, change, force_stop_at_end, beginning_nanosec, end_nanosec); + Engine::Base::Load(url, change, force_stop_at_end, beginning_nanosec, + end_nanosec); QUrl gst_url = FixupUrl(url); - bool crossfade = current_pipeline_ && - ((crossfade_enabled_ && change & Engine::Manual) || - (autocrossfade_enabled_ && change & Engine::Auto)); + bool crossfade = + current_pipeline_ && ((crossfade_enabled_ && change & Engine::Manual) || + (autocrossfade_enabled_ && change & Engine::Auto)); - if (change & Engine::Auto && change & Engine::SameAlbum && !crossfade_same_album_) + if (change & Engine::Auto && change & Engine::SameAlbum && + !crossfade_same_album_) crossfade = false; if (!crossfade && current_pipeline_ && current_pipeline_->url() == gst_url && @@ -271,13 +272,11 @@ bool GstEngine::Load(const QUrl& url, Engine::TrackChangeFlags change, return true; } - shared_ptr pipeline = CreatePipeline(gst_url, - force_stop_at_end ? end_nanosec : 0); - if (!pipeline) - return false; + shared_ptr pipeline = + CreatePipeline(gst_url, force_stop_at_end ? end_nanosec : 0); + if (!pipeline) return false; - if (crossfade) - StartFadeout(); + if (crossfade) StartFadeout(); BufferingFinished(); current_pipeline_ = pipeline; @@ -289,21 +288,22 @@ bool GstEngine::Load(const QUrl& url, Engine::TrackChangeFlags change, // Maybe fade in this track if (crossfade) - current_pipeline_->StartFader(fadeout_duration_nanosec_, QTimeLine::Forward); + current_pipeline_->StartFader(fadeout_duration_nanosec_, + QTimeLine::Forward); return true; } void GstEngine::StartFadeout() { - if (is_fading_out_to_pause_) - return; + if (is_fading_out_to_pause_) return; fadeout_pipeline_ = current_pipeline_; disconnect(fadeout_pipeline_.get(), 0, 0, 0); fadeout_pipeline_->RemoveAllBufferConsumers(); fadeout_pipeline_->StartFader(fadeout_duration_nanosec_, QTimeLine::Backward); - connect(fadeout_pipeline_.get(), SIGNAL(FaderFinished()), SLOT(FadeoutFinished())); + connect(fadeout_pipeline_.get(), SIGNAL(FaderFinished()), + SLOT(FadeoutFinished())); } void GstEngine::StartFadeoutPause() { @@ -312,27 +312,26 @@ void GstEngine::StartFadeoutPause() { fadeout_pause_pipeline_->StartFader(fadeout_pause_duration_nanosec_, QTimeLine::Backward, - QTimeLine::EaseInOutCurve, - false); + QTimeLine::EaseInOutCurve, false); if (fadeout_pipeline_ && fadeout_pipeline_->state() == GST_STATE_PLAYING) { fadeout_pipeline_->StartFader(fadeout_pause_duration_nanosec_, - QTimeLine::Backward, - QTimeLine::LinearCurve, + QTimeLine::Backward, QTimeLine::LinearCurve, false); } - connect(fadeout_pause_pipeline_.get(), SIGNAL(FaderFinished()), SLOT(FadeoutPauseFinished())); + connect(fadeout_pause_pipeline_.get(), SIGNAL(FaderFinished()), + SLOT(FadeoutPauseFinished())); is_fading_out_to_pause_ = true; } bool GstEngine::Play(quint64 offset_nanosec) { EnsureInitialised(); - if (!current_pipeline_ || current_pipeline_->is_buffering()) - return false; + if (!current_pipeline_ || current_pipeline_->is_buffering()) return false; - QFuture future = current_pipeline_->SetState(GST_STATE_PLAYING); + QFuture future = + current_pipeline_->SetState(GST_STATE_PLAYING); PlayFutureWatcher* watcher = new PlayFutureWatcher( - PlayFutureWatcherArg(offset_nanosec, current_pipeline_->id()), this); + PlayFutureWatcherArg(offset_nanosec, current_pipeline_->id()), this); watcher->setFuture(future); connect(watcher, SIGNAL(finished()), SLOT(PlayDone())); @@ -374,7 +373,7 @@ void GstEngine::PlayDone() { StartTimers(); // initial offset - if(offset_nanosec != 0 || beginning_nanosec_ != 0) { + if (offset_nanosec != 0 || beginning_nanosec_ != 0) { Seek(offset_nanosec); } @@ -383,15 +382,13 @@ void GstEngine::PlayDone() { emit ValidSongRequested(url_); } - void GstEngine::Stop() { StopTimers(); - url_ = QUrl(); // To ensure we return Empty from state() + url_ = QUrl(); // To ensure we return Empty from state() beginning_nanosec_ = end_nanosec_ = 0; - if (fadeout_enabled_ && current_pipeline_) - StartFadeout(); + if (fadeout_enabled_ && current_pipeline_) StartFadeout(); current_pipeline_.reset(); BufferingFinished(); @@ -418,16 +415,14 @@ void GstEngine::FadeoutPauseFinished() { } void GstEngine::Pause() { - if (!current_pipeline_ || current_pipeline_->is_buffering()) - return; + if (!current_pipeline_ || current_pipeline_->is_buffering()) return; // 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_) { disconnect(current_pipeline_.get(), SIGNAL(FaderFinished()), 0, 0); current_pipeline_->StartFader(fadeout_pause_duration_nanosec_, - QTimeLine::Forward, - QTimeLine::EaseInOutCurve, + QTimeLine::Forward, QTimeLine::EaseInOutCurve, false); is_fading_out_to_pause_ = false; has_faded_out_ = false; @@ -435,7 +430,7 @@ void GstEngine::Pause() { return; } - if ( current_pipeline_->state() == GST_STATE_PLAYING ) { + if (current_pipeline_->state() == GST_STATE_PLAYING) { if (fadeout_pause_enabled_) { StartFadeoutPause(); } else { @@ -447,10 +442,9 @@ void GstEngine::Pause() { } void GstEngine::Unpause() { - if (!current_pipeline_ || current_pipeline_->is_buffering()) - return; + if (!current_pipeline_ || current_pipeline_->is_buffering()) return; - if ( current_pipeline_->state() == GST_STATE_PAUSED ) { + if (current_pipeline_->state() == GST_STATE_PAUSED) { current_pipeline_->SetState(GST_STATE_PLAYING); // Check if we faded out last time. If yes, fade in no matter what the @@ -459,9 +453,8 @@ void GstEngine::Unpause() { if (has_faded_out_) { disconnect(current_pipeline_.get(), SIGNAL(FaderFinished()), 0, 0); current_pipeline_->StartFader(fadeout_pause_duration_nanosec_, - QTimeLine::Forward, - QTimeLine::EaseInOutCurve, - false); + QTimeLine::Forward, + QTimeLine::EaseInOutCurve, false); has_faded_out_ = false; } @@ -472,15 +465,14 @@ void GstEngine::Unpause() { } void GstEngine::Seek(quint64 offset_nanosec) { - if (!current_pipeline_) - return; + if (!current_pipeline_) return; seek_pos_ = beginning_nanosec_ + offset_nanosec; waiting_to_seek_ = true; if (!seek_timer_->isActive()) { SeekNow(); - seek_timer_->start(); // Stop us from seeking again for a little while + seek_timer_->start(); // Stop us from seeking again for a little while } } @@ -488,8 +480,7 @@ void GstEngine::SeekNow() { if (!waiting_to_seek_) return; waiting_to_seek_ = false; - if (!current_pipeline_) - return; + if (!current_pipeline_) return; if (!current_pipeline_->Seek(seek_pos_)) { qLog(Warning) << "Seek failed"; @@ -497,14 +488,13 @@ void GstEngine::SeekNow() { } void GstEngine::SetEqualizerEnabled(bool enabled) { - equalizer_enabled_= enabled; + equalizer_enabled_ = enabled; - if (current_pipeline_) - current_pipeline_->SetEqualizerEnabled(enabled); + if (current_pipeline_) current_pipeline_->SetEqualizerEnabled(enabled); } - -void GstEngine::SetEqualizerParameters(int preamp, const QList& band_gains) { +void GstEngine::SetEqualizerParameters(int preamp, + const QList& band_gains) { equalizer_preamp_ = preamp; equalizer_gains_ = band_gains; @@ -515,13 +505,11 @@ void GstEngine::SetEqualizerParameters(int preamp, const QList& band_gains) void GstEngine::SetStereoBalance(float value) { stereo_balance_ = value; - if (current_pipeline_) - current_pipeline_->SetStereoBalance(value); + if (current_pipeline_) current_pipeline_->SetStereoBalance(value); } -void GstEngine::SetVolumeSW( uint percent ) { - if (current_pipeline_) - current_pipeline_->SetVolume(percent); +void GstEngine::SetVolumeSW(uint percent) { + if (current_pipeline_) current_pipeline_->SetVolume(percent); } void GstEngine::StartTimers() { @@ -538,8 +526,7 @@ void GstEngine::StopTimers() { } void GstEngine::timerEvent(QTimerEvent* e) { - if (e->timerId() != timer_id_) - return; + if (e->timerId() != timer_id_) return; if (current_pipeline_) { const qint64 current_position = position_nanosec(); @@ -547,14 +534,14 @@ void GstEngine::timerEvent(QTimerEvent* e) { const qint64 remaining = current_length - current_position; - const qint64 fudge = kTimerIntervalNanosec + 100 * kNsecPerMsec; // Mmm fudge - const qint64 gap = buffer_duration_nanosec_ + ( - autocrossfade_enabled_ ? - fadeout_duration_nanosec_ : - kPreloadGapNanosec); + const qint64 fudge = + kTimerIntervalNanosec + 100 * kNsecPerMsec; // Mmm fudge + const qint64 gap = buffer_duration_nanosec_ + + (autocrossfade_enabled_ ? fadeout_duration_nanosec_ + : kPreloadGapNanosec); // only if we know the length of the current stream... - if(current_length > 0) { + if (current_length > 0) { // emit TrackAboutToEnd when we're a few seconds away from finishing if (remaining < gap + fudge) { EmitAboutToEnd(); @@ -577,15 +564,18 @@ void GstEngine::HandlePipelineError(int pipeline_id, const QString& message, // unable to play media stream with this url emit InvalidSongRequested(url_); - // TODO: the types of errors listed below won't be shown to user - they will - // get logged and the current song will be skipped; instead of maintaining + // TODO: the types of errors listed below won't be shown to user - they will + // get logged and the current song will be skipped; instead of maintaining // the list we should probably: // - don't report any engine's errors to user (always just log and skip) // - come up with a less intrusive error box (not a dialog but a notification // popup of some kind) and then report all errors - if(!(domain == GST_RESOURCE_ERROR && error_code == GST_RESOURCE_ERROR_NOT_FOUND) && - !(domain == GST_STREAM_ERROR && error_code == GST_STREAM_ERROR_TYPE_NOT_FOUND) && - !(domain == GST_RESOURCE_ERROR && error_code == GST_RESOURCE_ERROR_OPEN_READ)) { + if (!(domain == GST_RESOURCE_ERROR && + error_code == GST_RESOURCE_ERROR_NOT_FOUND) && + !(domain == GST_STREAM_ERROR && + error_code == GST_STREAM_ERROR_TYPE_NOT_FOUND) && + !(domain == GST_RESOURCE_ERROR && + error_code == GST_RESOURCE_ERROR_OPEN_READ)) { emit Error(message); } } @@ -601,36 +591,38 @@ void GstEngine::EndOfStreamReached(int pipeline_id, bool has_next_track) { emit TrackEnded(); } -void GstEngine::NewMetaData(int pipeline_id, const Engine::SimpleMetaBundle& bundle) { +void GstEngine::NewMetaData(int pipeline_id, + const Engine::SimpleMetaBundle& bundle) { if (!current_pipeline_.get() || current_pipeline_->id() != pipeline_id) return; emit MetaData(bundle); } -GstElement* GstEngine::CreateElement(const QString& factoryName, GstElement* bin) { +GstElement* GstEngine::CreateElement(const QString& factoryName, + GstElement* bin) { // Make a unique name - QString name = factoryName + "-" + QString::number(next_element_id_ ++); + QString name = factoryName + "-" + QString::number(next_element_id_++); GstElement* element = gst_element_factory_make( factoryName.toAscii().constData(), name.toAscii().constData()); if (!element) { - emit Error(QString("GStreamer could not create the element: %1. " - "Please make sure that you have installed all necessary GStreamer plugins (e.g. OGG and MP3)").arg( factoryName ) ); + emit Error(QString( + "GStreamer could not create the element: %1. " + "Please make sure that you have installed all necessary " + "GStreamer plugins (e.g. OGG and MP3)").arg(factoryName)); gst_object_unref(GST_OBJECT(bin)); return nullptr; } - if (bin) - gst_bin_add(GST_BIN(bin), element); + if (bin) gst_bin_add(GST_BIN(bin), element); return element; } - -GstEngine::PluginDetailsList - GstEngine::GetPluginList(const QString& classname) const { +GstEngine::PluginDetailsList GstEngine::GetPluginList(const QString& classname) + const { const_cast(this)->EnsureInitialised(); PluginDetailsList ret; @@ -667,16 +659,19 @@ shared_ptr GstEngine::CreatePipeline() { ret->set_mono_playback(mono_playback_); ret->AddBufferConsumer(this); - foreach (BufferConsumer* consumer, buffer_consumers_) { + foreach(BufferConsumer * consumer, buffer_consumers_) { ret->AddBufferConsumer(consumer); } - connect(ret.get(), SIGNAL(EndOfStreamReached(int, bool)), SLOT(EndOfStreamReached(int, bool))); - connect(ret.get(), SIGNAL(Error(int, QString,int,int)), SLOT(HandlePipelineError(int, QString,int,int))); + connect(ret.get(), SIGNAL(EndOfStreamReached(int, bool)), + SLOT(EndOfStreamReached(int, bool))); + connect(ret.get(), SIGNAL(Error(int, QString, int, int)), + SLOT(HandlePipelineError(int, QString, int, int))); connect(ret.get(), SIGNAL(MetadataFound(int, Engine::SimpleMetaBundle)), SLOT(NewMetaData(int, Engine::SimpleMetaBundle))); connect(ret.get(), SIGNAL(BufferingStarted()), SLOT(BufferingStarted())); - connect(ret.get(), SIGNAL(BufferingProgress(int)), SLOT(BufferingProgress(int))); + connect(ret.get(), SIGNAL(BufferingProgress(int)), + SLOT(BufferingProgress(int))); connect(ret.get(), SIGNAL(BufferingFinished()), SLOT(BufferingFinished())); return ret; @@ -696,33 +691,33 @@ shared_ptr GstEngine::CreatePipeline(const QUrl& url, return ret; } - if (!ret->InitFromUrl(url, end_nanosec)) - ret.reset(); + if (!ret->InitFromUrl(url, end_nanosec)) ret.reset(); return ret; } -bool GstEngine::DoesThisSinkSupportChangingTheOutputDeviceToAUserEditableString(const QString &name) { +bool GstEngine::DoesThisSinkSupportChangingTheOutputDeviceToAUserEditableString( + const QString& name) { return (name == "alsasink" || name == "osssink" || name == "pulsesink"); } -void GstEngine::AddBufferConsumer(BufferConsumer *consumer) { +void GstEngine::AddBufferConsumer(BufferConsumer* consumer) { buffer_consumers_ << consumer; - if (current_pipeline_) - current_pipeline_->AddBufferConsumer(consumer); + if (current_pipeline_) current_pipeline_->AddBufferConsumer(consumer); } -void GstEngine::RemoveBufferConsumer(BufferConsumer *consumer) { +void GstEngine::RemoveBufferConsumer(BufferConsumer* consumer) { buffer_consumers_.removeAll(consumer); - if (current_pipeline_) - current_pipeline_->RemoveBufferConsumer(consumer); + if (current_pipeline_) current_pipeline_->RemoveBufferConsumer(consumer); } int GstEngine::AddBackgroundStream(shared_ptr pipeline) { // We don't want to get metadata messages or end notifications. - disconnect(pipeline.get(), SIGNAL(MetadataFound(int,Engine::SimpleMetaBundle)), this, 0); - disconnect(pipeline.get(), SIGNAL(EndOfStreamReached(int,bool)), this, 0); - connect(pipeline.get(), SIGNAL(EndOfStreamReached(int,bool)), SLOT(BackgroundStreamFinished())); + disconnect(pipeline.get(), + SIGNAL(MetadataFound(int, Engine::SimpleMetaBundle)), this, 0); + disconnect(pipeline.get(), SIGNAL(EndOfStreamReached(int, bool)), this, 0); + connect(pipeline.get(), SIGNAL(EndOfStreamReached(int, bool)), + SLOT(BackgroundStreamFinished())); const int stream_id = next_background_stream_id_++; background_streams_[stream_id] = pipeline; diff --git a/src/engines/gstengine.h b/src/engines/gstengine.h index 3f3a6c8bf..25b8f5fac 100644 --- a/src/engines/gstengine.h +++ b/src/engines/gstengine.h @@ -80,20 +80,23 @@ class GstEngine : public Engine::Base, public BufferConsumer { Engine::State state() const; const Engine::Scope& scope(); - PluginDetailsList GetOutputsList() const { return GetPluginList( "Sink/Audio" ); } - static bool DoesThisSinkSupportChangingTheOutputDeviceToAUserEditableString(const QString& name); + PluginDetailsList GetOutputsList() const { + return GetPluginList("Sink/Audio"); + } + static bool DoesThisSinkSupportChangingTheOutputDeviceToAUserEditableString( + const QString& name); GstElement* CreateElement(const QString& factoryName, GstElement* bin = 0); // BufferConsumer - void ConsumeBuffer(GstBuffer *buffer, int pipeline_id); + void ConsumeBuffer(GstBuffer* buffer, int pipeline_id); public slots: void StartPreloading(const QUrl& url, bool force_stop_at_end, qint64 beginning_nanosec, qint64 end_nanosec); bool Load(const QUrl&, Engine::TrackChangeFlags change, - bool force_stop_at_end, - quint64 beginning_nanosec, qint64 end_nanosec); + bool force_stop_at_end, quint64 beginning_nanosec, + qint64 end_nanosec); bool Play(quint64 offset_nanosec); void Stop(); void Pause(); @@ -120,7 +123,8 @@ class GstEngine : public Engine::Base, public BufferConsumer { private slots: void EndOfStreamReached(int pipeline_id, bool has_next_track); - void HandlePipelineError(int pipeline_id, const QString& message, int domain, int error_code); + void HandlePipelineError(int pipeline_id, const QString& message, int domain, + int error_code); void NewMetaData(int pipeline_id, const Engine::SimpleMetaBundle& bundle); void AddBufferToScope(GstBuffer* buf, int pipeline_id); void FadeoutFinished(); @@ -136,7 +140,8 @@ class GstEngine : public Engine::Base, public BufferConsumer { private: typedef QPair PlayFutureWatcherArg; - typedef BoundFutureWatcher PlayFutureWatcher; + typedef BoundFutureWatcher + PlayFutureWatcher; static void SetEnv(const char* key, const QString& value); PluginDetailsList GetPluginList(const QString& classname) const; @@ -148,8 +153,8 @@ class GstEngine : public Engine::Base, public BufferConsumer { void StopTimers(); std::shared_ptr CreatePipeline(); - std::shared_ptr CreatePipeline( - const QUrl& url, qint64 end_nanosec); + std::shared_ptr CreatePipeline(const QUrl& url, + qint64 end_nanosec); void UpdateScope(); @@ -158,9 +163,9 @@ class GstEngine : public Engine::Base, public BufferConsumer { static QUrl FixupUrl(const QUrl& url); private: - static const qint64 kTimerIntervalNanosec = 1000 * kNsecPerMsec; // 1s - static const qint64 kPreloadGapNanosec = 2000 * kNsecPerMsec; // 2s - static const qint64 kSeekDelayNanosec = 100 * kNsecPerMsec; // 100msec + static const qint64 kTimerIntervalNanosec = 1000 * kNsecPerMsec; // 1s + static const qint64 kPreloadGapNanosec = 2000 * kNsecPerMsec; // 2s + static const qint64 kSeekDelayNanosec = 100 * kNsecPerMsec; // 100msec static const char* kHypnotoadPipeline; static const char* kEnterprisePipeline; @@ -213,5 +218,4 @@ class GstEngine : public Engine::Base, public BufferConsumer { bool has_faded_out_; }; - #endif /*AMAROK_GSTENGINE_H*/ diff --git a/src/engines/gstenginepipeline.cpp b/src/engines/gstenginepipeline.cpp index 67c47b1c0..8936e4d66 100644 --- a/src/engines/gstenginepipeline.cpp +++ b/src/engines/gstenginepipeline.cpp @@ -32,72 +32,69 @@ #include "internet/spotifyserver.h" #include "internet/spotifyservice.h" - const int GstEnginePipeline::kGstStateTimeoutNanosecs = 10000000; const int GstEnginePipeline::kFaderFudgeMsec = 2000; const int GstEnginePipeline::kEqBandCount = 10; const int GstEnginePipeline::kEqBandFrequencies[] = { - 60, 170, 310, 600, 1000, 3000, 6000, 12000, 14000, 16000}; + 60, 170, 310, 600, 1000, 3000, 6000, 12000, 14000, 16000}; int GstEnginePipeline::sId = 1; GstElementDeleter* GstEnginePipeline::sElementDeleter = nullptr; - GstEnginePipeline::GstEnginePipeline(GstEngine* engine) - : QObject(nullptr), - engine_(engine), - id_(sId++), - valid_(false), - sink_(GstEngine::kAutoSink), - segment_start_(0), - segment_start_received_(false), - emit_track_ended_on_segment_start_(false), - emit_track_ended_on_time_discontinuity_(false), - last_buffer_offset_(0), - eq_enabled_(false), - eq_preamp_(0), - stereo_balance_(0.0f), - rg_enabled_(false), - rg_mode_(0), - rg_preamp_(0.0), - rg_compression_(true), - buffer_duration_nanosec_(1 * kNsecPerSec), - buffering_(false), - mono_playback_(false), - end_offset_nanosec_(-1), - next_beginning_offset_nanosec_(-1), - next_end_offset_nanosec_(-1), - ignore_next_seek_(false), - ignore_tags_(false), - pipeline_is_initialised_(false), - pipeline_is_connected_(false), - pending_seek_nanosec_(-1), - volume_percent_(100), - volume_modifier_(1.0), - pipeline_(nullptr), - uridecodebin_(nullptr), - audiobin_(nullptr), - queue_(nullptr), - audioconvert_(nullptr), - rgvolume_(nullptr), - rglimiter_(nullptr), - audioconvert2_(nullptr), - equalizer_(nullptr), - stereo_panorama_(nullptr), - volume_(nullptr), - audioscale_(nullptr), - audiosink_(nullptr) -{ + : QObject(nullptr), + engine_(engine), + id_(sId++), + valid_(false), + sink_(GstEngine::kAutoSink), + segment_start_(0), + segment_start_received_(false), + emit_track_ended_on_segment_start_(false), + emit_track_ended_on_time_discontinuity_(false), + last_buffer_offset_(0), + eq_enabled_(false), + eq_preamp_(0), + stereo_balance_(0.0f), + rg_enabled_(false), + rg_mode_(0), + rg_preamp_(0.0), + rg_compression_(true), + buffer_duration_nanosec_(1 * kNsecPerSec), + buffering_(false), + mono_playback_(false), + end_offset_nanosec_(-1), + next_beginning_offset_nanosec_(-1), + next_end_offset_nanosec_(-1), + ignore_next_seek_(false), + ignore_tags_(false), + pipeline_is_initialised_(false), + pipeline_is_connected_(false), + pending_seek_nanosec_(-1), + volume_percent_(100), + volume_modifier_(1.0), + pipeline_(nullptr), + uridecodebin_(nullptr), + audiobin_(nullptr), + queue_(nullptr), + audioconvert_(nullptr), + rgvolume_(nullptr), + rglimiter_(nullptr), + audioconvert2_(nullptr), + equalizer_(nullptr), + stereo_panorama_(nullptr), + volume_(nullptr), + audioscale_(nullptr), + audiosink_(nullptr) { if (!sElementDeleter) { sElementDeleter = new GstElementDeleter; } - for (int i=0 ; iCreateElement("tcpserversrc", new_bin); GstElement* gdp = engine_->CreateElement("gdpdepay", new_bin); - if (!src || !gdp) - return false; + if (!src || !gdp) return false; // Pick a port number const int port = Utilities::PickUnusedPort(); @@ -163,13 +160,17 @@ bool GstEnginePipeline::ReplaceDecodeBin(const QUrl& url) { gst_object_unref(GST_OBJECT(pad)); // Tell spotify to start sending data to us. - InternetModel::Service()->server()->StartPlaybackLater(url.toString(), port); + InternetModel::Service()->server()->StartPlaybackLater( + url.toString(), port); } else { new_bin = engine_->CreateElement("uridecodebin"); - g_object_set(G_OBJECT(new_bin), "uri", url.toEncoded().constData(), nullptr); - CHECKED_GCONNECT(G_OBJECT(new_bin), "drained", &SourceDrainedCallback, this); + g_object_set(G_OBJECT(new_bin), "uri", url.toEncoded().constData(), + nullptr); + CHECKED_GCONNECT(G_OBJECT(new_bin), "drained", &SourceDrainedCallback, + this); CHECKED_GCONNECT(G_OBJECT(new_bin), "pad-added", &NewPadCallback, this); - CHECKED_GCONNECT(G_OBJECT(new_bin), "notify::source", &SourceSetupCallback, this); + CHECKED_GCONNECT(G_OBJECT(new_bin), "notify::source", &SourceSetupCallback, + this); } return ReplaceDecodeBin(new_bin); @@ -218,31 +219,34 @@ bool GstEnginePipeline::Init() { gst_bin_add(GST_BIN(pipeline_), audiobin_); // Create the sink - if (!(audiosink_ = engine_->CreateElement(sink_, audiobin_))) - return false; + if (!(audiosink_ = engine_->CreateElement(sink_, audiobin_))) return false; - if (GstEngine::DoesThisSinkSupportChangingTheOutputDeviceToAUserEditableString(sink_) && !device_.isEmpty()) - g_object_set(G_OBJECT(audiosink_), "device", device_.toUtf8().constData(), nullptr); + if (GstEngine:: + DoesThisSinkSupportChangingTheOutputDeviceToAUserEditableString( + sink_) && + !device_.isEmpty()) + g_object_set(G_OBJECT(audiosink_), "device", device_.toUtf8().constData(), + nullptr); // Create all the other elements - GstElement *tee, *probe_queue, *probe_converter, *probe_sink, *audio_queue, - *convert; + GstElement* tee, *probe_queue, *probe_converter, *probe_sink, *audio_queue, + *convert; - queue_ = engine_->CreateElement("queue2", audiobin_); - audioconvert_ = engine_->CreateElement("audioconvert", audiobin_); - tee = engine_->CreateElement("tee", audiobin_); + queue_ = engine_->CreateElement("queue2", audiobin_); + audioconvert_ = engine_->CreateElement("audioconvert", audiobin_); + tee = engine_->CreateElement("tee", audiobin_); - probe_queue = engine_->CreateElement("queue", audiobin_); - probe_converter = engine_->CreateElement("audioconvert", audiobin_); - probe_sink = engine_->CreateElement("fakesink", audiobin_); + probe_queue = engine_->CreateElement("queue", audiobin_); + probe_converter = engine_->CreateElement("audioconvert", audiobin_); + probe_sink = engine_->CreateElement("fakesink", audiobin_); - audio_queue = engine_->CreateElement("queue", audiobin_); - equalizer_preamp_ = engine_->CreateElement("volume", audiobin_); - equalizer_ = engine_->CreateElement("equalizer-nbands", audiobin_); - stereo_panorama_ = engine_->CreateElement("audiopanorama", audiobin_); - volume_ = engine_->CreateElement("volume", audiobin_); - audioscale_ = engine_->CreateElement("audioresample", audiobin_); - convert = engine_->CreateElement("audioconvert", audiobin_); + audio_queue = engine_->CreateElement("queue", audiobin_); + equalizer_preamp_ = engine_->CreateElement("volume", audiobin_); + equalizer_ = engine_->CreateElement("equalizer-nbands", audiobin_); + stereo_panorama_ = engine_->CreateElement("audiopanorama", audiobin_); + volume_ = engine_->CreateElement("volume", audiobin_); + audioscale_ = engine_->CreateElement("audioresample", audiobin_); + convert = engine_->CreateElement("audioconvert", audiobin_); if (!queue_ || !audioconvert_ || !tee || !probe_queue || !probe_converter || !probe_sink || !audio_queue || !equalizer_preamp_ || !equalizer_ || @@ -258,8 +262,8 @@ bool GstEnginePipeline::Init() { GstElement* convert_sink = tee; if (rg_enabled_) { - rgvolume_ = engine_->CreateElement("rgvolume", audiobin_); - rglimiter_ = engine_->CreateElement("rglimiter", audiobin_); + rgvolume_ = engine_->CreateElement("rgvolume", audiobin_); + rglimiter_ = engine_->CreateElement("rglimiter", audiobin_); audioconvert2_ = engine_->CreateElement("audioconvert", audiobin_); event_probe = audioconvert2_; convert_sink = rgvolume_; @@ -271,7 +275,8 @@ bool GstEnginePipeline::Init() { // Set replaygain settings g_object_set(G_OBJECT(rgvolume_), "album-mode", rg_mode_, nullptr); g_object_set(G_OBJECT(rgvolume_), "pre-amp", double(rg_preamp_), nullptr); - g_object_set(G_OBJECT(rglimiter_), "enabled", int(rg_compression_), nullptr); + g_object_set(G_OBJECT(rglimiter_), "enabled", int(rg_compression_), + nullptr); } // Create a pad on the outside of the audiobin and connect it to the pad of @@ -294,21 +299,22 @@ bool GstEnginePipeline::Init() { g_object_set(G_OBJECT(equalizer_), "num-bands", 10, nullptr); int last_band_frequency = 0; - for (int i=0 ; i 0) { @@ -328,13 +335,11 @@ bool GstEnginePipeline::Init() { // Create the caps to put in each path in the tee. The scope path gets 16-bit // ints and the audiosink path gets float32. - GstCaps* caps16 = gst_caps_new_simple ("audio/x-raw-int", - "width", G_TYPE_INT, 16, - "signed", G_TYPE_BOOLEAN, true, - nullptr); - GstCaps* caps32 = gst_caps_new_simple ("audio/x-raw-float", - "width", G_TYPE_INT, 32, - nullptr); + GstCaps* caps16 = + gst_caps_new_simple("audio/x-raw-int", "width", G_TYPE_INT, 16, "signed", + G_TYPE_BOOLEAN, true, nullptr); + GstCaps* caps32 = gst_caps_new_simple("audio/x-raw-float", "width", + G_TYPE_INT, 32, nullptr); if (mono_playback_) { gst_caps_set_simple(caps32, "channels", G_TYPE_INT, 1, nullptr); } @@ -346,8 +351,10 @@ bool GstEnginePipeline::Init() { gst_caps_unref(caps32); // Link the outputs of tee to the queues on each path. - gst_pad_link(gst_element_get_request_pad(tee, "src%d"), gst_element_get_static_pad(probe_queue, "sink")); - gst_pad_link(gst_element_get_request_pad(tee, "src%d"), gst_element_get_static_pad(audio_queue, "sink")); + gst_pad_link(gst_element_get_request_pad(tee, "src%d"), + gst_element_get_static_pad(probe_queue, "sink")); + gst_pad_link(gst_element_get_request_pad(tee, "src%d"), + gst_element_get_static_pad(audio_queue, "sink")); // Link replaygain elements if enabled. if (rg_enabled_) { @@ -356,13 +363,17 @@ bool GstEnginePipeline::Init() { // Link everything else. gst_element_link(probe_queue, probe_converter); - gst_element_link_many(audio_queue, equalizer_preamp_, equalizer_, stereo_panorama_, - volume_, audioscale_, convert, audiosink_, nullptr); + gst_element_link_many(audio_queue, equalizer_preamp_, equalizer_, + stereo_panorama_, volume_, audioscale_, convert, + audiosink_, nullptr); // Add probes and handlers. - gst_pad_add_buffer_probe(gst_element_get_static_pad(probe_converter, "src"), G_CALLBACK(HandoffCallback), this); - gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), BusCallbackSync, this); - bus_cb_id_ = gst_bus_add_watch(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), BusCallback, this); + gst_pad_add_buffer_probe(gst_element_get_static_pad(probe_converter, "src"), + G_CALLBACK(HandoffCallback), this); + gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), + BusCallbackSync, this); + bus_cb_id_ = gst_bus_add_watch(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), + BusCallback, this); MaybeLinkDecodeToAudio(); @@ -370,12 +381,10 @@ bool GstEnginePipeline::Init() { } void GstEnginePipeline::MaybeLinkDecodeToAudio() { - if (!uridecodebin_ || !audiobin_) - return; + if (!uridecodebin_ || !audiobin_) return; GstPad* pad = gst_element_get_static_pad(uridecodebin_, "src"); - if (!pad) - return; + if (!pad) return; gst_object_unref(pad); gst_element_link(uridecodebin_, audiobin_); @@ -384,7 +393,8 @@ void GstEnginePipeline::MaybeLinkDecodeToAudio() { bool GstEnginePipeline::InitFromString(const QString& pipeline) { pipeline_ = gst_pipeline_new("pipeline"); - GstElement* new_bin = CreateDecodeBinFromString(pipeline.toAscii().constData()); + GstElement* new_bin = + CreateDecodeBinFromString(pipeline.toAscii().constData()); if (!new_bin) { return false; } @@ -395,9 +405,9 @@ bool GstEnginePipeline::InitFromString(const QString& pipeline) { return gst_element_link(new_bin, audiobin_); } -bool GstEnginePipeline::InitFromUrl(const QUrl &url, qint64 end_nanosec) { +bool GstEnginePipeline::InitFromUrl(const QUrl& url, qint64 end_nanosec) { pipeline_ = gst_pipeline_new("pipeline"); - + if (url.scheme() == "cdda" && !url.path().isEmpty()) { // Currently, Gstreamer can't handle input CD devices inside cdda URL. So // we handle them ourselve: we extract the track number and re-create an @@ -420,17 +430,16 @@ bool GstEnginePipeline::InitFromUrl(const QUrl &url, qint64 end_nanosec) { GstEnginePipeline::~GstEnginePipeline() { if (pipeline_) { - gst_bus_set_sync_handler( - gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), nullptr, nullptr); + gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), + nullptr, nullptr); g_source_remove(bus_cb_id_); gst_element_set_state(pipeline_, GST_STATE_NULL); gst_object_unref(GST_OBJECT(pipeline_)); } } - - -gboolean GstEnginePipeline::BusCallback(GstBus*, GstMessage* msg, gpointer self) { +gboolean GstEnginePipeline::BusCallback(GstBus*, GstMessage* msg, + gpointer self) { GstEnginePipeline* instance = reinterpret_cast(self); qLog(Debug) << instance->id() << "bus message" << GST_MESSAGE_TYPE_NAME(msg); @@ -455,10 +464,12 @@ gboolean GstEnginePipeline::BusCallback(GstBus*, GstMessage* msg, gpointer self) return FALSE; } -GstBusSyncReply GstEnginePipeline::BusCallbackSync(GstBus*, GstMessage* msg, gpointer self) { +GstBusSyncReply GstEnginePipeline::BusCallbackSync(GstBus*, GstMessage* msg, + gpointer self) { GstEnginePipeline* instance = reinterpret_cast(self); - qLog(Debug) << instance->id() << "sync bus message" << GST_MESSAGE_TYPE_NAME(msg); + qLog(Debug) << instance->id() << "sync bus message" + << GST_MESSAGE_TYPE_NAME(msg); switch (GST_MESSAGE_TYPE(msg)) { case GST_MESSAGE_EOS: @@ -516,7 +527,7 @@ void GstEnginePipeline::StreamStatusMessageReceived(GstMessage* msg) { } void GstEnginePipeline::TaskEnterCallback(GstTask*, GThread*, gpointer) { - // Bump the priority of the thread only on OS X +// Bump the priority of the thread only on OS X #ifdef Q_OS_DARWIN sched_param param; @@ -552,8 +563,10 @@ void GstEnginePipeline::ErrorMessageReceived(GstMessage* msg) { g_error_free(error); free(debugs); - if (!redirect_url_.isEmpty() && debugstr.contains( - "A redirect message was posted on the bus and should have been handled by the application.")) { + if (!redirect_url_.isEmpty() && + debugstr.contains( + "A redirect message was posted on the bus and should have been " + "handled by the application.")) { // mmssrc posts a message on the bus *and* makes an error message when it // wants to do a redirect. We handle the message, but now we have to // ignore the error too. @@ -577,8 +590,7 @@ void GstEnginePipeline::TagMessageReceived(GstMessage* msg) { gst_tag_list_free(taglist); - if (ignore_tags_) - return; + if (ignore_tags_) return; if (!bundle.title.isEmpty() || !bundle.artist.isEmpty() || !bundle.comment.isEmpty() || !bundle.album.isEmpty()) @@ -606,7 +618,8 @@ void GstEnginePipeline::StateChangedMessageReceived(GstMessage* msg) { GstState old_state, new_state, pending; gst_message_parse_state_changed(msg, &old_state, &new_state, &pending); - if (!pipeline_is_initialised_ && (new_state == GST_STATE_PAUSED || new_state == GST_STATE_PLAYING)) { + if (!pipeline_is_initialised_ && + (new_state == GST_STATE_PAUSED || new_state == GST_STATE_PLAYING)) { pipeline_is_initialised_ = true; if (pending_seek_nanosec_ != -1 && pipeline_is_connected_) { QMetaObject::invokeMethod(this, "Seek", Qt::QueuedConnection, @@ -614,7 +627,8 @@ void GstEnginePipeline::StateChangedMessageReceived(GstMessage* msg) { } } - if (pipeline_is_initialised_ && new_state != GST_STATE_PAUSED && new_state != GST_STATE_PLAYING) { + if (pipeline_is_initialised_ && new_state != GST_STATE_PAUSED && + new_state != GST_STATE_PLAYING) { pipeline_is_initialised_ = false; } } @@ -646,12 +660,15 @@ void GstEnginePipeline::BufferingMessageReceived(GstMessage* msg) { } } -void GstEnginePipeline::NewPadCallback(GstElement*, GstPad* pad, gpointer self) { +void GstEnginePipeline::NewPadCallback(GstElement*, GstPad* pad, + gpointer self) { GstEnginePipeline* instance = reinterpret_cast(self); - GstPad* const audiopad = gst_element_get_static_pad(instance->audiobin_, "sink"); + GstPad* const audiopad = + gst_element_get_static_pad(instance->audiobin_, "sink"); if (GST_PAD_IS_LINKED(audiopad)) { - qLog(Warning) << instance->id() << "audiopad is already linked, unlinking old pad"; + qLog(Warning) << instance->id() + << "audiopad is already linked, unlinking old pad"; gst_pad_unlink(audiopad, GST_PAD_PEER(audiopad)); } @@ -660,13 +677,15 @@ void GstEnginePipeline::NewPadCallback(GstElement*, GstPad* pad, gpointer self) gst_object_unref(audiopad); instance->pipeline_is_connected_ = true; - if (instance->pending_seek_nanosec_ != -1 && instance->pipeline_is_initialised_) { + if (instance->pending_seek_nanosec_ != -1 && + instance->pipeline_is_initialised_) { QMetaObject::invokeMethod(instance, "Seek", Qt::QueuedConnection, Q_ARG(qint64, instance->pending_seek_nanosec_)); } } -bool GstEnginePipeline::HandoffCallback(GstPad*, GstBuffer* buf, gpointer self) { +bool GstEnginePipeline::HandoffCallback(GstPad*, GstBuffer* buf, + gpointer self) { GstEnginePipeline* instance = reinterpret_cast(self); QList consumers; @@ -675,7 +694,7 @@ bool GstEnginePipeline::HandoffCallback(GstPad*, GstBuffer* buf, gpointer self) consumers = instance->buffer_consumers_; } - foreach (BufferConsumer* consumer, consumers) { + foreach(BufferConsumer * consumer, consumers) { gst_buffer_ref(buf); consumer->ConsumeBuffer(buf, instance->id()); } @@ -690,7 +709,8 @@ bool GstEnginePipeline::HandoffCallback(GstPad*, GstBuffer* buf, gpointer self) if (end_time > instance->end_offset_nanosec_) { if (instance->has_next_valid_url()) { if (instance->next_url_ == instance->url_ && - instance->next_beginning_offset_nanosec_ == instance->end_offset_nanosec_) { + instance->next_beginning_offset_nanosec_ == + instance->end_offset_nanosec_) { // The "next" song is actually the next segment of this file - so // cheat and keep on playing, but just tell the Engine we've moved on. instance->end_offset_nanosec_ = instance->next_end_offset_nanosec_; @@ -727,17 +747,19 @@ bool GstEnginePipeline::HandoffCallback(GstPad*, GstBuffer* buf, gpointer self) return true; } -bool GstEnginePipeline::EventHandoffCallback(GstPad*, GstEvent* e, gpointer self) { +bool GstEnginePipeline::EventHandoffCallback(GstPad*, GstEvent* e, + gpointer self) { GstEnginePipeline* instance = reinterpret_cast(self); qLog(Debug) << instance->id() << "event" << GST_EVENT_TYPE_NAME(e); - if (GST_EVENT_TYPE(e) == GST_EVENT_NEWSEGMENT && !instance->segment_start_received_) { + if (GST_EVENT_TYPE(e) == GST_EVENT_NEWSEGMENT && + !instance->segment_start_received_) { // The segment start time is used to calculate the proper offset of data // buffers from the start of the stream gint64 start = 0; - gst_event_parse_new_segment( - e, nullptr, nullptr, nullptr, &start, nullptr, nullptr); + gst_event_parse_new_segment(e, nullptr, nullptr, nullptr, &start, nullptr, + nullptr); instance->segment_start_ = start; instance->segment_start_received_ = true; @@ -752,7 +774,8 @@ bool GstEnginePipeline::EventHandoffCallback(GstPad*, GstEvent* e, gpointer self return true; } -void GstEnginePipeline::SourceDrainedCallback(GstURIDecodeBin* bin, gpointer self) { +void GstEnginePipeline::SourceDrainedCallback(GstURIDecodeBin* bin, + gpointer self) { GstEnginePipeline* instance = reinterpret_cast(self); if (instance->has_next_valid_url()) { @@ -760,7 +783,8 @@ void GstEnginePipeline::SourceDrainedCallback(GstURIDecodeBin* bin, gpointer sel } } -void GstEnginePipeline::SourceSetupCallback(GstURIDecodeBin* bin, GParamSpec *pspec, gpointer self) { +void GstEnginePipeline::SourceSetupCallback(GstURIDecodeBin* bin, + GParamSpec* pspec, gpointer self) { GstEnginePipeline* instance = reinterpret_cast(self); GstElement* element; g_object_get(bin, "source", &element, nullptr); @@ -774,38 +798,40 @@ void GstEnginePipeline::SourceSetupCallback(GstURIDecodeBin* bin, GParamSpec *ps // documentation, this might be added in the future). Despite that, for now // we include device inside URL: we decompose it during Init and set device // here, when this callback is called. - g_object_set(element, "device", instance->source_device().toLocal8Bit().constData(), nullptr); + g_object_set(element, "device", + instance->source_device().toLocal8Bit().constData(), nullptr); } - if (g_object_class_find_property(G_OBJECT_GET_CLASS(element), "extra-headers") && + if (g_object_class_find_property(G_OBJECT_GET_CLASS(element), + "extra-headers") && instance->url().host().contains("grooveshark")) { // Grooveshark streaming servers will answer with a 400 error 'Bad request' // if we don't specify 'Range' field in HTTP header. // Maybe it could be usefull in some other cases, but for now, I prefer to // keep this grooveshark specific. GstStructure* headers; - headers = gst_structure_new("extra-headers", "Range", G_TYPE_STRING, "bytes=0-", nullptr); + headers = gst_structure_new("extra-headers", "Range", G_TYPE_STRING, + "bytes=0-", nullptr); g_object_set(element, "extra-headers", headers, nullptr); gst_structure_free(headers); } - if (g_object_class_find_property(G_OBJECT_GET_CLASS(element), "extra-headers") && + if (g_object_class_find_property(G_OBJECT_GET_CLASS(element), + "extra-headers") && instance->url().host().contains("files.one.ubuntu.com")) { GstStructure* headers; - headers = gst_structure_new( - "extra-headers", - "Authorization", - G_TYPE_STRING, - instance->url().fragment().toAscii().data(), - nullptr); + headers = + gst_structure_new("extra-headers", "Authorization", G_TYPE_STRING, + instance->url().fragment().toAscii().data(), nullptr); g_object_set(element, "extra-headers", headers, nullptr); gst_structure_free(headers); } if (g_object_class_find_property(G_OBJECT_GET_CLASS(element), "user-agent")) { - QString user_agent = QString("%1 %2").arg( - QCoreApplication::applicationName(), - QCoreApplication::applicationVersion()); - g_object_set(element, "user-agent", user_agent.toUtf8().constData(), nullptr); + QString user_agent = + QString("%1 %2").arg(QCoreApplication::applicationName(), + QCoreApplication::applicationVersion()); + g_object_set(element, "user-agent", user_agent.toUtf8().constData(), + nullptr); } } @@ -847,7 +873,7 @@ qint64 GstEnginePipeline::position() const { qint64 GstEnginePipeline::length() const { GstFormat fmt = GST_FORMAT_TIME; gint64 value = 0; - gst_element_query_duration(pipeline_, &fmt, &value); + gst_element_query_duration(pipeline_, &fmt, &value); return value; } @@ -887,7 +913,8 @@ void GstEnginePipeline::SetEqualizerEnabled(bool enabled) { UpdateEqualizer(); } -void GstEnginePipeline::SetEqualizerParams(int preamp, const QList& band_gains) { +void GstEnginePipeline::SetEqualizerParams(int preamp, + const QList& band_gains) { eq_preamp_ = preamp; eq_band_gains_ = band_gains; UpdateEqualizer(); @@ -900,14 +927,15 @@ void GstEnginePipeline::SetStereoBalance(float value) { void GstEnginePipeline::UpdateEqualizer() { // Update band gains - for (int i=0 ; icurrentTime()) / qreal(fader_->duration())); + qreal time = qreal(duration_msec) * + (qreal(fader_->currentTime()) / qreal(fader_->duration())); start_time = qRound(time); } } fader_.reset(new QTimeLine(duration_msec, this)); - connect(fader_.get(), SIGNAL(valueChanged(qreal)), SLOT(SetVolumeModifier(qreal))); + connect(fader_.get(), SIGNAL(valueChanged(qreal)), + SLOT(SetVolumeModifier(qreal))); connect(fader_.get(), SIGNAL(finished()), SLOT(FaderTimelineFinished())); fader_->setDirection(direction); fader_->setCurveShape(shape); @@ -1002,12 +1033,12 @@ void GstEnginePipeline::timerEvent(QTimerEvent* e) { QObject::timerEvent(e); } -void GstEnginePipeline::AddBufferConsumer(BufferConsumer *consumer) { +void GstEnginePipeline::AddBufferConsumer(BufferConsumer* consumer) { QMutexLocker l(&buffer_consumers_mutex_); buffer_consumers_ << consumer; } -void GstEnginePipeline::RemoveBufferConsumer(BufferConsumer *consumer) { +void GstEnginePipeline::RemoveBufferConsumer(BufferConsumer* consumer) { QMutexLocker l(&buffer_consumers_mutex_); buffer_consumers_.removeAll(consumer); } @@ -1017,8 +1048,7 @@ void GstEnginePipeline::RemoveAllBufferConsumers() { buffer_consumers_.clear(); } -void GstEnginePipeline::SetNextUrl(const QUrl& url, - qint64 beginning_nanosec, +void GstEnginePipeline::SetNextUrl(const QUrl& url, qint64 beginning_nanosec, qint64 end_nanosec) { next_url_ = url; next_beginning_offset_nanosec_ = beginning_nanosec; diff --git a/src/engines/gstenginepipeline.h b/src/engines/gstenginepipeline.h index 65e23003f..34d45d09b 100644 --- a/src/engines/gstenginepipeline.h +++ b/src/engines/gstenginepipeline.h @@ -78,7 +78,8 @@ class GstEnginePipeline : public QObject { // If this is set then it will be loaded automatically when playback finishes // for gapless playback - void SetNextUrl(const QUrl& url, qint64 beginning_nanosec, qint64 end_nanosec); + void SetNextUrl(const QUrl& url, qint64 beginning_nanosec, + qint64 end_nanosec); bool has_next_valid_url() const { return next_url_.isValid(); } // Get information about the music playback @@ -106,12 +107,13 @@ class GstEnginePipeline : public QObject { public slots: void SetVolumeModifier(qreal mod); - signals: +signals: void EndOfStreamReached(int pipeline_id, bool has_next_track); void MetadataFound(int pipeline_id, const Engine::SimpleMetaBundle& bundle); // This indicates an error, delegated from GStreamer, in the pipeline. // The message, domain and error_code are related to GStreamer's GError. - void Error(int pipeline_id, const QString& message, int domain, int error_code); + void Error(int pipeline_id, const QString& message, int domain, + int error_code); void FaderFinished(); void BufferingStarted(); @@ -119,7 +121,7 @@ class GstEnginePipeline : public QObject { void BufferingFinished(); protected: - void timerEvent(QTimerEvent *); + void timerEvent(QTimerEvent*); private: // Static callbacks. The GstEnginePipeline instance is passed in the last @@ -130,7 +132,8 @@ class GstEnginePipeline : public QObject { static bool HandoffCallback(GstPad*, GstBuffer*, gpointer); static bool EventHandoffCallback(GstPad*, GstEvent*, gpointer); static void SourceDrainedCallback(GstURIDecodeBin*, gpointer); - static void SourceSetupCallback(GstURIDecodeBin*, GParamSpec *pspec, gpointer); + static void SourceSetupCallback(GstURIDecodeBin*, GParamSpec* pspec, + gpointer); static void TaskEnterCallback(GstTask*, GThread*, gpointer); void TagMessageReceived(GstMessage*); @@ -283,4 +286,4 @@ class GstEnginePipeline : public QObject { QThreadPool set_state_threadpool_; }; -#endif // GSTENGINEPIPELINE_H +#endif // GSTENGINEPIPELINE_H diff --git a/src/globalsearch/digitallyimportedsearchprovider.cpp b/src/globalsearch/digitallyimportedsearchprovider.cpp index 06437a1a6..26046ed85 100644 --- a/src/globalsearch/digitallyimportedsearchprovider.cpp +++ b/src/globalsearch/digitallyimportedsearchprovider.cpp @@ -20,14 +20,15 @@ #include "internet/digitallyimportedservicebase.h" DigitallyImportedSearchProvider::DigitallyImportedSearchProvider( - DigitallyImportedServiceBase* service, Application* app, QObject* parent) - : SimpleSearchProvider(app, parent), - service_(service) -{ + DigitallyImportedServiceBase* service, Application* app, QObject* parent) + : SimpleSearchProvider(app, parent), service_(service) { Init(service_->name(), service->api_service_name(), service_->icon(), ArtIsInSongMetadata | CanGiveSuggestions | CanShowConfig); - set_safe_words(QStringList() << "sky.fm" << "skyfm" << "di.fm" << "difm" + set_safe_words(QStringList() << "sky.fm" + << "skyfm" + << "di.fm" + << "difm" << "digitallyimported"); set_max_suggestion_count(5); @@ -35,8 +36,7 @@ DigitallyImportedSearchProvider::DigitallyImportedSearchProvider( // Load the channel list on startup only if it doesn't involve going to update // info from the server. - if (!service_->IsChannelListStale()) - RecreateItems(); + if (!service_->IsChannelListStale()) RecreateItems(); } void DigitallyImportedSearchProvider::RecreateItems() { @@ -44,7 +44,7 @@ void DigitallyImportedSearchProvider::RecreateItems() { DigitallyImportedClient::ChannelList channels = service_->Channels(); - foreach (const DigitallyImportedClient::Channel& channel, channels) { + foreach(const DigitallyImportedClient::Channel & channel, channels) { Song song; service_->SongFromChannel(channel, &song); items << Item(song); diff --git a/src/globalsearch/digitallyimportedsearchprovider.h b/src/globalsearch/digitallyimportedsearchprovider.h index a2aeebd6d..4630da96e 100644 --- a/src/globalsearch/digitallyimportedsearchprovider.h +++ b/src/globalsearch/digitallyimportedsearchprovider.h @@ -23,17 +23,17 @@ class DigitallyImportedServiceBase; class DigitallyImportedSearchProvider : public SimpleSearchProvider { -public: + public: DigitallyImportedSearchProvider(DigitallyImportedServiceBase* service, Application* app, QObject* parent); void ShowConfig(); -protected: + protected: void RecreateItems(); -private: + private: DigitallyImportedServiceBase* service_; }; -#endif // DIGITALLYIMPORTEDSEARCHPROVIDER_H +#endif // DIGITALLYIMPORTEDSEARCHPROVIDER_H diff --git a/src/globalsearch/globalsearch.cpp b/src/globalsearch/globalsearch.cpp index b3c2912ae..7330b336f 100644 --- a/src/globalsearch/globalsearch.cpp +++ b/src/globalsearch/globalsearch.cpp @@ -33,31 +33,27 @@ const int GlobalSearch::kDelayedSearchTimeoutMs = 200; const char* GlobalSearch::kSettingsGroup = "GlobalSearch"; const int GlobalSearch::kMaxResultsPerEmission = 500; - GlobalSearch::GlobalSearch(Application* app, QObject* parent) - : QObject(parent), - app_(app), - next_id_(1), - url_provider_(new UrlSearchProvider(app, this)) -{ + : QObject(parent), + app_(app), + next_id_(1), + url_provider_(new UrlSearchProvider(app, this)) { cover_loader_options_.desired_height_ = SearchProvider::kArtHeight; cover_loader_options_.pad_output_image_ = true; cover_loader_options_.scale_output_image_ = true; - connect(app_->album_cover_loader(), - SIGNAL(ImageLoaded(quint64,QImage)), - SLOT(AlbumArtLoaded(quint64,QImage))); + connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)), + SLOT(AlbumArtLoaded(quint64, QImage))); ConnectProvider(url_provider_); } void GlobalSearch::ConnectProvider(SearchProvider* provider) { - connect(provider, SIGNAL(ResultsAvailable(int,SearchProvider::ResultList)), - SLOT(ResultsAvailableSlot(int,SearchProvider::ResultList))); - connect(provider, SIGNAL(SearchFinished(int)), - SLOT(SearchFinishedSlot(int))); - connect(provider, SIGNAL(ArtLoaded(int,QImage)), - SLOT(ArtLoadedSlot(int,QImage))); + connect(provider, SIGNAL(ResultsAvailable(int, SearchProvider::ResultList)), + SLOT(ResultsAvailableSlot(int, SearchProvider::ResultList))); + connect(provider, SIGNAL(SearchFinished(int)), SLOT(SearchFinishedSlot(int))); + connect(provider, SIGNAL(ArtLoaded(int, QImage)), + SLOT(ArtLoadedSlot(int, QImage))); connect(provider, SIGNAL(destroyed(QObject*)), SLOT(ProviderDestroyedSlot(QObject*))); } @@ -85,7 +81,7 @@ void GlobalSearch::AddProvider(SearchProvider* provider) { } int GlobalSearch::SearchAsync(const QString& query) { - const int id = next_id_ ++; + const int id = next_id_++; pending_search_providers_[id] = 0; int timer_id = -1; @@ -93,11 +89,10 @@ int GlobalSearch::SearchAsync(const QString& query) { if (url_provider_->LooksLikeUrl(query)) { url_provider_->SearchAsync(id, query); } else { - foreach (SearchProvider* provider, providers_.keys()) { - if (!is_provider_usable(provider)) - continue; + foreach(SearchProvider * provider, providers_.keys()) { + if (!is_provider_usable(provider)) continue; - pending_search_providers_[id] ++; + pending_search_providers_[id]++; if (provider->wants_delayed_queries()) { if (timer_id == -1) { @@ -117,7 +112,7 @@ int GlobalSearch::SearchAsync(const QString& query) { void GlobalSearch::CancelSearch(int id) { QMap::iterator it; - for (it = delayed_searches_.begin() ; it != delayed_searches_.end() ; ++it) { + for (it = delayed_searches_.begin(); it != delayed_searches_.end(); ++it) { if (it.value().id_ == id) { killTimer(it.key()); delayed_searches_.erase(it); @@ -129,7 +124,7 @@ void GlobalSearch::CancelSearch(int id) { void GlobalSearch::timerEvent(QTimerEvent* e) { QMap::iterator it = delayed_searches_.find(e->timerId()); if (it != delayed_searches_.end()) { - foreach (SearchProvider* provider, it.value().providers_) { + foreach(SearchProvider * provider, it.value().providers_) { provider->SearchAsync(it.value().id_, it.value().query_); } delayed_searches_.erase(it); @@ -139,15 +134,15 @@ void GlobalSearch::timerEvent(QTimerEvent* e) { QObject::timerEvent(e); } -QString GlobalSearch::PixmapCacheKey(const SearchProvider::Result& result) const { - return "globalsearch:" - % QString::number(qulonglong(result.provider_)) - % "," % result.metadata_.url().toString(); +QString GlobalSearch::PixmapCacheKey(const SearchProvider::Result& result) + const { + return "globalsearch:" % QString::number(qulonglong(result.provider_)) % "," % + result.metadata_.url().toString(); } -void GlobalSearch::ResultsAvailableSlot(int id, SearchProvider::ResultList results) { - if (results.isEmpty()) - return; +void GlobalSearch::ResultsAvailableSlot(int id, + SearchProvider::ResultList results) { + if (results.isEmpty()) return; // Limit the number of results that are used from each emission. // Just a sanity check to stop some providers (Jamendo) returning thousands @@ -159,7 +154,8 @@ void GlobalSearch::ResultsAvailableSlot(int id, SearchProvider::ResultList resul } // Load cached pixmaps into the results - for (SearchProvider::ResultList::iterator it = results.begin() ; it != results.end() ; ++it) { + for (SearchProvider::ResultList::iterator it = results.begin(); + it != results.end(); ++it) { it->pixmap_cache_key_ = PixmapCacheKey(*it); } @@ -167,8 +163,7 @@ void GlobalSearch::ResultsAvailableSlot(int id, SearchProvider::ResultList resul } void GlobalSearch::SearchFinishedSlot(int id) { - if (!pending_search_providers_.contains(id)) - return; + if (!pending_search_providers_.contains(id)) return; SearchProvider* provider = static_cast(sender()); const int remaining = --pending_search_providers_[id]; @@ -182,17 +177,14 @@ void GlobalSearch::SearchFinishedSlot(int id) { void GlobalSearch::ProviderDestroyedSlot(QObject* object) { SearchProvider* provider = static_cast(object); - if (!providers_.contains(provider)) - return; + if (!providers_.contains(provider)) return; providers_.remove(provider); emit ProviderRemoved(provider); // We have to abort any pending searches since we can't tell whether they // were on this provider. - foreach (int id, pending_search_providers_.keys()) { - emit SearchFinished(id); - } + foreach(int id, pending_search_providers_.keys()) { emit SearchFinished(id); } pending_search_providers_.clear(); } @@ -201,7 +193,7 @@ QList GlobalSearch::providers() const { } int GlobalSearch::LoadArtAsync(const SearchProvider::Result& result) { - const int id = next_id_ ++; + const int id = next_id_++; pending_art_searches_[id] = result.pixmap_cache_key_; @@ -213,7 +205,7 @@ int GlobalSearch::LoadArtAsync(const SearchProvider::Result& result) { if (result.provider_->art_is_in_song_metadata()) { quint64 loader_id = app_->album_cover_loader()->LoadImageAsync( - cover_loader_options_, result.metadata_); + cover_loader_options_, result.metadata_); cover_loader_tasks_[loader_id] = id; } else if (providers_.contains(result.provider_) && result.provider_->wants_serialised_art()) { @@ -240,7 +232,7 @@ void GlobalSearch::TakeNextQueuedArt(SearchProvider* provider) { providers_[provider].queued_art_.isEmpty()) return; - const QueuedArt& data = providers_[provider].queued_art_.first(); + const QueuedArt& data = providers_[provider].queued_art_.first(); provider->LoadArtAsync(data.id_, data.result_); } @@ -250,14 +242,14 @@ void GlobalSearch::ArtLoadedSlot(int id, const QImage& image) { } void GlobalSearch::AlbumArtLoaded(quint64 id, const QImage& image) { - if (!cover_loader_tasks_.contains(id)) - return; + if (!cover_loader_tasks_.contains(id)) return; int orig_id = cover_loader_tasks_.take(id); HandleLoadedArt(orig_id, image, nullptr); } -void GlobalSearch::HandleLoadedArt(int id, const QImage& image, SearchProvider* provider) { +void GlobalSearch::HandleLoadedArt(int id, const QImage& image, + SearchProvider* provider) { const QString key = pending_art_searches_.take(id); QPixmap pixmap = QPixmap::fromImage(image); @@ -265,10 +257,9 @@ void GlobalSearch::HandleLoadedArt(int id, const QImage& image, SearchProvider* emit ArtLoaded(id, pixmap); - if (provider && - providers_.contains(provider) && + if (provider && providers_.contains(provider) && !providers_[provider].queued_art_.isEmpty()) { - providers_[provider].queued_art_.removeFirst(); + providers_[provider].queued_art_.removeFirst(); TakeNextQueuedArt(provider); } } @@ -288,7 +279,7 @@ MimeData* GlobalSearch::LoadTracks(const SearchProvider::ResultList& results) { SearchProvider* first_provider = results[0].provider_; SearchProvider::ResultList results_copy; - foreach (const SearchProvider::Result& result, results) { + foreach(const SearchProvider::Result & result, results) { if (result.provider_ == first_provider) { results_copy << result; } @@ -300,8 +291,7 @@ MimeData* GlobalSearch::LoadTracks(const SearchProvider::ResultList& results) { bool GlobalSearch::SetProviderEnabled(const SearchProvider* const_provider, bool enabled) { SearchProvider* provider = const_cast(const_provider); - if (!providers_.contains(provider)) - return true; + if (!providers_.contains(provider)) return true; if (providers_[provider].enabled_ != enabled) { // If we try to enable this provider but it is not logged in, don't change @@ -319,11 +309,11 @@ bool GlobalSearch::SetProviderEnabled(const SearchProvider* const_provider, return true; } -bool GlobalSearch::is_provider_enabled(const SearchProvider* const_provider) const { +bool GlobalSearch::is_provider_enabled(const SearchProvider* const_provider) + const { SearchProvider* provider = const_cast(const_provider); - if (!providers_.contains(provider)) - return false; + if (!providers_.contains(provider)) return false; return providers_[provider].enabled_; } @@ -335,10 +325,9 @@ void GlobalSearch::ReloadSettings() { QSettings s; s.beginGroup(kSettingsGroup); - foreach (SearchProvider* provider, providers_.keys()) { + foreach(SearchProvider * provider, providers_.keys()) { QVariant value = s.value("enabled_" + provider->id()); - if (!value.isValid()) - continue; + if (!value.isValid()) continue; const bool enabled = value.toBool(); if (enabled != providers_[provider].enabled_) { @@ -351,7 +340,7 @@ void GlobalSearch::ReloadSettings() { void GlobalSearch::SaveProvidersSettings() { QSettings s; s.beginGroup(kSettingsGroup); - foreach (SearchProvider* provider, providers_.keys()) { + foreach(SearchProvider * provider, providers_.keys()) { s.setValue("enabled_" + provider->id(), providers_[provider].enabled_); } } @@ -360,9 +349,9 @@ QStringList GlobalSearch::GetSuggestions(int count) { QStringList ret; // Get count suggestions from each provider - foreach (SearchProvider* provider, providers_.keys()) { + foreach(SearchProvider * provider, providers_.keys()) { if (is_provider_enabled(provider) && provider->can_give_suggestions()) { - foreach (QString suggestion, provider->GetSuggestions(count)) { + foreach(QString suggestion, provider->GetSuggestions(count)) { suggestion = suggestion.trimmed().toLower(); if (!suggestion.isEmpty()) { diff --git a/src/globalsearch/globalsearch.h b/src/globalsearch/globalsearch.h index d6ec36d48..53d644f28 100644 --- a/src/globalsearch/globalsearch.h +++ b/src/globalsearch/globalsearch.h @@ -31,7 +31,7 @@ class UrlSearchProvider; class GlobalSearch : public QObject { Q_OBJECT -public: + public: GlobalSearch(Application* app, QObject* parent = 0); static const int kDelayedSearchTimeoutMs; @@ -53,14 +53,15 @@ public: void CancelSearch(int id); void CancelArt(int id); - bool FindCachedPixmap(const SearchProvider::Result& result, QPixmap* pixmap) const; + bool FindCachedPixmap(const SearchProvider::Result& result, + QPixmap* pixmap) const; // "enabled" is the user preference. "usable" is enabled AND logged in. QList providers() const; bool is_provider_enabled(const SearchProvider* provider) const; bool is_provider_usable(SearchProvider* provider) const; -public slots: + public slots: void ReloadSettings(); signals: @@ -74,10 +75,10 @@ signals: void ProviderRemoved(const SearchProvider* provider); void ProviderToggled(const SearchProvider* provider, bool enabled); -protected: + protected: void timerEvent(QTimerEvent* e); -private slots: + private slots: void ResultsAvailableSlot(int id, SearchProvider::ResultList results); void SearchFinishedSlot(int id); @@ -86,7 +87,7 @@ private slots: void ProviderDestroyedSlot(QObject* object); -private: + private: void ConnectProvider(SearchProvider* provider); void HandleLoadedArt(int id, const QImage& image, SearchProvider* provider); void TakeNextQueuedArt(SearchProvider* provider); @@ -94,7 +95,7 @@ private: void SaveProvidersSettings(); -private: + private: struct DelayedSearch { int id_; QString query_; @@ -131,4 +132,4 @@ private: UrlSearchProvider* url_provider_; }; -#endif // GLOBALSEARCH_H +#endif // GLOBALSEARCH_H diff --git a/src/globalsearch/globalsearchitemdelegate.cpp b/src/globalsearch/globalsearchitemdelegate.cpp index bd5f8d763..b8a6f02fa 100644 --- a/src/globalsearch/globalsearchitemdelegate.cpp +++ b/src/globalsearch/globalsearchitemdelegate.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -19,14 +19,11 @@ #include "globalsearchview.h" GlobalSearchItemDelegate::GlobalSearchItemDelegate(GlobalSearchView* view) - : LibraryItemDelegate(view), - view_(view) -{ -} + : LibraryItemDelegate(view), view_(view) {} -void GlobalSearchItemDelegate::paint( - QPainter* painter, const QStyleOptionViewItem& option, - const QModelIndex& index) const { +void GlobalSearchItemDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { // Tell the view we painted this item so it can lazy load some art. const_cast(view_)->LazyLoadArt(index); diff --git a/src/globalsearch/globalsearchitemdelegate.h b/src/globalsearch/globalsearchitemdelegate.h index 72536a57d..f5c7d398a 100644 --- a/src/globalsearch/globalsearchitemdelegate.h +++ b/src/globalsearch/globalsearchitemdelegate.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -23,14 +23,14 @@ class GlobalSearchView; class GlobalSearchItemDelegate : public LibraryItemDelegate { -public: + public: GlobalSearchItemDelegate(GlobalSearchView* view); void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; -private: + private: GlobalSearchView* view_; }; -#endif // GLOBALSEARCHITEMDELEGATE_H +#endif // GLOBALSEARCHITEMDELEGATE_H diff --git a/src/globalsearch/globalsearchmodel.cpp b/src/globalsearch/globalsearchmodel.cpp index ca0aa6e58..3fa1611d8 100644 --- a/src/globalsearch/globalsearchmodel.cpp +++ b/src/globalsearch/globalsearchmodel.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -22,20 +22,19 @@ #include GlobalSearchModel::GlobalSearchModel(GlobalSearch* engine, QObject* parent) - : QStandardItemModel(parent), - engine_(engine), - proxy_(nullptr), - use_pretty_covers_(true), - artist_icon_(":/icons/22x22/x-clementine-artist.png"), - album_icon_(":/icons/22x22/x-clementine-album.png") -{ + : QStandardItemModel(parent), + engine_(engine), + proxy_(nullptr), + use_pretty_covers_(true), + artist_icon_(":/icons/22x22/x-clementine-artist.png"), + album_icon_(":/icons/22x22/x-clementine-album.png") { group_by_[0] = LibraryModel::GroupBy_Artist; group_by_[1] = LibraryModel::GroupBy_Album; group_by_[2] = LibraryModel::GroupBy_None; no_cover_icon_ = QPixmap(":nocover.png").scaled( - LibraryModel::kPrettyCoverSize, LibraryModel::kPrettyCoverSize, - Qt::KeepAspectRatio, Qt::SmoothTransformation); + LibraryModel::kPrettyCoverSize, LibraryModel::kPrettyCoverSize, + Qt::KeepAspectRatio, Qt::SmoothTransformation); } void GlobalSearchModel::AddResults(const SearchProvider::ResultList& results) { @@ -50,10 +49,11 @@ void GlobalSearchModel::AddResults(const SearchProvider::ResultList& results) { if (configured_index != -1) { sort_index = configured_index; } else { - sort_index = next_provider_sort_index_ ++; + sort_index = next_provider_sort_index_++; } - QStandardItem* divider = new QStandardItem(provider->icon(), provider->name()); + QStandardItem* divider = + new QStandardItem(provider->icon(), provider->name()); divider->setData(true, LibraryModel::Role_IsDivider); divider->setData(sort_index, Role_ProviderIndex); divider->setFlags(Qt::ItemIsEnabled); @@ -64,7 +64,7 @@ void GlobalSearchModel::AddResults(const SearchProvider::ResultList& results) { sort_index = provider_sort_indices_[provider]; } - foreach (const SearchProvider::Result& result, results) { + foreach(const SearchProvider::Result & result, results) { QStandardItem* parent = invisibleRootItem(); // Find (or create) the container nodes for this result if we can. @@ -85,8 +85,10 @@ void GlobalSearchModel::AddResults(const SearchProvider::ResultList& results) { } } -QStandardItem* GlobalSearchModel::BuildContainers( - const Song& s, QStandardItem* parent, ContainerKey* key, int level) { +QStandardItem* GlobalSearchModel::BuildContainers(const Song& s, + QStandardItem* parent, + ContainerKey* key, + int level) { if (level >= 3) { return parent; } @@ -99,60 +101,64 @@ QStandardItem* GlobalSearchModel::BuildContainers( int year = 0; switch (group_by_[level]) { - case LibraryModel::GroupBy_Artist: - if (s.is_compilation()) { - display_text = tr("Various artists"); - sort_text = "aaaaaa"; - } else { - display_text = LibraryModel::TextOrUnknown(s.artist()); - sort_text = LibraryModel::SortTextForArtist(s.artist()); - } - has_artist_icon = true; - break; + case LibraryModel::GroupBy_Artist: + if (s.is_compilation()) { + display_text = tr("Various artists"); + sort_text = "aaaaaa"; + } else { + display_text = LibraryModel::TextOrUnknown(s.artist()); + sort_text = LibraryModel::SortTextForArtist(s.artist()); + } + has_artist_icon = true; + break; - case LibraryModel::GroupBy_YearAlbum: - year = qMax(0, s.year()); - display_text = LibraryModel::PrettyYearAlbum(year, s.album()); - sort_text = LibraryModel::SortTextForYear(year) + s.album(); - unique_tag = s.album_id(); - has_album_icon = true; - break; + case LibraryModel::GroupBy_YearAlbum: + year = qMax(0, s.year()); + display_text = LibraryModel::PrettyYearAlbum(year, s.album()); + sort_text = LibraryModel::SortTextForYear(year) + s.album(); + unique_tag = s.album_id(); + has_album_icon = true; + break; - case LibraryModel::GroupBy_Year: - year = qMax(0, s.year()); - display_text = QString::number(year); - sort_text = LibraryModel::SortTextForYear(year) + " "; - break; + case LibraryModel::GroupBy_Year: + year = qMax(0, s.year()); + display_text = QString::number(year); + sort_text = LibraryModel::SortTextForYear(year) + " "; + break; - case LibraryModel::GroupBy_Composer: display_text = s.composer(); - case LibraryModel::GroupBy_Performer: display_text = s.performer(); - case LibraryModel::GroupBy_Grouping: display_text = s.grouping(); - case LibraryModel::GroupBy_Genre: if (display_text.isNull()) display_text = s.genre(); - case LibraryModel::GroupBy_Album: - unique_tag = s.album_id(); - if (display_text.isNull()) { - display_text = s.album(); - } + case LibraryModel::GroupBy_Composer: + display_text = s.composer(); + case LibraryModel::GroupBy_Performer: + display_text = s.performer(); + case LibraryModel::GroupBy_Grouping: + display_text = s.grouping(); + case LibraryModel::GroupBy_Genre: + if (display_text.isNull()) display_text = s.genre(); + case LibraryModel::GroupBy_Album: + unique_tag = s.album_id(); + if (display_text.isNull()) { + display_text = s.album(); + } // fallthrough - case LibraryModel::GroupBy_AlbumArtist: if (display_text.isNull()) display_text = s.effective_albumartist(); - display_text = LibraryModel::TextOrUnknown(display_text); - sort_text = LibraryModel::SortTextForArtist(display_text); - has_album_icon = true; - break; + case LibraryModel::GroupBy_AlbumArtist: + if (display_text.isNull()) display_text = s.effective_albumartist(); + display_text = LibraryModel::TextOrUnknown(display_text); + sort_text = LibraryModel::SortTextForArtist(display_text); + has_album_icon = true; + break; - case LibraryModel::GroupBy_FileType: - display_text = s.TextForFiletype(); - sort_text = display_text; - break; + case LibraryModel::GroupBy_FileType: + display_text = s.TextForFiletype(); + sort_text = display_text; + break; - case LibraryModel::GroupBy_Bitrate: - display_text = QString(s.bitrate(), 1); - sort_text = display_text; - break; - - case LibraryModel::GroupBy_None: - return parent; + case LibraryModel::GroupBy_Bitrate: + display_text = QString(s.bitrate(), 1); + sort_text = display_text; + break; + case LibraryModel::GroupBy_None: + return parent; } // Find a container for this level @@ -192,9 +198,7 @@ void GlobalSearchModel::Clear() { SearchProvider::ResultList GlobalSearchModel::GetChildResults( const QModelIndexList& indexes) const { QList items; - foreach (const QModelIndex& index, indexes) { - items << itemFromIndex(index); - } + foreach(const QModelIndex & index, indexes) { items << itemFromIndex(index); } return GetChildResults(items); } @@ -203,16 +207,16 @@ SearchProvider::ResultList GlobalSearchModel::GetChildResults( SearchProvider::ResultList results; QSet visited; - foreach (QStandardItem* item, items) { + foreach(QStandardItem * item, items) { GetChildResults(item, &results, &visited); } return results; } -void GlobalSearchModel::GetChildResults(const QStandardItem* item, - SearchProvider::ResultList* results, - QSet* visited) const { +void GlobalSearchModel::GetChildResults( + const QStandardItem* item, SearchProvider::ResultList* results, + QSet* visited) const { if (visited->contains(item)) { return; } @@ -224,7 +228,7 @@ void GlobalSearchModel::GetChildResults(const QStandardItem* item, // Yes - visit all the children, but do so through the proxy so we get them // in the right order. - for (int i=0 ; irowCount() ; ++i) { + for (int i = 0; i < item->rowCount(); ++i) { const QModelIndex proxy_index = parent_proxy_index.child(i, 0); const QModelIndex index = proxy_->mapToSource(proxy_index); GetChildResults(itemFromIndex(index), results, visited); @@ -244,11 +248,12 @@ void GatherResults(const QStandardItem* parent, QMap* results) { QVariant result_variant = parent->data(GlobalSearchModel::Role_Result); if (result_variant.isValid()) { - SearchProvider::Result result = result_variant.value(); + SearchProvider::Result result = + result_variant.value(); (*results)[result.provider_].append(result); } - for (int i=0 ; irowCount() ; ++i) { + for (int i = 0; i < parent->rowCount(); ++i) { GatherResults(parent->child(i), results); } } @@ -267,7 +272,7 @@ void GlobalSearchModel::SetGroupBy(const LibraryModel::Grouping& grouping, // Reset the model and re-add all the results using the new grouping. Clear(); - foreach (const SearchProvider::ResultList& result_list, results) { + foreach(const SearchProvider::ResultList & result_list, results) { AddResults(result_list); } } diff --git a/src/globalsearch/globalsearchmodel.h b/src/globalsearch/globalsearchmodel.h index 05c13ca10..cb286fdba 100644 --- a/src/globalsearch/globalsearchmodel.h +++ b/src/globalsearch/globalsearchmodel.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -30,14 +30,13 @@ class QSortFilterProxyModel; class GlobalSearchModel : public QStandardItemModel { Q_OBJECT -public: + public: GlobalSearchModel(GlobalSearch* engine, QObject* parent = 0); enum Role { Role_Result = LibraryModel::LastRole, Role_LazyLoadingArt, Role_ProviderIndex, - LastRole }; @@ -48,28 +47,32 @@ public: void set_proxy(QSortFilterProxyModel* proxy) { proxy_ = proxy; } void set_use_pretty_covers(bool pretty) { use_pretty_covers_ = pretty; } - void set_provider_order(const QStringList& provider_order) { provider_order_ = provider_order; } + void set_provider_order(const QStringList& provider_order) { + provider_order_ = provider_order; + } void SetGroupBy(const LibraryModel::Grouping& grouping, bool regroup_now); void Clear(); - SearchProvider::ResultList GetChildResults(const QModelIndexList& indexes) const; - SearchProvider::ResultList GetChildResults(const QList& items) const; + SearchProvider::ResultList GetChildResults(const QModelIndexList& indexes) + const; + SearchProvider::ResultList GetChildResults(const QList& items) + const; // QAbstractItemModel QMimeData* mimeData(const QModelIndexList& indexes) const; -public slots: + public slots: void AddResults(const SearchProvider::ResultList& results); -private: + private: QStandardItem* BuildContainers(const Song& metadata, QStandardItem* parent, ContainerKey* key, int level = 0); void GetChildResults(const QStandardItem* item, SearchProvider::ResultList* results, QSet* visited) const; - -private: + + private: GlobalSearch* engine_; QSortFilterProxyModel* proxy_; @@ -87,17 +90,15 @@ private: }; inline uint qHash(const GlobalSearchModel::ContainerKey& key) { - return qHash(key.provider_index_) - ^ qHash(key.group_[0]) - ^ qHash(key.group_[1]) - ^ qHash(key.group_[2]); + return qHash(key.provider_index_) ^ qHash(key.group_[0]) ^ + qHash(key.group_[1]) ^ qHash(key.group_[2]); } -inline bool operator <(const GlobalSearchModel::ContainerKey& left, - const GlobalSearchModel::ContainerKey& right) { - #define CMP(field) \ - if (left.field < right.field) return true; \ - if (left.field > right.field) return false +inline bool operator<(const GlobalSearchModel::ContainerKey& left, + const GlobalSearchModel::ContainerKey& right) { +#define CMP(field) \ + if (left.field < right.field) return true; \ + if (left.field > right.field) return false CMP(provider_index_); CMP(group_[0]); @@ -105,7 +106,7 @@ inline bool operator <(const GlobalSearchModel::ContainerKey& left, CMP(group_[2]); return false; - #undef CMP +#undef CMP } -#endif // GLOBALSEARCHMODEL_H +#endif // GLOBALSEARCHMODEL_H diff --git a/src/globalsearch/globalsearchsettingspage.cpp b/src/globalsearch/globalsearchsettingspage.cpp index ef137767b..ba32bd8e3 100644 --- a/src/globalsearch/globalsearchsettingspage.cpp +++ b/src/globalsearch/globalsearchsettingspage.cpp @@ -25,9 +25,7 @@ #include GlobalSearchSettingsPage::GlobalSearchSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui::GlobalSearchSettingsPage) -{ + : SettingsPage(dialog), ui_(new Ui::GlobalSearchSettingsPage) { ui_->setupUi(this); ui_->sources->header()->setResizeMode(0, QHeaderView::Stretch); @@ -38,12 +36,12 @@ GlobalSearchSettingsPage::GlobalSearchSettingsPage(SettingsDialog* dialog) connect(ui_->up, SIGNAL(clicked()), SLOT(MoveUp())); connect(ui_->down, SIGNAL(clicked()), SLOT(MoveDown())); connect(ui_->configure, SIGNAL(clicked()), SLOT(ConfigureProvider())); - connect(ui_->sources, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), + connect(ui_->sources, + SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), SLOT(CurrentProviderChanged(QTreeWidgetItem*))); } -GlobalSearchSettingsPage::~GlobalSearchSettingsPage() { -} +GlobalSearchSettingsPage::~GlobalSearchSettingsPage() {} static bool CompareProviderId(SearchProvider* left, SearchProvider* right) { return left->id() < right->id(); @@ -62,10 +60,12 @@ void GlobalSearchSettingsPage::Load() { // Add the ones in the configured list first ui_->sources->clear(); - foreach (const QString& id, s.value("provider_order", QStringList() << "library").toStringList()) { + foreach( + const QString & id, + s.value("provider_order", QStringList() << "library").toStringList()) { // Find a matching provider for this id for (QList::iterator it = providers.begin(); - it != providers.end() ; ++it) { + it != providers.end(); ++it) { if ((*it)->id() == id) { AddProviderItem(engine, *it); providers.erase(it); @@ -75,7 +75,7 @@ void GlobalSearchSettingsPage::Load() { } // Now add any others that are remaining - foreach (SearchProvider* provider, providers) { + foreach(SearchProvider * provider, providers) { AddProviderItem(engine, provider); } @@ -98,18 +98,18 @@ void GlobalSearchSettingsPage::AddProviderItem(GlobalSearch* engine, void GlobalSearchSettingsPage::UpdateLoggedInState(GlobalSearch* engine, QTreeWidgetItem* item, bool set_checked_state) { - SearchProvider* provider = item->data(0, Qt::UserRole).value(); + SearchProvider* provider = + item->data(0, Qt::UserRole).value(); const bool enabled = engine->is_provider_enabled(provider); const bool logged_in = provider->IsLoggedIn(); - Qt::CheckState check_state = logged_in && enabled ? Qt::Checked : Qt::Unchecked; + Qt::CheckState check_state = + logged_in && enabled ? Qt::Checked : Qt::Unchecked; Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; - if (logged_in) - flags |= Qt::ItemIsUserCheckable; + if (logged_in) flags |= Qt::ItemIsUserCheckable; - if (set_checked_state) - item->setData(0, Qt::CheckStateRole, check_state); + if (set_checked_state) item->setData(0, Qt::CheckStateRole, check_state); item->setFlags(flags); if (logged_in) { @@ -127,16 +127,17 @@ void GlobalSearchSettingsPage::Save() { QStringList provider_order; - for (int i=0 ; isources->invisibleRootItem()->childCount() ; ++i) { + for (int i = 0; i < ui_->sources->invisibleRootItem()->childCount(); ++i) { const QTreeWidgetItem* item = ui_->sources->invisibleRootItem()->child(i); - const SearchProvider* provider = item->data(0, Qt::UserRole).value(); + const SearchProvider* provider = + item->data(0, Qt::UserRole).value(); provider_order << provider->id(); // Only save the enabled state for this provider if it's logged in. if (item->flags() & Qt::ItemIsUserCheckable) { s.setValue("enabled_" + provider->id(), - item->data(0, Qt::CheckStateRole).toInt() == Qt::Checked); + item->data(0, Qt::CheckStateRole).toInt() == Qt::Checked); } } @@ -145,26 +146,20 @@ void GlobalSearchSettingsPage::Save() { s.setValue("show_suggestions", ui_->show_suggestions->isChecked()); } -void GlobalSearchSettingsPage::MoveUp() { - MoveCurrentItem(-1); -} +void GlobalSearchSettingsPage::MoveUp() { MoveCurrentItem(-1); } -void GlobalSearchSettingsPage::MoveDown() { - MoveCurrentItem(+1); -} +void GlobalSearchSettingsPage::MoveDown() { MoveCurrentItem(+1); } void GlobalSearchSettingsPage::MoveCurrentItem(int d) { QTreeWidgetItem* item = ui_->sources->currentItem(); - if (!item) - return; + if (!item) return; QTreeWidgetItem* root = ui_->sources->invisibleRootItem(); const int row = root->indexOfChild(item); const int new_row = qBound(0, row + d, root->childCount()); - if (row == new_row) - return; + if (row == new_row) return; root->removeChild(item); root->insertChild(new_row, item); @@ -174,19 +169,19 @@ void GlobalSearchSettingsPage::MoveCurrentItem(int d) { void GlobalSearchSettingsPage::ConfigureProvider() { QTreeWidgetItem* item = ui_->sources->currentItem(); - if (!item) - return; + if (!item) return; - SearchProvider* provider = item->data(0, Qt::UserRole).value(); + SearchProvider* provider = + item->data(0, Qt::UserRole).value(); provider->ShowConfig(); } void GlobalSearchSettingsPage::CurrentProviderChanged(QTreeWidgetItem* item) { - if (!item) - return; + if (!item) return; QTreeWidgetItem* root = ui_->sources->invisibleRootItem(); - SearchProvider* provider = item->data(0, Qt::UserRole).value(); + SearchProvider* provider = + item->data(0, Qt::UserRole).value(); const int row = root->indexOfChild(item); ui_->up->setEnabled(row != 0); @@ -199,9 +194,8 @@ void GlobalSearchSettingsPage::showEvent(QShowEvent* e) { // Update the logged-in state of each item when we come back to this page in // the dialog. - for (int i = 0 ; i < ui_->sources->invisibleRootItem()->childCount() ; ++i) { + for (int i = 0; i < ui_->sources->invisibleRootItem()->childCount(); ++i) { UpdateLoggedInState(dialog()->global_search(), - ui_->sources->invisibleRootItem()->child(i), - false); + ui_->sources->invisibleRootItem()->child(i), false); } } diff --git a/src/globalsearch/globalsearchsettingspage.h b/src/globalsearch/globalsearchsettingspage.h index 0ef0c08aa..d656a9646 100644 --- a/src/globalsearch/globalsearchsettingspage.h +++ b/src/globalsearch/globalsearchsettingspage.h @@ -32,33 +32,33 @@ class QTreeWidgetItem; class GlobalSearchSettingsPage : public SettingsPage { Q_OBJECT -public: + public: GlobalSearchSettingsPage(SettingsDialog* dialog); ~GlobalSearchSettingsPage(); void Load(); void Save(); -protected: + protected: void showEvent(QShowEvent* e); -private slots: + private slots: void MoveUp(); void MoveDown(); void ConfigureProvider(); void CurrentProviderChanged(QTreeWidgetItem* item); -private: + private: void AddProviderItem(GlobalSearch* engine, SearchProvider* provider); void UpdateLoggedInState(GlobalSearch* engine, QTreeWidgetItem* item, bool set_checked_state); void MoveCurrentItem(int d); -private: + private: QScopedPointer ui_; QIcon warning_icon_; }; -#endif // GLOBALSEARCHSETTINGSPAGE_H +#endif // GLOBALSEARCHSETTINGSPAGE_H diff --git a/src/globalsearch/globalsearchsortmodel.cpp b/src/globalsearch/globalsearchsortmodel.cpp index 9e2758cdc..9a19899f4 100644 --- a/src/globalsearch/globalsearchsortmodel.cpp +++ b/src/globalsearch/globalsearchsortmodel.cpp @@ -21,49 +21,53 @@ #include "core/logging.h" GlobalSearchSortModel::GlobalSearchSortModel(QObject* parent) - : QSortFilterProxyModel(parent) -{ -} + : QSortFilterProxyModel(parent) {} -bool GlobalSearchSortModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { +bool GlobalSearchSortModel::lessThan(const QModelIndex& left, + const QModelIndex& right) const { // Compare the provider sort index first. - const int index_left = left.data(GlobalSearchModel::Role_ProviderIndex).toInt(); - const int index_right = right.data(GlobalSearchModel::Role_ProviderIndex).toInt(); + const int index_left = + left.data(GlobalSearchModel::Role_ProviderIndex).toInt(); + const int index_right = + right.data(GlobalSearchModel::Role_ProviderIndex).toInt(); if (index_left < index_right) return true; if (index_left > index_right) return false; // Dividers always go first - if (left.data(LibraryModel::Role_IsDivider).toBool()) return true; + if (left.data(LibraryModel::Role_IsDivider).toBool()) return true; if (right.data(LibraryModel::Role_IsDivider).toBool()) return false; // Containers go before songs if they're at the same level - const bool left_is_container = left.data(LibraryModel::Role_ContainerType).isValid(); - const bool right_is_container = right.data(LibraryModel::Role_ContainerType).isValid(); + const bool left_is_container = + left.data(LibraryModel::Role_ContainerType).isValid(); + const bool right_is_container = + right.data(LibraryModel::Role_ContainerType).isValid(); if (left_is_container && !right_is_container) return true; if (right_is_container && !left_is_container) return false; // Containers get sorted on their sort text. if (left_is_container) { return QString::localeAwareCompare( - left.data(LibraryModel::Role_SortText).toString(), - right.data(LibraryModel::Role_SortText).toString()) < 0; + left.data(LibraryModel::Role_SortText).toString(), + right.data(LibraryModel::Role_SortText).toString()) < 0; } // Otherwise we're comparing songs. Sort by disc, track, then title. - const SearchProvider::Result r1 = left.data(GlobalSearchModel::Role_Result) - .value(); + const SearchProvider::Result r1 = + left.data(GlobalSearchModel::Role_Result).value(); const SearchProvider::Result r2 = right.data(GlobalSearchModel::Role_Result) - .value(); + .value(); -#define CompareInt(field) \ +#define CompareInt(field) \ if (r1.metadata_.field() < r2.metadata_.field()) return true; \ if (r1.metadata_.field() > r2.metadata_.field()) return false int ret = 0; -#define CompareString(field) \ - ret = QString::localeAwareCompare(r1.metadata_.field(), r2.metadata_.field()); \ - if (ret < 0) return true; \ +#define CompareString(field) \ + ret = \ + QString::localeAwareCompare(r1.metadata_.field(), r2.metadata_.field()); \ + if (ret < 0) return true; \ if (ret > 0) return false CompareInt(disc); diff --git a/src/globalsearch/globalsearchsortmodel.h b/src/globalsearch/globalsearchsortmodel.h index b66de2f4e..19a5cedee 100644 --- a/src/globalsearch/globalsearchsortmodel.h +++ b/src/globalsearch/globalsearchsortmodel.h @@ -21,11 +21,11 @@ #include class GlobalSearchSortModel : public QSortFilterProxyModel { -public: + public: GlobalSearchSortModel(QObject* parent = 0); -protected: + protected: bool lessThan(const QModelIndex& left, const QModelIndex& right) const; }; -#endif // GLOBALSEARCHSORTMODEL_H +#endif // GLOBALSEARCHSORTMODEL_H diff --git a/src/globalsearch/globalsearchview.cpp b/src/globalsearch/globalsearchview.cpp index 7314e588a..9302f2c33 100644 --- a/src/globalsearch/globalsearchview.cpp +++ b/src/globalsearch/globalsearchview.cpp @@ -48,25 +48,24 @@ const int GlobalSearchView::kMaxSuggestions = 10; const int GlobalSearchView::kUpdateSuggestionsTimeoutMsec = 60 * kMsecPerSec; GlobalSearchView::GlobalSearchView(Application* app, QWidget* parent) - : QWidget(parent), - app_(app), - engine_(app_->global_search()), - ui_(new Ui_GlobalSearchView), - context_menu_(nullptr), - last_search_id_(0), - front_model_(new GlobalSearchModel(engine_, this)), - back_model_(new GlobalSearchModel(engine_, this)), - current_model_(front_model_), - front_proxy_(new GlobalSearchSortModel(this)), - back_proxy_(new GlobalSearchSortModel(this)), - current_proxy_(front_proxy_), - swap_models_timer_(new QTimer(this)), - update_suggestions_timer_(new QTimer(this)), - search_icon_(IconLoader::Load("search")), - warning_icon_(IconLoader::Load("dialog-warning")), - show_providers_(true), - show_suggestions_(true) -{ + : QWidget(parent), + app_(app), + engine_(app_->global_search()), + ui_(new Ui_GlobalSearchView), + context_menu_(nullptr), + last_search_id_(0), + front_model_(new GlobalSearchModel(engine_, this)), + back_model_(new GlobalSearchModel(engine_, this)), + current_model_(front_model_), + front_proxy_(new GlobalSearchSortModel(this)), + back_proxy_(new GlobalSearchSortModel(this)), + current_proxy_(front_proxy_), + swap_models_timer_(new QTimer(this)), + update_suggestions_timer_(new QTimer(this)), + search_icon_(IconLoader::Load("search")), + warning_icon_(IconLoader::Load("dialog-warning")), + show_providers_(true), + show_suggestions_(true) { ui_->setupUi(this); front_model_->set_proxy(front_proxy_); @@ -78,11 +77,14 @@ GlobalSearchView::GlobalSearchView(Application* app, QWidget* parent) ui_->settings->setIcon(IconLoader::Load("configure")); // Must be a queued connection to ensure the GlobalSearch handles it first. - connect(app_, SIGNAL(SettingsChanged()), SLOT(ReloadSettings()), Qt::QueuedConnection); + connect(app_, SIGNAL(SettingsChanged()), SLOT(ReloadSettings()), + Qt::QueuedConnection); connect(ui_->search, SIGNAL(textChanged(QString)), SLOT(TextEdited(QString))); - connect(ui_->results, SIGNAL(AddToPlaylistSignal(QMimeData*)), SIGNAL(AddToPlaylist(QMimeData*))); - connect(ui_->results, SIGNAL(FocusOnFilterSignal(QKeyEvent*)), SLOT(FocusOnFilter(QKeyEvent*))); + connect(ui_->results, SIGNAL(AddToPlaylistSignal(QMimeData*)), + SIGNAL(AddToPlaylist(QMimeData*))); + connect(ui_->results, SIGNAL(FocusOnFilterSignal(QKeyEvent*)), + SLOT(FocusOnFilter(QKeyEvent*))); // Set the appearance of the results list ui_->results->setItemDelegate(new GlobalSearchItemDelegate(this)); @@ -101,15 +103,17 @@ GlobalSearchView::GlobalSearchView(Application* app, QWidget* parent) // Set the colour of the help text to the disabled text colour QPalette help_palette = ui_->help_text->palette(); - const QColor help_color = help_palette.color(QPalette::Disabled, QPalette::Text); + const QColor help_color = + help_palette.color(QPalette::Disabled, QPalette::Text); help_palette.setColor(QPalette::Normal, QPalette::Text, help_color); help_palette.setColor(QPalette::Inactive, QPalette::Text, help_color); ui_->help_text->setPalette(help_palette); // Create suggestion widgets - for (int i=0 ; iaddWidget(widget); suggestion_widgets_ << widget; } @@ -133,7 +137,8 @@ GlobalSearchView::GlobalSearchView(Application* app, QWidget* parent) connect(swap_models_timer_, SIGNAL(timeout()), SLOT(SwapModels())); update_suggestions_timer_->setInterval(kUpdateSuggestionsTimeoutMsec); - connect(update_suggestions_timer_, SIGNAL(timeout()), SLOT(UpdateSuggestions())); + connect(update_suggestions_timer_, SIGNAL(timeout()), + SLOT(UpdateSuggestions())); // Add actions to the settings menu group_by_actions_ = LibraryFilterWidget::CreateGroupByActions(this); @@ -141,41 +146,41 @@ GlobalSearchView::GlobalSearchView(Application* app, QWidget* parent) settings_menu->addActions(group_by_actions_->actions()); settings_menu->addSeparator(); settings_menu->addAction(IconLoader::Load("configure"), - tr("Configure global search..."), this, SLOT(OpenSettingsDialog())); + tr("Configure global search..."), this, + SLOT(OpenSettingsDialog())); ui_->settings->setMenu(settings_menu); - connect(group_by_actions_, SIGNAL(triggered(QAction*)), SLOT(GroupByClicked(QAction*))); + connect(group_by_actions_, SIGNAL(triggered(QAction*)), + SLOT(GroupByClicked(QAction*))); // These have to be queued connections because they may get emitted before // our call to Search() (or whatever) returns and we add the ID to the map. - connect(engine_, SIGNAL(ResultsAvailable(int,SearchProvider::ResultList)), - SLOT(AddResults(int,SearchProvider::ResultList)), - Qt::QueuedConnection); - connect(engine_, SIGNAL(ArtLoaded(int,QPixmap)), SLOT(ArtLoaded(int,QPixmap)), + connect(engine_, SIGNAL(ResultsAvailable(int, SearchProvider::ResultList)), + SLOT(AddResults(int, SearchProvider::ResultList)), Qt::QueuedConnection); + connect(engine_, SIGNAL(ArtLoaded(int, QPixmap)), + SLOT(ArtLoaded(int, QPixmap)), Qt::QueuedConnection); } -GlobalSearchView::~GlobalSearchView() { - delete ui_; -} +GlobalSearchView::~GlobalSearchView() { delete ui_; } namespace { - bool CompareProvider(const QStringList& provider_order, - SearchProvider* left, SearchProvider* right) { - const int left_index = provider_order.indexOf(left->id()); - const int right_index = provider_order.indexOf(right->id()); - if (left_index == -1 && right_index == -1) { - // None are in our provider list: compare name instead - return left->name() < right->name(); - } else if (left_index == -1) { - // Left provider not in provider list - return false; - } else if (right_index == -1) { - // Right provider not in provider list - return true; - } - return left_index < right_index; +bool CompareProvider(const QStringList& provider_order, SearchProvider* left, + SearchProvider* right) { + const int left_index = provider_order.indexOf(left->id()); + const int right_index = provider_order.indexOf(right->id()); + if (left_index == -1 && right_index == -1) { + // None are in our provider list: compare name instead + return left->name() < right->name(); + } else if (left_index == -1) { + // Left provider not in provider list + return false; + } else if (right_index == -1) { + // Right provider not in provider list + return true; } + return left_index < right_index; +} } void GlobalSearchView::ReloadSettings() { @@ -197,9 +202,12 @@ void GlobalSearchView::ReloadSettings() { show_providers_ = s.value("show_providers", true).toBool(); show_suggestions_ = s.value("show_suggestions", true).toBool(); SetGroupBy(LibraryModel::Grouping( - LibraryModel::GroupBy(s.value("group_by1", int(LibraryModel::GroupBy_Artist)).toInt()), - LibraryModel::GroupBy(s.value("group_by2", int(LibraryModel::GroupBy_Album)).toInt()), - LibraryModel::GroupBy(s.value("group_by3", int(LibraryModel::GroupBy_None)).toInt()))); + LibraryModel::GroupBy( + s.value("group_by1", int(LibraryModel::GroupBy_Artist)).toInt()), + LibraryModel::GroupBy( + s.value("group_by2", int(LibraryModel::GroupBy_Album)).toInt()), + LibraryModel::GroupBy( + s.value("group_by3", int(LibraryModel::GroupBy_None)).toInt()))); s.endGroup(); // Delete any old status widgets @@ -217,7 +225,7 @@ void GlobalSearchView::ReloadSettings() { bool any_disabled = false; - foreach (SearchProvider* provider, providers) { + foreach(SearchProvider * provider, providers) { QWidget* parent = ui_->enabled_list; if (!engine_->is_provider_usable(provider)) { parent = ui_->disabled_list; @@ -243,12 +251,12 @@ void GlobalSearchView::ReloadSettings() { void GlobalSearchView::UpdateSuggestions() { const QStringList suggestions = engine_->GetSuggestions(kMaxSuggestions); - for (int i=0 ; iSetText(suggestions[i]); suggestion_widgets_[i]->show(); } - for (int i=suggestions.count() ; ihide(); } } @@ -281,9 +289,9 @@ void GlobalSearchView::TextEdited(const QString& text) { } } -void GlobalSearchView::AddResults(int id, const SearchProvider::ResultList& results) { - if (id != last_search_id_ || results.isEmpty()) - return; +void GlobalSearchView::AddResults(int id, + const SearchProvider::ResultList& results) { + if (id != last_search_id_ || results.isEmpty()) return; current_model_->AddResults(results); } @@ -320,7 +328,7 @@ void GlobalSearchView::LazyLoadArt(const QModelIndex& proxy_index) { // Is this an album? const LibraryModel::GroupBy container_type = LibraryModel::GroupBy( - proxy_index.data(LibraryModel::Role_ContainerType).toInt()); + proxy_index.data(LibraryModel::Role_ContainerType).toInt()); if (container_type != LibraryModel::GroupBy_Album && container_type != LibraryModel::GroupBy_AlbumArtist && container_type != LibraryModel::GroupBy_YearAlbum) { @@ -339,7 +347,8 @@ void GlobalSearchView::LazyLoadArt(const QModelIndex& proxy_index) { // Get the track's Result const SearchProvider::Result result = - item->data(GlobalSearchModel::Role_Result).value(); + item->data(GlobalSearchModel::Role_Result) + .value(); // Load the art. int id = engine_->LoadArtAsync(result); @@ -347,8 +356,7 @@ void GlobalSearchView::LazyLoadArt(const QModelIndex& proxy_index) { } void GlobalSearchView::ArtLoaded(int id, const QPixmap& pixmap) { - if (!art_requests_.contains(id)) - return; + if (!art_requests_.contains(id)) return; QModelIndex index = art_requests_.take(id); if (!pixmap.isNull()) { @@ -357,15 +365,14 @@ void GlobalSearchView::ArtLoaded(int id, const QPixmap& pixmap) { } MimeData* GlobalSearchView::SelectedMimeData() { - if (!ui_->results->selectionModel()) - return nullptr; + if (!ui_->results->selectionModel()) return nullptr; // Get all selected model indexes QModelIndexList indexes = ui_->results->selectionModel()->selectedRows(); if (indexes.isEmpty()) { // There's nothing selected - take the first thing in the model that isn't // a divider. - for (int i=0 ; irowCount() ; ++i) { + for (int i = 0; i < front_proxy_->rowCount(); ++i) { QModelIndex index = front_proxy_->index(i, 0); if (!index.data(LibraryModel::Role_IsDivider).toBool()) { indexes << index; @@ -382,7 +389,7 @@ MimeData* GlobalSearchView::SelectedMimeData() { // Get items for these indexes QList items; - foreach (const QModelIndex& index, indexes) { + foreach(const QModelIndex & index, indexes) { items << (front_model_->itemFromIndex(front_proxy_->mapToSource(index))); } @@ -395,7 +402,8 @@ bool GlobalSearchView::eventFilter(QObject* object, QEvent* event) { if (SearchKeyEvent(static_cast(event))) { return true; } - } else if (object == ui_->results_stack && event->type() == QEvent::ContextMenu) { + } else if (object == ui_->results_stack && + event->type() == QEvent::ContextMenu) { if (ResultsContextMenuEvent(static_cast(event))) { return true; } @@ -406,24 +414,24 @@ bool GlobalSearchView::eventFilter(QObject* object, QEvent* event) { bool GlobalSearchView::SearchKeyEvent(QKeyEvent* event) { switch (event->key()) { - case Qt::Key_Up: - ui_->results->UpAndFocus(); - break; + case Qt::Key_Up: + ui_->results->UpAndFocus(); + break; - case Qt::Key_Down: - ui_->results->DownAndFocus(); - break; + case Qt::Key_Down: + ui_->results->DownAndFocus(); + break; - case Qt::Key_Escape: - ui_->search->clear(); - break; + case Qt::Key_Escape: + ui_->search->clear(); + break; - case Qt::Key_Return: - AddSelectedToPlaylist(); - break; + case Qt::Key_Return: + AddSelectedToPlaylist(); + break; - default: - return false; + default: + return false; } event->accept(); @@ -433,28 +441,37 @@ bool GlobalSearchView::SearchKeyEvent(QKeyEvent* event) { bool GlobalSearchView::ResultsContextMenuEvent(QContextMenuEvent* event) { if (!context_menu_) { context_menu_ = new QMenu(this); - context_actions_ << context_menu_->addAction(IconLoader::Load("media-playback-start"), - tr("Append to current playlist"), this, SLOT(AddSelectedToPlaylist())); - context_actions_ << context_menu_->addAction(IconLoader::Load("media-playback-start"), - tr("Replace current playlist"), this, SLOT(LoadSelected())); - context_actions_ << context_menu_->addAction(IconLoader::Load("document-new"), - tr("Open in new playlist"), this, SLOT(OpenSelectedInNewPlaylist())); + context_actions_ << context_menu_->addAction( + IconLoader::Load("media-playback-start"), + tr("Append to current playlist"), this, + SLOT(AddSelectedToPlaylist())); + context_actions_ << context_menu_->addAction( + IconLoader::Load("media-playback-start"), + tr("Replace current playlist"), this, + SLOT(LoadSelected())); + context_actions_ << context_menu_->addAction( + IconLoader::Load("document-new"), + tr("Open in new playlist"), this, + SLOT(OpenSelectedInNewPlaylist())); context_menu_->addSeparator(); - context_actions_ << context_menu_->addAction(IconLoader::Load("go-next"), - tr("Queue track"), this, SLOT(AddSelectedToPlaylistEnqueue())); + context_actions_ << context_menu_->addAction( + IconLoader::Load("go-next"), tr("Queue track"), + this, SLOT(AddSelectedToPlaylistEnqueue())); context_menu_->addSeparator(); - context_menu_->addMenu(tr("Group by"))->addActions(group_by_actions_->actions()); + context_menu_->addMenu(tr("Group by")) + ->addActions(group_by_actions_->actions()); context_menu_->addAction(IconLoader::Load("configure"), - tr("Configure global search..."), this, SLOT(OpenSettingsDialog())); + tr("Configure global search..."), this, + SLOT(OpenSettingsDialog())); } const bool enable_context_actions = ui_->results->selectionModel() && ui_->results->selectionModel()->hasSelection(); - foreach (QAction* action, context_actions_) { + foreach(QAction * action, context_actions_) { action->setEnabled(enable_context_actions); } @@ -469,8 +486,7 @@ void GlobalSearchView::AddSelectedToPlaylist() { void GlobalSearchView::LoadSelected() { MimeData* data = SelectedMimeData(); - if (!data) - return; + if (!data) return; data->clear_first_ = true; emit AddToPlaylist(data); @@ -478,8 +494,7 @@ void GlobalSearchView::LoadSelected() { void GlobalSearchView::AddSelectedToPlaylistEnqueue() { MimeData* data = SelectedMimeData(); - if (!data) - return; + if (!data) return; data->enqueue_now_ = true; emit AddToPlaylist(data); @@ -487,8 +502,7 @@ void GlobalSearchView::AddSelectedToPlaylistEnqueue() { void GlobalSearchView::OpenSelectedInNewPlaylist() { MimeData* data = SelectedMimeData(); - if (!data) - return; + if (!data) return; data->open_in_new_playlist_ = true; emit AddToPlaylist(data); @@ -551,9 +565,8 @@ void GlobalSearchView::SetGroupBy(const LibraryModel::Grouping& g) { s.setValue("group_by3", int(g.third)); // Make sure the correct action is checked. - foreach (QAction* action, group_by_actions_->actions()) { - if (action->property("group_by").isNull()) - continue; + foreach(QAction * action, group_by_actions_->actions()) { + if (action->property("group_by").isNull()) continue; if (g == action->property("group_by").value()) { action->setChecked(true); diff --git a/src/globalsearch/globalsearchview.h b/src/globalsearch/globalsearchview.h index 6a0e963c8..41d9d0186 100644 --- a/src/globalsearch/globalsearchview.h +++ b/src/globalsearch/globalsearchview.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -39,8 +39,8 @@ class QStandardItemModel; class GlobalSearchView : public QWidget { Q_OBJECT - -public: + + public: GlobalSearchView(Application* app, QWidget* parent = 0); ~GlobalSearchView(); @@ -58,7 +58,7 @@ public: // QObject bool eventFilter(QObject* object, QEvent* event); -public slots: + public slots: void ReloadSettings(); void StartSearch(const QString& query); void FocusSearchField(); @@ -67,7 +67,7 @@ public slots: signals: void AddToPlaylist(QMimeData* data); -private slots: + private slots: void UpdateSuggestions(); void SwapModels(); @@ -85,13 +85,13 @@ private slots: void GroupByClicked(QAction* action); void SetGroupBy(const LibraryModel::Grouping& grouping); -private: + private: MimeData* SelectedMimeData(); bool SearchKeyEvent(QKeyEvent* event); bool ResultsContextMenuEvent(QContextMenuEvent* event); - -private: + + private: Application* app_; GlobalSearch* engine_; Ui_GlobalSearchView* ui_; @@ -125,9 +125,9 @@ private: QIcon search_icon_; QIcon warning_icon_; - + bool show_providers_; bool show_suggestions_; }; -#endif // GLOBALSEARCHVIEW_H +#endif // GLOBALSEARCHVIEW_H diff --git a/src/globalsearch/groovesharksearchprovider.cpp b/src/globalsearch/groovesharksearchprovider.cpp index 2c1ee44ee..24b9206fd 100644 --- a/src/globalsearch/groovesharksearchprovider.cpp +++ b/src/globalsearch/groovesharksearchprovider.cpp @@ -24,17 +24,15 @@ #include "covers/albumcoverloader.h" #include "internet/groovesharkservice.h" -GroovesharkSearchProvider::GroovesharkSearchProvider(Application* app, QObject* parent) - : SearchProvider(app, parent), - service_(nullptr) -{ -} +GroovesharkSearchProvider::GroovesharkSearchProvider(Application* app, + QObject* parent) + : SearchProvider(app, parent), service_(nullptr) {} void GroovesharkSearchProvider::Init(GroovesharkService* service) { service_ = service; - SearchProvider::Init("Grooveshark", "grooveshark", - QIcon(":providers/grooveshark.png"), - WantsDelayedQueries | ArtIsProbablyRemote | CanShowConfig); + SearchProvider::Init( + "Grooveshark", "grooveshark", QIcon(":providers/grooveshark.png"), + WantsDelayedQueries | ArtIsProbablyRemote | CanShowConfig); connect(service_, SIGNAL(SimpleSearchResults(int, SongList)), SLOT(SearchDone(int, SongList))); @@ -47,14 +45,14 @@ void GroovesharkSearchProvider::Init(GroovesharkService* service) { cover_loader_options_.pad_output_image_ = true; cover_loader_options_.scale_output_image_ = true; - connect(app_->album_cover_loader(), - SIGNAL(ImageLoaded(quint64, QImage)), + connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)), SLOT(AlbumArtLoaded(quint64, QImage))); } void GroovesharkSearchProvider::SearchAsync(int id, const QString& query) { const int service_id = service_->SimpleSearch(query); - pending_searches_[service_id] = PendingState(id, TokenizeQuery(query));; + pending_searches_[service_id] = PendingState(id, TokenizeQuery(query)); + ; const int album_id = service_->SearchAlbums(query); pending_searches_[album_id] = PendingState(id, TokenizeQuery(query)); @@ -66,7 +64,7 @@ void GroovesharkSearchProvider::SearchDone(int id, const SongList& songs) { const int global_search_id = state.orig_id_; ResultList ret; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { Result result(this); result.metadata_ = song; @@ -77,7 +75,8 @@ void GroovesharkSearchProvider::SearchDone(int id, const SongList& songs) { MaybeSearchFinished(global_search_id); } -void GroovesharkSearchProvider::AlbumSearchResult(int id, const QList& albums_ids) { +void GroovesharkSearchProvider::AlbumSearchResult( + int id, const QList& albums_ids) { // Map back to the original id. const PendingState state = pending_searches_.take(id); const int global_search_id = state.orig_id_; @@ -85,10 +84,9 @@ void GroovesharkSearchProvider::AlbumSearchResult(int id, const QList& MaybeSearchFinished(global_search_id); return; } - foreach (const quint64 album_id, albums_ids) { + foreach(const quint64 album_id, albums_ids) { pending_searches_[album_id] = PendingState(global_search_id, QStringList()); } - } void GroovesharkSearchProvider::MaybeSearchFinished(int id) { @@ -97,14 +95,14 @@ void GroovesharkSearchProvider::MaybeSearchFinished(int id) { } } - void GroovesharkSearchProvider::LoadArtAsync(int id, const Result& result) { quint64 loader_id = app_->album_cover_loader()->LoadImageAsync( - cover_loader_options_, result.metadata_); + cover_loader_options_, result.metadata_); cover_loader_tasks_[loader_id] = id; } -void GroovesharkSearchProvider::AlbumArtLoaded(quint64 id, const QImage& image) { +void GroovesharkSearchProvider::AlbumArtLoaded(quint64 id, + const QImage& image) { if (!cover_loader_tasks_.contains(id)) { return; } @@ -116,15 +114,14 @@ bool GroovesharkSearchProvider::IsLoggedIn() { return (service_ && service_->IsLoggedIn()); } -void GroovesharkSearchProvider::ShowConfig() { - service_->ShowConfig(); -} +void GroovesharkSearchProvider::ShowConfig() { service_->ShowConfig(); } -void GroovesharkSearchProvider::AlbumSongsLoaded(quint64 id, const SongList& songs) { +void GroovesharkSearchProvider::AlbumSongsLoaded(quint64 id, + const SongList& songs) { const PendingState state = pending_searches_.take(id); const int global_search_id = state.orig_id_; ResultList ret; - foreach (const Song& s, songs) { + foreach(const Song & s, songs) { Result result(this); result.metadata_ = s; ret << result; diff --git a/src/globalsearch/icecastsearchprovider.cpp b/src/globalsearch/icecastsearchprovider.cpp index ace22a63e..a0ad688e7 100644 --- a/src/globalsearch/icecastsearchprovider.cpp +++ b/src/globalsearch/icecastsearchprovider.cpp @@ -20,19 +20,18 @@ IcecastSearchProvider::IcecastSearchProvider(IcecastBackend* backend, Application* app, QObject* parent) - : BlockingSearchProvider(app, parent), - backend_(backend) -{ - Init("Icecast", "icecast", QIcon(":last.fm/icon_radio.png"), DisabledByDefault); + : BlockingSearchProvider(app, parent), backend_(backend) { + Init("Icecast", "icecast", QIcon(":last.fm/icon_radio.png"), + DisabledByDefault); } -SearchProvider::ResultList IcecastSearchProvider::Search(int id, const QString& query) { +SearchProvider::ResultList IcecastSearchProvider::Search(int id, + const QString& query) { IcecastBackend::StationList stations = backend_->GetStations(query); ResultList ret; - foreach (const IcecastBackend::Station& station, stations) { - if (ret.count() > 3) - break; + foreach(const IcecastBackend::Station & station, stations) { + if (ret.count() > 3) break; Result result(this); result.group_automatically_ = false; diff --git a/src/globalsearch/icecastsearchprovider.h b/src/globalsearch/icecastsearchprovider.h index c9b3a775e..f8350dbcb 100644 --- a/src/globalsearch/icecastsearchprovider.h +++ b/src/globalsearch/icecastsearchprovider.h @@ -22,15 +22,15 @@ class IcecastBackend; - class IcecastSearchProvider : public BlockingSearchProvider { -public: - IcecastSearchProvider(IcecastBackend* backend, Application* app, QObject* parent); + public: + IcecastSearchProvider(IcecastBackend* backend, Application* app, + QObject* parent); ResultList Search(int id, const QString& query); -private: + private: IcecastBackend* backend_; }; -#endif // ICECASTSEARCHPROVIDER_H +#endif // ICECASTSEARCHPROVIDER_H diff --git a/src/globalsearch/lastfmsearchprovider.cpp b/src/globalsearch/lastfmsearchprovider.cpp index 200814710..4634918aa 100644 --- a/src/globalsearch/lastfmsearchprovider.cpp +++ b/src/globalsearch/lastfmsearchprovider.cpp @@ -19,24 +19,22 @@ #include "core/logging.h" #include "internet/lastfmservice.h" - LastFMSearchProvider::LastFMSearchProvider(LastFMService* service, Application* app, QObject* parent) - : SimpleSearchProvider(app, parent), - service_(service) { + : SimpleSearchProvider(app, parent), service_(service) { Init("Last.fm", "lastfm", QIcon(":last.fm/as.png"), CanShowConfig | CanGiveSuggestions); icon_ = ScaleAndPad(QImage(":last.fm/as.png")); - set_safe_words(QStringList() << "lastfm" << "last.fm"); + set_safe_words(QStringList() << "lastfm" + << "last.fm"); set_max_suggestion_count(3); connect(service, SIGNAL(SavedItemsChanged()), SLOT(MaybeRecreateItems())); // Load the friends list on startup only if it doesn't involve going to update // info from the server. - if (!service_->IsFriendsListStale()) - RecreateItems(); + if (!service_->IsFriendsListStale()) RecreateItems(); } void LastFMSearchProvider::LoadArtAsync(int id, const Result& result) { @@ -52,8 +50,8 @@ void LastFMSearchProvider::RecreateItems() { QUrl("lastfm://user/USERNAME/recommended"), "recommended"); items << Item(tr("My Last.fm Library"), QUrl("lastfm://user/USERNAME/library"), "radio"); - items << Item(tr("My Last.fm Mix Radio"), - QUrl("lastfm://user/USERNAME/mix"), "mix"); + items << Item(tr("My Last.fm Mix Radio"), QUrl("lastfm://user/USERNAME/mix"), + "mix"); items << Item(tr("My Last.fm Neighborhood"), QUrl("lastfm://user/USERNAME/neighbours"), "neighborhood"); @@ -61,17 +59,17 @@ void LastFMSearchProvider::RecreateItems() { const QStringList tags = service_->SavedTagRadioNames(); const QStringList friends = service_->FriendNames(); - foreach (const QString& name, artists) { + foreach(const QString & name, artists) { items << Item(tr(LastFMService::kTitleArtist).arg(name), QUrl(QString(LastFMService::kUrlArtist).arg(name)), name); } - foreach (const QString& name, tags) { + foreach(const QString & name, tags) { items << Item(tr(LastFMService::kTitleTag).arg(name), QUrl(QString(LastFMService::kUrlTag).arg(name)), name); } - foreach (const QString& name, friends) { + foreach(const QString & name, friends) { items << Item(tr("Last.fm Radio Station - %1").arg(name), QUrl("lastfm://user/" + name + "/library"), name); items << Item(tr("Last.fm Mix Radio - %1").arg(name), @@ -83,10 +81,6 @@ void LastFMSearchProvider::RecreateItems() { SetItems(items); } -bool LastFMSearchProvider::IsLoggedIn() { - return service_->IsAuthenticated(); -} +bool LastFMSearchProvider::IsLoggedIn() { return service_->IsAuthenticated(); } -void LastFMSearchProvider::ShowConfig() { - service_->ShowConfig(); -} +void LastFMSearchProvider::ShowConfig() { service_->ShowConfig(); } diff --git a/src/globalsearch/lastfmsearchprovider.h b/src/globalsearch/lastfmsearchprovider.h index 849bb1a0f..a71d01584 100644 --- a/src/globalsearch/lastfmsearchprovider.h +++ b/src/globalsearch/lastfmsearchprovider.h @@ -23,20 +23,21 @@ class LastFMService; class LastFMSearchProvider : public SimpleSearchProvider { -public: - LastFMSearchProvider(LastFMService* service, Application* app, QObject* parent); + public: + LastFMSearchProvider(LastFMService* service, Application* app, + QObject* parent); void LoadArtAsync(int id, const Result& result); bool IsLoggedIn(); void ShowConfig(); -protected: + protected: void RecreateItems(); -private: + private: LastFMService* service_; QImage icon_; }; -#endif // LASTFMSEARCHPROVIDER_H +#endif // LASTFMSEARCHPROVIDER_H diff --git a/src/globalsearch/librarysearchprovider.cpp b/src/globalsearch/librarysearchprovider.cpp index de4a376d6..d1b3e787c 100644 --- a/src/globalsearch/librarysearchprovider.cpp +++ b/src/globalsearch/librarysearchprovider.cpp @@ -25,19 +25,15 @@ #include - LibrarySearchProvider::LibrarySearchProvider(LibraryBackendInterface* backend, const QString& name, const QString& id, const QIcon& icon, bool enabled_by_default, - Application* app, - QObject* parent) - : BlockingSearchProvider(app, parent), - backend_(backend) -{ - Hints hints = WantsSerialisedArtQueries | ArtIsInSongMetadata | - CanGiveSuggestions; + Application* app, QObject* parent) + : BlockingSearchProvider(app, parent), backend_(backend) { + Hints hints = + WantsSerialisedArtQueries | ArtIsInSongMetadata | CanGiveSuggestions; if (!enabled_by_default) { hints |= DisabledByDefault; @@ -46,7 +42,8 @@ LibrarySearchProvider::LibrarySearchProvider(LibraryBackendInterface* backend, Init(name, id, icon, hints); } -SearchProvider::ResultList LibrarySearchProvider::Search(int id, const QString& query) { +SearchProvider::ResultList LibrarySearchProvider::Search(int id, + const QString& query) { QueryOptions options; options.set_filter(query); @@ -94,7 +91,7 @@ QStringList LibrarySearchProvider::GetSuggestions(int count) { const int largest_rowid = q.Value(0).toInt(); - for (int attempt=0 ; attempt= count) { break; } @@ -110,7 +107,7 @@ QStringList LibrarySearchProvider::GetSuggestions(int count) { } const QString artist = q.Value(0).toString(); - const QString album = q.Value(1).toString(); + const QString album = q.Value(1).toString(); if (!artist.isEmpty() && !album.isEmpty()) ret << ((qrand() % 2 == 0) ? artist : album); diff --git a/src/globalsearch/librarysearchprovider.h b/src/globalsearch/librarysearchprovider.h index 2eb07f8a4..389845029 100644 --- a/src/globalsearch/librarysearchprovider.h +++ b/src/globalsearch/librarysearchprovider.h @@ -22,20 +22,19 @@ class LibraryBackendInterface; - class LibrarySearchProvider : public BlockingSearchProvider { -public: + public: LibrarySearchProvider(LibraryBackendInterface* backend, const QString& name, const QString& id, const QIcon& icon, - bool enabled_by_default, - Application* app, QObject* parent = 0); + bool enabled_by_default, Application* app, + QObject* parent = 0); ResultList Search(int id, const QString& query); MimeData* LoadTracks(const ResultList& results); QStringList GetSuggestions(int count); -private: + private: LibraryBackendInterface* backend_; }; -#endif // LIBRARYSEARCHPROVIDER_H +#endif // LIBRARYSEARCHPROVIDER_H diff --git a/src/globalsearch/savedradiosearchprovider.cpp b/src/globalsearch/savedradiosearchprovider.cpp index 5dd052dc2..8c1590442 100644 --- a/src/globalsearch/savedradiosearchprovider.cpp +++ b/src/globalsearch/savedradiosearchprovider.cpp @@ -21,12 +21,11 @@ #include "ui/iconloader.h" SavedRadioSearchProvider::SavedRadioSearchProvider(SavedRadio* service, - Application* app, QObject* parent) - : SimpleSearchProvider(app, parent), - service_(service) -{ - Init(tr("Your radio streams"), "savedradio", IconLoader::Load("document-open-remote"), - MimeDataContainsUrlsOnly); + Application* app, + QObject* parent) + : SimpleSearchProvider(app, parent), service_(service) { + Init(tr("Your radio streams"), "savedradio", + IconLoader::Load("document-open-remote"), MimeDataContainsUrlsOnly); set_max_suggestion_count(3); @@ -38,7 +37,7 @@ SavedRadioSearchProvider::SavedRadioSearchProvider(SavedRadio* service, void SavedRadioSearchProvider::RecreateItems() { QList items; - foreach (const SavedRadio::Stream& stream, service_->Streams()) { + foreach(const SavedRadio::Stream & stream, service_->Streams()) { Item item; item.metadata_.set_title(stream.name_); item.metadata_.set_url(stream.url_); diff --git a/src/globalsearch/savedradiosearchprovider.h b/src/globalsearch/savedradiosearchprovider.h index d6bb793c6..a4e43c87a 100644 --- a/src/globalsearch/savedradiosearchprovider.h +++ b/src/globalsearch/savedradiosearchprovider.h @@ -23,14 +23,15 @@ class SavedRadio; class SavedRadioSearchProvider : public SimpleSearchProvider { -public: - SavedRadioSearchProvider(SavedRadio* service, Application* app, QObject* parent); + public: + SavedRadioSearchProvider(SavedRadio* service, Application* app, + QObject* parent); -protected: + protected: void RecreateItems(); -private: + private: SavedRadio* service_; }; -#endif // SAVEDRADIOSEARCHPROVIDER_H +#endif // SAVEDRADIOSEARCHPROVIDER_H diff --git a/src/globalsearch/searchprovider.cpp b/src/globalsearch/searchprovider.cpp index 428355234..4398251f9 100644 --- a/src/globalsearch/searchprovider.cpp +++ b/src/globalsearch/searchprovider.cpp @@ -26,13 +26,8 @@ const int SearchProvider::kArtHeight = 32; - SearchProvider::SearchProvider(Application* app, QObject* parent) - : QObject(parent), - app_(app), - hints_(0) -{ -} + : QObject(parent), app_(app), hints_(0) {} void SearchProvider::Init(const QString& name, const QString& id, const QIcon& icon, Hints hints) { @@ -45,7 +40,7 @@ void SearchProvider::Init(const QString& name, const QString& id, QStringList SearchProvider::TokenizeQuery(const QString& query) { QStringList tokens(query.split(QRegExp("\\s+"))); - for (QStringList::iterator it = tokens.begin() ; it != tokens.end() ; ++it) { + for (QStringList::iterator it = tokens.begin(); it != tokens.end(); ++it) { (*it).remove('('); (*it).remove(')'); (*it).remove('"'); @@ -60,7 +55,7 @@ QStringList SearchProvider::TokenizeQuery(const QString& query) { } bool SearchProvider::Matches(const QStringList& tokens, const QString& string) { - foreach (const QString& token, tokens) { + foreach(const QString & token, tokens) { if (!string.contains(token, Qt::CaseInsensitive)) { return false; } @@ -69,13 +64,13 @@ bool SearchProvider::Matches(const QStringList& tokens, const QString& string) { return true; } -BlockingSearchProvider::BlockingSearchProvider(Application* app, QObject* parent) - : SearchProvider(app, parent) { -} +BlockingSearchProvider::BlockingSearchProvider(Application* app, + QObject* parent) + : SearchProvider(app, parent) {} void BlockingSearchProvider::SearchAsync(int id, const QString& query) { - QFuture future = QtConcurrent::run( - this, &BlockingSearchProvider::Search, id, query); + QFuture future = + QtConcurrent::run(this, &BlockingSearchProvider::Search, id, query); BoundFutureWatcher* watcher = new BoundFutureWatcher(id); @@ -94,21 +89,19 @@ void BlockingSearchProvider::BlockingSearchFinished() { } QImage SearchProvider::ScaleAndPad(const QImage& image) { - if (image.isNull()) - return QImage(); + if (image.isNull()) return QImage(); const QSize target_size = QSize(kArtHeight, kArtHeight); - if (image.size() == target_size) - return image; + if (image.size() == target_size) return image; // Scale the image down QImage copy; - copy = image.scaled(target_size, Qt::KeepAspectRatio, Qt::SmoothTransformation); + copy = + image.scaled(target_size, Qt::KeepAspectRatio, Qt::SmoothTransformation); // Pad the image to kHeight x kHeight - if (copy.size() == target_size) - return copy; + if (copy.size() == target_size) return copy; QImage padded_image(kArtHeight, kArtHeight, QImage::Format_ARGB32); padded_image.fill(0); @@ -132,12 +125,11 @@ MimeData* SearchProvider::LoadTracks(const ResultList& results) { mime_data = new MimeData; } else { SongList songs; - foreach (const Result& result, results) { - songs << result.metadata_; - } + foreach(const Result & result, results) { songs << result.metadata_; } if (internet_service()) { - InternetSongMimeData* internet_song_mime_data = new InternetSongMimeData(internet_service()); + InternetSongMimeData* internet_song_mime_data = + new InternetSongMimeData(internet_service()); internet_song_mime_data->songs = songs; mime_data = internet_song_mime_data; } else { @@ -148,9 +140,7 @@ MimeData* SearchProvider::LoadTracks(const ResultList& results) { } QList urls; - foreach (const Result& result, results) { - urls << result.metadata_.url(); - } + foreach(const Result & result, results) { urls << result.metadata_.url(); } mime_data->setUrls(urls); return mime_data; diff --git a/src/globalsearch/searchprovider.h b/src/globalsearch/searchprovider.h index dd22186a7..92f6d387d 100644 --- a/src/globalsearch/searchprovider.h +++ b/src/globalsearch/searchprovider.h @@ -28,18 +28,17 @@ class Application; class InternetService; class MimeData; - class SearchProvider : public QObject { Q_OBJECT -public: + public: SearchProvider(Application* app, QObject* parent = 0); static const int kArtHeight; struct Result { Result(SearchProvider* provider = 0) - : provider_(provider), group_automatically_(true) {} + : provider_(provider), group_automatically_(true) {} // This must be set by the provider using the constructor. SearchProvider* provider_; @@ -108,14 +107,18 @@ public: Hints hints() const { return hints_; } bool wants_delayed_queries() const { return hints() & WantsDelayedQueries; } - bool wants_serialised_art() const { return hints() & WantsSerialisedArtQueries; } + bool wants_serialised_art() const { + return hints() & WantsSerialisedArtQueries; + } bool art_is_probably_remote() const { return hints() & ArtIsProbablyRemote; } bool art_is_in_song_metadata() const { return hints() & ArtIsInSongMetadata; } bool can_show_config() const { return hints() & CanShowConfig; } bool can_give_suggestions() const { return hints() & CanGiveSuggestions; } bool is_disabled_by_default() const { return hints() & DisabledByDefault; } bool is_enabled_by_default() const { return !is_disabled_by_default(); } - bool mime_data_contains_urls_only() const { return hints() & MimeDataContainsUrlsOnly; } + bool mime_data_contains_urls_only() const { + return hints() & MimeDataContainsUrlsOnly; + } // Starts a search. Must emit ResultsAvailable zero or more times and then // SearchFinished exactly once, using this ID. @@ -138,7 +141,7 @@ public: // If provider needs user login to search and play songs, this method should // be reimplemented virtual bool IsLoggedIn() { return true; } - virtual void ShowConfig() { } // Remember to set the CanShowConfig hint + virtual void ShowConfig() {} // Remember to set the CanShowConfig hint // Returns the Internet service in charge of this provider, or NULL if there // is none virtual InternetService* internet_service() { return NULL; } @@ -151,7 +154,7 @@ signals: void ArtLoaded(int id, const QImage& image); -protected: + protected: // These functions treat queries in the same way as LibraryQuery. They're // useful for figuring out whether you got a result because it matched in // the song title or the artist/album name. @@ -165,9 +168,7 @@ protected: struct PendingState { PendingState() : orig_id_(-1) {} PendingState(int orig_id, QStringList tokens) - : orig_id_(orig_id), - tokens_(tokens) { - } + : orig_id_(orig_id), tokens_(tokens) {} int orig_id_; QStringList tokens_; @@ -180,10 +181,10 @@ protected: } }; -protected: + protected: Application* app_; -private: + private: QString name_; QString id_; QIcon icon_; @@ -194,20 +195,19 @@ Q_DECLARE_METATYPE(SearchProvider::Result) Q_DECLARE_METATYPE(SearchProvider::ResultList) Q_DECLARE_OPERATORS_FOR_FLAGS(SearchProvider::Hints) - class BlockingSearchProvider : public SearchProvider { Q_OBJECT -public: + public: BlockingSearchProvider(Application* app, QObject* parent = 0); void SearchAsync(int id, const QString& query); virtual ResultList Search(int id, const QString& query) = 0; -private slots: + private slots: void BlockingSearchFinished(); }; Q_DECLARE_METATYPE(SearchProvider*) -#endif // SEARCHPROVIDER_H +#endif // SEARCHPROVIDER_H diff --git a/src/globalsearch/searchproviderstatuswidget.cpp b/src/globalsearch/searchproviderstatuswidget.cpp index d4f2d069c..8bb25738d 100644 --- a/src/globalsearch/searchproviderstatuswidget.cpp +++ b/src/globalsearch/searchproviderstatuswidget.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -25,14 +25,12 @@ #include SearchProviderStatusWidget::SearchProviderStatusWidget( - const QIcon& warning_icon, - GlobalSearch* engine, SearchProvider* provider, + const QIcon& warning_icon, GlobalSearch* engine, SearchProvider* provider, QWidget* parent) - : QWidget(parent), - ui_(new Ui_SearchProviderStatusWidget), - engine_(engine), - provider_(provider) -{ + : QWidget(parent), + ui_(new Ui_SearchProviderStatusWidget), + engine_(engine), + provider_(provider) { ui_->setupUi(this); ui_->icon->setPixmap(provider->icon().pixmap(16)); @@ -44,23 +42,23 @@ SearchProviderStatusWidget::SearchProviderStatusWidget( if (enabled && logged_in) { ui_->disabled_group->hide(); } else { - const QString disabled_text = tr("Disabled", "Refers to search provider's status."); + const QString disabled_text = + tr("Disabled", "Refers to search provider's status."); const QString not_logged_in_text = tr("Not logged in"); - const int disabled_width = fontMetrics().width(" ") + qMax( - fontMetrics().width(disabled_text), - fontMetrics().width(not_logged_in_text)); + const int disabled_width = fontMetrics().width(" ") + + qMax(fontMetrics().width(disabled_text), + fontMetrics().width(not_logged_in_text)); ui_->disabled_reason->setMinimumWidth(disabled_width); - ui_->disabled_reason->setText(logged_in ? disabled_text : not_logged_in_text); + ui_->disabled_reason->setText(logged_in ? disabled_text + : not_logged_in_text); ui_->disabled_icon->setPixmap(warning_icon.pixmap(16)); ui_->disabled_reason->installEventFilter(this); } } -SearchProviderStatusWidget::~SearchProviderStatusWidget() { - delete ui_; -} +SearchProviderStatusWidget::~SearchProviderStatusWidget() { delete ui_; } bool SearchProviderStatusWidget::eventFilter(QObject* object, QEvent* event) { if (object != ui_->disabled_reason) { @@ -70,30 +68,31 @@ bool SearchProviderStatusWidget::eventFilter(QObject* object, QEvent* event) { QFont font(ui_->disabled_reason->font()); switch (event->type()) { - case QEvent::Enter: - font.setUnderline(true); - ui_->disabled_reason->setFont(font); - break; + case QEvent::Enter: + font.setUnderline(true); + ui_->disabled_reason->setFont(font); + break; - case QEvent::Leave: - font.setUnderline(false); - ui_->disabled_reason->setFont(font); - break; + case QEvent::Leave: + font.setUnderline(false); + ui_->disabled_reason->setFont(font); + break; - case QEvent::MouseButtonRelease: { - QMouseEvent* e = static_cast(event); - if (e->button() == Qt::LeftButton) { - if (!provider_->IsLoggedIn()) { - provider_->ShowConfig(); - } else { - engine_->application()->OpenSettingsDialogAtPage(SettingsDialog::Page_GlobalSearch); + case QEvent::MouseButtonRelease: { + QMouseEvent* e = static_cast(event); + if (e->button() == Qt::LeftButton) { + if (!provider_->IsLoggedIn()) { + provider_->ShowConfig(); + } else { + engine_->application()->OpenSettingsDialogAtPage( + SettingsDialog::Page_GlobalSearch); + } } + break; } - break; - } - default: - return false; + default: + return false; } return true; diff --git a/src/globalsearch/searchproviderstatuswidget.h b/src/globalsearch/searchproviderstatuswidget.h index a16cbd1ce..3bf871d2a 100644 --- a/src/globalsearch/searchproviderstatuswidget.h +++ b/src/globalsearch/searchproviderstatuswidget.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -25,19 +25,18 @@ class SearchProvider; class Ui_SearchProviderStatusWidget; class SearchProviderStatusWidget : public QWidget { -public: - SearchProviderStatusWidget(const QIcon& warning_icon, - GlobalSearch* engine, SearchProvider* provider, - QWidget* parent = 0); + public: + SearchProviderStatusWidget(const QIcon& warning_icon, GlobalSearch* engine, + SearchProvider* provider, QWidget* parent = 0); ~SearchProviderStatusWidget(); bool eventFilter(QObject* object, QEvent* event); - -private: + + private: Ui_SearchProviderStatusWidget* ui_; GlobalSearch* engine_; SearchProvider* provider_; }; -#endif // SEARCHPROVIDERSTATUSWIDGET_H +#endif // SEARCHPROVIDERSTATUSWIDGET_H diff --git a/src/globalsearch/simplesearchprovider.cpp b/src/globalsearch/simplesearchprovider.cpp index 84e715368..daa5db966 100644 --- a/src/globalsearch/simplesearchprovider.cpp +++ b/src/globalsearch/simplesearchprovider.cpp @@ -19,31 +19,24 @@ #include "core/logging.h" #include "playlist/songmimedata.h" - const int SimpleSearchProvider::kDefaultResultLimit = 6; -SimpleSearchProvider::Item::Item(const QString& title, const QUrl& url, const QString& keyword) - : keyword_(keyword) -{ +SimpleSearchProvider::Item::Item(const QString& title, const QUrl& url, + const QString& keyword) + : keyword_(keyword) { metadata_.set_title(title); metadata_.set_url(url); } SimpleSearchProvider::Item::Item(const Song& song, const QString& keyword) - : keyword_(keyword), - metadata_(song) -{ -} - + : keyword_(keyword), metadata_(song) {} SimpleSearchProvider::SimpleSearchProvider(Application* app, QObject* parent) - : BlockingSearchProvider(app, parent), - result_limit_(kDefaultResultLimit), - max_suggestion_count_(-1), - items_dirty_(true), - has_searched_before_(false) -{ -} + : BlockingSearchProvider(app, parent), + result_limit_(kDefaultResultLimit), + max_suggestion_count_(-1), + items_dirty_(true), + has_searched_before_(false) {} void SimpleSearchProvider::MaybeRecreateItems() { if (has_searched_before_) { @@ -53,7 +46,8 @@ void SimpleSearchProvider::MaybeRecreateItems() { } } -SearchProvider::ResultList SimpleSearchProvider::Search(int id, const QString& query) { +SearchProvider::ResultList SimpleSearchProvider::Search(int id, + const QString& query) { Q_UNUSED(id) if (items_dirty_) { @@ -67,9 +61,9 @@ SearchProvider::ResultList SimpleSearchProvider::Search(int id, const QString& q const QStringList tokens = TokenizeQuery(query); QMutexLocker l(&items_mutex_); - foreach (const Item& item, items_) { + foreach(const Item & item, items_) { bool matched = true; - foreach (const QString& token, tokens) { + foreach(const QString & token, tokens) { if (!item.keyword_.contains(token, Qt::CaseInsensitive) && !item.metadata_.title().contains(token, Qt::CaseInsensitive) && !safe_words_.contains(token, Qt::CaseInsensitive)) { @@ -85,8 +79,7 @@ SearchProvider::ResultList SimpleSearchProvider::Search(int id, const QString& q ret << result; } - if (ret.count() >= result_limit_) - break; + if (ret.count() >= result_limit_) break; } return ret; @@ -95,7 +88,7 @@ SearchProvider::ResultList SimpleSearchProvider::Search(int id, const QString& q void SimpleSearchProvider::SetItems(const ItemList& items) { QMutexLocker l(&items_mutex_); items_ = items; - for (ItemList::iterator it = items_.begin() ; it != items_.end() ; ++it) { + for (ItemList::iterator it = items_.begin(); it != items_.end(); ++it) { it->metadata_.set_filetype(Song::Type_Stream); } } @@ -108,19 +101,16 @@ QStringList SimpleSearchProvider::GetSuggestions(int count) { QStringList ret; QMutexLocker l(&items_mutex_); - if (items_.isEmpty()) - return ret; + if (items_.isEmpty()) return ret; - for (int attempt=0 ; attempt= count) { break; } const Item& item = items_[qrand() % items_.count()]; - if (!item.keyword_.isEmpty()) - ret << item.keyword_; - if (!item.metadata_.title().isEmpty()) - ret << item.metadata_.title(); + if (!item.keyword_.isEmpty()) ret << item.keyword_; + if (!item.metadata_.title().isEmpty()) ret << item.metadata_.title(); } return ret; diff --git a/src/globalsearch/simplesearchprovider.h b/src/globalsearch/simplesearchprovider.h index 10d24260f..26bc743a4 100644 --- a/src/globalsearch/simplesearchprovider.h +++ b/src/globalsearch/simplesearchprovider.h @@ -23,7 +23,7 @@ class SimpleSearchProvider : public BlockingSearchProvider { Q_OBJECT -public: + public: SimpleSearchProvider(Application* app, QObject* parent); static const int kDefaultResultLimit; @@ -34,13 +34,13 @@ public: // SearchProvider QStringList GetSuggestions(int count); -protected slots: + protected slots: // Calls RecreateItems now if the user has done a global search with this // provider at least once before. Otherwise will schedule RecreateItems the // next time the user does a search. void MaybeRecreateItems(); -protected: + protected: struct Item { Item() {} Item(const QString& title, const QUrl& url, @@ -56,7 +56,9 @@ protected: void set_result_limit(int result_limit) { result_limit_ = result_limit; } void set_max_suggestion_count(int count) { max_suggestion_count_ = count; } QStringList safe_words() const { return safe_words_; } - void set_safe_words(const QStringList& safe_words) { safe_words_ = safe_words; } + void set_safe_words(const QStringList& safe_words) { + safe_words_ = safe_words; + } void SetItems(const ItemList& items); @@ -64,7 +66,7 @@ protected: // call SetItems with the new list. virtual void RecreateItems() = 0; -private: + private: int result_limit_; QStringList safe_words_; int max_suggestion_count_; @@ -76,4 +78,4 @@ private: bool has_searched_before_; }; -#endif // SIMPLESEARCHPROVIDER_H +#endif // SIMPLESEARCHPROVIDER_H diff --git a/src/globalsearch/somafmsearchprovider.cpp b/src/globalsearch/somafmsearchprovider.cpp index 207e26b4b..a1680300e 100644 --- a/src/globalsearch/somafmsearchprovider.cpp +++ b/src/globalsearch/somafmsearchprovider.cpp @@ -18,12 +18,11 @@ #include "somafmsearchprovider.h" #include "internet/somafmservice.h" -SomaFMSearchProvider::SomaFMSearchProvider( - SomaFMServiceBase* service, Application* app, QObject* parent) - : SimpleSearchProvider(app, parent), - service_(service) -{ - Init(service->name(), service->url_scheme(), service->icon(), CanGiveSuggestions); +SomaFMSearchProvider::SomaFMSearchProvider(SomaFMServiceBase* service, + Application* app, QObject* parent) + : SimpleSearchProvider(app, parent), service_(service) { + Init(service->name(), service->url_scheme(), service->icon(), + CanGiveSuggestions); set_result_limit(3); set_max_suggestion_count(3); icon_ = ScaleAndPad( @@ -33,8 +32,7 @@ SomaFMSearchProvider::SomaFMSearchProvider( // Load the stream list on startup only if it doesn't involve going to update // info from the server. - if (!service_->IsStreamListStale()) - RecreateItems(); + if (!service_->IsStreamListStale()) RecreateItems(); } void SomaFMSearchProvider::LoadArtAsync(int id, const Result& result) { @@ -44,7 +42,7 @@ void SomaFMSearchProvider::LoadArtAsync(int id, const Result& result) { void SomaFMSearchProvider::RecreateItems() { QList items; - foreach (const SomaFMService::Stream& stream, service_->Streams()) { + foreach(const SomaFMService::Stream & stream, service_->Streams()) { Item item; item.metadata_ = stream.ToSong(service_->name()); item.keyword_ = stream.title_; diff --git a/src/globalsearch/somafmsearchprovider.h b/src/globalsearch/somafmsearchprovider.h index 5bd2f1971..40df8bf19 100644 --- a/src/globalsearch/somafmsearchprovider.h +++ b/src/globalsearch/somafmsearchprovider.h @@ -23,17 +23,18 @@ class SomaFMServiceBase; class SomaFMSearchProvider : public SimpleSearchProvider { -public: - SomaFMSearchProvider(SomaFMServiceBase* service, Application* app, QObject* parent); + public: + SomaFMSearchProvider(SomaFMServiceBase* service, Application* app, + QObject* parent); void LoadArtAsync(int id, const Result& result); -protected: + protected: void RecreateItems(); -private: + private: SomaFMServiceBase* service_; QImage icon_; }; -#endif // SOMAFMSEARCHPROVIDER_H +#endif // SOMAFMSEARCHPROVIDER_H diff --git a/src/globalsearch/soundcloudsearchprovider.cpp b/src/globalsearch/soundcloudsearchprovider.cpp index 5af8f456f..1c9966402 100644 --- a/src/globalsearch/soundcloudsearchprovider.cpp +++ b/src/globalsearch/soundcloudsearchprovider.cpp @@ -24,17 +24,15 @@ #include "covers/albumcoverloader.h" #include "internet/soundcloudservice.h" -SoundCloudSearchProvider::SoundCloudSearchProvider(Application* app, QObject* parent) - : SearchProvider(app, parent), - service_(nullptr) -{ -} +SoundCloudSearchProvider::SoundCloudSearchProvider(Application* app, + QObject* parent) + : SearchProvider(app, parent), service_(nullptr) {} void SoundCloudSearchProvider::Init(SoundCloudService* service) { service_ = service; - SearchProvider::Init("SoundCloud", "soundcloud", - QIcon(":providers/soundcloud.png"), - WantsDelayedQueries | ArtIsProbablyRemote | CanShowConfig); + SearchProvider::Init( + "SoundCloud", "soundcloud", QIcon(":providers/soundcloud.png"), + WantsDelayedQueries | ArtIsProbablyRemote | CanShowConfig); connect(service_, SIGNAL(SimpleSearchResults(int, SongList)), SLOT(SearchDone(int, SongList))); @@ -43,14 +41,14 @@ void SoundCloudSearchProvider::Init(SoundCloudService* service) { cover_loader_options_.pad_output_image_ = true; cover_loader_options_.scale_output_image_ = true; - connect(app_->album_cover_loader(), - SIGNAL(ImageLoaded(quint64, QImage)), + connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)), SLOT(AlbumArtLoaded(quint64, QImage))); } void SoundCloudSearchProvider::SearchAsync(int id, const QString& query) { const int service_id = service_->SimpleSearch(query); - pending_searches_[service_id] = PendingState(id, TokenizeQuery(query));; + pending_searches_[service_id] = PendingState(id, TokenizeQuery(query)); + ; } void SoundCloudSearchProvider::SearchDone(int id, const SongList& songs) { @@ -59,7 +57,7 @@ void SoundCloudSearchProvider::SearchDone(int id, const SongList& songs) { const int global_search_id = state.orig_id_; ResultList ret; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { Result result(this); result.metadata_ = song; @@ -78,7 +76,7 @@ void SoundCloudSearchProvider::MaybeSearchFinished(int id) { void SoundCloudSearchProvider::LoadArtAsync(int id, const Result& result) { quint64 loader_id = app_->album_cover_loader()->LoadImageAsync( - cover_loader_options_, result.metadata_); + cover_loader_options_, result.metadata_); cover_loader_tasks_[loader_id] = id; } diff --git a/src/globalsearch/spotifysearchprovider.cpp b/src/globalsearch/spotifysearchprovider.cpp index 3e08aa529..c1b2e25aa 100644 --- a/src/globalsearch/spotifysearchprovider.cpp +++ b/src/globalsearch/spotifysearchprovider.cpp @@ -32,21 +32,16 @@ const int kSearchAlbumLimit = 20; } SpotifySearchProvider::SpotifySearchProvider(Application* app, QObject* parent) - : SearchProvider(app, parent), - server_(nullptr), - service_(nullptr) -{ + : SearchProvider(app, parent), server_(nullptr), service_(nullptr) { Init("Spotify", "spotify", QIcon(":icons/32x32/spotify.png"), WantsDelayedQueries | WantsSerialisedArtQueries | ArtIsProbablyRemote | - CanShowConfig | CanGiveSuggestions); + CanShowConfig | CanGiveSuggestions); } SpotifyServer* SpotifySearchProvider::server() { - if (server_) - return server_; + if (server_) return server_; - if (!service_) - service_ = InternetModel::Service(); + if (!service_) service_ = InternetModel::Service(); if (service_->login_state() != SpotifyService::LoginState_LoggedIn) return nullptr; @@ -54,20 +49,19 @@ SpotifyServer* SpotifySearchProvider::server() { server_ = service_->server(); connect(server_, SIGNAL(SearchResults(pb::spotify::SearchResponse)), SLOT(SearchFinishedSlot(pb::spotify::SearchResponse))); - connect(server_, SIGNAL(ImageLoaded(QString,QImage)), - SLOT(ArtLoadedSlot(QString,QImage))); + connect(server_, SIGNAL(ImageLoaded(QString, QImage)), + SLOT(ArtLoadedSlot(QString, QImage))); connect(server_, SIGNAL(destroyed()), SLOT(ServerDestroyed())); connect(server_, SIGNAL(StarredLoaded(pb::spotify::LoadPlaylistResponse)), SLOT(SuggestionsLoaded(pb::spotify::LoadPlaylistResponse))); - connect(server_, SIGNAL(ToplistBrowseResults(pb::spotify::BrowseToplistResponse)), + connect(server_, + SIGNAL(ToplistBrowseResults(pb::spotify::BrowseToplistResponse)), SLOT(SuggestionsLoaded(pb::spotify::BrowseToplistResponse))); return server_; } -void SpotifySearchProvider::ServerDestroyed() { - server_ = nullptr; -} +void SpotifySearchProvider::ServerDestroyed() { server_ = nullptr; } void SpotifySearchProvider::SearchAsync(int id, const QString& query) { SpotifyServer* s = server(); @@ -85,17 +79,17 @@ void SpotifySearchProvider::SearchAsync(int id, const QString& query) { queries_[query_string] = state; } -void SpotifySearchProvider::SearchFinishedSlot(const pb::spotify::SearchResponse& response) { +void SpotifySearchProvider::SearchFinishedSlot( + const pb::spotify::SearchResponse& response) { QString query_string = QString::fromUtf8(response.request().query().c_str()); QMap::iterator it = queries_.find(query_string); - if (it == queries_.end()) - return; + if (it == queries_.end()) return; PendingState state = it.value(); queries_.erase(it); ResultList ret; - for (int i=0; i < response.result_size() ; ++i) { + for (int i = 0; i < response.result_size(); ++i) { const pb::spotify::Track& track = response.result(i); Result result(this); @@ -104,10 +98,10 @@ void SpotifySearchProvider::SearchFinishedSlot(const pb::spotify::SearchResponse ret << result; } - for (int i=0 ; iLoadImage(image_id); } -void SpotifySearchProvider::ArtLoadedSlot(const QString& id, const QImage& image) { +void SpotifySearchProvider::ArtLoadedSlot(const QString& id, + const QImage& image) { QMap::iterator it = pending_art_.find(id); - if (it == pending_art_.end()) - return; + if (it == pending_art_.end()) return; const int orig_id = it.value(); pending_art_.erase(it); diff --git a/src/globalsearch/spotifysearchprovider.h b/src/globalsearch/spotifysearchprovider.h index b8f5fdba0..90b7f11a0 100644 --- a/src/globalsearch/spotifysearchprovider.h +++ b/src/globalsearch/spotifysearchprovider.h @@ -24,11 +24,10 @@ class SpotifyServer; class SpotifyService; - class SpotifySearchProvider : public SearchProvider { Q_OBJECT -public: + public: SpotifySearchProvider(Application* app, QObject* parent = 0); void SearchAsync(int id, const QString& query); @@ -38,21 +37,21 @@ public: bool IsLoggedIn(); void ShowConfig(); -private slots: + private slots: void ServerDestroyed(); void SearchFinishedSlot(const pb::spotify::SearchResponse& response); void ArtLoadedSlot(const QString& id, const QImage& image); void SuggestionsLoaded(const pb::spotify::LoadPlaylistResponse& response); void SuggestionsLoaded(const pb::spotify::BrowseToplistResponse& response); -private: + private: SpotifyServer* server(); void LoadSuggestions(); void AddSuggestionFromTrack(const pb::spotify::Track& track); void AddSuggestionFromAlbum(const pb::spotify::Album& album); -private: + private: SpotifyServer* server_; SpotifyService* service_; @@ -63,4 +62,4 @@ private: QSet suggestions_; }; -#endif // SPOTIFYSEARCHPROVIDER_H +#endif // SPOTIFYSEARCHPROVIDER_H diff --git a/src/globalsearch/suggestionwidget.cpp b/src/globalsearch/suggestionwidget.cpp index d22848ee5..cfcc232fa 100644 --- a/src/globalsearch/suggestionwidget.cpp +++ b/src/globalsearch/suggestionwidget.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -22,18 +22,14 @@ #include SuggestionWidget::SuggestionWidget(const QIcon& search_icon, QWidget* parent) - : QWidget(parent), - ui_(new Ui_SuggestionWidget) -{ + : QWidget(parent), ui_(new Ui_SuggestionWidget) { ui_->setupUi(this); ui_->icon->setPixmap(search_icon.pixmap(16)); ui_->name->installEventFilter(this); } -SuggestionWidget::~SuggestionWidget() { - delete ui_; -} +SuggestionWidget::~SuggestionWidget() { delete ui_; } void SuggestionWidget::SetText(const QString& text) { ui_->name->setText(text); @@ -47,29 +43,29 @@ bool SuggestionWidget::eventFilter(QObject* object, QEvent* event) { QFont font(ui_->name->font()); switch (event->type()) { - case QEvent::Enter: - font.setUnderline(true); - ui_->name->setFont(font); - break; + case QEvent::Enter: + font.setUnderline(true); + ui_->name->setFont(font); + break; - case QEvent::Leave: - font.setUnderline(false); - ui_->name->setFont(font); - break; + case QEvent::Leave: + font.setUnderline(false); + ui_->name->setFont(font); + break; - case QEvent::MouseButtonRelease: { - QMouseEvent* e = static_cast(event); - if (e->button() == Qt::LeftButton) { - QString text = ui_->name->text(); - text.replace(QRegExp("\\W"), " "); + case QEvent::MouseButtonRelease: { + QMouseEvent* e = static_cast(event); + if (e->button() == Qt::LeftButton) { + QString text = ui_->name->text(); + text.replace(QRegExp("\\W"), " "); - emit SuggestionClicked(text.simplified()); + emit SuggestionClicked(text.simplified()); + } + break; } - break; - } - default: - return false; + default: + return false; } return true; diff --git a/src/globalsearch/suggestionwidget.h b/src/globalsearch/suggestionwidget.h index 850dfced5..771a05ca8 100644 --- a/src/globalsearch/suggestionwidget.h +++ b/src/globalsearch/suggestionwidget.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -25,20 +25,20 @@ class Ui_SuggestionWidget; class SuggestionWidget : public QWidget { Q_OBJECT -public: + public: SuggestionWidget(const QIcon& search_icon, QWidget* parent = 0); ~SuggestionWidget(); bool eventFilter(QObject* object, QEvent* event); -public slots: + public slots: void SetText(const QString& text); signals: void SuggestionClicked(const QString& query); - -private: + + private: Ui_SuggestionWidget* ui_; }; -#endif // SUGGESTIONWIDGET_H +#endif // SUGGESTIONWIDGET_H diff --git a/src/globalsearch/urlsearchprovider.cpp b/src/globalsearch/urlsearchprovider.cpp index c14c150ad..82f8f20a3 100644 --- a/src/globalsearch/urlsearchprovider.cpp +++ b/src/globalsearch/urlsearchprovider.cpp @@ -25,9 +25,7 @@ const char* UrlSearchProvider::kUrlRegex = "^[a-zA-Z][a-zA-Z0-9+-.]*://"; UrlSearchProvider::UrlSearchProvider(Application* app, QObject* parent) - : SearchProvider(app, parent), - url_regex_(kUrlRegex) -{ + : SearchProvider(app, parent), url_regex_(kUrlRegex) { QIcon icon = IconLoader::Load("applications-internet"); image_ = ScaleAndPad(icon.pixmap(kArtHeight, kArtHeight).toImage()); diff --git a/src/globalsearch/urlsearchprovider.h b/src/globalsearch/urlsearchprovider.h index 1ce91cc61..0f982dcc0 100644 --- a/src/globalsearch/urlsearchprovider.h +++ b/src/globalsearch/urlsearchprovider.h @@ -23,7 +23,7 @@ #include class UrlSearchProvider : public SearchProvider { -public: + public: UrlSearchProvider(Application* app, QObject* parent); bool LooksLikeUrl(const QString& query) const; @@ -31,11 +31,11 @@ public: void SearchAsync(int id, const QString& query); void LoadArtAsync(int id, const Result& result); -private: + private: static const char* kUrlRegex; QRegExp url_regex_; QImage image_; }; -#endif // URLSEARCHPROVIDER_H +#endif // URLSEARCHPROVIDER_H diff --git a/src/internet/boxservice.cpp b/src/internet/boxservice.cpp index 066e7b213..d1cd91e82 100644 --- a/src/internet/boxservice.cpp +++ b/src/internet/boxservice.cpp @@ -17,37 +17,25 @@ namespace { static const char* kClientId = "gbswb9wp7gjyldc3qrw68h2rk68jaf4h"; static const char* kClientSecret = "pZ6cUCQz5X0xaWoPVbCDg6GpmfTtz73s"; -static const char* kOAuthEndpoint = - "https://api.box.com/oauth2/authorize"; -static const char* kOAuthTokenEndpoint = - "https://api.box.com/oauth2/token"; +static const char* kOAuthEndpoint = "https://api.box.com/oauth2/authorize"; +static const char* kOAuthTokenEndpoint = "https://api.box.com/oauth2/token"; -static const char* kUserInfo = - "https://api.box.com/2.0/users/me"; -static const char* kFolderItems = - "https://api.box.com/2.0/folders/%1/items"; +static const char* kUserInfo = "https://api.box.com/2.0/users/me"; +static const char* kFolderItems = "https://api.box.com/2.0/folders/%1/items"; static const int kRootFolderId = 0; -static const char* kFileContent = - "https://api.box.com/2.0/files/%1/content"; - -static const char* kEvents = - "https://api.box.com/2.0/events"; +static const char* kFileContent = "https://api.box.com/2.0/files/%1/content"; +static const char* kEvents = "https://api.box.com/2.0/events"; } BoxService::BoxService(Application* app, InternetModel* parent) - : CloudFileService( - app, parent, - kServiceName, kSettingsGroup, - QIcon(":/providers/box.png"), - SettingsDialog::Page_Box) { + : CloudFileService(app, parent, kServiceName, kSettingsGroup, + QIcon(":/providers/box.png"), SettingsDialog::Page_Box) { app->player()->RegisterUrlHandler(new BoxUrlHandler(this, this)); } -bool BoxService::has_credentials() const { - return !refresh_token().isEmpty(); -} +bool BoxService::has_credentials() const { return !refresh_token().isEmpty(); } QString BoxService::refresh_token() const { QSettings s; @@ -58,7 +46,7 @@ QString BoxService::refresh_token() const { bool BoxService::is_authenticated() const { return !access_token_.isEmpty() && - QDateTime::currentDateTime().secsTo(expiry_time_) > 0; + QDateTime::currentDateTime().secsTo(expiry_time_) > 0; } void BoxService::EnsureConnected() { @@ -74,17 +62,14 @@ void BoxService::Connect() { OAuthenticator* oauth = new OAuthenticator( kClientId, kClientSecret, OAuthenticator::RedirectStyle::REMOTE, this); if (!refresh_token().isEmpty()) { - oauth->RefreshAuthorisation( - kOAuthTokenEndpoint, refresh_token()); + oauth->RefreshAuthorisation(kOAuthTokenEndpoint, refresh_token()); } else { - oauth->StartAuthorisation( - kOAuthEndpoint, - kOAuthTokenEndpoint, - QString::null); + oauth->StartAuthorisation(kOAuthEndpoint, kOAuthTokenEndpoint, + QString::null); } - NewClosure(oauth, SIGNAL(Finished()), - this, SLOT(ConnectFinished(OAuthenticator*)), oauth); + NewClosure(oauth, SIGNAL(Finished()), this, + SLOT(ConnectFinished(OAuthenticator*)), oauth); } void BoxService::ConnectFinished(OAuthenticator* oauth) { @@ -103,8 +88,8 @@ void BoxService::ConnectFinished(OAuthenticator* oauth) { AddAuthorizationHeader(&request); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(FetchUserInfoFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(FetchUserInfoFinished(QNetworkReply*)), reply); } else { emit Connected(); } @@ -112,8 +97,8 @@ void BoxService::ConnectFinished(OAuthenticator* oauth) { } void BoxService::AddAuthorizationHeader(QNetworkRequest* request) const { - request->setRawHeader( - "Authorization", QString("Bearer %1").arg(access_token_).toUtf8()); + request->setRawHeader("Authorization", + QString("Bearer %1").arg(access_token_).toUtf8()); } void BoxService::FetchUserInfoFinished(QNetworkReply* reply) { @@ -161,8 +146,8 @@ void BoxService::InitialiseEventsCursor() { QNetworkRequest request(url); AddAuthorizationHeader(&request); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(InitialiseEventsFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(InitialiseEventsFinished(QNetworkReply*)), reply); } void BoxService::InitialiseEventsFinished(QNetworkReply* reply) { @@ -176,7 +161,8 @@ void BoxService::InitialiseEventsFinished(QNetworkReply* reply) { } } -void BoxService::FetchRecursiveFolderItems(const int folder_id, const int offset) { +void BoxService::FetchRecursiveFolderItems(const int folder_id, + const int offset) { QUrl url(QString(kFolderItems).arg(folder_id)); QStringList fields; fields << "etag" @@ -191,13 +177,13 @@ void BoxService::FetchRecursiveFolderItems(const int folder_id, const int offset QNetworkRequest request(url); AddAuthorizationHeader(&request); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(FetchFolderItemsFinished(QNetworkReply*, int)), - reply, folder_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(FetchFolderItemsFinished(QNetworkReply*, int)), reply, + folder_id); } -void BoxService::FetchFolderItemsFinished( - QNetworkReply* reply, const int folder_id) { +void BoxService::FetchFolderItemsFinished(QNetworkReply* reply, + const int folder_id) { reply->deleteLater(); QByteArray data = reply->readAll(); @@ -213,7 +199,7 @@ void BoxService::FetchFolderItemsFinished( FetchRecursiveFolderItems(folder_id, offset + entries.size()); } - foreach (const QVariant& e, entries) { + foreach(const QVariant & e, entries) { QVariantMap entry = e.toMap(); if (entry["type"].toString() == "folder") { FetchRecursiveFolderItems(entry["id"].toInt()); @@ -238,9 +224,9 @@ void BoxService::MaybeAddFileEntry(const QVariantMap& entry) { // This is actually a redirect. Follow it now. QNetworkReply* reply = FetchContentUrlForFile(entry["id"].toString()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(RedirectFollowed(QNetworkReply*, Song, QString)), - reply, song, mime_type); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(RedirectFollowed(QNetworkReply*, Song, QString)), reply, song, + mime_type); } QNetworkReply* BoxService::FetchContentUrlForFile(const QString& file_id) { @@ -251,20 +237,18 @@ QNetworkReply* BoxService::FetchContentUrlForFile(const QString& file_id) { return reply; } -void BoxService::RedirectFollowed( - QNetworkReply* reply, const Song& song, const QString& mime_type) { +void BoxService::RedirectFollowed(QNetworkReply* reply, const Song& song, + const QString& mime_type) { reply->deleteLater(); - QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); + QVariant redirect = + reply->attribute(QNetworkRequest::RedirectionTargetAttribute); if (!redirect.isValid()) { return; } QUrl real_url = redirect.toUrl(); - MaybeAddFileToDatabase( - song, - mime_type, - real_url, - QString("Bearer %1").arg(access_token_)); + MaybeAddFileToDatabase(song, mime_type, real_url, + QString("Bearer %1").arg(access_token_)); } void BoxService::UpdateFilesFromCursor(const QString& cursor) { @@ -274,8 +258,8 @@ void BoxService::UpdateFilesFromCursor(const QString& cursor) { QNetworkRequest request(url); AddAuthorizationHeader(&request); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(FetchEventsFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(FetchEventsFinished(QNetworkReply*)), reply); } void BoxService::FetchEventsFinished(QNetworkReply* reply) { @@ -289,7 +273,7 @@ void BoxService::FetchEventsFinished(QNetworkReply* reply) { s.setValue("cursor", response["next_stream_position"]); QVariantList entries = response["entries"].toList(); - foreach (const QVariant& e, entries) { + foreach(const QVariant & e, entries) { QVariantMap event = e.toMap(); QString type = event["event_type"].toString(); QVariantMap source = event["source"].toMap(); diff --git a/src/internet/boxservice.h b/src/internet/boxservice.h index 084aa8875..97a822b24 100644 --- a/src/internet/boxservice.h +++ b/src/internet/boxservice.h @@ -24,15 +24,15 @@ class BoxService : public CloudFileService { void Connect(); void ForgetCredentials(); - signals: +signals: void Connected(); private slots: void ConnectFinished(OAuthenticator* oauth); void FetchUserInfoFinished(QNetworkReply* reply); void FetchFolderItemsFinished(QNetworkReply* reply, const int folder_id); - void RedirectFollowed( - QNetworkReply* reply, const Song& song, const QString& mime_type); + void RedirectFollowed(QNetworkReply* reply, const Song& song, + const QString& mime_type); void InitialiseEventsFinished(QNetworkReply* reply); void FetchEventsFinished(QNetworkReply* reply); diff --git a/src/internet/boxsettingspage.cpp b/src/internet/boxsettingspage.cpp index 3874829a5..f8889469a 100644 --- a/src/internet/boxsettingspage.cpp +++ b/src/internet/boxsettingspage.cpp @@ -26,10 +26,9 @@ #include "ui/settingsdialog.h" BoxSettingsPage::BoxSettingsPage(SettingsDialog* parent) - : SettingsPage(parent), - ui_(new Ui::BoxSettingsPage), - service_(dialog()->app()->internet_model()->Service()) -{ + : SettingsPage(parent), + ui_(new Ui::BoxSettingsPage), + service_(dialog()->app()->internet_model()->Service()) { ui_->setupUi(this); ui_->login_state->AddCredentialGroup(ui_->login_container); @@ -40,9 +39,7 @@ BoxSettingsPage::BoxSettingsPage(SettingsDialog* parent) dialog()->installEventFilter(this); } -BoxSettingsPage::~BoxSettingsPage() { - delete ui_; -} +BoxSettingsPage::~BoxSettingsPage() { delete ui_; } void BoxSettingsPage::Load() { QSettings s; diff --git a/src/internet/boxsettingspage.h b/src/internet/boxsettingspage.h index 13b46c34f..5c094dd18 100644 --- a/src/internet/boxsettingspage.h +++ b/src/internet/boxsettingspage.h @@ -29,7 +29,7 @@ class Ui_BoxSettingsPage; class BoxSettingsPage : public SettingsPage { Q_OBJECT -public: + public: BoxSettingsPage(SettingsDialog* parent = 0); ~BoxSettingsPage(); @@ -39,15 +39,15 @@ public: // QObject bool eventFilter(QObject* object, QEvent* event); -private slots: + private slots: void LoginClicked(); void LogoutClicked(); void Connected(); -private: + private: Ui_BoxSettingsPage* ui_; BoxService* service_; }; -#endif // BOXSETTINGSPAGE_H +#endif // BOXSETTINGSPAGE_H diff --git a/src/internet/boxurlhandler.cpp b/src/internet/boxurlhandler.cpp index d296e6ba6..08d404ad3 100644 --- a/src/internet/boxurlhandler.cpp +++ b/src/internet/boxurlhandler.cpp @@ -3,9 +3,7 @@ #include "boxservice.h" BoxUrlHandler::BoxUrlHandler(BoxService* service, QObject* parent) - : UrlHandler(parent), - service_(service) { -} + : UrlHandler(parent), service_(service) {} UrlHandler::LoadResult BoxUrlHandler::StartLoading(const QUrl& url) { QString file_id = url.path(); diff --git a/src/internet/cloudfileservice.cpp b/src/internet/cloudfileservice.cpp index 55cb1ab7a..92b600ee1 100644 --- a/src/internet/cloudfileservice.cpp +++ b/src/internet/cloudfileservice.cpp @@ -17,29 +17,26 @@ #include "playlist/playlist.h" #include "ui/iconloader.h" -CloudFileService::CloudFileService( - Application* app, - InternetModel* parent, - const QString& service_name, - const QString& service_id, - const QIcon& icon, - SettingsDialog::Page settings_page) - : InternetService(service_name, app, parent, parent), - root_(nullptr), - network_(new NetworkAccessManager(this)), - library_sort_model_(new QSortFilterProxyModel(this)), - playlist_manager_(app->playlist_manager()), - task_manager_(app->task_manager()), - icon_(icon), - settings_page_(settings_page) { +CloudFileService::CloudFileService(Application* app, InternetModel* parent, + const QString& service_name, + const QString& service_id, const QIcon& icon, + SettingsDialog::Page settings_page) + : InternetService(service_name, app, parent, parent), + root_(nullptr), + network_(new NetworkAccessManager(this)), + library_sort_model_(new QSortFilterProxyModel(this)), + playlist_manager_(app->playlist_manager()), + task_manager_(app->task_manager()), + icon_(icon), + settings_page_(settings_page) { library_backend_ = new LibraryBackend; library_backend_->moveToThread(app_->database()->thread()); QString songs_table = service_id + "_songs"; QString songs_fts_table = service_id + "_songs_fts"; - library_backend_->Init( - app->database(), songs_table, QString::null, QString::null, songs_fts_table); + library_backend_->Init(app->database(), songs_table, QString::null, + QString::null, songs_fts_table); library_model_ = new LibraryModel(library_backend_, app_, this); library_sort_model_->setSourceModel(library_model_); @@ -49,11 +46,7 @@ CloudFileService::CloudFileService( library_sort_model_->sort(0); app->global_search()->AddProvider(new LibrarySearchProvider( - library_backend_, - service_name, - service_id, - icon_, - true, app_, this)); + library_backend_, service_name, service_id, icon_, true, app_, this)); } QStandardItem* CloudFileService::CreateRootItem() { @@ -83,11 +76,8 @@ void CloudFileService::ShowContextMenu(const QPoint& global_pos) { if (!context_menu_) { context_menu_.reset(new QMenu); context_menu_->addActions(GetPlaylistActions()); - context_menu_->addAction( - IconLoader::Load("download"), - tr("Cover Manager"), - this, - SLOT(ShowCoverManager())); + context_menu_->addAction(IconLoader::Load("download"), tr("Cover Manager"), + this, SLOT(ShowCoverManager())); } context_menu_->popup(global_pos); } @@ -103,15 +93,16 @@ void CloudFileService::ShowCoverManager() { } void CloudFileService::AddToPlaylist(QMimeData* mime) { - playlist_manager_->current()->dropMimeData( - mime, Qt::CopyAction, -1, 0, QModelIndex()); + playlist_manager_->current()->dropMimeData(mime, Qt::CopyAction, -1, 0, + QModelIndex()); } void CloudFileService::ShowSettingsDialog() { app_->OpenSettingsDialogAtPage(settings_page_); } -bool CloudFileService::ShouldIndexFile(const QUrl& url, const QString& mime_type) const { +bool CloudFileService::ShouldIndexFile(const QUrl& url, + const QString& mime_type) const { if (!IsSupportedMimeType(mime_type)) { return false; } @@ -123,33 +114,28 @@ bool CloudFileService::ShouldIndexFile(const QUrl& url, const QString& mime_type return true; } -void CloudFileService::MaybeAddFileToDatabase( - const Song& metadata, - const QString& mime_type, - const QUrl& download_url, - const QString& authorisation) { +void CloudFileService::MaybeAddFileToDatabase(const Song& metadata, + const QString& mime_type, + const QUrl& download_url, + const QString& authorisation) { if (!ShouldIndexFile(metadata.url(), mime_type)) { return; } - const int task_id = task_manager_->StartTask( - tr("Indexing %1").arg(metadata.title())); + const int task_id = + task_manager_->StartTask(tr("Indexing %1").arg(metadata.title())); TagReaderClient::ReplyType* reply = app_->tag_reader_client()->ReadCloudFile( - download_url, - metadata.title(), - metadata.filesize(), - mime_type, + download_url, metadata.title(), metadata.filesize(), mime_type, authorisation); - NewClosure(reply, SIGNAL(Finished(bool)), - this, SLOT(ReadTagsFinished(TagReaderClient::ReplyType*,Song,int)), + NewClosure(reply, SIGNAL(Finished(bool)), this, + SLOT(ReadTagsFinished(TagReaderClient::ReplyType*, Song, int)), reply, metadata, task_id); } -void CloudFileService::ReadTagsFinished( - TagReaderClient::ReplyType* reply, - const Song& metadata, - const int task_id) { +void CloudFileService::ReadTagsFinished(TagReaderClient::ReplyType* reply, + const Song& metadata, + const int task_id) { reply->deleteLater(); TaskManager::ScopedTask(task_id, task_manager_); @@ -173,14 +159,10 @@ void CloudFileService::ReadTagsFinished( } bool CloudFileService::IsSupportedMimeType(const QString& mime_type) const { - return mime_type == "audio/ogg" || - mime_type == "audio/mpeg" || - mime_type == "audio/mp4" || - mime_type == "audio/flac" || - mime_type == "audio/x-flac" || - mime_type == "application/ogg" || - mime_type == "application/x-flac" || - mime_type == "audio/x-ms-wma"; + return mime_type == "audio/ogg" || mime_type == "audio/mpeg" || + mime_type == "audio/mp4" || mime_type == "audio/flac" || + mime_type == "audio/x-flac" || mime_type == "application/ogg" || + mime_type == "application/x-flac" || mime_type == "audio/x-ms-wma"; } QString CloudFileService::GuessMimeTypeForFile(const QString& filename) const { diff --git a/src/internet/cloudfileservice.h b/src/internet/cloudfileservice.h index d31a54ccc..1fce347d4 100644 --- a/src/internet/cloudfileservice.h +++ b/src/internet/cloudfileservice.h @@ -20,13 +20,9 @@ class PlaylistManager; class CloudFileService : public InternetService { Q_OBJECT public: - CloudFileService( - Application* app, - InternetModel* parent, - const QString& service_name, - const QString& service_id, - const QIcon& icon, - SettingsDialog::Page settings_page); + CloudFileService(Application* app, InternetModel* parent, + const QString& service_name, const QString& service_id, + const QIcon& icon, SettingsDialog::Page settings_page); // InternetService virtual QStandardItem* CreateRootItem(); @@ -37,23 +33,19 @@ class CloudFileService : public InternetService { virtual bool has_credentials() const = 0; virtual void Connect() = 0; virtual bool ShouldIndexFile(const QUrl& url, const QString& mime_type) const; - virtual void MaybeAddFileToDatabase( - const Song& metadata, - const QString& mime_type, - const QUrl& download_url, - const QString& authorisation); + virtual void MaybeAddFileToDatabase(const Song& metadata, + const QString& mime_type, + const QUrl& download_url, + const QString& authorisation); virtual bool IsSupportedMimeType(const QString& mime_type) const; QString GuessMimeTypeForFile(const QString& filename) const; - protected slots: void ShowCoverManager(); void AddToPlaylist(QMimeData* mime); void ShowSettingsDialog(); - void ReadTagsFinished( - TagReaderClient::ReplyType* reply, - const Song& metadata, - const int task_id); + void ReadTagsFinished(TagReaderClient::ReplyType* reply, const Song& metadata, + const int task_id); protected: QStandardItem* root_; diff --git a/src/internet/digitallyimportedclient.cpp b/src/internet/digitallyimportedclient.cpp index 9f7bde819..a4b4c056f 100644 --- a/src/internet/digitallyimportedclient.cpp +++ b/src/internet/digitallyimportedclient.cpp @@ -35,20 +35,22 @@ const char* DigitallyImportedClient::kAuthUrl = "http://api.audioaddict.com/v1/%1/members/authenticate"; const char* DigitallyImportedClient::kChannelListUrl = - "http://api.v2.audioaddict.com/v1/%1/mobile/batch_update?asset_group_key=mobile_icons&stream_set_key="; + "http://api.v2.audioaddict.com/v1/%1/mobile/" + "batch_update?asset_group_key=mobile_icons&stream_set_key="; +DigitallyImportedClient::DigitallyImportedClient(const QString& service_name, + QObject* parent) + : QObject(parent), + network_(new NetworkAccessManager(this)), + service_name_(service_name) {} -DigitallyImportedClient::DigitallyImportedClient(const QString& service_name, QObject* parent) - : QObject(parent), - network_(new NetworkAccessManager(this)), - service_name_(service_name) -{ -} - -void DigitallyImportedClient::SetAuthorisationHeader(QNetworkRequest* req) const { +void DigitallyImportedClient::SetAuthorisationHeader(QNetworkRequest* req) + const { req->setRawHeader("Authorization", - "Basic " + QString("%1:%2").arg(kApiUsername, kApiPassword) - .toAscii().toBase64()); + "Basic " + QString("%1:%2") + .arg(kApiUsername, kApiPassword) + .toAscii() + .toBase64()); } QNetworkReply* DigitallyImportedClient::Auth(const QString& username, @@ -57,18 +59,19 @@ QNetworkReply* DigitallyImportedClient::Auth(const QString& username, SetAuthorisationHeader(&req); QByteArray postdata = "username=" + QUrl::toPercentEncoding(username) + - "&password=" + QUrl::toPercentEncoding(password); + "&password=" + QUrl::toPercentEncoding(password); return network_->post(req, postdata); } -DigitallyImportedClient::AuthReply -DigitallyImportedClient::ParseAuthReply(QNetworkReply* reply) const { +DigitallyImportedClient::AuthReply DigitallyImportedClient::ParseAuthReply( + QNetworkReply* reply) const { AuthReply ret; ret.success_ = false; ret.error_reason_ = tr("Unknown error"); - const int http_status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + const int http_status = + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (http_status == 403) { ret.error_reason_ = reply->readAll(); return ret; @@ -83,15 +86,15 @@ DigitallyImportedClient::ParseAuthReply(QNetworkReply* reply) const { return ret; } - QVariantList subscriptions = data.value("subscriptions", QVariantList()).toList(); + QVariantList subscriptions = + data.value("subscriptions", QVariantList()).toList(); if (subscriptions.isEmpty() || subscriptions[0].toMap().value("status").toString() != "active") { ret.error_reason_ = tr("You do not have an active subscription"); return ret; } - if (!data.contains("first_name") || - !data.contains("last_name") || + if (!data.contains("first_name") || !data.contains("last_name") || !subscriptions[0].toMap().contains("expires_on") || !data.contains("listen_key")) return ret; @@ -99,40 +102,40 @@ DigitallyImportedClient::ParseAuthReply(QNetworkReply* reply) const { ret.success_ = true; ret.first_name_ = data["first_name"].toString(); ret.last_name_ = data["last_name"].toString(); - ret.expires_ = QDateTime::fromString(subscriptions[0].toMap()["expires_on"].toString(), Qt::ISODate); + ret.expires_ = QDateTime::fromString( + subscriptions[0].toMap()["expires_on"].toString(), Qt::ISODate); ret.listen_hash_ = data["listen_key"].toString(); return ret; } QNetworkReply* DigitallyImportedClient::GetChannelList() { - //QNetworkRequest req(QUrl(QString(kChannelListUrl))); + // QNetworkRequest req(QUrl(QString(kChannelListUrl))); QNetworkRequest req(QUrl(QString(kChannelListUrl).arg(service_name_))); SetAuthorisationHeader(&req); return network_->get(req); } -DigitallyImportedClient::ChannelList -DigitallyImportedClient::ParseChannelList(QNetworkReply* reply) const { +DigitallyImportedClient::ChannelList DigitallyImportedClient::ParseChannelList( + QNetworkReply* reply) const { ChannelList ret; QJson::Parser parser; QVariantMap data = parser.parse(reply).toMap(); - if (!data.contains("channel_filters")) - return ret; + if (!data.contains("channel_filters")) return ret; QVariantList filters = data["channel_filters"].toList(); - foreach (const QVariant& filter, filters) { + foreach(const QVariant & filter, filters) { // Find the filter called "All" QVariantMap filter_map = filter.toMap(); - if (filter_map.value("name", QString()).toString() != "All") - continue; + if (filter_map.value("name", QString()).toString() != "All") continue; // Add all its stations to the result - QVariantList channels = filter_map.value("channels", QVariantList()).toList(); - foreach (const QVariant& channel_var, channels) { + QVariantList channels = + filter_map.value("channels", QVariantList()).toList(); + foreach(const QVariant & channel_var, channels) { QVariantMap channel_map = channel_var.toMap(); Channel channel; @@ -150,20 +153,16 @@ DigitallyImportedClient::ParseChannelList(QNetworkReply* reply) const { return ret; } -QDataStream& operator<<(QDataStream& out, const DigitallyImportedClient::Channel& channel) { - out << channel.art_url_ - << channel.director_ - << channel.description_ - << channel.name_ - << channel.key_; +QDataStream& operator<<(QDataStream& out, + const DigitallyImportedClient::Channel& channel) { + out << channel.art_url_ << channel.director_ << channel.description_ + << channel.name_ << channel.key_; return out; } -QDataStream& operator>>(QDataStream& in, DigitallyImportedClient::Channel& channel) { - in >> channel.art_url_ - >> channel.director_ - >> channel.description_ - >> channel.name_ - >> channel.key_; +QDataStream& operator>>(QDataStream& in, + DigitallyImportedClient::Channel& channel) { + in >> channel.art_url_ >> channel.director_ >> channel.description_ >> + channel.name_ >> channel.key_; return in; } diff --git a/src/internet/digitallyimportedclient.h b/src/internet/digitallyimportedclient.h index e42508f16..dbd0692e1 100644 --- a/src/internet/digitallyimportedclient.h +++ b/src/internet/digitallyimportedclient.h @@ -30,7 +30,7 @@ class QNetworkRequest; class DigitallyImportedClient : public QObject { Q_OBJECT -public: + public: DigitallyImportedClient(const QString& service_name, QObject* parent = 0); static const char* kApiUsername; @@ -59,7 +59,7 @@ public: QString name_; QString key_; - bool operator <(const Channel& other) const { return name_ < other.name_; } + bool operator<(const Channel& other) const { return name_ < other.name_; } }; typedef QList ChannelList; @@ -69,17 +69,19 @@ public: QNetworkReply* GetChannelList(); ChannelList ParseChannelList(QNetworkReply* reply) const; -private: + private: void SetAuthorisationHeader(QNetworkRequest* req) const; -private: + private: QNetworkAccessManager* network_; QString service_name_; }; -QDataStream& operator<<(QDataStream& out, const DigitallyImportedClient::Channel& channel); -QDataStream& operator>>(QDataStream& in, DigitallyImportedClient::Channel& channel); +QDataStream& operator<<(QDataStream& out, + const DigitallyImportedClient::Channel& channel); +QDataStream& operator>>(QDataStream& in, + DigitallyImportedClient::Channel& channel); Q_DECLARE_METATYPE(DigitallyImportedClient::Channel) -#endif // DIGITALLYIMPORTEDCLIENT_H +#endif // DIGITALLYIMPORTEDCLIENT_H diff --git a/src/internet/digitallyimportedservicebase.cpp b/src/internet/digitallyimportedservicebase.cpp index 3e363afbc..025b72d28 100644 --- a/src/internet/digitallyimportedservicebase.cpp +++ b/src/internet/digitallyimportedservicebase.cpp @@ -37,50 +37,43 @@ const char* DigitallyImportedServiceBase::kSettingsGroup = "digitally_imported"; const int DigitallyImportedServiceBase::kStreamsCacheDurationSecs = - 60 * 60 * 24 * 14; // 2 weeks - + 60 * 60 * 24 * 14; // 2 weeks DigitallyImportedServiceBase::DigitallyImportedServiceBase( - const QString& name, - const QString& description, - const QUrl& homepage_url, - const QIcon& icon, - const QString& api_service_name, - Application* app, InternetModel* model, QObject* parent) - : InternetService(name, app, model, parent), - homepage_url_(homepage_url), - icon_(icon), - service_description_(description), - api_service_name_(api_service_name), - network_(new NetworkAccessManager(this)), - url_handler_(new DigitallyImportedUrlHandler(app, this)), - basic_audio_type_(1), - premium_audio_type_(2), - root_(nullptr), - saved_channels_(kSettingsGroup, api_service_name, kStreamsCacheDurationSecs), - api_client_(new DigitallyImportedClient(api_service_name, this)) -{ + const QString& name, const QString& description, const QUrl& homepage_url, + const QIcon& icon, const QString& api_service_name, Application* app, + InternetModel* model, QObject* parent) + : InternetService(name, app, model, parent), + homepage_url_(homepage_url), + icon_(icon), + service_description_(description), + api_service_name_(api_service_name), + network_(new NetworkAccessManager(this)), + url_handler_(new DigitallyImportedUrlHandler(app, this)), + basic_audio_type_(1), + premium_audio_type_(2), + root_(nullptr), + saved_channels_(kSettingsGroup, api_service_name, + kStreamsCacheDurationSecs), + api_client_(new DigitallyImportedClient(api_service_name, this)) { ReloadSettings(); model->app()->player()->RegisterUrlHandler(url_handler_); model->app()->global_search()->AddProvider( - new DigitallyImportedSearchProvider(this, app_, this)); + new DigitallyImportedSearchProvider(this, app_, this)); - basic_playlists_ - << "http://%1/public3/%2.pls" - << "http://%1/public1/%2.pls" - << "http://%1/public5/%2.asx"; + basic_playlists_ << "http://%1/public3/%2.pls" + << "http://%1/public1/%2.pls" + << "http://%1/public5/%2.asx"; - premium_playlists_ - << "http://%1/premium_high/%2.pls?hash=%3" - << "http://%1/premium_medium/%2.pls?hash=%3" - << "http://%1/premium/%2.pls?hash=%3" - << "http://%1/premium_wma_low/%2.asx?hash=%3" - << "http://%1/premium_wma/%2.asx?hash=%3"; + premium_playlists_ << "http://%1/premium_high/%2.pls?hash=%3" + << "http://%1/premium_medium/%2.pls?hash=%3" + << "http://%1/premium/%2.pls?hash=%3" + << "http://%1/premium_wma_low/%2.asx?hash=%3" + << "http://%1/premium_wma/%2.asx?hash=%3"; } -DigitallyImportedServiceBase::~DigitallyImportedServiceBase() { -} +DigitallyImportedServiceBase::~DigitallyImportedServiceBase() {} QStandardItem* DigitallyImportedServiceBase::CreateRootItem() { root_ = new QStandardItem(icon_, service_description_); @@ -108,41 +101,41 @@ void DigitallyImportedServiceBase::ForceRefreshStreams() { int task_id = app_->task_manager()->StartTask(tr("Getting streams")); QNetworkReply* reply = api_client_->GetChannelList(); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(RefreshStreamsFinished(QNetworkReply*,int)), - reply, task_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(RefreshStreamsFinished(QNetworkReply*, int)), reply, task_id); } -void DigitallyImportedServiceBase::RefreshStreamsFinished(QNetworkReply* reply, int task_id) { +void DigitallyImportedServiceBase::RefreshStreamsFinished(QNetworkReply* reply, + int task_id) { app_->task_manager()->SetTaskFinished(task_id); reply->deleteLater(); // Parse the list and sort by name - DigitallyImportedClient::ChannelList channels = api_client_->ParseChannelList(reply); + DigitallyImportedClient::ChannelList channels = + api_client_->ParseChannelList(reply); qSort(channels); saved_channels_.Update(channels); // Only update the item's children if it's already been populated - if (!root_->data(InternetModel::Role_CanLazyLoad).toBool()) - PopulateStreams(); + if (!root_->data(InternetModel::Role_CanLazyLoad).toBool()) PopulateStreams(); emit StreamsChanged(); } void DigitallyImportedServiceBase::PopulateStreams() { - if (root_->hasChildren()) - root_->removeRows(0, root_->rowCount()); + if (root_->hasChildren()) root_->removeRows(0, root_->rowCount()); // Add each stream to the model - foreach (const DigitallyImportedClient::Channel& channel, saved_channels_) { + foreach(const DigitallyImportedClient::Channel & channel, saved_channels_) { Song song; SongFromChannel(channel, &song); - QStandardItem* item = new QStandardItem(QIcon(":/last.fm/icon_radio.png"), - song.title()); + QStandardItem* item = + new QStandardItem(QIcon(":/last.fm/icon_radio.png"), song.title()); item->setData(channel.description_, Qt::ToolTipRole); - item->setData(InternetModel::PlayBehaviour_SingleItem, InternetModel::Role_PlayBehaviour); + item->setData(InternetModel::PlayBehaviour_SingleItem, + InternetModel::Role_PlayBehaviour); item->setData(QVariant::fromValue(song), InternetModel::Role_SongMetadata); root_->appendRow(item); } @@ -179,11 +172,10 @@ void DigitallyImportedServiceBase::ShowContextMenu(const QPoint& global_pos) { tr("Open %1 in browser").arg(homepage_url_.host()), this, SLOT(Homepage())); context_menu_->addAction(IconLoader::Load("view-refresh"), - tr("Refresh streams"), - this, SLOT(ForceRefreshStreams())); + tr("Refresh streams"), this, + SLOT(ForceRefreshStreams())); context_menu_->addSeparator(); - context_menu_->addAction(IconLoader::Load("configure"), - tr("Configure..."), + context_menu_->addAction(IconLoader::Load("configure"), tr("Configure..."), this, SLOT(ShowSettingsDialog())); } @@ -197,7 +189,8 @@ bool DigitallyImportedServiceBase::is_premium_account() const { void DigitallyImportedServiceBase::LoadPlaylistFinished(QNetworkReply* reply) { reply->deleteLater(); - if (reply->header(QNetworkRequest::ContentTypeHeader).toString() == "text/html") { + if (reply->header(QNetworkRequest::ContentTypeHeader).toString() == + "text/html") { url_handler_->CancelTask(); emit StreamError(tr("Error loading di.fm playlist")); @@ -212,7 +205,8 @@ void DigitallyImportedServiceBase::ShowSettingsDialog() { DigitallyImportedClient::ChannelList DigitallyImportedServiceBase::Channels() { if (IsChannelListStale()) { - metaObject()->invokeMethod(this, "ForceRefreshStreams", Qt::QueuedConnection); + metaObject()->invokeMethod(this, "ForceRefreshStreams", + Qt::QueuedConnection); } return saved_channels_; @@ -225,11 +219,10 @@ void DigitallyImportedServiceBase::LoadStation(const QString& key) { const QString host = "listen." + homepage_url_.host().remove("www."); if (is_premium_account()) { - playlist_url = QUrl(premium_playlists_[premium_audio_type_].arg( - host, key, listen_hash_)); + playlist_url = QUrl( + premium_playlists_[premium_audio_type_].arg(host, key, listen_hash_)); } else { - playlist_url = QUrl(basic_playlists_[basic_audio_type_].arg( - host, key)); + playlist_url = QUrl(basic_playlists_[basic_audio_type_].arg(host, key)); } qLog(Debug) << "Getting playlist URL" << playlist_url; @@ -239,47 +232,30 @@ void DigitallyImportedServiceBase::LoadStation(const QString& key) { SLOT(LoadPlaylistFinished(QNetworkReply*)), reply); } +DigitallyImportedService::DigitallyImportedService(Application* app, + InternetModel* model, + QObject* parent) + : DigitallyImportedServiceBase("DigitallyImported", "Digitally Imported", + QUrl("http://www.di.fm"), + QIcon(":/providers/digitallyimported.png"), + "di", app, model, parent) {} -DigitallyImportedService::DigitallyImportedService( - Application* app, InternetModel* model, QObject* parent) - : DigitallyImportedServiceBase("DigitallyImported", - "Digitally Imported", - QUrl("http://www.di.fm"), - QIcon(":/providers/digitallyimported.png"), - "di", - app, model, parent) -{ +SkyFmService::SkyFmService(Application* app, InternetModel* model, + QObject* parent) + : DigitallyImportedServiceBase( + "SKY.fm", "SKY.fm", QUrl("http://www.sky.fm"), + QIcon(":/providers/skyfm.png"), "sky", app, model, parent) {} + +JazzRadioService::JazzRadioService(Application* app, InternetModel* model, + QObject* parent) + : DigitallyImportedServiceBase( + "JazzRadio", "JAZZRADIO.com", QUrl("http://www.jazzradio.com"), + QIcon(":/providers/jazzradio.png"), "jazzradio", app, model, parent) { } -SkyFmService::SkyFmService( - Application* app, InternetModel* model, QObject* parent) - : DigitallyImportedServiceBase("SKY.fm", - "SKY.fm", - QUrl("http://www.sky.fm"), - QIcon(":/providers/skyfm.png"), - "sky", - app, model, parent) -{ -} - -JazzRadioService::JazzRadioService( - Application* app, InternetModel* model, QObject* parent) - : DigitallyImportedServiceBase("JazzRadio", - "JAZZRADIO.com", - QUrl("http://www.jazzradio.com"), - QIcon(":/providers/jazzradio.png"), - "jazzradio", - app, model, parent) -{ -} - -RockRadioService::RockRadioService( - Application* app, InternetModel* model, QObject* parent) - : DigitallyImportedServiceBase("RockRadio", - "ROCKRADIO.com", - QUrl("http://www.rockradio.com"), - QIcon(":/providers/rockradio.png"), - "rockradio", - app, model, parent) -{ +RockRadioService::RockRadioService(Application* app, InternetModel* model, + QObject* parent) + : DigitallyImportedServiceBase( + "RockRadio", "ROCKRADIO.com", QUrl("http://www.rockradio.com"), + QIcon(":/providers/rockradio.png"), "rockradio", app, model, parent) { } diff --git a/src/internet/digitallyimportedservicebase.h b/src/internet/digitallyimportedservicebase.h index d58f3c614..5471c780e 100644 --- a/src/internet/digitallyimportedservicebase.h +++ b/src/internet/digitallyimportedservicebase.h @@ -29,19 +29,15 @@ class DigitallyImportedUrlHandler; class QNetworkAccessManager; - class DigitallyImportedServiceBase : public InternetService { Q_OBJECT friend class DigitallyImportedUrlHandler; -public: - DigitallyImportedServiceBase(const QString& name, - const QString& description, - const QUrl& homepage_url, - const QIcon& icon, + public: + DigitallyImportedServiceBase(const QString& name, const QString& description, + const QUrl& homepage_url, const QIcon& icon, const QString& api_service_name, - Application* app, - InternetModel* model, + Application* app, InternetModel* model, QObject* parent = NULL); ~DigitallyImportedServiceBase(); @@ -66,25 +62,25 @@ public: void SongFromChannel(const DigitallyImportedClient::Channel& channel, Song* song) const; -public slots: + public slots: void ShowSettingsDialog(); signals: void StreamsChanged(); -private slots: + private slots: void LoadPlaylistFinished(QNetworkReply* reply); void Homepage(); void ForceRefreshStreams(); void RefreshStreams(); void RefreshStreamsFinished(QNetworkReply* reply, int task_id); -private: + private: void PopulateStreams(); void LoadStation(const QString& key); -private: + private: // Set by subclasses through the constructor QUrl homepage_url_; QIcon icon_; @@ -113,23 +109,26 @@ private: }; class DigitallyImportedService : public DigitallyImportedServiceBase { -public: - DigitallyImportedService(Application* app, InternetModel* model, QObject* parent = NULL); + public: + DigitallyImportedService(Application* app, InternetModel* model, + QObject* parent = NULL); }; class SkyFmService : public DigitallyImportedServiceBase { -public: + public: SkyFmService(Application* app, InternetModel* model, QObject* parent = NULL); }; class JazzRadioService : public DigitallyImportedServiceBase { -public: - JazzRadioService(Application* app, InternetModel* model, QObject* parent = NULL); + public: + JazzRadioService(Application* app, InternetModel* model, + QObject* parent = NULL); }; class RockRadioService : public DigitallyImportedServiceBase { -public: - RockRadioService(Application* app, InternetModel* model, QObject* parent = NULL); + public: + RockRadioService(Application* app, InternetModel* model, + QObject* parent = NULL); }; -#endif // DIGITALLYIMPORTEDSERVICEBASE_H +#endif // DIGITALLYIMPORTEDSERVICEBASE_H diff --git a/src/internet/digitallyimportedsettingspage.cpp b/src/internet/digitallyimportedsettingspage.cpp index 7a4470f57..f06a2db53 100644 --- a/src/internet/digitallyimportedsettingspage.cpp +++ b/src/internet/digitallyimportedsettingspage.cpp @@ -25,12 +25,11 @@ #include #include - -DigitallyImportedSettingsPage::DigitallyImportedSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_DigitallyImportedSettingsPage), - client_(new DigitallyImportedClient("di", this)) -{ +DigitallyImportedSettingsPage::DigitallyImportedSettingsPage( + SettingsDialog* dialog) + : SettingsPage(dialog), + ui_(new Ui_DigitallyImportedSettingsPage), + client_(new DigitallyImportedClient("di", this)) { ui_->setupUi(this); setWindowIcon(QIcon(":/providers/digitallyimported-32.png")); @@ -42,22 +41,21 @@ DigitallyImportedSettingsPage::DigitallyImportedSettingsPage(SettingsDialog* dia ui_->login_state->AddCredentialField(ui_->password); ui_->login_state->AddCredentialGroup(ui_->credential_group); - ui_->login_state->SetAccountTypeText(tr( - "You can listen for free without an account, but Premium members can " - "listen to higher quality streams without advertisements.")); + ui_->login_state->SetAccountTypeText( + tr("You can listen for free without an account, but Premium members can " + "listen to higher quality streams without advertisements.")); ui_->login_state->SetAccountTypeVisible(true); } -DigitallyImportedSettingsPage::~DigitallyImportedSettingsPage() { - delete ui_; -} +DigitallyImportedSettingsPage::~DigitallyImportedSettingsPage() { delete ui_; } void DigitallyImportedSettingsPage::Login() { ui_->login_state->SetLoggedIn(LoginStateWidget::LoginInProgress); - QNetworkReply* reply = client_->Auth(ui_->username->text(), ui_->password->text()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(LoginFinished(QNetworkReply*)), reply); + QNetworkReply* reply = + client_->Auth(ui_->username->text(), ui_->password->text()); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(LoginFinished(QNetworkReply*)), reply); } void DigitallyImportedSettingsPage::LoginFinished(QNetworkReply* reply) { @@ -84,8 +82,9 @@ void DigitallyImportedSettingsPage::LoginFinished(QNetworkReply* reply) { } } -void DigitallyImportedSettingsPage::UpdateLoginState( - const QString& listen_hash, const QString& name, const QDateTime& expires) { +void DigitallyImportedSettingsPage::UpdateLoginState(const QString& listen_hash, + const QString& name, + const QDateTime& expires) { if (listen_hash.isEmpty()) { ui_->login_state->SetLoggedIn(LoginStateWidget::LoggedOut); ui_->login_state->SetExpires(QDate()); @@ -114,8 +113,10 @@ void DigitallyImportedSettingsPage::Load() { QSettings s; s.beginGroup(DigitallyImportedServiceBase::kSettingsGroup); - ui_->basic_audio_type->setCurrentIndex(s.value("basic_audio_type", 1).toInt()); - ui_->premium_audio_type->setCurrentIndex(s.value("premium_audio_type", 2).toInt()); + ui_->basic_audio_type->setCurrentIndex( + s.value("basic_audio_type", 1).toInt()); + ui_->premium_audio_type->setCurrentIndex( + s.value("premium_audio_type", 2).toInt()); ui_->username->setText(s.value("username").toString()); UpdateLoginState(s.value("listen_hash").toString(), @@ -131,5 +132,3 @@ void DigitallyImportedSettingsPage::Save() { s.setValue("premium_audio_type", ui_->premium_audio_type->currentIndex()); s.setValue("username", ui_->username->text()); } - - diff --git a/src/internet/digitallyimportedsettingspage.h b/src/internet/digitallyimportedsettingspage.h index eaf31ef45..f22947925 100644 --- a/src/internet/digitallyimportedsettingspage.h +++ b/src/internet/digitallyimportedsettingspage.h @@ -28,27 +28,27 @@ class QNetworkReply; class DigitallyImportedSettingsPage : public SettingsPage { Q_OBJECT -public: + public: DigitallyImportedSettingsPage(SettingsDialog* dialog); ~DigitallyImportedSettingsPage(); void Load(); void Save(); -private slots: + private slots: void Login(); void Logout(); void LoginFinished(QNetworkReply* reply); -private: + private: void UpdateLoginState(const QString& listen_hash, const QString& name, const QDateTime& expires); -private: + private: Ui_DigitallyImportedSettingsPage* ui_; DigitallyImportedClient* client_; }; -#endif // DIGITALLYIMPORTEDSETTINGSPAGE_H +#endif // DIGITALLYIMPORTEDSETTINGSPAGE_H diff --git a/src/internet/digitallyimportedurlhandler.cpp b/src/internet/digitallyimportedurlhandler.cpp index 651097148..c57cdf371 100644 --- a/src/internet/digitallyimportedurlhandler.cpp +++ b/src/internet/digitallyimportedurlhandler.cpp @@ -25,12 +25,7 @@ DigitallyImportedUrlHandler::DigitallyImportedUrlHandler( Application* app, DigitallyImportedServiceBase* service) - : UrlHandler(service), - app_(app), - service_(service), - task_id_(-1) -{ -} + : UrlHandler(service), app_(app), service_(service), task_id_(-1) {} QString DigitallyImportedUrlHandler::scheme() const { return service_->api_service_name(); @@ -49,7 +44,8 @@ QIcon DigitallyImportedUrlHandler::icon() const { return QIcon(); } -UrlHandler::LoadResult DigitallyImportedUrlHandler::StartLoading(const QUrl& url) { +UrlHandler::LoadResult DigitallyImportedUrlHandler::StartLoading( + const QUrl& url) { LoadResult ret(url); if (task_id_ != -1) { return ret; @@ -91,7 +87,7 @@ void DigitallyImportedUrlHandler::LoadPlaylistFinished(QIODevice* device) { } emit AsyncLoadComplete(LoadResult( - last_original_url_, LoadResult::TrackAvailable, songs[0].url())); + last_original_url_, LoadResult::TrackAvailable, songs[0].url())); } void DigitallyImportedUrlHandler::CancelTask() { diff --git a/src/internet/digitallyimportedurlhandler.h b/src/internet/digitallyimportedurlhandler.h index 9cd398c5f..3386a6257 100644 --- a/src/internet/digitallyimportedurlhandler.h +++ b/src/internet/digitallyimportedurlhandler.h @@ -23,10 +23,10 @@ class Application; class DigitallyImportedServiceBase; - class DigitallyImportedUrlHandler : public UrlHandler { -public: - DigitallyImportedUrlHandler(Application* app, DigitallyImportedServiceBase* service); + public: + DigitallyImportedUrlHandler(Application* app, + DigitallyImportedServiceBase* service); QString scheme() const; QIcon icon() const; @@ -35,7 +35,7 @@ public: void CancelTask(); void LoadPlaylistFinished(QIODevice* device); -private: + private: Application* app_; DigitallyImportedServiceBase* service_; int task_id_; @@ -43,4 +43,4 @@ private: QUrl last_original_url_; }; -#endif // DIGITALLYIMPORTEDURLHANDLER_H +#endif // DIGITALLYIMPORTEDURLHANDLER_H diff --git a/src/internet/dropboxauthenticator.cpp b/src/internet/dropboxauthenticator.cpp index ce3239df6..e5e8eac56 100644 --- a/src/internet/dropboxauthenticator.cpp +++ b/src/internet/dropboxauthenticator.cpp @@ -32,20 +32,18 @@ static const char* kAccountInfoEndpoint = } // namespace DropboxAuthenticator::DropboxAuthenticator(QObject* parent) - : QObject(parent), - network_(new NetworkAccessManager(this)) { -} + : QObject(parent), network_(new NetworkAccessManager(this)) {} void DropboxAuthenticator::StartAuthorisation() { QUrl url(kRequestTokenEndpoint); - QByteArray authorisation_header = GenerateAuthorisationHeader( - QString::null, QString::null); + QByteArray authorisation_header = + GenerateAuthorisationHeader(QString::null, QString::null); QNetworkRequest request(url); request.setRawHeader("Authorization", authorisation_header); QNetworkReply* reply = network_->post(request, QByteArray()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(RequestTokenFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(RequestTokenFinished(QNetworkReply*)), reply); } namespace { @@ -54,7 +52,7 @@ namespace { QMap ParseParamList(const QString& params) { QMap ret; QStringList components = params.split("&"); - foreach (const QString& component, components) { + foreach(const QString & component, components) { QStringList pairs = component.split("="); if (pairs.size() != 2) { continue; @@ -63,7 +61,6 @@ QMap ParseParamList(const QString& params) { } return ret; } - } void DropboxAuthenticator::RequestTokenFinished(QNetworkReply* reply) { @@ -79,8 +76,8 @@ void DropboxAuthenticator::Authorise() { LocalRedirectServer* server = new LocalRedirectServer(this); server->Listen(); - NewClosure(server, SIGNAL(Finished()), - this, SLOT(RedirectArrived(LocalRedirectServer*)), server); + NewClosure(server, SIGNAL(Finished()), this, + SLOT(RedirectArrived(LocalRedirectServer*)), server); QUrl url(kAuthoriseEndpoint); url.addQueryItem("oauth_token", token_); @@ -100,13 +97,13 @@ void DropboxAuthenticator::RedirectArrived(LocalRedirectServer* server) { void DropboxAuthenticator::RequestAccessToken() { QUrl url(kAccessTokenEndpoint); QNetworkRequest request(url); - QByteArray authorisation_header = GenerateAuthorisationHeader( - token_, secret_); + QByteArray authorisation_header = + GenerateAuthorisationHeader(token_, secret_); request.setRawHeader("Authorization", authorisation_header); QNetworkReply* reply = network_->post(request, QByteArray()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(RequestAccessTokenFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(RequestAccessTokenFinished(QNetworkReply*)), reply); } void DropboxAuthenticator::RequestAccessTokenFinished(QNetworkReply* reply) { @@ -125,11 +122,10 @@ QByteArray DropboxAuthenticator::GenerateAuthorisationHeader() { } QByteArray DropboxAuthenticator::GenerateAuthorisationHeader( - const QString& token, - const QString& token_secret) { + const QString& token, const QString& token_secret) { typedef QPair Param; - QByteArray signature = QUrl::toPercentEncoding( - QString("%1&%2").arg(kAppSecret, token_secret)); + QByteArray signature = + QUrl::toPercentEncoding(QString("%1&%2").arg(kAppSecret, token_secret)); QList params; params << Param("oauth_consumer_key", kAppKey) << Param("oauth_signature_method", "PLAINTEXT") @@ -140,7 +136,7 @@ QByteArray DropboxAuthenticator::GenerateAuthorisationHeader( params << Param("oauth_token", token); } QStringList encoded_params; - foreach (const Param& p, params) { + foreach(const Param & p, params) { encoded_params << QString("%1=\"%2\"").arg(p.first, p.second); } QString authorisation_header = QString("OAuth ") + encoded_params.join(", "); @@ -153,11 +149,12 @@ void DropboxAuthenticator::RequestAccountInformation() { request.setRawHeader("Authorization", GenerateAuthorisationHeader()); qLog(Debug) << Q_FUNC_INFO << url << request.rawHeader("Authorization"); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(RequestAccountInformationFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(RequestAccountInformationFinished(QNetworkReply*)), reply); } -void DropboxAuthenticator::RequestAccountInformationFinished(QNetworkReply* reply) { +void DropboxAuthenticator::RequestAccountInformationFinished( + QNetworkReply* reply) { reply->deleteLater(); QJson::Parser parser; QVariantMap response = parser.parse(reply).toMap(); diff --git a/src/internet/dropboxauthenticator.h b/src/internet/dropboxauthenticator.h index 7a7e0875f..7457390b4 100644 --- a/src/internet/dropboxauthenticator.h +++ b/src/internet/dropboxauthenticator.h @@ -19,10 +19,10 @@ class DropboxAuthenticator : public QObject { const QString& uid() const { return uid_; } const QString& name() const { return name_; } - static QByteArray GenerateAuthorisationHeader( - const QString& token, const QString& secret); + static QByteArray GenerateAuthorisationHeader(const QString& token, + const QString& secret); - signals: +signals: void Finished(); private slots: @@ -45,7 +45,6 @@ class DropboxAuthenticator : public QObject { QString token_; QString secret_; - // Permanent OAuth access tokens. QString access_token_; QString access_token_secret_; diff --git a/src/internet/dropboxservice.cpp b/src/internet/dropboxservice.cpp index 75637616e..b6863b7cc 100644 --- a/src/internet/dropboxservice.cpp +++ b/src/internet/dropboxservice.cpp @@ -24,21 +24,17 @@ namespace { static const char* kServiceId = "dropbox"; -static const char* kMediaEndpoint = - "https://api.dropbox.com/1/media/dropbox/"; -static const char* kDeltaEndpoint = - "https://api.dropbox.com/1/delta"; +static const char* kMediaEndpoint = "https://api.dropbox.com/1/media/dropbox/"; +static const char* kDeltaEndpoint = "https://api.dropbox.com/1/delta"; static const char* kLongPollEndpoint = "https://api-notify.dropbox.com/1/longpoll_delta"; } // namespace DropboxService::DropboxService(Application* app, InternetModel* parent) - : CloudFileService( - app, parent, - kServiceName, kServiceId, - QIcon(":/providers/dropbox.png"), - SettingsDialog::Page_Dropbox), + : CloudFileService(app, parent, kServiceName, kServiceId, + QIcon(":/providers/dropbox.png"), + SettingsDialog::Page_Dropbox), network_(new NetworkAccessManager(this)) { QSettings settings; settings.beginGroup(kSettingsGroup); @@ -59,7 +55,8 @@ void DropboxService::Connect() { } } -void DropboxService::AuthenticationFinished(DropboxAuthenticator* authenticator) { +void DropboxService::AuthenticationFinished( + DropboxAuthenticator* authenticator) { authenticator->deleteLater(); access_token_ = authenticator->access_token(); @@ -79,8 +76,7 @@ void DropboxService::AuthenticationFinished(DropboxAuthenticator* authenticator) QByteArray DropboxService::GenerateAuthorisationHeader() { return DropboxAuthenticator::GenerateAuthorisationHeader( - access_token_, - access_token_secret_); + access_token_, access_token_secret_); } void DropboxService::RequestFileList() { @@ -95,8 +91,8 @@ void DropboxService::RequestFileList() { request.setRawHeader("Authorization", GenerateAuthorisationHeader()); QNetworkReply* reply = network_->post(request, QByteArray()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(RequestFileListFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(RequestFileListFinished(QNetworkReply*)), reply); } void DropboxService::RequestFileListFinished(QNetworkReply* reply) { @@ -104,8 +100,7 @@ void DropboxService::RequestFileListFinished(QNetworkReply* reply) { QJson::Parser parser; QVariantMap response = parser.parse(reply).toMap(); - if (response.contains("reset") && - response["reset"].toBool()) { + if (response.contains("reset") && response["reset"].toBool()) { qLog(Debug) << "Resetting Dropbox DB"; library_backend_->DeleteAll(); } @@ -116,7 +111,7 @@ void DropboxService::RequestFileListFinished(QNetworkReply* reply) { QVariantList contents = response["entries"].toList(); qLog(Debug) << "Delta found:" << contents.size(); - foreach (const QVariant& c, contents) { + foreach(const QVariant & c, contents) { QVariantList item = c.toList(); QString path = item[0].toString(); @@ -139,16 +134,17 @@ void DropboxService::RequestFileListFinished(QNetworkReply* reply) { continue; } - // Workaround: Since Dropbox doesn't recognize Opus files and thus treats them + // Workaround: Since Dropbox doesn't recognize Opus files and thus treats + // them // as application/octet-stream, we overwrite the mime type here - if (metadata["mime_type"].toString() == "application/octet-stream" && + if (metadata["mime_type"].toString() == "application/octet-stream" && url.toString().endsWith(".opus")) metadata["mime_type"] = GuessMimeTypeForFile(url.toString()); if (ShouldIndexFile(url, metadata["mime_type"].toString())) { QNetworkReply* reply = FetchContentUrl(url); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(FetchContentUrlFinished(QNetworkReply*, QVariantMap)), + NewClosure(reply, SIGNAL(finished()), this, + SLOT(FetchContentUrlFinished(QNetworkReply*, QVariantMap)), reply, metadata); } } @@ -172,8 +168,8 @@ void DropboxService::LongPollDelta() { QNetworkRequest request(request_url); request.setRawHeader("Authorization", GenerateAuthorisationHeader()); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(LongPollFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(LongPollFinished(QNetworkReply*)), reply); } void DropboxService::LongPollFinished(QNetworkReply* reply) { @@ -201,8 +197,8 @@ QNetworkReply* DropboxService::FetchContentUrl(const QUrl& url) { return network_->post(request, QByteArray()); } -void DropboxService::FetchContentUrlFinished( - QNetworkReply* reply, const QVariantMap& data) { +void DropboxService::FetchContentUrlFinished(QNetworkReply* reply, + const QVariantMap& data) { reply->deleteLater(); QJson::Parser parser; QVariantMap response = parser.parse(reply).toMap(); @@ -220,11 +216,9 @@ void DropboxService::FetchContentUrlFinished( song.set_filesize(data["bytes"].toInt()); song.set_ctime(0); - MaybeAddFileToDatabase( - song, - data["mime_type"].toString(), - QUrl::fromEncoded(response["url"].toByteArray()), - QString::null); + MaybeAddFileToDatabase(song, data["mime_type"].toString(), + QUrl::fromEncoded(response["url"].toByteArray()), + QString::null); } QUrl DropboxService::GetStreamingUrlFromSongId(const QUrl& url) { diff --git a/src/internet/dropboxservice.h b/src/internet/dropboxservice.h index 2e026ab10..9434fa5da 100644 --- a/src/internet/dropboxservice.h +++ b/src/internet/dropboxservice.h @@ -21,7 +21,7 @@ class DropboxService : public CloudFileService { QUrl GetStreamingUrlFromSongId(const QUrl& url); - signals: +signals: void Connected(); public slots: diff --git a/src/internet/dropboxsettingspage.cpp b/src/internet/dropboxsettingspage.cpp index a6ad9dee6..22418d9d5 100644 --- a/src/internet/dropboxsettingspage.cpp +++ b/src/internet/dropboxsettingspage.cpp @@ -25,10 +25,9 @@ #include "ui/settingsdialog.h" DropboxSettingsPage::DropboxSettingsPage(SettingsDialog* parent) - : SettingsPage(parent), - ui_(new Ui::DropboxSettingsPage), - service_(dialog()->app()->internet_model()->Service()) -{ + : SettingsPage(parent), + ui_(new Ui::DropboxSettingsPage), + service_(dialog()->app()->internet_model()->Service()) { ui_->setupUi(this); ui_->login_state->AddCredentialGroup(ui_->login_container); @@ -38,9 +37,7 @@ DropboxSettingsPage::DropboxSettingsPage(SettingsDialog* parent) dialog()->installEventFilter(this); } -DropboxSettingsPage::~DropboxSettingsPage() { - delete ui_; -} +DropboxSettingsPage::~DropboxSettingsPage() { delete ui_; } void DropboxSettingsPage::Load() { QSettings s; @@ -60,11 +57,10 @@ void DropboxSettingsPage::Save() { void DropboxSettingsPage::LoginClicked() { DropboxAuthenticator* authenticator = new DropboxAuthenticator; - NewClosure(authenticator, SIGNAL(Finished()), - this, SLOT(Connected(DropboxAuthenticator*)), - authenticator); - NewClosure(authenticator, SIGNAL(Finished()), - service_, SLOT(AuthenticationFinished(DropboxAuthenticator*)), + NewClosure(authenticator, SIGNAL(Finished()), this, + SLOT(Connected(DropboxAuthenticator*)), authenticator); + NewClosure(authenticator, SIGNAL(Finished()), service_, + SLOT(AuthenticationFinished(DropboxAuthenticator*)), authenticator); authenticator->StartAuthorisation(); @@ -85,6 +81,6 @@ void DropboxSettingsPage::LogoutClicked() { } void DropboxSettingsPage::Connected(DropboxAuthenticator* authenticator) { - ui_->login_state->SetLoggedIn( - LoginStateWidget::LoggedIn, authenticator->name()); + ui_->login_state->SetLoggedIn(LoginStateWidget::LoggedIn, + authenticator->name()); } diff --git a/src/internet/dropboxsettingspage.h b/src/internet/dropboxsettingspage.h index ea646a4bd..a0712246b 100644 --- a/src/internet/dropboxsettingspage.h +++ b/src/internet/dropboxsettingspage.h @@ -30,7 +30,7 @@ class Ui_DropboxSettingsPage; class DropboxSettingsPage : public SettingsPage { Q_OBJECT -public: + public: DropboxSettingsPage(SettingsDialog* parent = 0); ~DropboxSettingsPage(); @@ -40,15 +40,15 @@ public: // QObject bool eventFilter(QObject* object, QEvent* event); -private slots: + private slots: void LoginClicked(); void LogoutClicked(); void Connected(DropboxAuthenticator* authenticator); -private: + private: Ui_DropboxSettingsPage* ui_; DropboxService* service_; }; -#endif // DROPBOXSETTINGSPAGE_H +#endif // DROPBOXSETTINGSPAGE_H diff --git a/src/internet/dropboxurlhandler.cpp b/src/internet/dropboxurlhandler.cpp index b5d381fdc..1a2068e2c 100644 --- a/src/internet/dropboxurlhandler.cpp +++ b/src/internet/dropboxurlhandler.cpp @@ -2,12 +2,8 @@ #include "internet/dropboxservice.h" -DropboxUrlHandler::DropboxUrlHandler( - DropboxService* service, - QObject* parent) - : UrlHandler(parent), - service_(service) { -} +DropboxUrlHandler::DropboxUrlHandler(DropboxService* service, QObject* parent) + : UrlHandler(parent), service_(service) {} UrlHandler::LoadResult DropboxUrlHandler::StartLoading(const QUrl& url) { return LoadResult(url, LoadResult::TrackAvailable, diff --git a/src/internet/fixlastfm.cpp b/src/internet/fixlastfm.cpp index 5bc36fad7..607f5c162 100644 --- a/src/internet/fixlastfm.cpp +++ b/src/internet/fixlastfm.cpp @@ -18,8 +18,5 @@ #include "fixlastfm.h" #ifdef QT_NO_DEBUG_OUTPUT - QDebug& operator<<(QDebug& d, const QUrl&) { - return d; - } +QDebug& operator<<(QDebug& d, const QUrl&) { return d; } #endif - diff --git a/src/internet/fixlastfm.h b/src/internet/fixlastfm.h index 139de00ec..f23e2702e 100644 --- a/src/internet/fixlastfm.h +++ b/src/internet/fixlastfm.h @@ -21,10 +21,10 @@ // Include this before to fix a compile error in release mode #ifdef QT_NO_DEBUG_OUTPUT -# include -# include - // Stub this out so lastfm/Track still compiles - QDebug& operator<<(QDebug&, const QUrl&); +#include +#include +// Stub this out so lastfm/Track still compiles +QDebug& operator<<(QDebug&, const QUrl&); #endif #endif diff --git a/src/internet/geolocator.cpp b/src/internet/geolocator.cpp index a2a2b4cc2..2c773b995 100644 --- a/src/internet/geolocator.cpp +++ b/src/internet/geolocator.cpp @@ -32,18 +32,14 @@ const char* Geolocator::kUrl = "http://data.clementine-player.org/geolocate"; using std::numeric_limits; Geolocator::LatLng::LatLng() - : lat_e6_(numeric_limits::min()), - lng_e6_(numeric_limits::min()) { -} + : lat_e6_(numeric_limits::min()), + lng_e6_(numeric_limits::min()) {} Geolocator::LatLng::LatLng(int lat_e6, int lng_e6) - : lat_e6_(lat_e6), - lng_e6_(lng_e6) { -} + : lat_e6_(lat_e6), lng_e6_(lng_e6) {} Geolocator::LatLng::LatLng(const QString& latlng) - : lat_e6_(numeric_limits::min()), - lng_e6_(numeric_limits::min()) { + : lat_e6_(numeric_limits::min()), lng_e6_(numeric_limits::min()) { QStringList split = latlng.split(","); if (split.length() != 2) { return; @@ -83,14 +79,13 @@ bool Geolocator::LatLng::IsValid() const { lng_e6_ != numeric_limits::min(); } -Geolocator::Geolocator(QObject* parent) - : QObject(parent) { -} +Geolocator::Geolocator(QObject* parent) : QObject(parent) {} void Geolocator::Geolocate() { QNetworkRequest req = QNetworkRequest(QUrl(kUrl)); QNetworkReply* reply = network_.get(req); - NewClosure(reply, SIGNAL(finished()), this, SLOT(RequestFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(RequestFinished(QNetworkReply*)), reply); } void Geolocator::RequestFinished(QNetworkReply* reply) { diff --git a/src/internet/geolocator.h b/src/internet/geolocator.h index fabe4ccac..af8e4bf8e 100644 --- a/src/internet/geolocator.h +++ b/src/internet/geolocator.h @@ -47,7 +47,7 @@ class Geolocator : public QObject { int lng_e6_; }; - signals: +signals: void Finished(Geolocator::LatLng latlng); private slots: diff --git a/src/internet/googledriveclient.cpp b/src/internet/googledriveclient.cpp index fed872450..a0b2b543a 100644 --- a/src/internet/googledriveclient.cpp +++ b/src/internet/googledriveclient.cpp @@ -42,16 +42,14 @@ static const char* kOAuthTokenEndpoint = static const char* kOAuthScope = "https://www.googleapis.com/auth/drive.readonly " "https://www.googleapis.com/auth/userinfo.email"; -static const char* kClientId = - "679260893280.apps.googleusercontent.com"; -static const char* kClientSecret = - "l3cWb8efUZsrBI4wmY3uKl6i"; +static const char* kClientId = "679260893280.apps.googleusercontent.com"; +static const char* kClientSecret = "l3cWb8efUZsrBI4wmY3uKl6i"; } QStringList File::parent_ids() const { QStringList ret; - foreach (const QVariant& var, data_["parents"].toList()) { + foreach(const QVariant & var, data_["parents"].toList()) { QVariantMap map(var.toMap()); if (map["isRoot"].toBool()) { @@ -64,28 +62,16 @@ QStringList File::parent_ids() const { return ret; } -ConnectResponse::ConnectResponse(QObject* parent) - : QObject(parent) -{ -} +ConnectResponse::ConnectResponse(QObject* parent) : QObject(parent) {} GetFileResponse::GetFileResponse(const QString& file_id, QObject* parent) - : QObject(parent), - file_id_(file_id) -{ -} + : QObject(parent), file_id_(file_id) {} ListChangesResponse::ListChangesResponse(const QString& cursor, QObject* parent) - : QObject(parent), - cursor_(cursor) -{ -} + : QObject(parent), cursor_(cursor) {} Client::Client(QObject* parent) - : QObject(parent), - network_(new NetworkAccessManager(this)) -{ -} + : QObject(parent), network_(new NetworkAccessManager(this)) {} ConnectResponse* Client::Connect(const QString& refresh_token) { ConnectResponse* ret = new ConnectResponse(this); @@ -93,17 +79,14 @@ ConnectResponse* Client::Connect(const QString& refresh_token) { kClientId, kClientSecret, OAuthenticator::RedirectStyle::LOCALHOST, this); if (refresh_token.isEmpty()) { - oauth->StartAuthorisation( - kOAuthEndpoint, - kOAuthTokenEndpoint, - kOAuthScope); + oauth->StartAuthorisation(kOAuthEndpoint, kOAuthTokenEndpoint, kOAuthScope); } else { oauth->RefreshAuthorisation(kOAuthTokenEndpoint, refresh_token); } - NewClosure(oauth, SIGNAL(Finished()), - this, SLOT(ConnectFinished(ConnectResponse*,OAuthenticator*)), - ret, oauth); + NewClosure(oauth, SIGNAL(Finished()), this, + SLOT(ConnectFinished(ConnectResponse*, OAuthenticator*)), ret, + oauth); return ret; } @@ -118,13 +101,13 @@ void Client::ConnectFinished(ConnectResponse* response, OAuthenticator* oauth) { QNetworkRequest request(url); AddAuthorizationHeader(&request); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(FetchUserInfoFinished(ConnectResponse*, QNetworkReply*)), - response, reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(FetchUserInfoFinished(ConnectResponse*, QNetworkReply*)), + response, reply); } -void Client::FetchUserInfoFinished( - ConnectResponse* response, QNetworkReply* reply) { +void Client::FetchUserInfoFinished(ConnectResponse* response, + QNetworkReply* reply) { reply->deleteLater(); if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) != 200) { qLog(Warning) << "Failed to get user info" << reply->readAll(); @@ -146,8 +129,8 @@ void Client::FetchUserInfoFinished( } void Client::AddAuthorizationHeader(QNetworkRequest* request) const { - request->setRawHeader( - "Authorization", QString("Bearer %1").arg(access_token_).toUtf8()); + request->setRawHeader("Authorization", + QString("Bearer %1").arg(access_token_).toUtf8()); } GetFileResponse* Client::GetFile(const QString& file_id) { @@ -158,13 +141,13 @@ GetFileResponse* Client::GetFile(const QString& file_id) { QNetworkRequest request = QNetworkRequest(url); AddAuthorizationHeader(&request); // Never cache these requests as we will get out of date download URLs. - request.setAttribute( - QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork); + request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, + QNetworkRequest::AlwaysNetwork); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(GetFileFinished(GetFileResponse*,QNetworkReply*)), - ret, reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(GetFileFinished(GetFileResponse*, QNetworkReply*)), ret, + reply); return ret; } @@ -191,7 +174,8 @@ ListChangesResponse* Client::ListChanges(const QString& cursor) { return ret; } -void Client::MakeListChangesRequest(ListChangesResponse* response, const QString& page_token) { +void Client::MakeListChangesRequest(ListChangesResponse* response, + const QString& page_token) { QUrl url(kGoogleDriveChanges); if (!response->cursor().isEmpty()) { url.addQueryItem("startChangeId", response->cursor()); @@ -206,12 +190,13 @@ void Client::MakeListChangesRequest(ListChangesResponse* response, const QString AddAuthorizationHeader(&request); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(ListChangesFinished(ListChangesResponse*,QNetworkReply*)), + NewClosure(reply, SIGNAL(finished()), this, + SLOT(ListChangesFinished(ListChangesResponse*, QNetworkReply*)), response, reply); } -void Client::ListChangesFinished(ListChangesResponse* response, QNetworkReply* reply) { +void Client::ListChangesFinished(ListChangesResponse* response, + QNetworkReply* reply) { reply->deleteLater(); QJson::Parser parser; @@ -231,7 +216,7 @@ void Client::ListChangesFinished(ListChangesResponse* response, QNetworkReply* r // Emit the FilesFound signal for the files in the response. FileList files; QList files_deleted; - foreach (const QVariant& v, result["items"].toList()) { + foreach(const QVariant & v, result["items"].toList()) { QVariantMap change = v.toMap(); if (!change["deleted"].toBool()) { files << File(change["file"].toMap()); @@ -256,7 +241,7 @@ void Client::ListChangesFinished(ListChangesResponse* response, QNetworkReply* r bool Client::is_authenticated() const { return !access_token_.isEmpty() && - QDateTime::currentDateTime().secsTo(expiry_time_) > 0; + QDateTime::currentDateTime().secsTo(expiry_time_) > 0; } void Client::ForgetCredentials() { diff --git a/src/internet/googledriveclient.h b/src/internet/googledriveclient.h index cecb2a1e9..07212698a 100644 --- a/src/internet/googledriveclient.h +++ b/src/internet/googledriveclient.h @@ -30,14 +30,13 @@ class QNetworkAccessManager; class QNetworkReply; class QNetworkRequest; - namespace google_drive { class Client; // Holds the metadata for a file on Google Drive. class File { -public: + public: File(const QVariantMap& data = QVariantMap()) : data_(data) {} static const char* kFolderMimeType; @@ -72,57 +71,55 @@ public: bool is_restricted() const { return has_label("restricted"); } bool is_viewed() const { return has_label("viewed"); } -private: + private: QVariantMap data_; }; typedef QList FileList; - class ConnectResponse : public QObject { Q_OBJECT friend class Client; -public: + public: const QString& refresh_token() const { return refresh_token_; } const QString& user_email() const { return user_email_; } signals: void Finished(); -private: + private: ConnectResponse(QObject* parent); QString refresh_token_; QString user_email_; }; - class GetFileResponse : public QObject { Q_OBJECT friend class Client; -public: + public: const QString& file_id() const { return file_id_; } const File& file() const { return file_; } signals: void Finished(); -private: + private: GetFileResponse(const QString& file_id, QObject* parent); QString file_id_; File file_; }; - class ListChangesResponse : public QObject { Q_OBJECT friend class Client; + public: const QString& cursor() const { return cursor_; } const QString& next_cursor() const { return next_cursor_; } - signals: +signals: void FilesFound(const QList& files); void FilesDeleted(const QList& files); void Finished(); @@ -133,11 +130,10 @@ class ListChangesResponse : public QObject { QString next_cursor_; }; - class Client : public QObject { Q_OBJECT -public: + public: Client(QObject* parent = 0); bool is_authenticated() const; @@ -149,28 +145,27 @@ public: GetFileResponse* GetFile(const QString& file_id); ListChangesResponse* ListChanges(const QString& cursor); - signals: void Authenticated(); -private slots: + private slots: void ConnectFinished(ConnectResponse* response, OAuthenticator* oauth); void FetchUserInfoFinished(ConnectResponse* response, QNetworkReply* reply); void GetFileFinished(GetFileResponse* response, QNetworkReply* reply); void ListChangesFinished(ListChangesResponse* response, QNetworkReply* reply); -private: + private: void AddAuthorizationHeader(QNetworkRequest* request) const; void MakeListChangesRequest(ListChangesResponse* response, const QString& page_token = QString()); -private: + private: QNetworkAccessManager* network_; QString access_token_; QDateTime expiry_time_; }; -} // namespace +} // namespace -#endif // GOOGLEDRIVECLIENT_H +#endif // GOOGLEDRIVECLIENT_H diff --git a/src/internet/googledriveservice.cpp b/src/internet/googledriveservice.cpp index 15fc3cc09..b8312eaaa 100644 --- a/src/internet/googledriveservice.cpp +++ b/src/internet/googledriveservice.cpp @@ -30,16 +30,12 @@ namespace { static const char* kDriveEditFileUrl = "https://docs.google.com/file/d/%1/edit"; static const char* kServiceId = "google_drive"; - } - GoogleDriveService::GoogleDriveService(Application* app, InternetModel* parent) - : CloudFileService( - app, parent, - kServiceName, kServiceId, - QIcon(":/providers/googledrive.png"), - SettingsDialog::Page_GoogleDrive), + : CloudFileService(app, parent, kServiceName, kServiceId, + QIcon(":/providers/googledrive.png"), + SettingsDialog::Page_GoogleDrive), client_(new google_drive::Client(this)) { app->player()->RegisterUrlHandler(new GoogleDriveUrlHandler(this, this)); } @@ -57,9 +53,8 @@ QString GoogleDriveService::refresh_token() const { void GoogleDriveService::Connect() { google_drive::ConnectResponse* response = client_->Connect(refresh_token()); - NewClosure(response, SIGNAL(Finished()), - this, SLOT(ConnectFinished(google_drive::ConnectResponse*)), - response); + NewClosure(response, SIGNAL(Finished()), this, + SLOT(ConnectFinished(google_drive::ConnectResponse*)), response); } void GoogleDriveService::ForgetCredentials() { @@ -73,24 +68,27 @@ void GoogleDriveService::ForgetCredentials() { } void GoogleDriveService::ListChanges(const QString& cursor) { - google_drive::ListChangesResponse* changes_response = client_->ListChanges(cursor); + google_drive::ListChangesResponse* changes_response = + client_->ListChanges(cursor); connect(changes_response, SIGNAL(FilesFound(QList)), SLOT(FilesFound(QList))); connect(changes_response, SIGNAL(FilesDeleted(QList)), SLOT(FilesDeleted(QList))); - NewClosure(changes_response, SIGNAL(Finished()), - this, SLOT(ListChangesFinished(google_drive::ListChangesResponse*)), + NewClosure(changes_response, SIGNAL(Finished()), this, + SLOT(ListChangesFinished(google_drive::ListChangesResponse*)), changes_response); } -void GoogleDriveService::ListChangesFinished(google_drive::ListChangesResponse* changes_response) { +void GoogleDriveService::ListChangesFinished( + google_drive::ListChangesResponse* changes_response) { changes_response->deleteLater(); QSettings s; s.beginGroup(kSettingsGroup); s.setValue("cursor", changes_response->next_cursor()); } -void GoogleDriveService::ConnectFinished(google_drive::ConnectResponse* response) { +void GoogleDriveService::ConnectFinished( + google_drive::ConnectResponse* response) { response->deleteLater(); // Save the refresh token @@ -121,7 +119,7 @@ void GoogleDriveService::EnsureConnected() { } void GoogleDriveService::FilesFound(const QList& files) { - foreach (const google_drive::File& file, files) { + foreach(const google_drive::File & file, files) { if (!IsSupportedMimeType(file.mime_type())) { continue; } @@ -145,16 +143,13 @@ void GoogleDriveService::FilesFound(const QList& files) { song.set_title(file.title()); } - MaybeAddFileToDatabase( - song, - file.mime_type(), - file.download_url(), - QString("Bearer %1").arg(client_->access_token())); + MaybeAddFileToDatabase(song, file.mime_type(), file.download_url(), + QString("Bearer %1").arg(client_->access_token())); } } void GoogleDriveService::FilesDeleted(const QList& files) { - foreach (const QUrl& url, files) { + foreach(const QUrl & url, files) { Song song = library_backend_->GetSongByUrl(url); qLog(Debug) << "Deleting:" << url << song.title(); if (song.is_valid()) { @@ -181,25 +176,20 @@ void GoogleDriveService::ShowContextMenu(const QPoint& global_pos) { context_menu_.reset(new QMenu); context_menu_->addActions(GetPlaylistActions()); open_in_drive_action_ = context_menu_->addAction( - QIcon(":/providers/googledrive.png"), tr("Open in Google Drive"), - this, SLOT(OpenWithDrive())); + QIcon(":/providers/googledrive.png"), tr("Open in Google Drive"), this, + SLOT(OpenWithDrive())); context_menu_->addSeparator(); - context_menu_->addAction( - IconLoader::Load("download"), - tr("Cover Manager"), - this, - SLOT(ShowCoverManager())); - context_menu_->addAction(IconLoader::Load("configure"), - tr("Configure..."), + context_menu_->addAction(IconLoader::Load("download"), tr("Cover Manager"), + this, SLOT(ShowCoverManager())); + context_menu_->addAction(IconLoader::Load("configure"), tr("Configure..."), this, SLOT(ShowSettingsDialog())); } // Only show some actions if there are real songs selected bool songs_selected = false; - foreach (const QModelIndex& index, model()->selected_indexes()) { + foreach(const QModelIndex & index, model()->selected_indexes()) { const int type = index.data(LibraryModel::Role_Type).toInt(); - if (type == LibraryItem::Type_Song || - type == LibraryItem::Type_Container) { + if (type == LibraryItem::Type_Song || type == LibraryItem::Type_Container) { songs_selected = true; break; } @@ -213,15 +203,15 @@ void GoogleDriveService::ShowContextMenu(const QPoint& global_pos) { void GoogleDriveService::OpenWithDrive() { // Map indexes to the actual library model. QModelIndexList library_indexes; - foreach (const QModelIndex& index, model()->selected_indexes()) { + foreach(const QModelIndex & index, model()->selected_indexes()) { if (index.model() == library_sort_model_) { library_indexes << library_sort_model_->mapToSource(index); } } // Ask the library for the songs for these indexes. - foreach (const Song& song, library_model_->GetChildSongs(library_indexes)) { + foreach(const Song & song, library_model_->GetChildSongs(library_indexes)) { QDesktopServices::openUrl( - QUrl(QString(kDriveEditFileUrl).arg(song.url().path()))); + QUrl(QString(kDriveEditFileUrl).arg(song.url().path()))); } } diff --git a/src/internet/googledriveservice.h b/src/internet/googledriveservice.h index a5760902b..0d86b1e20 100644 --- a/src/internet/googledriveservice.h +++ b/src/internet/googledriveservice.h @@ -4,11 +4,11 @@ #include "cloudfileservice.h" namespace google_drive { - class Client; - class ConnectResponse; - class File; - class ListFilesResponse; - class ListChangesResponse; +class Client; +class ConnectResponse; +class File; +class ListFilesResponse; +class ListChangesResponse; } class GoogleDriveService : public CloudFileService { @@ -31,7 +31,7 @@ class GoogleDriveService : public CloudFileService { void Connect(); void ForgetCredentials(); - signals: +signals: void Connected(); private slots: diff --git a/src/internet/googledrivesettingspage.cpp b/src/internet/googledrivesettingspage.cpp index c19f6f344..5a4ff2622 100644 --- a/src/internet/googledrivesettingspage.cpp +++ b/src/internet/googledrivesettingspage.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -26,10 +26,10 @@ #include GoogleDriveSettingsPage::GoogleDriveSettingsPage(SettingsDialog* parent) - : SettingsPage(parent), - ui_(new Ui::GoogleDriveSettingsPage), - service_(dialog()->app()->internet_model()->Service()) -{ + : SettingsPage(parent), + ui_(new Ui::GoogleDriveSettingsPage), + service_( + dialog()->app()->internet_model()->Service()) { ui_->setupUi(this); ui_->login_state->AddCredentialGroup(ui_->login_container); @@ -40,9 +40,7 @@ GoogleDriveSettingsPage::GoogleDriveSettingsPage(SettingsDialog* parent) dialog()->installEventFilter(this); } -GoogleDriveSettingsPage::~GoogleDriveSettingsPage() { - delete ui_; -} +GoogleDriveSettingsPage::~GoogleDriveSettingsPage() { delete ui_; } void GoogleDriveSettingsPage::Load() { QSettings s; diff --git a/src/internet/googledrivesettingspage.h b/src/internet/googledrivesettingspage.h index cbf39a417..7cd8088e9 100644 --- a/src/internet/googledrivesettingspage.h +++ b/src/internet/googledrivesettingspage.h @@ -29,7 +29,7 @@ class Ui_GoogleDriveSettingsPage; class GoogleDriveSettingsPage : public SettingsPage { Q_OBJECT -public: + public: GoogleDriveSettingsPage(SettingsDialog* parent = 0); ~GoogleDriveSettingsPage(); @@ -39,15 +39,15 @@ public: // QObject bool eventFilter(QObject* object, QEvent* event); -private slots: + private slots: void LoginClicked(); void LogoutClicked(); void Connected(); -private: + private: Ui_GoogleDriveSettingsPage* ui_; GoogleDriveService* service_; }; -#endif // GOOGLEDRIVESETTINGSPAGE_H +#endif // GOOGLEDRIVESETTINGSPAGE_H diff --git a/src/internet/googledriveurlhandler.cpp b/src/internet/googledriveurlhandler.cpp index 3c74e72dc..2a35297cb 100644 --- a/src/internet/googledriveurlhandler.cpp +++ b/src/internet/googledriveurlhandler.cpp @@ -2,12 +2,9 @@ #include "googledriveservice.h" -GoogleDriveUrlHandler::GoogleDriveUrlHandler( - GoogleDriveService* service, - QObject* parent) - : UrlHandler(parent), - service_(service) { -} +GoogleDriveUrlHandler::GoogleDriveUrlHandler(GoogleDriveService* service, + QObject* parent) + : UrlHandler(parent), service_(service) {} UrlHandler::LoadResult GoogleDriveUrlHandler::StartLoading(const QUrl& url) { QString file_id = url.path(); diff --git a/src/internet/groovesharkradio.cpp b/src/internet/groovesharkradio.cpp index 80cec51ba..64e127908 100644 --- a/src/internet/groovesharkradio.cpp +++ b/src/internet/groovesharkradio.cpp @@ -22,25 +22,14 @@ #include "internet/internetplaylistitem.h" GroovesharkRadio::GroovesharkRadio(GroovesharkService* service) - : service_(service), - tag_id_(0), - use_tag_(false), - first_time_(true) { -} + : service_(service), tag_id_(0), use_tag_(false), first_time_(true) {} GroovesharkRadio::GroovesharkRadio(GroovesharkService* service, int tag_id) - : service_(service), - tag_id_(tag_id), - use_tag_(true), - first_time_(true) { -} + : service_(service), tag_id_(tag_id), use_tag_(true), first_time_(true) {} -void GroovesharkRadio::Load(const QByteArray& data) { -} +void GroovesharkRadio::Load(const QByteArray& data) {} -QByteArray GroovesharkRadio::Save() const { - return QByteArray(); -} +QByteArray GroovesharkRadio::Save() const { return QByteArray(); } PlaylistItemList GroovesharkRadio::Generate() { PlaylistItemList items; @@ -55,7 +44,8 @@ PlaylistItemList GroovesharkRadio::Generate() { if (!song.is_valid()) { return items; } - PlaylistItemPtr playlist_item = PlaylistItemPtr(new InternetPlaylistItem(service_, song)); + PlaylistItemPtr playlist_item = + PlaylistItemPtr(new InternetPlaylistItem(service_, song)); items << playlist_item; first_time_ = false; } @@ -63,7 +53,8 @@ PlaylistItemList GroovesharkRadio::Generate() { if (!song.is_valid()) { return items; } - PlaylistItemPtr playlist_item = PlaylistItemPtr(new InternetPlaylistItem(service_, song)); + PlaylistItemPtr playlist_item = + PlaylistItemPtr(new InternetPlaylistItem(service_, song)); items << playlist_item; return items; } diff --git a/src/internet/groovesharkradio.h b/src/internet/groovesharkradio.h index f1ccaf0d2..56df3d619 100644 --- a/src/internet/groovesharkradio.h +++ b/src/internet/groovesharkradio.h @@ -24,7 +24,7 @@ class GroovesharkService; class GroovesharkRadio : public smart_playlists::Generator { -public: + public: // Start Grooveshark radio for a particular type of music GroovesharkRadio(GroovesharkService* service, int tag_id); // Start Grooveshark radio based on last artists and songs you listen to @@ -37,7 +37,7 @@ public: PlaylistItemList GenerateMore(int count) { return Generate(); } bool is_dynamic() const { return true; } -private: + private: GroovesharkService* service_; int tag_id_; // Boolean to specify if we should use tag. If not, we will used autoplay @@ -47,5 +47,5 @@ private: bool first_time_; QVariantMap autoplay_state_; }; - -#endif // GROOVESHARKRADIO_H + +#endif // GROOVESHARKRADIO_H diff --git a/src/internet/groovesharkservice.cpp b/src/internet/groovesharkservice.cpp index d700d7e88..ff02b3cf7 100644 --- a/src/internet/groovesharkservice.cpp +++ b/src/internet/groovesharkservice.cpp @@ -67,12 +67,14 @@ using smart_playlists::GeneratorPtr; // accessible to third parties. Therefore this application key is obfuscated to // prevent third parties from viewing it. const char* GroovesharkService::kApiKey = "clementineplayer"; -const char* GroovesharkService::kApiSecret = "OzLDTB5XqmhkkhxMUK0/Mp5PQgD5O27DTEJa/jtkwEw="; +const char* GroovesharkService::kApiSecret = + "OzLDTB5XqmhkkhxMUK0/Mp5PQgD5O27DTEJa/jtkwEw="; const char* GroovesharkService::kServiceName = "Grooveshark"; const char* GroovesharkService::kSettingsGroup = "Grooveshark"; const char* GroovesharkService::kUrl = "http://api.grooveshark.com/ws/3.0/"; -const char* GroovesharkService::kUrlCover = "http://beta.grooveshark.com/static/amazonart/l"; +const char* GroovesharkService::kUrlCover = + "http://beta.grooveshark.com/static/amazonart/l"; const char* GroovesharkService::kHomepage = "http://grooveshark.com/"; const int GroovesharkService::kSongSearchLimit = 100; @@ -83,38 +85,38 @@ const int GroovesharkService::kSearchDelayMsec = 400; typedef QPair Param; -GroovesharkService::GroovesharkService(Application* app, InternetModel *parent) - : InternetService(kServiceName, app, parent, parent), - url_handler_(new GroovesharkUrlHandler(this, this)), - next_pending_search_id_(0), - root_(nullptr), - search_(nullptr), - popular_month_(nullptr), - popular_today_(nullptr), - stations_(nullptr), - grooveshark_radio_(nullptr), - favorites_(nullptr), - library_(nullptr), - playlists_parent_(nullptr), - subscribed_playlists_parent_(nullptr), - network_(new NetworkAccessManager(this)), - context_menu_(nullptr), - create_playlist_(nullptr), - delete_playlist_(nullptr), - rename_playlist_(nullptr), - remove_from_playlist_(nullptr), - remove_from_favorites_(nullptr), - remove_from_library_(nullptr), - get_url_to_share_song_(nullptr), - get_url_to_share_playlist_(nullptr), - search_box_(new SearchBoxWidget(this)), - search_delay_(new QTimer(this)), - last_search_reply_(nullptr), - api_key_(QByteArray::fromBase64(kApiSecret)), - login_state_(LoginState_OtherError), - task_popular_id_(0), - task_playlists_id_(0), - task_search_id_(0) { +GroovesharkService::GroovesharkService(Application* app, InternetModel* parent) + : InternetService(kServiceName, app, parent, parent), + url_handler_(new GroovesharkUrlHandler(this, this)), + next_pending_search_id_(0), + root_(nullptr), + search_(nullptr), + popular_month_(nullptr), + popular_today_(nullptr), + stations_(nullptr), + grooveshark_radio_(nullptr), + favorites_(nullptr), + library_(nullptr), + playlists_parent_(nullptr), + subscribed_playlists_parent_(nullptr), + network_(new NetworkAccessManager(this)), + context_menu_(nullptr), + create_playlist_(nullptr), + delete_playlist_(nullptr), + rename_playlist_(nullptr), + remove_from_playlist_(nullptr), + remove_from_favorites_(nullptr), + remove_from_library_(nullptr), + get_url_to_share_song_(nullptr), + get_url_to_share_playlist_(nullptr), + search_box_(new SearchBoxWidget(this)), + search_delay_(new QTimer(this)), + last_search_reply_(nullptr), + api_key_(QByteArray::fromBase64(kApiSecret)), + login_state_(LoginState_OtherError), + task_popular_id_(0), + task_playlists_id_(0), + task_search_id_(0) { app_->player()->RegisterUrlHandler(url_handler_); @@ -128,27 +130,28 @@ GroovesharkService::GroovesharkService(Application* app, InternetModel *parent) session_id_ = s.value("sessionid").toString(); username_ = s.value("username").toString(); - GroovesharkSearchProvider* search_provider = new GroovesharkSearchProvider(app_, this); + GroovesharkSearchProvider* search_provider = + new GroovesharkSearchProvider(app_, this); search_provider->Init(this); app_->global_search()->AddProvider(search_provider); - // Init secret: this code is ugly, but that's good as nobody is supposed to wonder what it does - QByteArray ba = QByteArray::fromBase64(QCoreApplication::applicationName().toLatin1()); + // Init secret: this code is ugly, but that's good as nobody is supposed to + // wonder what it does + QByteArray ba = + QByteArray::fromBase64(QCoreApplication::applicationName().toLatin1()); int n = api_key_.length(), n2 = ba.length(); - for (int i=0; isetData(true, InternetModel::Role_CanLazyLoad); root_->setData(InternetModel::PlayBehaviour_DoubleClickAction, - InternetModel::Role_PlayBehaviour); + InternetModel::Role_PlayBehaviour); return root_; } @@ -168,8 +171,7 @@ void GroovesharkService::ShowConfig() { } QWidget* GroovesharkService::HeaderWidget() const { - if (IsLoggedIn()) - return search_box_; + if (IsLoggedIn()) return search_box_; return nullptr; } @@ -194,8 +196,7 @@ void GroovesharkService::Search(const QString& text, bool now) { int GroovesharkService::SimpleSearch(const QString& query) { QList parameters; - parameters << Param("query", query) - << Param("country", "") + parameters << Param("query", query) << Param("country", "") << Param("limit", QString::number(kSongSimpleSearchLimit)) << Param("offset", ""); @@ -216,17 +217,15 @@ void GroovesharkService::SimpleSearchFinished(QNetworkReply* reply, int id) { int GroovesharkService::SearchAlbums(const QString& query) { QList parameters; - parameters << Param("query", query) - << Param("country", "") + parameters << Param("query", query) << Param("country", "") << Param("limit", QString::number(kAlbumSearchLimit)); QNetworkReply* reply = CreateRequest("getAlbumSearchResults", parameters); const int id = next_pending_search_id_++; - NewClosure(reply, SIGNAL(finished()), - this, SLOT(SearchAlbumsFinished(QNetworkReply*,int)), - reply, id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(SearchAlbumsFinished(QNetworkReply*, int)), reply, id); return id; } @@ -238,7 +237,7 @@ void GroovesharkService::SearchAlbumsFinished(QNetworkReply* reply, int id) { QVariantList albums = result["albums"].toList(); QList ret; - foreach (const QVariant& v, albums) { + foreach(const QVariant & v, albums) { quint64 album_id = v.toMap()["AlbumID"].toULongLong(); GetAlbumSongs(album_id); ret << album_id; @@ -249,15 +248,15 @@ void GroovesharkService::SearchAlbumsFinished(QNetworkReply* reply, int id) { void GroovesharkService::GetAlbumSongs(quint64 album_id) { QList parameters; - parameters << Param("albumID", album_id) - << Param("country", ""); + parameters << Param("albumID", album_id) << Param("country", ""); QNetworkReply* reply = CreateRequest("getAlbumSongs", parameters); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(GetAlbumSongsFinished(QNetworkReply*,quint64)), - reply, album_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(GetAlbumSongsFinished(QNetworkReply*, quint64)), reply, + album_id); } -void GroovesharkService::GetAlbumSongsFinished(QNetworkReply* reply, quint64 album_id) { +void GroovesharkService::GetAlbumSongsFinished(QNetworkReply* reply, + quint64 album_id) { reply->deleteLater(); QVariantMap result = ExtractResult(reply); SongList songs = ExtractSongs(result); @@ -267,16 +266,16 @@ void GroovesharkService::GetAlbumSongsFinished(QNetworkReply* reply, quint64 alb void GroovesharkService::DoSearch() { if (!task_search_id_) { - task_search_id_ = app_->task_manager()->StartTask(tr("Searching on Grooveshark")); + task_search_id_ = + app_->task_manager()->StartTask(tr("Searching on Grooveshark")); } ClearSearchResults(); QList parameters; - parameters << Param("query", pending_search_) - << Param("country", "") - << Param("limit", QString::number(kSongSearchLimit)) - << Param("offset", ""); + parameters << Param("query", pending_search_) << Param("country", "") + << Param("limit", QString::number(kSongSearchLimit)) + << Param("offset", ""); last_search_reply_ = CreateRequest("getSongSearchResults", parameters); NewClosure(last_search_reply_, SIGNAL(finished()), this, SLOT(SearchSongsFinished(QNetworkReply*)), last_search_reply_); @@ -285,8 +284,7 @@ void GroovesharkService::DoSearch() { void GroovesharkService::SearchSongsFinished(QNetworkReply* reply) { reply->deleteLater(); - if (reply != last_search_reply_) - return; + if (reply != last_search_reply_) return; QVariantMap result = ExtractResult(reply); SongList songs = ExtractSongs(result); @@ -294,7 +292,7 @@ void GroovesharkService::SearchSongsFinished(QNetworkReply* reply) { task_search_id_ = 0; // Fill results list - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { QStandardItem* child = CreateSongItem(song); search_->appendRow(child); } @@ -304,30 +302,30 @@ void GroovesharkService::SearchSongsFinished(QNetworkReply* reply) { } void GroovesharkService::InitCountry() { - if (!country_.isEmpty()) - return; + if (!country_.isEmpty()) return; // Get country info - QNetworkReply *reply_country = CreateRequest("getCountry", QList()); + QNetworkReply* reply_country = CreateRequest("getCountry", QList()); if (WaitForReply(reply_country)) { country_ = ExtractResult(reply_country); } reply_country->deleteLater(); } -QUrl GroovesharkService::GetStreamingUrlFromSongId(const QString& song_id, const QString& artist_id, - QString* server_id, QString* stream_key, qint64* length_nanosec) { +QUrl GroovesharkService::GetStreamingUrlFromSongId(const QString& song_id, + const QString& artist_id, + QString* server_id, + QString* stream_key, + qint64* length_nanosec) { QList parameters; InitCountry(); - parameters << Param("songID", song_id) - << Param("country", country_); + parameters << Param("songID", song_id) << Param("country", country_); QNetworkReply* reply = CreateRequest("getSubscriberStreamKey", parameters); // Wait for the reply bool reply_has_timeouted = !WaitForReply(reply); reply->deleteLater(); - if (reply_has_timeouted) - return QUrl(); + if (reply_has_timeouted) return QUrl(); QVariantMap result = ExtractResult(reply); server_id->clear(); @@ -339,23 +337,23 @@ QUrl GroovesharkService::GetStreamingUrlFromSongId(const QString& song_id, const last_songs_ids_.append(song_id.toInt()); last_artists_ids_.append(artist_id.toInt()); // If we have enough ids, remove the old ones - if (last_songs_ids_.size() > 100) - last_songs_ids_.removeFirst(); - if (last_artists_ids_.size() > 100) - last_artists_ids_.removeFirst(); + if (last_songs_ids_.size() > 100) last_songs_ids_.removeFirst(); + if (last_artists_ids_.size() > 100) last_artists_ids_.removeFirst(); return QUrl(result["url"].toString()); } -void GroovesharkService::Login(const QString& username, const QString& password) { +void GroovesharkService::Login(const QString& username, + const QString& password) { // To login, we first need to create a session. Next, we will authenticate // this session using the user's username and password (for now, we just keep // them in mind) username_ = username; - password_ = QCryptographicHash::hash(password.toLocal8Bit(), QCryptographicHash::Md5).toHex(); + password_ = QCryptographicHash::hash(password.toLocal8Bit(), + QCryptographicHash::Md5).toHex(); QList parameters; - QNetworkReply *reply = CreateRequest("startSession", parameters, true); + QNetworkReply* reply = CreateRequest("startSession", parameters, true); NewClosure(reply, SIGNAL(finished()), this, SLOT(SessionCreated(QNetworkReply*)), reply); @@ -364,7 +362,8 @@ void GroovesharkService::Login(const QString& username, const QString& password) void GroovesharkService::SessionCreated(QNetworkReply* reply) { reply->deleteLater(); - if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) { + if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != + 200) { emit StreamError("Failed to create Grooveshark session: " + reply->errorString()); emit LoginFinished(false); @@ -383,10 +382,9 @@ void GroovesharkService::SessionCreated(QNetworkReply* reply) { void GroovesharkService::AuthenticateSession() { QList parameters; - parameters << Param("login", username_) - << Param("password", password_); + parameters << Param("login", username_) << Param("password", password_); - QNetworkReply *reply = CreateRequest("authenticate", parameters, true); + QNetworkReply* reply = CreateRequest("authenticate", parameters, true); NewClosure(reply, SIGNAL(finished()), this, SLOT(Authenticated(QNetworkReply*)), reply); } @@ -400,12 +398,14 @@ void GroovesharkService::Authenticated(QNetworkReply* reply) { if (!result["success"].toBool() || result["UserID"].toInt() == 0) { error = tr("Invalid username and/or password"); login_state_ = LoginState_AuthFailed; - } else if(!result["IsAnywhere"].toBool() || !result["IsPremium"].toBool()) { - error = tr("User %1 doesn't have a Grooveshark Anywhere account").arg(username_); + } else if (!result["IsAnywhere"].toBool() || !result["IsPremium"].toBool()) { + error = tr("User %1 doesn't have a Grooveshark Anywhere account") + .arg(username_); login_state_ = LoginState_NoPremium; } if (!error.isEmpty()) { - QMessageBox::warning(nullptr, tr("Grooveshark login error"), error, QMessageBox::Close); + QMessageBox::warning(nullptr, tr("Grooveshark login error"), error, + QMessageBox::Close); ResetSessionId(); emit LoginFinished(false); return; @@ -417,8 +417,7 @@ void GroovesharkService::Authenticated(QNetworkReply* reply) { } void GroovesharkService::ClearSearchResults() { - if (search_) - search_->removeRows(0, search_->rowCount()); + if (search_) search_->removeRows(0, search_->rowCount()); } void GroovesharkService::Logout() { @@ -457,16 +456,16 @@ void GroovesharkService::ShowContextMenu(const QPoint& global_pos) { EnsureMenuCreated(); // Check if we should display actions - bool display_delete_playlist_action = false, - display_remove_from_playlist_action = false, - display_remove_from_favorites_action = false, - display_remove_from_library_action = false, - display_share_song_url = false, - display_share_playlist_url = false; + bool display_delete_playlist_action = false, + display_remove_from_playlist_action = false, + display_remove_from_favorites_action = false, + display_remove_from_library_action = false, + display_share_song_url = false, display_share_playlist_url = false; QModelIndex index(model()->current_index()); - if (index.data(InternetModel::Role_Type).toInt() == InternetModel::Type_UserPlaylist && + if (index.data(InternetModel::Role_Type).toInt() == + InternetModel::Type_UserPlaylist && index.data(Role_PlaylistType).toInt() == UserPlaylist) { display_delete_playlist_action = true; } @@ -491,19 +490,22 @@ void GroovesharkService::ShowContextMenu(const QPoint& global_pos) { // Check if we can display actions to get URL for sharing songs/playlists: // - share song - if (index.data(InternetModel::Role_Type).toInt() == InternetModel::Type_Track) { + if (index.data(InternetModel::Role_Type).toInt() == + InternetModel::Type_Track) { display_share_song_url = true; - current_song_id_ = ExtractSongId(index.data(InternetModel::Role_Url).toUrl()); + current_song_id_ = + ExtractSongId(index.data(InternetModel::Role_Url).toUrl()); } get_url_to_share_song_->setVisible(display_share_song_url); // - share playlist - if (index.data(InternetModel::Role_Type).toInt() == InternetModel::Type_UserPlaylist - && index.data(Role_UserPlaylistId).isValid()) { + if (index.data(InternetModel::Role_Type).toInt() == + InternetModel::Type_UserPlaylist && + index.data(Role_UserPlaylistId).isValid()) { display_share_playlist_url = true; current_playlist_id_ = index.data(Role_UserPlaylistId).toInt(); - } else if (parent_type == InternetModel::Type_UserPlaylist - && index.parent().data(Role_UserPlaylistId).isValid()) { + } else if (parent_type == InternetModel::Type_UserPlaylist && + index.parent().data(Role_UserPlaylistId).isValid()) { display_share_playlist_url = true; current_playlist_id_ = index.parent().data(Role_UserPlaylistId).toInt(); } @@ -513,7 +515,7 @@ void GroovesharkService::ShowContextMenu(const QPoint& global_pos) { } void GroovesharkService::EnsureMenuCreated() { - if(!context_menu_) { + if (!context_menu_) { context_menu_ = new QMenu; context_menu_->addActions(GetPlaylistActions()); create_playlist_ = context_menu_->addAction( @@ -527,30 +529,30 @@ void GroovesharkService::EnsureMenuCreated() { this, SLOT(RenameCurrentPlaylist())); context_menu_->addSeparator(); remove_from_playlist_ = context_menu_->addAction( - IconLoader::Load("list-remove"), tr("Remove from playlist"), - this, SLOT(RemoveCurrentFromPlaylist())); + IconLoader::Load("list-remove"), tr("Remove from playlist"), this, + SLOT(RemoveCurrentFromPlaylist())); remove_from_favorites_ = context_menu_->addAction( - IconLoader::Load("list-remove"), tr("Remove from favorites"), - this, SLOT(RemoveCurrentFromFavorites())); + IconLoader::Load("list-remove"), tr("Remove from favorites"), this, + SLOT(RemoveCurrentFromFavorites())); remove_from_library_ = context_menu_->addAction( - IconLoader::Load("list-remove"), tr("Remove from My Music"), - this, SLOT(RemoveCurrentFromLibrary())); - get_url_to_share_song_ = context_menu_->addAction( - tr("Get a URL to share this Grooveshark song"), - this, SLOT(GetCurrentSongUrlToShare())); + IconLoader::Load("list-remove"), tr("Remove from My Music"), this, + SLOT(RemoveCurrentFromLibrary())); + get_url_to_share_song_ = + context_menu_->addAction(tr("Get a URL to share this Grooveshark song"), + this, SLOT(GetCurrentSongUrlToShare())); get_url_to_share_playlist_ = context_menu_->addAction( - tr("Get a URL to share this Grooveshark playlist"), - this, SLOT(GetCurrentPlaylistUrlToShare())); + tr("Get a URL to share this Grooveshark playlist"), this, + SLOT(GetCurrentPlaylistUrlToShare())); context_menu_->addSeparator(); context_menu_->addAction(IconLoader::Load("download"), tr("Open %1 in browser").arg("grooveshark.com"), this, SLOT(Homepage())); - context_menu_->addAction(IconLoader::Load("view-refresh"), - tr("Refresh"), this, SLOT(RefreshItems())); + context_menu_->addAction(IconLoader::Load("view-refresh"), tr("Refresh"), + this, SLOT(RefreshItems())); context_menu_->addSeparator(); context_menu_->addAction(IconLoader::Load("configure"), - tr("Configure Grooveshark..."), - this, SLOT(ShowConfig())); + tr("Configure Grooveshark..."), this, + SLOT(ShowConfig())); } } @@ -565,48 +567,61 @@ void GroovesharkService::RefreshItems() { void GroovesharkService::EnsureItemsCreated() { if (IsLoggedIn() && !search_) { - search_ = new QStandardItem(IconLoader::Load("edit-find"), - tr("Search results")); - search_->setToolTip(tr("Start typing something on the search box above to " - "fill this search results list")); + search_ = + new QStandardItem(IconLoader::Load("edit-find"), tr("Search results")); + search_->setToolTip( + tr("Start typing something on the search box above to " + "fill this search results list")); search_->setData(InternetModel::PlayBehaviour_MultipleItems, InternetModel::Role_PlayBehaviour); root_->appendRow(search_); - QStandardItem* popular = new QStandardItem(QIcon(":/star-on.png"), - tr("Popular songs")); + QStandardItem* popular = + new QStandardItem(QIcon(":/star-on.png"), tr("Popular songs")); root_->appendRow(popular); - popular_month_ = new QStandardItem(QIcon(":/star-on.png"), tr("Popular songs of the Month")); - popular_month_->setData(InternetModel::Type_UserPlaylist, InternetModel::Role_Type); + popular_month_ = new QStandardItem(QIcon(":/star-on.png"), + tr("Popular songs of the Month")); + popular_month_->setData(InternetModel::Type_UserPlaylist, + InternetModel::Role_Type); popular_month_->setData(true, InternetModel::Role_CanLazyLoad); popular_month_->setData(InternetModel::PlayBehaviour_MultipleItems, - InternetModel::Role_PlayBehaviour); + InternetModel::Role_PlayBehaviour); popular->appendRow(popular_month_); - popular_today_ = new QStandardItem(QIcon(":/star-on.png"), tr("Popular songs today")); - popular_today_->setData(InternetModel::Type_UserPlaylist, InternetModel::Role_Type); + popular_today_ = + new QStandardItem(QIcon(":/star-on.png"), tr("Popular songs today")); + popular_today_->setData(InternetModel::Type_UserPlaylist, + InternetModel::Role_Type); popular_today_->setData(true, InternetModel::Role_CanLazyLoad); popular_today_->setData(InternetModel::PlayBehaviour_MultipleItems, - InternetModel::Role_PlayBehaviour); + InternetModel::Role_PlayBehaviour); popular->appendRow(popular_today_); - QStandardItem* radios_divider = new QStandardItem(QIcon(":last.fm/icon_radio.png"), - tr("Radios")); + QStandardItem* radios_divider = + new QStandardItem(QIcon(":last.fm/icon_radio.png"), tr("Radios")); root_->appendRow(radios_divider); - stations_ = new QStandardItem(QIcon(":last.fm/icon_radio.png"), tr("Stations")); - stations_->setData(InternetModel::Type_UserPlaylist, InternetModel::Role_Type); + stations_ = + new QStandardItem(QIcon(":last.fm/icon_radio.png"), tr("Stations")); + stations_->setData(InternetModel::Type_UserPlaylist, + InternetModel::Role_Type); stations_->setData(true, InternetModel::Role_CanLazyLoad); radios_divider->appendRow(stations_); - grooveshark_radio_ = new QStandardItem(QIcon(":last.fm/icon_radio.png"), tr("Grooveshark radio")); - grooveshark_radio_->setToolTip(tr("Listen to Grooveshark songs based on what you've listened to previously")); - grooveshark_radio_->setData(InternetModel::Type_SmartPlaylist, InternetModel::Role_Type); + grooveshark_radio_ = new QStandardItem(QIcon(":last.fm/icon_radio.png"), + tr("Grooveshark radio")); + grooveshark_radio_->setToolTip( + tr("Listen to Grooveshark songs based on what you've listened to " + "previously")); + grooveshark_radio_->setData(InternetModel::Type_SmartPlaylist, + InternetModel::Role_Type); radios_divider->appendRow(grooveshark_radio_); - library_ = new QStandardItem(IconLoader::Load("folder-sound"), tr("My Music")); - library_->setData(InternetModel::Type_UserPlaylist, InternetModel::Role_Type); + library_ = + new QStandardItem(IconLoader::Load("folder-sound"), tr("My Music")); + library_->setData(InternetModel::Type_UserPlaylist, + InternetModel::Role_Type); library_->setData(UserLibrary, Role_PlaylistType); library_->setData(true, InternetModel::Role_CanLazyLoad); library_->setData(true, InternetModel::Role_CanBeModified); @@ -614,8 +629,10 @@ void GroovesharkService::EnsureItemsCreated() { InternetModel::Role_PlayBehaviour); root_->appendRow(library_); - favorites_ = new QStandardItem(QIcon(":/last.fm/love.png"), tr("Favorites")); - favorites_->setData(InternetModel::Type_UserPlaylist, InternetModel::Role_Type); + favorites_ = + new QStandardItem(QIcon(":/last.fm/love.png"), tr("Favorites")); + favorites_->setData(InternetModel::Type_UserPlaylist, + InternetModel::Role_Type); favorites_->setData(UserFavorites, Role_PlaylistType); favorites_->setData(true, InternetModel::Role_CanLazyLoad); favorites_->setData(true, InternetModel::Role_CanBeModified); @@ -626,7 +643,8 @@ void GroovesharkService::EnsureItemsCreated() { playlists_parent_ = new QStandardItem(tr("Playlists")); root_->appendRow(playlists_parent_); - subscribed_playlists_parent_ = new QStandardItem(tr("Subscribed playlists")); + subscribed_playlists_parent_ = + new QStandardItem(tr("Subscribed playlists")); root_->appendRow(subscribed_playlists_parent_); RetrieveUserFavorites(); @@ -646,21 +664,22 @@ void GroovesharkService::EnsureConnected() { } } -QStandardItem* GroovesharkService::CreatePlaylistItem(const QString& playlist_name, - int playlist_id) { +QStandardItem* GroovesharkService::CreatePlaylistItem( + const QString& playlist_name, int playlist_id) { QStandardItem* item = new QStandardItem(playlist_name); item->setData(InternetModel::Type_UserPlaylist, InternetModel::Role_Type); item->setData(UserPlaylist, Role_PlaylistType); item->setData(true, InternetModel::Role_CanLazyLoad); item->setData(true, InternetModel::Role_CanBeModified); - item->setData(InternetModel::PlayBehaviour_MultipleItems, InternetModel::Role_PlayBehaviour); + item->setData(InternetModel::PlayBehaviour_MultipleItems, + InternetModel::Role_PlayBehaviour); item->setData(playlist_id, Role_UserPlaylistId); return item; } void GroovesharkService::RetrieveUserPlaylists() { task_playlists_id_ = - app_->task_manager()->StartTask(tr("Retrieving Grooveshark playlists")); + app_->task_manager()->StartTask(tr("Retrieving Grooveshark playlists")); QNetworkReply* reply = CreateRequest("getUserPlaylists", QList()); NewClosure(reply, SIGNAL(finished()), this, @@ -673,7 +692,7 @@ void GroovesharkService::UserPlaylistsRetrieved(QNetworkReply* reply) { QVariantMap result = ExtractResult(reply); QList playlists = ExtractPlaylistInfo(result); - foreach(const PlaylistInfo& playlist_info, playlists) { + foreach(const PlaylistInfo & playlist_info, playlists) { int playlist_id = playlist_info.id_; const QString& playlist_name = playlist_info.name_; QStandardItem* playlist_item = @@ -693,19 +712,20 @@ void GroovesharkService::UserPlaylistsRetrieved(QNetworkReply* reply) { } } -void GroovesharkService::PlaylistSongsRetrieved( - QNetworkReply* reply, int playlist_id) { +void GroovesharkService::PlaylistSongsRetrieved(QNetworkReply* reply, + int playlist_id) { reply->deleteLater(); pending_retrieve_playlists_.remove(playlist_id); - PlaylistInfo* playlist_info = subscribed_playlists_.contains(playlist_id) ? - &subscribed_playlists_[playlist_id] : &playlists_[playlist_id]; + PlaylistInfo* playlist_info = subscribed_playlists_.contains(playlist_id) + ? &subscribed_playlists_[playlist_id] + : &playlists_[playlist_id]; playlist_info->item_->removeRows(0, playlist_info->item_->rowCount()); QVariantMap result = ExtractResult(reply); SongList songs = ExtractSongs(result); Song::SortSongsListAlphabetically(&songs); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { QStandardItem* child = CreateSongItem(song); child->setData(playlist_info->id_, Role_UserPlaylistId); child->setData(true, InternetModel::Role_CanBeModified); @@ -722,15 +742,16 @@ void GroovesharkService::PlaylistSongsRetrieved( } void GroovesharkService::RetrieveUserFavorites() { - int task_id = - app_->task_manager()->StartTask(tr("Retrieving Grooveshark favorites songs")); + int task_id = app_->task_manager()->StartTask( + tr("Retrieving Grooveshark favorites songs")); QNetworkReply* reply = CreateRequest("getUserFavoriteSongs", QList()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(UserFavoritesRetrieved(QNetworkReply*, int)), reply, task_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(UserFavoritesRetrieved(QNetworkReply*, int)), reply, task_id); } -void GroovesharkService::UserFavoritesRetrieved(QNetworkReply* reply, int task_id) { +void GroovesharkService::UserFavoritesRetrieved(QNetworkReply* reply, + int task_id) { reply->deleteLater(); app_->task_manager()->SetTaskFinished(task_id); @@ -745,7 +766,7 @@ void GroovesharkService::UserFavoritesRetrieved(QNetworkReply* reply, int task_i SongList songs = ExtractSongs(result); Song::SortSongsListAlphabetically(&songs); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { QStandardItem* child = CreateSongItem(song); child->setData(true, InternetModel::Role_CanBeModified); @@ -754,15 +775,17 @@ void GroovesharkService::UserFavoritesRetrieved(QNetworkReply* reply, int task_i } void GroovesharkService::RetrieveUserLibrarySongs() { - int task_id = - app_->task_manager()->StartTask(tr("Retrieving Grooveshark My Music songs")); + int task_id = app_->task_manager()->StartTask( + tr("Retrieving Grooveshark My Music songs")); QNetworkReply* reply = CreateRequest("getUserLibrarySongs", QList()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(UserLibrarySongsRetrieved(QNetworkReply*, int)), reply, task_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(UserLibrarySongsRetrieved(QNetworkReply*, int)), reply, + task_id); } -void GroovesharkService::UserLibrarySongsRetrieved(QNetworkReply* reply, int task_id) { +void GroovesharkService::UserLibrarySongsRetrieved(QNetworkReply* reply, + int task_id) { reply->deleteLater(); app_->task_manager()->SetTaskFinished(task_id); @@ -777,7 +800,7 @@ void GroovesharkService::UserLibrarySongsRetrieved(QNetworkReply* reply, int tas SongList songs = ExtractSongs(result); Song::SortSongsListAlphabetically(&songs); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { QStandardItem* child = CreateSongItem(song); child->setData(true, InternetModel::Role_CanBeModified); @@ -787,17 +810,17 @@ void GroovesharkService::UserLibrarySongsRetrieved(QNetworkReply* reply, int tas void GroovesharkService::RetrievePopularSongs() { task_popular_id_ = - app_->task_manager()->StartTask(tr("Getting Grooveshark popular songs")); + app_->task_manager()->StartTask(tr("Getting Grooveshark popular songs")); RetrievePopularSongsMonth(); RetrievePopularSongsToday(); } void GroovesharkService::RetrievePopularSongsMonth() { QList parameters; - parameters << Param("limit", QString::number(kSongSearchLimit)); + parameters << Param("limit", QString::number(kSongSearchLimit)); QNetworkReply* reply = CreateRequest("getPopularSongsMonth", parameters); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(PopularSongsMonthRetrieved(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(PopularSongsMonthRetrieved(QNetworkReply*)), reply); } void GroovesharkService::PopularSongsMonthRetrieved(QNetworkReply* reply) { @@ -810,10 +833,9 @@ void GroovesharkService::PopularSongsMonthRetrieved(QNetworkReply* reply) { app_->task_manager()->SetTaskFinished(task_popular_id_); } - if (!popular_month_) - return; + if (!popular_month_) return; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { QStandardItem* child = CreateSongItem(song); popular_month_->appendRow(child); } @@ -821,10 +843,10 @@ void GroovesharkService::PopularSongsMonthRetrieved(QNetworkReply* reply) { void GroovesharkService::RetrievePopularSongsToday() { QList parameters; - parameters << Param("limit", QString::number(kSongSearchLimit)); + parameters << Param("limit", QString::number(kSongSearchLimit)); QNetworkReply* reply = CreateRequest("getPopularSongsToday", parameters); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(PopularSongsTodayRetrieved(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(PopularSongsTodayRetrieved(QNetworkReply*)), reply); } void GroovesharkService::PopularSongsTodayRetrieved(QNetworkReply* reply) { @@ -837,19 +859,19 @@ void GroovesharkService::PopularSongsTodayRetrieved(QNetworkReply* reply) { app_->task_manager()->SetTaskFinished(task_popular_id_); } - if (!popular_today_) - return; + if (!popular_today_) return; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { QStandardItem* child = CreateSongItem(song); popular_today_->appendRow(child); } } void GroovesharkService::RetrieveSubscribedPlaylists() { - QNetworkReply* reply = CreateRequest("getUserPlaylistsSubscribed", QList()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(SubscribedPlaylistsRetrieved(QNetworkReply*)), reply); + QNetworkReply* reply = + CreateRequest("getUserPlaylistsSubscribed", QList()); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(SubscribedPlaylistsRetrieved(QNetworkReply*)), reply); } void GroovesharkService::SubscribedPlaylistsRetrieved(QNetworkReply* reply) { @@ -858,18 +880,19 @@ void GroovesharkService::SubscribedPlaylistsRetrieved(QNetworkReply* reply) { QVariantMap result = ExtractResult(reply); QList playlists = ExtractPlaylistInfo(result); - foreach(const PlaylistInfo& playlist_info, playlists) { + foreach(const PlaylistInfo & playlist_info, playlists) { int playlist_id = playlist_info.id_; const QString& playlist_name = playlist_info.name_; - QStandardItem* playlist_item = CreatePlaylistItem(playlist_name, playlist_id); + QStandardItem* playlist_item = + CreatePlaylistItem(playlist_name, playlist_id); // Refine some playlist properties that should be different for subscribed // playlists playlist_item->setData(SubscribedPlaylist, Role_PlaylistType); playlist_item->setData(false, InternetModel::Role_CanBeModified); - - subscribed_playlists_.insert(playlist_id, - PlaylistInfo(playlist_id, playlist_name, playlist_item)); + + subscribed_playlists_.insert( + playlist_id, PlaylistInfo(playlist_id, playlist_name, playlist_item)); subscribed_playlists_parent_->appendRow(playlist_item); // Request playlist's songs @@ -879,16 +902,15 @@ void GroovesharkService::SubscribedPlaylistsRetrieved(QNetworkReply* reply) { void GroovesharkService::RetrieveAutoplayTags() { QNetworkReply* reply = CreateRequest("getAutoplayTags", QList()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(AutoplayTagsRetrieved(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(AutoplayTagsRetrieved(QNetworkReply*)), reply); } void GroovesharkService::AutoplayTagsRetrieved(QNetworkReply* reply) { reply->deleteLater(); QVariantMap result = ExtractResult(reply); QVariantMap::const_iterator it; - if (!stations_) - return; + if (!stations_) return; for (it = result.constBegin(); it != result.constEnd(); ++it) { int id = it.key().toInt(); QString name = it.value().toString().toLower(); @@ -896,24 +918,26 @@ void GroovesharkService::AutoplayTagsRetrieved(QNetworkReply* reply) { name.replace("_", " "); name[0] = name[0].toUpper(); - QStandardItem* item = new QStandardItem(QIcon(":last.fm/icon_radio.png"), name); + QStandardItem* item = + new QStandardItem(QIcon(":last.fm/icon_radio.png"), name); item->setData(InternetModel::Type_SmartPlaylist, InternetModel::Role_Type); - item->setData(InternetModel::PlayBehaviour_SingleItem, InternetModel::Role_PlayBehaviour); + item->setData(InternetModel::PlayBehaviour_SingleItem, + InternetModel::Role_PlayBehaviour); item->setData(id, Role_UserPlaylistId); stations_->appendRow(item); } } -Song GroovesharkService::StartAutoplayTag(int tag_id, QVariantMap& autoplay_state) { +Song GroovesharkService::StartAutoplayTag(int tag_id, + QVariantMap& autoplay_state) { QList parameters; parameters << Param("tagID", tag_id); QNetworkReply* reply = CreateRequest("startAutoplayTag", parameters); bool reply_has_timeouted = !WaitForReply(reply); reply->deleteLater(); - if (reply_has_timeouted) - return Song(); + if (reply_has_timeouted) return Song(); QVariantMap result = ExtractResult(reply); autoplay_state = result["autoplayState"].toMap(); @@ -923,21 +947,20 @@ Song GroovesharkService::StartAutoplayTag(int tag_id, QVariantMap& autoplay_stat Song GroovesharkService::StartAutoplay(QVariantMap& autoplay_state) { QList parameters; QVariantList artists_ids_qvariant; - foreach (int artist_id, last_artists_ids_) { + foreach(int artist_id, last_artists_ids_) { artists_ids_qvariant << QVariant(artist_id); } QVariantList songs_ids_qvariant; - foreach (int song_id, last_songs_ids_) { + foreach(int song_id, last_songs_ids_) { songs_ids_qvariant << QVariant(song_id); } - parameters << Param("artistIDs", artists_ids_qvariant) - << Param("songIDs", songs_ids_qvariant); + parameters << Param("artistIDs", artists_ids_qvariant) + << Param("songIDs", songs_ids_qvariant); QNetworkReply* reply = CreateRequest("startAutoplay", parameters); bool reply_has_timeouted = !WaitForReply(reply); reply->deleteLater(); - if (reply_has_timeouted) - return Song(); + if (reply_has_timeouted) return Song(); QVariantMap result = ExtractResult(reply); autoplay_state = result["autoplayState"].toMap(); @@ -951,8 +974,7 @@ Song GroovesharkService::GetAutoplaySong(QVariantMap& autoplay_state) { bool reply_has_timeouted = !WaitForReply(reply); reply->deleteLater(); - if (reply_has_timeouted) - return Song(); + if (reply_has_timeouted) return Song(); QVariantMap result = ExtractResult(reply); autoplay_state = result["autoplayState"].toMap(); @@ -962,8 +984,8 @@ Song GroovesharkService::GetAutoplaySong(QVariantMap& autoplay_state) { void GroovesharkService::MarkStreamKeyOver30Secs(const QString& stream_key, const QString& server_id) { QList parameters; - parameters << Param("streamKey", stream_key) - << Param("streamServerID", server_id); + parameters << Param("streamKey", stream_key) + << Param("streamServerID", server_id); QNetworkReply* reply = CreateRequest("markStreamKeyOver30Secs", parameters); NewClosure(reply, SIGNAL(finished()), this, @@ -982,9 +1004,8 @@ void GroovesharkService::MarkSongComplete(const QString& song_id, const QString& stream_key, const QString& server_id) { QList parameters; - parameters << Param("songID", song_id) - << Param("streamKey", stream_key) - << Param("streamServerID", server_id); + parameters << Param("songID", song_id) << Param("streamKey", stream_key) + << Param("streamServerID", server_id); QNetworkReply* reply = CreateRequest("markSongComplete", parameters); NewClosure(reply, SIGNAL(finished()), this, @@ -1007,26 +1028,28 @@ void GroovesharkService::ItemDoubleClicked(QStandardItem* item) { GeneratorPtr GroovesharkService::CreateGenerator(QStandardItem* item) { GeneratorPtr ret; - if (!item || - item->data(InternetModel::Role_Type).toInt() != InternetModel::Type_SmartPlaylist) { + if (!item || item->data(InternetModel::Role_Type).toInt() != + InternetModel::Type_SmartPlaylist) { return ret; } if (item == grooveshark_radio_) { if (last_artists_ids_.isEmpty()) { QMessageBox::warning(nullptr, tr("Error"), - tr("To start Grooveshark radio, you should first listen to a few other Grooveshark songs")); + tr("To start Grooveshark radio, you should first " + "listen to a few other Grooveshark songs")); return ret; } ret = GeneratorPtr(new GroovesharkRadio(this)); } else { int tag_id = item->data(Role_UserPlaylistId).toInt(); - ret = GeneratorPtr(new GroovesharkRadio(this ,tag_id)); + ret = GeneratorPtr(new GroovesharkRadio(this, tag_id)); } return ret; } -void GroovesharkService::DropMimeData(const QMimeData* data, const QModelIndex& index) { +void GroovesharkService::DropMimeData(const QMimeData* data, + const QModelIndex& index) { if (!data) { return; } @@ -1046,17 +1069,17 @@ void GroovesharkService::DropMimeData(const QMimeData* data, const QModelIndex& int playlist_type = index.data(Role_PlaylistType).toInt(); int parent_playlist_type = index.parent().data(Role_PlaylistType).toInt(); // If dropped on Favorites list - if (playlist_type == UserFavorites || parent_playlist_type == UserFavorites) { - foreach (int song_id, data_songs_ids) { - AddUserFavoriteSong(song_id); - } - } else if (playlist_type == UserLibrary || parent_playlist_type == UserLibrary) { + if (playlist_type == UserFavorites || + parent_playlist_type == UserFavorites) { + foreach(int song_id, data_songs_ids) { AddUserFavoriteSong(song_id); } + } else if (playlist_type == UserLibrary || + parent_playlist_type == UserLibrary) { // FIXME: Adding songs to user libray doesn't work atm, but the problem // seems to be on Grooveshark server side, as it returns success=true // when calling addUserLibrarySongs with a valid song id. // So this code is deactivated for now to not mislead user - //AddUserLibrarySongs(data_songs_ids); - } else { // Dropped on a normal playlist + // AddUserLibrarySongs(data_songs_ids); + } else { // Dropped on a normal playlist // Get the playlist int playlist_id = index.data(Role_UserPlaylistId).toInt(); if (!playlists_.contains(playlist_id)) { @@ -1077,37 +1100,41 @@ QList GroovesharkService::playlistitem_actions(const Song& song) { while (!playlistitem_actions_.isEmpty()) { QAction* action = playlistitem_actions_.takeFirst(); QMenu* menu = action->menu(); - if (menu) - delete menu; + if (menu) delete menu; delete action; } // Create a 'add to favorites' action - QAction* add_to_favorites = new QAction(QIcon(":/last.fm/love.png"), - tr("Add to Grooveshark favorites"), this); - connect(add_to_favorites, SIGNAL(triggered()), SLOT(AddCurrentSongToUserFavorites())); + QAction* add_to_favorites = new QAction( + QIcon(":/last.fm/love.png"), tr("Add to Grooveshark favorites"), this); + connect(add_to_favorites, SIGNAL(triggered()), + SLOT(AddCurrentSongToUserFavorites())); playlistitem_actions_.append(add_to_favorites); // FIXME: as explained above, adding songs to library doesn't work currently - //QAction* add_to_library = new QAction(IconLoader::Load("folder-sound"), - // tr("Add to Grooveshark My Music"), this); - //connect(add_to_library, SIGNAL(triggered()), SLOT(AddCurrentSongToUserLibrary())); - //playlistitem_actions_.append(add_to_library); + // QAction* add_to_library = new QAction(IconLoader::Load("folder-sound"), + // tr("Add to Grooveshark My Music"), + // this); + // connect(add_to_library, SIGNAL(triggered()), + // SLOT(AddCurrentSongToUserLibrary())); + // playlistitem_actions_.append(add_to_library); // Create a menu with 'add to playlist' actions for each Grooveshark playlist - QAction* add_to_playlists = new QAction(IconLoader::Load("list-add"), - tr("Add to Grooveshark playlists"), this); + QAction* add_to_playlists = new QAction( + IconLoader::Load("list-add"), tr("Add to Grooveshark playlists"), this); QMenu* playlists_menu = new QMenu(); - foreach (PlaylistInfo playlist_info, playlists_.values()) { + foreach(PlaylistInfo playlist_info, playlists_.values()) { QAction* add_to_playlist = new QAction(playlist_info.name_, this); add_to_playlist->setData(playlist_info.id_); playlists_menu->addAction(add_to_playlist); } - connect(playlists_menu, SIGNAL(triggered(QAction*)), SLOT(AddCurrentSongToPlaylist(QAction*))); + connect(playlists_menu, SIGNAL(triggered(QAction*)), + SLOT(AddCurrentSongToPlaylist(QAction*))); add_to_playlists->setMenu(playlists_menu); playlistitem_actions_.append(add_to_playlists); - QAction* share_song = new QAction(tr("Get a URL to share this Grooveshark song"), this); + QAction* share_song = + new QAction(tr("Get a URL to share this Grooveshark song"), this); connect(share_song, SIGNAL(triggered()), SLOT(GetCurrentSongUrlToShare())); playlistitem_actions_.append(share_song); @@ -1134,8 +1161,7 @@ void GroovesharkService::SongUrlToShareReceived(QNetworkReply* reply) { reply->deleteLater(); QVariantMap result = ExtractResult(reply); - if (!result["url"].isValid()) - return; + if (!result["url"].isValid()) return; QString url = result["url"].toString(); ShowUrlBox(tr("Grooveshark song's URL"), url); } @@ -1147,7 +1173,8 @@ void GroovesharkService::GetCurrentPlaylistUrlToShare() { void GroovesharkService::GetPlaylistUrlToShare(int playlist_id) { QList parameters; parameters << Param("playlistID", playlist_id); - QNetworkReply* reply = CreateRequest("getPlaylistURLFromPlaylistID", parameters); + QNetworkReply* reply = + CreateRequest("getPlaylistURLFromPlaylistID", parameters); NewClosure(reply, SIGNAL(finished()), this, SLOT(PlaylistUrlToShareReceived(QNetworkReply*)), reply); @@ -1156,8 +1183,7 @@ void GroovesharkService::GetPlaylistUrlToShare(int playlist_id) { void GroovesharkService::PlaylistUrlToShareReceived(QNetworkReply* reply) { reply->deleteLater(); QVariantMap result = ExtractResult(reply); - if (!result["url"].isValid()) - return; + if (!result["url"].isValid()) return; QString url = result["url"].toString(); ShowUrlBox(tr("Grooveshark playlist's URL"), url); } @@ -1191,33 +1217,32 @@ void GroovesharkService::AddCurrentSongToPlaylist(QAction* action) { SetPlaylistSongs(playlist_id, songs_ids); } -void GroovesharkService::SetPlaylistSongs(int playlist_id, const QList& songs_ids) { +void GroovesharkService::SetPlaylistSongs(int playlist_id, + const QList& songs_ids) { // If we are still retrieving playlists songs, don't update playlist: don't // take the risk to erase all (not yet retrieved) playlist's songs. - if (!pending_retrieve_playlists_.isEmpty()) - return; + if (!pending_retrieve_playlists_.isEmpty()) return; int task_id = - app_->task_manager()->StartTask(tr("Update Grooveshark playlist")); + app_->task_manager()->StartTask(tr("Update Grooveshark playlist")); QList parameters; // Convert song ids to QVariant QVariantList songs_ids_qvariant; - foreach (int song_id, songs_ids) { - songs_ids_qvariant << QVariant(song_id); - } + foreach(int song_id, songs_ids) { songs_ids_qvariant << QVariant(song_id); } - parameters << Param("playlistID", playlist_id) - << Param("songIDs", songs_ids_qvariant); + parameters << Param("playlistID", playlist_id) + << Param("songIDs", songs_ids_qvariant); QNetworkReply* reply = CreateRequest("setPlaylistSongs", parameters); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(PlaylistSongsSet(QNetworkReply*, int, int)), - reply, playlist_id, task_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(PlaylistSongsSet(QNetworkReply*, int, int)), reply, + playlist_id, task_id); } -void GroovesharkService::PlaylistSongsSet(QNetworkReply* reply, int playlist_id, int task_id) { +void GroovesharkService::PlaylistSongsSet(QNetworkReply* reply, int playlist_id, + int task_id) { reply->deleteLater(); app_->task_manager()->SetTaskFinished(task_id); @@ -1233,30 +1258,31 @@ void GroovesharkService::PlaylistSongsSet(QNetworkReply* reply, int playlist_id, void GroovesharkService::RefreshPlaylist(int playlist_id) { QList parameters; parameters << Param("playlistID", playlist_id); - QNetworkReply* reply = CreateRequest("getPlaylistSongs", parameters); + QNetworkReply* reply = CreateRequest("getPlaylistSongs", parameters); NewClosure(reply, SIGNAL(finished()), this, - SLOT(PlaylistSongsRetrieved(QNetworkReply*, int)), reply, playlist_id); + SLOT(PlaylistSongsRetrieved(QNetworkReply*, int)), reply, + playlist_id); pending_retrieve_playlists_.insert(playlist_id); } void GroovesharkService::CreateNewPlaylist() { - QString name = QInputDialog::getText(nullptr, - tr("Create a new Grooveshark playlist"), - tr("Name"), - QLineEdit::Normal); + QString name = + QInputDialog::getText(nullptr, tr("Create a new Grooveshark playlist"), + tr("Name"), QLineEdit::Normal); if (name.isEmpty()) { return; } QList parameters; - parameters << Param("name", name) - << Param("songIDs", QVariantList()); + parameters << Param("name", name) << Param("songIDs", QVariantList()); QNetworkReply* reply = CreateRequest("createPlaylist", parameters); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(NewPlaylistCreated(QNetworkReply*, const QString&)), reply, name); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(NewPlaylistCreated(QNetworkReply*, const QString&)), reply, + name); } -void GroovesharkService::NewPlaylistCreated(QNetworkReply* reply, const QString& name) { +void GroovesharkService::NewPlaylistCreated(QNetworkReply* reply, + const QString& name) { reply->deleteLater(); QVariantMap result = ExtractResult(reply); if (!result["success"].toBool() || !result["playlistID"].isValid()) { @@ -1287,10 +1313,10 @@ void GroovesharkService::DeletePlaylist(int playlist_id) { return; } - std::unique_ptr confirmation_dialog(new QMessageBox( - QMessageBox::Question, tr("Delete Grooveshark playlist"), - tr("Are you sure you want to delete this playlist?"), - QMessageBox::Yes | QMessageBox::Cancel)); + std::unique_ptr confirmation_dialog( + new QMessageBox(QMessageBox::Question, tr("Delete Grooveshark playlist"), + tr("Are you sure you want to delete this playlist?"), + QMessageBox::Yes | QMessageBox::Cancel)); if (confirmation_dialog->exec() != QMessageBox::Yes) { return; } @@ -1298,11 +1324,12 @@ void GroovesharkService::DeletePlaylist(int playlist_id) { QList parameters; parameters << Param("playlistID", playlist_id); QNetworkReply* reply = CreateRequest("deletePlaylist", parameters); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(PlaylistDeleted(QNetworkReply*, int)), reply, playlist_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(PlaylistDeleted(QNetworkReply*, int)), reply, playlist_id); } -void GroovesharkService::PlaylistDeleted(QNetworkReply* reply, int playlist_id) { +void GroovesharkService::PlaylistDeleted(QNetworkReply* reply, + int playlist_id) { reply->deleteLater(); QVariantMap result = ExtractResult(reply); if (!result["success"].toBool()) { @@ -1319,8 +1346,9 @@ void GroovesharkService::PlaylistDeleted(QNetworkReply* reply, int playlist_id) void GroovesharkService::RenameCurrentPlaylist() { const QModelIndex& index(model()->current_index()); - if (index.data(InternetModel::Role_Type).toInt() != InternetModel::Type_UserPlaylist - || index.data(Role_PlaylistType).toInt() != UserPlaylist) { + if (index.data(InternetModel::Role_Type).toInt() != + InternetModel::Type_UserPlaylist || + index.data(Role_PlaylistType).toInt() != UserPlaylist) { return; } @@ -1333,25 +1361,22 @@ void GroovesharkService::RenamePlaylist(int playlist_id) { return; } const QString& old_name = playlists_[playlist_id].name_; - QString new_name = QInputDialog::getText(nullptr, - tr("Rename \"%1\" playlist").arg(old_name), - tr("Name"), - QLineEdit::Normal, - old_name); + QString new_name = + QInputDialog::getText(nullptr, tr("Rename \"%1\" playlist").arg(old_name), + tr("Name"), QLineEdit::Normal, old_name); if (new_name.isEmpty()) { return; } QList parameters; - parameters << Param("playlistID", playlist_id) - << Param("name", new_name); + parameters << Param("playlistID", playlist_id) << Param("name", new_name); QNetworkReply* reply = CreateRequest("renamePlaylist", parameters); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(PlaylistRenamed(QNetworkReply*, int, const QString&)), reply, playlist_id, new_name); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(PlaylistRenamed(QNetworkReply*, int, const QString&)), reply, + playlist_id, new_name); } -void GroovesharkService::PlaylistRenamed(QNetworkReply* reply, - int playlist_id, +void GroovesharkService::PlaylistRenamed(QNetworkReply* reply, int playlist_id, const QString& new_name) { reply->deleteLater(); QVariantMap result = ExtractResult(reply); @@ -1372,12 +1397,12 @@ void GroovesharkService::AddUserFavoriteSong(int song_id) { QList parameters; parameters << Param("songID", song_id); QNetworkReply* reply = CreateRequest("addUserFavoriteSong", parameters); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(UserFavoriteSongAdded(QNetworkReply*, int)), - reply, task_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(UserFavoriteSongAdded(QNetworkReply*, int)), reply, task_id); } -void GroovesharkService::UserFavoriteSongAdded(QNetworkReply* reply, int task_id) { +void GroovesharkService::UserFavoriteSongAdded(QNetworkReply* reply, + int task_id) { reply->deleteLater(); app_->task_manager()->SetTaskFinished(task_id); @@ -1396,9 +1421,7 @@ void GroovesharkService::AddUserLibrarySongs(const QList& songs_ids) { // Convert songs ids to QVariant QVariantList songs_ids_qvariant; - foreach (int song_id, songs_ids) { - songs_ids_qvariant << QVariant(song_id); - } + foreach(int song_id, songs_ids) { songs_ids_qvariant << QVariant(song_id); } QVariantList albums_ids_qvariant; QVariantList artists_ids_qvariant; @@ -1408,12 +1431,12 @@ void GroovesharkService::AddUserLibrarySongs(const QList& songs_ids) { parameters << Param("albumIDs", albums_ids_qvariant); parameters << Param("artistIDs", artists_ids_qvariant); QNetworkReply* reply = CreateRequest("addUserLibrarySongs", parameters); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(UserLibrarySongAdded(QNetworkReply*, int)), - reply, task_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(UserLibrarySongAdded(QNetworkReply*, int)), reply, task_id); } -void GroovesharkService::UserLibrarySongAdded(QNetworkReply* reply, int task_id) { +void GroovesharkService::UserLibrarySongAdded(QNetworkReply* reply, + int task_id) { reply->deleteLater(); app_->task_manager()->SetTaskFinished(task_id); @@ -1429,7 +1452,7 @@ void GroovesharkService::UserLibrarySongAdded(QNetworkReply* reply, int task_id) void GroovesharkService::RemoveCurrentFromPlaylist() { const QModelIndexList& indexes(model()->selected_indexes()); QMap > playlists_songs_ids; - foreach (const QModelIndex& index, indexes) { + foreach(const QModelIndex & index, indexes) { if (index.parent().data(InternetModel::Role_Type).toInt() != InternetModel::Type_UserPlaylist) { @@ -1443,21 +1466,21 @@ void GroovesharkService::RemoveCurrentFromPlaylist() { } } - for (QMap >::const_iterator it = playlists_songs_ids.constBegin(); - it != playlists_songs_ids.constEnd(); - ++it) { + for (QMap >::const_iterator it = + playlists_songs_ids.constBegin(); + it != playlists_songs_ids.constEnd(); ++it) { RemoveFromPlaylist(it.key(), it.value()); } } -void GroovesharkService::RemoveFromPlaylist(int playlist_id, - const QList& songs_ids_to_remove) { +void GroovesharkService::RemoveFromPlaylist( + int playlist_id, const QList& songs_ids_to_remove) { if (!playlists_.contains(playlist_id)) { return; } QList songs_ids = playlists_[playlist_id].songs_ids_; - foreach (const int song_id, songs_ids_to_remove) { + foreach(const int song_id, songs_ids_to_remove) { songs_ids.removeOne(song_id); } @@ -1467,7 +1490,7 @@ void GroovesharkService::RemoveFromPlaylist(int playlist_id, void GroovesharkService::RemoveCurrentFromFavorites() { const QModelIndexList& indexes(model()->selected_indexes()); QList songs_ids; - foreach (const QModelIndex& index, indexes) { + foreach(const QModelIndex & index, indexes) { if (index.parent().data(Role_PlaylistType).toInt() != UserFavorites) { continue; @@ -1478,30 +1501,33 @@ void GroovesharkService::RemoveCurrentFromFavorites() { songs_ids << song_id; } } - + RemoveFromFavorites(songs_ids); } -void GroovesharkService::RemoveFromFavorites(const QList& songs_ids_to_remove) { - if (songs_ids_to_remove.isEmpty()) - return; +void GroovesharkService::RemoveFromFavorites( + const QList& songs_ids_to_remove) { + if (songs_ids_to_remove.isEmpty()) return; - int task_id = app_->task_manager()->StartTask(tr("Removing songs from favorites")); + int task_id = + app_->task_manager()->StartTask(tr("Removing songs from favorites")); QList parameters; // Convert song ids to QVariant QVariantList songs_ids_qvariant; - foreach (const int song_id, songs_ids_to_remove) { + foreach(const int song_id, songs_ids_to_remove) { songs_ids_qvariant << QVariant(song_id); } parameters << Param("songIDs", songs_ids_qvariant); QNetworkReply* reply = CreateRequest("removeUserFavoriteSongs", parameters); NewClosure(reply, SIGNAL(finished()), this, - SLOT(SongsRemovedFromFavorites(QNetworkReply*, int)), reply, task_id); + SLOT(SongsRemovedFromFavorites(QNetworkReply*, int)), reply, + task_id); } -void GroovesharkService::SongsRemovedFromFavorites(QNetworkReply* reply, int task_id) { +void GroovesharkService::SongsRemovedFromFavorites(QNetworkReply* reply, + int task_id) { app_->task_manager()->SetTaskFinished(task_id); reply->deleteLater(); @@ -1517,7 +1543,7 @@ void GroovesharkService::RemoveCurrentFromLibrary() { const QModelIndexList& indexes(model()->selected_indexes()); QList songs_ids; - foreach (const QModelIndex& index, indexes) { + foreach(const QModelIndex & index, indexes) { if (index.parent().data(Role_PlaylistType).toInt() != UserLibrary) { continue; @@ -1528,20 +1554,21 @@ void GroovesharkService::RemoveCurrentFromLibrary() { songs_ids << song_id; } } - + RemoveFromLibrary(songs_ids); } -void GroovesharkService::RemoveFromLibrary(const QList& songs_ids_to_remove) { - if (songs_ids_to_remove.isEmpty()) - return; +void GroovesharkService::RemoveFromLibrary( + const QList& songs_ids_to_remove) { + if (songs_ids_to_remove.isEmpty()) return; - int task_id = app_->task_manager()->StartTask(tr("Removing songs from My Music")); + int task_id = + app_->task_manager()->StartTask(tr("Removing songs from My Music")); QList parameters; // Convert song ids to QVariant QVariantList songs_ids_qvariant; - foreach (const int song_id, songs_ids_to_remove) { + foreach(const int song_id, songs_ids_to_remove) { songs_ids_qvariant << QVariant(song_id); } QVariantList albums_ids_qvariant; @@ -1555,10 +1582,12 @@ void GroovesharkService::RemoveFromLibrary(const QList& songs_ids_to_remove QNetworkReply* reply = CreateRequest("removeUserLibrarySongs", parameters); NewClosure(reply, SIGNAL(finished()), this, - SLOT(SongsRemovedFromLibrary(QNetworkReply*, int)), reply, task_id); + SLOT(SongsRemovedFromLibrary(QNetworkReply*, int)), reply, + task_id); } -void GroovesharkService::SongsRemovedFromLibrary(QNetworkReply* reply, int task_id) { +void GroovesharkService::SongsRemovedFromLibrary(QNetworkReply* reply, + int task_id) { app_->task_manager()->SetTaskFinished(task_id); reply->deleteLater(); @@ -1570,10 +1599,9 @@ void GroovesharkService::SongsRemovedFromLibrary(QNetworkReply* reply, int task_ RetrieveUserLibrarySongs(); } -QNetworkReply* GroovesharkService::CreateRequest( - const QString& method_name, - const QList& params, - bool use_https) { +QNetworkReply* GroovesharkService::CreateRequest(const QString& method_name, + const QList& params, + bool use_https) { QVariantMap request_params; request_params.insert("method", method_name); @@ -1592,7 +1620,7 @@ QNetworkReply* GroovesharkService::CreateRequest( request_params.insert("header", header); QVariantMap parameters; - foreach(const Param& param, params) { + foreach(const Param & param, params) { parameters.insert(param.first, param.second); } request_params.insert("parameters", parameters); @@ -1604,9 +1632,12 @@ QNetworkReply* GroovesharkService::CreateRequest( if (use_https) { url.setScheme("https"); } - url.setQueryItems( QList >() << QPair("sig", Utilities::HmacMd5(api_key_, post_params).toHex())); + url.setQueryItems( + QList >() + << QPair( + "sig", Utilities::HmacMd5(api_key_, post_params).toHex())); QNetworkRequest req(url); - QNetworkReply *reply = network_->post(req, post_params); + QNetworkReply* reply = network_->post(req, post_params); if (use_https) { connect(reply, SIGNAL(sslErrors(QList)), @@ -1619,7 +1650,7 @@ QNetworkReply* GroovesharkService::CreateRequest( void GroovesharkService::RequestSslErrors(const QList& errors) { QNetworkReply* reply = qobject_cast(sender()); - foreach (const QSslError& error, errors) { + foreach(const QSslError & error, errors) { emit StreamError("SSL error occurred in Grooveshark request for " + reply->url().toString() + ": " + error.errorString()); } @@ -1651,14 +1682,16 @@ QVariantMap GroovesharkService::ExtractResult(QNetworkReply* reply) { QVariantList::iterator it; for (it = errors.begin(); it != errors.end(); ++it) { QVariantMap error = (*it).toMap(); - qLog(Error) << "Grooveshark error: (" << error["code"].toInt() <<") " << error["message"].toString(); + qLog(Error) << "Grooveshark error: (" << error["code"].toInt() << ") " + << error["message"].toString(); switch (error["code"].toInt()) { - case 100: // User auth required - case 102: // User premium required - case 300: // Session required - // These errors can happen if session_id is obsolete (e.g. we haven't use + case 100: // User auth required + case 102: // User premium required + case 300: // Session required + // These errors can happen if session_id is obsolete (e.g. we haven't + // use // it for more than two weeks): force the user to login again - Logout(); + Logout(); break; } } @@ -1668,7 +1701,7 @@ QVariantMap GroovesharkService::ExtractResult(QNetworkReply* reply) { SongList GroovesharkService::ExtractSongs(const QVariantMap& result) { QVariantList result_songs = result["songs"].toList(); SongList songs; - for (int i=0; i GroovesharkService::ExtractSongsIds(const QVariantMap& result) { QVariantList result_songs = result["songs"].toList(); QList songs_ids; - for (int i=0; i GroovesharkService::ExtractSongsIds(const QVariantMap& result) { QList GroovesharkService::ExtractSongsIds(const QList& urls) { QList songs_ids; - foreach (const QUrl& url, urls) { + foreach(const QUrl & url, urls) { int song_id = ExtractSongId(url); if (song_id) { songs_ids << song_id; @@ -1744,13 +1779,14 @@ int GroovesharkService::ExtractSongId(const QUrl& url) { return 0; } -QList GroovesharkService::ExtractPlaylistInfo(const QVariantMap& result) { +QList GroovesharkService::ExtractPlaylistInfo( + const QVariantMap& result) { QVariantList playlists_qvariant = result["playlists"].toList(); QList playlists; // Get playlists info - foreach (const QVariant& playlist_qvariant, playlists_qvariant) { + foreach(const QVariant & playlist_qvariant, playlists_qvariant) { QVariantMap playlist = playlist_qvariant.toMap(); int playlist_id = playlist["PlaylistID"].toInt(); QString playlist_name = playlist["PlaylistName"].toString(); diff --git a/src/internet/groovesharkservice.h b/src/internet/groovesharkservice.h index d39510f11..9141c09cc 100644 --- a/src/internet/groovesharkservice.h +++ b/src/internet/groovesharkservice.h @@ -36,7 +36,7 @@ class QSortFilterProxyModel; class GroovesharkService : public InternetService { Q_OBJECT public: - GroovesharkService(Application* app, InternetModel *parent); + GroovesharkService(Application* app, InternetModel* parent); ~GroovesharkService(); enum Role { @@ -63,7 +63,7 @@ class GroovesharkService : public InternetService { // Internet Service methods QStandardItem* CreateRootItem(); - void LazyPopulate(QStandardItem *parent); + void LazyPopulate(QStandardItem* parent); void ItemDoubleClicked(QStandardItem* item); smart_playlists::GeneratorPtr CreateGenerator(QStandardItem* item); @@ -73,9 +73,9 @@ class GroovesharkService : public InternetService { QWidget* HeaderWidget() const; // User should be logged in to be able to generate streaming urls - QUrl GetStreamingUrlFromSongId(const QString& song_id, const QString& artist_id, - QString* server_id, QString* stream_key, - qint64* length_nanosec); + QUrl GetStreamingUrlFromSongId(const QString& song_id, + const QString& artist_id, QString* server_id, + QString* stream_key, qint64* length_nanosec); void Login(const QString& username, const QString& password); void Logout(); bool IsLoggedIn() const { return !session_id_.isEmpty(); } @@ -88,7 +88,8 @@ class GroovesharkService : public InternetService { void RetrieveSubscribedPlaylists(); void RetrieveAutoplayTags(); void SetPlaylistSongs(int playlist_id, const QList& songs_ids); - void RemoveFromPlaylist(int playlist_id, const QList& songs_ids_to_remove); + void RemoveFromPlaylist(int playlist_id, + const QList& songs_ids_to_remove); // Refresh playlist_id playlist , or create it if it doesn't exist void RefreshPlaylist(int playlist_id); void DeletePlaylist(int playlist_id); @@ -103,10 +104,13 @@ class GroovesharkService : public InternetService { // first song to play Song StartAutoplayTag(int tag_id, QVariantMap& autoplay_state); Song StartAutoplay(QVariantMap& autoplay_state); - // Get another autoplay song. autoplay_state is the autoplay_state received from StartAutoplayTag + // Get another autoplay song. autoplay_state is the autoplay_state received + // from StartAutoplayTag Song GetAutoplaySong(QVariantMap& autoplay_state); - void MarkStreamKeyOver30Secs(const QString& stream_key, const QString& server_id); - void MarkSongComplete(const QString& song_id, const QString& stream_key, const QString& server_id); + void MarkStreamKeyOver30Secs(const QString& stream_key, + const QString& server_id); + void MarkSongComplete(const QString& song_id, const QString& stream_key, + const QString& server_id); // Persisted in the settings and updated on each Login(). LoginState login_state() const { return login_state_; } @@ -119,7 +123,7 @@ class GroovesharkService : public InternetService { static const char* kServiceName; static const char* kSettingsGroup; - signals: +signals: void LoginFinished(bool success); void SimpleSearchResults(int id, SongList songs); // AlbumSearchResult emits the search id and the Grooveshark ids of the @@ -136,9 +140,9 @@ class GroovesharkService : public InternetService { struct PlaylistInfo { PlaylistInfo() {} PlaylistInfo(int id, QString name, QStandardItem* item = NULL) - : id_(id), name_(name), item_(item) {} + : id_(id), name_(name), item_(item) {} - bool operator< (const PlaylistInfo other) const { + bool operator<(const PlaylistInfo other) const { return name_.localeAwareCompare(other.name_) < 0; } @@ -170,9 +174,14 @@ class GroovesharkService : public InternetService { void DeleteCurrentPlaylist(); void RenameCurrentPlaylist(); void PlaylistDeleted(QNetworkReply* reply, int playlist_id); - void PlaylistRenamed(QNetworkReply* reply, int playlist_id, const QString& new_name); - void AddCurrentSongToUserFavorites() { AddUserFavoriteSong(current_song_id_); } - void AddCurrentSongToUserLibrary() { AddUserLibrarySongs(QList() << current_song_id_); } + void PlaylistRenamed(QNetworkReply* reply, int playlist_id, + const QString& new_name); + void AddCurrentSongToUserFavorites() { + AddUserFavoriteSong(current_song_id_); + } + void AddCurrentSongToUserLibrary() { + AddUserLibrarySongs(QList() << current_song_id_); + } void AddCurrentSongToPlaylist(QAction* action); void UserFavoriteSongAdded(QNetworkReply* reply, int task_id); void UserLibrarySongAdded(QNetworkReply* reply, int task_id); @@ -203,7 +212,8 @@ class GroovesharkService : public InternetService { // Create a playlist item, with data set as excepted. Doesn't fill the item // with songs rows. - QStandardItem* CreatePlaylistItem(const QString& playlist_name, int playlist_id); + QStandardItem* CreatePlaylistItem(const QString& playlist_name, + int playlist_id); void AuthenticateSession(); void InitCountry(); @@ -211,10 +221,9 @@ class GroovesharkService : public InternetService { // Create a request for the given method, with the given params. // If need_authentication is true, add session_id to params. // Returns the reply object created - QNetworkReply* CreateRequest( - const QString& method_name, - const QList >& params, - bool use_https = false); + QNetworkReply* CreateRequest(const QString& method_name, + const QList >& params, + bool use_https = false); // Convenient function which block until 'reply' replies, or timeout after 10 // seconds. Returns false if reply has timeouted bool WaitForReply(QNetworkReply* reply); @@ -231,14 +240,14 @@ class GroovesharkService : public InternetService { // Convenient functions for extracting Grooveshark songs ids QList ExtractSongsIds(const QVariantMap& result); QList ExtractSongsIds(const QList& urls); - int ExtractSongId(const QUrl& url); // Returns 0 if url is not a Grooveshark url + int ExtractSongId( + const QUrl& url); // Returns 0 if url is not a Grooveshark url // Convenient function for extracting basic playlist info (only 'id' and // 'name': QStandardItem still need to be created), and sort them by name QList ExtractPlaylistInfo(const QVariantMap& result); void ResetSessionId(); - GroovesharkUrlHandler* url_handler_; QString pending_search_; @@ -288,7 +297,7 @@ class GroovesharkService : public InternetService { QNetworkReply* last_search_reply_; QString username_; - QString password_; // In fact, password's md5 hash + QString password_; // In fact, password's md5 hash QString user_id_; QString session_id_; QMap country_; @@ -318,5 +327,4 @@ class GroovesharkService : public InternetService { static const char* kApiSecret; }; - -#endif // GROOVESHARKSERVICE_H +#endif // GROOVESHARKSERVICE_H diff --git a/src/internet/groovesharksettingspage.cpp b/src/internet/groovesharksettingspage.cpp index b44b0b68e..71bd461a3 100644 --- a/src/internet/groovesharksettingspage.cpp +++ b/src/internet/groovesharksettingspage.cpp @@ -30,11 +30,10 @@ #include GroovesharkSettingsPage::GroovesharkSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_GroovesharkSettingsPage), - service_(InternetModel::Service()), - validated_(false) -{ + : SettingsPage(dialog), + ui_(new Ui_GroovesharkSettingsPage), + service_(InternetModel::Service()), + validated_(false) { ui_->setupUi(this); setWindowIcon(QIcon(":/providers/grooveshark.png")); @@ -50,9 +49,7 @@ GroovesharkSettingsPage::GroovesharkSettingsPage(SettingsDialog* dialog) ui_->login_state->AddCredentialGroup(ui_->account_group); } -GroovesharkSettingsPage::~GroovesharkSettingsPage() { - delete ui_; -} +GroovesharkSettingsPage::~GroovesharkSettingsPage() { delete ui_; } void GroovesharkSettingsPage::Login() { if (service_->IsLoggedIn()) { @@ -93,23 +90,26 @@ void GroovesharkSettingsPage::LoginFinished(bool success) { void GroovesharkSettingsPage::UpdateLoginState() { const bool logged_in = service_->IsLoggedIn(); - ui_->login_state->SetLoggedIn(logged_in ? LoginStateWidget::LoggedIn - : LoginStateWidget::LoggedOut, - ui_->username->text()); + ui_->login_state->SetLoggedIn( + logged_in ? LoginStateWidget::LoggedIn : LoginStateWidget::LoggedOut, + ui_->username->text()); ui_->login_state->SetAccountTypeVisible(!logged_in); switch (service_->login_state()) { - case GroovesharkService::LoginState_NoPremium: - ui_->login_state->SetAccountTypeText(tr("You do not have a Grooveshark Anywhere account.")); - break; + case GroovesharkService::LoginState_NoPremium: + ui_->login_state->SetAccountTypeText( + tr("You do not have a Grooveshark Anywhere account.")); + break; - case GroovesharkService::LoginState_AuthFailed: - ui_->login_state->SetAccountTypeText(tr("Your username or password was incorrect.")); - break; + case GroovesharkService::LoginState_AuthFailed: + ui_->login_state->SetAccountTypeText( + tr("Your username or password was incorrect.")); + break; - default: - ui_->login_state->SetAccountTypeText(tr("A Grooveshark Anywhere account is required.")); - break; + default: + ui_->login_state->SetAccountTypeText( + tr("A Grooveshark Anywhere account is required.")); + break; } } diff --git a/src/internet/groovesharksettingspage.h b/src/internet/groovesharksettingspage.h index 838cad311..88b74fbe4 100644 --- a/src/internet/groovesharksettingspage.h +++ b/src/internet/groovesharksettingspage.h @@ -27,22 +27,22 @@ class GroovesharkService; class GroovesharkSettingsPage : public SettingsPage { Q_OBJECT -public: + public: GroovesharkSettingsPage(SettingsDialog* dialog); ~GroovesharkSettingsPage(); void Load(); void Save(); -private slots: + private slots: void Login(); void LoginFinished(bool success); void Logout(); -private: + private: void UpdateLoginState(); -private: + private: Ui_GroovesharkSettingsPage* ui_; GroovesharkService* service_; @@ -51,4 +51,4 @@ private: QString original_password_; }; -#endif // GROOVESHARKSETTINGSPAGE_H +#endif // GROOVESHARKSETTINGSPAGE_H diff --git a/src/internet/groovesharkurlhandler.cpp b/src/internet/groovesharkurlhandler.cpp index 1948526e9..c505baf1c 100644 --- a/src/internet/groovesharkurlhandler.cpp +++ b/src/internet/groovesharkurlhandler.cpp @@ -22,21 +22,23 @@ #include "groovesharkservice.h" #include "core/logging.h" - -GroovesharkUrlHandler::GroovesharkUrlHandler(GroovesharkService* service, QObject* parent) - : UrlHandler(parent), - service_(service), - timer_mark_stream_key_(new QTimer(this)) { +GroovesharkUrlHandler::GroovesharkUrlHandler(GroovesharkService* service, + QObject* parent) + : UrlHandler(parent), + service_(service), + timer_mark_stream_key_(new QTimer(this)) { // We have to warn Grooveshark when user has listened for more than 30 // seconds of a song, and when it ends. I guess this is used by Grooveshark // for statistics and user history. - // To do this, we have TrackAboutToEnd method, and timer_mark_stream_key_ timer. + // To do this, we have TrackAboutToEnd method, and timer_mark_stream_key_ + // timer. // It is not perfect, as we may call Grooveshark MarkStreamKeyOver30Secs even // if user hasn't actually listen to 30 seconds (e.g. stream set to pause // state) but this is not a big deal and it should be accurate enough anyway. timer_mark_stream_key_->setInterval(30000); timer_mark_stream_key_->setSingleShot(true); - connect(timer_mark_stream_key_, SIGNAL(timeout()), SLOT(MarkStreamKeyOver30Secs())); + connect(timer_mark_stream_key_, SIGNAL(timeout()), + SLOT(MarkStreamKeyOver30Secs())); } UrlHandler::LoadResult GroovesharkUrlHandler::StartLoading(const QUrl& url) { @@ -48,17 +50,19 @@ UrlHandler::LoadResult GroovesharkUrlHandler::StartLoading(const QUrl& url) { qLog(Error) << "Should be grooveshark://artist_id/album_id/song_id"; } else { last_artist_id_ = ids[0]; - last_album_id_ = ids[1]; - last_song_id_ = ids[2]; + last_album_id_ = ids[1]; + last_song_id_ = ids[2]; - streaming_url = service_->GetStreamingUrlFromSongId(last_song_id_, last_artist_id_, - &last_server_id_, &last_stream_key_, &length_nanosec); + streaming_url = service_->GetStreamingUrlFromSongId( + last_song_id_, last_artist_id_, &last_server_id_, &last_stream_key_, + &length_nanosec); qLog(Debug) << "Grooveshark Streaming URL: " << streaming_url; timer_mark_stream_key_->start(); } - return LoadResult(url, LoadResult::TrackAvailable, streaming_url, length_nanosec); + return LoadResult(url, LoadResult::TrackAvailable, streaming_url, + length_nanosec); } void GroovesharkUrlHandler::TrackAboutToEnd() { @@ -69,9 +73,7 @@ void GroovesharkUrlHandler::TrackAboutToEnd() { service_->MarkSongComplete(last_song_id_, last_stream_key_, last_server_id_); } -void GroovesharkUrlHandler::TrackSkipped() { - timer_mark_stream_key_->stop(); -} +void GroovesharkUrlHandler::TrackSkipped() { timer_mark_stream_key_->stop(); } void GroovesharkUrlHandler::MarkStreamKeyOver30Secs() { service_->MarkStreamKeyOver30Secs(last_stream_key_, last_server_id_); diff --git a/src/internet/groovesharkurlhandler.h b/src/internet/groovesharkurlhandler.h index c0ca3b228..cc5cad9e7 100644 --- a/src/internet/groovesharkurlhandler.h +++ b/src/internet/groovesharkurlhandler.h @@ -25,7 +25,7 @@ class QTimer; class GroovesharkUrlHandler : public UrlHandler { Q_OBJECT -public: + public: GroovesharkUrlHandler(GroovesharkService* service, QObject* parent); QString scheme() const { return "grooveshark"; } @@ -34,10 +34,10 @@ public: void TrackAboutToEnd(); void TrackSkipped(); -private slots: + private slots: void MarkStreamKeyOver30Secs(); -private: + private: GroovesharkService* service_; QTimer* timer_mark_stream_key_; QString last_artist_id_; @@ -47,4 +47,4 @@ private: QString last_stream_key_; }; -#endif // GROOVESHARKURLHANDLER_H +#endif // GROOVESHARKURLHANDLER_H diff --git a/src/internet/icecastbackend.cpp b/src/internet/icecastbackend.cpp index 51cfa3007..2d19e352c 100644 --- a/src/internet/icecastbackend.cpp +++ b/src/internet/icecastbackend.cpp @@ -24,14 +24,9 @@ const char* IcecastBackend::kTableName = "icecast_stations"; -IcecastBackend::IcecastBackend(QObject* parent) - : QObject(parent) -{ -} +IcecastBackend::IcecastBackend(QObject* parent) : QObject(parent) {} -void IcecastBackend::Init(Database* db) { - db_ = db; -} +void IcecastBackend::Init(Database* db) { db_ = db; } QStringList IcecastBackend::GetGenresAlphabetical(const QString& filter) { QStringList ret; @@ -41,7 +36,7 @@ QStringList IcecastBackend::GetGenresAlphabetical(const QString& filter) { QString where = filter.isEmpty() ? "" : "WHERE name LIKE :filter"; QString sql = QString("SELECT DISTINCT genre FROM %1 %2 ORDER BY genre") - .arg(kTableName, where); + .arg(kTableName, where); QSqlQuery q(sql, db); if (!filter.isEmpty()) { @@ -64,10 +59,11 @@ QStringList IcecastBackend::GetGenresByPopularity(const QString& filter) { QString where = filter.isEmpty() ? "" : "WHERE name LIKE :filter"; - QString sql = QString("SELECT genre, COUNT(*) AS count FROM %1 " - " %2" - " GROUP BY genre" - " ORDER BY count DESC").arg(kTableName, where); + QString sql = QString( + "SELECT genre, COUNT(*) AS count FROM %1 " + " %2" + " GROUP BY genre" + " ORDER BY count DESC").arg(kTableName, where); QSqlQuery q(sql, db); if (!filter.isEmpty()) { q.bindValue(":filter", QString("%" + filter + "%")); @@ -100,30 +96,29 @@ IcecastBackend::StationList IcecastBackend::GetStations(const QString& filter, bound_items << "%" + filter + "%"; } - QString sql = QString("SELECT name, url, mime_type, bitrate, channels," - " samplerate, genre" - " FROM %1").arg(kTableName); + QString sql = QString( + "SELECT name, url, mime_type, bitrate, channels," + " samplerate, genre" + " FROM %1").arg(kTableName); if (!where_clauses.isEmpty()) { sql += " WHERE " + where_clauses.join(" AND "); } QSqlQuery q(sql, db); - foreach (const QString& value, bound_items) { - q.addBindValue(value); - } + foreach(const QString & value, bound_items) { q.addBindValue(value); } q.exec(); if (db_->CheckErrors(q)) return ret; while (q.next()) { Station station; - station.name = q.value(0).toString(); - station.url = QUrl(q.value(1).toString()); - station.mime_type = q.value(2).toString(); - station.bitrate = q.value(3).toInt(); - station.channels = q.value(4).toInt(); + station.name = q.value(0).toString(); + station.url = QUrl(q.value(1).toString()); + station.mime_type = q.value(2).toString(); + station.bitrate = q.value(3).toInt(); + station.channels = q.value(4).toInt(); station.samplerate = q.value(5).toInt(); - station.genre = q.value(6).toString(); + station.genre = q.value(6).toString(); ret << station; } return ret; @@ -148,14 +143,16 @@ void IcecastBackend::ClearAndAddStations(const StationList& stations) { q.exec(); if (db_->CheckErrors(q)) return; - q = QSqlQuery(QString("INSERT INTO %1 (name, url, mime_type, bitrate," - " channels, samplerate, genre)" - " VALUES (:name, :url, :mime_type, :bitrate," - " :channels, :samplerate, :genre)") - .arg(kTableName), db); + q = QSqlQuery( + QString( + "INSERT INTO %1 (name, url, mime_type, bitrate," + " channels, samplerate, genre)" + " VALUES (:name, :url, :mime_type, :bitrate," + " :channels, :samplerate, :genre)").arg(kTableName), + db); // Add these ones - foreach (const Station& station, stations) { + foreach(const Station & station, stations) { q.bindValue(":name", station.name); q.bindValue(":url", station.url); q.bindValue(":mime_type", station.mime_type); diff --git a/src/internet/icecastbackend.h b/src/internet/icecastbackend.h index f5ffd1b87..f67203f45 100644 --- a/src/internet/icecastbackend.h +++ b/src/internet/icecastbackend.h @@ -28,18 +28,14 @@ class Database; class IcecastBackend : public QObject { Q_OBJECT -public: + public: IcecastBackend(QObject* parent = 0); void Init(Database* db); static const char* kTableName; struct Station { - Station() - : bitrate(0), - channels(0), - samplerate(0) { - } + Station() : bitrate(0), channels(0), samplerate(0) {} QString name; QUrl url; @@ -65,8 +61,8 @@ public: signals: void DatabaseReset(); -private: + private: Database* db_; }; -#endif // ICECASTBACKEND_H +#endif // ICECASTBACKEND_H diff --git a/src/internet/icecastfilterwidget.cpp b/src/internet/icecastfilterwidget.cpp index ce7e7f3f3..ba7bb9a9e 100644 --- a/src/internet/icecastfilterwidget.cpp +++ b/src/internet/icecastfilterwidget.cpp @@ -27,12 +27,11 @@ const char* IcecastFilterWidget::kSettingsGroup = "Icecast"; -IcecastFilterWidget::IcecastFilterWidget(QWidget *parent) - : QWidget(parent), - ui_(new Ui_IcecastFilterWidget), - menu_(new QMenu(tr("Display options"), this)), - sort_mode_mapper_(new QSignalMapper(this)) -{ +IcecastFilterWidget::IcecastFilterWidget(QWidget* parent) + : QWidget(parent), + ui_(new Ui_IcecastFilterWidget), + menu_(new QMenu(tr("Display options"), this)), + sort_mode_mapper_(new QSignalMapper(this)) { ui_->setupUi(this); // Icons @@ -40,9 +39,12 @@ IcecastFilterWidget::IcecastFilterWidget(QWidget *parent) // Options actions QActionGroup* group = new QActionGroup(this); - AddAction(group, ui_->action_sort_genre_popularity, IcecastModel::SortMode_GenreByPopularity); - AddAction(group, ui_->action_sort_genre_alphabetically, IcecastModel::SortMode_GenreAlphabetical); - AddAction(group, ui_->action_sort_station, IcecastModel::SortMode_StationAlphabetical); + AddAction(group, ui_->action_sort_genre_popularity, + IcecastModel::SortMode_GenreByPopularity); + AddAction(group, ui_->action_sort_genre_alphabetically, + IcecastModel::SortMode_GenreAlphabetical); + AddAction(group, ui_->action_sort_station, + IcecastModel::SortMode_StationAlphabetical); // Options menu menu_->setIcon(ui_->options->icon()); @@ -52,31 +54,30 @@ IcecastFilterWidget::IcecastFilterWidget(QWidget *parent) connect(sort_mode_mapper_, SIGNAL(mapped(int)), SLOT(SortModeChanged(int))); } -void IcecastFilterWidget::AddAction( - QActionGroup* group, QAction* action, IcecastModel::SortMode mode) { +void IcecastFilterWidget::AddAction(QActionGroup* group, QAction* action, + IcecastModel::SortMode mode) { group->addAction(action); sort_mode_mapper_->setMapping(action, mode); connect(action, SIGNAL(triggered()), sort_mode_mapper_, SLOT(map())); } -IcecastFilterWidget::~IcecastFilterWidget() { - delete ui_; -} +IcecastFilterWidget::~IcecastFilterWidget() { delete ui_; } -void IcecastFilterWidget::FocusOnFilter(QKeyEvent *event) { +void IcecastFilterWidget::FocusOnFilter(QKeyEvent* event) { ui_->filter->setFocus(Qt::OtherFocusReason); QApplication::sendEvent(ui_->filter, event); } void IcecastFilterWidget::SetIcecastModel(IcecastModel* model) { model_ = model; - connect(ui_->filter, SIGNAL(textChanged(QString)), - model_, SLOT(SetFilterText(QString))); + connect(ui_->filter, SIGNAL(textChanged(QString)), model_, + SLOT(SetFilterText(QString))); // Load settings QSettings s; s.beginGroup(kSettingsGroup); - switch (s.value("sort_by", IcecastModel::SortMode_GenreByPopularity).toInt()) { + switch ( + s.value("sort_by", IcecastModel::SortMode_GenreByPopularity).toInt()) { case IcecastModel::SortMode_GenreByPopularity: ui_->action_sort_genre_popularity->trigger(); break; diff --git a/src/internet/icecastfilterwidget.h b/src/internet/icecastfilterwidget.h index f99f5076c..44a8a5296 100644 --- a/src/internet/icecastfilterwidget.h +++ b/src/internet/icecastfilterwidget.h @@ -32,7 +32,7 @@ class QSignalMapper; class IcecastFilterWidget : public QWidget { Q_OBJECT -public: + public: IcecastFilterWidget(QWidget* parent = 0); ~IcecastFilterWidget(); @@ -42,16 +42,17 @@ public: QMenu* menu() const { return menu_; } -public slots: + public slots: void FocusOnFilter(QKeyEvent* e); -private slots: + private slots: void SortModeChanged(int mode); -private: - void AddAction(QActionGroup* group, QAction* action, IcecastModel::SortMode mode); + private: + void AddAction(QActionGroup* group, QAction* action, + IcecastModel::SortMode mode); -private: + private: Ui_IcecastFilterWidget* ui_; IcecastModel* model_; QMenu* menu_; @@ -59,4 +60,4 @@ private: QSignalMapper* sort_mode_mapper_; }; -#endif // ICECASTFILTERWIDGET_H +#endif // ICECASTFILTERWIDGET_H diff --git a/src/internet/icecastitem.h b/src/internet/icecastitem.h index c09485447..60d6c6dea 100644 --- a/src/internet/icecastitem.h +++ b/src/internet/icecastitem.h @@ -22,20 +22,15 @@ #include "core/simpletreeitem.h" class IcecastItem : public SimpleTreeItem { -public: - enum Type { - Type_Root, - Type_Genre, - Type_Station, - Type_Divider, - }; + public: + enum Type { Type_Root, Type_Genre, Type_Station, Type_Divider, }; IcecastItem(SimpleTreeModel* model) - : SimpleTreeItem(Type_Root, model) {} + : SimpleTreeItem(Type_Root, model) {} IcecastItem(Type type, IcecastItem* parent = NULL) - : SimpleTreeItem(type, parent) {} + : SimpleTreeItem(type, parent) {} IcecastBackend::Station station; }; -#endif // ICECASTITEM_H +#endif // ICECASTITEM_H diff --git a/src/internet/icecastmodel.cpp b/src/internet/icecastmodel.cpp index 5954c365d..70e78b7b0 100644 --- a/src/internet/icecastmodel.cpp +++ b/src/internet/icecastmodel.cpp @@ -19,18 +19,15 @@ #include "icecastmodel.h" #include "playlist/songmimedata.h" IcecastModel::IcecastModel(IcecastBackend* backend, QObject* parent) - : SimpleTreeModel(new IcecastItem(this), parent), - backend_(backend), - sort_mode_(SortMode_GenreByPopularity), - genre_icon_(":last.fm/icon_tag.png"), - station_icon_(":last.fm/icon_radio.png") -{ + : SimpleTreeModel(new IcecastItem(this), parent), + backend_(backend), + sort_mode_(SortMode_GenreByPopularity), + genre_icon_(":last.fm/icon_tag.png"), + station_icon_(":last.fm/icon_radio.png") { root_->lazy_loaded = true; } -IcecastModel::~IcecastModel() { - delete root_; -} +IcecastModel::~IcecastModel() { delete root_; } void IcecastModel::Init() { connect(backend_, SIGNAL(DatabaseReset()), SLOT(Reset())); @@ -50,8 +47,7 @@ void IcecastModel::Reset() { } void IcecastModel::LazyPopulate(IcecastItem* parent) { - if (parent->lazy_loaded) - return; + if (parent->lazy_loaded) return; parent->lazy_loaded = true; switch (parent->type) { @@ -85,9 +81,10 @@ void IcecastModel::PopulateGenre(IcecastItem* parent, const QString& genre, QChar last_divider; IcecastBackend::StationList stations = backend_->GetStations(filter_, genre); - foreach (const IcecastBackend::Station& station, stations) { + foreach(const IcecastBackend::Station & station, stations) { QChar divider_char = DividerKey(station.name); - if (create_dividers && !divider_char.isNull() && divider_char != last_divider) { + if (create_dividers && !divider_char.isNull() && + divider_char != last_divider) { last_divider = divider_char; IcecastItem* divider = new IcecastItem(IcecastItem::Type_Divider, parent); @@ -107,7 +104,7 @@ void IcecastModel::PopulateGenre(IcecastItem* parent, const QString& genre, void IcecastModel::AddGenres(const QStringList& genres, bool create_dividers) { QChar last_divider; - foreach (const QString& genre, genres) { + foreach(const QString & genre, genres) { QChar divider_char = DividerKey(genre); if (create_dividers && divider_char != last_divider) { last_divider = divider_char; @@ -123,16 +120,13 @@ void IcecastModel::AddGenres(const QStringList& genres, bool create_dividers) { } QChar IcecastModel::DividerKey(const QString& text) { - if (text.isEmpty()) - return QChar(); + if (text.isEmpty()) return QChar(); QChar c; c = text[0]; - if (c.isDigit()) - return '0'; - if (c.isPunct() || c.isSymbol()) - return QChar(); + if (c.isDigit()) return '0'; + if (c.isPunct() || c.isSymbol()) return QChar(); if (c.decompositionTag() != QChar::NoDecomposition) return QChar(c.decomposition()[0]); @@ -140,8 +134,7 @@ QChar IcecastModel::DividerKey(const QString& text) { } QString IcecastModel::DividerDisplayText(const QChar& key) { - if (key == '0') - return "0-9"; + if (key == '0') return "0-9"; return key; } @@ -158,8 +151,10 @@ QVariant IcecastModel::data(const IcecastItem* item, int role) const { case Qt::DecorationRole: switch (item->type) { - case IcecastItem::Type_Genre: return genre_icon_; - case IcecastItem::Type_Station: return station_icon_; + case IcecastItem::Type_Genre: + return genre_icon_; + case IcecastItem::Type_Station: + return station_icon_; } break; @@ -181,16 +176,13 @@ void IcecastModel::SetSortMode(SortMode mode) { Qt::ItemFlags IcecastModel::flags(const QModelIndex& index) const { switch (IndexToItem(index)->type) { - case IcecastItem::Type_Station: - return Qt::ItemIsSelectable | - Qt::ItemIsEnabled | - Qt::ItemIsDragEnabled; - case IcecastItem::Type_Genre: - case IcecastItem::Type_Root: - case IcecastItem::Type_Divider: - default: - return Qt::ItemIsSelectable | - Qt::ItemIsEnabled; + case IcecastItem::Type_Station: + return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled; + case IcecastItem::Type_Genre: + case IcecastItem::Type_Root: + case IcecastItem::Type_Divider: + default: + return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } } @@ -199,16 +191,14 @@ QStringList IcecastModel::mimeTypes() const { } QMimeData* IcecastModel::mimeData(const QModelIndexList& indexes) const { - if (indexes.isEmpty()) - return nullptr; + if (indexes.isEmpty()) return nullptr; SongMimeData* data = new SongMimeData; QList urls; - foreach (const QModelIndex& index, indexes) { + foreach(const QModelIndex & index, indexes) { IcecastItem* item = IndexToItem(index); - if (!item || item->type != IcecastItem::Type_Station) - continue; + if (!item || item->type != IcecastItem::Type_Station) continue; data->songs << item->station.ToSong(); urls << item->station.url; @@ -227,8 +217,7 @@ QMimeData* IcecastModel::mimeData(const QModelIndexList& indexes) const { Song IcecastModel::GetSong(const QModelIndex& index) const { IcecastItem* item = IndexToItem(index); - if (!item || item->type != IcecastItem::Type_Station) - return Song(); + if (!item || item->type != IcecastItem::Type_Station) return Song(); return item->station.ToSong(); } diff --git a/src/internet/icecastmodel.h b/src/internet/icecastmodel.h index 00297426e..e25fb94df 100644 --- a/src/internet/icecastmodel.h +++ b/src/internet/icecastmodel.h @@ -29,7 +29,7 @@ class IcecastBackend; class IcecastModel : public SimpleTreeModel { Q_OBJECT -public: + public: IcecastModel(IcecastBackend* backend, QObject* parent = 0); ~IcecastModel(); @@ -40,39 +40,38 @@ public: SortMode_StationAlphabetical = 2, }; - enum Role { - Role_IsDivider = LibraryModel::Role_IsDivider, - }; + enum Role { Role_IsDivider = LibraryModel::Role_IsDivider, }; IcecastBackend* backend() const { return backend_; } Song GetSong(const QModelIndex& index) const; // QAbstractItemModel - QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; Qt::ItemFlags flags(const QModelIndex& index) const; QStringList mimeTypes() const; QMimeData* mimeData(const QModelIndexList& indexes) const; -public slots: + public slots: void Init(); void Reset(); void SetFilterText(const QString& filter); void SetSortMode(SortMode mode); -protected: + protected: void LazyPopulate(IcecastItem* parent); -private: + private: QVariant data(const IcecastItem* item, int role) const; - void PopulateGenre(IcecastItem* parent, const QString& genre, bool create_dividers); + void PopulateGenre(IcecastItem* parent, const QString& genre, + bool create_dividers); void AddGenres(const QStringList& genres, bool create_dividers); static QChar DividerKey(const QString& text); static QString DividerDisplayText(const QChar& key); -private: + private: IcecastBackend* backend_; QString filter_; @@ -82,4 +81,4 @@ private: QIcon station_icon_; }; -#endif // ICECASTMODEL_H +#endif // ICECASTMODEL_H diff --git a/src/internet/icecastservice.cpp b/src/internet/icecastservice.cpp index 50ca8445b..d5a76f55b 100644 --- a/src/internet/icecastservice.cpp +++ b/src/internet/icecastservice.cpp @@ -44,9 +44,9 @@ using std::sort; using std::unique; - const char* IcecastService::kServiceName = "Icecast"; -const char* IcecastService::kDirectoryUrl = "http://data.clementine-player.org/icecast-directory"; +const char* IcecastService::kDirectoryUrl = + "http://data.clementine-player.org/icecast-directory"; const char* IcecastService::kHomepage = "http://dir.xiph.org/"; IcecastService::IcecastService(Application* app, InternetModel* parent) @@ -56,8 +56,7 @@ IcecastService::IcecastService(Application* app, InternetModel* parent) backend_(nullptr), model_(nullptr), filter_(new IcecastFilterWidget(0)), - load_directory_task_id_(0) -{ + load_directory_task_id_(0) { backend_ = new IcecastBackend; backend_->moveToThread(app_->database()->thread()); backend_->Init(app_->database()); @@ -65,11 +64,11 @@ IcecastService::IcecastService(Application* app, InternetModel* parent) model_ = new IcecastModel(backend_, this); filter_->SetIcecastModel(model_); - app_->global_search()->AddProvider(new IcecastSearchProvider(backend_, app_, this)); + app_->global_search()->AddProvider( + new IcecastSearchProvider(backend_, app_, this)); } -IcecastService::~IcecastService() { -} +IcecastService::~IcecastService() {} QStandardItem* IcecastService::CreateRootItem() { root_ = new QStandardItem(QIcon(":last.fm/icon_radio.png"), kServiceName); @@ -81,7 +80,8 @@ void IcecastService::LazyPopulate(QStandardItem* item) { switch (item->data(InternetModel::Role_Type).toInt()) { case InternetModel::Type_Service: model_->Init(); - model()->merged_model()->AddSubModel(model()->indexFromItem(item), model_); + model()->merged_model()->AddSubModel(model()->indexFromItem(item), + model_); if (backend_->IsEmpty()) { LoadDirectory(); @@ -97,8 +97,8 @@ void IcecastService::LoadDirectory() { RequestDirectory(QUrl(kDirectoryUrl)); if (!load_directory_task_id_) { - load_directory_task_id_ = app_->task_manager()->StartTask( - tr("Downloading Icecast directory")); + load_directory_task_id_ = + app_->task_manager()->StartTask(tr("Downloading Icecast directory")); } } @@ -116,7 +116,8 @@ void IcecastService::DownloadDirectoryFinished(QNetworkReply* reply) { if (reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid()) { // Discard the old reply and follow the redirect reply->deleteLater(); - RequestDirectory(reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl()); + RequestDirectory( + reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl()); return; } @@ -125,19 +126,17 @@ void IcecastService::DownloadDirectoryFinished(QNetworkReply* reply) { QFutureWatcher* watcher = new QFutureWatcher(this); watcher->setFuture(future); NewClosure(watcher, SIGNAL(finished()), this, - SLOT(ParseDirectoryFinished(QFuture)), - future); + SLOT(ParseDirectoryFinished(QFuture)), + future); connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater())); } namespace { template struct GenreSorter { - GenreSorter(const QMultiHash& genres) - : genres_(genres) { - } + GenreSorter(const QMultiHash& genres) : genres_(genres) {} - bool operator() (const QString& a, const QString& b) const { + bool operator()(const QString& a, const QString& b) const { return genres_.count(a) > genres_.count(b); } @@ -147,31 +146,30 @@ struct GenreSorter { template struct StationSorter { - bool operator() (const T& a, const T& b) const { + bool operator()(const T& a, const T& b) const { return a.name.compare(b.name, Qt::CaseInsensitive) < 0; } }; template struct StationSorter { - bool operator() (const T* a, const T* b) const { + bool operator()(const T* a, const T* b) const { return a->name.compare(b->name, Qt::CaseInsensitive) < 0; } }; template struct StationEquality { - bool operator() (T a, T b) const { - return a.name == b.name; - } + bool operator()(T a, T b) const { return a.name == b.name; } }; QStringList FilterGenres(const QStringList& genres) { QStringList ret; - foreach (const QString& genre, genres) { + foreach(const QString & genre, genres) { if (genre.length() < 2) continue; if (genre.contains("ÃÂ")) continue; // Broken unicode. - if (genre.contains(QRegExp("^#x[0-9a-f][0-9a-f]"))) continue; // Broken XML entities. + if (genre.contains(QRegExp("^#x[0-9a-f][0-9a-f]"))) + continue; // Broken XML entities. // Convert 80 -> 80s. if (genre.contains(QRegExp("^[0-9]0$"))) { @@ -186,23 +184,25 @@ QStringList FilterGenres(const QStringList& genres) { } return ret; } - } void IcecastService::ParseDirectoryFinished( QFuture future) { IcecastBackend::StationList all_stations = future.result(); - sort(all_stations.begin(), all_stations.end(), StationSorter()); - // Remove duplicates by name. These tend to be multiple URLs for the same station. + sort(all_stations.begin(), all_stations.end(), + StationSorter()); + // Remove duplicates by name. These tend to be multiple URLs for the same + // station. IcecastBackend::StationList::iterator it = - unique(all_stations.begin(), all_stations.end(), StationEquality()); + unique(all_stations.begin(), all_stations.end(), + StationEquality()); all_stations.erase(it, all_stations.end()); // Cluster stations by genre. QMultiHash genres; // Add stations. - for (int i=0 ; i genre_set = genres.keys().toSet(); // Merge genres with only 1 or 2 stations into "Other". - foreach (const QString& genre, genre_set) { + foreach(const QString & genre, genre_set) { if (genres.count(genre) < 3) { const QList& small_genre = genres.values(genre); - foreach (IcecastBackend::Station* s, small_genre) { - s->genre = "Other"; - } + foreach(IcecastBackend::Station * s, small_genre) { s->genre = "Other"; } } } @@ -225,7 +223,8 @@ void IcecastService::ParseDirectoryFinished( load_directory_task_id_ = 0; } -IcecastBackend::StationList IcecastService::ParseDirectory(QIODevice* device) const { +IcecastBackend::StationList IcecastService::ParseDirectory(QIODevice* device) + const { QXmlStreamReader reader(device); IcecastBackend::StationList stations; while (!reader.atEnd()) { @@ -239,25 +238,27 @@ IcecastBackend::StationList IcecastService::ParseDirectory(QIODevice* device) co return stations; } -IcecastBackend::Station IcecastService::ReadStation(QXmlStreamReader* reader) const { +IcecastBackend::Station IcecastService::ReadStation(QXmlStreamReader* reader) + const { IcecastBackend::Station station; while (!reader->atEnd()) { reader->readNext(); - if (reader->tokenType() == QXmlStreamReader::EndElement) - break; + if (reader->tokenType() == QXmlStreamReader::EndElement) break; if (reader->tokenType() == QXmlStreamReader::StartElement) { QStringRef name = reader->name(); - QString value = reader->readElementText(QXmlStreamReader::SkipChildElements); + QString value = + reader->readElementText(QXmlStreamReader::SkipChildElements); if (name == "server_name") station.name = value; - if (name == "listen_url") station.url = QUrl(value); + if (name == "listen_url") station.url = QUrl(value); if (name == "server_type") station.mime_type = value; - if (name == "bitrate") station.bitrate = value.toInt(); - if (name == "channels") station.channels = value.toInt(); - if (name == "samplerate") station.samplerate = value.toInt(); - if (name == "genre") station.genre = - FilterGenres(value.split(' ', QString::SkipEmptyParts))[0]; + if (name == "bitrate") station.bitrate = value.toInt(); + if (name == "channels") station.channels = value.toInt(); + if (name == "samplerate") station.samplerate = value.toInt(); + if (name == "genre") + station.genre = + FilterGenres(value.split(' ', QString::SkipEmptyParts))[0]; } } @@ -269,9 +270,7 @@ IcecastBackend::Station IcecastService::ReadStation(QXmlStreamReader* reader) co return station; } -QWidget* IcecastService::HeaderWidget() const { - return filter_; -} +QWidget* IcecastService::HeaderWidget() const { return filter_; } void IcecastService::ShowContextMenu(const QPoint& global_pos) { EnsureMenuCreated(); @@ -287,19 +286,20 @@ void IcecastService::ShowContextMenu(const QPoint& global_pos) { } void IcecastService::EnsureMenuCreated() { - if (context_menu_) - return; + if (context_menu_) return; context_menu_ = new QMenu; context_menu_->addActions(GetPlaylistActions()); - context_menu_->addAction(IconLoader::Load("download"), tr("Open %1 in browser").arg("dir.xiph.org"), this, SLOT(Homepage())); - context_menu_->addAction(IconLoader::Load("view-refresh"), tr("Refresh station list"), this, SLOT(LoadDirectory())); + context_menu_->addAction(IconLoader::Load("download"), + tr("Open %1 in browser").arg("dir.xiph.org"), this, + SLOT(Homepage())); + context_menu_->addAction(IconLoader::Load("view-refresh"), + tr("Refresh station list"), this, + SLOT(LoadDirectory())); context_menu_->addSeparator(); context_menu_->addMenu(filter_->menu()); } -void IcecastService::Homepage() { - QDesktopServices::openUrl(QUrl(kHomepage)); -} +void IcecastService::Homepage() { QDesktopServices::openUrl(QUrl(kHomepage)); } diff --git a/src/internet/icecastservice.h b/src/internet/icecastservice.h index 36e054da4..52c549597 100644 --- a/src/internet/icecastservice.h +++ b/src/internet/icecastservice.h @@ -33,7 +33,7 @@ class QNetworkReply; class IcecastService : public InternetService { Q_OBJECT -public: + public: IcecastService(Application* app, InternetModel* parent); ~IcecastService(); @@ -41,10 +41,7 @@ public: static const char* kDirectoryUrl; static const char* kHomepage; - enum ItemType { - Type_Stream = 3000, - Type_Genre, - }; + enum ItemType { Type_Stream = 3000, Type_Genre, }; QStandardItem* CreateRootItem(); void LazyPopulate(QStandardItem* item); @@ -53,14 +50,13 @@ public: QWidget* HeaderWidget() const; -private slots: + private slots: void LoadDirectory(); void Homepage(); void DownloadDirectoryFinished(QNetworkReply* reply); - void ParseDirectoryFinished( - QFuture future); + void ParseDirectoryFinished(QFuture future); -private: + private: void RequestDirectory(const QUrl& url); void EnsureMenuCreated(); IcecastBackend::StationList ParseDirectory(QIODevice* device) const; diff --git a/src/internet/internetmimedata.h b/src/internet/internetmimedata.h index f6d089f3f..3e0513a49 100644 --- a/src/internet/internetmimedata.h +++ b/src/internet/internetmimedata.h @@ -28,12 +28,11 @@ class InternetModel; class InternetMimeData : public MimeData { Q_OBJECT -public: - InternetMimeData(const InternetModel* _model) - : model(_model) {} + public: + InternetMimeData(const InternetModel* _model) : model(_model) {} const InternetModel* model; QModelIndexList indexes; }; -#endif // INTERNETMIMEDATA_H +#endif // INTERNETMIMEDATA_H diff --git a/src/internet/internetmodel.cpp b/src/internet/internetmodel.cpp index 9b01a7dfc..93a59664e 100644 --- a/src/internet/internetmodel.cpp +++ b/src/internet/internetmodel.cpp @@ -39,22 +39,22 @@ #include "smartplaylists/generatormimedata.h" #ifdef HAVE_LIBLASTFM - #include "lastfmservice.h" +#include "lastfmservice.h" #endif #ifdef HAVE_GOOGLE_DRIVE - #include "googledriveservice.h" +#include "googledriveservice.h" #endif #ifdef HAVE_UBUNTU_ONE - #include "ubuntuoneservice.h" +#include "ubuntuoneservice.h" #endif #ifdef HAVE_DROPBOX - #include "dropboxservice.h" +#include "dropboxservice.h" #endif #ifdef HAVE_SKYDRIVE - #include "skydriveservice.h" +#include "skydriveservice.h" #endif #ifdef HAVE_BOX - #include "boxservice.h" +#include "boxservice.h" #endif using smart_playlists::Generator; @@ -64,10 +64,9 @@ using smart_playlists::GeneratorPtr; QMap* InternetModel::sServices = nullptr; InternetModel::InternetModel(Application* app, QObject* parent) - : QStandardItemModel(parent), - app_(app), - merged_model_(new MergedProxyModel(this)) -{ + : QStandardItemModel(parent), + app_(app), + merged_model_(new MergedProxyModel(this)) { if (!sServices) { sServices = new QMap; } @@ -110,10 +109,11 @@ InternetModel::InternetModel(Application* app, QObject* parent) #endif } -void InternetModel::AddService(InternetService *service) { +void InternetModel::AddService(InternetService* service) { QStandardItem* root = service->CreateRootItem(); if (!root) { - qLog(Warning) << "Internet service" << service->name() << "did not return a root item"; + qLog(Warning) << "Internet service" << service->name() + << "did not return a root item"; return; } @@ -125,22 +125,25 @@ void InternetModel::AddService(InternetService *service) { sServices->insert(service->name(), service); connect(service, SIGNAL(StreamError(QString)), SIGNAL(StreamError(QString))); - connect(service, SIGNAL(StreamMetadataFound(QUrl,Song)), SIGNAL(StreamMetadataFound(QUrl,Song))); - connect(service, SIGNAL(AddToPlaylistSignal(QMimeData*)), SIGNAL(AddToPlaylist(QMimeData*))); - connect(service, SIGNAL(ScrollToIndex(QModelIndex)), SIGNAL(ScrollToIndex(QModelIndex))); + connect(service, SIGNAL(StreamMetadataFound(QUrl, Song)), + SIGNAL(StreamMetadataFound(QUrl, Song))); + connect(service, SIGNAL(AddToPlaylistSignal(QMimeData*)), + SIGNAL(AddToPlaylist(QMimeData*))); + connect(service, SIGNAL(ScrollToIndex(QModelIndex)), + SIGNAL(ScrollToIndex(QModelIndex))); connect(service, SIGNAL(destroyed()), SLOT(ServiceDeleted())); service->ReloadSettings(); } void InternetModel::RemoveService(InternetService* service) { - if (!sServices->contains(service->name())) - return; + if (!sServices->contains(service->name())) return; // Find and remove the root item that this service created - for (int i=0 ; irowCount() ; ++i) { + for (int i = 0; i < invisibleRootItem()->rowCount(); ++i) { QStandardItem* item = invisibleRootItem()->child(i); - if (!item || item->data(Role_Service).value() == service) { + if (!item || + item->data(Role_Service).value() == service) { invisibleRootItem()->removeRow(i); break; } @@ -155,24 +158,25 @@ void InternetModel::RemoveService(InternetService* service) { void InternetModel::ServiceDeleted() { InternetService* service = qobject_cast(sender()); - if (service) - RemoveService(service); + if (service) RemoveService(service); } InternetService* InternetModel::ServiceByName(const QString& name) { - if (sServices->contains(name)) - return sServices->value(name); + if (sServices->contains(name)) return sServices->value(name); return nullptr; } -InternetService* InternetModel::ServiceForItem(const QStandardItem* item) const { +InternetService* InternetModel::ServiceForItem(const QStandardItem* item) + const { return ServiceForIndex(indexFromItem(item)); } -InternetService* InternetModel::ServiceForIndex(const QModelIndex& index) const { +InternetService* InternetModel::ServiceForIndex(const QModelIndex& index) + const { QModelIndex current_index = index; while (current_index.isValid()) { - InternetService* service = current_index.data(Role_Service).value(); + InternetService* service = + current_index.data(Role_Service).value(); if (service) { return service; } @@ -182,9 +186,8 @@ InternetService* InternetModel::ServiceForIndex(const QModelIndex& index) const } Qt::ItemFlags InternetModel::flags(const QModelIndex& index) const { - Qt::ItemFlags flags = Qt::ItemIsSelectable | - Qt::ItemIsEnabled | - Qt::ItemIsDropEnabled; + Qt::ItemFlags flags = + Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled; if (IsPlayable(index)) { flags |= Qt::ItemIsDragEnabled; } @@ -192,8 +195,7 @@ Qt::ItemFlags InternetModel::flags(const QModelIndex& index) const { } bool InternetModel::hasChildren(const QModelIndex& parent) const { - if (parent.data(Role_CanLazyLoad).toBool()) - return true; + if (parent.data(Role_CanLazyLoad).toBool()) return true; return QStandardItemModel::hasChildren(parent); } @@ -212,8 +214,7 @@ int InternetModel::rowCount(const QModelIndex& parent) const { bool InternetModel::IsPlayable(const QModelIndex& index) const { QVariant behaviour = index.data(Role_PlayBehaviour); - if (!behaviour.isValid()) - return false; + if (!behaviour.isValid()) return false; PlayBehaviour pb = PlayBehaviour(behaviour.toInt()); return (pb == PlayBehaviour_MultipleItems || pb == PlayBehaviour_SingleItem || @@ -226,19 +227,18 @@ QStringList InternetModel::mimeTypes() const { QMimeData* InternetModel::mimeData(const QModelIndexList& indexes) const { // Special case for when the user double clicked on a special item. - if (indexes.count() == 1 && - indexes[0].data(Role_PlayBehaviour).toInt() == - PlayBehaviour_DoubleClickAction) { - InternetModel::ServiceForIndex(indexes[0])->ItemDoubleClicked(itemFromIndex(indexes[0])); + if (indexes.count() == 1 && indexes[0].data(Role_PlayBehaviour).toInt() == + PlayBehaviour_DoubleClickAction) { + InternetModel::ServiceForIndex(indexes[0]) + ->ItemDoubleClicked(itemFromIndex(indexes[0])); return nullptr; } if (indexes.count() == 1 && indexes[0].data(Role_Type).toInt() == Type_SmartPlaylist) { - GeneratorPtr generator = - InternetModel::ServiceForIndex(indexes[0])->CreateGenerator(itemFromIndex(indexes[0])); - if (!generator) - return nullptr; + GeneratorPtr generator = InternetModel::ServiceForIndex(indexes[0]) + ->CreateGenerator(itemFromIndex(indexes[0])); + if (!generator) return nullptr; GeneratorMimeData* data = new GeneratorMimeData(generator); data->setData(LibraryModel::kSmartPlaylistsMimeType, QByteArray()); data->name_for_new_playlist_ = this->data(indexes.first()).toString(); @@ -249,9 +249,8 @@ QMimeData* InternetModel::mimeData(const QModelIndexList& indexes) const { QModelIndexList new_indexes; QModelIndex last_valid_index; - foreach (const QModelIndex& index, indexes) { - if (!IsPlayable(index)) - continue; + foreach(const QModelIndex & index, indexes) { + if (!IsPlayable(index)) continue; last_valid_index = index; if (index.data(Role_PlayBehaviour).toInt() == PlayBehaviour_MultipleItems) { @@ -270,18 +269,20 @@ QMimeData* InternetModel::mimeData(const QModelIndexList& indexes) const { } } - if (urls.isEmpty()) - return nullptr; + if (urls.isEmpty()) return nullptr; InternetMimeData* data = new InternetMimeData(this); data->setUrls(urls); data->indexes = new_indexes; - data->name_for_new_playlist_ = InternetModel::ServiceForIndex(last_valid_index)->name(); + data->name_for_new_playlist_ = + InternetModel::ServiceForIndex(last_valid_index)->name(); return data; } -bool InternetModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) { +bool InternetModel::dropMimeData(const QMimeData* data, Qt::DropAction action, + int row, int column, + const QModelIndex& parent) { if (action == Qt::IgnoreAction) { return false; } @@ -292,23 +293,22 @@ bool InternetModel::dropMimeData(const QMimeData* data, Qt::DropAction action, i return true; } -void InternetModel::ShowContextMenu(const QModelIndexList& selected_merged_model_indexes, - const QModelIndex& current_merged_model_index, - const QPoint& global_pos) { +void InternetModel::ShowContextMenu( + const QModelIndexList& selected_merged_model_indexes, + const QModelIndex& current_merged_model_index, const QPoint& global_pos) { current_index_ = merged_model_->mapToSource(current_merged_model_index); selected_indexes_.clear(); - foreach (const QModelIndex& index, selected_merged_model_indexes) { + foreach(const QModelIndex & index, selected_merged_model_indexes) { selected_indexes_ << merged_model_->mapToSource(index); } InternetService* service = ServiceForIndex(current_merged_model_index); - if (service) - service->ShowContextMenu(global_pos); + if (service) service->ShowContextMenu(global_pos); } void InternetModel::ReloadSettings() { - foreach (InternetService* service, sServices->values()) { + foreach(InternetService * service, sServices->values()) { service->ReloadSettings(); } } diff --git a/src/internet/internetmodel.h b/src/internet/internetmodel.h index e1f2b73b3..14433c1d1 100644 --- a/src/internet/internetmodel.h +++ b/src/internet/internetmodel.h @@ -35,13 +35,13 @@ class SettingsDialog; class TaskManager; #ifdef HAVE_LIBLASTFM - class LastFMService; +class LastFMService; #endif class InternetModel : public QStandardItemModel { Q_OBJECT -public: + public: InternetModel(Application* app, QObject* parent = 0); enum Role { @@ -77,9 +77,7 @@ public: // Setting this to true means that the item can be changed by user action // (e.g. changing remote playlists) Role_CanBeModified, - RoleCount, - Role_IsDivider = LibraryModel::Role_IsDivider, }; @@ -88,7 +86,6 @@ public: Type_Track, Type_UserPlaylist, Type_SmartPlaylist, - TypeCount }; @@ -120,7 +117,7 @@ public: // Needs to be static for InternetPlaylistItem::restore static InternetService* ServiceByName(const QString& name); - template + template static T* Service() { return static_cast(ServiceByName(T::kServiceName)); } @@ -143,7 +140,8 @@ public: Qt::ItemFlags flags(const QModelIndex& index) const; QStringList mimeTypes() const; QMimeData* mimeData(const QModelIndexList& indexes) const; - bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); + bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, + int column, const QModelIndex& parent); bool hasChildren(const QModelIndex& parent) const; int rowCount(const QModelIndex& parent) const; @@ -165,10 +163,10 @@ signals: void AddToPlaylist(QMimeData* data); void ScrollToIndex(const QModelIndex& index); -private slots: + private slots: void ServiceDeleted(); -private: + private: static QMap* sServices; Application* app_; @@ -180,4 +178,4 @@ private: QModelIndex current_index_; }; -#endif // INTERNETMODEL_H +#endif // INTERNETMODEL_H diff --git a/src/internet/internetplaylistitem.cpp b/src/internet/internetplaylistitem.cpp index 5db1781cf..803a0b029 100644 --- a/src/internet/internetplaylistitem.cpp +++ b/src/internet/internetplaylistitem.cpp @@ -27,23 +27,21 @@ #include InternetPlaylistItem::InternetPlaylistItem(const QString& type) - : PlaylistItem(type), - set_service_icon_(false) -{ -} + : PlaylistItem(type), set_service_icon_(false) {} -InternetPlaylistItem::InternetPlaylistItem(InternetService* service, const Song& metadata) - : PlaylistItem("Internet"), - service_name_(service->name()), - set_service_icon_(false), - metadata_(metadata) -{ +InternetPlaylistItem::InternetPlaylistItem(InternetService* service, + const Song& metadata) + : PlaylistItem("Internet"), + service_name_(service->name()), + set_service_icon_(false), + metadata_(metadata) { InitMetadata(); } bool InternetPlaylistItem::InitFromQuery(const SqlRow& query) { // The song tables gets joined first, plus one each for the song ROWIDs - const int row = (Song::kColumns.count() + 1) * PlaylistBackend::kSongTableJoins; + const int row = + (Song::kColumns.count() + 1) * PlaylistBackend::kSongTableJoins; service_name_ = query.value(row + 1).toString(); @@ -70,8 +68,10 @@ InternetService* InternetPlaylistItem::service() const { QVariant InternetPlaylistItem::DatabaseValue(DatabaseColumn column) const { switch (column) { - case Column_InternetService: return service_name_; - default: return PlaylistItem::DatabaseValue(column); + case Column_InternetService: + return service_name_; + default: + return PlaylistItem::DatabaseValue(column); } } @@ -88,25 +88,20 @@ Song InternetPlaylistItem::Metadata() const { service(); } - if (HasTemporaryMetadata()) - return temp_metadata_; + if (HasTemporaryMetadata()) return temp_metadata_; return metadata_; } -QUrl InternetPlaylistItem::Url() const { - return metadata_.url(); -} +QUrl InternetPlaylistItem::Url() const { return metadata_.url(); } PlaylistItem::Options InternetPlaylistItem::options() const { InternetService* s = service(); - if (!s) - return Default; + if (!s) return Default; return s->playlistitem_options(); } QList InternetPlaylistItem::actions() { InternetService* s = service(); - if (!s) - return QList(); + if (!s) return QList(); return s->playlistitem_actions(metadata_); } diff --git a/src/internet/internetplaylistitem.h b/src/internet/internetplaylistitem.h index df14e1659..3f636397c 100644 --- a/src/internet/internetplaylistitem.h +++ b/src/internet/internetplaylistitem.h @@ -55,4 +55,4 @@ class InternetPlaylistItem : public PlaylistItem { Song metadata_; }; -#endif // INTERNETPLAYLISTITEM_H +#endif // INTERNETPLAYLISTITEM_H diff --git a/src/internet/internetservice.cpp b/src/internet/internetservice.cpp index 31d5bfd49..ee033e651 100644 --- a/src/internet/internetservice.cpp +++ b/src/internet/internetservice.cpp @@ -27,66 +27,68 @@ InternetService::InternetService(const QString& name, Application* app, InternetModel* model, QObject* parent) - : QObject(parent), - app_(app), - model_(model), - name_(name), - append_to_playlist_(nullptr), - replace_playlist_(nullptr), - open_in_new_playlist_(nullptr), - separator_(nullptr) -{ -} + : QObject(parent), + app_(app), + model_(model), + name_(name), + append_to_playlist_(nullptr), + replace_playlist_(nullptr), + open_in_new_playlist_(nullptr), + separator_(nullptr) {} QList InternetService::GetPlaylistActions() { - if(!separator_) { + if (!separator_) { separator_ = new QAction(this); separator_->setSeparator(true); } return QList() << GetAppendToPlaylistAction() << GetReplacePlaylistAction() - << GetOpenInNewPlaylistAction() - << separator_; + << GetOpenInNewPlaylistAction() << separator_; } QAction* InternetService::GetAppendToPlaylistAction() { - if(!append_to_playlist_) { + if (!append_to_playlist_) { append_to_playlist_ = new QAction(IconLoader::Load("media-playback-start"), tr("Append to current playlist"), this); - connect(append_to_playlist_, SIGNAL(triggered()), this, SLOT(AppendToPlaylist())); + connect(append_to_playlist_, SIGNAL(triggered()), this, + SLOT(AppendToPlaylist())); } return append_to_playlist_; } QAction* InternetService::GetReplacePlaylistAction() { - if(!replace_playlist_) { + if (!replace_playlist_) { replace_playlist_ = new QAction(IconLoader::Load("media-playback-start"), tr("Replace current playlist"), this); - connect(replace_playlist_, SIGNAL(triggered()), this, SLOT(ReplacePlaylist())); + connect(replace_playlist_, SIGNAL(triggered()), this, + SLOT(ReplacePlaylist())); } return replace_playlist_; } QAction* InternetService::GetOpenInNewPlaylistAction() { - if(!open_in_new_playlist_) { + if (!open_in_new_playlist_) { open_in_new_playlist_ = new QAction(IconLoader::Load("document-new"), tr("Open in new playlist"), this); - connect(open_in_new_playlist_, SIGNAL(triggered()), this, SLOT(OpenInNewPlaylist())); + connect(open_in_new_playlist_, SIGNAL(triggered()), this, + SLOT(OpenInNewPlaylist())); } return open_in_new_playlist_; } -void InternetService::AddItemToPlaylist(const QModelIndex& index, AddMode add_mode) { +void InternetService::AddItemToPlaylist(const QModelIndex& index, + AddMode add_mode) { AddItemsToPlaylist(QModelIndexList() << index, add_mode); } -void InternetService::AddItemsToPlaylist(const QModelIndexList& indexes, AddMode add_mode) { +void InternetService::AddItemsToPlaylist(const QModelIndexList& indexes, + AddMode add_mode) { QMimeData* data = model()->merged_model()->mimeData( - model()->merged_model()->mapFromSource(indexes)); + model()->merged_model()->mapFromSource(indexes)); if (MimeData* mime_data = qobject_cast(data)) { mime_data->clear_first_ = add_mode == AddMode_Replace; mime_data->open_in_new_playlist_ = add_mode == AddMode_OpenInNew; @@ -107,12 +109,12 @@ void InternetService::OpenInNewPlaylist() { } QStandardItem* InternetService::CreateSongItem(const Song& song) { - QStandardItem* item = new QStandardItem(song.PrettyTitleWithArtist()); - item->setData(InternetModel::Type_Track, InternetModel::Role_Type); - item->setData(QVariant::fromValue(song), InternetModel::Role_SongMetadata); - item->setData(InternetModel::PlayBehaviour_SingleItem, InternetModel::Role_PlayBehaviour); - item->setData(song.url(), InternetModel::Role_Url); + QStandardItem* item = new QStandardItem(song.PrettyTitleWithArtist()); + item->setData(InternetModel::Type_Track, InternetModel::Role_Type); + item->setData(QVariant::fromValue(song), InternetModel::Role_SongMetadata); + item->setData(InternetModel::PlayBehaviour_SingleItem, + InternetModel::Role_PlayBehaviour); + item->setData(song.url(), InternetModel::Role_Url); - return item; + return item; } - diff --git a/src/internet/internetservice.h b/src/internet/internetservice.h index 482e472b3..3aeb355b2 100644 --- a/src/internet/internetservice.h +++ b/src/internet/internetservice.h @@ -36,7 +36,7 @@ class QStandardItem; class InternetService : public QObject { Q_OBJECT -public: + public: // Constructs a new internet service with the given name and model. The name // should be user-friendly (like 'DigitallyImported' or 'Last.fm'). InternetService(const QString& name, Application* app, InternetModel* model, @@ -52,13 +52,20 @@ public: virtual void ShowContextMenu(const QPoint& global_pos) {} virtual void ItemDoubleClicked(QStandardItem* item) {} // Create a generator for smart playlists - virtual smart_playlists::GeneratorPtr CreateGenerator(QStandardItem* item) { return smart_playlists::GeneratorPtr(); } + virtual smart_playlists::GeneratorPtr CreateGenerator(QStandardItem* item) { + return smart_playlists::GeneratorPtr(); + } // Give the service a chance to do a custom action when data is dropped on it virtual void DropMimeData(const QMimeData* data, const QModelIndex& index) {} - virtual PlaylistItem::Options playlistitem_options() const { return PlaylistItem::Default; } - // Redefine this function to add service' specific actions to the playlist item - virtual QList playlistitem_actions(const Song& song) { return QList(); } + virtual PlaylistItem::Options playlistitem_options() const { + return PlaylistItem::Default; + } + // Redefine this function to add service' specific actions to the playlist + // item + virtual QList playlistitem_actions(const Song& song) { + return QList(); + } virtual QWidget* HeaderWidget() const { return NULL; } @@ -73,15 +80,15 @@ signals: void AddToPlaylistSignal(QMimeData* data); void ScrollToIndex(const QModelIndex& index); -public slots: + public slots: virtual void ShowConfig() {} -private slots: + private slots: void AppendToPlaylist(); void ReplacePlaylist(); void OpenInNewPlaylist(); -protected: + protected: // Returns all the playlist insertion related QActions (see below). QList GetPlaylistActions(); @@ -111,10 +118,10 @@ protected: // Set some common properties (type=track, url, etc.) QStandardItem* CreateSongItem(const Song& song); -protected: + protected: Application* app_; -private: + private: InternetModel* model_; QString name_; @@ -126,4 +133,4 @@ private: Q_DECLARE_METATYPE(InternetService*); -#endif // INTERNETSERVICE_H +#endif // INTERNETSERVICE_H diff --git a/src/internet/internetsongmimedata.h b/src/internet/internetsongmimedata.h index 9b6f69ad0..07e86d237 100644 --- a/src/internet/internetsongmimedata.h +++ b/src/internet/internetsongmimedata.h @@ -26,12 +26,11 @@ class InternetService; class InternetSongMimeData : public MimeData { Q_OBJECT -public: - InternetSongMimeData(InternetService* _service) - : service(_service) {} + public: + InternetSongMimeData(InternetService* _service) : service(_service) {} InternetService* service; SongList songs; }; -#endif // INTERNETSONGMIMEDATA_H +#endif // INTERNETSONGMIMEDATA_H diff --git a/src/internet/internetview.cpp b/src/internet/internetview.cpp index 9a8c94b49..4b14dcf5e 100644 --- a/src/internet/internetview.cpp +++ b/src/internet/internetview.cpp @@ -22,9 +22,7 @@ #include -InternetView::InternetView(QWidget *parent) - : AutoExpandingTreeView(parent) -{ +InternetView::InternetView(QWidget* parent) : AutoExpandingTreeView(parent) { setItemDelegate(new LibraryItemDelegate(this)); SetExpandOnReset(false); setAttribute(Qt::WA_MacShowFocusRect, false); @@ -33,26 +31,27 @@ InternetView::InternetView(QWidget *parent) void InternetView::contextMenuEvent(QContextMenuEvent* e) { QModelIndex index = indexAt(e->pos()); - if (!index.isValid()) - return; + if (!index.isValid()) return; MergedProxyModel* merged_model = static_cast(model()); - InternetModel* internet_model = static_cast(merged_model->sourceModel()); + InternetModel* internet_model = + static_cast(merged_model->sourceModel()); internet_model->ShowContextMenu(selectionModel()->selectedRows(), index, e->globalPos()); } -void InternetView::currentChanged(const QModelIndex ¤t, const QModelIndex&) { +void InternetView::currentChanged(const QModelIndex& current, + const QModelIndex&) { emit CurrentIndexChanged(current); } -void InternetView::setModel(QAbstractItemModel *model) { +void InternetView::setModel(QAbstractItemModel* model) { AutoExpandingTreeView::setModel(model); if (MergedProxyModel* merged_model = qobject_cast(model)) { connect(merged_model, - SIGNAL(SubModelReset(QModelIndex,QAbstractItemModel*)), + SIGNAL(SubModelReset(QModelIndex, QAbstractItemModel*)), SLOT(RecursivelyExpand(QModelIndex))); } } diff --git a/src/internet/internetview.h b/src/internet/internetview.h index 334959401..5188deab3 100644 --- a/src/internet/internetview.h +++ b/src/internet/internetview.h @@ -30,11 +30,11 @@ class InternetView : public AutoExpandingTreeView { void contextMenuEvent(QContextMenuEvent* e); // QTreeView - void currentChanged(const QModelIndex ¤t, const QModelIndex &previous); - void setModel(QAbstractItemModel *model); + void currentChanged(const QModelIndex& current, const QModelIndex& previous); + void setModel(QAbstractItemModel* model); - signals: +signals: void CurrentIndexChanged(const QModelIndex& index); }; -#endif // INTERNETVIEW_H +#endif // INTERNETVIEW_H diff --git a/src/internet/internetviewcontainer.cpp b/src/internet/internetviewcontainer.cpp index 1a731bbbb..d632d6974 100644 --- a/src/internet/internetviewcontainer.cpp +++ b/src/internet/internetviewcontainer.cpp @@ -29,27 +29,25 @@ const int InternetViewContainer::kAnimationDuration = 500; -InternetViewContainer::InternetViewContainer(QWidget *parent) - : QWidget(parent), - ui_(new Ui_InternetViewContainer), - app_(nullptr), - current_service_(nullptr), - current_header_(nullptr) -{ +InternetViewContainer::InternetViewContainer(QWidget* parent) + : QWidget(parent), + ui_(new Ui_InternetViewContainer), + app_(nullptr), + current_service_(nullptr), + current_header_(nullptr) { ui_->setupUi(this); - connect(ui_->tree, SIGNAL(collapsed(QModelIndex)), SLOT(Collapsed(QModelIndex))); - connect(ui_->tree, SIGNAL(expanded(QModelIndex)), SLOT(Expanded(QModelIndex))); - connect(ui_->tree, SIGNAL(FocusOnFilterSignal(QKeyEvent*)), SLOT(FocusOnFilter(QKeyEvent*))); + connect(ui_->tree, SIGNAL(collapsed(QModelIndex)), + SLOT(Collapsed(QModelIndex))); + connect(ui_->tree, SIGNAL(expanded(QModelIndex)), + SLOT(Expanded(QModelIndex))); + connect(ui_->tree, SIGNAL(FocusOnFilterSignal(QKeyEvent*)), + SLOT(FocusOnFilter(QKeyEvent*))); } -InternetViewContainer::~InternetViewContainer() { - delete ui_; -} +InternetViewContainer::~InternetViewContainer() { delete ui_; } -InternetView* InternetViewContainer::tree() const { - return ui_->tree; -} +InternetView* InternetViewContainer::tree() const { return ui_->tree; } void InternetViewContainer::SetApplication(Application* app) { app_ = app; @@ -57,14 +55,14 @@ void InternetViewContainer::SetApplication(Application* app) { ui_->tree->setModel(app_->internet_model()->merged_model()); connect(ui_->tree->selectionModel(), - SIGNAL(currentChanged(QModelIndex,QModelIndex)), + SIGNAL(currentChanged(QModelIndex, QModelIndex)), SLOT(CurrentIndexChanged(QModelIndex))); } void InternetViewContainer::ServiceChanged(const QModelIndex& index) { - InternetService* service = index.data(InternetModel::Role_Service).value(); - if (!service || service == current_service_) - return; + InternetService* service = + index.data(InternetModel::Role_Service).value(); + if (!service || service == current_service_) return; current_service_ = service; QWidget* header = service->HeaderWidget(); @@ -78,7 +76,8 @@ void InternetViewContainer::ServiceChanged(const QModelIndex& index) { d.visible_ = false; d.animation_ = new QTimeLine(kAnimationDuration, this); d.animation_->setFrameRange(0, header->sizeHint().height()); - connect(d.animation_, SIGNAL(frameChanged(int)), SLOT(SetHeaderHeight(int))); + connect(d.animation_, SIGNAL(frameChanged(int)), + SLOT(SetHeaderHeight(int))); headers_.insert(header, d); } @@ -93,8 +92,9 @@ void InternetViewContainer::CurrentIndexChanged(const QModelIndex& index) { } void InternetViewContainer::Collapsed(const QModelIndex& index) { - if (app_->internet_model()->merged_model()->mapToSource(index).model() == app_->internet_model() - && index.data(InternetModel::Role_Type) == InternetModel::Type_Service) { + if (app_->internet_model()->merged_model()->mapToSource(index).model() == + app_->internet_model() && + index.data(InternetModel::Role_Type) == InternetModel::Type_Service) { SetHeaderVisible(current_header_, false); current_service_ = nullptr; current_header_ = nullptr; @@ -106,15 +106,14 @@ void InternetViewContainer::Expanded(const QModelIndex& index) { } void InternetViewContainer::SetHeaderVisible(QWidget* header, bool visible) { - if (!header) - return; + if (!header) return; HeaderData& d = headers_[header]; - if (d.visible_ == visible) - return; + if (d.visible_ == visible) return; d.visible_ = visible; - d.animation_->setDirection(visible ? QTimeLine::Forward : QTimeLine::Backward); + d.animation_->setDirection(visible ? QTimeLine::Forward + : QTimeLine::Backward); d.animation_->start(); } @@ -123,10 +122,10 @@ void InternetViewContainer::FocusOnFilter(QKeyEvent* event) { if (current_header_) { int slot = current_header_->metaObject()->indexOfSlot( - QMetaObject::normalizedSignature("FocusOnFilter(QKeyEvent*)")); + QMetaObject::normalizedSignature("FocusOnFilter(QKeyEvent*)")); if (slot != -1) { current_header_->metaObject()->method(slot).invoke( - current_header_, Q_ARG(QKeyEvent*, event)); + current_header_, Q_ARG(QKeyEvent*, event)); } } } @@ -134,15 +133,14 @@ void InternetViewContainer::FocusOnFilter(QKeyEvent* event) { void InternetViewContainer::SetHeaderHeight(int height) { QTimeLine* animation = qobject_cast(sender()); QWidget* header = nullptr; - foreach (QWidget* h, headers_.keys()) { + foreach(QWidget * h, headers_.keys()) { if (headers_[h].animation_ == animation) { header = h; break; } } - if (header) - header->setMaximumHeight(height); + if (header) header->setMaximumHeight(height); } void InternetViewContainer::ScrollToIndex(const QModelIndex& index) { diff --git a/src/internet/internetviewcontainer.h b/src/internet/internetviewcontainer.h index 5da4f8844..748c67074 100644 --- a/src/internet/internetviewcontainer.h +++ b/src/internet/internetviewcontainer.h @@ -72,4 +72,4 @@ class InternetViewContainer : public QWidget { QMap headers_; }; -#endif // INTERNETVIEWCONTAINER_H +#endif // INTERNETVIEWCONTAINER_H diff --git a/src/internet/jamendodynamicplaylist.cpp b/src/internet/jamendodynamicplaylist.cpp index c9c45de2f..4109b9e56 100644 --- a/src/internet/jamendodynamicplaylist.cpp +++ b/src/internet/jamendodynamicplaylist.cpp @@ -33,17 +33,17 @@ const char* JamendoDynamicPlaylist::kUrl = "http://api.jamendo.com/get2/id/track/plain/"; JamendoDynamicPlaylist::JamendoDynamicPlaylist() - : order_by_(OrderBy_Rating), - order_direction_(Order_Descending), - current_page_(0), - current_index_(0) { -} + : order_by_(OrderBy_Rating), + order_direction_(Order_Descending), + current_page_(0), + current_index_(0) {} -JamendoDynamicPlaylist::JamendoDynamicPlaylist(const QString& name, OrderBy order_by) - : order_by_(order_by), - order_direction_(Order_Descending), - current_page_(0), - current_index_(0) { +JamendoDynamicPlaylist::JamendoDynamicPlaylist(const QString& name, + OrderBy order_by) + : order_by_(order_by), + order_direction_(Order_Descending), + current_page_(0), + current_index_(0) { set_name(name); } @@ -52,7 +52,8 @@ void JamendoDynamicPlaylist::Load(const QByteArray& data) { s >> *this; } -void JamendoDynamicPlaylist::Load(OrderBy order_by, OrderDirection order_direction) { +void JamendoDynamicPlaylist::Load(OrderBy order_by, + OrderDirection order_direction) { order_by_ = order_by; order_direction_ = order_direction; } @@ -65,9 +66,7 @@ QByteArray JamendoDynamicPlaylist::Save() const { return ret; } -PlaylistItemList JamendoDynamicPlaylist::Generate() { - return GenerateMore(20); -} +PlaylistItemList JamendoDynamicPlaylist::Generate() { return GenerateMore(20); } PlaylistItemList JamendoDynamicPlaylist::GenerateMore(int count) { int tries = 0; @@ -91,14 +90,26 @@ PlaylistItemList JamendoDynamicPlaylist::GenerateMore(int count) { QString JamendoDynamicPlaylist::OrderSpec(OrderBy by, OrderDirection dir) { QString ret; switch (by) { - case OrderBy_Listened: ret += "listened"; break; - case OrderBy_Rating: ret += "rating"; break; - case OrderBy_RatingMonth: ret += "ratingmonth"; break; - case OrderBy_RatingWeek: ret += "ratingweek"; break; + case OrderBy_Listened: + ret += "listened"; + break; + case OrderBy_Rating: + ret += "rating"; + break; + case OrderBy_RatingMonth: + ret += "ratingmonth"; + break; + case OrderBy_RatingWeek: + ret += "ratingweek"; + break; } switch (dir) { - case Order_Ascending: ret += "_asc"; break; - case Order_Descending: ret += "_desc"; break; + case Order_Ascending: + ret += "_asc"; + break; + case Order_Descending: + ret += "_desc"; + break; } return ret; } @@ -111,7 +122,8 @@ void JamendoDynamicPlaylist::Fetch() { // We have to use QHttp here because there's no way to disable Keep-Alive // with QNetworkManager. - QHttpRequestHeader header("GET", QString(url.encodedPath() + "?" + url.encodedQuery())); + QHttpRequestHeader header( + "GET", QString(url.encodedPath() + "?" + url.encodedQuery())); header.setValue("Host", url.encodedHost()); QHttp http(url.host()); @@ -120,13 +132,14 @@ void JamendoDynamicPlaylist::Fetch() { // Wait for the reply { QEventLoop event_loop; - connect(&http, SIGNAL(requestFinished(int,bool)), &event_loop, SLOT(quit())); + connect(&http, SIGNAL(requestFinished(int, bool)), &event_loop, + SLOT(quit())); event_loop.exec(); } if (http.error() != QHttp::NoError) { qLog(Warning) << "HTTP error returned from Jamendo:" << http.errorString() - << ", url:" << url.toString(); + << ", url:" << url.toString(); return; } @@ -135,28 +148,27 @@ void JamendoDynamicPlaylist::Fetch() { // Get the songs from the database SongList songs = backend_->GetSongsByForeignId( - lines, JamendoService::kTrackIdsTable, JamendoService::kTrackIdsColumn); + lines, JamendoService::kTrackIdsTable, JamendoService::kTrackIdsColumn); if (songs.empty()) { - qLog(Warning) << "No songs returned from Jamendo:" - << url.toString(); + qLog(Warning) << "No songs returned from Jamendo:" << url.toString(); return; } current_items_.clear(); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { if (song.is_valid()) current_items_ << PlaylistItemPtr(new JamendoPlaylistItem(song)); } current_index_ = 0; } -QDataStream& operator <<(QDataStream& s, const JamendoDynamicPlaylist& p) { +QDataStream& operator<<(QDataStream& s, const JamendoDynamicPlaylist& p) { s << quint8(p.order_by_) << quint8(p.order_direction_); return s; } -QDataStream& operator >>(QDataStream& s, JamendoDynamicPlaylist& p) { +QDataStream& operator>>(QDataStream& s, JamendoDynamicPlaylist& p) { quint8 order_by, order_direction; s >> order_by >> order_direction; p.order_by_ = JamendoDynamicPlaylist::OrderBy(order_by); diff --git a/src/internet/jamendodynamicplaylist.h b/src/internet/jamendodynamicplaylist.h index 266f46364..d69318208 100644 --- a/src/internet/jamendodynamicplaylist.h +++ b/src/internet/jamendodynamicplaylist.h @@ -22,10 +22,11 @@ class JamendoDynamicPlaylist : public smart_playlists::Generator { Q_OBJECT - friend QDataStream& operator <<(QDataStream& s, const JamendoDynamicPlaylist& p); - friend QDataStream& operator >>(QDataStream& s, JamendoDynamicPlaylist& p); + friend QDataStream& operator<<(QDataStream& s, + const JamendoDynamicPlaylist& p); + friend QDataStream& operator>>(QDataStream& s, JamendoDynamicPlaylist& p); -public: + public: // These values are persisted - only add to the end enum OrderBy { OrderBy_Rating = 0, @@ -35,10 +36,7 @@ public: }; // These values are persisted - only add to the end - enum OrderDirection { - Order_Ascending = 0, - Order_Descending = 1, - }; + enum OrderDirection { Order_Ascending = 0, Order_Descending = 1, }; JamendoDynamicPlaylist(); JamendoDynamicPlaylist(const QString& name, OrderBy order_by); @@ -46,7 +44,8 @@ public: QString type() const { return "Jamendo"; } void Load(const QByteArray& data); - void Load(OrderBy order_by, OrderDirection order_direction = Order_Descending); + void Load(OrderBy order_by, + OrderDirection order_direction = Order_Descending); QByteArray Save() const; PlaylistItemList Generate(); @@ -54,11 +53,11 @@ public: bool is_dynamic() const { return true; } PlaylistItemList GenerateMore(int count); -private: + private: void Fetch(); static QString OrderSpec(OrderBy by, OrderDirection dir); -private: + private: OrderBy order_by_; OrderDirection order_direction_; @@ -71,7 +70,7 @@ private: static const char* kUrl; }; -QDataStream& operator <<(QDataStream& s, const JamendoDynamicPlaylist& p); -QDataStream& operator >>(QDataStream& s, JamendoDynamicPlaylist& p); +QDataStream& operator<<(QDataStream& s, const JamendoDynamicPlaylist& p); +QDataStream& operator>>(QDataStream& s, JamendoDynamicPlaylist& p); #endif diff --git a/src/internet/jamendoplaylistitem.cpp b/src/internet/jamendoplaylistitem.cpp index f14d69829..253ac4134 100644 --- a/src/internet/jamendoplaylistitem.cpp +++ b/src/internet/jamendoplaylistitem.cpp @@ -18,13 +18,10 @@ #include "jamendoplaylistitem.h" JamendoPlaylistItem::JamendoPlaylistItem(const QString& type) - : LibraryPlaylistItem(type) -{ -} + : LibraryPlaylistItem(type) {} JamendoPlaylistItem::JamendoPlaylistItem(const Song& song) - : LibraryPlaylistItem("Jamendo") -{ + : LibraryPlaylistItem("Jamendo") { song_ = song; } @@ -35,6 +32,4 @@ bool JamendoPlaylistItem::InitFromQuery(const SqlRow& query) { return song_.is_valid(); } -QUrl JamendoPlaylistItem::Url() const { - return song_.url(); -} +QUrl JamendoPlaylistItem::Url() const { return song_.url(); } diff --git a/src/internet/jamendoplaylistitem.h b/src/internet/jamendoplaylistitem.h index 4faab507e..06e35a3e1 100644 --- a/src/internet/jamendoplaylistitem.h +++ b/src/internet/jamendoplaylistitem.h @@ -21,7 +21,7 @@ #include "library/libraryplaylistitem.h" class JamendoPlaylistItem : public LibraryPlaylistItem { -public: + public: JamendoPlaylistItem(const QString& type); JamendoPlaylistItem(const Song& song); @@ -30,4 +30,4 @@ public: QUrl Url() const; }; -#endif // JAMENDOPLAYLISTITEM_H +#endif // JAMENDOPLAYLISTITEM_H diff --git a/src/internet/jamendoservice.cpp b/src/internet/jamendoservice.cpp index c968909dd..3661a6379 100644 --- a/src/internet/jamendoservice.cpp +++ b/src/internet/jamendoservice.cpp @@ -51,14 +51,17 @@ const char* JamendoService::kServiceName = "Jamendo"; const char* JamendoService::kDirectoryUrl = "http://img.jamendo.com/data/dbdump_artistalbumtrack.xml.gz"; const char* JamendoService::kMp3StreamUrl = - "http://api.jamendo.com/get2/stream/track/redirect/?id=%1&streamencoding=mp31"; + "http://api.jamendo.com/get2/stream/track/redirect/" + "?id=%1&streamencoding=mp31"; const char* JamendoService::kOggStreamUrl = - "http://api.jamendo.com/get2/stream/track/redirect/?id=%1&streamencoding=ogg2"; + "http://api.jamendo.com/get2/stream/track/redirect/" + "?id=%1&streamencoding=ogg2"; const char* JamendoService::kAlbumCoverUrl = "http://api.jamendo.com/get2/image/album/redirect/?id=%1&imagesize=300"; const char* JamendoService::kHomepage = "http://www.jamendo.com/"; const char* JamendoService::kAlbumInfoUrl = "http://www.jamendo.com/album/%1"; -const char* JamendoService::kDownloadAlbumUrl = "http://www.jamendo.com/download/album/%1"; +const char* JamendoService::kDownloadAlbumUrl = + "http://www.jamendo.com/download/album/%1"; const char* JamendoService::kSongsTable = "jamendo.songs"; const char* JamendoService::kFtsTable = "jamendo.songs_fts"; @@ -84,8 +87,8 @@ JamendoService::JamendoService(Application* app, InternetModel* parent) accepted_download_(false) { library_backend_ = new LibraryBackend; library_backend_->moveToThread(app_->database()->thread()); - library_backend_->Init(app_->database(), kSongsTable, - QString::null, QString::null, kFtsTable); + library_backend_->Init(app_->database(), kSongsTable, QString::null, + QString::null, kFtsTable); connect(library_backend_, SIGNAL(TotalSongCountUpdated(int)), SLOT(UpdateTotalSongCount(int))); @@ -98,23 +101,27 @@ JamendoService::JamendoService(Application* app, InternetModel* parent) library_model_ = new LibraryModel(library_backend_, app_, this); library_model_->set_show_various_artists(false); library_model_->set_show_smart_playlists(false); - library_model_->set_default_smart_playlists(LibraryModel::DefaultGenerators() - << (LibraryModel::GeneratorList() - << GeneratorPtr(new JamendoDynamicPlaylist(tr("Jamendo Top Tracks of the Month"), - JamendoDynamicPlaylist::OrderBy_RatingMonth)) - << GeneratorPtr(new JamendoDynamicPlaylist(tr("Jamendo Top Tracks of the Week"), - JamendoDynamicPlaylist::OrderBy_RatingWeek)) - << GeneratorPtr(new JamendoDynamicPlaylist(tr("Jamendo Top Tracks"), - JamendoDynamicPlaylist::OrderBy_Rating)) - << GeneratorPtr(new JamendoDynamicPlaylist(tr("Jamendo Most Listened Tracks"), - JamendoDynamicPlaylist::OrderBy_Listened)) - ) - << (LibraryModel::GeneratorList() - << GeneratorPtr(new QueryGenerator(tr("Dynamic random mix"), Search( - Search::Type_All, Search::TermList(), - Search::Sort_Random, SearchTerm::Field_Title), true)) - ) - ); + library_model_->set_default_smart_playlists( + LibraryModel::DefaultGenerators() + << (LibraryModel::GeneratorList() + << GeneratorPtr(new JamendoDynamicPlaylist( + tr("Jamendo Top Tracks of the Month"), + JamendoDynamicPlaylist::OrderBy_RatingMonth)) + << GeneratorPtr(new JamendoDynamicPlaylist( + tr("Jamendo Top Tracks of the Week"), + JamendoDynamicPlaylist::OrderBy_RatingWeek)) + << GeneratorPtr(new JamendoDynamicPlaylist( + tr("Jamendo Top Tracks"), + JamendoDynamicPlaylist::OrderBy_Rating)) + << GeneratorPtr(new JamendoDynamicPlaylist( + tr("Jamendo Most Listened Tracks"), + JamendoDynamicPlaylist::OrderBy_Listened))) + << (LibraryModel::GeneratorList() + << GeneratorPtr(new QueryGenerator( + tr("Dynamic random mix"), + Search(Search::Type_All, Search::TermList(), + Search::Sort_Random, SearchTerm::Field_Title), + true)))); library_sort_model_->setSourceModel(library_model_); library_sort_model_->setSortRole(LibraryModel::Role_SortText); @@ -123,22 +130,19 @@ JamendoService::JamendoService(Application* app, InternetModel* parent) library_sort_model_->sort(0); search_provider_ = new LibrarySearchProvider( - library_backend_, - tr("Jamendo"), - "jamendo", - QIcon(":/providers/jamendo.png"), - false, app_, this); + library_backend_, tr("Jamendo"), "jamendo", + QIcon(":/providers/jamendo.png"), false, app_, this); app_->global_search()->AddProvider(search_provider_); connect(app_->global_search(), - SIGNAL(ProviderToggled(const SearchProvider*,bool)), - SLOT(SearchProviderToggled(const SearchProvider*,bool))); + SIGNAL(ProviderToggled(const SearchProvider*, bool)), + SLOT(SearchProviderToggled(const SearchProvider*, bool))); } -JamendoService::~JamendoService() { -} +JamendoService::~JamendoService() {} QStandardItem* JamendoService::CreateRootItem() { - QStandardItem* item = new QStandardItem(QIcon(":providers/jamendo.png"), kServiceName); + QStandardItem* item = + new QStandardItem(QIcon(":providers/jamendo.png"), kServiceName); item->setData(true, InternetModel::Role_CanLazyLoad); return item; } @@ -161,15 +165,19 @@ void JamendoService::UpdateTotalSongCount(int count) { total_song_count_ = count; if (total_song_count_ > 0) { library_model_->set_show_smart_playlists(true); - accepted_download_ = true; //the user has previously accepted + accepted_download_ = true; // the user has previously accepted } } void JamendoService::DownloadDirectory() { - //don't ask if we're refreshing the database + // don't ask if we're refreshing the database if (total_song_count_ == 0) { - if (QMessageBox::question(context_menu_, tr("Jamendo database"), tr("This action will create a database which could be as big as 150 MB.\n" - "Do you want to continue anyway?"), QMessageBox::Ok | QMessageBox::Cancel) != QMessageBox::Ok) + if (QMessageBox::question(context_menu_, tr("Jamendo database"), + tr("This action will create a database which " + "could be as big as 150 MB.\n" + "Do you want to continue anyway?"), + QMessageBox::Ok | QMessageBox::Cancel) != + QMessageBox::Ok) return; } accepted_download_ = true; @@ -179,19 +187,19 @@ void JamendoService::DownloadDirectory() { QNetworkReply* reply = network_->get(req); connect(reply, SIGNAL(finished()), SLOT(DownloadDirectoryFinished())); - connect(reply, SIGNAL(downloadProgress(qint64,qint64)), - SLOT(DownloadDirectoryProgress(qint64,qint64))); + connect(reply, SIGNAL(downloadProgress(qint64, qint64)), + SLOT(DownloadDirectoryProgress(qint64, qint64))); if (!load_database_task_id_) { - load_database_task_id_ = app_->task_manager()->StartTask( - tr("Downloading Jamendo catalogue")); + load_database_task_id_ = + app_->task_manager()->StartTask(tr("Downloading Jamendo catalogue")); } } void JamendoService::DownloadDirectoryProgress(qint64 received, qint64 total) { float progress = float(received) / total; app_->task_manager()->SetTaskProgress(load_database_task_id_, - int(progress * 100), 100); + int(progress * 100), 100); } void JamendoService::DownloadDirectoryFinished() { @@ -210,11 +218,11 @@ void JamendoService::DownloadDirectoryFinished() { return; } - load_database_task_id_ = app_->task_manager()->StartTask( - tr("Parsing Jamendo catalogue")); + load_database_task_id_ = + app_->task_manager()->StartTask(tr("Parsing Jamendo catalogue")); - QFuture future = QtConcurrent::run( - this, &JamendoService::ParseDirectory, gzip); + QFuture future = + QtConcurrent::run(this, &JamendoService::ParseDirectory, gzip); QFutureWatcher* watcher = new QFutureWatcher(); watcher->setFuture(future); connect(watcher, SIGNAL(finished()), SLOT(ParseDirectoryFinished())); @@ -226,8 +234,8 @@ void JamendoService::ParseDirectory(QIODevice* device) const { // Bit of a hack: don't update the model while we're parsing the xml disconnect(library_backend_, SIGNAL(SongsDiscovered(SongList)), library_model_, SLOT(SongsDiscovered(SongList))); - disconnect(library_backend_, SIGNAL(TotalSongCountUpdated(int)), - this, SLOT(UpdateTotalSongCount(int))); + disconnect(library_backend_, SIGNAL(TotalSongCountUpdated(int)), this, + SLOT(UpdateTotalSongCount(int))); // Delete the database and recreate it. This is faster than dropping tables // or removing rows. @@ -253,16 +261,16 @@ void JamendoService::ParseDirectory(QIODevice* device) const { track_ids.clear(); // Update progress info - app_->task_manager()->SetTaskProgress( - load_database_task_id_, total_count, kApproxDatabaseSize); + app_->task_manager()->SetTaskProgress(load_database_task_id_, total_count, + kApproxDatabaseSize); } } library_backend_->AddOrUpdateSongs(songs); InsertTrackIds(track_ids); - connect(library_backend_, SIGNAL(SongsDiscovered(SongList)), - library_model_, SLOT(SongsDiscovered(SongList))); + connect(library_backend_, SIGNAL(SongsDiscovered(SongList)), library_model_, + SLOT(SongsDiscovered(SongList))); connect(library_backend_, SIGNAL(TotalSongCountUpdated(int)), SLOT(UpdateTotalSongCount(int))); @@ -276,9 +284,10 @@ void JamendoService::InsertTrackIds(const TrackIdList& ids) const { ScopedTransaction t(&db); QSqlQuery insert(QString("INSERT INTO %1 (%2) VALUES (:id)") - .arg(kTrackIdsTable, kTrackIdsColumn), db); + .arg(kTrackIdsTable, kTrackIdsColumn), + db); - foreach (int id, ids) { + foreach(int id, ids) { insert.bindValue(":id", id); if (!insert.exec()) { qLog(Warning) << "Query failed" << insert.lastQuery(); @@ -311,8 +320,9 @@ SongList JamendoService::ReadArtist(QXmlStreamReader* reader, return ret; } -SongList JamendoService::ReadAlbum( - const QString& artist, QXmlStreamReader* reader, TrackIdList* track_ids) const { +SongList JamendoService::ReadAlbum(const QString& artist, + QXmlStreamReader* reader, + TrackIdList* track_ids) const { SongList ret; QString current_album; QString cover; @@ -329,8 +339,8 @@ SongList JamendoService::ReadAlbum( cover = QString(kAlbumCoverUrl).arg(id); current_album_id = id.toInt(); } else if (reader->name() == "track") { - ret << ReadTrack(artist, current_album, cover, current_album_id, - reader, track_ids); + ret << ReadTrack(artist, current_album, cover, current_album_id, reader, + track_ids); } } else if (reader->isEndElement() && reader->name() == "album") { break; @@ -339,10 +349,8 @@ SongList JamendoService::ReadAlbum( return ret; } -Song JamendoService::ReadTrack(const QString& artist, - const QString& album, - const QString& album_cover, - int album_id, +Song JamendoService::ReadTrack(const QString& artist, const QString& album, + const QString& album_cover, int album_id, QXmlStreamReader* reader, TrackIdList* track_ids) const { Song song; @@ -375,8 +383,7 @@ Song JamendoService::ReadTrack(const QString& artist, } else if (name == "id") { QString id_text = reader->readElementText(); int id = id_text.toInt(); - if (id == 0) - continue; + if (id == 0) continue; QString mp3_url = QString(kMp3StreamUrl).arg(id_text); song.set_url(QUrl(mp3_url)); @@ -397,7 +404,7 @@ void JamendoService::ParseDirectoryFinished() { QFutureWatcher* watcher = static_cast*>(sender()); delete watcher; - //show smart playlists + // show smart playlists library_model_->set_show_smart_playlists(true); library_model_->Reset(); @@ -406,18 +413,23 @@ void JamendoService::ParseDirectoryFinished() { } void JamendoService::EnsureMenuCreated() { - if (library_filter_) - return; + if (library_filter_) return; context_menu_ = new QMenu; context_menu_->addActions(GetPlaylistActions()); album_info_ = context_menu_->addAction(IconLoader::Load("view-media-lyrics"), - tr("Album info on jamendo.com..."), this, SLOT(AlbumInfo())); + tr("Album info on jamendo.com..."), + this, SLOT(AlbumInfo())); download_album_ = context_menu_->addAction(IconLoader::Load("download"), - tr("Download this album..."), this, SLOT(DownloadAlbum())); + tr("Download this album..."), this, + SLOT(DownloadAlbum())); context_menu_->addSeparator(); - context_menu_->addAction(IconLoader::Load("download"), tr("Open %1 in browser").arg("jamendo.com"), this, SLOT(Homepage())); - context_menu_->addAction(IconLoader::Load("view-refresh"), tr("Refresh catalogue"), this, SLOT(DownloadDirectory())); + context_menu_->addAction(IconLoader::Load("download"), + tr("Open %1 in browser").arg("jamendo.com"), this, + SLOT(Homepage())); + context_menu_->addAction(IconLoader::Load("view-refresh"), + tr("Refresh catalogue"), this, + SLOT(DownloadDirectory())); if (accepted_download_) { library_filter_ = new LibraryFilterWidget(0); @@ -437,7 +449,7 @@ void JamendoService::ShowContextMenu(const QPoint& global_pos) { const bool enabled = accepted_download_ && model()->current_index().model() == library_sort_model_; - //make menu items visible and enabled only when needed + // make menu items visible and enabled only when needed GetAppendToPlaylistAction()->setVisible(accepted_download_); GetAppendToPlaylistAction()->setEnabled(enabled); GetReplacePlaylistAction()->setVisible(accepted_download_); @@ -460,13 +472,11 @@ QWidget* JamendoService::HeaderWidget() const { void JamendoService::AlbumInfo() { SongList songs(library_model_->GetChildSongs( library_sort_model_->mapToSource(model()->current_index()))); - if (songs.isEmpty()) - return; + if (songs.isEmpty()) return; // We put the album ID into the comment field int id = songs.first().comment().toInt(); - if (!id) - return; + if (!id) return; QDesktopServices::openUrl(QUrl(QString(kAlbumInfoUrl).arg(id))); } @@ -474,20 +484,16 @@ void JamendoService::AlbumInfo() { void JamendoService::DownloadAlbum() { SongList songs(library_model_->GetChildSongs( library_sort_model_->mapToSource(model()->current_index()))); - if (songs.isEmpty()) - return; + if (songs.isEmpty()) return; // We put the album ID into the comment field int id = songs.first().comment().toInt(); - if (!id) - return; + if (!id) return; QDesktopServices::openUrl(QUrl(QString(kDownloadAlbumUrl).arg(id))); } -void JamendoService::Homepage() { - QDesktopServices::openUrl(QUrl(kHomepage)); -} +void JamendoService::Homepage() { QDesktopServices::openUrl(QUrl(kHomepage)); } void JamendoService::SearchProviderToggled(const SearchProvider* provider, bool enabled) { diff --git a/src/internet/jamendoservice.h b/src/internet/jamendoservice.h index c2000a1c7..b658da0ef 100644 --- a/src/internet/jamendoservice.h +++ b/src/internet/jamendoservice.h @@ -77,12 +77,9 @@ class JamendoService : public InternetService { SongList ReadArtist(QXmlStreamReader* reader, TrackIdList* track_ids) const; SongList ReadAlbum(const QString& artist, QXmlStreamReader* reader, TrackIdList* track_ids) const; - Song ReadTrack(const QString& artist, - const QString& album, - const QString& album_cover, - int album_id, - QXmlStreamReader* reader, - TrackIdList* track_ids) const; + Song ReadTrack(const QString& artist, const QString& album, + const QString& album_cover, int album_id, + QXmlStreamReader* reader, TrackIdList* track_ids) const; void InsertTrackIds(const TrackIdList& ids) const; void EnsureMenuCreated(); diff --git a/src/internet/lastfmcompat.cpp b/src/internet/lastfmcompat.cpp index 09603fb8c..8f4d1579e 100644 --- a/src/internet/lastfmcompat.cpp +++ b/src/internet/lastfmcompat.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -23,16 +23,15 @@ namespace compat { #ifdef HAVE_LIBLASTFM1 -XmlQuery EmptyXmlQuery() { - return XmlQuery(); -} +XmlQuery EmptyXmlQuery() { return XmlQuery(); } -bool ParseQuery(const QByteArray& data, XmlQuery* query, bool* connection_problems) { +bool ParseQuery(const QByteArray& data, XmlQuery* query, + bool* connection_problems) { const bool ret = query->parse(data); if (connection_problems) { - *connection_problems = - !ret && query->parseError().enumValue() == lastfm::ws::MalformedResponse; + *connection_problems = !ret && query->parseError().enumValue() == + lastfm::ws::MalformedResponse; } return ret; @@ -48,32 +47,33 @@ bool ParseUserList(QNetworkReply* reply, QList* users) { return true; } -uint ScrobbleTimeMin() { - return lastfm::ScrobblePoint::scrobbleTimeMin(); -} +uint ScrobbleTimeMin() { return lastfm::ScrobblePoint::scrobbleTimeMin(); } -#else // HAVE_LIBLASTFM1 +#else // HAVE_LIBLASTFM1 XmlQuery EmptyXmlQuery() { QByteArray dummy; return XmlQuery(dummy); } -bool ParseQuery(const QByteArray& data, XmlQuery* query, bool* connection_problems) { +bool ParseQuery(const QByteArray& data, XmlQuery* query, + bool* connection_problems) { try { *query = lastfm::XmlQuery(data); - #ifdef Q_OS_WIN32 - if (lastfm::ws::last_parse_error != lastfm::ws::NoError) { - return false; - } - #endif // Q_OS_WIN32 - } catch (lastfm::ws::ParseError e) { +#ifdef Q_OS_WIN32 + if (lastfm::ws::last_parse_error != lastfm::ws::NoError) { + return false; + } +#endif // Q_OS_WIN32 + } + catch (lastfm::ws::ParseError e) { qLog(Error) << "Last.fm parse error: " << e.enumValue(); if (connection_problems) { *connection_problems = e.enumValue() == lastfm::ws::MalformedResponse; } return false; - } catch(std::runtime_error& e) { + } + catch (std::runtime_error& e) { qLog(Error) << e.what(); return false; } @@ -93,23 +93,21 @@ bool ParseQuery(const QByteArray& data, XmlQuery* query, bool* connection_proble bool ParseUserList(QNetworkReply* reply, QList* users) { try { *users = lastfm::User::list(reply); - #ifdef Q_OS_WIN32 - if (lastfm::ws::last_parse_error != lastfm::ws::NoError) { - return false; - } - #endif // Q_OS_WIN32 - } catch(std::runtime_error& e) { +#ifdef Q_OS_WIN32 + if (lastfm::ws::last_parse_error != lastfm::ws::NoError) { + return false; + } +#endif // Q_OS_WIN32 + } + catch (std::runtime_error& e) { qLog(Error) << e.what(); return false; } return true; } -uint ScrobbleTimeMin() { - return ScrobblePoint::kScrobbleMinLength; -} - -#endif // HAVE_LIBLASTFM1 +uint ScrobbleTimeMin() { return ScrobblePoint::kScrobbleMinLength; } +#endif // HAVE_LIBLASTFM1 } } diff --git a/src/internet/lastfmcompat.h b/src/internet/lastfmcompat.h index ca24d2e8d..007dd2e06 100644 --- a/src/internet/lastfmcompat.h +++ b/src/internet/lastfmcompat.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -22,21 +22,21 @@ #include "fixlastfm.h" #ifdef HAVE_LIBLASTFM1 - #include - #include - #include - #include - #include - #include - #include +#include +#include +#include +#include +#include +#include +#include #else - #include - #include - #include - #include - #include - #include - #include +#include +#include +#include +#include +#include +#include +#include #endif namespace lastfm { @@ -52,14 +52,13 @@ bool ParseUserList(QNetworkReply* reply, QList* users); uint ScrobbleTimeMin(); #ifdef HAVE_LIBLASTFM1 - typedef lastfm::ScrobbleCache ScrobbleCache; - typedef lastfm::User AuthenticatedUser; +typedef lastfm::ScrobbleCache ScrobbleCache; +typedef lastfm::User AuthenticatedUser; #else - typedef ::ScrobbleCache ScrobbleCache; - typedef lastfm::AuthenticatedUser AuthenticatedUser; +typedef ::ScrobbleCache ScrobbleCache; +typedef lastfm::AuthenticatedUser AuthenticatedUser; #endif - } } -#endif // LASTFMCOMPAT_H +#endif // LASTFMCOMPAT_H diff --git a/src/internet/lastfmservice.cpp b/src/internet/lastfmservice.cpp index 756dd661f..2f594817a 100644 --- a/src/internet/lastfmservice.cpp +++ b/src/internet/lastfmservice.cpp @@ -15,20 +15,21 @@ along with Clementine. If not, see . */ -// StringBuilder is activated to speed-up QString concatenation. As explained here: +// StringBuilder is activated to speed-up QString concatenation. As explained +// here: // http://labs.qt.nokia.com/2011/06/13/string-concatenation-with-qstringbuilder/ // this cause some compilation errors in some cases. As Lasfm library inlines // some functions in their includes files, which aren't compatible with // QStringBuilder, we undef it here #include #if QT_VERSION >= 0x040600 - #if QT_VERSION >= 0x040800 - #undef QT_USE_QSTRINGBUILDER - #else - #undef QT_USE_FAST_CONCATENATION - #undef QT_USE_FAST_OPERATOR_PLUS - #endif // QT_VERSION >= 0x040800 -#endif // QT_VERSION >= 0x040600 +#if QT_VERSION >= 0x040800 +#undef QT_USE_QSTRINGBUILDER +#else +#undef QT_USE_FAST_CONCATENATION +#undef QT_USE_FAST_OPERATOR_PLUS +#endif // QT_VERSION >= 0x040800 +#endif // QT_VERSION >= 0x040600 #include "lastfmservice.h" @@ -36,9 +37,9 @@ #include #ifdef HAVE_LIBLASTFM1 - #include +#include #else - #include +#include #endif #include "lastfmcompat.h" @@ -62,8 +63,7 @@ using lastfm::XmlQuery; uint qHash(const lastfm::Track& track) { - return qHash(track.title()) ^ - qHash(track.artist().name()) ^ + return qHash(track.title()) ^ qHash(track.artist().name()) ^ qHash(track.album().title()); } @@ -73,54 +73,61 @@ const char* LastFMService::kAudioscrobblerClientId = "tng"; const char* LastFMService::kApiKey = "75d20fb472be99275392aefa2760ea09"; const char* LastFMService::kSecret = "d3072b60ae626be12be69448f5c46e70"; -const char* LastFMService::kUrlArtist = "lastfm://artist/%1/similarartists"; -const char* LastFMService::kUrlTag = "lastfm://globaltags/%1"; -const char* LastFMService::kUrlCustom = "lastfm://rql/%1"; +const char* LastFMService::kUrlArtist = "lastfm://artist/%1/similarartists"; +const char* LastFMService::kUrlTag = "lastfm://globaltags/%1"; +const char* LastFMService::kUrlCustom = "lastfm://rql/%1"; -const char* LastFMService::kTitleArtist = QT_TR_NOOP("Last.fm Similar Artists to %1"); -const char* LastFMService::kTitleTag = QT_TR_NOOP("Last.fm Tag Radio: %1"); -const char* LastFMService::kTitleCustom = QT_TR_NOOP("Last.fm Custom Radio: %1"); +const char* LastFMService::kTitleArtist = + QT_TR_NOOP("Last.fm Similar Artists to %1"); +const char* LastFMService::kTitleTag = QT_TR_NOOP("Last.fm Tag Radio: %1"); +const char* LastFMService::kTitleCustom = + QT_TR_NOOP("Last.fm Custom Radio: %1"); -const int LastFMService::kFriendsCacheDurationSecs = 60 * 60 * 24; // 1 day +const int LastFMService::kFriendsCacheDurationSecs = 60 * 60 * 24; // 1 day LastFMService::LastFMService(Application* app, InternetModel* parent) - : InternetService(kServiceName, app, parent, parent), - url_handler_(new LastFMUrlHandler(this, this)), - scrobbler_(nullptr), - already_scrobbled_(false), - station_dialog_(new LastFMStationDialog), - context_menu_(new QMenu), - initial_tune_(false), - tune_task_id_(0), - scrobbling_enabled_(false), - root_item_(nullptr), - artist_list_(nullptr), - tag_list_(nullptr), - custom_list_(nullptr), - friends_list_(nullptr), - neighbours_list_(nullptr), - friend_names_(kSettingsGroup, "friend_names", kFriendsCacheDurationSecs), - connection_problems_(false) -{ + : InternetService(kServiceName, app, parent, parent), + url_handler_(new LastFMUrlHandler(this, this)), + scrobbler_(nullptr), + already_scrobbled_(false), + station_dialog_(new LastFMStationDialog), + context_menu_(new QMenu), + initial_tune_(false), + tune_task_id_(0), + scrobbling_enabled_(false), + root_item_(nullptr), + artist_list_(nullptr), + tag_list_(nullptr), + custom_list_(nullptr), + friends_list_(nullptr), + neighbours_list_(nullptr), + friend_names_(kSettingsGroup, "friend_names", kFriendsCacheDurationSecs), + connection_problems_(false) { ReloadSettings(); - //we emit the signal the first time to be sure the buttons are in the right state + // we emit the signal the first time to be sure the buttons are in the right + // state emit ScrobblingEnabledChanged(scrobbling_enabled_); context_menu_->addActions(GetPlaylistActions()); - remove_action_ = context_menu_->addAction( - IconLoader::Load("list-remove"), tr("Remove"), this, SLOT(Remove())); + remove_action_ = context_menu_->addAction(IconLoader::Load("list-remove"), + tr("Remove"), this, SLOT(Remove())); context_menu_->addSeparator(); add_artist_action_ = context_menu_->addAction( - QIcon(":last.fm/icon_radio.png"), tr("Play artist radio..."), this, SLOT(AddArtistRadio())); - add_tag_action_ = context_menu_->addAction( - QIcon(":last.fm/icon_tag.png"), tr("Play tag radio..."), this, SLOT(AddTagRadio())); + QIcon(":last.fm/icon_radio.png"), tr("Play artist radio..."), this, + SLOT(AddArtistRadio())); + add_tag_action_ = context_menu_->addAction(QIcon(":last.fm/icon_tag.png"), + tr("Play tag radio..."), this, + SLOT(AddTagRadio())); add_custom_action_ = context_menu_->addAction( - QIcon(":last.fm/icon_radio.png"), tr("Play custom radio..."), this, SLOT(AddCustomRadio())); + QIcon(":last.fm/icon_radio.png"), tr("Play custom radio..."), this, + SLOT(AddCustomRadio())); refresh_friends_action_ = context_menu_->addAction( - IconLoader::Load("view-refresh"), tr("Refresh friends list"), this, SLOT(ForceRefreshFriends())); - context_menu_->addAction( - IconLoader::Load("configure"), tr("Configure Last.fm..."), this, SLOT(ShowConfig())); + IconLoader::Load("view-refresh"), tr("Refresh friends list"), this, + SLOT(ForceRefreshFriends())); + context_menu_->addAction(IconLoader::Load("configure"), + tr("Configure Last.fm..."), this, + SLOT(ShowConfig())); remove_action_->setEnabled(false); add_artist_action_->setEnabled(false); @@ -130,11 +137,11 @@ LastFMService::LastFMService(Application* app, InternetModel* parent) app_->player()->RegisterUrlHandler(url_handler_); app_->cover_providers()->AddProvider(new LastFmCoverProvider(this)); - app_->global_search()->AddProvider(new LastFMSearchProvider(this, app_, this)); + app_->global_search()->AddProvider( + new LastFMSearchProvider(this, app_, this)); } -LastFMService::~LastFMService() { -} +LastFMService::~LastFMService() {} void LastFMService::ReloadSettings() { bool scrobbling_enabled_old = scrobbling_enabled_; @@ -144,12 +151,13 @@ void LastFMService::ReloadSettings() { lastfm::ws::SessionKey = settings.value("Session").toString(); scrobbling_enabled_ = settings.value("ScrobblingEnabled", true).toBool(); buttons_visible_ = settings.value("ShowLoveBanButtons", true).toBool(); - scrobble_button_visible_ = settings.value("ShowScrobbleButton", true).toBool(); + scrobble_button_visible_ = + settings.value("ShowScrobbleButton", true).toBool(); prefer_albumartist_ = settings.value("PreferAlbumArtist", false).toBool(); friend_names_.Load(); - //avoid emitting signal if it's not changed - if(scrobbling_enabled_old != scrobbling_enabled_) + // avoid emitting signal if it's not changed + if (scrobbling_enabled_old != scrobbling_enabled_) emit ScrobblingEnabledChanged(scrobbling_enabled_); emit ButtonVisibilityChanged(buttons_visible_); emit ScrobbleButtonVisibilityChanged(scrobble_button_visible_); @@ -180,56 +188,57 @@ void LastFMService::LazyPopulate(QStandardItem* parent) { switch (parent->data(InternetModel::Role_Type).toInt()) { case InternetModel::Type_Service: // Normal radio types - CreateStationItem(parent, - tr("My Recommendations"), - ":last.fm/recommended_radio.png", - QUrl("lastfm://user/USERNAME/recommended"), - tr("My Last.fm Recommended Radio")); - CreateStationItem(parent, - tr("My Radio Station"), - ":last.fm/personal_radio.png", - QUrl("lastfm://user/USERNAME/library"), - tr("My Last.fm Library")); - CreateStationItem(parent, - tr("My Mix Radio"), - ":last.fm/loved_radio.png", - QUrl("lastfm://user/USERNAME/mix"), - tr("My Last.fm Mix Radio")); - CreateStationItem(parent, - tr("My Neighborhood"), - ":last.fm/neighbour_radio.png", - QUrl("lastfm://user/USERNAME/neighbours"), - tr("My Last.fm Neighborhood")); + CreateStationItem(parent, tr("My Recommendations"), + ":last.fm/recommended_radio.png", + QUrl("lastfm://user/USERNAME/recommended"), + tr("My Last.fm Recommended Radio")); + CreateStationItem( + parent, tr("My Radio Station"), ":last.fm/personal_radio.png", + QUrl("lastfm://user/USERNAME/library"), tr("My Last.fm Library")); + CreateStationItem(parent, tr("My Mix Radio"), ":last.fm/loved_radio.png", + QUrl("lastfm://user/USERNAME/mix"), + tr("My Last.fm Mix Radio")); + CreateStationItem(parent, tr("My Neighborhood"), + ":last.fm/neighbour_radio.png", + QUrl("lastfm://user/USERNAME/neighbours"), + tr("My Last.fm Neighborhood")); // Types that have children - artist_list_ = new QStandardItem(QIcon(":last.fm/icon_radio.png"), tr("Artist radio")); + artist_list_ = new QStandardItem(QIcon(":last.fm/icon_radio.png"), + tr("Artist radio")); artist_list_->setData(Type_Artists, InternetModel::Role_Type); parent->appendRow(artist_list_); - tag_list_ = new QStandardItem(QIcon(":last.fm/icon_tag.png"), tr("Tag radio")); + tag_list_ = + new QStandardItem(QIcon(":last.fm/icon_tag.png"), tr("Tag radio")); tag_list_->setData(Type_Tags, InternetModel::Role_Type); parent->appendRow(tag_list_); - custom_list_ = new QStandardItem(QIcon(":last.fm/icon_radio.png"), tr("Custom radio")); + custom_list_ = new QStandardItem(QIcon(":last.fm/icon_radio.png"), + tr("Custom radio")); custom_list_->setData(Type_Custom, InternetModel::Role_Type); parent->appendRow(custom_list_); - RestoreList("artists", kUrlArtist, tr(kTitleArtist), QIcon(":last.fm/icon_radio.png"), artist_list_); - RestoreList("tags", kUrlTag, tr(kTitleTag), QIcon(":last.fm/icon_tag.png"), tag_list_); - RestoreList("custom", kUrlCustom, tr(kTitleCustom), QIcon(":last.fm/icon_radio.png"), custom_list_); + RestoreList("artists", kUrlArtist, tr(kTitleArtist), + QIcon(":last.fm/icon_radio.png"), artist_list_); + RestoreList("tags", kUrlTag, tr(kTitleTag), + QIcon(":last.fm/icon_tag.png"), tag_list_); + RestoreList("custom", kUrlCustom, tr(kTitleCustom), + QIcon(":last.fm/icon_radio.png"), custom_list_); - friends_list_ = new QStandardItem(QIcon(":last.fm/my_friends.png"), tr("Friends")); + friends_list_ = + new QStandardItem(QIcon(":last.fm/my_friends.png"), tr("Friends")); friends_list_->setData(Type_Friends, InternetModel::Role_Type); friends_list_->setData(true, InternetModel::Role_CanLazyLoad); parent->appendRow(friends_list_); - neighbours_list_ = new QStandardItem(QIcon(":last.fm/my_neighbours.png"), tr("Neighbors")); + neighbours_list_ = new QStandardItem(QIcon(":last.fm/my_neighbours.png"), + tr("Neighbors")); neighbours_list_->setData(Type_Neighbours, InternetModel::Role_Type); neighbours_list_->setData(true, InternetModel::Role_CanLazyLoad); parent->appendRow(neighbours_list_); - if (!IsAuthenticated()) - ShowConfig(); + if (!IsAuthenticated()) ShowConfig(); add_artist_action_->setEnabled(true); add_tag_action_->setEnabled(true); @@ -246,20 +255,20 @@ void LastFMService::LazyPopulate(QStandardItem* parent) { case Type_OtherUser: CreateStationItem(parent, - tr("Last.fm Radio Station - %1").arg(parent->text()), - ":last.fm/personal_radio.png", - QUrl("lastfm://user/" + parent->text() + "/library"), - tr("Last.fm Library - %1").arg(parent->text())); + tr("Last.fm Radio Station - %1").arg(parent->text()), + ":last.fm/personal_radio.png", + QUrl("lastfm://user/" + parent->text() + "/library"), + tr("Last.fm Library - %1").arg(parent->text())); CreateStationItem(parent, - tr("Last.fm Mix Radio - %1").arg(parent->text()), - ":last.fm/loved_radio.png", - QUrl("lastfm://user/" + parent->text() + "/mix"), - tr("Last.fm Mix Radio - %1").arg(parent->text())); + tr("Last.fm Mix Radio - %1").arg(parent->text()), + ":last.fm/loved_radio.png", + QUrl("lastfm://user/" + parent->text() + "/mix"), + tr("Last.fm Mix Radio - %1").arg(parent->text())); CreateStationItem(parent, - tr("Last.fm Neighbor Radio - %1").arg(parent->text()), - ":last.fm/neighbour_radio.png", - QUrl("lastfm://user/" + parent->text() + "/neighbours"), - tr("Last.fm Neighbor Radio - %1").arg(parent->text())); + tr("Last.fm Neighbor Radio - %1").arg(parent->text()), + ":last.fm/neighbour_radio.png", + QUrl("lastfm://user/" + parent->text() + "/neighbours"), + tr("Last.fm Neighbor Radio - %1").arg(parent->text())); break; default: @@ -267,25 +276,30 @@ void LastFMService::LazyPopulate(QStandardItem* parent) { } } -QStandardItem* LastFMService::CreateStationItem( - QStandardItem* parent, const QString& name, const QString& icon, - const QUrl& url, const QString& title) { +QStandardItem* LastFMService::CreateStationItem(QStandardItem* parent, + const QString& name, + const QString& icon, + const QUrl& url, + const QString& title) { Song song; song.set_url(url); song.set_title(title); QStandardItem* ret = new QStandardItem(QIcon(icon), name); ret->setData(QVariant::fromValue(song), InternetModel::Role_SongMetadata); - ret->setData(InternetModel::PlayBehaviour_SingleItem, InternetModel::Role_PlayBehaviour); + ret->setData(InternetModel::PlayBehaviour_SingleItem, + InternetModel::Role_PlayBehaviour); parent->appendRow(ret); return ret; } -void LastFMService::Authenticate(const QString& username, const QString& password) { +void LastFMService::Authenticate(const QString& username, + const QString& password) { QMap params; params["method"] = "auth.getMobileSession"; params["username"] = username; - params["authToken"] = lastfm::md5((username + lastfm::md5(password.toUtf8())).toUtf8()); + params["authToken"] = + lastfm::md5((username + lastfm::md5(password.toUtf8())).toUtf8()); QNetworkReply* reply = lastfm::ws::post(params); NewClosure(reply, SIGNAL(finished()), this, @@ -351,7 +365,8 @@ void LastFMService::UpdateSubscriberStatusFinished(QNetworkReply* reply) { bool is_subscriber = false; lastfm::XmlQuery lfm(lastfm::compat::EmptyXmlQuery()); - if (lastfm::compat::ParseQuery(reply->readAll(), &lfm, &connection_problems_)) { + if (lastfm::compat::ParseQuery(reply->readAll(), &lfm, + &connection_problems_)) { QString subscriber = lfm["user"]["subscriber"].text(); is_subscriber = (subscriber.toInt() == 1); @@ -403,8 +418,7 @@ void LastFMService::StreamMetadataReady() { void LastFMService::TunerError(lastfm::ws::Error error) { qLog(Warning) << "Last.fm error" << error; - if (!initial_tune_) - return; + if (!initial_tune_) return; app_->task_manager()->SetTaskFinished(tune_task_id_); tune_task_id_ = 0; @@ -419,26 +433,43 @@ void LastFMService::TunerError(lastfm::ws::Error error) { QString LastFMService::ErrorString(lastfm::ws::Error error) const { switch (error) { - case lastfm::ws::InvalidService: return tr("Invalid service"); - case lastfm::ws::InvalidMethod: return tr("Invalid method"); - case lastfm::ws::AuthenticationFailed: return tr("Authentication failed"); - case lastfm::ws::InvalidFormat: return tr("Invalid format"); - case lastfm::ws::InvalidParameters: return tr("Invalid parameters"); - case lastfm::ws::InvalidResourceSpecified: return tr("Invalid resource specified"); - case lastfm::ws::OperationFailed: return tr("Operation failed"); - case lastfm::ws::InvalidSessionKey: return tr("Invalid session key"); - case lastfm::ws::InvalidApiKey: return tr("Invalid API key"); - case lastfm::ws::ServiceOffline: return tr("Service offline"); - case lastfm::ws::SubscribersOnly: return tr("This stream is for paid subscribers only"); + case lastfm::ws::InvalidService: + return tr("Invalid service"); + case lastfm::ws::InvalidMethod: + return tr("Invalid method"); + case lastfm::ws::AuthenticationFailed: + return tr("Authentication failed"); + case lastfm::ws::InvalidFormat: + return tr("Invalid format"); + case lastfm::ws::InvalidParameters: + return tr("Invalid parameters"); + case lastfm::ws::InvalidResourceSpecified: + return tr("Invalid resource specified"); + case lastfm::ws::OperationFailed: + return tr("Operation failed"); + case lastfm::ws::InvalidSessionKey: + return tr("Invalid session key"); + case lastfm::ws::InvalidApiKey: + return tr("Invalid API key"); + case lastfm::ws::ServiceOffline: + return tr("Service offline"); + case lastfm::ws::SubscribersOnly: + return tr("This stream is for paid subscribers only"); - case lastfm::ws::TryAgainLater: return tr("Last.fm is currently busy, please try again in a few minutes"); + case lastfm::ws::TryAgainLater: + return tr("Last.fm is currently busy, please try again in a few minutes"); - case lastfm::ws::NotEnoughContent: return tr("Not enough content"); - case lastfm::ws::NotEnoughMembers: return tr("Not enough members"); - case lastfm::ws::NotEnoughFans: return tr("Not enough fans"); - case lastfm::ws::NotEnoughNeighbours: return tr("Not enough neighbors"); + case lastfm::ws::NotEnoughContent: + return tr("Not enough content"); + case lastfm::ws::NotEnoughMembers: + return tr("Not enough members"); + case lastfm::ws::NotEnoughFans: + return tr("Not enough fans"); + case lastfm::ws::NotEnoughNeighbours: + return tr("Not enough neighbors"); - case lastfm::ws::MalformedResponse: return tr("Malformed response"); + case lastfm::ws::MalformedResponse: + return tr("Malformed response"); case lastfm::ws::UnknownError: default: @@ -454,16 +485,17 @@ void LastFMService::TunerTrackAvailable() { } bool LastFMService::InitScrobbler() { - if (!IsAuthenticated() || !IsScrobblingEnabled()) - return false; + if (!IsAuthenticated() || !IsScrobblingEnabled()) return false; if (!scrobbler_) scrobbler_ = new lastfm::Audioscrobbler(kAudioscrobblerClientId); - //reemit the signal since the sender is private +// reemit the signal since the sender is private #ifdef HAVE_LIBLASTFM1 - connect(scrobbler_, SIGNAL(scrobblesSubmitted(QList)), SIGNAL(ScrobbleSubmitted())); - connect(scrobbler_, SIGNAL(nowPlayingError(int,QString)), SIGNAL(ScrobbleError(int))); + connect(scrobbler_, SIGNAL(scrobblesSubmitted(QList)), + SIGNAL(ScrobbleSubmitted())); + connect(scrobbler_, SIGNAL(nowPlayingError(int, QString)), + SIGNAL(ScrobbleError(int))); #else connect(scrobbler_, SIGNAL(status(int)), SLOT(ScrobblerStatus(int))); #endif @@ -472,18 +504,18 @@ bool LastFMService::InitScrobbler() { void LastFMService::ScrobblerStatus(int value) { switch (value) { - case 2: - case 3: - emit ScrobbleSubmitted(); - break; + case 2: + case 3: + emit ScrobbleSubmitted(); + break; - default: - emit ScrobbleError(value); - break; + default: + emit ScrobbleError(value); + break; } } -lastfm::Track LastFMService::TrackFromSong(const Song &song) const { +lastfm::Track LastFMService::TrackFromSong(const Song& song) const { if (song.title() == last_track_.title() && song.artist() == last_track_.artist() && song.album() == last_track_.album()) @@ -492,12 +524,10 @@ lastfm::Track LastFMService::TrackFromSong(const Song &song) const { lastfm::Track ret; song.ToLastFM(&ret, PreferAlbumArtist()); return ret; - } -void LastFMService::NowPlaying(const Song &song) { - if (!InitScrobbler()) - return; +void LastFMService::NowPlaying(const Song& song) { + if (!InitScrobbler()) return; // Scrobbling streams is difficult if we don't have length of each individual // part. In Song::ToLastFm we set the Track's source to @@ -506,12 +536,14 @@ void LastFMService::NowPlaying(const Song &song) { // since it started playing. if (!last_track_.isNull() && last_track_.source() == lastfm::Track::NonPersonalisedBroadcast) { - const int duration_secs = last_track_.timestamp().secsTo(QDateTime::currentDateTime()); + const int duration_secs = + last_track_.timestamp().secsTo(QDateTime::currentDateTime()); if (duration_secs >= lastfm::compat::ScrobbleTimeMin()) { lastfm::MutableTrack mtrack(last_track_); mtrack.setDuration(duration_secs); - qLog(Info) << "Scrobbling stream track" << mtrack.title() << "length" << duration_secs; + qLog(Info) << "Scrobbling stream track" << mtrack.title() << "length" + << duration_secs; scrobbler_->cache(mtrack); scrobbler_->submit(); @@ -527,25 +559,25 @@ void LastFMService::NowPlaying(const Song &song) { #ifndef HAVE_LIBLASTFM1 // Check immediately if the song is valid Scrobble::Invalidity invalidity; - if (!lastfm::Scrobble(last_track_).isValid( &invalidity )) { - //for now just notify this, we can also see the cause + if (!lastfm::Scrobble(last_track_).isValid(&invalidity)) { + // for now just notify this, we can also see the cause emit ScrobbleError(-1); return; } #else - // TODO: validity was removed from liblastfm1 but might reappear, it should have - // no impact as we get a different error when actually trying to scrobble. +// TODO: validity was removed from liblastfm1 but might reappear, it should have +// no impact as we get a different error when actually trying to scrobble. #endif scrobbler_->nowPlaying(mtrack); } void LastFMService::Scrobble() { - if (!InitScrobbler()) - return; + if (!InitScrobbler()) return; lastfm::compat::ScrobbleCache cache(lastfm::ws::Username); - qLog(Debug) << "There are" << cache.tracks().count() << "tracks in the last.fm cache."; + qLog(Debug) << "There are" << cache.tracks().count() + << "tracks in the last.fm cache."; scrobbler_->cache(last_track_); // Let's mark a track as cached, useful when the connection is down @@ -556,8 +588,7 @@ void LastFMService::Scrobble() { } void LastFMService::Love() { - if (!IsAuthenticated()) - ShowConfig(); + if (!IsAuthenticated()) ShowConfig(); lastfm::MutableTrack mtrack(last_track_); mtrack.love(); @@ -580,7 +611,11 @@ void LastFMService::Ban() { } void LastFMService::ShowContextMenu(const QPoint& global_pos) { - switch (model()->current_index().parent().data(InternetModel::Role_Type).toInt()) { + switch (model() + ->current_index() + .parent() + .data(InternetModel::Role_Type) + .toInt()) { case Type_Artists: case Type_Tags: case Type_Custom: @@ -613,7 +648,7 @@ static QStringList SavedArtistOrTagRadioNames(const QString& name) { QSettings s; s.beginGroup(LastFMService::kSettingsGroup); int count = s.beginReadArray(name); - for (int i=0 ; ihasChildren()) friends_list_->removeRows(0, friends_list_->rowCount()); - foreach (const QString& name, friend_names_) { + foreach(const QString & name, friend_names_) { Song song; song.set_url(QUrl("lastfm://user/" + name + "/library")); song.set_title(tr("Last.fm Library - %1").arg(name)); - QStandardItem* item = new QStandardItem(QIcon(":last.fm/icon_user.png"), name); + QStandardItem* item = + new QStandardItem(QIcon(":last.fm/icon_user.png"), name); item->setData(QVariant::fromValue(song), InternetModel::Role_SongMetadata); item->setData(true, InternetModel::Role_CanLazyLoad); item->setData(Type_OtherUser, InternetModel::Role_Type); - item->setData(InternetModel::PlayBehaviour_SingleItem, InternetModel::Role_PlayBehaviour); + item->setData(InternetModel::PlayBehaviour_SingleItem, + InternetModel::Role_PlayBehaviour); friends_list_->appendRow(item); } } @@ -713,36 +743,35 @@ void LastFMService::RefreshNeighboursFinished(QNetworkReply* reply) { if (neighbours_list_->hasChildren()) neighbours_list_->removeRows(0, neighbours_list_->rowCount()); - foreach (const lastfm::User& n, neighbours) { + foreach(const lastfm::User & n, neighbours) { Song song; song.set_url(QUrl("lastfm://user/" + n.name() + "/library")); song.set_title(tr("Last.fm Library - %1").arg(n.name())); - QStandardItem* item = new QStandardItem(QIcon(":last.fm/user_purple.png"), n.name()); + QStandardItem* item = + new QStandardItem(QIcon(":last.fm/user_purple.png"), n.name()); item->setData(QVariant::fromValue(song), InternetModel::Role_SongMetadata); item->setData(true, InternetModel::Role_CanLazyLoad); item->setData(Type_OtherUser, InternetModel::Role_Type); - item->setData(InternetModel::PlayBehaviour_SingleItem, InternetModel::Role_PlayBehaviour); + item->setData(InternetModel::PlayBehaviour_SingleItem, + InternetModel::Role_PlayBehaviour); neighbours_list_->appendRow(item); } } void LastFMService::AddArtistRadio() { - AddArtistOrTag("artists", LastFMStationDialog::Artist, - kUrlArtist, tr(kTitleArtist), - ":last.fm/icon_radio.png", artist_list_); + AddArtistOrTag("artists", LastFMStationDialog::Artist, kUrlArtist, + tr(kTitleArtist), ":last.fm/icon_radio.png", artist_list_); } void LastFMService::AddTagRadio() { - AddArtistOrTag("tags", LastFMStationDialog::Tag, - kUrlTag, tr(kTitleTag), + AddArtistOrTag("tags", LastFMStationDialog::Tag, kUrlTag, tr(kTitleTag), ":last.fm/icon_tag.png", tag_list_); } void LastFMService::AddCustomRadio() { - AddArtistOrTag("custom", LastFMStationDialog::Custom, - kUrlCustom, tr(kTitleCustom), - ":last.fm/icon_radio.png", custom_list_); + AddArtistOrTag("custom", LastFMStationDialog::Custom, kUrlCustom, + tr(kTitleCustom), ":last.fm/icon_radio.png", custom_list_); } void LastFMService::AddArtistOrTag(const QString& name, @@ -751,11 +780,9 @@ void LastFMService::AddArtistOrTag(const QString& name, const QString& title_pattern, const QString& icon, QStandardItem* list) { station_dialog_->SetType(dialog_type); - if (station_dialog_->exec() == QDialog::Rejected) - return; + if (station_dialog_->exec() == QDialog::Rejected) return; - if (station_dialog_->content().isEmpty()) - return; + if (station_dialog_->content().isEmpty()) return; QString content = station_dialog_->content(); QString url; @@ -773,7 +800,8 @@ void LastFMService::AddArtistOrTag(const QString& name, QStandardItem* item = new QStandardItem(QIcon(icon), content); item->setData(QVariant::fromValue(song), InternetModel::Role_SongMetadata); - item->setData(InternetModel::PlayBehaviour_SingleItem, InternetModel::Role_PlayBehaviour); + item->setData(InternetModel::PlayBehaviour_SingleItem, + InternetModel::Role_PlayBehaviour); list->appendRow(item); emit AddItemToPlaylist(item->index(), AddMode_Append); @@ -787,23 +815,21 @@ void LastFMService::SaveList(const QString& name, QStandardItem* list) const { settings.beginGroup(kSettingsGroup); settings.beginWriteArray(name, list->rowCount()); - for (int i=0 ; irowCount() ; ++i) { + for (int i = 0; i < list->rowCount(); ++i) { settings.setArrayIndex(i); settings.setValue("key", list->child(i)->text()); } settings.endArray(); } -void LastFMService::RestoreList(const QString& name, - const QString& url_pattern, - const QString& title_pattern, - const QIcon& icon, QStandardItem* parent) { - if (parent->hasChildren()) - parent->removeRows(0, parent->rowCount()); +void LastFMService::RestoreList(const QString& name, const QString& url_pattern, + const QString& title_pattern, const QIcon& icon, + QStandardItem* parent) { + if (parent->hasChildren()) parent->removeRows(0, parent->rowCount()); const QStringList keys = SavedArtistOrTagRadioNames(name); - foreach (const QString& key, keys) { + foreach(const QString & key, keys) { QString url; if (name == "custom" && key.startsWith("lastfm://")) { url = key; @@ -819,13 +845,15 @@ void LastFMService::RestoreList(const QString& name, QStandardItem* item = new QStandardItem(icon, key); item->setData(QVariant::fromValue(song), InternetModel::Role_SongMetadata); - item->setData(InternetModel::PlayBehaviour_SingleItem, InternetModel::Role_PlayBehaviour); + item->setData(InternetModel::PlayBehaviour_SingleItem, + InternetModel::Role_PlayBehaviour); parent->appendRow(item); } } void LastFMService::Remove() { - QStandardItem* context_item = model()->itemFromIndex(model()->current_index()); + QStandardItem* context_item = + model()->itemFromIndex(model()->current_index()); int type = context_item->parent()->data(InternetModel::Role_Type).toInt(); context_item->parent()->removeRow(context_item->row()); @@ -855,7 +883,7 @@ void LastFMService::FetchMoreTracksFinished(QNetworkReply* reply) { lastfm::XmlQuery query(lastfm::compat::EmptyXmlQuery()); if (lastfm::compat::ParseQuery(reply->readAll(), &query)) { const XmlQuery& playlist = query["playlist"]; - foreach (const XmlQuery& q, playlist["trackList"].children("track")) { + foreach(const XmlQuery & q, playlist["trackList"].children("track")) { lastfm::MutableTrack t; t.setUrl(QUrl(q["location"].text())); t.setExtra("trackauth", q["extension"]["trackauth"].text()); @@ -878,7 +906,8 @@ void LastFMService::FetchMoreTracksFinished(QNetworkReply* reply) { void LastFMService::Tune(const QUrl& url) { if (!tune_task_id_) - tune_task_id_ = app_->task_manager()->StartTask(tr("Loading Last.fm radio")); + tune_task_id_ = + app_->task_manager()->StartTask(tr("Loading Last.fm radio")); last_url_ = url; initial_tune_ = true; @@ -903,8 +932,7 @@ void LastFMService::TuneFinished(QNetworkReply* reply) { } PlaylistItem::Options LastFMService::playlistitem_options() const { - return PlaylistItem::LastFMControls | - PlaylistItem::PauseDisabled | + return PlaylistItem::LastFMControls | PlaylistItem::PauseDisabled | PlaylistItem::SeekDisabled; } @@ -912,15 +940,15 @@ PlaylistItemPtr LastFMService::PlaylistItemForUrl(const QUrl& url) { // This is a bit of a hack, it's only used by the artist/song info tag // widgets for tag radio and similar artists radio. - if (url.scheme() != "lastfm") - return PlaylistItemPtr(); + if (url.scheme() != "lastfm") return PlaylistItemPtr(); QStringList sections(url.path().split("/", QString::SkipEmptyParts)); Song song; song.set_url(url); - if (sections.count() == 2 && url.host() == "artist" && sections[1] == "similarartists") { + if (sections.count() == 2 && url.host() == "artist" && + sections[1] == "similarartists") { song.set_title(tr(kTitleArtist).arg(sections[0])); } else if (sections.count() == 1 && url.host() == "globaltags") { song.set_title(tr(kTitleTag).arg(sections[0])); @@ -932,10 +960,10 @@ PlaylistItemPtr LastFMService::PlaylistItemForUrl(const QUrl& url) { } void LastFMService::ToggleScrobbling() { - //toggle status + // toggle status scrobbling_enabled_ = !scrobbling_enabled_; - //save to the settings + // save to the settings QSettings s; s.beginGroup(kSettingsGroup); s.setValue("ScrobblingEnabled", scrobbling_enabled_); diff --git a/src/internet/lastfmservice.h b/src/internet/lastfmservice.h index 9b832ea7a..485e9a07f 100644 --- a/src/internet/lastfmservice.h +++ b/src/internet/lastfmservice.h @@ -85,7 +85,7 @@ class LastFMService : public InternetService { QStandardItem* CreateRootItem(); void LazyPopulate(QStandardItem* parent); - void ShowContextMenu(const QPoint &global_pos); + void ShowContextMenu(const QPoint& global_pos); PlaylistItem::Options playlistitem_options() const; @@ -126,7 +126,7 @@ class LastFMService : public InternetService { void ShowConfig(); void ToggleScrobbling(); - signals: +signals: void AuthenticationComplete(bool success, const QString& error_message); void ScrobblingEnabledChanged(bool value); void ButtonVisibilityChanged(bool value); @@ -163,9 +163,9 @@ class LastFMService : public InternetService { void StreamMetadataReady(); private: - QStandardItem* CreateStationItem(QStandardItem* parent, - const QString& name, const QString& icon, const QUrl& url, - const QString& title); + QStandardItem* CreateStationItem(QStandardItem* parent, const QString& name, + const QString& icon, const QUrl& url, + const QString& title); QString ErrorString(lastfm::ws::Error error) const; bool InitScrobbler(); lastfm::Track TrackFromSong(const Song& song) const; @@ -173,14 +173,12 @@ class LastFMService : public InternetService { void RefreshNeighbours(); void AddArtistOrTag(const QString& name, LastFMStationDialog::Type dialog_type, - const QString& url_pattern, - const QString& title_pattern, + const QString& url_pattern, const QString& title_pattern, const QString& icon, QStandardItem* list); void SaveList(const QString& name, QStandardItem* list) const; - void RestoreList(const QString& name, - const QString& url_pattern, - const QString& title_pattern, - const QIcon& icon, QStandardItem* parent); + void RestoreList(const QString& name, const QString& url_pattern, + const QString& title_pattern, const QIcon& icon, + QStandardItem* parent); static QUrl FixupUrl(const QUrl& url); void Tune(const QUrl& station); @@ -231,4 +229,4 @@ class LastFMService : public InternetService { bool connection_problems_; }; -#endif // LASTFMSERVICE_H +#endif // LASTFMSERVICE_H diff --git a/src/internet/lastfmsettingspage.cpp b/src/internet/lastfmsettingspage.cpp index e09812e5d..ba55a8a35 100644 --- a/src/internet/lastfmsettingspage.cpp +++ b/src/internet/lastfmsettingspage.cpp @@ -28,19 +28,20 @@ #include LastFMSettingsPage::LastFMSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - service_(static_cast(InternetModel::ServiceByName("Last.fm"))), - ui_(new Ui_LastFMSettingsPage), - waiting_for_auth_(false) -{ + : SettingsPage(dialog), + service_( + static_cast(InternetModel::ServiceByName("Last.fm"))), + ui_(new Ui_LastFMSettingsPage), + waiting_for_auth_(false) { ui_->setupUi(this); // Icons setWindowIcon(QIcon(":/last.fm/as.png")); - connect(service_, SIGNAL(AuthenticationComplete(bool,QString)), - SLOT(AuthenticationComplete(bool,QString))); - connect(service_, SIGNAL(UpdatedSubscriberStatus(bool)), SLOT(UpdatedSubscriberStatus(bool))); + connect(service_, SIGNAL(AuthenticationComplete(bool, QString)), + SLOT(AuthenticationComplete(bool, QString))); + connect(service_, SIGNAL(UpdatedSubscriberStatus(bool)), + SLOT(UpdatedSubscriberStatus(bool))); connect(ui_->login_state, SIGNAL(LogoutClicked()), SLOT(Logout())); connect(ui_->login_state, SIGNAL(LoginClicked()), SLOT(Login())); connect(ui_->login, SIGNAL(clicked()), SLOT(Login())); @@ -53,9 +54,7 @@ LastFMSettingsPage::LastFMSettingsPage(SettingsDialog* dialog) resize(sizeHint()); } -LastFMSettingsPage::~LastFMSettingsPage() { - delete ui_; -} +LastFMSettingsPage::~LastFMSettingsPage() { delete ui_; } void LastFMSettingsPage::Login() { waiting_for_auth_ = true; @@ -66,8 +65,7 @@ void LastFMSettingsPage::Login() { void LastFMSettingsPage::AuthenticationComplete(bool success, const QString& message) { - if (!waiting_for_auth_) - return; // Wasn't us that was waiting for auth + if (!waiting_for_auth_) return; // Wasn't us that was waiting for auth waiting_for_auth_ = false; @@ -107,12 +105,14 @@ void LastFMSettingsPage::UpdatedSubscriberStatus(bool is_subscriber) { if (!is_subscriber) { if (service_->HasConnectionProblems()) { ui_->login_state->SetAccountTypeText( - tr("Clementine couldn't fetch your subscription status since there are problems " - "with your connection. Played tracks will be cached and sent later to Last.fm.")); + tr("Clementine couldn't fetch your subscription status since there " + "are problems " + "with your connection. Played tracks will be cached and sent " + "later to Last.fm.")); } else { ui_->login_state->SetAccountTypeText( - tr("You will not be able to play Last.fm radio stations " - "as you are not a Last.fm subscriber.")); + tr("You will not be able to play Last.fm radio stations " + "as you are not a Last.fm subscriber.")); } } } @@ -138,9 +138,9 @@ void LastFMSettingsPage::Logout() { } void LastFMSettingsPage::RefreshControls(bool authenticated) { - ui_->login_state->SetLoggedIn(authenticated ? LoginStateWidget::LoggedIn - : LoginStateWidget::LoggedOut, - lastfm::ws::Username); + ui_->login_state->SetLoggedIn( + authenticated ? LoginStateWidget::LoggedIn : LoginStateWidget::LoggedOut, + lastfm::ws::Username); ui_->login_state->SetAccountTypeVisible(!authenticated); if (!authenticated) { diff --git a/src/internet/lastfmsettingspage.h b/src/internet/lastfmsettingspage.h index 30bbb604f..329be560b 100644 --- a/src/internet/lastfmsettingspage.h +++ b/src/internet/lastfmsettingspage.h @@ -26,20 +26,20 @@ class Ui_LastFMSettingsPage; class LastFMSettingsPage : public SettingsPage { Q_OBJECT -public: + public: LastFMSettingsPage(SettingsDialog* dialog); ~LastFMSettingsPage(); void Load(); void Save(); -private slots: + private slots: void Login(); void AuthenticationComplete(bool success, const QString& error_message); void Logout(); void UpdatedSubscriberStatus(bool is_subscriber); -private: + private: LastFMService* service_; Ui_LastFMSettingsPage* ui_; QMovie* loading_icon_; @@ -49,4 +49,4 @@ private: void RefreshControls(bool authenticated); }; -#endif // LASTFMSETTINGSPAGE_H +#endif // LASTFMSETTINGSPAGE_H diff --git a/src/internet/lastfmstationdialog.cpp b/src/internet/lastfmstationdialog.cpp index 86fa75228..2a16dc3b3 100644 --- a/src/internet/lastfmstationdialog.cpp +++ b/src/internet/lastfmstationdialog.cpp @@ -19,17 +19,13 @@ #include "ui_lastfmstationdialog.h" LastFMStationDialog::LastFMStationDialog(QWidget* parent) - : QDialog(parent), - ui_(new Ui_LastFMStationDialog) -{ + : QDialog(parent), ui_(new Ui_LastFMStationDialog) { ui_->setupUi(this); resize(sizeHint()); } -LastFMStationDialog::~LastFMStationDialog() { - delete ui_; -} +LastFMStationDialog::~LastFMStationDialog() { delete ui_; } void LastFMStationDialog::SetType(Type type) { ui_->type->setCurrentIndex(type); @@ -37,6 +33,4 @@ void LastFMStationDialog::SetType(Type type) { ui_->content->setFocus(Qt::OtherFocusReason); } -QString LastFMStationDialog::content() const { - return ui_->content->text(); -} +QString LastFMStationDialog::content() const { return ui_->content->text(); } diff --git a/src/internet/lastfmstationdialog.h b/src/internet/lastfmstationdialog.h index 67d6cf9b2..de2ce3990 100644 --- a/src/internet/lastfmstationdialog.h +++ b/src/internet/lastfmstationdialog.h @@ -29,11 +29,7 @@ class LastFMStationDialog : public QDialog { LastFMStationDialog(QWidget* parent = 0); ~LastFMStationDialog(); - enum Type { - Artist, - Tag, - Custom, - }; + enum Type { Artist, Tag, Custom, }; void SetType(Type type); QString content() const; @@ -42,4 +38,4 @@ class LastFMStationDialog : public QDialog { Ui_LastFMStationDialog* ui_; }; -#endif // LASTFMSTATIONDIALOG_H +#endif // LASTFMSTATIONDIALOG_H diff --git a/src/internet/lastfmurlhandler.cpp b/src/internet/lastfmurlhandler.cpp index 5617fb9e2..2750c2294 100644 --- a/src/internet/lastfmurlhandler.cpp +++ b/src/internet/lastfmurlhandler.cpp @@ -19,13 +19,10 @@ #include "lastfmurlhandler.h" LastFMUrlHandler::LastFMUrlHandler(LastFMService* service, QObject* parent) - : UrlHandler(parent), - service_(service) { -} + : UrlHandler(parent), service_(service) {} UrlHandler::LoadResult LastFMUrlHandler::StartLoading(const QUrl& url) { - if (!service_->IsAuthenticated()) - return LoadResult(); + if (!service_->IsAuthenticated()) return LoadResult(); service_->Tune(url); return LoadResult(url, LoadResult::WillLoadAsynchronously); @@ -36,7 +33,8 @@ void LastFMUrlHandler::TunerTrackAvailable() { } void LastFMUrlHandler::TunerError() { - emit AsyncLoadComplete(LoadResult(service_->last_url_, LoadResult::NoMoreTracks)); + emit AsyncLoadComplete( + LoadResult(service_->last_url_, LoadResult::NoMoreTracks)); } UrlHandler::LoadResult LastFMUrlHandler::LoadNext(const QUrl& url) { diff --git a/src/internet/lastfmurlhandler.h b/src/internet/lastfmurlhandler.h index 3f3bf174b..4cfcb9757 100644 --- a/src/internet/lastfmurlhandler.h +++ b/src/internet/lastfmurlhandler.h @@ -22,11 +22,10 @@ class LastFMService; - class LastFMUrlHandler : public UrlHandler { friend class LastFMService; -public: + public: LastFMUrlHandler(LastFMService* service, QObject* parent); QString scheme() const { return "lastfm"; } @@ -37,8 +36,8 @@ public: void TunerTrackAvailable(); void TunerError(); -private: + private: LastFMService* service_; }; -#endif // LASTFMURLHANDLER_H +#endif // LASTFMURLHANDLER_H diff --git a/src/internet/localredirectserver.cpp b/src/internet/localredirectserver.cpp index ca51892ba..b961385d3 100644 --- a/src/internet/localredirectserver.cpp +++ b/src/internet/localredirectserver.cpp @@ -11,9 +11,7 @@ #include "core/closure.h" LocalRedirectServer::LocalRedirectServer(QObject* parent) - : QObject(parent), - server_(new QTcpServer(this)) { -} + : QObject(parent), server_(new QTcpServer(this)) {} void LocalRedirectServer::Listen() { server_->listen(QHostAddress::LocalHost); @@ -31,8 +29,8 @@ void LocalRedirectServer::NewConnection() { server_->close(); QByteArray buffer; - NewClosure(socket, SIGNAL(readyRead()), - this, SLOT(ReadyRead(QTcpSocket*,QByteArray)), socket, buffer); + NewClosure(socket, SIGNAL(readyRead()), this, + SLOT(ReadyRead(QTcpSocket*, QByteArray)), socket, buffer); } void LocalRedirectServer::ReadyRead(QTcpSocket* socket, QByteArray buffer) { @@ -43,8 +41,8 @@ void LocalRedirectServer::ReadyRead(QTcpSocket* socket, QByteArray buffer) { request_url_ = ParseUrlFromRequest(buffer); emit Finished(); } else { - NewClosure(socket, SIGNAL(readyRead()), - this, SLOT(ReadyReady(QTcpSocket*,QByteArray)), socket, buffer); + NewClosure(socket, SIGNAL(readyRead()), this, + SLOT(ReadyReady(QTcpSocket*, QByteArray)), socket, buffer); } } @@ -68,8 +66,11 @@ void LocalRedirectServer::WriteTemplate(QTcpSocket* socket) const { QBuffer image_buffer; image_buffer.open(QIODevice::ReadWrite); - QApplication::style()->standardIcon(QStyle::SP_DialogOkButton) - .pixmap(16).toImage().save(&image_buffer, "PNG"); + QApplication::style() + ->standardIcon(QStyle::SP_DialogOkButton) + .pixmap(16) + .toImage() + .save(&image_buffer, "PNG"); page_data.replace("@IMAGE_DATA@", image_buffer.data().toBase64()); socket->write("HTTP/1.0 200 OK\r\n"); diff --git a/src/internet/localredirectserver.h b/src/internet/localredirectserver.h index 2c6993add..77138a242 100644 --- a/src/internet/localredirectserver.h +++ b/src/internet/localredirectserver.h @@ -22,8 +22,7 @@ class LocalRedirectServer : public QObject { // Returns the URL requested by the OAuth redirect. const QUrl& request_url() const { return request_url_; } - - signals: +signals: void Finished(); private slots: diff --git a/src/internet/magnatunedownloaddialog.cpp b/src/internet/magnatunedownloaddialog.cpp index d8d92aca7..69ed878e0 100644 --- a/src/internet/magnatunedownloaddialog.cpp +++ b/src/internet/magnatunedownloaddialog.cpp @@ -39,14 +39,13 @@ #include "widgets/progressitemdelegate.h" MagnatuneDownloadDialog::MagnatuneDownloadDialog(MagnatuneService* service, - QWidget *parent) - : QDialog(parent), - ui_(new Ui_MagnatuneDownloadDialog), - service_(service), - network_(new NetworkAccessManager(this)), - current_reply_(nullptr), - next_row_(0) -{ + QWidget* parent) + : QDialog(parent), + ui_(new Ui_MagnatuneDownloadDialog), + service_(service), + network_(new NetworkAccessManager(this)), + current_reply_(nullptr), + next_row_(0) { ui_->setupUi(this); ui_->albums->header()->setResizeMode(QHeaderView::ResizeToContents); ui_->albums->header()->setResizeMode(1, QHeaderView::Fixed); @@ -71,7 +70,7 @@ void MagnatuneDownloadDialog::Show(const SongList& songs) { ui_->albums->clear(); QSet sku_codes; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { if (!sku_codes.contains(song.comment())) { sku_codes.insert(song.comment()); @@ -101,7 +100,7 @@ void MagnatuneDownloadDialog::accept() { ui_->options->setEnabled(false); // Reset all the progress bars - for (int i=0 ; ialbums->topLevelItemCount() ; ++i) { + for (int i = 0; i < ui_->albums->topLevelItemCount(); ++i) { ui_->albums->topLevelItem(i)->setData(1, Qt::DisplayRole, QVariant()); } @@ -130,7 +129,8 @@ void MagnatuneDownloadDialog::DownloadNext() { current_reply_ = network_->get(QNetworkRequest(url)); - connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(Error(QNetworkReply::NetworkError))); + connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), + SLOT(Error(QNetworkReply::NetworkError))); connect(current_reply_, SIGNAL(finished()), SLOT(MetadataFinished())); } @@ -144,8 +144,8 @@ void MagnatuneDownloadDialog::Error(QNetworkReply::NetworkError e) { QMetaEnum error_enum = QNetworkReply::staticMetaObject.enumerator( QNetworkReply::staticMetaObject.indexOfEnumerator("NetworkError")); - QString message = tr("Unable to download %1 (%2)") - .arg(url.toString()).arg(error_enum.valueToKey(e)); + QString message = tr("Unable to download %1 (%2)").arg(url.toString()).arg( + error_enum.valueToKey(e)); ShowError(message); } @@ -165,11 +165,21 @@ void MagnatuneDownloadDialog::MetadataFinished() { // Work out what format we want QString type; switch (ui_->format->currentIndex()) { - case MagnatuneService::Format_Ogg: type = "URL_OGGZIP"; break; - case MagnatuneService::Format_Flac: type = "URL_FLACZIP"; break; - case MagnatuneService::Format_Wav: type = "URL_WAVZIP"; break; - case MagnatuneService::Format_MP3_VBR: type = "URL_VBRZIP"; break; - case MagnatuneService::Format_MP3_128: type = "URL_128KMP3ZIP"; break; + case MagnatuneService::Format_Ogg: + type = "URL_OGGZIP"; + break; + case MagnatuneService::Format_Flac: + type = "URL_FLACZIP"; + break; + case MagnatuneService::Format_Wav: + type = "URL_WAVZIP"; + break; + case MagnatuneService::Format_MP3_VBR: + type = "URL_VBRZIP"; + break; + case MagnatuneService::Format_MP3_128: + type = "URL_128KMP3ZIP"; + break; } // Parse the XML (lol) to find the URL @@ -191,9 +201,11 @@ void MagnatuneDownloadDialog::MetadataFinished() { // Start the actual download current_reply_ = network_->get(QNetworkRequest(url)); - connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(Error(QNetworkReply::NetworkError))); + connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), + SLOT(Error(QNetworkReply::NetworkError))); connect(current_reply_, SIGNAL(finished()), SLOT(DownloadFinished())); - connect(current_reply_, SIGNAL(downloadProgress(qint64,qint64)), SLOT(DownloadProgress(qint64,qint64))); + connect(current_reply_, SIGNAL(downloadProgress(qint64, qint64)), + SLOT(DownloadProgress(qint64, qint64))); connect(current_reply_, SIGNAL(readyRead()), SLOT(DownloadReadyRead())); // Close any open file @@ -210,7 +222,7 @@ void MagnatuneDownloadDialog::MetadataFinished() { void MagnatuneDownloadDialog::DownloadFinished() { current_reply_->deleteLater(); - next_row_ ++; + next_row_++; DownloadNext(); } @@ -224,7 +236,7 @@ void MagnatuneDownloadDialog::DownloadReadyRead() { download_file_->write(reply->readAll()); } -void MagnatuneDownloadDialog::ShowError(const QString &message) { +void MagnatuneDownloadDialog::ShowError(const QString& message) { QMessageBox::critical(this, tr("Error"), message, QMessageBox::Close); AllFinished(true); } @@ -232,8 +244,7 @@ void MagnatuneDownloadDialog::ShowError(const QString &message) { void MagnatuneDownloadDialog::AllFinished(bool error) { current_reply_ = nullptr; - if (error) - ui_->button_box->button(QDialogButtonBox::Ok)->show(); + if (error) ui_->button_box->button(QDialogButtonBox::Ok)->show(); ui_->button_box->button(QDialogButtonBox::Close)->show(); ui_->button_box->button(QDialogButtonBox::Cancel)->hide(); ui_->options->setEnabled(true); @@ -243,7 +254,7 @@ void MagnatuneDownloadDialog::AllFinished(bool error) { if (!error) { QStringList albums; - for (int i=0 ; ialbums->topLevelItemCount() ; ++i) { + for (int i = 0; i < ui_->albums->topLevelItemCount(); ++i) { albums << ui_->albums->topLevelItem(i)->text(0); } emit Finished(albums); @@ -266,11 +277,21 @@ QString MagnatuneDownloadDialog::GetOutputFilename() { QString extension; switch (MagnatuneService::PreferredFormat(ui_->format->currentIndex())) { - case MagnatuneService::Format_Ogg: extension = "ogg"; break; - case MagnatuneService::Format_Flac: extension = "flac"; break; - case MagnatuneService::Format_Wav: extension = "wav"; break; - case MagnatuneService::Format_MP3_VBR: extension = "vbr"; break; - case MagnatuneService::Format_MP3_128: extension = "mp3"; break; + case MagnatuneService::Format_Ogg: + extension = "ogg"; + break; + case MagnatuneService::Format_Flac: + extension = "flac"; + break; + case MagnatuneService::Format_Wav: + extension = "wav"; + break; + case MagnatuneService::Format_MP3_VBR: + extension = "vbr"; + break; + case MagnatuneService::Format_MP3_128: + extension = "mp3"; + break; } return QString("%1/%2-%3.zip").arg(ui_->directory->text(), album, extension); @@ -278,10 +299,10 @@ QString MagnatuneDownloadDialog::GetOutputFilename() { void MagnatuneDownloadDialog::closeEvent(QCloseEvent* e) { if (current_reply_ && current_reply_->isRunning()) { - std::unique_ptr message_box(new QMessageBox( - QMessageBox::Question, tr("Really cancel?"), - tr("Closing this window will cancel the download."), - QMessageBox::Abort, this)); + std::unique_ptr message_box( + new QMessageBox(QMessageBox::Question, tr("Really cancel?"), + tr("Closing this window will cancel the download."), + QMessageBox::Abort, this)); message_box->addButton(tr("Don't stop!"), QMessageBox::AcceptRole); if (message_box->exec() != QMessageBox::Abort) { diff --git a/src/internet/magnatunedownloaddialog.h b/src/internet/magnatunedownloaddialog.h index 7c0ffb438..d9743f5f9 100644 --- a/src/internet/magnatunedownloaddialog.h +++ b/src/internet/magnatunedownloaddialog.h @@ -34,8 +34,8 @@ class QXmlStreamReader; class MagnatuneDownloadDialog : public QDialog { Q_OBJECT -public: - MagnatuneDownloadDialog(MagnatuneService* service, QWidget *parent = 0); + public: + MagnatuneDownloadDialog(MagnatuneService* service, QWidget* parent = 0); ~MagnatuneDownloadDialog(); void Show(const SongList& songs); @@ -43,13 +43,13 @@ public: signals: void Finished(const QStringList& albums); -public slots: + public slots: void accept(); -protected: + protected: void closeEvent(QCloseEvent* e); -private slots: + private slots: void Browse(); void DownloadNext(); @@ -62,10 +62,10 @@ private slots: void ShowError(const QString& message); void AllFinished(bool error); -private: + private: QString GetOutputFilename(); -private: + private: Ui_MagnatuneDownloadDialog* ui_; MagnatuneService* service_; @@ -76,4 +76,4 @@ private: int next_row_; }; -#endif // MAGNATUNEDOWNLOADDIALOG_H +#endif // MAGNATUNEDOWNLOADDIALOG_H diff --git a/src/internet/magnatuneplaylistitem.cpp b/src/internet/magnatuneplaylistitem.cpp index 5702c8df6..c582517c6 100644 --- a/src/internet/magnatuneplaylistitem.cpp +++ b/src/internet/magnatuneplaylistitem.cpp @@ -19,13 +19,10 @@ #include "internetmodel.h" MagnatunePlaylistItem::MagnatunePlaylistItem(const QString& type) - : LibraryPlaylistItem(type) -{ -} + : LibraryPlaylistItem(type) {} MagnatunePlaylistItem::MagnatunePlaylistItem(const Song& song) - : LibraryPlaylistItem("Magnatune") -{ + : LibraryPlaylistItem("Magnatune") { song_ = song; } @@ -36,6 +33,4 @@ bool MagnatunePlaylistItem::InitFromQuery(const SqlRow& query) { return song_.is_valid(); } -QUrl MagnatunePlaylistItem::Url() const { - return song_.url(); -} +QUrl MagnatunePlaylistItem::Url() const { return song_.url(); } diff --git a/src/internet/magnatuneplaylistitem.h b/src/internet/magnatuneplaylistitem.h index c7066ddc1..e6b0f3ba2 100644 --- a/src/internet/magnatuneplaylistitem.h +++ b/src/internet/magnatuneplaylistitem.h @@ -30,4 +30,4 @@ class MagnatunePlaylistItem : public LibraryPlaylistItem { QUrl Url() const; }; -#endif // MAGNATUNEPLAYLISTITEM_H +#endif // MAGNATUNEPLAYLISTITEM_H diff --git a/src/internet/magnatuneservice.cpp b/src/internet/magnatuneservice.cpp index fe661be2f..a776eec12 100644 --- a/src/internet/magnatuneservice.cpp +++ b/src/internet/magnatuneservice.cpp @@ -57,33 +57,34 @@ const char* MagnatuneService::kSongsTable = "magnatune_songs"; const char* MagnatuneService::kFtsTable = "magnatune_songs_fts"; const char* MagnatuneService::kHomepage = "http://magnatune.com"; -const char* MagnatuneService::kDatabaseUrl = "http://magnatune.com/info/song_info_xml.gz"; +const char* MagnatuneService::kDatabaseUrl = + "http://magnatune.com/info/song_info_xml.gz"; const char* MagnatuneService::kStreamingHostname = "streaming.magnatune.com"; const char* MagnatuneService::kDownloadHostname = "download.magnatune.com"; const char* MagnatuneService::kPartnerId = "clementine"; -const char* MagnatuneService::kDownloadUrl = "http://download.magnatune.com/buy/membership_free_dl_xml"; +const char* MagnatuneService::kDownloadUrl = + "http://download.magnatune.com/buy/membership_free_dl_xml"; MagnatuneService::MagnatuneService(Application* app, InternetModel* parent) - : InternetService(kServiceName, app, parent, parent), - url_handler_(new MagnatuneUrlHandler(this, this)), - context_menu_(nullptr), - root_(nullptr), - library_backend_(nullptr), - library_model_(nullptr), - library_filter_(nullptr), - library_sort_model_(new QSortFilterProxyModel(this)), - load_database_task_id_(0), - membership_(Membership_None), - format_(Format_Ogg), - total_song_count_(0), - network_(new NetworkAccessManager(this)) -{ + : InternetService(kServiceName, app, parent, parent), + url_handler_(new MagnatuneUrlHandler(this, this)), + context_menu_(nullptr), + root_(nullptr), + library_backend_(nullptr), + library_model_(nullptr), + library_filter_(nullptr), + library_sort_model_(new QSortFilterProxyModel(this)), + load_database_task_id_(0), + membership_(Membership_None), + format_(Format_Ogg), + total_song_count_(0), + network_(new NetworkAccessManager(this)) { // Create the library backend in the database thread library_backend_ = new LibraryBackend; library_backend_->moveToThread(app_->database()->thread()); - library_backend_->Init(app_->database(), kSongsTable, - QString::null, QString::null, kFtsTable); + library_backend_->Init(app_->database(), kSongsTable, QString::null, + QString::null, kFtsTable); library_model_ = new LibraryModel(library_backend_, app_, this); connect(library_backend_, SIGNAL(TotalSongCountUpdated(int)), @@ -97,16 +98,11 @@ MagnatuneService::MagnatuneService(Application* app, InternetModel* parent) app_->player()->RegisterUrlHandler(url_handler_); app_->global_search()->AddProvider(new LibrarySearchProvider( - library_backend_, - tr("Magnatune"), - "magnatune", - QIcon(":/providers/magnatune.png"), - true, app_, this)); + library_backend_, tr("Magnatune"), "magnatune", + QIcon(":/providers/magnatune.png"), true, app_, this)); } -MagnatuneService::~MagnatuneService() { - delete context_menu_; -} +MagnatuneService::~MagnatuneService() { delete context_menu_; } void MagnatuneService::ReloadSettings() { QSettings s; @@ -150,10 +146,10 @@ void MagnatuneService::ReloadDatabase() { QNetworkReply* reply = network_->get(request); connect(reply, SIGNAL(finished()), SLOT(ReloadDatabaseFinished())); - + if (!load_database_task_id_) - load_database_task_id_ = app_->task_manager()->StartTask( - tr("Downloading Magnatune catalogue")); + load_database_task_id_ = + app_->task_manager()->StartTask(tr("Downloading Magnatune catalogue")); } void MagnatuneService::ReloadDatabaseFinished() { @@ -168,8 +164,7 @@ void MagnatuneService::ReloadDatabaseFinished() { return; } - if (root_->hasChildren()) - root_->removeRows(0, root_->rowCount()); + if (root_->hasChildren()) root_->removeRows(0, root_->rowCount()); // The XML file is compressed QtIOCompressor gzip(reply); @@ -205,22 +200,22 @@ Song MagnatuneService::ReadTrack(QXmlStreamReader& reader) { while (!reader.atEnd()) { reader.readNext(); - if (reader.tokenType() == QXmlStreamReader::EndElement) - break; + if (reader.tokenType() == QXmlStreamReader::EndElement) break; if (reader.tokenType() == QXmlStreamReader::StartElement) { QStringRef name = reader.name(); QString value = ReadElementText(reader); - if (name == "artist") song.set_artist(value); - if (name == "albumname") song.set_album(value); - if (name == "trackname") song.set_title(value); - if (name == "tracknum") song.set_track(value.toInt()); - if (name == "year") song.set_year(value.toInt()); + if (name == "artist") song.set_artist(value); + if (name == "albumname") song.set_album(value); + if (name == "trackname") song.set_title(value); + if (name == "tracknum") song.set_track(value.toInt()); + if (name == "year") song.set_year(value.toInt()); if (name == "magnatunegenres") song.set_genre(value.section(',', 0, 0)); - if (name == "seconds") song.set_length_nanosec(value.toInt() * kNsecPerSec); - if (name == "cover_small") song.set_art_automatic(value); - if (name == "albumsku") song.set_comment(value); + if (name == "seconds") + song.set_length_nanosec(value.toInt() * kNsecPerSec); + if (name == "cover_small") song.set_art_automatic(value); + if (name == "albumsku") song.set_comment(value); if (name == "url") { QUrl url; // Magnatune's URLs are already encoded @@ -249,33 +244,43 @@ QString MagnatuneService::ReadElementText(QXmlStreamReader& reader) { QString ret; while (!reader.atEnd()) { switch (reader.readNext()) { - case QXmlStreamReader::StartElement: level++; break; - case QXmlStreamReader::EndElement: level--; break; + case QXmlStreamReader::StartElement: + level++; + break; + case QXmlStreamReader::EndElement: + level--; + break; case QXmlStreamReader::Characters: ret += reader.text().toString().trimmed(); break; - default: break; + default: + break; } - if (level == 0) - break; + if (level == 0) break; } return ret; } void MagnatuneService::EnsureMenuCreated() { - if (context_menu_) - return; + if (context_menu_) return; context_menu_ = new QMenu; context_menu_->addActions(GetPlaylistActions()); - download_ = context_menu_->addAction( - IconLoader::Load("download"), tr("Download this album"), this, SLOT(Download())); + download_ = context_menu_->addAction(IconLoader::Load("download"), + tr("Download this album"), this, + SLOT(Download())); context_menu_->addSeparator(); - context_menu_->addAction(IconLoader::Load("download"), tr("Open %1 in browser").arg("magnatune.com"), this, SLOT(Homepage())); - context_menu_->addAction(IconLoader::Load("view-refresh"), tr("Refresh catalogue"), this, SLOT(ReloadDatabase())); - QAction* config_action = context_menu_->addAction(IconLoader::Load("configure"), tr("Configure Magnatune..."), this, SLOT(ShowConfig())); + context_menu_->addAction(IconLoader::Load("download"), + tr("Open %1 in browser").arg("magnatune.com"), this, + SLOT(Homepage())); + context_menu_->addAction(IconLoader::Load("view-refresh"), + tr("Refresh catalogue"), this, + SLOT(ReloadDatabase())); + QAction* config_action = context_menu_->addAction( + IconLoader::Load("configure"), tr("Configure Magnatune..."), this, + SLOT(ShowConfig())); library_filter_ = new LibraryFilterWidget(0); library_filter_->SetSettingsGroup(kSettingsGroup); @@ -308,9 +313,9 @@ QUrl MagnatuneService::ModifyUrl(const QUrl& url) const { QUrl ret(url); ret.setScheme("http"); - switch(membership_) { + switch (membership_) { case Membership_None: - return ret; // Use the URL as-is + return ret; // Use the URL as-is // Otherwise add the hostname case Membership_Streaming: @@ -338,14 +343,16 @@ void MagnatuneService::ShowConfig() { } void MagnatuneService::Download() { - QModelIndex index = library_sort_model_->mapToSource(model()->current_index()); + QModelIndex index = + library_sort_model_->mapToSource(model()->current_index()); SongList songs = library_model_->GetChildSongs(index); MagnatuneDownloadDialog* dialog = new MagnatuneDownloadDialog(this, 0); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->Show(songs); - connect(dialog, SIGNAL(Finished(QStringList)), SIGNAL(DownloadFinished(QStringList))); + connect(dialog, SIGNAL(Finished(QStringList)), + SIGNAL(DownloadFinished(QStringList))); } QWidget* MagnatuneService::HeaderWidget() const { diff --git a/src/internet/magnatuneservice.h b/src/internet/magnatuneservice.h index bb70a6d94..4050d926c 100644 --- a/src/internet/magnatuneservice.h +++ b/src/internet/magnatuneservice.h @@ -86,7 +86,7 @@ class MagnatuneService : public InternetService { QUrl ModifyUrl(const QUrl& url) const; - signals: +signals: void DownloadFinished(const QStringList& albums); private slots: @@ -127,4 +127,4 @@ class MagnatuneService : public InternetService { QNetworkAccessManager* network_; }; -#endif // MAGNATUNESERVICE_H +#endif // MAGNATUNESERVICE_H diff --git a/src/internet/magnatunesettingspage.cpp b/src/internet/magnatunesettingspage.cpp index 58eafb07f..e87db600a 100644 --- a/src/internet/magnatunesettingspage.cpp +++ b/src/internet/magnatunesettingspage.cpp @@ -29,17 +29,18 @@ #include MagnatuneSettingsPage::MagnatuneSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - network_(new NetworkAccessManager(this)), - ui_(new Ui_MagnatuneSettingsPage), - logged_in_(false) -{ + : SettingsPage(dialog), + network_(new NetworkAccessManager(this)), + ui_(new Ui_MagnatuneSettingsPage), + logged_in_(false) { ui_->setupUi(this); setWindowIcon(QIcon(":/providers/magnatune.png")); - connect(ui_->membership, SIGNAL(currentIndexChanged(int)), SLOT(MembershipChanged(int))); + connect(ui_->membership, SIGNAL(currentIndexChanged(int)), + SLOT(MembershipChanged(int))); - connect(network_, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), + connect(network_, + SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), SLOT(AuthenticationRequired(QNetworkReply*, QAuthenticator*))); connect(ui_->login, SIGNAL(clicked()), SLOT(Login())); connect(ui_->login_state, SIGNAL(LoginClicked()), SLOT(Login())); @@ -49,22 +50,21 @@ MagnatuneSettingsPage::MagnatuneSettingsPage(SettingsDialog* dialog) ui_->login_state->AddCredentialField(ui_->password); ui_->login_state->AddCredentialGroup(ui_->login_container); - ui_->login_state->SetAccountTypeText(tr( - "You can listen to Magnatune songs for free without an account. " - "Purchasing a membership removes the messages at the end of each track.")); + ui_->login_state->SetAccountTypeText( + tr("You can listen to Magnatune songs for free without an account. " + "Purchasing a membership removes the messages at the end of each " + "track.")); } -MagnatuneSettingsPage::~MagnatuneSettingsPage() { - delete ui_; -} +MagnatuneSettingsPage::~MagnatuneSettingsPage() { delete ui_; } const char* kMagnatuneDownloadValidateUrl = "http://download.magnatune.com/"; const char* kMagnatuneStreamingValidateUrl = "http://streaming.magnatune.com/"; void MagnatuneSettingsPage::UpdateLoginState() { - ui_->login_state->SetLoggedIn(logged_in_ ? LoginStateWidget::LoggedIn - : LoginStateWidget::LoggedOut, - ui_->username->text()); + ui_->login_state->SetLoggedIn( + logged_in_ ? LoginStateWidget::LoggedIn : LoginStateWidget::LoggedOut, + ui_->username->text()); ui_->login_state->SetAccountTypeVisible(!logged_in_); } @@ -72,9 +72,9 @@ void MagnatuneSettingsPage::Login() { MagnatuneService::MembershipType type = MagnatuneService::MembershipType(ui_->membership->currentIndex()); - QUrl url(type == MagnatuneService::Membership_Streaming ? - kMagnatuneStreamingValidateUrl : - kMagnatuneDownloadValidateUrl, + QUrl url(type == MagnatuneService::Membership_Streaming + ? kMagnatuneStreamingValidateUrl + : kMagnatuneDownloadValidateUrl, QUrl::StrictMode); url.setUserName(ui_->username->text()); @@ -109,8 +109,8 @@ void MagnatuneSettingsPage::LoginFinished() { reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200; if (!logged_in_) { - QMessageBox::warning( - this, tr("Authentication failed"), tr("Your Magnatune credentials were incorrect")); + QMessageBox::warning(this, tr("Authentication failed"), + tr("Your Magnatune credentials were incorrect")); } else { Save(); } @@ -118,8 +118,8 @@ void MagnatuneSettingsPage::LoginFinished() { UpdateLoginState(); } -void MagnatuneSettingsPage::AuthenticationRequired( - QNetworkReply* reply, QAuthenticator*) { +void MagnatuneSettingsPage::AuthenticationRequired(QNetworkReply* reply, + QAuthenticator*) { // We send the authentication with the first request so this means we got // a 401 Authentication Required, ie. the credentials are incorrect. reply->abort(); @@ -129,13 +129,15 @@ void MagnatuneSettingsPage::Load() { QSettings s; s.beginGroup(MagnatuneService::kSettingsGroup); - ui_->membership->setCurrentIndex(s.value("membership", MagnatuneService::Membership_None).toInt()); + ui_->membership->setCurrentIndex( + s.value("membership", MagnatuneService::Membership_None).toInt()); ui_->username->setText(s.value("username").toString()); ui_->password->setText(s.value("password").toString()); - ui_->format->setCurrentIndex(s.value("format", MagnatuneService::Format_Ogg).toInt()); - logged_in_ = s.value("logged_in", - !ui_->username->text().isEmpty() && - !ui_->password->text().isEmpty()).toBool(); + ui_->format->setCurrentIndex( + s.value("format", MagnatuneService::Format_Ogg).toInt()); + logged_in_ = + s.value("logged_in", !ui_->username->text().isEmpty() && + !ui_->password->text().isEmpty()).toBool(); UpdateLoginState(); } diff --git a/src/internet/magnatunesettingspage.h b/src/internet/magnatunesettingspage.h index 352996d1d..e9231ee8e 100644 --- a/src/internet/magnatunesettingspage.h +++ b/src/internet/magnatunesettingspage.h @@ -28,28 +28,28 @@ class Ui_MagnatuneSettingsPage; class MagnatuneSettingsPage : public SettingsPage { Q_OBJECT -public: + public: MagnatuneSettingsPage(SettingsDialog* dialog); ~MagnatuneSettingsPage(); void Load(); void Save(); -private slots: + private slots: void Login(); void Logout(); void MembershipChanged(int value); void LoginFinished(); void AuthenticationRequired(QNetworkReply* reply, QAuthenticator* auth); -private: + private: void UpdateLoginState(); -private: + private: NetworkAccessManager* network_; Ui_MagnatuneSettingsPage* ui_; bool logged_in_; }; -#endif // MAGNATUNESETTINGSPAGE_H +#endif // MAGNATUNESETTINGSPAGE_H diff --git a/src/internet/magnatuneurlhandler.cpp b/src/internet/magnatuneurlhandler.cpp index 86785557a..c98ca552b 100644 --- a/src/internet/magnatuneurlhandler.cpp +++ b/src/internet/magnatuneurlhandler.cpp @@ -18,10 +18,9 @@ #include "magnatuneservice.h" #include "magnatuneurlhandler.h" -MagnatuneUrlHandler::MagnatuneUrlHandler(MagnatuneService* service, QObject* parent) - : UrlHandler(parent), - service_(service) { -} +MagnatuneUrlHandler::MagnatuneUrlHandler(MagnatuneService* service, + QObject* parent) + : UrlHandler(parent), service_(service) {} UrlHandler::LoadResult MagnatuneUrlHandler::StartLoading(const QUrl& url) { return LoadResult(url, LoadResult::TrackAvailable, service_->ModifyUrl(url)); diff --git a/src/internet/magnatuneurlhandler.h b/src/internet/magnatuneurlhandler.h index 0d00fc196..e971c05fb 100644 --- a/src/internet/magnatuneurlhandler.h +++ b/src/internet/magnatuneurlhandler.h @@ -22,17 +22,16 @@ class MagnatuneService; - class MagnatuneUrlHandler : public UrlHandler { -public: + public: MagnatuneUrlHandler(MagnatuneService* service, QObject* parent); QString scheme() const { return "magnatune"; } QIcon icon() const { return QIcon(":providers/magnatune.png"); } LoadResult StartLoading(const QUrl& url); -private: + private: MagnatuneService* service_; }; -#endif // MAGNATUNEURLHANDLER_H +#endif // MAGNATUNEURLHANDLER_H diff --git a/src/internet/oauthenticator.cpp b/src/internet/oauthenticator.cpp index e44daee37..f92338890 100644 --- a/src/internet/oauthenticator.cpp +++ b/src/internet/oauthenticator.cpp @@ -10,21 +10,17 @@ #include "core/logging.h" #include "internet/localredirectserver.h" -OAuthenticator::OAuthenticator( - const QString& client_id, - const QString& client_secret, - RedirectStyle redirect, - QObject* parent) - : QObject(parent), - client_id_(client_id), - client_secret_(client_secret), - redirect_style_(redirect) { -} +OAuthenticator::OAuthenticator(const QString& client_id, + const QString& client_secret, + RedirectStyle redirect, QObject* parent) + : QObject(parent), + client_id_(client_id), + client_secret_(client_secret), + redirect_style_(redirect) {} -void OAuthenticator::StartAuthorisation( - const QString& oauth_endpoint, - const QString& token_endpoint, - const QString& scope) { +void OAuthenticator::StartAuthorisation(const QString& oauth_endpoint, + const QString& token_endpoint, + const QString& scope) { token_endpoint_ = QUrl(token_endpoint); LocalRedirectServer* server = new LocalRedirectServer(this); server->Listen(); @@ -35,28 +31,26 @@ void OAuthenticator::StartAuthorisation( QUrl redirect_url; if (redirect_style_ == RedirectStyle::REMOTE) { const int port = server->url().port(); - redirect_url = QUrl( - QString("https://clementine-data.appspot.com/skydrive?port=%1").arg(port)); + redirect_url = + QUrl(QString("https://clementine-data.appspot.com/skydrive?port=%1") + .arg(port)); } else { redirect_url = server->url(); } url.addQueryItem("redirect_uri", redirect_url.toString()); url.addQueryItem("scope", scope); - NewClosure(server, SIGNAL(Finished()), - this, &OAuthenticator::RedirectArrived, server, redirect_url); + NewClosure(server, SIGNAL(Finished()), this, &OAuthenticator::RedirectArrived, + server, redirect_url); QDesktopServices::openUrl(url); } -void OAuthenticator::RedirectArrived( - LocalRedirectServer* server, QUrl url) { +void OAuthenticator::RedirectArrived(LocalRedirectServer* server, QUrl url) { server->deleteLater(); QUrl request_url = server->request_url(); qLog(Debug) << Q_FUNC_INFO << request_url; - RequestAccessToken( - request_url.queryItemValue("code").toUtf8(), - url); + RequestAccessToken(request_url.queryItemValue("code").toUtf8(), url); } QByteArray OAuthenticator::ParseHttpRequest(const QByteArray& request) const { @@ -68,20 +62,21 @@ QByteArray OAuthenticator::ParseHttpRequest(const QByteArray& request) const { return code; } -void OAuthenticator::RequestAccessToken(const QByteArray& code, const QUrl& url) { +void OAuthenticator::RequestAccessToken(const QByteArray& code, + const QUrl& url) { typedef QPair Param; QList parameters; - parameters << Param("code", code) - << Param("client_id", client_id_) + parameters << Param("code", code) << Param("client_id", client_id_) << Param("client_secret", client_secret_) << Param("grant_type", "authorization_code") - // Even though we don't use this URI anymore, it must match the - // original one. + // Even though we don't use this URI anymore, it must match the + // original one. << Param("redirect_uri", url.toString()); QStringList params; - foreach (const Param& p, parameters) { - params.append(QString("%1=%2").arg(p.first, QString(QUrl::toPercentEncoding(p.second)))); + foreach(const Param & p, parameters) { + params.append(QString("%1=%2").arg( + p.first, QString(QUrl::toPercentEncoding(p.second)))); } QString post_data = params.join("&"); qLog(Debug) << post_data; @@ -99,8 +94,7 @@ void OAuthenticator::FetchAccessTokenFinished(QNetworkReply* reply) { reply->deleteLater(); if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) != 200) { - qLog(Error) << "Failed to get access token" - << reply->readAll(); + qLog(Error) << "Failed to get access token" << reply->readAll(); return; } @@ -121,9 +115,8 @@ void OAuthenticator::FetchAccessTokenFinished(QNetworkReply* reply) { emit Finished(); } -void OAuthenticator::RefreshAuthorisation( - const QString& token_endpoint, - const QString& refresh_token) { +void OAuthenticator::RefreshAuthorisation(const QString& token_endpoint, + const QString& refresh_token) { refresh_token_ = refresh_token; QUrl url(token_endpoint); @@ -135,8 +128,9 @@ void OAuthenticator::RefreshAuthorisation( << Param("grant_type", "refresh_token") << Param("refresh_token", refresh_token); QStringList params; - foreach (const Param& p, parameters) { - params.append(QString("%1=%2").arg(p.first, QString(QUrl::toPercentEncoding(p.second)))); + foreach(const Param & p, parameters) { + params.append(QString("%1=%2").arg( + p.first, QString(QUrl::toPercentEncoding(p.second)))); } QString post_data = params.join("&"); diff --git a/src/internet/oauthenticator.h b/src/internet/oauthenticator.h index 8c229bcd5..0e5cbbd3e 100644 --- a/src/internet/oauthenticator.h +++ b/src/internet/oauthenticator.h @@ -20,18 +20,12 @@ class OAuthenticator : public QObject { REMOTE = 1, }; - OAuthenticator( - const QString& client_id, - const QString& client_secret, - RedirectStyle redirect, - QObject* parent = 0); - void StartAuthorisation( - const QString& oauth_endpoint, - const QString& token_endpoint, - const QString& scope); - void RefreshAuthorisation( - const QString& token_endpoint, - const QString& refresh_token); + OAuthenticator(const QString& client_id, const QString& client_secret, + RedirectStyle redirect, QObject* parent = 0); + void StartAuthorisation(const QString& oauth_endpoint, + const QString& token_endpoint, const QString& scope); + void RefreshAuthorisation(const QString& token_endpoint, + const QString& refresh_token); // Token to use now. const QString& access_token() const { return access_token_; } @@ -41,7 +35,7 @@ class OAuthenticator : public QObject { const QDateTime& expiry_time() const { return expiry_time_; } - signals: +signals: void Finished(); private slots: diff --git a/src/internet/savedradio.cpp b/src/internet/savedradio.cpp index 478250c9b..ce5d409b5 100644 --- a/src/internet/savedradio.cpp +++ b/src/internet/savedradio.cpp @@ -31,18 +31,16 @@ const char* SavedRadio::kServiceName = "SavedRadio"; const char* SavedRadio::kSettingsGroup = "SavedRadio"; SavedRadio::SavedRadio(Application* app, InternetModel* parent) - : InternetService(kServiceName, app, parent, parent), - context_menu_(nullptr), - root_(nullptr) -{ + : InternetService(kServiceName, app, parent, parent), + context_menu_(nullptr), + root_(nullptr) { LoadStreams(); - app_->global_search()->AddProvider(new SavedRadioSearchProvider(this, app_, this)); + app_->global_search()->AddProvider( + new SavedRadioSearchProvider(this, app_, this)); } -SavedRadio::~SavedRadio() { - delete context_menu_; -} +SavedRadio::~SavedRadio() { delete context_menu_; } QStandardItem* SavedRadio::CreateRootItem() { root_ = new QStandardItem(IconLoader::Load("document-open-remote"), @@ -54,8 +52,8 @@ QStandardItem* SavedRadio::CreateRootItem() { void SavedRadio::LazyPopulate(QStandardItem* item) { switch (item->data(InternetModel::Role_Type).toInt()) { case InternetModel::Type_Service: - foreach (const Stream& stream, streams_) - AddStreamToList(stream, root_); + foreach(const Stream & stream, streams_) + AddStreamToList(stream, root_); break; @@ -70,9 +68,10 @@ void SavedRadio::LoadStreams() { s.beginGroup(kSettingsGroup); int count = s.beginReadArray("streams"); - for (int i=0 ; iaddActions(GetPlaylistActions()); - remove_action_ = context_menu_->addAction(IconLoader::Load("list-remove"), tr("Remove"), this, SLOT(Remove())); - edit_action_ = context_menu_->addAction(IconLoader::Load("edit-rename"), tr("Edit..."), this, SLOT(Edit())); + remove_action_ = context_menu_->addAction( + IconLoader::Load("list-remove"), tr("Remove"), this, SLOT(Remove())); + edit_action_ = context_menu_->addAction(IconLoader::Load("edit-rename"), + tr("Edit..."), this, SLOT(Edit())); context_menu_->addSeparator(); - context_menu_->addAction(IconLoader::Load("document-open-remote"), tr("Add another stream..."), this, SIGNAL(ShowAddStreamDialog())); + context_menu_->addAction(IconLoader::Load("document-open-remote"), + tr("Add another stream..."), this, + SIGNAL(ShowAddStreamDialog())); } const bool is_root = @@ -117,15 +120,18 @@ void SavedRadio::ShowContextMenu(const QPoint& global_pos) { } void SavedRadio::Remove() { - QStandardItem* context_item = model()->itemFromIndex(model()->current_index()); + QStandardItem* context_item = + model()->itemFromIndex(model()->current_index()); - streams_.removeAll(Stream(QUrl(context_item->data(InternetModel::Role_Url).toUrl()))); + streams_.removeAll( + Stream(QUrl(context_item->data(InternetModel::Role_Url).toUrl()))); context_item->parent()->removeRow(context_item->row()); SaveStreams(); } void SavedRadio::Edit() { - QStandardItem* context_item = model()->itemFromIndex(model()->current_index()); + QStandardItem* context_item = + model()->itemFromIndex(model()->current_index()); if (!edit_dialog_) { edit_dialog_.reset(new AddStreamDialog); @@ -134,10 +140,10 @@ void SavedRadio::Edit() { edit_dialog_->set_name(context_item->text()); edit_dialog_->set_url(context_item->data(InternetModel::Role_Url).toUrl()); - if (edit_dialog_->exec() == QDialog::Rejected) - return; + if (edit_dialog_->exec() == QDialog::Rejected) return; - int i = streams_.indexOf(Stream(QUrl(context_item->data(InternetModel::Role_Url).toUrl()))); + int i = streams_.indexOf( + Stream(QUrl(context_item->data(InternetModel::Role_Url).toUrl()))); Stream* stream = &streams_[i]; stream->name_ = edit_dialog_->name(); stream->url_ = edit_dialog_->url(); @@ -149,15 +155,16 @@ void SavedRadio::Edit() { } void SavedRadio::AddStreamToList(const Stream& stream, QStandardItem* parent) { - QStandardItem* s = new QStandardItem(QIcon(":last.fm/icon_radio.png"), stream.name_); + QStandardItem* s = + new QStandardItem(QIcon(":last.fm/icon_radio.png"), stream.name_); s->setData(stream.url_, InternetModel::Role_Url); - s->setData(InternetModel::PlayBehaviour_UseSongLoader, InternetModel::Role_PlayBehaviour); + s->setData(InternetModel::PlayBehaviour_UseSongLoader, + InternetModel::Role_PlayBehaviour); parent->appendRow(s); } -void SavedRadio::Add(const QUrl &url, const QString& name) { - if (streams_.contains(Stream(url))) - return; +void SavedRadio::Add(const QUrl& url, const QString& name) { + if (streams_.contains(Stream(url))) return; Stream stream(url, name); streams_ << stream; diff --git a/src/internet/savedradio.h b/src/internet/savedradio.h index 619aeec66..d96a5e524 100644 --- a/src/internet/savedradio.h +++ b/src/internet/savedradio.h @@ -33,16 +33,14 @@ class SavedRadio : public InternetService { SavedRadio(Application* app, InternetModel* parent); ~SavedRadio(); - enum ItemType { - Type_Stream = 2000, - }; + enum ItemType { Type_Stream = 2000, }; struct Stream { Stream(const QUrl& url, const QString& name = QString()) - : url_(url), name_(name) {} + : url_(url), name_(name) {} // For QList::contains - bool operator ==(const Stream& other) const { return url_ == other.url_; } + bool operator==(const Stream& other) const { return url_ == other.url_; } QUrl url_; QString name_; @@ -61,7 +59,7 @@ class SavedRadio : public InternetService { StreamList Streams() const { return streams_; } - signals: +signals: void ShowAddStreamDialog(); void StreamsChanged(); @@ -86,4 +84,4 @@ class SavedRadio : public InternetService { std::unique_ptr edit_dialog_; }; -#endif // SAVEDRADIO_H +#endif // SAVEDRADIO_H diff --git a/src/internet/searchboxwidget.cpp b/src/internet/searchboxwidget.cpp index 514f569ef..cf975c5a4 100644 --- a/src/internet/searchboxwidget.cpp +++ b/src/internet/searchboxwidget.cpp @@ -25,10 +25,9 @@ #include SearchBoxWidget::SearchBoxWidget(InternetService* service) - : service_(service), - ui_(new Ui_SearchBoxWidget), - menu_(new QMenu(tr("Display options"), this)) -{ + : service_(service), + ui_(new Ui_SearchBoxWidget), + menu_(new QMenu(tr("Display options"), this)) { ui_->setupUi(this); // Icons @@ -39,22 +38,22 @@ SearchBoxWidget::SearchBoxWidget(InternetService* service) ui_->options->setMenu(menu_); menu_->addAction(IconLoader::Load("configure"), - tr("Configure %1...").arg(service_->name()), - service_, SLOT(ShowConfig())); + tr("Configure %1...").arg(service_->name()), service_, + SLOT(ShowConfig())); - ui_->filter->setPlaceholderText(QString("Search on %1").arg(service_->name())); - connect(ui_->filter, SIGNAL(textChanged(QString)), SIGNAL(TextChanged(QString))); + ui_->filter->setPlaceholderText( + QString("Search on %1").arg(service_->name())); + connect(ui_->filter, SIGNAL(textChanged(QString)), + SIGNAL(TextChanged(QString))); did_you_mean_ = new DidYouMean(ui_->filter, this); - connect(did_you_mean_, SIGNAL(Accepted(QString)), - ui_->filter, SLOT(setText(QString))); + connect(did_you_mean_, SIGNAL(Accepted(QString)), ui_->filter, + SLOT(setText(QString))); } -SearchBoxWidget::~SearchBoxWidget() { - delete ui_; -} +SearchBoxWidget::~SearchBoxWidget() { delete ui_; } -void SearchBoxWidget::FocusOnFilter(QKeyEvent *event) { +void SearchBoxWidget::FocusOnFilter(QKeyEvent* event) { ui_->filter->setFocus(Qt::OtherFocusReason); QApplication::sendEvent(ui_->filter, event); } diff --git a/src/internet/searchboxwidget.h b/src/internet/searchboxwidget.h index 9ba3c6b3b..7752c4530 100644 --- a/src/internet/searchboxwidget.h +++ b/src/internet/searchboxwidget.h @@ -30,7 +30,7 @@ class QMenu; class SearchBoxWidget : public QWidget { Q_OBJECT -public: + public: SearchBoxWidget(InternetService* service); ~SearchBoxWidget(); @@ -39,17 +39,17 @@ public: signals: void TextChanged(const QString& text); -public slots: + public slots: void FocusOnFilter(QKeyEvent* e); -protected: + protected: void keyReleaseEvent(QKeyEvent* e); -private: + private: InternetService* service_; Ui_SearchBoxWidget* ui_; QMenu* menu_; DidYouMean* did_you_mean_; }; -#endif // SEARCHBOXWIDGET_H +#endif // SEARCHBOXWIDGET_H diff --git a/src/internet/skydriveservice.cpp b/src/internet/skydriveservice.cpp index e3023f5c1..87431fd0c 100644 --- a/src/internet/skydriveservice.cpp +++ b/src/internet/skydriveservice.cpp @@ -30,18 +30,14 @@ static const char* kSkydriveBase = "https://apis.live.net/v5.0/"; } // namespace -SkydriveService::SkydriveService( - Application* app, - InternetModel* parent) - : CloudFileService( - app, parent, kServiceName, kServiceId, - QIcon(":providers/skydrive.png"), SettingsDialog::Page_Skydrive) { +SkydriveService::SkydriveService(Application* app, InternetModel* parent) + : CloudFileService(app, parent, kServiceName, kServiceId, + QIcon(":providers/skydrive.png"), + SettingsDialog::Page_Skydrive) { app->player()->RegisterUrlHandler(new SkydriveUrlHandler(this, this)); } -bool SkydriveService::has_credentials() const { - return true; -} +bool SkydriveService::has_credentials() const { return true; } void SkydriveService::Connect() { OAuthenticator* oauth = new OAuthenticator( @@ -49,17 +45,14 @@ void SkydriveService::Connect() { QSettings s; s.beginGroup(kSettingsGroup); if (s.contains("refresh_token")) { - oauth->RefreshAuthorisation( - kOAuthTokenEndpoint, s.value("refresh_token").toString()); + oauth->RefreshAuthorisation(kOAuthTokenEndpoint, + s.value("refresh_token").toString()); } else { - oauth->StartAuthorisation( - kOAuthEndpoint, - kOAuthTokenEndpoint, - kOAuthScope); + oauth->StartAuthorisation(kOAuthEndpoint, kOAuthTokenEndpoint, kOAuthScope); } - NewClosure(oauth, SIGNAL(Finished()), - this, SLOT(ConnectFinished(OAuthenticator*)), oauth); + NewClosure(oauth, SIGNAL(Finished()), this, + SLOT(ConnectFinished(OAuthenticator*)), oauth); } void SkydriveService::ConnectFinished(OAuthenticator* oauth) { @@ -77,13 +70,13 @@ void SkydriveService::ConnectFinished(OAuthenticator* oauth) { AddAuthorizationHeader(&request); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(FetchUserInfoFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(FetchUserInfoFinished(QNetworkReply*)), reply); } void SkydriveService::AddAuthorizationHeader(QNetworkRequest* request) { - request->setRawHeader( - "Authorization", QString("Bearer %1").arg(access_token_).toUtf8()); + request->setRawHeader("Authorization", + QString("Bearer %1").arg(access_token_).toUtf8()); } void SkydriveService::FetchUserInfoFinished(QNetworkReply* reply) { @@ -111,8 +104,8 @@ void SkydriveService::ListFiles(const QString& folder) { AddAuthorizationHeader(&request); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(ListFilesFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(ListFilesFinished(QNetworkReply*)), reply); } void SkydriveService::ListFilesFinished(QNetworkReply* reply) { @@ -122,7 +115,7 @@ void SkydriveService::ListFilesFinished(QNetworkReply* reply) { qLog(Debug) << response; QVariantList files = response["data"].toList(); - foreach (const QVariant& f, files) { + foreach(const QVariant & f, files) { QVariantMap file = f.toMap(); if (file["type"].toString() == "audio") { QString mime_type = GuessMimeTypeForFile(file["name"].toString()); @@ -142,11 +135,7 @@ void SkydriveService::ListFilesFinished(QNetworkReply* reply) { // HTTPS appears to be broken somehow between Qt & Skydrive downloads. // Fortunately, just changing the scheme to HTTP works. download_url.setScheme("http"); - MaybeAddFileToDatabase( - song, - mime_type, - download_url, - QString::null); + MaybeAddFileToDatabase(song, mime_type, download_url, QString::null); } } } diff --git a/src/internet/skydriveservice.h b/src/internet/skydriveservice.h index 2a6ede077..330abdba6 100644 --- a/src/internet/skydriveservice.h +++ b/src/internet/skydriveservice.h @@ -13,9 +13,7 @@ class SkydriveService : public CloudFileService { Q_OBJECT public: - SkydriveService( - Application* app, - InternetModel* parent); + SkydriveService(Application* app, InternetModel* parent); QUrl GetStreamingUrlFromSongId(const QString& song_id); protected: @@ -28,7 +26,7 @@ class SkydriveService : public CloudFileService { void FetchUserInfoFinished(QNetworkReply* reply); void ListFilesFinished(QNetworkReply* reply); - signals: +signals: void Connected(); private: diff --git a/src/internet/skydriveurlhandler.cpp b/src/internet/skydriveurlhandler.cpp index ec71ed4aa..ae00ed3d9 100644 --- a/src/internet/skydriveurlhandler.cpp +++ b/src/internet/skydriveurlhandler.cpp @@ -2,12 +2,9 @@ #include "skydriveservice.h" -SkydriveUrlHandler::SkydriveUrlHandler( - SkydriveService* service, - QObject* parent) - : UrlHandler(parent), - service_(service) { -} +SkydriveUrlHandler::SkydriveUrlHandler(SkydriveService* service, + QObject* parent) + : UrlHandler(parent), service_(service) {} UrlHandler::LoadResult SkydriveUrlHandler::StartLoading(const QUrl& url) { QString file_id(url.path()); diff --git a/src/internet/somafmservice.cpp b/src/internet/somafmservice.cpp index 899866ac8..f29377ba1 100644 --- a/src/internet/somafmservice.cpp +++ b/src/internet/somafmservice.cpp @@ -38,43 +38,39 @@ #include const int SomaFMServiceBase::kStreamsCacheDurationSecs = - 60 * 60 * 24 * 28; // 4 weeks + 60 * 60 * 24 * 28; // 4 weeks -bool operator <(const SomaFMServiceBase::Stream& a, - const SomaFMServiceBase::Stream& b) { +bool operator<(const SomaFMServiceBase::Stream& a, + const SomaFMServiceBase::Stream& b) { return a.title_.compare(b.title_, Qt::CaseInsensitive) < 0; } -SomaFMServiceBase::SomaFMServiceBase( - Application* app, - InternetModel* parent, - const QString& name, - const QUrl& channel_list_url, - const QUrl& homepage_url, - const QUrl& donate_page_url, - const QIcon& icon) - : InternetService(name, app, parent, parent), - url_scheme_(name.toLower().remove(' ')), - url_handler_(new SomaFMUrlHandler(app, this, this)), - root_(nullptr), - context_menu_(nullptr), - network_(new NetworkAccessManager(this)), - streams_(name, "streams", kStreamsCacheDurationSecs), - name_(name), - channel_list_url_(channel_list_url), - homepage_url_(homepage_url), - donate_page_url_(donate_page_url), - icon_(icon) -{ +SomaFMServiceBase::SomaFMServiceBase(Application* app, InternetModel* parent, + const QString& name, + const QUrl& channel_list_url, + const QUrl& homepage_url, + const QUrl& donate_page_url, + const QIcon& icon) + : InternetService(name, app, parent, parent), + url_scheme_(name.toLower().remove(' ')), + url_handler_(new SomaFMUrlHandler(app, this, this)), + root_(nullptr), + context_menu_(nullptr), + network_(new NetworkAccessManager(this)), + streams_(name, "streams", kStreamsCacheDurationSecs), + name_(name), + channel_list_url_(channel_list_url), + homepage_url_(homepage_url), + donate_page_url_(donate_page_url), + icon_(icon) { ReloadSettings(); app_->player()->RegisterUrlHandler(url_handler_); - app_->global_search()->AddProvider(new SomaFMSearchProvider(this, app_, this)); + app_->global_search()->AddProvider( + new SomaFMSearchProvider(this, app_, this)); } -SomaFMServiceBase::~SomaFMServiceBase() { - delete context_menu_; -} +SomaFMServiceBase::~SomaFMServiceBase() { delete context_menu_; } QStandardItem* SomaFMServiceBase::CreateRootItem() { root_ = new QStandardItem(icon_, name_); @@ -97,13 +93,18 @@ void SomaFMServiceBase::ShowContextMenu(const QPoint& global_pos) { if (!context_menu_) { context_menu_ = new QMenu; context_menu_->addActions(GetPlaylistActions()); - context_menu_->addAction(IconLoader::Load("download"), tr("Open %1 in browser").arg(homepage_url_.host()), this, SLOT(Homepage())); + context_menu_->addAction(IconLoader::Load("download"), + tr("Open %1 in browser").arg(homepage_url_.host()), + this, SLOT(Homepage())); if (!donate_page_url_.isEmpty()) { - context_menu_->addAction(IconLoader::Load("download"), tr("Donate"), this, SLOT(Donate())); + context_menu_->addAction(IconLoader::Load("download"), tr("Donate"), this, + SLOT(Donate())); } - context_menu_->addAction(IconLoader::Load("view-refresh"), tr("Refresh channels"), this, SLOT(ForceRefreshStreams())); + context_menu_->addAction(IconLoader::Load("view-refresh"), + tr("Refresh channels"), this, + SLOT(ForceRefreshStreams())); } context_menu_->popup(global_pos); @@ -113,12 +114,12 @@ void SomaFMServiceBase::ForceRefreshStreams() { QNetworkReply* reply = network_->get(QNetworkRequest(channel_list_url_)); int task_id = app_->task_manager()->StartTask(tr("Getting channels")); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(RefreshStreamsFinished(QNetworkReply*,int)), - reply, task_id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(RefreshStreamsFinished(QNetworkReply*, int)), reply, task_id); } -void SomaFMServiceBase::RefreshStreamsFinished(QNetworkReply* reply, int task_id) { +void SomaFMServiceBase::RefreshStreamsFinished(QNetworkReply* reply, + int task_id) { app_->task_manager()->SetTaskFinished(task_id); reply->deleteLater(); @@ -144,8 +145,7 @@ void SomaFMServiceBase::RefreshStreamsFinished(QNetworkReply* reply, int task_id streams_.Sort(); // Only update the item's children if it's already been populated - if (!root_->data(InternetModel::Role_CanLazyLoad).toBool()) - PopulateStreams(); + if (!root_->data(InternetModel::Role_CanLazyLoad).toBool()) PopulateStreams(); emit StreamsChanged(); } @@ -166,7 +166,8 @@ void SomaFMServiceBase::ReadChannel(QXmlStreamReader& reader, StreamList* ret) { stream.title_ = reader.readElementText(); } else if (reader.name() == "dj") { stream.dj_ = reader.readElementText(); - } else if (reader.name() == "fastpls" && reader.attributes().value("format") == "mp3") { + } else if (reader.name() == "fastpls" && + reader.attributes().value("format") == "mp3") { QUrl url(reader.readElementText()); url.setScheme(url_handler_->scheme()); @@ -196,9 +197,7 @@ Song SomaFMServiceBase::Stream::ToSong(const QString& prefix) const { return ret; } -void SomaFMServiceBase::Homepage() { - QDesktopServices::openUrl(homepage_url_); -} +void SomaFMServiceBase::Homepage() { QDesktopServices::openUrl(homepage_url_); } void SomaFMServiceBase::Donate() { QDesktopServices::openUrl(donate_page_url_); @@ -210,7 +209,8 @@ PlaylistItem::Options SomaFMServiceBase::playlistitem_options() const { SomaFMServiceBase::StreamList SomaFMServiceBase::Streams() { if (IsStreamListStale()) { - metaObject()->invokeMethod(this, "ForceRefreshStreams", Qt::QueuedConnection); + metaObject()->invokeMethod(this, "ForceRefreshStreams", + Qt::QueuedConnection); } return streams_; } @@ -224,30 +224,29 @@ void SomaFMServiceBase::RefreshStreams() { } void SomaFMServiceBase::PopulateStreams() { - if (root_->hasChildren()) - root_->removeRows(0, root_->rowCount()); + if (root_->hasChildren()) root_->removeRows(0, root_->rowCount()); - foreach (const Stream& stream, streams_) { - QStandardItem* item = new QStandardItem(QIcon(":last.fm/icon_radio.png"), QString()); + foreach(const Stream & stream, streams_) { + QStandardItem* item = + new QStandardItem(QIcon(":last.fm/icon_radio.png"), QString()); item->setText(stream.title_); - item->setData(QVariant::fromValue(stream.ToSong(name_)), InternetModel::Role_SongMetadata); - item->setData(InternetModel::PlayBehaviour_SingleItem, InternetModel::Role_PlayBehaviour); + item->setData(QVariant::fromValue(stream.ToSong(name_)), + InternetModel::Role_SongMetadata); + item->setData(InternetModel::PlayBehaviour_SingleItem, + InternetModel::Role_PlayBehaviour); root_->appendRow(item); } } -QDataStream& operator<<(QDataStream& out, const SomaFMServiceBase::Stream& stream) { - out << stream.title_ - << stream.dj_ - << stream.url_; +QDataStream& operator<<(QDataStream& out, + const SomaFMServiceBase::Stream& stream) { + out << stream.title_ << stream.dj_ << stream.url_; return out; } QDataStream& operator>>(QDataStream& in, SomaFMServiceBase::Stream& stream) { - in >> stream.title_ - >> stream.dj_ - >> stream.url_; + in >> stream.title_ >> stream.dj_ >> stream.url_; return in; } @@ -256,26 +255,14 @@ void SomaFMServiceBase::ReloadSettings() { streams_.Sort(); } - SomaFMService::SomaFMService(Application* app, InternetModel* parent) - : SomaFMServiceBase( - app, - parent, - "SomaFM", - QUrl("http://somafm.com/channels.xml"), - QUrl("http://somafm.com"), - QUrl(), - QIcon(":providers/somafm.png")) { -} - + : SomaFMServiceBase( + app, parent, "SomaFM", QUrl("http://somafm.com/channels.xml"), + QUrl("http://somafm.com"), QUrl(), QIcon(":providers/somafm.png")) {} RadioGFMService::RadioGFMService(Application* app, InternetModel* parent) - : SomaFMServiceBase( - app, - parent, - "Radio GFM", - QUrl("http://streams.radio-gfm.net/channels.xml"), - QUrl("http://www.radio-gfm.net"), - QUrl("http://www.radio-gfm.net/spenden"), - QIcon(":providers/radiogfm.png")) { -} + : SomaFMServiceBase(app, parent, "Radio GFM", + QUrl("http://streams.radio-gfm.net/channels.xml"), + QUrl("http://www.radio-gfm.net"), + QUrl("http://www.radio-gfm.net/spenden"), + QIcon(":providers/radiogfm.png")) {} diff --git a/src/internet/somafmservice.h b/src/internet/somafmservice.h index 7d14eb50b..9c34e1c89 100644 --- a/src/internet/somafmservice.h +++ b/src/internet/somafmservice.h @@ -32,20 +32,14 @@ class QMenu; class SomaFMServiceBase : public InternetService { Q_OBJECT -public: - SomaFMServiceBase( - Application* app, - InternetModel* parent, - const QString& name, - const QUrl& channel_list_url, - const QUrl& homepage_url, - const QUrl& donate_page_url, - const QIcon& icon); + public: + SomaFMServiceBase(Application* app, InternetModel* parent, + const QString& name, const QUrl& channel_list_url, + const QUrl& homepage_url, const QUrl& donate_page_url, + const QIcon& icon); ~SomaFMServiceBase(); - enum ItemType { - Type_Stream = 2000, - }; + enum ItemType { Type_Stream = 2000, }; struct Stream { QString title_; @@ -76,7 +70,7 @@ public: signals: void StreamsChanged(); -private slots: + private slots: void ForceRefreshStreams(); void RefreshStreams(); void RefreshStreamsFinished(QNetworkReply* reply, int task_id); @@ -84,11 +78,11 @@ private slots: void Homepage(); void Donate(); -private: + private: void ReadChannel(QXmlStreamReader& reader, StreamList* ret); void PopulateStreams(); -private: + private: const QString url_scheme_; SomaFMUrlHandler* url_handler_; @@ -120,4 +114,4 @@ QDataStream& operator<<(QDataStream& out, const SomaFMService::Stream& stream); QDataStream& operator>>(QDataStream& in, SomaFMService::Stream& stream); Q_DECLARE_METATYPE(SomaFMService::Stream) -#endif // SOMAFMSERVICE_H +#endif // SOMAFMSERVICE_H diff --git a/src/internet/somafmurlhandler.cpp b/src/internet/somafmurlhandler.cpp index 062ff45a1..2e4f1cba7 100644 --- a/src/internet/somafmurlhandler.cpp +++ b/src/internet/somafmurlhandler.cpp @@ -28,30 +28,21 @@ #include #include -SomaFMUrlHandler::SomaFMUrlHandler(Application* app, - SomaFMServiceBase* service, +SomaFMUrlHandler::SomaFMUrlHandler(Application* app, SomaFMServiceBase* service, QObject* parent) - : UrlHandler(parent), - app_(app), - service_(service), - task_id_(0) -{ -} + : UrlHandler(parent), app_(app), service_(service), task_id_(0) {} -QString SomaFMUrlHandler::scheme() const { - return service_->url_scheme(); -} +QString SomaFMUrlHandler::scheme() const { return service_->url_scheme(); } -QIcon SomaFMUrlHandler::icon() const { - return service_->icon(); -} +QIcon SomaFMUrlHandler::icon() const { return service_->icon(); } UrlHandler::LoadResult SomaFMUrlHandler::StartLoading(const QUrl& url) { QUrl playlist_url = url; playlist_url.setScheme("http"); // Load the playlist - QNetworkReply* reply = service_->network()->get(QNetworkRequest(playlist_url)); + QNetworkReply* reply = + service_->network()->get(QNetworkRequest(playlist_url)); connect(reply, SIGNAL(finished()), SLOT(LoadPlaylistFinished())); if (!task_id_) @@ -88,6 +79,6 @@ void SomaFMUrlHandler::LoadPlaylistFinished() { return; } - emit AsyncLoadComplete(LoadResult(original_url, LoadResult::TrackAvailable, - songs[0].url())); + emit AsyncLoadComplete( + LoadResult(original_url, LoadResult::TrackAvailable, songs[0].url())); } diff --git a/src/internet/somafmurlhandler.h b/src/internet/somafmurlhandler.h index 1e4ea0121..e2919393e 100644 --- a/src/internet/somafmurlhandler.h +++ b/src/internet/somafmurlhandler.h @@ -23,28 +23,25 @@ class Application; class SomaFMServiceBase; - class SomaFMUrlHandler : public UrlHandler { Q_OBJECT -public: - SomaFMUrlHandler( - Application* app, - SomaFMServiceBase* service, - QObject* parent); + public: + SomaFMUrlHandler(Application* app, SomaFMServiceBase* service, + QObject* parent); QString scheme() const; QIcon icon() const; LoadResult StartLoading(const QUrl& url); -private slots: + private slots: void LoadPlaylistFinished(); -private: + private: Application* app_; SomaFMServiceBase* service_; int task_id_; }; -#endif // SOMAFMURLHANDLER_H +#endif // SOMAFMURLHANDLER_H diff --git a/src/internet/soundcloudservice.cpp b/src/internet/soundcloudservice.cpp index 8ebf2379b..1a4a3f79b 100644 --- a/src/internet/soundcloudservice.cpp +++ b/src/internet/soundcloudservice.cpp @@ -42,7 +42,8 @@ #include "globalsearch/soundcloudsearchprovider.h" #include "ui/iconloader.h" -const char* SoundCloudService::kApiClientId = "2add0f709fcfae1fd7a198ec7573d2d4"; +const char* SoundCloudService::kApiClientId = + "2add0f709fcfae1fd7a198ec7573d2d4"; const char* SoundCloudService::kServiceName = "SoundCloud"; const char* SoundCloudService::kSettingsGroup = "SoundCloud"; @@ -55,36 +56,35 @@ const int SoundCloudService::kSongSimpleSearchLimit = 10; typedef QPair Param; -SoundCloudService::SoundCloudService(Application* app, InternetModel *parent) - : InternetService(kServiceName, app, parent, parent), - root_(nullptr), - search_(nullptr), - network_(new NetworkAccessManager(this)), - context_menu_(nullptr), - search_box_(new SearchBoxWidget(this)), - search_delay_(new QTimer(this)), - next_pending_search_id_(0) { +SoundCloudService::SoundCloudService(Application* app, InternetModel* parent) + : InternetService(kServiceName, app, parent, parent), + root_(nullptr), + search_(nullptr), + network_(new NetworkAccessManager(this)), + context_menu_(nullptr), + search_box_(new SearchBoxWidget(this)), + search_delay_(new QTimer(this)), + next_pending_search_id_(0) { search_delay_->setInterval(kSearchDelayMsec); search_delay_->setSingleShot(true); connect(search_delay_, SIGNAL(timeout()), SLOT(DoSearch())); - SoundCloudSearchProvider* search_provider = new SoundCloudSearchProvider(app_, this); + SoundCloudSearchProvider* search_provider = + new SoundCloudSearchProvider(app_, this); search_provider->Init(this); app_->global_search()->AddProvider(search_provider); connect(search_box_, SIGNAL(TextChanged(QString)), SLOT(Search(QString))); } - -SoundCloudService::~SoundCloudService() { -} +SoundCloudService::~SoundCloudService() {} QStandardItem* SoundCloudService::CreateRootItem() { root_ = new QStandardItem(QIcon(":providers/soundcloud.png"), kServiceName); root_->setData(true, InternetModel::Role_CanLazyLoad); root_->setData(InternetModel::PlayBehaviour_DoubleClickAction, - InternetModel::Role_PlayBehaviour); + InternetModel::Role_PlayBehaviour); return root_; } @@ -100,18 +100,17 @@ void SoundCloudService::LazyPopulate(QStandardItem* item) { } void SoundCloudService::EnsureItemsCreated() { - search_ = new QStandardItem(IconLoader::Load("edit-find"), - tr("Search results")); - search_->setToolTip(tr("Start typing something on the search box above to " - "fill this search results list")); + search_ = + new QStandardItem(IconLoader::Load("edit-find"), tr("Search results")); + search_->setToolTip( + tr("Start typing something on the search box above to " + "fill this search results list")); search_->setData(InternetModel::PlayBehaviour_MultipleItems, InternetModel::Role_PlayBehaviour); root_->appendRow(search_); } -QWidget* SoundCloudService::HeaderWidget() const { - return search_box_; -} +QWidget* SoundCloudService::HeaderWidget() const { return search_box_; } void SoundCloudService::Homepage() { QDesktopServices::openUrl(QUrl(kHomepage)); @@ -140,12 +139,11 @@ void SoundCloudService::DoSearch() { ClearSearchResults(); QList parameters; - parameters << Param("q", pending_search_); + parameters << Param("q", pending_search_); QNetworkReply* reply = CreateRequest("tracks", parameters); const int id = next_pending_search_id_++; - NewClosure(reply, SIGNAL(finished()), - this, SLOT(SearchFinished(QNetworkReply*,int)), - reply, id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(SearchFinished(QNetworkReply*, int)), reply, id); } void SoundCloudService::SearchFinished(QNetworkReply* reply, int task_id) { @@ -153,7 +151,7 @@ void SoundCloudService::SearchFinished(QNetworkReply* reply, int task_id) { SongList songs = ExtractSongs(ExtractResult(reply)); // Fill results list - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { QStandardItem* child = CreateSongItem(song); search_->appendRow(child); } @@ -163,18 +161,16 @@ void SoundCloudService::SearchFinished(QNetworkReply* reply, int task_id) { } void SoundCloudService::ClearSearchResults() { - if (search_) - search_->removeRows(0, search_->rowCount()); + if (search_) search_->removeRows(0, search_->rowCount()); } int SoundCloudService::SimpleSearch(const QString& text) { QList parameters; - parameters << Param("q", text); + parameters << Param("q", text); QNetworkReply* reply = CreateRequest("tracks", parameters); const int id = next_pending_search_id_++; - NewClosure(reply, SIGNAL(finished()), - this, SLOT(SimpleSearchFinished(QNetworkReply*,int)), - reply, id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(SimpleSearchFinished(QNetworkReply*, int)), reply, id); return id; } @@ -186,7 +182,7 @@ void SoundCloudService::SimpleSearchFinished(QNetworkReply* reply, int id) { } void SoundCloudService::EnsureMenuCreated() { - if(!context_menu_) { + if (!context_menu_) { context_menu_ = new QMenu; context_menu_->addActions(GetPlaylistActions()); context_menu_->addSeparator(); @@ -198,20 +194,19 @@ void SoundCloudService::EnsureMenuCreated() { void SoundCloudService::ShowContextMenu(const QPoint& global_pos) { EnsureMenuCreated(); - + context_menu_->popup(global_pos); } -QNetworkReply* SoundCloudService::CreateRequest( - const QString& ressource_name, - const QList& params) { +QNetworkReply* SoundCloudService::CreateRequest(const QString& ressource_name, + const QList& params) { QUrl url(kUrl); url.setPath(ressource_name); url.addQueryItem("client_id", kApiClientId); - foreach(const Param& param, params) { + foreach(const Param & param, params) { url.addQueryItem(param.first, param.second); } @@ -219,7 +214,7 @@ QNetworkReply* SoundCloudService::CreateRequest( QNetworkRequest req(url); req.setRawHeader("Accept", "application/json"); - QNetworkReply *reply = network_->get(req); + QNetworkReply* reply = network_->get(req); return reply; } @@ -237,7 +232,7 @@ SongList SoundCloudService::ExtractSongs(const QVariant& result) { SongList songs; QVariantList q_variant_list = result.toList(); - foreach(const QVariant& q, q_variant_list) { + foreach(const QVariant & q, q_variant_list) { Song song = ExtractSong(q.toMap()); if (song.is_valid()) { songs << song; diff --git a/src/internet/soundcloudservice.h b/src/internet/soundcloudservice.h index c51f45482..60ddd6e77 100644 --- a/src/internet/soundcloudservice.h +++ b/src/internet/soundcloudservice.h @@ -30,15 +30,15 @@ class QNetworkReply; class SoundCloudService : public InternetService { Q_OBJECT public: - SoundCloudService(Application* app, InternetModel *parent); + SoundCloudService(Application* app, InternetModel* parent); ~SoundCloudService(); // Internet Service methods QStandardItem* CreateRootItem(); - void LazyPopulate(QStandardItem *parent); + void LazyPopulate(QStandardItem* parent); // TODO - //QList playlistitem_actions(const Song& song); + // QList playlistitem_actions(const Song& song); void ShowContextMenu(const QPoint& global_pos); QWidget* HeaderWidget() const; @@ -47,7 +47,7 @@ class SoundCloudService : public InternetService { static const char* kServiceName; static const char* kSettingsGroup; - signals: +signals: void SimpleSearchResults(int id, SongList songs); private slots: @@ -93,5 +93,4 @@ class SoundCloudService : public InternetService { static const char* kApiClientId; }; - -#endif // SOUNDCLOUDSERVICE_H +#endif // SOUNDCLOUDSERVICE_H diff --git a/src/internet/spotifyblobdownloader.cpp b/src/internet/spotifyblobdownloader.cpp index 5bd12a057..b19e3a17b 100644 --- a/src/internet/spotifyblobdownloader.cpp +++ b/src/internet/spotifyblobdownloader.cpp @@ -30,24 +30,24 @@ #include #ifdef HAVE_QCA - #include -#endif // HAVE_QCA +#include +#endif // HAVE_QCA #ifdef Q_OS_UNIX - #include +#include #endif const char* SpotifyBlobDownloader::kSignatureSuffix = ".sha1"; - -SpotifyBlobDownloader::SpotifyBlobDownloader( - const QString& version, const QString& path, QObject* parent) - : QObject(parent), - version_(version), - path_(path), - network_(new NetworkAccessManager(this)), - progress_(new QProgressDialog(tr("Downloading Spotify plugin"), tr("Cancel"), 0, 0)) -{ +SpotifyBlobDownloader::SpotifyBlobDownloader(const QString& version, + const QString& path, + QObject* parent) + : QObject(parent), + version_(version), + path_(path), + network_(new NetworkAccessManager(this)), + progress_(new QProgressDialog(tr("Downloading Spotify plugin"), + tr("Cancel"), 0, 0)) { progress_->setWindowTitle(QCoreApplication::applicationName()); connect(progress_, SIGNAL(canceled()), SLOT(Cancel())); } @@ -60,9 +60,10 @@ SpotifyBlobDownloader::~SpotifyBlobDownloader() { } bool SpotifyBlobDownloader::Prompt() { - QMessageBox::StandardButton ret = QMessageBox::question(nullptr, - tr("Spotify plugin not installed"), - tr("An additional plugin is required to use Spotify in Clementine. Would you like to download and install it now?"), + QMessageBox::StandardButton ret = QMessageBox::question( + nullptr, tr("Spotify plugin not installed"), + tr("An additional plugin is required to use Spotify in Clementine. " + "Would you like to download and install it now?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); return ret == QMessageBox::Yes; } @@ -71,19 +72,21 @@ void SpotifyBlobDownloader::Start() { qDeleteAll(replies_); replies_.clear(); - const QStringList filenames = QStringList() - << "blob" - << "blob" + QString(kSignatureSuffix) - << "libspotify.so.12.1.45" - << "libspotify.so.12.1.45" + QString(kSignatureSuffix); + const QStringList filenames = + QStringList() << "blob" + << "blob" + QString(kSignatureSuffix) + << "libspotify.so.12.1.45" + << "libspotify.so.12.1.45" + QString(kSignatureSuffix); - foreach (const QString& filename, filenames) { - const QUrl url(SpotifyService::kBlobDownloadUrl + version_ + "/" + filename); + foreach(const QString & filename, filenames) { + const QUrl url(SpotifyService::kBlobDownloadUrl + version_ + "/" + + filename); qLog(Info) << "Downloading" << url; QNetworkReply* reply = network_->get(QNetworkRequest(url)); connect(reply, SIGNAL(finished()), SLOT(ReplyFinished())); - connect(reply, SIGNAL(downloadProgress(qint64,qint64)), SLOT(ReplyProgress())); + connect(reply, SIGNAL(downloadProgress(qint64, qint64)), + SLOT(ReplyProgress())); replies_ << reply; } @@ -100,7 +103,7 @@ void SpotifyBlobDownloader::ReplyFinished() { } // Is everything finished? - foreach (QNetworkReply* reply, replies_) { + foreach(QNetworkReply * reply, replies_) { if (!reply->isFinished()) { return; } @@ -110,7 +113,7 @@ void SpotifyBlobDownloader::ReplyFinished() { QMap file_data; QStringList signature_filenames; - foreach (QNetworkReply* reply, replies_) { + foreach(QNetworkReply * reply, replies_) { const QString filename = reply->url().path().section('/', -1, -1); if (filename.endsWith(kSignatureSuffix)) { @@ -123,37 +126,36 @@ void SpotifyBlobDownloader::ReplyFinished() { #ifdef HAVE_QCA // Load the public key QCA::ConvertResult conversion_result; - QCA::PublicKey key = QCA::PublicKey::fromPEMFile(":/clementine-spotify-public.pem", - &conversion_result); + QCA::PublicKey key = QCA::PublicKey::fromPEMFile( + ":/clementine-spotify-public.pem", &conversion_result); if (QCA::ConvertGood != conversion_result) { ShowError("Failed to load Spotify public key"); return; } // Verify signatures - foreach (const QString& signature_filename, signature_filenames) { + foreach(const QString & signature_filename, signature_filenames) { QString actual_filename = signature_filename; actual_filename.remove(kSignatureSuffix); - qLog(Debug) << "Verifying" << actual_filename << "against" << signature_filename; + qLog(Debug) << "Verifying" << actual_filename << "against" + << signature_filename; if (!key.verifyMessage(file_data[actual_filename], - file_data[signature_filename], - QCA::EMSA3_SHA1)) { + file_data[signature_filename], QCA::EMSA3_SHA1)) { ShowError("Invalid signature: " + actual_filename); return; } } -#endif // HAVE_QCA +#endif // HAVE_QCA // Make the destination directory and write the files into it QDir().mkpath(path_); - foreach (const QString& filename, file_data.keys()) { + foreach(const QString & filename, file_data.keys()) { const QString dest_path = path_ + "/" + filename; - if (filename.endsWith(kSignatureSuffix)) - continue; + if (filename.endsWith(kSignatureSuffix)) continue; qLog(Info) << "Writing" << dest_path; @@ -185,7 +187,7 @@ void SpotifyBlobDownloader::ReplyFinished() { link_path += "." + version_parts.takeFirst(); } } -#endif // Q_OS_UNIX +#endif // Q_OS_UNIX } EmitFinished(); @@ -195,7 +197,7 @@ void SpotifyBlobDownloader::ReplyProgress() { int progress = 0; int total = 0; - foreach (QNetworkReply* reply, replies_) { + foreach(QNetworkReply * reply, replies_) { progress += reply->bytesAvailable(); total += reply->rawHeader("Content-Length").toInt(); } @@ -204,14 +206,12 @@ void SpotifyBlobDownloader::ReplyProgress() { progress_->setValue(progress); } -void SpotifyBlobDownloader::Cancel() { - deleteLater(); -} +void SpotifyBlobDownloader::Cancel() { deleteLater(); } void SpotifyBlobDownloader::ShowError(const QString& message) { // Stop any remaining replies before showing the dialog so they don't // carry on in the background - foreach (QNetworkReply* reply, replies_) { + foreach(QNetworkReply * reply, replies_) { disconnect(reply, 0, this, 0); reply->abort(); } diff --git a/src/internet/spotifyblobdownloader.h b/src/internet/spotifyblobdownloader.h index 7304aed4c..c9ed9efba 100644 --- a/src/internet/spotifyblobdownloader.h +++ b/src/internet/spotifyblobdownloader.h @@ -27,7 +27,7 @@ class QProgressDialog; class SpotifyBlobDownloader : public QObject { Q_OBJECT -public: + public: SpotifyBlobDownloader(const QString& version, const QString& path, QObject* parent = 0); ~SpotifyBlobDownloader(); @@ -41,16 +41,16 @@ public: signals: void Finished(); -private slots: + private slots: void ReplyFinished(); void ReplyProgress(); void Cancel(); -private: + private: void ShowError(const QString& message); void EmitFinished(); -private: + private: QString version_; QString path_; @@ -60,4 +60,4 @@ private: QProgressDialog* progress_; }; -#endif // SPOTIFYBLOBDOWNLOADER_H +#endif // SPOTIFYBLOBDOWNLOADER_H diff --git a/src/internet/spotifyserver.cpp b/src/internet/spotifyserver.cpp index 3728b2449..566d6cd24 100644 --- a/src/internet/spotifyserver.cpp +++ b/src/internet/spotifyserver.cpp @@ -26,10 +26,9 @@ #include SpotifyServer::SpotifyServer(QObject* parent) - : AbstractMessageHandler(nullptr, parent), - server_(new QTcpServer(this)), - logged_in_(false) -{ + : AbstractMessageHandler(nullptr, parent), + server_(new QTcpServer(this)), + logged_in_(false) { connect(server_, SIGNAL(newConnection()), SLOT(NewConnection())); } @@ -39,9 +38,7 @@ void SpotifyServer::Init() { } } -int SpotifyServer::server_port() const { - return server_->serverPort(); -} +int SpotifyServer::server_port() const { return server_->serverPort(); } void SpotifyServer::NewConnection() { QTcpSocket* socket = server_->nextPendingConnection(); @@ -50,7 +47,7 @@ void SpotifyServer::NewConnection() { qLog(Info) << "Connection from port" << socket->peerPort(); // Send any login messages that were queued before the client connected - foreach (const pb::spotify::Message& message, queued_login_messages_) { + foreach(const pb::spotify::Message & message, queued_login_messages_) { SendOrQueueMessage(message); } queued_login_messages_.clear(); @@ -73,7 +70,8 @@ void SpotifyServer::SendOrQueueMessage(const pb::spotify::Message& message) { } void SpotifyServer::Login(const QString& username, const QString& password, - pb::spotify::Bitrate bitrate, bool volume_normalisation) { + pb::spotify::Bitrate bitrate, + bool volume_normalisation) { pb::spotify::Message message; pb::spotify::LoginRequest* request = message.mutable_login_request(); @@ -82,15 +80,18 @@ void SpotifyServer::Login(const QString& username, const QString& password, request->set_password(DataCommaSizeFromQString(password)); } request->mutable_playback_settings()->set_bitrate(bitrate); - request->mutable_playback_settings()->set_volume_normalisation(volume_normalisation); + request->mutable_playback_settings()->set_volume_normalisation( + volume_normalisation); SendOrQueueMessage(message); } -void SpotifyServer::SetPlaybackSettings(pb::spotify::Bitrate bitrate, bool volume_normalisation) { +void SpotifyServer::SetPlaybackSettings(pb::spotify::Bitrate bitrate, + bool volume_normalisation) { pb::spotify::Message message; - pb::spotify::PlaybackSettings* request = message.mutable_set_playback_settings_request(); + pb::spotify::PlaybackSettings* request = + message.mutable_set_playback_settings_request(); request->set_bitrate(bitrate); request->set_volume_normalisation(volume_normalisation); @@ -104,18 +105,20 @@ void SpotifyServer::MessageArrived(const pb::spotify::Message& message) { if (response.success()) { // Send any messages that were queued before the client logged in - foreach (const pb::spotify::Message& message, queued_messages_) { + foreach(const pb::spotify::Message & message, queued_messages_) { SendOrQueueMessage(message); } queued_messages_.clear(); } - emit LoginCompleted(response.success(), QStringFromStdString(response.error()), + emit LoginCompleted(response.success(), + QStringFromStdString(response.error()), response.error_code()); } else if (message.has_playlists_updated()) { emit PlaylistsUpdated(message.playlists_updated()); } else if (message.has_load_playlist_response()) { - const pb::spotify::LoadPlaylistResponse& response = message.load_playlist_response(); + const pb::spotify::LoadPlaylistResponse& response = + message.load_playlist_response(); switch (response.request().type()) { case pb::spotify::Inbox: @@ -139,8 +142,9 @@ void SpotifyServer::MessageArrived(const pb::spotify::Message& message) { const QString id = QStringFromStdString(response.id()); if (response.has_data()) { - emit ImageLoaded(id, QImage::fromData(QByteArray( - response.data().data(), response.data().size()))); + emit ImageLoaded( + id, QImage::fromData( + QByteArray(response.data().data(), response.data().size()))); } else { emit ImageLoaded(id, QImage()); } @@ -155,7 +159,8 @@ void SpotifyServer::MessageArrived(const pb::spotify::Message& message) { void SpotifyServer::LoadPlaylist(pb::spotify::PlaylistType type, int index) { pb::spotify::Message message; - pb::spotify::LoadPlaylistRequest* req = message.mutable_load_playlist_request(); + pb::spotify::LoadPlaylistRequest* req = + message.mutable_load_playlist_request(); req->set_type(type); if (index != -1) { @@ -165,10 +170,11 @@ void SpotifyServer::LoadPlaylist(pb::spotify::PlaylistType type, int index) { SendOrQueueMessage(message); } -void SpotifyServer::SyncPlaylist( - pb::spotify::PlaylistType type, int index, bool offline) { +void SpotifyServer::SyncPlaylist(pb::spotify::PlaylistType type, int index, + bool offline) { pb::spotify::Message message; - pb::spotify::SyncPlaylistRequest* req = message.mutable_sync_playlist_request(); + pb::spotify::SyncPlaylistRequest* req = + message.mutable_sync_playlist_request(); req->mutable_request()->set_type(type); if (index != -1) { req->mutable_request()->set_user_playlist_index(index); @@ -178,9 +184,7 @@ void SpotifyServer::SyncPlaylist( SendOrQueueMessage(message); } -void SpotifyServer::SyncInbox() { - SyncPlaylist(pb::spotify::Inbox, -1, true); -} +void SpotifyServer::SyncInbox() { SyncPlaylist(pb::spotify::Inbox, -1, true); } void SpotifyServer::SyncStarred() { SyncPlaylist(pb::spotify::Starred, -1, true); @@ -191,13 +195,9 @@ void SpotifyServer::SyncUserPlaylist(int index) { SyncPlaylist(pb::spotify::UserPlaylist, index, true); } -void SpotifyServer::LoadInbox() { - LoadPlaylist(pb::spotify::Inbox); -} +void SpotifyServer::LoadInbox() { LoadPlaylist(pb::spotify::Inbox); } -void SpotifyServer::LoadStarred() { - LoadPlaylist(pb::spotify::Starred); -} +void SpotifyServer::LoadStarred() { LoadPlaylist(pb::spotify::Starred); } void SpotifyServer::LoadUserPlaylist(int index) { Q_ASSERT(index >= 0); @@ -208,10 +208,9 @@ void SpotifyServer::StartPlaybackLater(const QString& uri, quint16 port) { QTimer* timer = new QTimer(this); connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater())); - timer->start(100); // lol - NewClosure(timer, SIGNAL(timeout()), - this, SLOT(StartPlayback(QString,quint16)), - uri, port); + timer->start(100); // lol + NewClosure(timer, SIGNAL(timeout()), this, + SLOT(StartPlayback(QString, quint16)), uri, port); } void SpotifyServer::StartPlayback(const QString& uri, quint16 port) { @@ -259,7 +258,8 @@ void SpotifyServer::AlbumBrowse(const QString& uri) { void SpotifyServer::LoadToplist() { pb::spotify::Message message; - pb::spotify::BrowseToplistRequest* req = message.mutable_browse_toplist_request(); + pb::spotify::BrowseToplistRequest* req = + message.mutable_browse_toplist_request(); req->set_type(pb::spotify::BrowseToplistRequest::Tracks); req->set_region(pb::spotify::BrowseToplistRequest::Everywhere); diff --git a/src/internet/spotifyserver.h b/src/internet/spotifyserver.h index ca06d62c3..a235504f6 100644 --- a/src/internet/spotifyserver.h +++ b/src/internet/spotifyserver.h @@ -24,14 +24,13 @@ #include #include - class QTcpServer; class QTcpSocket; class SpotifyServer : public AbstractMessageHandler { Q_OBJECT -public: + public: SpotifyServer(QObject* parent = 0); void Init(); @@ -48,12 +47,13 @@ public: void Search(const QString& text, int limit, int limit_album = 0); void LoadImage(const QString& id); void AlbumBrowse(const QString& uri); - void SetPlaybackSettings(pb::spotify::Bitrate bitrate, bool volume_normalisation); + void SetPlaybackSettings(pb::spotify::Bitrate bitrate, + bool volume_normalisation); void LoadToplist(); int server_port() const; -public slots: + public slots: void StartPlayback(const QString& uri, quint16 port); void Seek(qint64 offset_bytes); @@ -72,13 +72,13 @@ signals: void AlbumBrowseResults(const pb::spotify::BrowseAlbumResponse& response); void ToplistBrowseResults(const pb::spotify::BrowseToplistResponse& response); -protected: + protected: void MessageArrived(const pb::spotify::Message& message); -private slots: + private slots: void NewConnection(); -private: + private: void LoadPlaylist(pb::spotify::PlaylistType type, int index = -1); void SyncPlaylist(pb::spotify::PlaylistType type, int index, bool offline); void SendOrQueueMessage(const pb::spotify::Message& message); @@ -90,4 +90,4 @@ private: QList queued_messages_; }; -#endif // SPOTIFYSERVER_H +#endif // SPOTIFYSERVER_H diff --git a/src/internet/spotifyservice.cpp b/src/internet/spotifyservice.cpp index e3f623121..82ef17648 100644 --- a/src/internet/spotifyservice.cpp +++ b/src/internet/spotifyservice.cpp @@ -38,7 +38,8 @@ Q_DECLARE_METATYPE(QStandardItem*); const char* SpotifyService::kServiceName = "Spotify"; const char* SpotifyService::kSettingsGroup = "Spotify"; -const char* SpotifyService::kBlobDownloadUrl = "http://spotify.clementine-player.org/"; +const char* SpotifyService::kBlobDownloadUrl = + "http://spotify.clementine-player.org/"; const int SpotifyService::kSearchDelayMsec = 400; SpotifyService::SpotifyService(Application* app, InternetModel* parent) @@ -56,22 +57,24 @@ SpotifyService::SpotifyService(Application* app, InternetModel* parent) search_delay_(new QTimer(this)), login_state_(LoginState_OtherError), bitrate_(pb::spotify::Bitrate320k), - volume_normalisation_(false) -{ - // Build the search path for the binary blob. - // Look for one distributed alongside clementine first, then check in the - // user's home directory for any that have been downloaded. + volume_normalisation_(false) { +// Build the search path for the binary blob. +// Look for one distributed alongside clementine first, then check in the +// user's home directory for any that have been downloaded. #ifdef Q_OS_MAC system_blob_path_ = QCoreApplication::applicationDirPath() + - "/../PlugIns/clementine-spotifyblob"; + "/../PlugIns/clementine-spotifyblob"; #else system_blob_path_ = QCoreApplication::applicationDirPath() + - "/clementine-spotifyblob" CMAKE_EXECUTABLE_SUFFIX; + "/clementine-spotifyblob" CMAKE_EXECUTABLE_SUFFIX; #endif - local_blob_version_ = QString("version%1-%2bit").arg(SPOTIFY_BLOB_VERSION).arg(sizeof(void*) * 8); - local_blob_path_ = Utilities::GetConfigPath(Utilities::Path_LocalSpotifyBlob) + - "/" + local_blob_version_ + "/blob"; + local_blob_version_ = QString("version%1-%2bit") + .arg(SPOTIFY_BLOB_VERSION) + .arg(sizeof(void*) * 8); + local_blob_path_ = + Utilities::GetConfigPath(Utilities::Path_LocalSpotifyBlob) + "/" + + local_blob_version_ + "/blob"; qLog(Debug) << "Spotify system blob path:" << system_blob_path_; qLog(Debug) << "Spotify local blob path:" << local_blob_path_; @@ -139,8 +142,9 @@ void SpotifyService::Login(const QString& username, const QString& password) { EnsureServerCreated(username, password); } -void SpotifyService::LoginCompleted(bool success, const QString& error, - pb::spotify::LoginResponse_Error error_code) { +void SpotifyService::LoginCompleted( + bool success, const QString& error, + pb::spotify::LoginResponse_Error error_code) { if (login_task_id_) { app_->task_manager()->SetTaskFinished(login_task_id_); login_task_id_ = 0; @@ -151,37 +155,40 @@ void SpotifyService::LoginCompleted(bool success, const QString& error, QString error_copy(error); switch (error_code) { - case pb::spotify::LoginResponse_Error_BadUsernameOrPassword: - login_state_ = LoginState_BadCredentials; - break; + case pb::spotify::LoginResponse_Error_BadUsernameOrPassword: + login_state_ = LoginState_BadCredentials; + break; - case pb::spotify::LoginResponse_Error_UserBanned: - login_state_ = LoginState_Banned; - break; + case pb::spotify::LoginResponse_Error_UserBanned: + login_state_ = LoginState_Banned; + break; - case pb::spotify::LoginResponse_Error_UserNeedsPremium: - login_state_ = LoginState_NoPremium; - break; + case pb::spotify::LoginResponse_Error_UserNeedsPremium: + login_state_ = LoginState_NoPremium; + break; - case pb::spotify::LoginResponse_Error_ReloginFailed: - if (login_state_ == LoginState_LoggedIn) { - // This is the first time the relogin has failed - show a message this - // time only. - error_copy = tr("You have been logged out of Spotify, please re-enter your password in the Settings dialog."); - } else { - show_error_dialog = false; - } + case pb::spotify::LoginResponse_Error_ReloginFailed: + if (login_state_ == LoginState_LoggedIn) { + // This is the first time the relogin has failed - show a message this + // time only. + error_copy = + tr("You have been logged out of Spotify, please re-enter your " + "password in the Settings dialog."); + } else { + show_error_dialog = false; + } - login_state_ = LoginState_ReloginFailed; - break; + login_state_ = LoginState_ReloginFailed; + break; - default: - login_state_ = LoginState_OtherError; - break; + default: + login_state_ = LoginState_OtherError; + break; } if (show_error_dialog) { - QMessageBox::warning(nullptr, tr("Spotify login error"), error_copy, QMessageBox::Close); + QMessageBox::warning(nullptr, tr("Spotify login error"), error_copy, + QMessageBox::Close); } } else { login_state_ = LoginState_LoggedIn; @@ -208,9 +215,10 @@ void SpotifyService::ReloadSettings() { QSettings s; s.beginGroup(kSettingsGroup); - login_state_ = LoginState(s.value("login_state", LoginState_OtherError).toInt()); + login_state_ = + LoginState(s.value("login_state", LoginState_OtherError).toInt()); bitrate_ = static_cast( - s.value("bitrate", pb::spotify::Bitrate320k).toInt()); + s.value("bitrate", pb::spotify::Bitrate320k).toInt()); volume_normalisation_ = s.value("volume_normalisation", false).toBool(); if (server_ && blob_process_) { @@ -227,25 +235,30 @@ void SpotifyService::EnsureServerCreated(const QString& username, delete server_; server_ = new SpotifyServer(this); - connect(server_, SIGNAL(LoginCompleted(bool,QString,pb::spotify::LoginResponse_Error)), - SLOT(LoginCompleted(bool,QString,pb::spotify::LoginResponse_Error))); + connect( + server_, + SIGNAL(LoginCompleted(bool, QString, pb::spotify::LoginResponse_Error)), + SLOT(LoginCompleted(bool, QString, pb::spotify::LoginResponse_Error))); connect(server_, SIGNAL(PlaylistsUpdated(pb::spotify::Playlists)), SLOT(PlaylistsUpdated(pb::spotify::Playlists))); connect(server_, SIGNAL(InboxLoaded(pb::spotify::LoadPlaylistResponse)), SLOT(InboxLoaded(pb::spotify::LoadPlaylistResponse))); connect(server_, SIGNAL(StarredLoaded(pb::spotify::LoadPlaylistResponse)), SLOT(StarredLoaded(pb::spotify::LoadPlaylistResponse))); - connect(server_, SIGNAL(UserPlaylistLoaded(pb::spotify::LoadPlaylistResponse)), + connect(server_, + SIGNAL(UserPlaylistLoaded(pb::spotify::LoadPlaylistResponse)), SLOT(UserPlaylistLoaded(pb::spotify::LoadPlaylistResponse))); connect(server_, SIGNAL(PlaybackError(QString)), SIGNAL(StreamError(QString))); connect(server_, SIGNAL(SearchResults(pb::spotify::SearchResponse)), SLOT(SearchResults(pb::spotify::SearchResponse))); - connect(server_, SIGNAL(ImageLoaded(QString,QImage)), - SIGNAL(ImageLoaded(QString,QImage))); - connect(server_, SIGNAL(SyncPlaylistProgress(pb::spotify::SyncPlaylistProgress)), + connect(server_, SIGNAL(ImageLoaded(QString, QImage)), + SIGNAL(ImageLoaded(QString, QImage))); + connect(server_, + SIGNAL(SyncPlaylistProgress(pb::spotify::SyncPlaylistProgress)), SLOT(SyncPlaylistProgress(pb::spotify::SyncPlaylistProgress))); - connect(server_, SIGNAL(ToplistBrowseResults(pb::spotify::BrowseToplistResponse)), + connect(server_, + SIGNAL(ToplistBrowseResults(pb::spotify::BrowseToplistResponse)), SLOT(ToplistLoaded(pb::spotify::BrowseToplistResponse))); server_->Init(); @@ -263,7 +276,8 @@ void SpotifyService::EnsureServerCreated(const QString& username, login_password = QString(); } - server_->Login(login_username, login_password, bitrate_, volume_normalisation_); + server_->Login(login_username, login_password, bitrate_, + volume_normalisation_); StartBlobProcess(); } @@ -292,11 +306,11 @@ void SpotifyService::StartBlobProcess() { app_->task_manager()->SetTaskFinished(login_task_id_); } - #ifdef HAVE_SPOTIFY_DOWNLOADER - if (SpotifyBlobDownloader::Prompt()) { - InstallBlob(); - } - #endif +#ifdef HAVE_SPOTIFY_DOWNLOADER + if (SpotifyBlobDownloader::Prompt()) { + InstallBlob(); + } +#endif return; } @@ -306,34 +320,30 @@ void SpotifyService::StartBlobProcess() { blob_process_->setProcessChannelMode(QProcess::ForwardedChannels); blob_process_->setProcessEnvironment(env); - connect(blob_process_, - SIGNAL(error(QProcess::ProcessError)), + connect(blob_process_, SIGNAL(error(QProcess::ProcessError)), SLOT(BlobProcessError(QProcess::ProcessError))); qLog(Info) << "Starting" << blob_path; blob_process_->start( - blob_path, QStringList() << QString::number(server_->server_port())); + blob_path, QStringList() << QString::number(server_->server_port())); } bool SpotifyService::IsBlobInstalled() const { - return QFile::exists(system_blob_path_) || - QFile::exists(local_blob_path_); + return QFile::exists(system_blob_path_) || QFile::exists(local_blob_path_); } void SpotifyService::InstallBlob() { #ifdef HAVE_SPOTIFY_DOWNLOADER // The downloader deletes itself when it finishes SpotifyBlobDownloader* downloader = new SpotifyBlobDownloader( - local_blob_version_, QFileInfo(local_blob_path_).path(), this); + local_blob_version_, QFileInfo(local_blob_path_).path(), this); connect(downloader, SIGNAL(Finished()), SLOT(BlobDownloadFinished())); connect(downloader, SIGNAL(Finished()), SIGNAL(BlobStateChanged())); downloader->Start(); #endif // HAVE_SPOTIFY_DOWNLOADER } -void SpotifyService::BlobDownloadFinished() { - EnsureServerCreated(); -} +void SpotifyService::BlobDownloadFinished() { EnsureServerCreated(); } void SpotifyService::PlaylistsUpdated(const pb::spotify::Playlists& response) { if (login_task_id_) { @@ -343,31 +353,32 @@ void SpotifyService::PlaylistsUpdated(const pb::spotify::Playlists& response) { // Create starred and inbox playlists if they're not here already if (!search_) { - search_ = new QStandardItem(IconLoader::Load("edit-find"), - tr("Search results")); - search_->setToolTip(tr("Start typing something on the search box above to " - "fill this search results list")); + search_ = + new QStandardItem(IconLoader::Load("edit-find"), tr("Search results")); + search_->setToolTip( + tr("Start typing something on the search box above to " + "fill this search results list")); search_->setData(Type_SearchResults, InternetModel::Role_Type); search_->setData(InternetModel::PlayBehaviour_MultipleItems, - InternetModel::Role_PlayBehaviour); + InternetModel::Role_PlayBehaviour); starred_ = new QStandardItem(QIcon(":/star-on.png"), tr("Starred")); starred_->setData(Type_StarredPlaylist, InternetModel::Role_Type); starred_->setData(true, InternetModel::Role_CanLazyLoad); starred_->setData(InternetModel::PlayBehaviour_MultipleItems, - InternetModel::Role_PlayBehaviour); + InternetModel::Role_PlayBehaviour); inbox_ = new QStandardItem(IconLoader::Load("mail-message"), tr("Inbox")); inbox_->setData(Type_InboxPlaylist, InternetModel::Role_Type); inbox_->setData(true, InternetModel::Role_CanLazyLoad); inbox_->setData(InternetModel::PlayBehaviour_MultipleItems, - InternetModel::Role_PlayBehaviour); + InternetModel::Role_PlayBehaviour); toplist_ = new QStandardItem(QIcon(), tr("Top tracks")); toplist_->setData(Type_Toplist, InternetModel::Role_Type); toplist_->setData(true, InternetModel::Role_CanLazyLoad); toplist_->setData(InternetModel::PlayBehaviour_MultipleItems, - InternetModel::Role_PlayBehaviour); + InternetModel::Role_PlayBehaviour); root_->appendRow(search_); root_->appendRow(toplist_); @@ -382,19 +393,20 @@ void SpotifyService::PlaylistsUpdated(const pb::spotify::Playlists& response) { } // Remove and recreate the other playlists - foreach (QStandardItem* item, playlists_) { + foreach(QStandardItem * item, playlists_) { item->parent()->removeRow(item->row()); } playlists_.clear(); - for (int i=0 ; isetData(InternetModel::Type_UserPlaylist, InternetModel::Role_Type); item->setData(true, InternetModel::Role_CanLazyLoad); item->setData(msg.index(), Role_UserPlaylistIndex); - item->setData(InternetModel::PlayBehaviour_MultipleItems, InternetModel::Role_PlayBehaviour); + item->setData(InternetModel::PlayBehaviour_MultipleItems, + InternetModel::Role_PlayBehaviour); root_->appendRow(item); playlists_ << item; @@ -404,12 +416,13 @@ void SpotifyService::PlaylistsUpdated(const pb::spotify::Playlists& response) { } } -bool SpotifyService::DoPlaylistsDiffer(const pb::spotify::Playlists& response) const { +bool SpotifyService::DoPlaylistsDiffer(const pb::spotify::Playlists& response) + const { if (playlists_.count() != response.playlist_size()) { return true; } - for (int i=0 ; idata(Role_UserPlaylistIndex).toInt() == index) { return item; } @@ -452,9 +468,11 @@ QStandardItem* SpotifyService::PlaylistBySpotifyIndex(int index) const { return nullptr; } -void SpotifyService::UserPlaylistLoaded(const pb::spotify::LoadPlaylistResponse& response) { +void SpotifyService::UserPlaylistLoaded( + const pb::spotify::LoadPlaylistResponse& response) { // Find a playlist with this index - QStandardItem* item = PlaylistBySpotifyIndex(response.request().user_playlist_index()); + QStandardItem* item = + PlaylistBySpotifyIndex(response.request().user_playlist_index()); if (item) { FillPlaylist(item, response); } @@ -463,10 +481,9 @@ void SpotifyService::UserPlaylistLoaded(const pb::spotify::LoadPlaylistResponse& void SpotifyService::FillPlaylist( QStandardItem* item, const google::protobuf::RepeatedPtrField& tracks) { - if (item->hasChildren()) - item->removeRows(0, item->rowCount()); + if (item->hasChildren()) item->removeRows(0, item->rowCount()); - for (int i=0 ; i < tracks.size() ; ++i) { + for (int i = 0; i < tracks.size(); ++i) { Song song; SongFromProtobuf(tracks.Get(i), &song); @@ -476,12 +493,14 @@ void SpotifyService::FillPlaylist( } } -void SpotifyService::FillPlaylist(QStandardItem* item, const pb::spotify::LoadPlaylistResponse& response) { +void SpotifyService::FillPlaylist( + QStandardItem* item, const pb::spotify::LoadPlaylistResponse& response) { qLog(Debug) << "Filling playlist:" << item->text(); FillPlaylist(item, response.track()); } -void SpotifyService::SongFromProtobuf(const pb::spotify::Track& track, Song* song) { +void SpotifyService::SongFromProtobuf(const pb::spotify::Track& track, + Song* song) { song->set_rating(track.starred() ? 1.0 : 0.0); song->set_title(QStringFromStdString(track.title())); song->set_album(QStringFromStdString(track.album())); @@ -491,10 +510,11 @@ void SpotifyService::SongFromProtobuf(const pb::spotify::Track& track, Song* son song->set_track(track.track()); song->set_year(track.year()); song->set_url(QUrl(QStringFromStdString(track.uri()))); - song->set_art_automatic("spotify://image/" + QStringFromStdString(track.album_art_id())); + song->set_art_automatic("spotify://image/" + + QStringFromStdString(track.album_art_id())); QStringList artists; - for (int i=0 ; iaddAction(IconLoader::Load("configure"), tr("Configure Spotify..."), this, SLOT(ShowConfig())); + context_menu_->addAction(IconLoader::Load("configure"), + tr("Configure Spotify..."), this, + SLOT(ShowConfig())); playlist_context_menu_ = new QMenu; playlist_context_menu_->addActions(GetPlaylistActions()); playlist_context_menu_->addSeparator(); playlist_sync_action_ = playlist_context_menu_->addAction( - IconLoader::Load("view-refresh"), - tr("Make playlist available offline"), - this, - SLOT(SyncPlaylist())); + IconLoader::Load("view-refresh"), tr("Make playlist available offline"), + this, SLOT(SyncPlaylist())); playlist_context_menu_->addSeparator(); playlist_context_menu_->addAction(IconLoader::Load("configure"), - tr("Configure Spotify..."), - this, SLOT(ShowConfig())); + tr("Configure Spotify..."), this, + SLOT(ShowConfig())); } void SpotifyService::ClearSearchResults() { - if (search_) - search_->removeRows(0, search_->rowCount()); + if (search_) search_->removeRows(0, search_->rowCount()); } void SpotifyService::SyncPlaylist() { @@ -558,11 +575,13 @@ void SpotifyService::SyncPlaylist() { } case Type_InboxPlaylist: server_->SyncInbox(); - inbox_sync_id_ = app_->task_manager()->StartTask(tr("Syncing Spotify inbox")); + inbox_sync_id_ = + app_->task_manager()->StartTask(tr("Syncing Spotify inbox")); break; case Type_StarredPlaylist: server_->SyncStarred(); - starred_sync_id_ = app_->task_manager()->StartTask(tr("Syncing Spotify starred tracks")); + starred_sync_id_ = + app_->task_manager()->StartTask(tr("Syncing Spotify starred tracks")); break; default: break; @@ -596,7 +615,8 @@ void SpotifyService::DoSearch() { } } -void SpotifyService::SearchResults(const pb::spotify::SearchResponse& response) { +void SpotifyService::SearchResults( + const pb::spotify::SearchResponse& response) { if (QStringFromStdString(response.request().query()) != pending_search_) { qLog(Debug) << "Old search result for" << QStringFromStdString(response.request().query()) @@ -606,7 +626,7 @@ void SpotifyService::SearchResults(const pb::spotify::SearchResponse& response) pending_search_.clear(); SongList songs; - for (int i=0 ; iappendRow(child); } - const QString did_you_mean_suggestion = QStringFromStdString(response.did_you_mean()); + const QString did_you_mean_suggestion = + QStringFromStdString(response.did_you_mean()); qLog(Debug) << "Did you mean suggestion: " << did_you_mean_suggestion; if (!did_you_mean_suggestion.isEmpty()) { search_box_->did_you_mean()->Show(did_you_mean_suggestion); @@ -653,8 +674,7 @@ void SpotifyService::ShowContextMenu(const QPoint& global_pos) { QStandardItem* item = model()->itemFromIndex(model()->current_index()); if (item) { int type = item->data(InternetModel::Role_Type).toInt(); - if (type == Type_InboxPlaylist || - type == Type_StarredPlaylist || + if (type == Type_InboxPlaylist || type == Type_StarredPlaylist || type == InternetModel::Type_UserPlaylist) { playlist_sync_action_->setData(qVariantFromValue(item)); playlist_context_menu_->popup(global_pos); @@ -665,10 +685,10 @@ void SpotifyService::ShowContextMenu(const QPoint& global_pos) { context_menu_->popup(global_pos); } -void SpotifyService::ItemDoubleClicked(QStandardItem* item) { -} +void SpotifyService::ItemDoubleClicked(QStandardItem* item) {} -void SpotifyService::DropMimeData(const QMimeData* data, const QModelIndex& index) { +void SpotifyService::DropMimeData(const QMimeData* data, + const QModelIndex& index) { qLog(Debug) << Q_FUNC_INFO << data->urls(); } diff --git a/src/internet/spotifyservice.h b/src/internet/spotifyservice.h index 530aa0a5d..39d7f5d0c 100644 --- a/src/internet/spotifyservice.h +++ b/src/internet/spotifyservice.h @@ -17,7 +17,7 @@ class QMenu; class SpotifyService : public InternetService { Q_OBJECT -public: + public: SpotifyService(Application* app, InternetModel* parent); ~SpotifyService(); @@ -29,9 +29,7 @@ public: Type_Toplist, }; - enum Role { - Role_UserPlaylistIndex = InternetModel::RoleCount, - }; + enum Role { Role_UserPlaylistIndex = InternetModel::RoleCount, }; // Values are persisted - don't change. enum LoginState { @@ -78,23 +76,24 @@ signals: void LoginFinished(bool success); void ImageLoaded(const QString& id, const QImage& image); -public slots: + public slots: void Search(const QString& text, bool now = false); void ShowConfig(); -private: + private: void StartBlobProcess(); void FillPlaylist( QStandardItem* item, const google::protobuf::RepeatedPtrField& tracks); - void FillPlaylist(QStandardItem* item, const pb::spotify::LoadPlaylistResponse& response); + void FillPlaylist(QStandardItem* item, + const pb::spotify::LoadPlaylistResponse& response); void EnsureMenuCreated(); void ClearSearchResults(); QStandardItem* PlaylistBySpotifyIndex(int index) const; bool DoPlaylistsDiffer(const pb::spotify::Playlists& response) const; -private slots: + private slots: void EnsureServerCreated(const QString& username = QString(), const QString& password = QString()); void BlobProcessError(QProcess::ProcessError error); @@ -113,7 +112,7 @@ private slots: void SyncPlaylist(); void BlobDownloadFinished(); -private: + private: SpotifyServer* server_; QString system_blob_path_; diff --git a/src/internet/spotifysettingspage.cpp b/src/internet/spotifysettingspage.cpp index f1a73bfa7..011457674 100644 --- a/src/internet/spotifysettingspage.cpp +++ b/src/internet/spotifysettingspage.cpp @@ -32,11 +32,10 @@ #include SpotifySettingsPage::SpotifySettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_SpotifySettingsPage), - service_(InternetModel::Service()), - validated_(false) -{ + : SettingsPage(dialog), + ui_(new Ui_SpotifySettingsPage), + service_(InternetModel::Service()), + validated_(false) { ui_->setupUi(this); setWindowIcon(QIcon(":/icons/48x48/spotify.png")); @@ -64,9 +63,7 @@ SpotifySettingsPage::SpotifySettingsPage(SettingsDialog* dialog) BlobStateChanged(); } -SpotifySettingsPage::~SpotifySettingsPage() { - delete ui_; -} +SpotifySettingsPage::~SpotifySettingsPage() { delete ui_; } void SpotifySettingsPage::BlobStateChanged() { const bool installed = service_->IsBlobInstalled(); @@ -81,9 +78,7 @@ void SpotifySettingsPage::BlobStateChanged() { #endif } -void SpotifySettingsPage::DownloadBlob() { - service_->InstallBlob(); -} +void SpotifySettingsPage::DownloadBlob() { service_->InstallBlob(); } void SpotifySettingsPage::Login() { if (!service_->IsBlobInstalled()) { @@ -124,7 +119,8 @@ void SpotifySettingsPage::Save() { s.setValue("username", ui_->username->text()); s.setValue("password", ui_->password->text()); - s.setValue("bitrate", ui_->bitrate->itemData(ui_->bitrate->currentIndex()).toInt()); + s.setValue("bitrate", + ui_->bitrate->itemData(ui_->bitrate->currentIndex()).toInt()); s.setValue("volume_normalisation", ui_->volume_normalisation->isChecked()); } @@ -139,28 +135,33 @@ void SpotifySettingsPage::UpdateLoginState() { const bool logged_in = service_->login_state() == SpotifyService::LoginState_LoggedIn; - ui_->login_state->SetLoggedIn(logged_in ? LoginStateWidget::LoggedIn - : LoginStateWidget::LoggedOut, - ui_->username->text()); + ui_->login_state->SetLoggedIn( + logged_in ? LoginStateWidget::LoggedIn : LoginStateWidget::LoggedOut, + ui_->username->text()); ui_->login_state->SetAccountTypeVisible(!logged_in); switch (service_->login_state()) { - case SpotifyService::LoginState_NoPremium: - ui_->login_state->SetAccountTypeText(tr("You do not have a Spotify Premium account.")); - break; + case SpotifyService::LoginState_NoPremium: + ui_->login_state->SetAccountTypeText( + tr("You do not have a Spotify Premium account.")); + break; - case SpotifyService::LoginState_Banned: - case SpotifyService::LoginState_BadCredentials: - ui_->login_state->SetAccountTypeText(tr("Your username or password was incorrect.")); - break; + case SpotifyService::LoginState_Banned: + case SpotifyService::LoginState_BadCredentials: + ui_->login_state->SetAccountTypeText( + tr("Your username or password was incorrect.")); + break; - case SpotifyService::LoginState_ReloginFailed: - ui_->login_state->SetAccountTypeText(tr("You have been logged out of Spotify, please re-enter your password.")); - break; + case SpotifyService::LoginState_ReloginFailed: + ui_->login_state->SetAccountTypeText( + tr("You have been logged out of Spotify, please re-enter your " + "password.")); + break; - default: - ui_->login_state->SetAccountTypeText(tr("A Spotify Premium account is required.")); - break; + default: + ui_->login_state->SetAccountTypeText( + tr("A Spotify Premium account is required.")); + break; } } diff --git a/src/internet/spotifysettingspage.h b/src/internet/spotifysettingspage.h index d36b8b4a9..68ac10c29 100644 --- a/src/internet/spotifysettingspage.h +++ b/src/internet/spotifysettingspage.h @@ -27,26 +27,26 @@ class SpotifyService; class SpotifySettingsPage : public SettingsPage { Q_OBJECT -public: + public: SpotifySettingsPage(SettingsDialog* dialog); ~SpotifySettingsPage(); void Load(); void Save(); -public slots: + public slots: void BlobStateChanged(); void DownloadBlob(); -private slots: + private slots: void Login(); void LoginFinished(bool success); void Logout(); -private: + private: void UpdateLoginState(); -private: + private: Ui_SpotifySettingsPage* ui_; SpotifyService* service_; @@ -55,4 +55,4 @@ private: QString original_password_; }; -#endif // SPOTIFYSETTINGSPAGE_H +#endif // SPOTIFYSETTINGSPAGE_H diff --git a/src/internet/subsonicservice.cpp b/src/internet/subsonicservice.cpp index bb9443d9c..64c7bed88 100644 --- a/src/internet/subsonicservice.cpp +++ b/src/internet/subsonicservice.cpp @@ -36,32 +36,28 @@ const char* SubsonicService::kFtsTable = "subsonic_songs_fts"; const int SubsonicService::kMaxRedirects = 10; SubsonicService::SubsonicService(Application* app, InternetModel* parent) - : InternetService(kServiceName, app, parent, parent), - network_(new QNetworkAccessManager(this)), - url_handler_(new SubsonicUrlHandler(this, this)), - scanner_(new SubsonicLibraryScanner(this, this)), - load_database_task_id_(0), - context_menu_(nullptr), - root_(nullptr), - library_backend_(nullptr), - library_model_(nullptr), - library_filter_(nullptr), - library_sort_model_(new QSortFilterProxyModel(this)), - total_song_count_(0), - login_state_(LoginState_OtherError), - redirect_count_(0) { + : InternetService(kServiceName, app, parent, parent), + network_(new QNetworkAccessManager(this)), + url_handler_(new SubsonicUrlHandler(this, this)), + scanner_(new SubsonicLibraryScanner(this, this)), + load_database_task_id_(0), + context_menu_(nullptr), + root_(nullptr), + library_backend_(nullptr), + library_model_(nullptr), + library_filter_(nullptr), + library_sort_model_(new QSortFilterProxyModel(this)), + total_song_count_(0), + login_state_(LoginState_OtherError), + redirect_count_(0) { app_->player()->RegisterUrlHandler(url_handler_); - connect(scanner_, SIGNAL(ScanFinished()), - SLOT(ReloadDatabaseFinished())); + connect(scanner_, SIGNAL(ScanFinished()), SLOT(ReloadDatabaseFinished())); library_backend_ = new LibraryBackend; library_backend_->moveToThread(app_->database()->thread()); - library_backend_->Init(app_->database(), - kSongsTable, - QString::null, - QString::null, - kFtsTable); + library_backend_->Init(app_->database(), kSongsTable, QString::null, + QString::null, kFtsTable); connect(library_backend_, SIGNAL(TotalSongCountUpdated(int)), SLOT(UpdateTotalSongCount(int))); @@ -87,29 +83,23 @@ SubsonicService::SubsonicService(Application* app, InternetModel* parent) context_menu_ = new QMenu; context_menu_->addActions(GetPlaylistActions()); context_menu_->addSeparator(); - context_menu_->addAction( - IconLoader::Load("view-refresh"), - tr("Refresh catalogue"), - this, SLOT(ReloadDatabase())); + context_menu_->addAction(IconLoader::Load("view-refresh"), + tr("Refresh catalogue"), this, + SLOT(ReloadDatabase())); QAction* config_action = context_menu_->addAction( - IconLoader::Load("configure"), - tr("Configure Subsonic..."), - this, SLOT(ShowConfig())); + IconLoader::Load("configure"), tr("Configure Subsonic..."), this, + SLOT(ShowConfig())); context_menu_->addSeparator(); context_menu_->addMenu(library_filter_->menu()); library_filter_->AddMenuAction(config_action); app_->global_search()->AddProvider(new LibrarySearchProvider( - library_backend_, - tr("Subsonic"), - "subsonic", - QIcon(":/providers/subsonic.png"), - true, app_, this)); + library_backend_, tr("Subsonic"), "subsonic", + QIcon(":/providers/subsonic.png"), true, app_, this)); } -SubsonicService::~SubsonicService() { -} +SubsonicService::~SubsonicService() {} QStandardItem* SubsonicService::CreateRootItem() { root_ = new QStandardItem(QIcon(":providers/subsonic.png"), kServiceName); @@ -143,9 +133,7 @@ void SubsonicService::ShowContextMenu(const QPoint& global_pos) { context_menu_->popup(global_pos); } -QWidget* SubsonicService::HeaderWidget() const { - return library_filter_; -} +QWidget* SubsonicService::HeaderWidget() const { return library_filter_; } void SubsonicService::ReloadSettings() { QSettings s; @@ -160,13 +148,13 @@ void SubsonicService::ReloadSettings() { } bool SubsonicService::IsConfigured() const { - return !configured_server_.isEmpty() && - !username_.isEmpty() && + return !configured_server_.isEmpty() && !username_.isEmpty() && !password_.isEmpty(); } void SubsonicService::Login() { - // Recreate fresh network state, otherwise old HTTPS settings seem to get reused + // Recreate fresh network state, otherwise old HTTPS settings seem to get + // reused network_->deleteLater(); network_ = new QNetworkAccessManager(this); network_->setCookieJar(new QNetworkCookieJar(network_)); @@ -182,8 +170,8 @@ void SubsonicService::Login() { } } -void SubsonicService::Login( - const QString& server, const QString& username, const QString& password, const bool& usesslv3) { +void SubsonicService::Login(const QString& server, const QString& username, + const QString& password, const bool& usesslv3) { UpdateServer(server); username_ = username; password_ = password; @@ -193,9 +181,8 @@ void SubsonicService::Login( void SubsonicService::Ping() { QNetworkReply* reply = Send(BuildRequestUrl("ping")); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(OnPingFinished(QNetworkReply*)), - reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(OnPingFinished(QNetworkReply*)), reply); } QUrl SubsonicService::BuildRequestUrl(const QString& view) const { @@ -227,7 +214,7 @@ QNetworkReply* SubsonicService::Send(const QUrl& url) { sslconfig.setProtocol(QSsl::SslV3); } request.setSslConfiguration(sslconfig); - QNetworkReply *reply = network_->get(request); + QNetworkReply* reply = network_->get(request); return reply; } @@ -237,8 +224,8 @@ void SubsonicService::UpdateTotalSongCount(int count) { void SubsonicService::ReloadDatabase() { if (!load_database_task_id_) { - load_database_task_id_ = app_->task_manager()->StartTask( - tr("Fetching Subsonic library")); + load_database_task_id_ = + app_->task_manager()->StartTask(tr("Fetching Subsonic library")); } scanner_->Scan(); } @@ -252,7 +239,8 @@ void SubsonicService::ReloadDatabaseFinished() { library_model_->Reset(); } -void SubsonicService::OnLoginStateChanged(SubsonicService::LoginState newstate) { +void SubsonicService::OnLoginStateChanged( + SubsonicService::LoginState newstate) { // TODO: library refresh logic? } @@ -260,7 +248,7 @@ void SubsonicService::OnPingFinished(QNetworkReply* reply) { reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { - switch(reply->error()) { + switch (reply->error()) { case QNetworkReply::ConnectionRefusedError: login_state_ = LoginState_ConnectionRefused; break; @@ -273,18 +261,20 @@ void SubsonicService::OnPingFinished(QNetworkReply* reply) { case QNetworkReply::SslHandshakeFailedError: login_state_ = LoginState_SslError; break; - default: //Treat uncaught error types here as generic + default: // Treat uncaught error types here as generic login_state_ = LoginState_BadServer; break; } qLog(Error) << "Failed to connect (" - << Utilities::EnumToString(QNetworkReply::staticMetaObject, "NetworkError", reply->error()) + << Utilities::EnumToString(QNetworkReply::staticMetaObject, + "NetworkError", reply->error()) << "):" << reply->errorString(); } else { QXmlStreamReader reader(reply); reader.readNextStartElement(); QStringRef status = reader.attributes().value("status"); - int http_status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + int http_status_code = + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (status == "ok") { login_state_ = LoginState_Loggedin; } else if (http_status_code >= 300 && http_status_code <= 399) { @@ -292,18 +282,19 @@ void SubsonicService::OnPingFinished(QNetworkReply* reply) { QUrl redirect_url = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (redirect_url.isEmpty()) { - qLog(Debug) << "Received HTTP code " << http_status_code << ", but no URL"; + qLog(Debug) << "Received HTTP code " << http_status_code + << ", but no URL"; login_state_ = LoginState_RedirectNoUrl; } else { redirect_count_++; qLog(Debug) << "Redirect receieved to " << redirect_url.toString(QUrl::RemoveQuery) - << ", current redirect count is " - << redirect_count_; + << ", current redirect count is " << redirect_count_; if (redirect_count_ <= kMaxRedirects) { working_server_ = ScrubUrl(redirect_url).toString(QUrl::RemoveQuery); Ping(); - // To avoid the LoginStateChanged, as it will come from the recursive request. + // To avoid the LoginStateChanged, as it will come from the recursive + // request. return; } else { // Redirect limit exceeded @@ -314,7 +305,8 @@ void SubsonicService::OnPingFinished(QNetworkReply* reply) { reader.readNextStartElement(); int error = reader.attributes().value("code").toString().toInt(); qLog(Error) << "Subsonic error (" - << Utilities::EnumToString(SubsonicService::staticMetaObject, "ApiError", error) + << Utilities::EnumToString(SubsonicService::staticMetaObject, + "ApiError", error) << "):" << reader.attributes().value("message").toString(); switch (error) { // "Parameter missing" for "ping" is always blank username or password @@ -338,7 +330,8 @@ void SubsonicService::OnPingFinished(QNetworkReply* reply) { } } qLog(Debug) << "Login state changed:" - << Utilities::EnumToString(SubsonicService::staticMetaObject, "LoginState", login_state_); + << Utilities::EnumToString(SubsonicService::staticMetaObject, + "LoginState", login_state_); emit LoginStateChanged(login_state_); } @@ -352,19 +345,14 @@ void SubsonicService::UpdateServer(const QString& server) { redirect_count_ = 0; } - const int SubsonicLibraryScanner::kAlbumChunkSize = 500; const int SubsonicLibraryScanner::kConcurrentRequests = 8; -SubsonicLibraryScanner::SubsonicLibraryScanner( - SubsonicService* service, QObject* parent) - : QObject(parent), - service_(service), - scanning_(false) { -} +SubsonicLibraryScanner::SubsonicLibraryScanner(SubsonicService* service, + QObject* parent) + : QObject(parent), service_(service), scanning_(false) {} -SubsonicLibraryScanner::~SubsonicLibraryScanner() { -} +SubsonicLibraryScanner::~SubsonicLibraryScanner() {} void SubsonicLibraryScanner::Scan() { if (scanning_) { @@ -378,8 +366,8 @@ void SubsonicLibraryScanner::Scan() { GetAlbumList(0); } -void SubsonicLibraryScanner::OnGetAlbumListFinished( - QNetworkReply* reply, int offset) { +void SubsonicLibraryScanner::OnGetAlbumListFinished(QNetworkReply* reply, + int offset) { reply->deleteLater(); QXmlStreamReader reader(reply); @@ -408,7 +396,8 @@ void SubsonicLibraryScanner::OnGetAlbumListFinished( scanning_ = false; } else { // Empty reply but we have some albums, time to start fetching songs - // Start up the maximum number of concurrent requests, finished requests get replaced with new ones + // Start up the maximum number of concurrent requests, finished requests get + // replaced with new ones for (int i = 0; i < kConcurrentRequests && !album_queue_.empty(); ++i) { GetAlbum(album_queue_.dequeue()); } @@ -478,17 +467,15 @@ void SubsonicLibraryScanner::GetAlbumList(int offset) { url.addQueryItem("size", QString::number(kAlbumChunkSize)); url.addQueryItem("offset", QString::number(offset)); QNetworkReply* reply = service_->Send(url); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(OnGetAlbumListFinished(QNetworkReply*,int)), - reply, offset); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(OnGetAlbumListFinished(QNetworkReply*, int)), reply, offset); } void SubsonicLibraryScanner::GetAlbum(const QString& id) { QUrl url = service_->BuildRequestUrl("getAlbum"); url.addQueryItem("id", id); QNetworkReply* reply = service_->Send(url); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(OnGetAlbumFinished(QNetworkReply*)), - reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(OnGetAlbumFinished(QNetworkReply*)), reply); pending_requests_.insert(reply); } diff --git a/src/internet/subsonicservice.h b/src/internet/subsonicservice.h index 47f2c0d60..4deb88644 100644 --- a/src/internet/subsonicservice.h +++ b/src/internet/subsonicservice.h @@ -14,14 +14,13 @@ class QXmlStreamReader; class SubsonicUrlHandler; class SubsonicLibraryScanner; -class SubsonicService : public InternetService -{ +class SubsonicService : public InternetService { Q_OBJECT Q_ENUMS(LoginState) Q_ENUMS(ApiError) public: - SubsonicService(Application* app, InternetModel *parent); + SubsonicService(Application* app, InternetModel* parent); ~SubsonicService(); enum LoginState { @@ -53,15 +52,9 @@ class SubsonicService : public InternetService ApiError_NotFound = 70, }; - enum Type { - Type_Artist = InternetModel::TypeCount, - Type_Album, - Type_Track, - }; + enum Type { Type_Artist = InternetModel::TypeCount, Type_Album, Type_Track, }; - enum Role { - Role_Id = InternetModel::RoleCount, - }; + enum Role { Role_Id = InternetModel::RoleCount, }; typedef QMap RequestOptions; @@ -74,11 +67,8 @@ class SubsonicService : public InternetService void ReloadSettings(); void Login(); - void Login( - const QString& server, - const QString& username, - const QString& password, - const bool& usesslv3); + void Login(const QString& server, const QString& username, + const QString& password, const bool& usesslv3); LoginState login_state() const { return login_state_; } @@ -88,7 +78,8 @@ class SubsonicService : public InternetService QUrl BuildRequestUrl(const QString& view) const; // Scrubs the part of the path that we re-add in BuildRequestUrl(). static QUrl ScrubUrl(const QUrl& url); - // Convenience function to reduce QNetworkRequest/QSslConfiguration boilerplate. + // Convenience function to reduce QNetworkRequest/QSslConfiguration + // boilerplate. QNetworkReply* Send(const QUrl& url); static const char* kServiceName; @@ -101,7 +92,7 @@ class SubsonicService : public InternetService static const int kMaxRedirects; - signals: +signals: void LoginStateChanged(SubsonicService::LoginState newstate); private: @@ -132,7 +123,7 @@ class SubsonicService : public InternetService bool usesslv3_; LoginState login_state_; - QString working_server_; // The actual server, possibly post-redirect + QString working_server_; // The actual server, possibly post-redirect int redirect_count_; private slots: @@ -158,7 +149,7 @@ class SubsonicLibraryScanner : public QObject { static const int kAlbumChunkSize; static const int kConcurrentRequests; - signals: +signals: void ScanFinished(); private slots: @@ -178,4 +169,4 @@ class SubsonicLibraryScanner : public QObject { SongList songs_; }; -#endif // SUBSONICSERVICE_H +#endif // SUBSONICSERVICE_H diff --git a/src/internet/subsonicsettingspage.cpp b/src/internet/subsonicsettingspage.cpp index c9bf7f171..cafa9d607 100644 --- a/src/internet/subsonicsettingspage.cpp +++ b/src/internet/subsonicsettingspage.cpp @@ -5,11 +5,10 @@ #include -SubsonicSettingsPage::SubsonicSettingsPage(SettingsDialog *dialog) - : SettingsPage(dialog), - ui_(new Ui_SubsonicSettingsPage), - service_(InternetModel::Service()) -{ +SubsonicSettingsPage::SubsonicSettingsPage(SettingsDialog* dialog) + : SettingsPage(dialog), + ui_(new Ui_SubsonicSettingsPage), + service_(InternetModel::Service()) { ui_->setupUi(this); setWindowIcon(QIcon(":/providers/subsonic-32.png")); @@ -26,18 +25,15 @@ SubsonicSettingsPage::SubsonicSettingsPage(SettingsDialog *dialog) ui_->login_state->AddCredentialField(ui_->usesslv3); ui_->login_state->AddCredentialGroup(ui_->server_group); - ui_->login_state->SetAccountTypeText(tr( - "Streaming from a Subsonic server requires a valid server license after the 30-day trial period.")); + ui_->login_state->SetAccountTypeText( + tr("Streaming from a Subsonic server requires a valid server license " + "after the 30-day trial period.")); ui_->login_state->SetAccountTypeVisible(true); } -SubsonicSettingsPage::~SubsonicSettingsPage() -{ - delete ui_; -} +SubsonicSettingsPage::~SubsonicSettingsPage() { delete ui_; } -void SubsonicSettingsPage::Load() -{ +void SubsonicSettingsPage::Load() { QSettings s; s.beginGroup(SubsonicService::kSettingsGroup); @@ -46,15 +42,15 @@ void SubsonicSettingsPage::Load() ui_->password->setText(s.value("password").toString()); ui_->usesslv3->setChecked(s.value("usesslv3").toBool()); - // If the settings are complete, SubsonicService will have used them already and + // If the settings are complete, SubsonicService will have used them already + // and // we can tell the user if they worked if (ui_->server->text() != "" && ui_->username->text() != "") { LoginStateChanged(service_->login_state()); } } -void SubsonicSettingsPage::Save() -{ +void SubsonicSettingsPage::Save() { QSettings s; s.beginGroup(SubsonicService::kSettingsGroup); @@ -64,81 +60,90 @@ void SubsonicSettingsPage::Save() s.setValue("usesslv3", ui_->usesslv3->isChecked()); } -void SubsonicSettingsPage::LoginStateChanged(SubsonicService::LoginState newstate) -{ +void SubsonicSettingsPage::LoginStateChanged( + SubsonicService::LoginState newstate) { const bool logged_in = newstate == SubsonicService::LoginState_Loggedin; - ui_->login_state->SetLoggedIn(logged_in ? LoginStateWidget::LoggedIn - : LoginStateWidget::LoggedOut, - QString("%1 (%2)") - .arg(ui_->username->text()) - .arg(ui_->server->text())); + ui_->login_state->SetLoggedIn( + logged_in ? LoginStateWidget::LoggedIn : LoginStateWidget::LoggedOut, + QString("%1 (%2)").arg(ui_->username->text()).arg(ui_->server->text())); ui_->login_state->SetAccountTypeVisible(!logged_in); - switch (newstate) - { - case SubsonicService::LoginState_BadServer: - ui_->login_state->SetAccountTypeText(tr("Could not connect to Subsonic, check server URL. " - "Example: http://localhost:4040/")); - break; + switch (newstate) { + case SubsonicService::LoginState_BadServer: + ui_->login_state->SetAccountTypeText( + tr("Could not connect to Subsonic, check server URL. " + "Example: http://localhost:4040/")); + break; - case SubsonicService::LoginState_BadCredentials: - ui_->login_state->SetAccountTypeText(tr("Wrong username or password.")); - break; + case SubsonicService::LoginState_BadCredentials: + ui_->login_state->SetAccountTypeText(tr("Wrong username or password.")); + break; - case SubsonicService::LoginState_OutdatedClient: - ui_->login_state->SetAccountTypeText(tr("Incompatible Subsonic REST protocol version. Client must upgrade.")); - break; + case SubsonicService::LoginState_OutdatedClient: + ui_->login_state->SetAccountTypeText(tr( + "Incompatible Subsonic REST protocol version. Client must upgrade.")); + break; - case SubsonicService::LoginState_OutdatedServer: - ui_->login_state->SetAccountTypeText(tr("Incompatible Subsonic REST protocol version. Server must upgrade.")); - break; + case SubsonicService::LoginState_OutdatedServer: + ui_->login_state->SetAccountTypeText(tr( + "Incompatible Subsonic REST protocol version. Server must upgrade.")); + break; - case SubsonicService::LoginState_Unlicensed: - ui_->login_state->SetAccountTypeText(tr("The trial period for the Subsonic server is over. " - "Please donate to get a license key. Visit subsonic.org for details.")); - break; + case SubsonicService::LoginState_Unlicensed: + ui_->login_state->SetAccountTypeText( + tr("The trial period for the Subsonic server is over. " + "Please donate to get a license key. Visit subsonic.org for " + "details.")); + break; - case SubsonicService::LoginState_OtherError: - ui_->login_state->SetAccountTypeText(tr("An unspecified error occurred.")); - break; + case SubsonicService::LoginState_OtherError: + ui_->login_state->SetAccountTypeText( + tr("An unspecified error occurred.")); + break; - case SubsonicService::LoginState_ConnectionRefused: - ui_->login_state->SetAccountTypeText(tr("Connection refused by server, check server URL. " - "Example: http://localhost:4040/")); - break; + case SubsonicService::LoginState_ConnectionRefused: + ui_->login_state->SetAccountTypeText( + tr("Connection refused by server, check server URL. " + "Example: http://localhost:4040/")); + break; - case SubsonicService::LoginState_HostNotFound: - ui_->login_state->SetAccountTypeText(tr("Host not found, check server URL. " - "Example: http://localhost:4040/")); - break; + case SubsonicService::LoginState_HostNotFound: + ui_->login_state->SetAccountTypeText( + tr("Host not found, check server URL. " + "Example: http://localhost:4040/")); + break; - case SubsonicService::LoginState_Timeout: - ui_->login_state->SetAccountTypeText(tr("Connection timed out, check server URL. " - "Example: http://localhost:4040/")); - break; + case SubsonicService::LoginState_Timeout: + ui_->login_state->SetAccountTypeText( + tr("Connection timed out, check server URL. " + "Example: http://localhost:4040/")); + break; - case SubsonicService::LoginState_SslError: - ui_->login_state->SetAccountTypeText(tr("SSL handshake error, verify server configuration. " - "SSLv3 option below may workaround some issues.")); - break; + case SubsonicService::LoginState_SslError: + ui_->login_state->SetAccountTypeText( + tr("SSL handshake error, verify server configuration. " + "SSLv3 option below may workaround some issues.")); + break; - case SubsonicService::LoginState_IncompleteCredentials: - ui_->login_state->SetAccountTypeText(tr("Incomplete configuration, please ensure all fields are populated.")); - break; + case SubsonicService::LoginState_IncompleteCredentials: + ui_->login_state->SetAccountTypeText(tr( + "Incomplete configuration, please ensure all fields are populated.")); + break; - case SubsonicService::LoginState_RedirectLimitExceeded: - ui_->login_state->SetAccountTypeText(tr("Redirect limit exceeded, verify server configuration.")); - break; + case SubsonicService::LoginState_RedirectLimitExceeded: + ui_->login_state->SetAccountTypeText( + tr("Redirect limit exceeded, verify server configuration.")); + break; - case SubsonicService::LoginState_RedirectNoUrl: - ui_->login_state->SetAccountTypeText(tr("HTTP 3xx status code received without URL, " - "verify server configuration.")); - break; + case SubsonicService::LoginState_RedirectNoUrl: + ui_->login_state->SetAccountTypeText( + tr("HTTP 3xx status code received without URL, " + "verify server configuration.")); + break; - - default: - break; + default: + break; } } @@ -146,26 +151,27 @@ void SubsonicSettingsPage::ServerEditingFinished() { QString input = ui_->server->text(); QUrl url = QUrl::fromUserInput(input); - // Veto things that don't get guessed as an HTTP URL, the result will be unhelpful + // Veto things that don't get guessed as an HTTP URL, the result will be + // unhelpful if (!url.scheme().startsWith("http")) { return; } - // If the user specified a /rest location, remove it since we're going to re-add it later + // If the user specified a /rest location, remove it since we're going to + // re-add it later url = SubsonicService::ScrubUrl(url); ui_->server->setText(url.toString()); qLog(Debug) << "URL fixed:" << input << "to" << url; } -void SubsonicSettingsPage::Login() -{ +void SubsonicSettingsPage::Login() { ui_->login_state->SetLoggedIn(LoginStateWidget::LoginInProgress); - service_->Login(ui_->server->text(), ui_->username->text(), ui_->password->text(), ui_->usesslv3->isChecked()); + service_->Login(ui_->server->text(), ui_->username->text(), + ui_->password->text(), ui_->usesslv3->isChecked()); } -void SubsonicSettingsPage::Logout() -{ +void SubsonicSettingsPage::Logout() { ui_->username->setText(""); ui_->password->setText(""); } diff --git a/src/internet/subsonicsettingspage.h b/src/internet/subsonicsettingspage.h index 07579c400..111f43140 100644 --- a/src/internet/subsonicsettingspage.h +++ b/src/internet/subsonicsettingspage.h @@ -6,12 +6,11 @@ class Ui_SubsonicSettingsPage; -class SubsonicSettingsPage : public SettingsPage -{ +class SubsonicSettingsPage : public SettingsPage { Q_OBJECT public: - SubsonicSettingsPage(SettingsDialog *dialog); + SubsonicSettingsPage(SettingsDialog* dialog); ~SubsonicSettingsPage(); void Load(); @@ -30,4 +29,4 @@ class SubsonicSettingsPage : public SettingsPage SubsonicService* service_; }; -#endif // SUBSONICSETTINGSPAGE_H +#endif // SUBSONICSETTINGSPAGE_H diff --git a/src/internet/subsonicurlhandler.cpp b/src/internet/subsonicurlhandler.cpp index 0e1e6fe5c..ba348868a 100644 --- a/src/internet/subsonicurlhandler.cpp +++ b/src/internet/subsonicurlhandler.cpp @@ -1,10 +1,9 @@ #include "subsonicservice.h" #include "subsonicurlhandler.h" -SubsonicUrlHandler::SubsonicUrlHandler(SubsonicService* service, QObject* parent) - : UrlHandler(parent), - service_(service) { -} +SubsonicUrlHandler::SubsonicUrlHandler(SubsonicService* service, + QObject* parent) + : UrlHandler(parent), service_(service) {} UrlHandler::LoadResult SubsonicUrlHandler::StartLoading(const QUrl& url) { if (service_->login_state() != SubsonicService::LoginState_Loggedin) diff --git a/src/internet/subsonicurlhandler.h b/src/internet/subsonicurlhandler.h index 6d820f6fc..0b5117d5c 100644 --- a/src/internet/subsonicurlhandler.h +++ b/src/internet/subsonicurlhandler.h @@ -14,10 +14,10 @@ class SubsonicUrlHandler : public UrlHandler { QString scheme() const { return "subsonic"; } QIcon icon() const { return QIcon(":providers/subsonic-32.png"); } LoadResult StartLoading(const QUrl& url); - //LoadResult LoadNext(const QUrl& url); + // LoadResult LoadNext(const QUrl& url); private: SubsonicService* service_; }; -#endif // SUBSONICURLHANDLER_H +#endif // SUBSONICURLHANDLER_H diff --git a/src/internet/ubuntuoneauthenticator.cpp b/src/internet/ubuntuoneauthenticator.cpp index 9a62460a9..74be05984 100644 --- a/src/internet/ubuntuoneauthenticator.cpp +++ b/src/internet/ubuntuoneauthenticator.cpp @@ -24,22 +24,20 @@ static const char* kOAuthHeaderPrefix = "OAuth realm=\"\", "; } UbuntuOneAuthenticator::UbuntuOneAuthenticator(QObject* parent) - : QObject(parent), - network_(new NetworkAccessManager(this)), - success_(false) { -} + : QObject(parent), + network_(new NetworkAccessManager(this)), + success_(false) {} -void UbuntuOneAuthenticator::StartAuthorisation( - const QString& email, - const QString& password) { +void UbuntuOneAuthenticator::StartAuthorisation(const QString& email, + const QString& password) { QUrl url(kUbuntuOneEndpoint); url.addQueryItem("ws.op", "authenticate"); QString token_name = QString(kTokenNameTemplate).arg( - QHostInfo::localHostName(), - QCoreApplication::applicationName()); + QHostInfo::localHostName(), QCoreApplication::applicationName()); url.addQueryItem("token_name", token_name); - QByteArray authentication = QString(email + ":" + password).toAscii().toBase64(); + QByteArray authentication = + QString(email + ":" + password).toAscii().toBase64(); QString authorisation = QString("Basic %1").arg(QString::fromAscii(authentication)); @@ -48,8 +46,8 @@ void UbuntuOneAuthenticator::StartAuthorisation( request.setRawHeader("Accept", "application/json"); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(AuthorisationFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(AuthorisationFinished(QNetworkReply*)), reply); qLog(Debug) << url; qLog(Debug) << authorisation; @@ -65,7 +63,8 @@ void UbuntuOneAuthenticator::AuthorisationFinished(QNetworkReply* reply) { bool ok = false; QVariant json = parser.parse(data, &ok); if (!ok) { - qLog(Error) << "Failed to authenticate to Ubuntu One:" << parser.errorString(); + qLog(Error) << "Failed to authenticate to Ubuntu One:" + << parser.errorString(); emit Finished(); return; } @@ -80,10 +79,8 @@ void UbuntuOneAuthenticator::AuthorisationFinished(QNetworkReply* reply) { } QByteArray UbuntuOneAuthenticator::GenerateAuthorisationHeader( - const QString& consumer_key, - const QString& consumer_secret, - const QString& token, - const QString& token_secret) { + const QString& consumer_key, const QString& consumer_secret, + const QString& token, const QString& token_secret) { typedef QPair Param; QString timestamp = QString::number(time(nullptr)); QList parameters; @@ -95,18 +92,17 @@ QByteArray UbuntuOneAuthenticator::GenerateAuthorisationHeader( << Param("oauth_signature_method", "PLAINTEXT"); qSort(parameters.begin(), parameters.end()); QStringList encoded_params; - foreach (const Param& p, parameters) { + foreach(const Param & p, parameters) { encoded_params << QString("%1=%2").arg(p.first, p.second); } - QString signing_key = - consumer_secret + "&" + token_secret; + QString signing_key = consumer_secret + "&" + token_secret; QByteArray signature = QUrl::toPercentEncoding(signing_key); // Construct authorisation header parameters << Param("oauth_signature", signature); QStringList header_params; - foreach (const Param& p, parameters) { + foreach(const Param & p, parameters) { header_params << QString("%1=\"%2\"").arg(p.first, p.second); } QString authorisation_header = header_params.join(", "); @@ -116,11 +112,8 @@ QByteArray UbuntuOneAuthenticator::GenerateAuthorisationHeader( } QByteArray UbuntuOneAuthenticator::GenerateAuthorisationHeader() { - return GenerateAuthorisationHeader( - consumer_key_, - consumer_secret_, - token_, - token_secret_); + return GenerateAuthorisationHeader(consumer_key_, consumer_secret_, token_, + token_secret_); } void UbuntuOneAuthenticator::CopySSOTokens() { @@ -130,8 +123,8 @@ void UbuntuOneAuthenticator::CopySSOTokens() { request.setRawHeader("Accept", "application/json"); QNetworkReply* reply = network_->get(request); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(CopySSOTokensFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(CopySSOTokensFinished(QNetworkReply*)), reply); } void UbuntuOneAuthenticator::CopySSOTokensFinished(QNetworkReply* reply) { diff --git a/src/internet/ubuntuoneauthenticator.h b/src/internet/ubuntuoneauthenticator.h index edac507c2..a61f40a36 100644 --- a/src/internet/ubuntuoneauthenticator.h +++ b/src/internet/ubuntuoneauthenticator.h @@ -18,13 +18,12 @@ class UbuntuOneAuthenticator : public QObject { QString token() const { return token_; } QString token_secret() const { return token_secret_; } - static QByteArray GenerateAuthorisationHeader( - const QString& consumer_key, - const QString& consumer_secret, - const QString& token, - const QString& token_secret); + static QByteArray GenerateAuthorisationHeader(const QString& consumer_key, + const QString& consumer_secret, + const QString& token, + const QString& token_secret); - signals: +signals: void Finished(); private slots: @@ -47,4 +46,4 @@ class UbuntuOneAuthenticator : public QObject { QString token_secret_; }; -#endif // UBUNTUONEAUTHENTICATOR_H +#endif // UBUNTUONEAUTHENTICATOR_H diff --git a/src/internet/ubuntuoneservice.cpp b/src/internet/ubuntuoneservice.cpp index 68b769096..7ee16461a 100644 --- a/src/internet/ubuntuoneservice.cpp +++ b/src/internet/ubuntuoneservice.cpp @@ -37,11 +37,9 @@ static const char* kServiceId = "ubuntu_one"; } UbuntuOneService::UbuntuOneService(Application* app, InternetModel* parent) - : CloudFileService( - app, parent, - kServiceName, kServiceId, - QIcon(":/providers/ubuntuone.png"), - SettingsDialog::Page_UbuntuOne) { + : CloudFileService(app, parent, kServiceName, kServiceId, + QIcon(":/providers/ubuntuone.png"), + SettingsDialog::Page_UbuntuOne) { app_->player()->RegisterUrlHandler(new UbuntuOneUrlHandler(this, this)); QSettings s; @@ -68,10 +66,7 @@ void UbuntuOneService::Connect() { QByteArray UbuntuOneService::GenerateAuthorisationHeader() { return UbuntuOneAuthenticator::GenerateAuthorisationHeader( - consumer_key_, - consumer_secret_, - token_, - token_secret_); + consumer_key_, consumer_secret_, token_, token_secret_); } void UbuntuOneService::AuthenticationFinished( @@ -107,8 +102,8 @@ QNetworkReply* UbuntuOneService::SendRequest(const QUrl& url) { void UbuntuOneService::RequestVolumeList() { QUrl volumes_url(kVolumesEndpoint); QNetworkReply* reply = SendRequest(volumes_url); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(VolumeListRequestFinished(QNetworkReply*)), reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(VolumeListRequestFinished(QNetworkReply*)), reply); } void UbuntuOneService::VolumeListRequestFinished(QNetworkReply* reply) { @@ -116,7 +111,7 @@ void UbuntuOneService::VolumeListRequestFinished(QNetworkReply* reply) { QJson::Parser parser; QVariantList result = parser.parse(reply).toList(); - foreach (const QVariant& v, result) { + foreach(const QVariant & v, result) { RequestFileList(v.toMap()["node_path"].toString()); } } @@ -127,8 +122,8 @@ void UbuntuOneService::RequestFileList(const QString& path) { qLog(Debug) << "Sending files request" << files_url; QNetworkReply* files_reply = SendRequest(files_url); - NewClosure(files_reply, SIGNAL(finished()), - this, SLOT(FileListRequestFinished(QNetworkReply*)), files_reply); + NewClosure(files_reply, SIGNAL(finished()), this, + SLOT(FileListRequestFinished(QNetworkReply*)), files_reply); } void UbuntuOneService::FileListRequestFinished(QNetworkReply* reply) { @@ -137,7 +132,7 @@ void UbuntuOneService::FileListRequestFinished(QNetworkReply* reply) { QVariantMap result = parser.parse(reply).toMap(); QVariantList children = result["children"].toList(); - foreach (const QVariant& c, children) { + foreach(const QVariant & c, children) { QVariantMap child = c.toMap(); if (child["kind"].toString() == "file") { QString content_path = child["content_path"].toString(); @@ -150,17 +145,15 @@ void UbuntuOneService::FileListRequestFinished(QNetworkReply* reply) { Song metadata; metadata.set_url(service_url); metadata.set_etag(child["hash"].toString()); - metadata.set_mtime(QDateTime::fromString( - child["when_changed"].toString(), Qt::ISODate).toTime_t()); - metadata.set_ctime(QDateTime::fromString( - child["when_created"].toString(), Qt::ISODate).toTime_t()); + metadata.set_mtime(QDateTime::fromString(child["when_changed"].toString(), + Qt::ISODate).toTime_t()); + metadata.set_ctime(QDateTime::fromString(child["when_created"].toString(), + Qt::ISODate).toTime_t()); metadata.set_filesize(child["size"].toInt()); metadata.set_title(child["path"].toString().mid(1)); MaybeAddFileToDatabase( - metadata, - GuessMimeTypeForFile(child["path"].toString().mid(1)), - content_url, - GenerateAuthorisationHeader()); + metadata, GuessMimeTypeForFile(child["path"].toString().mid(1)), + content_url, GenerateAuthorisationHeader()); } else { RequestFileList(child["resource_path"].toString()); } @@ -185,6 +178,6 @@ void UbuntuOneService::ShowCoverManager() { } void UbuntuOneService::AddToPlaylist(QMimeData* mime) { - playlist_manager_->current()->dropMimeData( - mime, Qt::CopyAction, -1, 0, QModelIndex()); + playlist_manager_->current()->dropMimeData(mime, Qt::CopyAction, -1, 0, + QModelIndex()); } diff --git a/src/internet/ubuntuonesettingspage.cpp b/src/internet/ubuntuonesettingspage.cpp index 957b58c5f..2a7ed3783 100644 --- a/src/internet/ubuntuonesettingspage.cpp +++ b/src/internet/ubuntuonesettingspage.cpp @@ -38,8 +38,7 @@ void UbuntuOneSettingsPage::Load() { } } -void UbuntuOneSettingsPage::Save() { -} +void UbuntuOneSettingsPage::Save() {} void UbuntuOneSettingsPage::LoginClicked() { const QString username = ui_->username->text(); @@ -48,10 +47,10 @@ void UbuntuOneSettingsPage::LoginClicked() { UbuntuOneAuthenticator* authenticator = new UbuntuOneAuthenticator; authenticator->StartAuthorisation(username, password); - NewClosure(authenticator, SIGNAL(Finished()), - this, SLOT(Connected(UbuntuOneAuthenticator*)), authenticator); - NewClosure(authenticator, SIGNAL(Finished()), - service_, SLOT(AuthenticationFinished(UbuntuOneAuthenticator*)), + NewClosure(authenticator, SIGNAL(Finished()), this, + SLOT(Connected(UbuntuOneAuthenticator*)), authenticator); + NewClosure(authenticator, SIGNAL(Finished()), service_, + SLOT(AuthenticationFinished(UbuntuOneAuthenticator*)), authenticator); ui_->login_state->SetLoggedIn(LoginStateWidget::LoginInProgress); @@ -77,7 +76,8 @@ void UbuntuOneSettingsPage::Connected(UbuntuOneAuthenticator* authenticator) { return; } - ui_->login_state->SetLoggedIn(LoginStateWidget::LoggedIn, ui_->username->text()); + ui_->login_state->SetLoggedIn(LoginStateWidget::LoggedIn, + ui_->username->text()); authenticated_ = true; QSettings s; diff --git a/src/internet/ubuntuoneurlhandler.cpp b/src/internet/ubuntuoneurlhandler.cpp index 972039d63..ed939b28b 100644 --- a/src/internet/ubuntuoneurlhandler.cpp +++ b/src/internet/ubuntuoneurlhandler.cpp @@ -2,12 +2,9 @@ #include "ubuntuoneservice.h" -UbuntuOneUrlHandler::UbuntuOneUrlHandler( - UbuntuOneService* service, - QObject* parent) - : UrlHandler(parent), - service_(service) { -} +UbuntuOneUrlHandler::UbuntuOneUrlHandler(UbuntuOneService* service, + QObject* parent) + : UrlHandler(parent), service_(service) {} UrlHandler::LoadResult UbuntuOneUrlHandler::StartLoading(const QUrl& url) { QString file_id = url.path(); diff --git a/src/library/directory.h b/src/library/directory.h index 9af610d36..fcc44feed 100644 --- a/src/library/directory.h +++ b/src/library/directory.h @@ -27,7 +27,7 @@ class QSqlQuery; struct Directory { Directory() : id(-1) {} - bool operator ==(const Directory& other) const { + bool operator==(const Directory& other) const { return path == other.path && id == other.id; } @@ -39,7 +39,6 @@ Q_DECLARE_METATYPE(Directory) typedef QList DirectoryList; Q_DECLARE_METATYPE(DirectoryList) - struct Subdirectory { Subdirectory() : directory_id(-1), mtime(0) {} @@ -52,4 +51,4 @@ Q_DECLARE_METATYPE(Subdirectory) typedef QList SubdirectoryList; Q_DECLARE_METATYPE(SubdirectoryList) -#endif // DIRECTORY_H +#endif // DIRECTORY_H diff --git a/src/library/groupbydialog.cpp b/src/library/groupbydialog.cpp index 8b2f49955..f7a1c883b 100644 --- a/src/library/groupbydialog.cpp +++ b/src/library/groupbydialog.cpp @@ -51,23 +51,20 @@ struct tag_group_by {}; class GroupByDialogPrivate { private: typedef multi_index_container< - Mapping, - indexed_by< - ordered_unique, - member >, - ordered_unique, - member > - > - > MappingContainer; + Mapping, + indexed_by< + ordered_unique, + member >, + ordered_unique, + member > > > MappingContainer; public: MappingContainer mapping_; }; -GroupByDialog::GroupByDialog(QWidget *parent) - : QDialog(parent), - ui_(new Ui_GroupByDialog), - p_(new GroupByDialogPrivate) { +GroupByDialog::GroupByDialog(QWidget* parent) + : QDialog(parent), ui_(new Ui_GroupByDialog), p_(new GroupByDialogPrivate) { ui_->setupUi(this); Reset(); @@ -93,21 +90,26 @@ GroupByDialog::GroupByDialog(QWidget *parent) GroupByDialog::~GroupByDialog() {} void GroupByDialog::Reset() { - ui_->first->setCurrentIndex(2); // Artist - ui_->second->setCurrentIndex(1); // Album - ui_->third->setCurrentIndex(0); // None + ui_->first->setCurrentIndex(2); // Artist + ui_->second->setCurrentIndex(1); // Album + ui_->third->setCurrentIndex(0); // None } void GroupByDialog::accept() { emit Accepted(LibraryModel::Grouping( p_->mapping_.get().find(ui_->first->currentIndex())->group_by, p_->mapping_.get().find(ui_->second->currentIndex())->group_by, - p_->mapping_.get().find(ui_->third->currentIndex())->group_by)); + p_->mapping_.get() + .find(ui_->third->currentIndex()) + ->group_by)); QDialog::accept(); } void GroupByDialog::LibraryGroupingChanged(const LibraryModel::Grouping& g) { - ui_->first->setCurrentIndex(p_->mapping_.get().find(g[0])->combo_box_index); - ui_->second->setCurrentIndex(p_->mapping_.get().find(g[1])->combo_box_index); - ui_->third->setCurrentIndex(p_->mapping_.get().find(g[2])->combo_box_index); + ui_->first->setCurrentIndex( + p_->mapping_.get().find(g[0])->combo_box_index); + ui_->second->setCurrentIndex( + p_->mapping_.get().find(g[1])->combo_box_index); + ui_->third->setCurrentIndex( + p_->mapping_.get().find(g[2])->combo_box_index); } diff --git a/src/library/groupbydialog.h b/src/library/groupbydialog.h index 6c5cbc894..e1b3e8e3d 100644 --- a/src/library/groupbydialog.h +++ b/src/library/groupbydialog.h @@ -38,7 +38,7 @@ class GroupByDialog : public QDialog { void LibraryGroupingChanged(const LibraryModel::Grouping& g); void accept(); - signals: +signals: void Accepted(const LibraryModel::Grouping& g); private slots: @@ -49,4 +49,4 @@ class GroupByDialog : public QDialog { std::unique_ptr p_; }; -#endif // GROUPBYDIALOG_H +#endif // GROUPBYDIALOG_H diff --git a/src/library/library.cpp b/src/library/library.cpp index e631c9c41..ae827c5e2 100644 --- a/src/library/library.cpp +++ b/src/library/library.cpp @@ -34,18 +34,18 @@ const char* Library::kDirsTable = "directories"; const char* Library::kSubdirsTable = "subdirectories"; const char* Library::kFtsTable = "songs_fts"; -Library::Library(Application* app, QObject *parent) - : QObject(parent), - app_(app), - backend_(nullptr), - model_(nullptr), - watcher_(nullptr), - watcher_thread_(nullptr) -{ +Library::Library(Application* app, QObject* parent) + : QObject(parent), + app_(app), + backend_(nullptr), + model_(nullptr), + watcher_(nullptr), + watcher_thread_(nullptr) { backend_ = new LibraryBackend; backend()->moveToThread(app->database()->thread()); - backend_->Init(app->database(), kSongsTable, kDirsTable, kSubdirsTable, kFtsTable); + backend_->Init(app->database(), kSongsTable, kDirsTable, kSubdirsTable, + kFtsTable); using smart_playlists::Generator; using smart_playlists::GeneratorPtr; @@ -55,46 +55,64 @@ Library::Library(Application* app, QObject *parent) model_ = new LibraryModel(backend_, app_, this); model_->set_show_smart_playlists(true); - model_->set_default_smart_playlists(LibraryModel::DefaultGenerators() - << (LibraryModel::GeneratorList() - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "50 random tracks"), Search( - Search::Type_All, Search::TermList(), - Search::Sort_Random, SearchTerm::Field_Title, 50))) - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "Ever played"), Search( - Search::Type_And, Search::TermList() - << SearchTerm(SearchTerm::Field_PlayCount, SearchTerm::Op_GreaterThan, 0), - Search::Sort_Random, SearchTerm::Field_Title))) - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "Never played"), Search( - Search::Type_And, Search::TermList() - << SearchTerm(SearchTerm::Field_PlayCount, SearchTerm::Op_Equals, 0), - Search::Sort_Random, SearchTerm::Field_Title))) - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "Last played"), Search( - Search::Type_All, Search::TermList(), - Search::Sort_FieldDesc, SearchTerm::Field_LastPlayed))) - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "Most played"), Search( - Search::Type_All, Search::TermList(), - Search::Sort_FieldDesc, SearchTerm::Field_PlayCount))) - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "Favourite tracks"), Search( - Search::Type_All, Search::TermList(), - Search::Sort_FieldDesc, SearchTerm::Field_Score))) - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "Newest tracks"), Search( - Search::Type_All, Search::TermList(), - Search::Sort_FieldDesc, SearchTerm::Field_DateCreated))) - ) << (LibraryModel::GeneratorList() - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "All tracks"), Search( - Search::Type_All, Search::TermList(), - Search::Sort_FieldAsc, SearchTerm::Field_Artist, -1))) - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "Least favourite tracks"), Search( - Search::Type_Or, Search::TermList() - << SearchTerm(SearchTerm::Field_Rating, SearchTerm::Op_LessThan, 0.6) - << SearchTerm(SearchTerm::Field_SkipCount, SearchTerm::Op_GreaterThan, 4), - Search::Sort_FieldDesc, SearchTerm::Field_SkipCount))) - ) << (LibraryModel::GeneratorList() - << GeneratorPtr(new QueryGenerator(QT_TRANSLATE_NOOP("Library", "Dynamic random mix"), Search( - Search::Type_All, Search::TermList(), - Search::Sort_Random, SearchTerm::Field_Title), true)) - ) - ); + model_->set_default_smart_playlists( + LibraryModel::DefaultGenerators() + << (LibraryModel::GeneratorList() + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "50 random tracks"), + Search(Search::Type_All, Search::TermList(), + Search::Sort_Random, SearchTerm::Field_Title, 50))) + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "Ever played"), + Search(Search::Type_And, + Search::TermList() + << SearchTerm(SearchTerm::Field_PlayCount, + SearchTerm::Op_GreaterThan, 0), + Search::Sort_Random, SearchTerm::Field_Title))) + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "Never played"), + Search(Search::Type_And, + Search::TermList() + << SearchTerm(SearchTerm::Field_PlayCount, + SearchTerm::Op_Equals, 0), + Search::Sort_Random, SearchTerm::Field_Title))) + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "Last played"), + Search(Search::Type_All, Search::TermList(), + Search::Sort_FieldDesc, SearchTerm::Field_LastPlayed))) + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "Most played"), + Search(Search::Type_All, Search::TermList(), + Search::Sort_FieldDesc, SearchTerm::Field_PlayCount))) + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "Favourite tracks"), + Search(Search::Type_All, Search::TermList(), + Search::Sort_FieldDesc, SearchTerm::Field_Score))) + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "Newest tracks"), + Search(Search::Type_All, Search::TermList(), + Search::Sort_FieldDesc, + SearchTerm::Field_DateCreated)))) + << (LibraryModel::GeneratorList() + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "All tracks"), + Search(Search::Type_All, Search::TermList(), + Search::Sort_FieldAsc, SearchTerm::Field_Artist, -1))) + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "Least favourite tracks"), + Search(Search::Type_Or, + Search::TermList() + << SearchTerm(SearchTerm::Field_Rating, + SearchTerm::Op_LessThan, 0.6) + << SearchTerm(SearchTerm::Field_SkipCount, + SearchTerm::Op_GreaterThan, 4), + Search::Sort_FieldDesc, SearchTerm::Field_SkipCount)))) + << (LibraryModel::GeneratorList() + << GeneratorPtr(new QueryGenerator( + QT_TRANSLATE_NOOP("Library", "Dynamic random mix"), + Search(Search::Type_All, Search::TermList(), + Search::Sort_Random, SearchTerm::Field_Title), + true)))); // full rescan revisions full_rescan_revisions_[26] = tr("CUE sheet support"); @@ -116,44 +134,36 @@ void Library::Init() { watcher_->set_backend(backend_); watcher_->set_task_manager(app_->task_manager()); - connect(backend_, SIGNAL(DirectoryDiscovered(Directory,SubdirectoryList)), - watcher_, SLOT(AddDirectory(Directory,SubdirectoryList))); - connect(backend_, SIGNAL(DirectoryDeleted(Directory)), - watcher_, SLOT(RemoveDirectory(Directory))); - connect(watcher_, SIGNAL(NewOrUpdatedSongs(SongList)), - backend_, SLOT(AddOrUpdateSongs(SongList))); - connect(watcher_, SIGNAL(SongsMTimeUpdated(SongList)), - backend_, SLOT(UpdateMTimesOnly(SongList))); - connect(watcher_, SIGNAL(SongsDeleted(SongList)), - backend_, SLOT(MarkSongsUnavailable(SongList))); - connect(watcher_, SIGNAL(SongsReadded(SongList,bool)), - backend_, SLOT(MarkSongsUnavailable(SongList,bool))); - connect(watcher_, SIGNAL(SubdirsDiscovered(SubdirectoryList)), - backend_, SLOT(AddOrUpdateSubdirs(SubdirectoryList))); - connect(watcher_, SIGNAL(SubdirsMTimeUpdated(SubdirectoryList)), - backend_, SLOT(AddOrUpdateSubdirs(SubdirectoryList))); - connect(watcher_, SIGNAL(CompilationsNeedUpdating()), - backend_, SLOT(UpdateCompilations())); + connect(backend_, SIGNAL(DirectoryDiscovered(Directory, SubdirectoryList)), + watcher_, SLOT(AddDirectory(Directory, SubdirectoryList))); + connect(backend_, SIGNAL(DirectoryDeleted(Directory)), watcher_, + SLOT(RemoveDirectory(Directory))); + connect(watcher_, SIGNAL(NewOrUpdatedSongs(SongList)), backend_, + SLOT(AddOrUpdateSongs(SongList))); + connect(watcher_, SIGNAL(SongsMTimeUpdated(SongList)), backend_, + SLOT(UpdateMTimesOnly(SongList))); + connect(watcher_, SIGNAL(SongsDeleted(SongList)), backend_, + SLOT(MarkSongsUnavailable(SongList))); + connect(watcher_, SIGNAL(SongsReadded(SongList, bool)), backend_, + SLOT(MarkSongsUnavailable(SongList, bool))); + connect(watcher_, SIGNAL(SubdirsDiscovered(SubdirectoryList)), backend_, + SLOT(AddOrUpdateSubdirs(SubdirectoryList))); + connect(watcher_, SIGNAL(SubdirsMTimeUpdated(SubdirectoryList)), backend_, + SLOT(AddOrUpdateSubdirs(SubdirectoryList))); + connect(watcher_, SIGNAL(CompilationsNeedUpdating()), backend_, + SLOT(UpdateCompilations())); // This will start the watcher checking for updates backend_->LoadDirectoriesAsync(); } -void Library::IncrementalScan() { - watcher_->IncrementalScanAsync(); -} +void Library::IncrementalScan() { watcher_->IncrementalScanAsync(); } -void Library::FullScan() { - watcher_->FullScanAsync(); -} +void Library::FullScan() { watcher_->FullScanAsync(); } -void Library::PauseWatcher() { - watcher_->SetRescanPausedAsync(true); -} +void Library::PauseWatcher() { watcher_->SetRescanPausedAsync(true); } -void Library::ResumeWatcher() { - watcher_->SetRescanPausedAsync(false); -} +void Library::ResumeWatcher() { watcher_->SetRescanPausedAsync(false); } void Library::ReloadSettings() { backend_->ReloadSettingsAsync(); @@ -163,12 +173,13 @@ void Library::ReloadSettings() { void Library::WriteAllSongsStatisticsToFiles() { const SongList all_songs = backend_->GetAllSongs(); - const int task_id = app_->task_manager()->StartTask(tr("Saving songs statistics into songs files")); + const int task_id = app_->task_manager()->StartTask( + tr("Saving songs statistics into songs files")); app_->task_manager()->SetTaskBlocksLibraryScans(task_id); const int nb_songs = all_songs.size(); int i = 0; - foreach (const Song& song, all_songs) { + foreach(const Song & song, all_songs) { TagReaderClient::Instance()->UpdateSongStatisticsBlocking(song); TagReaderClient::Instance()->UpdateSongRatingBlocking(song); app_->task_manager()->SetTaskProgress(task_id, ++i, nb_songs); diff --git a/src/library/library.h b/src/library/library.h index 70681cda6..32b6c9a9b 100644 --- a/src/library/library.h +++ b/src/library/library.h @@ -45,7 +45,9 @@ class Library : public QObject { LibraryBackend* backend() const { return backend_; } LibraryModel* model() const { return model_; } - QString full_rescan_reason(int schema_version) const { return full_rescan_revisions_.value(schema_version, QString()); } + QString full_rescan_reason(int schema_version) const { + return full_rescan_revisions_.value(schema_version, QString()); + } void WriteAllSongsStatisticsToFiles(); @@ -68,7 +70,8 @@ class Library : public QObject { LibraryWatcher* watcher_; QThread* watcher_thread_; - // DB schema versions which should trigger a full library rescan (each of those with + // DB schema versions which should trigger a full library rescan (each of + // those with // a short reason why). QHash full_rescan_revisions_; }; diff --git a/src/library/librarybackend.cpp b/src/library/librarybackend.cpp index 3fde02881..d1f9bb37f 100644 --- a/src/library/librarybackend.cpp +++ b/src/library/librarybackend.cpp @@ -37,18 +37,18 @@ const char* LibraryBackend::kSettingsGroup = "LibraryBackend"; const char* LibraryBackend::kNewScoreSql = "case when playcount <= 0 then (%1 * 100 + score) / 2" - " else (score * (playcount + skipcount) + %1 * 100) / (playcount + skipcount + 1)" + " else (score * (playcount + skipcount) + %1 * 100) / (playcount + " + "skipcount + 1)" " end"; -LibraryBackend::LibraryBackend(QObject *parent) - : LibraryBackendInterface(parent), - save_statistics_in_file_(false), - save_ratings_in_file_(false) -{ -} +LibraryBackend::LibraryBackend(QObject* parent) + : LibraryBackendInterface(parent), + save_statistics_in_file_(false), + save_ratings_in_file_(false) {} void LibraryBackend::Init(Database* db, const QString& songs_table, - const QString& dirs_table, const QString& subdirs_table, + const QString& dirs_table, + const QString& subdirs_table, const QString& fts_table) { db_ = db; songs_table_ = songs_table; @@ -63,7 +63,8 @@ void LibraryBackend::LoadDirectoriesAsync() { } void LibraryBackend::UpdateTotalSongCountAsync() { - metaObject()->invokeMethod(this, "UpdateTotalSongCount", Qt::QueuedConnection); + metaObject()->invokeMethod(this, "UpdateTotalSongCount", + Qt::QueuedConnection); } void LibraryBackend::IncrementPlayCountAsync(int id) { @@ -92,7 +93,7 @@ void LibraryBackend::LoadDirectories() { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - foreach (const Directory& dir, dirs) { + foreach(const Directory & dir, dirs) { emit DirectoryDiscovered(dir, SubdirsInDirectory(dir.id, db)); } } @@ -104,7 +105,8 @@ void LibraryBackend::ChangeDirPath(int id, const QString& old_path, ScopedTransaction t(&db); // Do the dirs table - QSqlQuery q(QString("UPDATE %1 SET path=:path WHERE ROWID=:id").arg(dirs_table_), db); + QSqlQuery q( + QString("UPDATE %1 SET path=:path WHERE ROWID=:id").arg(dirs_table_), db); q.bindValue(":path", new_path); q.bindValue(":id", id); q.exec(); @@ -116,16 +118,24 @@ void LibraryBackend::ChangeDirPath(int id, const QString& old_path, const int path_len = old_url.length(); // Do the subdirs table - q = QSqlQuery(QString("UPDATE %1 SET path=:path || substr(path, %2)" - " WHERE directory=:id").arg(subdirs_table_).arg(path_len), db); + q = QSqlQuery(QString( + "UPDATE %1 SET path=:path || substr(path, %2)" + " WHERE directory=:id") + .arg(subdirs_table_) + .arg(path_len), + db); q.bindValue(":path", new_url); q.bindValue(":id", id); q.exec(); if (db_->CheckErrors(q)) return; // Do the songs table - q = QSqlQuery(QString("UPDATE %1 SET filename=:path || substr(filename, %2)" - " WHERE directory=:id").arg(songs_table_).arg(path_len), db); + q = QSqlQuery(QString( + "UPDATE %1 SET filename=:path || substr(filename, %2)" + " WHERE directory=:id") + .arg(songs_table_) + .arg(path_len), + db); q.bindValue(":path", new_url); q.bindValue(":id", id); q.exec(); @@ -160,9 +170,11 @@ SubdirectoryList LibraryBackend::SubdirsInDirectory(int id) { return SubdirsInDirectory(id, db); } -SubdirectoryList LibraryBackend::SubdirsInDirectory(int id, QSqlDatabase &db) { - QSqlQuery q(QString("SELECT path, mtime FROM %1" - " WHERE directory = :dir").arg(subdirs_table_), db); +SubdirectoryList LibraryBackend::SubdirsInDirectory(int id, QSqlDatabase& db) { + QSqlQuery q(QString( + "SELECT path, mtime FROM %1" + " WHERE directory = :dir").arg(subdirs_table_), + db); q.bindValue(":dir", id); q.exec(); if (db_->CheckErrors(q)) return SubdirectoryList(); @@ -183,7 +195,9 @@ void LibraryBackend::UpdateTotalSongCount() { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q(QString("SELECT COUNT(*) FROM %1 WHERE unavailable = 0").arg(songs_table_), db); + QSqlQuery q(QString("SELECT COUNT(*) FROM %1 WHERE unavailable = 0") + .arg(songs_table_), + db); q.exec(); if (db_->CheckErrors(q)) return; if (!q.next()) return; @@ -195,17 +209,20 @@ void LibraryBackend::AddDirectory(const QString& path) { QString canonical_path = QFileInfo(path).canonicalFilePath(); QString db_path = canonical_path; - if (Application::kIsPortable - && Utilities::UrlOnSameDriveAsClementine(QUrl::fromLocalFile(canonical_path))) { - db_path = Utilities::GetRelativePathToClementineBin(QUrl::fromLocalFile(db_path)).toLocalFile(); + if (Application::kIsPortable && Utilities::UrlOnSameDriveAsClementine( + QUrl::fromLocalFile(canonical_path))) { + db_path = Utilities::GetRelativePathToClementineBin( + QUrl::fromLocalFile(db_path)).toLocalFile(); qLog(Debug) << "db_path" << db_path; } QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q(QString("INSERT INTO %1 (path, subdirs)" - " VALUES (:path, 1)").arg(dirs_table_), db); + QSqlQuery q(QString( + "INSERT INTO %1 (path, subdirs)" + " VALUES (:path, 1)").arg(dirs_table_), + db); q.bindValue(":path", db_path); q.exec(); if (db_->CheckErrors(q)) return; @@ -227,15 +244,15 @@ void LibraryBackend::RemoveDirectory(const Directory& dir) { ScopedTransaction transaction(&db); // Delete the subdirs that were in this directory - QSqlQuery q(QString("DELETE FROM %1 WHERE directory = :id") - .arg(subdirs_table_), db); + QSqlQuery q( + QString("DELETE FROM %1 WHERE directory = :id").arg(subdirs_table_), db); q.bindValue(":id", dir.id); q.exec(); if (db_->CheckErrors(q)) return; // Now remove the directory itself - q = QSqlQuery(QString("DELETE FROM %1 WHERE ROWID = :id") - .arg(dirs_table_), db); + q = QSqlQuery(QString("DELETE FROM %1 WHERE ROWID = :id").arg(dirs_table_), + db); q.bindValue(":id", dir.id); q.exec(); if (db_->CheckErrors(q)) return; @@ -249,9 +266,10 @@ SongList LibraryBackend::FindSongsInDirectory(int id) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q(QString("SELECT ROWID, " + Song::kColumnSpec + - " FROM %1 WHERE directory = :directory") - .arg(songs_table_), db); + QSqlQuery q( + QString("SELECT ROWID, " + Song::kColumnSpec + + " FROM %1 WHERE directory = :directory").arg(songs_table_), + db); q.bindValue(":directory", id); q.exec(); if (db_->CheckErrors(q)) return SongList(); @@ -268,21 +286,28 @@ SongList LibraryBackend::FindSongsInDirectory(int id) { void LibraryBackend::AddOrUpdateSubdirs(const SubdirectoryList& subdirs) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery find_query(QString("SELECT ROWID FROM %1" - " WHERE directory = :id AND path = :path") - .arg(subdirs_table_), db); - QSqlQuery add_query(QString("INSERT INTO %1 (directory, path, mtime)" - " VALUES (:id, :path, :mtime)") - .arg(subdirs_table_), db); - QSqlQuery update_query(QString("UPDATE %1 SET mtime = :mtime" - " WHERE directory = :id AND path = :path") - .arg(subdirs_table_), db); - QSqlQuery delete_query(QString("DELETE FROM %1" - " WHERE directory = :id AND path = :path") - .arg(subdirs_table_), db); + QSqlQuery find_query( + QString( + "SELECT ROWID FROM %1" + " WHERE directory = :id AND path = :path").arg(subdirs_table_), + db); + QSqlQuery add_query(QString( + "INSERT INTO %1 (directory, path, mtime)" + " VALUES (:id, :path, :mtime)").arg(subdirs_table_), + db); + QSqlQuery update_query( + QString( + "UPDATE %1 SET mtime = :mtime" + " WHERE directory = :id AND path = :path").arg(subdirs_table_), + db); + QSqlQuery delete_query( + QString( + "DELETE FROM %1" + " WHERE directory = :id AND path = :path").arg(subdirs_table_), + db); ScopedTransaction transaction(&db); - foreach (const Subdirectory& subdir, subdirs) { + foreach(const Subdirectory & subdir, subdirs) { if (subdir.mtime == 0) { // Delete the subdirectory delete_query.bindValue(":id", subdir.directory_id); @@ -318,25 +343,32 @@ void LibraryBackend::AddOrUpdateSongs(const SongList& songs) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery check_dir(QString("SELECT ROWID FROM %1 WHERE ROWID = :id") - .arg(dirs_table_), db); - QSqlQuery add_song(QString("INSERT INTO %1 (" + Song::kColumnSpec + ")" - " VALUES (" + Song::kBindSpec + ")") - .arg(songs_table_), db); + QSqlQuery check_dir( + QString("SELECT ROWID FROM %1 WHERE ROWID = :id").arg(dirs_table_), db); + QSqlQuery add_song(QString("INSERT INTO %1 (" + Song::kColumnSpec + + ")" + " VALUES (" + + Song::kBindSpec + ")").arg(songs_table_), + db); QSqlQuery update_song(QString("UPDATE %1 SET " + Song::kUpdateSpec + - " WHERE ROWID = :id").arg(songs_table_), db); - QSqlQuery add_song_fts(QString("INSERT INTO %1 (ROWID, " + Song::kFtsColumnSpec + ")" - " VALUES (:id, " + Song::kFtsBindSpec + ")") - .arg(fts_table_), db); + " WHERE ROWID = :id").arg(songs_table_), + db); + QSqlQuery add_song_fts( + QString("INSERT INTO %1 (ROWID, " + Song::kFtsColumnSpec + + ")" + " VALUES (:id, " + + Song::kFtsBindSpec + ")").arg(fts_table_), + db); QSqlQuery update_song_fts(QString("UPDATE %1 SET " + Song::kFtsUpdateSpec + - " WHERE ROWID = :id").arg(fts_table_), db); + " WHERE ROWID = :id").arg(fts_table_), + db); ScopedTransaction transaction(&db); SongList added_songs; SongList deleted_songs; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { // Do a sanity check first - make sure the song's directory still exists // This is to fix a possible race condition when a directory is removed // while LibraryWatcher is scanning it. @@ -345,8 +377,7 @@ void LibraryBackend::AddOrUpdateSongs(const SongList& songs) { check_dir.exec(); if (db_->CheckErrors(check_dir)) continue; - if (!check_dir.next()) - continue; // Directory didn't exist + if (!check_dir.next()) continue; // Directory didn't exist } if (song.id() == -1) { @@ -372,8 +403,7 @@ void LibraryBackend::AddOrUpdateSongs(const SongList& songs) { } else { // Get the previous song data first Song old_song(GetSongById(song.id())); - if (!old_song.is_valid()) - continue; + if (!old_song.is_valid()) continue; // Update song.BindToQuery(&update_song); @@ -393,11 +423,9 @@ void LibraryBackend::AddOrUpdateSongs(const SongList& songs) { transaction.Commit(); - if (!deleted_songs.isEmpty()) - emit SongsDeleted(deleted_songs); + if (!deleted_songs.isEmpty()) emit SongsDeleted(deleted_songs); - if (!added_songs.isEmpty()) - emit SongsDiscovered(added_songs); + if (!added_songs.isEmpty()) emit SongsDiscovered(added_songs); UpdateTotalSongCountAsync(); } @@ -407,10 +435,11 @@ void LibraryBackend::UpdateMTimesOnly(const SongList& songs) { QSqlDatabase db(db_->Connect()); QSqlQuery q(QString("UPDATE %1 SET mtime = :mtime WHERE ROWID = :id") - .arg(songs_table_), db); + .arg(songs_table_), + db); ScopedTransaction transaction(&db); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { q.bindValue(":mtime", song.mtime()); q.bindValue(":id", song.id()); q.exec(); @@ -419,17 +448,17 @@ void LibraryBackend::UpdateMTimesOnly(const SongList& songs) { transaction.Commit(); } -void LibraryBackend::DeleteSongs(const SongList &songs) { +void LibraryBackend::DeleteSongs(const SongList& songs) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery remove(QString("DELETE FROM %1 WHERE ROWID = :id") - .arg(songs_table_), db); - QSqlQuery remove_fts(QString("DELETE FROM %1 WHERE ROWID = :id") - .arg(fts_table_), db); + QSqlQuery remove( + QString("DELETE FROM %1 WHERE ROWID = :id").arg(songs_table_), db); + QSqlQuery remove_fts( + QString("DELETE FROM %1 WHERE ROWID = :id").arg(fts_table_), db); ScopedTransaction transaction(&db); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { remove.bindValue(":id", song.id()); remove.exec(); db_->CheckErrors(remove); @@ -445,15 +474,18 @@ void LibraryBackend::DeleteSongs(const SongList &songs) { UpdateTotalSongCountAsync(); } -void LibraryBackend::MarkSongsUnavailable(const SongList& songs, bool unavailable) { +void LibraryBackend::MarkSongsUnavailable(const SongList& songs, + bool unavailable) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); QSqlQuery remove(QString("UPDATE %1 SET unavailable = %2 WHERE ROWID = :id") - .arg(songs_table_).arg(int(unavailable)), db); + .arg(songs_table_) + .arg(int(unavailable)), + db); ScopedTransaction transaction(&db); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { remove.bindValue(":id", song.id()); remove.exec(); db_->CheckErrors(remove); @@ -464,7 +496,8 @@ void LibraryBackend::MarkSongsUnavailable(const SongList& songs, bool unavailabl UpdateTotalSongCountAsync(); } -QStringList LibraryBackend::GetAll(const QString& column, const QueryOptions& opt) { +QStringList LibraryBackend::GetAll(const QString& column, + const QueryOptions& opt) { LibraryQuery query(opt); query.SetColumnSpec("DISTINCT " + column); query.AddCompilationRequirement(false); @@ -499,24 +532,26 @@ QStringList LibraryBackend::GetAllArtistsWithAlbums(const QueryOptions& opt) { return ret; } -LibraryBackend::AlbumList LibraryBackend::GetAllAlbums(const QueryOptions &opt) { +LibraryBackend::AlbumList LibraryBackend::GetAllAlbums( + const QueryOptions& opt) { return GetAlbums(QString(), false, opt); } -LibraryBackend::AlbumList LibraryBackend::GetAlbumsByArtist(const QString& artist, - const QueryOptions& opt) { +LibraryBackend::AlbumList LibraryBackend::GetAlbumsByArtist( + const QString& artist, const QueryOptions& opt) { return GetAlbums(artist, false, opt); } - -SongList LibraryBackend::GetSongsByAlbum(const QString& album, const QueryOptions& opt) { +SongList LibraryBackend::GetSongsByAlbum(const QString& album, + const QueryOptions& opt) { LibraryQuery query(opt); query.AddCompilationRequirement(false); query.AddWhere("album", album); return ExecLibraryQuery(&query); } -SongList LibraryBackend::GetSongs(const QString& artist, const QString& album, const QueryOptions& opt) { +SongList LibraryBackend::GetSongs(const QString& artist, const QString& album, + const QueryOptions& opt) { LibraryQuery query(opt); query.AddCompilationRequirement(false); query.AddWhere("artist", artist); @@ -549,9 +584,7 @@ SongList LibraryBackend::GetSongsById(const QList& ids) { QSqlDatabase db(db_->Connect()); QStringList str_ids; - foreach (int id, ids) { - str_ids << QString::number(id); - } + foreach(int id, ids) { str_ids << QString::number(id); } return GetSongsById(str_ids, db); } @@ -563,17 +596,22 @@ SongList LibraryBackend::GetSongsById(const QStringList& ids) { return GetSongsById(ids, db); } -SongList LibraryBackend::GetSongsByForeignId( - const QStringList& ids, const QString& table, const QString& column) { +SongList LibraryBackend::GetSongsByForeignId(const QStringList& ids, + const QString& table, + const QString& column) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); QString in = ids.join(","); - QSqlQuery q(QString("SELECT %2.ROWID, " + Song::kColumnSpec + ", %2.%3" - " FROM %2, %1" - " WHERE %2.%3 IN (%4) AND %1.ROWID = %2.ROWID AND unavailable = 0") - .arg(songs_table_, table, column, in), db); + QSqlQuery q( + QString( + "SELECT %2.ROWID, " + Song::kColumnSpec + + ", %2.%3" + " FROM %2, %1" + " WHERE %2.%3 IN (%4) AND %1.ROWID = %2.ROWID AND unavailable = 0") + .arg(songs_table_, table, column, in), + db); q.exec(); if (db_->CheckErrors(q)) return SongList(); @@ -581,8 +619,7 @@ SongList LibraryBackend::GetSongsByForeignId( while (q.next()) { const QString foreign_id = q.value(Song::kColumns.count() + 1).toString(); const int index = ids.indexOf(foreign_id); - if (index == -1) - continue; + if (index == -1) continue; ret[index].InitFromQuery(q, true); } @@ -591,16 +628,18 @@ SongList LibraryBackend::GetSongsByForeignId( Song LibraryBackend::GetSongById(int id, QSqlDatabase& db) { SongList list = GetSongsById(QStringList() << QString::number(id), db); - if (list.isEmpty()) - return Song(); + if (list.isEmpty()) return Song(); return list.first(); } -SongList LibraryBackend::GetSongsById(const QStringList& ids, QSqlDatabase& db) { +SongList LibraryBackend::GetSongsById(const QStringList& ids, + QSqlDatabase& db) { QString in = ids.join(","); - QSqlQuery q(QString("SELECT ROWID, " + Song::kColumnSpec + " FROM %1" - " WHERE ROWID IN (%2)").arg(songs_table_, in), db); + QSqlQuery q(QString("SELECT ROWID, " + Song::kColumnSpec + + " FROM %1" + " WHERE ROWID IN (%2)").arg(songs_table_, in), + db); q.exec(); if (db_->CheckErrors(q)) return SongList(); @@ -633,7 +672,7 @@ SongList LibraryBackend::GetSongsByUrl(const QUrl& url) { SongList songlist; if (ExecQuery(&query)) { - while(query.Next()) { + while (query.Next()) { Song song; song.InitFromQuery(query, true); @@ -643,11 +682,13 @@ SongList LibraryBackend::GetSongsByUrl(const QUrl& url) { return songlist; } -LibraryBackend::AlbumList LibraryBackend::GetCompilationAlbums(const QueryOptions& opt) { +LibraryBackend::AlbumList LibraryBackend::GetCompilationAlbums( + const QueryOptions& opt) { return GetAlbums(QString(), true, opt); } -SongList LibraryBackend::GetCompilationSongs(const QString& album, const QueryOptions& opt) { +SongList LibraryBackend::GetCompilationSongs(const QString& album, + const QueryOptions& opt) { LibraryQuery query(opt); query.SetColumnSpec("%songs_table.ROWID, " + Song::kColumnSpec); query.AddCompilationRequirement(true); @@ -669,11 +710,15 @@ void LibraryBackend::UpdateCompilations() { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - // Look for albums that have songs by more than one 'effective album artist' in the same + // Look for albums that have songs by more than one 'effective album artist' + // in the same // directory - QSqlQuery q(QString("SELECT effective_albumartist, album, filename, sampler " - "FROM %1 WHERE unavailable = 0 ORDER BY album").arg(songs_table_), db); + QSqlQuery q( + QString( + "SELECT effective_albumartist, album, filename, sampler " + "FROM %1 WHERE unavailable = 0 ORDER BY album").arg(songs_table_), + db); q.exec(); if (db_->CheckErrors(q)) return; @@ -685,49 +730,61 @@ void LibraryBackend::UpdateCompilations() { bool sampler = q.value(3).toBool(); // Ignore songs that don't have an album field set - if (album.isEmpty()) - continue; + if (album.isEmpty()) continue; // Find the directory the song is in int last_separator = filename.lastIndexOf('/'); - if (last_separator == -1) - continue; + if (last_separator == -1) continue; CompilationInfo& info = compilation_info[album]; info.artists.insert(artist); info.directories.insert(filename.left(last_separator)); - if (sampler) info.has_samplers = true; - else info.has_not_samplers = true; + if (sampler) + info.has_samplers = true; + else + info.has_not_samplers = true; } // Now mark the songs that we think are in compilations - QSqlQuery update(QString("UPDATE %1" - " SET sampler = :sampler," - " effective_compilation = ((compilation OR :sampler OR forced_compilation_on) AND NOT forced_compilation_off) + 0" - " WHERE album = :album AND unavailable = 0").arg(songs_table_), db); - QSqlQuery find_songs(QString("SELECT ROWID, " + Song::kColumnSpec + " FROM %1" - " WHERE album = :album AND sampler = :sampler AND unavailable = 0") - .arg(songs_table_), db); + QSqlQuery update( + QString( + "UPDATE %1" + " SET sampler = :sampler," + " effective_compilation = ((compilation OR :sampler OR " + "forced_compilation_on) AND NOT forced_compilation_off) + 0" + " WHERE album = :album AND unavailable = 0").arg(songs_table_), + db); + QSqlQuery find_songs( + QString( + "SELECT ROWID, " + Song::kColumnSpec + + " FROM %1" + " WHERE album = :album AND sampler = :sampler AND unavailable = 0") + .arg(songs_table_), + db); SongList deleted_songs; SongList added_songs; ScopedTransaction transaction(&db); - QMap::const_iterator it = compilation_info.constBegin(); - for ( ; it != compilation_info.constEnd() ; ++it) { + QMap::const_iterator it = + compilation_info.constBegin(); + for (; it != compilation_info.constEnd(); ++it) { const CompilationInfo& info = it.value(); QString album(it.key()); - // If there were more 'effective album artists' than there were directories for this album, + // If there were more 'effective album artists' than there were directories + // for this album, // then it's a compilation if (info.artists.count() > info.directories.count()) { if (info.has_not_samplers) - UpdateCompilations(find_songs, update, deleted_songs, added_songs, album, 1); + UpdateCompilations(find_songs, update, deleted_songs, added_songs, + album, 1); } else { if (info.has_samplers) - UpdateCompilations(find_songs, update, deleted_songs, added_songs, album, 0); + UpdateCompilations(find_songs, update, deleted_songs, added_songs, + album, 0); } } @@ -739,8 +796,10 @@ void LibraryBackend::UpdateCompilations() { } } -void LibraryBackend::UpdateCompilations(QSqlQuery& find_songs, QSqlQuery& update, - SongList& deleted_songs, SongList& added_songs, +void LibraryBackend::UpdateCompilations(QSqlQuery& find_songs, + QSqlQuery& update, + SongList& deleted_songs, + SongList& added_songs, const QString& album, int sampler) { // Get songs that were already in that album, so we can tell the model // they've been updated @@ -768,8 +827,9 @@ LibraryBackend::AlbumList LibraryBackend::GetAlbums(const QString& artist, AlbumList ret; LibraryQuery query(opt); - query.SetColumnSpec("album, artist, compilation, sampler, art_automatic, " - "art_manual, filename"); + query.SetColumnSpec( + "album, artist, compilation, sampler, art_automatic, " + "art_manual, filename"); query.SetOrderBy("album"); if (compilation) { @@ -794,8 +854,7 @@ LibraryBackend::AlbumList LibraryBackend::GetAlbums(const QString& artist, info.art_manual = query.Value(5).toString(); info.first_url = QUrl::fromEncoded(query.Value(6).toByteArray()); - if (info.artist == last_artist && info.album_name == last_album) - continue; + if (info.artist == last_artist && info.album_name == last_album) continue; ret << info; @@ -806,7 +865,8 @@ LibraryBackend::AlbumList LibraryBackend::GetAlbums(const QString& artist, return ret; } -LibraryBackend::Album LibraryBackend::GetAlbumArt(const QString& artist, const QString& album) { +LibraryBackend::Album LibraryBackend::GetAlbumArt(const QString& artist, + const QString& album) { Album ret; ret.album_name = album; ret.artist = artist; @@ -828,18 +888,17 @@ LibraryBackend::Album LibraryBackend::GetAlbumArt(const QString& artist, const Q return ret; } -void LibraryBackend::UpdateManualAlbumArtAsync(const QString &artist, - const QString &album, - const QString &art) { +void LibraryBackend::UpdateManualAlbumArtAsync(const QString& artist, + const QString& album, + const QString& art) { metaObject()->invokeMethod(this, "UpdateManualAlbumArt", Qt::QueuedConnection, - Q_ARG(QString, artist), - Q_ARG(QString, album), + Q_ARG(QString, artist), Q_ARG(QString, album), Q_ARG(QString, art)); } -void LibraryBackend::UpdateManualAlbumArt(const QString &artist, - const QString &album, - const QString &art) { +void LibraryBackend::UpdateManualAlbumArt(const QString& artist, + const QString& album, + const QString& art) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); @@ -847,8 +906,7 @@ void LibraryBackend::UpdateManualAlbumArt(const QString &artist, LibraryQuery query; query.SetColumnSpec("ROWID, " + Song::kColumnSpec); query.AddWhere("album", album); - if (!artist.isNull()) - query.AddWhere("artist", artist); + if (!artist.isNull()) query.AddWhere("artist", artist); if (!ExecQuery(&query)) return; @@ -859,23 +917,21 @@ void LibraryBackend::UpdateManualAlbumArt(const QString &artist, deleted_songs << song; } - // Update the songs - QString sql(QString("UPDATE %1 SET art_manual = :art" - " WHERE album = :album AND unavailable = 0").arg(songs_table_)); - if (!artist.isNull()) - sql += " AND artist = :artist"; + QString sql( + QString( + "UPDATE %1 SET art_manual = :art" + " WHERE album = :album AND unavailable = 0").arg(songs_table_)); + if (!artist.isNull()) sql += " AND artist = :artist"; QSqlQuery q(sql, db); q.bindValue(":art", art); q.bindValue(":album", album); - if (!artist.isNull()) - q.bindValue(":artist", artist); + if (!artist.isNull()) q.bindValue(":artist", artist); q.exec(); db_->CheckErrors(q); - // Now get the updated songs if (!ExecQuery(&query)) return; @@ -892,18 +948,18 @@ void LibraryBackend::UpdateManualAlbumArt(const QString &artist, } } -void LibraryBackend::ForceCompilation(const QString& album, const QList& artists, bool on) { +void LibraryBackend::ForceCompilation(const QString& album, + const QList& artists, bool on) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); SongList deleted_songs, added_songs; - foreach(const QString &artist, artists) { + foreach(const QString & artist, artists) { // Get the songs before they're updated LibraryQuery query; query.SetColumnSpec("ROWID, " + Song::kColumnSpec); query.AddWhere("album", album); - if (!artist.isNull()) - query.AddWhere("artist", artist); + if (!artist.isNull()) query.AddWhere("artist", artist); if (!ExecQuery(&query)) return; @@ -914,19 +970,20 @@ void LibraryBackend::ForceCompilation(const QString& album, const QList } // Update the songs - QString sql(QString("UPDATE %1 SET forced_compilation_on = :forced_compilation_on," - " forced_compilation_off = :forced_compilation_off," - " effective_compilation = ((compilation OR sampler OR :forced_compilation_on) AND NOT :forced_compilation_off) + 0" - " WHERE album = :album AND unavailable = 0").arg(songs_table_)); - if (!artist.isEmpty()) - sql += " AND artist = :artist"; + QString sql( + QString( + "UPDATE %1 SET forced_compilation_on = :forced_compilation_on," + " forced_compilation_off = :forced_compilation_off," + " effective_compilation = ((compilation OR sampler OR " + ":forced_compilation_on) AND NOT :forced_compilation_off) + 0" + " WHERE album = :album AND unavailable = 0").arg(songs_table_)); + if (!artist.isEmpty()) sql += " AND artist = :artist"; QSqlQuery q(sql, db); q.bindValue(":forced_compilation_on", on ? 1 : 0); q.bindValue(":forced_compilation_off", on ? 0 : 1); q.bindValue(":album", album); - if (!artist.isEmpty()) - q.bindValue(":artist", artist); + if (!artist.isEmpty()) q.bindValue(":artist", artist); q.exec(); db_->CheckErrors(q); @@ -947,7 +1004,7 @@ void LibraryBackend::ForceCompilation(const QString& album, const QList } } -bool LibraryBackend::ExecQuery(LibraryQuery *q) { +bool LibraryBackend::ExecQuery(LibraryQuery* q) { return !db_->CheckErrors(q->Exec(db_->Connect(), songs_table_, fts_table_)); } @@ -962,8 +1019,7 @@ SongList LibraryBackend::FindSongs(const smart_playlists::Search& search) { SongList ret; QSqlQuery query(sql, db); query.exec(); - if (db_->CheckErrors(query)) - return ret; + if (db_->CheckErrors(query)) return ret; // Read the results while (query.next()) { @@ -978,84 +1034,86 @@ SongList LibraryBackend::GetAllSongs() { // Get all the songs! return FindSongs(smart_playlists::Search( smart_playlists::Search::Type_All, smart_playlists::Search::TermList(), - smart_playlists::Search::Sort_FieldAsc, smart_playlists::SearchTerm::Field_Artist, -1)); + smart_playlists::Search::Sort_FieldAsc, + smart_playlists::SearchTerm::Field_Artist, -1)); } void LibraryBackend::IncrementPlayCount(int id) { - if (id == -1) - return; + if (id == -1) return; QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q(QString("UPDATE %1 SET playcount = playcount + 1," - " lastplayed = :now," - " score = " + QString(kNewScoreSql).arg("1.0") + - " WHERE ROWID = :id").arg(songs_table_), db); + QSqlQuery q(QString( + "UPDATE %1 SET playcount = playcount + 1," + " lastplayed = :now," + " score = " + + QString(kNewScoreSql).arg("1.0") + + " WHERE ROWID = :id").arg(songs_table_), + db); q.bindValue(":now", QDateTime::currentDateTime().toTime_t()); q.bindValue(":id", id); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; Song new_song = GetSongById(id, db); emit SongsStatisticsChanged(SongList() << new_song); } void LibraryBackend::IncrementSkipCount(int id, float progress) { - if (id == -1) - return; + if (id == -1) return; progress = qBound(0.0f, progress, 1.0f); QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q(QString("UPDATE %1 SET skipcount = skipcount + 1," - " score = " + QString(kNewScoreSql).arg(progress) + - " WHERE ROWID = :id").arg(songs_table_), db); + QSqlQuery q(QString( + "UPDATE %1 SET skipcount = skipcount + 1," + " score = " + + QString(kNewScoreSql).arg(progress) + + " WHERE ROWID = :id").arg(songs_table_), + db); q.bindValue(":id", id); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; Song new_song = GetSongById(id, db); emit SongsStatisticsChanged(SongList() << new_song); } void LibraryBackend::ResetStatistics(int id) { - if (id == -1) - return; + if (id == -1) return; QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); QSqlQuery q(QString( - "UPDATE %1 SET playcount = 0, skipcount = 0," - " lastplayed = -1, score = 0" - " WHERE ROWID = :id").arg(songs_table_), db); + "UPDATE %1 SET playcount = 0, skipcount = 0," + " lastplayed = -1, score = 0" + " WHERE ROWID = :id").arg(songs_table_), + db); q.bindValue(":id", id); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; Song new_song = GetSongById(id, db); emit SongsStatisticsChanged(SongList() << new_song); } void LibraryBackend::UpdateSongRating(int id, float rating) { - if (id == -1) - return; + if (id == -1) return; QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q(QString("UPDATE %1 SET rating = :rating" - " WHERE ROWID = :id").arg(songs_table_), db); + QSqlQuery q(QString( + "UPDATE %1 SET rating = :rating" + " WHERE ROWID = :id").arg(songs_table_), + db); q.bindValue(":rating", rating); q.bindValue(":id", id); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; Song new_song = GetSongById(id, db); emit SongsRatingChanged(SongList() << new_song); @@ -1069,13 +1127,11 @@ void LibraryBackend::DeleteAll() { QSqlQuery q("DELETE FROM " + songs_table_, db); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; q = QSqlQuery("DELETE FROM " + fts_table_, db); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; t.Commit(); } @@ -1093,14 +1149,18 @@ void LibraryBackend::ReloadSettings() { // Statistics { - bool save_statistics_in_file = s.value("save_statistics_in_file", false).toBool(); - // Compare with previous value to know if we should connect, disconnect or nothing + bool save_statistics_in_file = + s.value("save_statistics_in_file", false).toBool(); + // Compare with previous value to know if we should connect, disconnect or + // nothing if (save_statistics_in_file_ && !save_statistics_in_file) { disconnect(this, SIGNAL(SongsStatisticsChanged(SongList)), - TagReaderClient::Instance(), SLOT(UpdateSongsStatistics(SongList))); + TagReaderClient::Instance(), + SLOT(UpdateSongsStatistics(SongList))); } else if (!save_statistics_in_file_ && save_statistics_in_file) { connect(this, SIGNAL(SongsStatisticsChanged(SongList)), - TagReaderClient::Instance(), SLOT(UpdateSongsStatistics(SongList))); + TagReaderClient::Instance(), + SLOT(UpdateSongsStatistics(SongList))); } // Save old value save_statistics_in_file_ = save_statistics_in_file; @@ -1109,13 +1169,15 @@ void LibraryBackend::ReloadSettings() { // Rating { bool save_ratings_in_file = s.value("save_ratings_in_file", false).toBool(); - // Compare with previous value to know if we should connect, disconnect or nothing + // Compare with previous value to know if we should connect, disconnect or + // nothing if (save_ratings_in_file_ && !save_ratings_in_file) { disconnect(this, SIGNAL(SongsRatingChanged(SongList)), - TagReaderClient::Instance(), SLOT(UpdateSongsRating(SongList))); + TagReaderClient::Instance(), + SLOT(UpdateSongsRating(SongList))); } else if (!save_ratings_in_file_ && save_ratings_in_file) { connect(this, SIGNAL(SongsRatingChanged(SongList)), - TagReaderClient::Instance(), SLOT(UpdateSongsRating(SongList))); + TagReaderClient::Instance(), SLOT(UpdateSongsRating(SongList))); } // Save old value save_ratings_in_file_ = save_ratings_in_file; diff --git a/src/library/librarybackend.h b/src/library/librarybackend.h index 45137c800..9a3bb458b 100644 --- a/src/library/librarybackend.h +++ b/src/library/librarybackend.h @@ -28,12 +28,14 @@ class Database; -namespace smart_playlists { class Search; } +namespace smart_playlists { +class Search; +} class LibraryBackendInterface : public QObject { Q_OBJECT -public: + public: LibraryBackendInterface(QObject* parent = 0) : QObject(parent) {} virtual ~LibraryBackendInterface() {} @@ -42,9 +44,11 @@ public: Album(const QString& _artist, const QString& _album_name, const QString& _art_automatic, const QString& _art_manual, const QUrl& _first_url) - : artist(_artist), album_name(_album_name), - art_automatic(_art_automatic), art_manual(_art_manual), - first_url(_first_url) {} + : artist(_artist), + album_name(_album_name), + art_automatic(_art_automatic), + art_manual(_art_manual), + first_url(_first_url) {} QString artist; QString album_name; @@ -66,31 +70,43 @@ public: virtual SongList FindSongsInDirectory(int id) = 0; virtual SubdirectoryList SubdirsInDirectory(int id) = 0; virtual DirectoryList GetAllDirectories() = 0; - virtual void ChangeDirPath(int id, const QString& old_path, const QString& new_path) = 0; + virtual void ChangeDirPath(int id, const QString& old_path, + const QString& new_path) = 0; - virtual QStringList GetAllArtists(const QueryOptions& opt = QueryOptions()) = 0; - virtual QStringList GetAllArtistsWithAlbums(const QueryOptions& opt = QueryOptions()) = 0; - virtual SongList GetSongsByAlbum(const QString& album, const QueryOptions& opt = QueryOptions()) = 0; - virtual SongList GetSongs( - const QString& artist, const QString& album, const QueryOptions& opt = QueryOptions()) = 0; + virtual QStringList GetAllArtists( + const QueryOptions& opt = QueryOptions()) = 0; + virtual QStringList GetAllArtistsWithAlbums( + const QueryOptions& opt = QueryOptions()) = 0; + virtual SongList GetSongsByAlbum( + const QString& album, const QueryOptions& opt = QueryOptions()) = 0; + virtual SongList GetSongs(const QString& artist, const QString& album, + const QueryOptions& opt = QueryOptions()) = 0; - virtual SongList GetCompilationSongs(const QString& album, const QueryOptions& opt = QueryOptions()) = 0; + virtual SongList GetCompilationSongs( + const QString& album, const QueryOptions& opt = QueryOptions()) = 0; virtual AlbumList GetAllAlbums(const QueryOptions& opt = QueryOptions()) = 0; - virtual AlbumList GetAlbumsByArtist(const QString& artist, const QueryOptions& opt = QueryOptions()) = 0; - virtual AlbumList GetCompilationAlbums(const QueryOptions& opt = QueryOptions()) = 0; + virtual AlbumList GetAlbumsByArtist( + const QString& artist, const QueryOptions& opt = QueryOptions()) = 0; + virtual AlbumList GetCompilationAlbums( + const QueryOptions& opt = QueryOptions()) = 0; - virtual void UpdateManualAlbumArtAsync(const QString& artist, const QString& album, const QString& art) = 0; + virtual void UpdateManualAlbumArtAsync(const QString& artist, + const QString& album, + const QString& art) = 0; virtual Album GetAlbumArt(const QString& artist, const QString& album) = 0; virtual Song GetSongById(int id) = 0; - // Returns all sections of a song with the given filename. If there's just one section + // Returns all sections of a song with the given filename. If there's just one + // section // the resulting list will have it's size equal to 1. virtual SongList GetSongsByUrl(const QUrl& url) = 0; - // Returns a section of a song with the given filename and beginning. If the section + // Returns a section of a song with the given filename and beginning. If the + // section // is not present in library, returns invalid song. - // Using default beginning value is suitable when searching for single-section songs. + // Using default beginning value is suitable when searching for single-section + // songs. virtual Song GetSongByUrl(const QUrl& url, qint64 beginning = 0) = 0; virtual void AddDirectory(const QString& path) = 0; @@ -106,9 +122,8 @@ class LibraryBackend : public LibraryBackendInterface { static const char* kSettingsGroup; Q_INVOKABLE LibraryBackend(QObject* parent = 0); - void Init(Database* db, const QString& songs_table, - const QString& dirs_table, const QString& subdirs_table, - const QString& fts_table); + void Init(Database* db, const QString& songs_table, const QString& dirs_table, + const QString& subdirs_table, const QString& fts_table); Database* db() const { return db_; } @@ -127,19 +142,25 @@ class LibraryBackend : public LibraryBackendInterface { DirectoryList GetAllDirectories(); void ChangeDirPath(int id, const QString& old_path, const QString& new_path); - QStringList GetAll(const QString& column, const QueryOptions& opt = QueryOptions()); + QStringList GetAll(const QString& column, + const QueryOptions& opt = QueryOptions()); QStringList GetAllArtists(const QueryOptions& opt = QueryOptions()); QStringList GetAllArtistsWithAlbums(const QueryOptions& opt = QueryOptions()); - SongList GetSongsByAlbum(const QString& album, const QueryOptions& opt = QueryOptions()); - SongList GetSongs(const QString& artist, const QString& album, const QueryOptions& opt = QueryOptions()); + SongList GetSongsByAlbum(const QString& album, + const QueryOptions& opt = QueryOptions()); + SongList GetSongs(const QString& artist, const QString& album, + const QueryOptions& opt = QueryOptions()); - SongList GetCompilationSongs(const QString& album, const QueryOptions& opt = QueryOptions()); + SongList GetCompilationSongs(const QString& album, + const QueryOptions& opt = QueryOptions()); AlbumList GetAllAlbums(const QueryOptions& opt = QueryOptions()); - AlbumList GetAlbumsByArtist(const QString& artist, const QueryOptions& opt = QueryOptions()); + AlbumList GetAlbumsByArtist(const QString& artist, + const QueryOptions& opt = QueryOptions()); AlbumList GetCompilationAlbums(const QueryOptions& opt = QueryOptions()); - void UpdateManualAlbumArtAsync(const QString& artist, const QString& album, const QString& art); + void UpdateManualAlbumArtAsync(const QString& artist, const QString& album, + const QString& art); Album GetAlbumArt(const QString& artist, const QString& album); Song GetSongById(int id); @@ -177,16 +198,19 @@ class LibraryBackend : public LibraryBackendInterface { void MarkSongsUnavailable(const SongList& songs, bool unavailable = true); void AddOrUpdateSubdirs(const SubdirectoryList& subdirs); void UpdateCompilations(); - void UpdateManualAlbumArt(const QString& artist, const QString& album, const QString& art); - void ForceCompilation(const QString& album, const QList& artists, bool on); + void UpdateManualAlbumArt(const QString& artist, const QString& album, + const QString& art); + void ForceCompilation(const QString& album, const QList& artists, + bool on); void IncrementPlayCount(int id); void IncrementSkipCount(int id, float progress); void ResetStatistics(int id); void UpdateSongRating(int id, float rating); void ReloadSettings(); - signals: - void DirectoryDiscovered(const Directory& dir, const SubdirectoryList& subdirs); +signals: + void DirectoryDiscovered(const Directory& dir, + const SubdirectoryList& subdirs); void DirectoryDeleted(const Directory& dir); void SongsDiscovered(const SongList& songs); @@ -206,7 +230,6 @@ class LibraryBackend : public LibraryBackendInterface { bool has_samplers; bool has_not_samplers; - }; static const char* kNewScoreSql; @@ -231,4 +254,4 @@ class LibraryBackend : public LibraryBackendInterface { bool save_ratings_in_file_; }; -#endif // LIBRARYBACKEND_H +#endif // LIBRARYBACKEND_H diff --git a/src/library/librarydirectorymodel.cpp b/src/library/librarydirectorymodel.cpp index 06596f242..afe18c783 100644 --- a/src/library/librarydirectorymodel.cpp +++ b/src/library/librarydirectorymodel.cpp @@ -23,35 +23,37 @@ #include "core/utilities.h" #include "ui/iconloader.h" -LibraryDirectoryModel::LibraryDirectoryModel(LibraryBackend* backend, QObject* parent) - : QStandardItemModel(parent), - dir_icon_(IconLoader::Load("document-open-folder")), - backend_(backend) -{ - connect(backend_, SIGNAL(DirectoryDiscovered(Directory, SubdirectoryList)), SLOT(DirectoryDiscovered(Directory))); - connect(backend_, SIGNAL(DirectoryDeleted(Directory)), SLOT(DirectoryDeleted(Directory))); +LibraryDirectoryModel::LibraryDirectoryModel(LibraryBackend* backend, + QObject* parent) + : QStandardItemModel(parent), + dir_icon_(IconLoader::Load("document-open-folder")), + backend_(backend) { + connect(backend_, SIGNAL(DirectoryDiscovered(Directory, SubdirectoryList)), + SLOT(DirectoryDiscovered(Directory))); + connect(backend_, SIGNAL(DirectoryDeleted(Directory)), + SLOT(DirectoryDeleted(Directory))); } -LibraryDirectoryModel::~LibraryDirectoryModel() { -} +LibraryDirectoryModel::~LibraryDirectoryModel() {} -void LibraryDirectoryModel::DirectoryDiscovered(const Directory &dir) { +void LibraryDirectoryModel::DirectoryDiscovered(const Directory& dir) { QStandardItem* item; - if (Application::kIsPortable - && Utilities::UrlOnSameDriveAsClementine(QUrl::fromLocalFile(dir.path))) { + if (Application::kIsPortable && + Utilities::UrlOnSameDriveAsClementine(QUrl::fromLocalFile(dir.path))) { item = new QStandardItem(Utilities::GetRelativePathToClementineBin( - QUrl::fromLocalFile(dir.path)).toLocalFile()); + QUrl::fromLocalFile(dir.path)).toLocalFile()); } else { item = new QStandardItem(dir.path); } item->setData(dir.id, kIdRole); item->setIcon(dir_icon_); - storage_ << std::shared_ptr(new FilesystemMusicStorage(dir.path)); + storage_ << std::shared_ptr( + new FilesystemMusicStorage(dir.path)); appendRow(item); } -void LibraryDirectoryModel::DirectoryDeleted(const Directory &dir) { - for (int i=0 ; idata(kIdRole).toInt() == dir.id) { removeRow(i); storage_.removeAt(i); @@ -61,15 +63,13 @@ void LibraryDirectoryModel::DirectoryDeleted(const Directory &dir) { } void LibraryDirectoryModel::AddDirectory(const QString& path) { - if (!backend_) - return; + if (!backend_) return; backend_->AddDirectory(path); } void LibraryDirectoryModel::RemoveDirectory(const QModelIndex& index) { - if (!backend_ || !index.isValid()) - return; + if (!backend_ || !index.isValid()) return; Directory dir; dir.path = index.data().toString(); @@ -78,19 +78,21 @@ void LibraryDirectoryModel::RemoveDirectory(const QModelIndex& index) { backend_->RemoveDirectory(dir); } -QVariant LibraryDirectoryModel::data(const QModelIndex &index, int role) const { +QVariant LibraryDirectoryModel::data(const QModelIndex& index, int role) const { switch (role) { - case MusicStorage::Role_Storage: - case MusicStorage::Role_StorageForceConnect: - return QVariant::fromValue(storage_[index.row()]); + case MusicStorage::Role_Storage: + case MusicStorage::Role_StorageForceConnect: + return QVariant::fromValue(storage_[index.row()]); - case MusicStorage::Role_FreeSpace: - return Utilities::FileSystemFreeSpace(data(index, Qt::DisplayRole).toString()); + case MusicStorage::Role_FreeSpace: + return Utilities::FileSystemFreeSpace( + data(index, Qt::DisplayRole).toString()); - case MusicStorage::Role_Capacity: - return Utilities::FileSystemCapacity(data(index, Qt::DisplayRole).toString()); + case MusicStorage::Role_Capacity: + return Utilities::FileSystemCapacity( + data(index, Qt::DisplayRole).toString()); - default: - return QStandardItemModel::data(index, role); + default: + return QStandardItemModel::data(index, role); } } diff --git a/src/library/librarydirectorymodel.h b/src/library/librarydirectorymodel.h index 5d7c4d482..92494828c 100644 --- a/src/library/librarydirectorymodel.h +++ b/src/library/librarydirectorymodel.h @@ -39,7 +39,7 @@ class LibraryDirectoryModel : public QStandardItemModel { void AddDirectory(const QString& path); void RemoveDirectory(const QModelIndex& index); - QVariant data(const QModelIndex &index, int role) const; + QVariant data(const QModelIndex& index, int role) const; private slots: // To be called by the backend @@ -54,4 +54,4 @@ class LibraryDirectoryModel : public QStandardItemModel { QList > storage_; }; -#endif // LIBRARYDIRECTORYMODEL_H +#endif // LIBRARYDIRECTORYMODEL_H diff --git a/src/library/libraryfilterwidget.cpp b/src/library/libraryfilterwidget.cpp index 37c3aec2b..11f0287cf 100644 --- a/src/library/libraryfilterwidget.cpp +++ b/src/library/libraryfilterwidget.cpp @@ -30,15 +30,14 @@ #include #include -LibraryFilterWidget::LibraryFilterWidget(QWidget *parent) - : QWidget(parent), - ui_(new Ui_LibraryFilterWidget), - model_(nullptr), - group_by_dialog_(new GroupByDialog), - filter_delay_(new QTimer(this)), - filter_applies_to_model_(true), - delay_behaviour_(DelayedOnLargeLibraries) -{ +LibraryFilterWidget::LibraryFilterWidget(QWidget* parent) + : QWidget(parent), + ui_(new Ui_LibraryFilterWidget), + model_(nullptr), + group_by_dialog_(new GroupByDialog), + filter_delay_(new QTimer(this)), + filter_applies_to_model_(true), + delay_behaviour_(DelayedOnLargeLibraries) { ui_->setupUi(this); connect(ui_->filter, SIGNAL(returnPressed()), SIGNAL(ReturnPressed())); connect(filter_delay_, SIGNAL(timeout()), SLOT(FilterDelayTimeout())); @@ -63,18 +62,25 @@ LibraryFilterWidget::LibraryFilterWidget(QWidget *parent) filter_age_mapper_ = new QSignalMapper(this); filter_age_mapper_->setMapping(ui_->filter_age_all, -1); - filter_age_mapper_->setMapping(ui_->filter_age_today, 60*60*24); - filter_age_mapper_->setMapping(ui_->filter_age_week, 60*60*24*7); - filter_age_mapper_->setMapping(ui_->filter_age_month, 60*60*24*30); - filter_age_mapper_->setMapping(ui_->filter_age_three_months, 60*60*24*30*3); - filter_age_mapper_->setMapping(ui_->filter_age_year, 60*60*24*365); + filter_age_mapper_->setMapping(ui_->filter_age_today, 60 * 60 * 24); + filter_age_mapper_->setMapping(ui_->filter_age_week, 60 * 60 * 24 * 7); + filter_age_mapper_->setMapping(ui_->filter_age_month, 60 * 60 * 24 * 30); + filter_age_mapper_->setMapping(ui_->filter_age_three_months, + 60 * 60 * 24 * 30 * 3); + filter_age_mapper_->setMapping(ui_->filter_age_year, 60 * 60 * 24 * 365); - connect(ui_->filter_age_all, SIGNAL(triggered()), filter_age_mapper_, SLOT(map())); - connect(ui_->filter_age_today, SIGNAL(triggered()), filter_age_mapper_, SLOT(map())); - connect(ui_->filter_age_week, SIGNAL(triggered()), filter_age_mapper_, SLOT(map())); - connect(ui_->filter_age_month, SIGNAL(triggered()), filter_age_mapper_, SLOT(map())); - connect(ui_->filter_age_three_months, SIGNAL(triggered()), filter_age_mapper_, SLOT(map())); - connect(ui_->filter_age_year, SIGNAL(triggered()), filter_age_mapper_, SLOT(map())); + connect(ui_->filter_age_all, SIGNAL(triggered()), filter_age_mapper_, + SLOT(map())); + connect(ui_->filter_age_today, SIGNAL(triggered()), filter_age_mapper_, + SLOT(map())); + connect(ui_->filter_age_week, SIGNAL(triggered()), filter_age_mapper_, + SLOT(map())); + connect(ui_->filter_age_month, SIGNAL(triggered()), filter_age_mapper_, + SLOT(map())); + connect(ui_->filter_age_three_months, SIGNAL(triggered()), filter_age_mapper_, + SLOT(map())); + connect(ui_->filter_age_year, SIGNAL(triggered()), filter_age_mapper_, + SLOT(map())); // "Group by ..." group_by_group_ = CreateGroupByActions(this); @@ -82,7 +88,8 @@ LibraryFilterWidget::LibraryFilterWidget(QWidget *parent) group_by_menu_ = new QMenu(tr("Group by"), this); group_by_menu_->addActions(group_by_group_->actions()); - connect(group_by_group_, SIGNAL(triggered(QAction*)), SLOT(GroupByClicked(QAction*))); + connect(group_by_group_, SIGNAL(triggered(QAction*)), + SLOT(GroupByClicked(QAction*))); // Library config menu library_menu_ = new QMenu(tr("Display options"), this); @@ -92,35 +99,46 @@ LibraryFilterWidget::LibraryFilterWidget(QWidget *parent) library_menu_->addSeparator(); ui_->options->setMenu(library_menu_); - connect(ui_->filter, SIGNAL(textChanged(QString)), SLOT(FilterTextChanged(QString))); + connect(ui_->filter, SIGNAL(textChanged(QString)), + SLOT(FilterTextChanged(QString))); } -LibraryFilterWidget::~LibraryFilterWidget() { - delete ui_; -} +LibraryFilterWidget::~LibraryFilterWidget() { delete ui_; } QActionGroup* LibraryFilterWidget::CreateGroupByActions(QObject* parent) { QActionGroup* ret = new QActionGroup(parent); - ret->addAction(CreateGroupByAction(tr("Group by Artist"), parent, + ret->addAction(CreateGroupByAction( + tr("Group by Artist"), parent, LibraryModel::Grouping(LibraryModel::GroupBy_Artist))); - ret->addAction(CreateGroupByAction(tr("Group by Artist/Album"), parent, - LibraryModel::Grouping(LibraryModel::GroupBy_Artist, LibraryModel::GroupBy_Album))); - ret->addAction(CreateGroupByAction(tr("Group by Artist/Year - Album"), parent, - LibraryModel::Grouping(LibraryModel::GroupBy_Artist, LibraryModel::GroupBy_YearAlbum))); - ret->addAction(CreateGroupByAction(tr("Group by Album"), parent, - LibraryModel::Grouping(LibraryModel::GroupBy_Album))); - ret->addAction(CreateGroupByAction(tr("Group by Genre/Album"), parent, - LibraryModel::Grouping(LibraryModel::GroupBy_Genre, LibraryModel::GroupBy_Album))); - ret->addAction(CreateGroupByAction(tr("Group by Genre/Artist/Album"), parent, - LibraryModel::Grouping(LibraryModel::GroupBy_Genre, LibraryModel::GroupBy_Artist, LibraryModel::GroupBy_Album))); + ret->addAction( + CreateGroupByAction(tr("Group by Artist/Album"), parent, + LibraryModel::Grouping(LibraryModel::GroupBy_Artist, + LibraryModel::GroupBy_Album))); + ret->addAction(CreateGroupByAction( + tr("Group by Artist/Year - Album"), parent, + LibraryModel::Grouping(LibraryModel::GroupBy_Artist, + LibraryModel::GroupBy_YearAlbum))); + ret->addAction( + CreateGroupByAction(tr("Group by Album"), parent, + LibraryModel::Grouping(LibraryModel::GroupBy_Album))); + ret->addAction( + CreateGroupByAction(tr("Group by Genre/Album"), parent, + LibraryModel::Grouping(LibraryModel::GroupBy_Genre, + LibraryModel::GroupBy_Album))); + ret->addAction( + CreateGroupByAction(tr("Group by Genre/Artist/Album"), parent, + LibraryModel::Grouping(LibraryModel::GroupBy_Genre, + LibraryModel::GroupBy_Artist, + LibraryModel::GroupBy_Album))); ret->addAction(CreateGroupByAction(tr("Advanced grouping..."), parent, - LibraryModel::Grouping())); + LibraryModel::Grouping())); return ret; } QAction* LibraryFilterWidget::CreateGroupByAction( - const QString& text, QObject* parent, const LibraryModel::Grouping& grouping) { + const QString& text, QObject* parent, + const LibraryModel::Grouping& grouping) { QAction* ret = new QAction(text, parent); ret->setCheckable(true); @@ -131,12 +149,12 @@ QAction* LibraryFilterWidget::CreateGroupByAction( return ret; } -void LibraryFilterWidget::FocusOnFilter(QKeyEvent *event) { +void LibraryFilterWidget::FocusOnFilter(QKeyEvent* event) { ui_->filter->setFocus(); QApplication::sendEvent(ui_->filter, event); } -void LibraryFilterWidget::SetLibraryModel(LibraryModel *model) { +void LibraryFilterWidget::SetLibraryModel(LibraryModel* model) { if (model_) { disconnect(model_, 0, this, 0); disconnect(model_, 0, group_by_dialog_.get(), 0); @@ -148,21 +166,26 @@ void LibraryFilterWidget::SetLibraryModel(LibraryModel *model) { // Connect signals connect(model_, SIGNAL(GroupingChanged(LibraryModel::Grouping)), - group_by_dialog_.get(), SLOT(LibraryGroupingChanged(LibraryModel::Grouping))); + group_by_dialog_.get(), + SLOT(LibraryGroupingChanged(LibraryModel::Grouping))); connect(model_, SIGNAL(GroupingChanged(LibraryModel::Grouping)), SLOT(GroupingChanged(LibraryModel::Grouping))); connect(group_by_dialog_.get(), SIGNAL(Accepted(LibraryModel::Grouping)), model_, SLOT(SetGroupBy(LibraryModel::Grouping))); - connect(filter_age_mapper_, SIGNAL(mapped(int)), model_, SLOT(SetFilterAge(int))); + connect(filter_age_mapper_, SIGNAL(mapped(int)), model_, + SLOT(SetFilterAge(int))); // Load settings if (!settings_group_.isEmpty()) { QSettings s; s.beginGroup(settings_group_); model_->SetGroupBy(LibraryModel::Grouping( - LibraryModel::GroupBy(s.value("group_by1", int(LibraryModel::GroupBy_Artist)).toInt()), - LibraryModel::GroupBy(s.value("group_by2", int(LibraryModel::GroupBy_Album)).toInt()), - LibraryModel::GroupBy(s.value("group_by3", int(LibraryModel::GroupBy_None)).toInt()))); + LibraryModel::GroupBy( + s.value("group_by1", int(LibraryModel::GroupBy_Artist)).toInt()), + LibraryModel::GroupBy( + s.value("group_by2", int(LibraryModel::GroupBy_Album)).toInt()), + LibraryModel::GroupBy( + s.value("group_by3", int(LibraryModel::GroupBy_None)).toInt()))); } } @@ -172,7 +195,8 @@ void LibraryFilterWidget::GroupByClicked(QAction* action) { return; } - LibraryModel::Grouping g = action->property("group_by").value(); + LibraryModel::Grouping g = + action->property("group_by").value(); model_->SetGroupBy(g); } @@ -187,9 +211,8 @@ void LibraryFilterWidget::GroupingChanged(const LibraryModel::Grouping& g) { } // Now make sure the correct action is checked - foreach (QAction* action, group_by_group_->actions()) { - if (action->property("group_by").isNull()) - continue; + foreach(QAction * action, group_by_group_->actions()) { + if (action->property("group_by").isNull()) continue; if (g == action->property("group_by").value()) { action->setChecked(true); @@ -254,10 +277,10 @@ void LibraryFilterWidget::FilterTextChanged(const QString& text) { // even with FTS, so if there are a large number of songs in the database // introduce a small delay before actually filtering the model, so if the // user is typing the first few characters of something it will be quicker. - const bool delay = (delay_behaviour_ == AlwaysDelayed) - || (delay_behaviour_ == DelayedOnLargeLibraries && - !text.isEmpty() && text.length() < 3 && - model_->total_song_count() >= 100000); + const bool delay = + (delay_behaviour_ == AlwaysDelayed) || + (delay_behaviour_ == DelayedOnLargeLibraries && !text.isEmpty() && + text.length() < 3 && model_->total_song_count() >= 100000); if (delay) { filter_delay_->start(); diff --git a/src/library/libraryfilterwidget.h b/src/library/libraryfilterwidget.h index 74620ba20..426c5ab39 100644 --- a/src/library/libraryfilterwidget.h +++ b/src/library/libraryfilterwidget.h @@ -41,7 +41,7 @@ class LibraryFilterWidget : public QWidget { LibraryFilterWidget(QWidget* parent = 0); ~LibraryFilterWidget(); - static const int kFilterDelay = 500; // msec + static const int kFilterDelay = 500; // msec enum DelayBehaviour { AlwaysInstant, @@ -52,8 +52,12 @@ class LibraryFilterWidget : public QWidget { static QActionGroup* CreateGroupByActions(QObject* parent); void SetFilterHint(const QString& hint); - void SetApplyFilterToLibrary(bool filter_applies_to_model) { filter_applies_to_model_ = filter_applies_to_model; } - void SetDelayBehaviour(DelayBehaviour behaviour) { delay_behaviour_ = behaviour; } + void SetApplyFilterToLibrary(bool filter_applies_to_model) { + filter_applies_to_model_ = filter_applies_to_model; + } + void SetDelayBehaviour(DelayBehaviour behaviour) { + delay_behaviour_ = behaviour; + } void SetAgeFilterEnabled(bool enabled); void SetGroupByEnabled(bool enabled); void ShowInLibrary(const QString& search); @@ -68,7 +72,7 @@ class LibraryFilterWidget : public QWidget { void SetQueryMode(QueryOptions::QueryMode view); void FocusOnFilter(QKeyEvent* e); - signals: +signals: void UpPressed(); void DownPressed(); void ReturnPressed(); @@ -109,4 +113,4 @@ class LibraryFilterWidget : public QWidget { QString settings_group_; }; -#endif // LIBRARYFILTERWIDGET_H +#endif // LIBRARYFILTERWIDGET_H diff --git a/src/library/libraryitem.h b/src/library/libraryitem.h index 2a14c45a7..e9363b36e 100644 --- a/src/library/libraryitem.h +++ b/src/library/libraryitem.h @@ -37,14 +37,14 @@ class LibraryItem : public SimpleTreeItem { }; LibraryItem(SimpleTreeModel* model) - : SimpleTreeItem(Type_Root, model), - container_level(-1), - compilation_artist_node_(NULL) {} + : SimpleTreeItem(Type_Root, model), + container_level(-1), + compilation_artist_node_(NULL) {} LibraryItem(Type type, LibraryItem* parent = NULL) - : SimpleTreeItem(type, parent), - container_level(-1), - compilation_artist_node_(NULL) {} + : SimpleTreeItem(type, parent), + container_level(-1), + compilation_artist_node_(NULL) {} int container_level; Song metadata; @@ -52,4 +52,4 @@ class LibraryItem : public SimpleTreeItem { LibraryItem* compilation_artist_node_; }; -#endif // LIBRARYITEM_H +#endif // LIBRARYITEM_H diff --git a/src/library/librarymodel.cpp b/src/library/librarymodel.cpp index 9a1240aaf..cc0ef0560 100644 --- a/src/library/librarymodel.cpp +++ b/src/library/librarymodel.cpp @@ -52,8 +52,10 @@ using smart_playlists::GeneratorMimeData; using smart_playlists::GeneratorPtr; using smart_playlists::QueryGenerator; -const char* LibraryModel::kSmartPlaylistsMimeType = "application/x-clementine-smart-playlist-generator"; -const char* LibraryModel::kSmartPlaylistsSettingsGroup = "SerialisedSmartPlaylists"; +const char* LibraryModel::kSmartPlaylistsMimeType = + "application/x-clementine-smart-playlist-generator"; +const char* LibraryModel::kSmartPlaylistsSettingsGroup = + "SerialisedSmartPlaylists"; const int LibraryModel::kSmartPlaylistsVersion = 4; const int LibraryModel::kPrettyCoverSize = 32; @@ -61,7 +63,8 @@ typedef QFuture RootQueryFuture; typedef QFutureWatcher RootQueryWatcher; static bool IsArtistGroupBy(const LibraryModel::GroupBy by) { - return by == LibraryModel::GroupBy_Artist || by == LibraryModel::GroupBy_AlbumArtist; + return by == LibraryModel::GroupBy_Artist || + by == LibraryModel::GroupBy_AlbumArtist; } static bool IsCompilationArtistNode(const LibraryItem* node) { @@ -70,21 +73,20 @@ static bool IsCompilationArtistNode(const LibraryItem* node) { LibraryModel::LibraryModel(LibraryBackend* backend, Application* app, QObject* parent) - : SimpleTreeModel(new LibraryItem(this), parent), - backend_(backend), - app_(app), - dir_model_(new LibraryDirectoryModel(backend, this)), - show_smart_playlists_(false), - show_various_artists_(true), - total_song_count_(0), - artist_icon_(":/icons/22x22/x-clementine-artist.png"), - album_icon_(":/icons/22x22/x-clementine-album.png"), - playlists_dir_icon_(IconLoader::Load("folder-sound")), - playlist_icon_(":/icons/22x22/x-clementine-albums.png"), - init_task_id_(-1), - use_pretty_covers_(false), - show_dividers_(true) -{ + : SimpleTreeModel(new LibraryItem(this), parent), + backend_(backend), + app_(app), + dir_model_(new LibraryDirectoryModel(backend, this)), + show_smart_playlists_(false), + show_various_artists_(true), + total_song_count_(0), + artist_icon_(":/icons/22x22/x-clementine-artist.png"), + album_icon_(":/icons/22x22/x-clementine-album.png"), + playlists_dir_icon_(IconLoader::Load("folder-sound")), + playlist_icon_(":/icons/22x22/x-clementine-albums.png"), + init_task_id_(-1), + use_pretty_covers_(false), + show_dividers_(true) { root_->lazy_loaded = true; group_by_[0] = GroupBy_Artist; @@ -95,27 +97,29 @@ LibraryModel::LibraryModel(LibraryBackend* backend, Application* app, cover_loader_options_.pad_output_image_ = true; cover_loader_options_.scale_output_image_ = true; - connect(app_->album_cover_loader(), - SIGNAL(ImageLoaded(quint64,QImage)), - SLOT(AlbumArtLoaded(quint64,QImage))); + connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)), + SLOT(AlbumArtLoaded(quint64, QImage))); - no_cover_icon_ = QPixmap(":nocover.png").scaled( - kPrettyCoverSize, kPrettyCoverSize, - Qt::KeepAspectRatio, Qt::SmoothTransformation); + no_cover_icon_ = QPixmap(":nocover.png") + .scaled(kPrettyCoverSize, kPrettyCoverSize, + Qt::KeepAspectRatio, Qt::SmoothTransformation); - connect(backend_, SIGNAL(SongsDiscovered(SongList)), SLOT(SongsDiscovered(SongList))); - connect(backend_, SIGNAL(SongsDeleted(SongList)), SLOT(SongsDeleted(SongList))); - connect(backend_, SIGNAL(SongsStatisticsChanged(SongList)), SLOT(SongsSlightlyChanged(SongList))); - connect(backend_, SIGNAL(SongsRatingChanged(SongList)), SLOT(SongsSlightlyChanged(SongList))); + connect(backend_, SIGNAL(SongsDiscovered(SongList)), + SLOT(SongsDiscovered(SongList))); + connect(backend_, SIGNAL(SongsDeleted(SongList)), + SLOT(SongsDeleted(SongList))); + connect(backend_, SIGNAL(SongsStatisticsChanged(SongList)), + SLOT(SongsSlightlyChanged(SongList))); + connect(backend_, SIGNAL(SongsRatingChanged(SongList)), + SLOT(SongsSlightlyChanged(SongList))); connect(backend_, SIGNAL(DatabaseReset()), SLOT(Reset())); - connect(backend_, SIGNAL(TotalSongCountUpdated(int)), SLOT(TotalSongCountUpdatedSlot(int))); + connect(backend_, SIGNAL(TotalSongCountUpdated(int)), + SLOT(TotalSongCountUpdatedSlot(int))); backend_->UpdateTotalSongCountAsync(); } -LibraryModel::~LibraryModel() { - delete root_; -} +LibraryModel::~LibraryModel() { delete root_; } void LibraryModel::set_pretty_covers(bool use_pretty_covers) { if (use_pretty_covers != use_pretty_covers_) { @@ -134,7 +138,8 @@ void LibraryModel::set_show_dividers(bool show_dividers) { void LibraryModel::Init(bool async) { if (async) { // Show a loading indicator in the model. - LibraryItem* loading = new LibraryItem(LibraryItem::Type_LoadingIndicator, root_); + LibraryItem* loading = + new LibraryItem(LibraryItem::Type_LoadingIndicator, root_); loading->display_text = tr("Loading..."); loading->lazy_loaded = true; reset(); @@ -149,15 +154,13 @@ void LibraryModel::Init(bool async) { } void LibraryModel::SongsDiscovered(const SongList& songs) { - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { // Sanity check to make sure we don't add songs that are outside the user's // filter - if (!query_options_.Matches(song)) - continue; + if (!query_options_.Matches(song)) continue; // Hey, we've already got that one! - if (song_nodes_.contains(song.id())) - continue; + if (song_nodes_.contains(song.id())) continue; // Before we can add each song we need to make sure the required container // items already exist in the tree. These depend on which "group by" @@ -167,7 +170,7 @@ void LibraryModel::SongsDiscovered(const SongList& songs) { // Find parent containers in the tree LibraryItem* container = root_; - for (int i=0 ; i<3 ; ++i) { + for (int i = 0; i < 3; ++i) { GroupBy type = group_by_[i]; if (type == GroupBy_None) break; @@ -182,19 +185,39 @@ void LibraryModel::SongsDiscovered(const SongList& songs) { // item's key QString key; switch (type) { - case GroupBy_Album: key = song.album(); break; - case GroupBy_Artist: key = song.artist(); break; - case GroupBy_Composer: key = song.composer(); break; - case GroupBy_Performer: key = song.performer(); break; - case GroupBy_Grouping: key = song.grouping(); break; - case GroupBy_Genre: key = song.genre(); break; - case GroupBy_AlbumArtist: key = song.effective_albumartist(); break; + case GroupBy_Album: + key = song.album(); + break; + case GroupBy_Artist: + key = song.artist(); + break; + case GroupBy_Composer: + key = song.composer(); + break; + case GroupBy_Performer: + key = song.performer(); + break; + case GroupBy_Grouping: + key = song.grouping(); + break; + case GroupBy_Genre: + key = song.genre(); + break; + case GroupBy_AlbumArtist: + key = song.effective_albumartist(); + break; case GroupBy_Year: - key = QString::number(qMax(0, song.year())); break; + key = QString::number(qMax(0, song.year())); + break; case GroupBy_YearAlbum: - key = PrettyYearAlbum(qMax(0, song.year()), song.album()); break; - case GroupBy_FileType: key = song.filetype(); break; - case GroupBy_Bitrate: key = song.bitrate(); break; + key = PrettyYearAlbum(qMax(0, song.year()), song.album()); + break; + case GroupBy_FileType: + key = song.filetype(); + break; + case GroupBy_Bitrate: + key = song.bitrate(); + break; case GroupBy_None: qLog(Error) << "GroupBy_None"; break; @@ -211,12 +234,10 @@ void LibraryModel::SongsDiscovered(const SongList& songs) { // If we just created the damn thing then we don't need to continue into // it any further because it'll get lazy-loaded properly later. - if (!container->lazy_loaded) - break; + if (!container->lazy_loaded) break; } - if (!container->lazy_loaded) - continue; + if (!container->lazy_loaded) continue; // We've gone all the way down to the deepest level and everything was // already lazy loaded, so now we have to create the song in the container. @@ -229,26 +250,28 @@ void LibraryModel::SongsSlightlyChanged(const SongList& songs) { // This is called if there was a minor change to the songs that will not // normally require the library to be restructured. We can just update our // internal cache of Song objects without worrying about resetting the model. - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { if (song_nodes_.contains(song.id())) { song_nodes_[song.id()]->metadata = song; } } } -LibraryItem* LibraryModel::CreateCompilationArtistNode(bool signal, LibraryItem* parent) { +LibraryItem* LibraryModel::CreateCompilationArtistNode(bool signal, + LibraryItem* parent) { if (signal) - beginInsertRows(ItemToIndex(parent), parent->children.count(), parent->children.count()); + beginInsertRows(ItemToIndex(parent), parent->children.count(), + parent->children.count()); parent->compilation_artist_node_ = new LibraryItem(LibraryItem::Type_Container, parent); parent->compilation_artist_node_->compilation_artist_node_ = nullptr; parent->compilation_artist_node_->key = tr("Various artists"); parent->compilation_artist_node_->sort_text = " various"; - parent->compilation_artist_node_->container_level = parent->container_level + 1; + parent->compilation_artist_node_->container_level = + parent->container_level + 1; - if (signal) - endInsertRows(); + if (signal) endInsertRows(); return parent->compilation_artist_node_; } @@ -257,78 +280,73 @@ QString LibraryModel::DividerKey(GroupBy type, LibraryItem* item) const { // Items which are to be grouped under the same divider must produce the // same divider key. This will only get called for top-level items. - if (item->sort_text.isEmpty()) - return QString(); + if (item->sort_text.isEmpty()) return QString(); switch (type) { - case GroupBy_Album: - case GroupBy_Artist: - case GroupBy_Composer: - case GroupBy_Performer: - case GroupBy_Grouping: - case GroupBy_Genre: - case GroupBy_AlbumArtist: - case GroupBy_FileType: { - QChar c = item->sort_text[0]; - if (c.isDigit()) - return "0"; - if (c == ' ') + case GroupBy_Album: + case GroupBy_Artist: + case GroupBy_Composer: + case GroupBy_Performer: + case GroupBy_Grouping: + case GroupBy_Genre: + case GroupBy_AlbumArtist: + case GroupBy_FileType: { + QChar c = item->sort_text[0]; + if (c.isDigit()) return "0"; + if (c == ' ') return QString(); + if (c.decompositionTag() != QChar::NoDecomposition) + return QChar(c.decomposition()[0]); + return c; + } + + case GroupBy_Year: + return SortTextForYear(item->sort_text.toInt() / 10 * 10); + + case GroupBy_YearAlbum: + return SortTextForYear(item->metadata.year()); + + case GroupBy_Bitrate: + return SortTextForBitrate(item->metadata.bitrate()); + + case GroupBy_None: return QString(); - if (c.decompositionTag() != QChar::NoDecomposition) - return QChar(c.decomposition()[0]); - return c; } - - case GroupBy_Year: - return SortTextForYear(item->sort_text.toInt() / 10 * 10); - - case GroupBy_YearAlbum: - return SortTextForYear(item->metadata.year()); - - case GroupBy_Bitrate: - return SortTextForBitrate(item->metadata.bitrate()); - - case GroupBy_None: - return QString(); - } - qLog(Error) << "Unknown GroupBy type" << type << "for item" << item->display_text; + qLog(Error) << "Unknown GroupBy type" << type << "for item" + << item->display_text; return QString(); } -QString LibraryModel::DividerDisplayText(GroupBy type, const QString& key) const { +QString LibraryModel::DividerDisplayText(GroupBy type, + const QString& key) const { // Pretty display text for the dividers. switch (type) { - case GroupBy_Album: - case GroupBy_Artist: - case GroupBy_Composer: - case GroupBy_Performer: - case GroupBy_Grouping: - case GroupBy_Genre: - case GroupBy_AlbumArtist: - case GroupBy_FileType: - if (key == "0") - return "0-9"; - return key.toUpper(); + case GroupBy_Album: + case GroupBy_Artist: + case GroupBy_Composer: + case GroupBy_Performer: + case GroupBy_Grouping: + case GroupBy_Genre: + case GroupBy_AlbumArtist: + case GroupBy_FileType: + if (key == "0") return "0-9"; + return key.toUpper(); - case GroupBy_YearAlbum: - if (key == "0000") - return tr("Unknown"); - return key.toUpper(); + case GroupBy_YearAlbum: + if (key == "0000") return tr("Unknown"); + return key.toUpper(); - case GroupBy_Year: - if (key == "0000") - return tr("Unknown"); - return QString::number(key.toInt()); // To remove leading 0s + case GroupBy_Year: + if (key == "0000") return tr("Unknown"); + return QString::number(key.toInt()); // To remove leading 0s - case GroupBy_Bitrate: - if (key == "000") - return tr("Unknown"); - return QString::number(key.toInt()); // To remove leading 0s + case GroupBy_Bitrate: + if (key == "000") return tr("Unknown"); + return QString::number(key.toInt()); // To remove leading 0s - case GroupBy_None: - // fallthrough - ; + case GroupBy_None: + // fallthrough + ; } qLog(Error) << "Unknown GroupBy type" << type << "for divider key" << key; return QString(); @@ -338,12 +356,11 @@ void LibraryModel::SongsDeleted(const SongList& songs) { // Delete the actual song nodes first, keeping track of each parent so we // might check to see if they're empty later. QSet parents; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { if (song_nodes_.contains(song.id())) { LibraryItem* node = song_nodes_[song.id()]; - if (node->parent != root_) - parents << node->parent; + if (node->parent != root_) parents << node->parent; beginRemoveRows(ItemToIndex(node->parent), node->row, node->row); node->parent->Delete(node->row); @@ -363,14 +380,12 @@ void LibraryModel::SongsDeleted(const SongList& songs) { // Now delete empty parents QSet divider_keys; while (!parents.isEmpty()) { - foreach (LibraryItem* node, parents) { + foreach(LibraryItem * node, parents) { parents.remove(node); - if (node->children.count() != 0) - continue; + if (node->children.count() != 0) continue; // Consider its parent for the next round - if (node->parent != root_) - parents << node->parent; + if (node->parent != root_) parents << node->parent; // Maybe consider its divider node if (node->container_level == 0) @@ -390,21 +405,19 @@ void LibraryModel::SongsDeleted(const SongList& songs) { } // Delete empty dividers - foreach (const QString& divider_key, divider_keys) { - if (!divider_nodes_.contains(divider_key)) - continue; + foreach(const QString & divider_key, divider_keys) { + if (!divider_nodes_.contains(divider_key)) continue; // Look to see if there are any other items still under this divider bool found = false; - foreach (LibraryItem* node, container_nodes_[0].values()) { + foreach(LibraryItem * node, container_nodes_[0].values()) { if (DividerKey(group_by_[0], node) == divider_key) { found = true; break; } } - if (found) - continue; + if (found) continue; // Remove the divider int row = divider_nodes_[divider_key]->row; @@ -428,8 +441,7 @@ QString LibraryModel::AlbumIconPixmapCacheKey(const QModelIndex& index) const { QVariant LibraryModel::AlbumIcon(const QModelIndex& index) { LibraryItem* item = IndexToItem(index); - if (!item) - return no_cover_icon_; + if (!item) return no_cover_icon_; // Check the cache for a pixmap we already loaded. const QString cache_key = AlbumIconPixmapCacheKey(index); @@ -448,7 +460,7 @@ QVariant LibraryModel::AlbumIcon(const QModelIndex& index) { SongList songs = GetChildSongs(index); if (!songs.isEmpty()) { const quint64 id = app_->album_cover_loader()->LoadImageAsync( - cover_loader_options_, songs.first()); + cover_loader_options_, songs.first()); pending_art_[id] = ItemAndCacheKey(item, cache_key); pending_cache_keys_.insert(cache_key); } @@ -460,8 +472,7 @@ void LibraryModel::AlbumArtLoaded(quint64 id, const QImage& image) { ItemAndCacheKey item_and_cache_key = pending_art_.take(id); LibraryItem* item = item_and_cache_key.first; const QString& cache_key = item_and_cache_key.second; - if (!item) - return; + if (!item) return; pending_cache_keys_.remove(cache_key); @@ -479,17 +490,19 @@ void LibraryModel::AlbumArtLoaded(quint64 id, const QImage& image) { QVariant LibraryModel::data(const QModelIndex& index, int role) const { const LibraryItem* item = IndexToItem(index); - - // Handle a special case for returning album artwork instead of a generic CD icon. + + // Handle a special case for returning album artwork instead of a generic CD + // icon. // this is here instead of in the other data() function to let us use the // QModelIndex& version of GetChildSongs, which satisfies const-ness, instead // of the LibraryItem* version, which doesn't. - if (use_pretty_covers_) { + if (use_pretty_covers_) { bool is_album_node = false; - if (role == Qt::DecorationRole && item->type == LibraryItem::Type_Container) { + if (role == Qt::DecorationRole && + item->type == LibraryItem::Type_Container) { GroupBy container_type = group_by_[item->container_level]; - is_album_node = container_type == GroupBy_Album - || container_type == GroupBy_YearAlbum; + is_album_node = container_type == GroupBy_Album || + container_type == GroupBy_YearAlbum; } if (is_album_node) { // It has const behaviour some of the time - that's ok right? @@ -501,9 +514,9 @@ QVariant LibraryModel::data(const QModelIndex& index, int role) const { } QVariant LibraryModel::data(const LibraryItem* item, int role) const { - GroupBy container_type = - item->type == LibraryItem::Type_Container ? - group_by_[item->container_level] : GroupBy_None; + GroupBy container_type = item->type == LibraryItem::Type_Container + ? group_by_[item->container_level] + : GroupBy_None; switch (role) { case Qt::DisplayRole: @@ -550,16 +563,16 @@ QVariant LibraryModel::data(const LibraryItem* item, int role) const { case Role_Editable: if (!item->lazy_loaded) { - const_cast(this)->LazyPopulate( - const_cast(item), true); + const_cast(this) + ->LazyPopulate(const_cast(item), true); } - if(item->type == LibraryItem::Type_Container) { + if (item->type == LibraryItem::Type_Container) { // if we have even one non editable item as a child, we ourselves // are not available for edit - if(!item->children.isEmpty()) { - foreach(LibraryItem* child, item->children) { - if(!data(child, role).toBool()) { + if (!item->children.isEmpty()) { + foreach(LibraryItem * child, item->children) { + if (!data(child, role).toBool()) { return false; } } @@ -567,7 +580,7 @@ QVariant LibraryModel::data(const LibraryItem* item, int role) const { } else { return false; } - } else if(item->type == LibraryItem::Type_Song) { + } else if (item->type == LibraryItem::Type_Song) { return item->metadata.IsEditable(); } else { return false; @@ -622,8 +635,7 @@ LibraryModel::QueryResult LibraryModel::RunQuery(LibraryItem* parent) { // Execute the query QMutexLocker l(backend_->db()->Mutex()); - if (!backend_->ExecQuery(&q)) - return result; + if (!backend_->ExecQuery(&q)) return result; while (q.Next()) { result.rows << SqlRow(q); @@ -643,11 +655,10 @@ void LibraryModel::PostQuery(LibraryItem* parent, } // Step through the results - foreach (const SqlRow& row, result.rows) { + foreach(const SqlRow & row, result.rows) { // Create the item - it will get inserted into the model here - LibraryItem* item = - ItemFromQuery(child_type, signal, child_level == 0, parent, row, - child_level); + LibraryItem* item = ItemFromQuery(child_type, signal, child_level == 0, + parent, row, child_level); // Save a pointer to it for later if (child_type == GroupBy_None) @@ -658,8 +669,7 @@ void LibraryModel::PostQuery(LibraryItem* parent, } void LibraryModel::LazyPopulate(LibraryItem* parent, bool signal) { - if (parent->lazy_loaded) - return; + if (parent->lazy_loaded) return; parent->lazy_loaded = true; QueryResult result = RunQuery(parent); @@ -667,8 +677,8 @@ void LibraryModel::LazyPopulate(LibraryItem* parent, bool signal) { } void LibraryModel::ResetAsync() { - RootQueryFuture future = QtConcurrent::run( - this, &LibraryModel::RunQuery, root_); + RootQueryFuture future = + QtConcurrent::run(this, &LibraryModel::RunQuery, root_); RootQueryWatcher* watcher = new RootQueryWatcher(this); watcher->setFuture(future); @@ -725,111 +735,112 @@ void LibraryModel::Reset() { void LibraryModel::InitQuery(GroupBy type, LibraryQuery* q) { // Say what type of thing we want to get back from the database. switch (type) { - case GroupBy_Artist: - q->SetColumnSpec("DISTINCT artist"); - break; - case GroupBy_Album: - q->SetColumnSpec("DISTINCT album"); - break; - case GroupBy_Composer: - q->SetColumnSpec("DISTINCT composer"); - break; - case GroupBy_Performer: - q->SetColumnSpec("DISTINCT performer"); - break; - case GroupBy_Grouping: - q->SetColumnSpec("DISTINCT grouping"); - break; - case GroupBy_YearAlbum: - q->SetColumnSpec("DISTINCT year, album"); - break; - case GroupBy_Year: - q->SetColumnSpec("DISTINCT year"); - break; - case GroupBy_Genre: - q->SetColumnSpec("DISTINCT genre"); - break; - case GroupBy_AlbumArtist: - q->SetColumnSpec("DISTINCT effective_albumartist"); - break; - case GroupBy_Bitrate: - q->SetColumnSpec("DISTINCT bitrate"); - break; - case GroupBy_None: - q->SetColumnSpec("%songs_table.ROWID, " + Song::kColumnSpec); - break; - case GroupBy_FileType: - q->SetColumnSpec("DISTINCT filetype"); - break; + case GroupBy_Artist: + q->SetColumnSpec("DISTINCT artist"); + break; + case GroupBy_Album: + q->SetColumnSpec("DISTINCT album"); + break; + case GroupBy_Composer: + q->SetColumnSpec("DISTINCT composer"); + break; + case GroupBy_Performer: + q->SetColumnSpec("DISTINCT performer"); + break; + case GroupBy_Grouping: + q->SetColumnSpec("DISTINCT grouping"); + break; + case GroupBy_YearAlbum: + q->SetColumnSpec("DISTINCT year, album"); + break; + case GroupBy_Year: + q->SetColumnSpec("DISTINCT year"); + break; + case GroupBy_Genre: + q->SetColumnSpec("DISTINCT genre"); + break; + case GroupBy_AlbumArtist: + q->SetColumnSpec("DISTINCT effective_albumartist"); + break; + case GroupBy_Bitrate: + q->SetColumnSpec("DISTINCT bitrate"); + break; + case GroupBy_None: + q->SetColumnSpec("%songs_table.ROWID, " + Song::kColumnSpec); + break; + case GroupBy_FileType: + q->SetColumnSpec("DISTINCT filetype"); + break; } } -void LibraryModel::FilterQuery(GroupBy type, LibraryItem* item, LibraryQuery* q) { +void LibraryModel::FilterQuery(GroupBy type, LibraryItem* item, + LibraryQuery* q) { // Say how we want the query to be filtered. This is done once for each // parent going up the tree. switch (type) { - case GroupBy_Artist: - if (IsCompilationArtistNode(item)) - q->AddCompilationRequirement(true); - else { - // Don't duplicate compilations outside the Various artists node - q->AddCompilationRequirement(false); - q->AddWhere("artist", item->key); - } - break; - case GroupBy_Album: - q->AddWhere("album", item->key); - break; - case GroupBy_YearAlbum: - q->AddWhere("year", item->metadata.year()); - q->AddWhere("album", item->metadata.album()); - break; - case GroupBy_Year: - q->AddWhere("year", item->key); - break; - case GroupBy_Composer: - q->AddWhere("composer", item->key); - break; - case GroupBy_Performer: - q->AddWhere("performer", item->key); - break; - case GroupBy_Grouping: - q->AddWhere("grouping", item->key); - break; - case GroupBy_Genre: - q->AddWhere("genre", item->key); - break; - case GroupBy_AlbumArtist: - if (IsCompilationArtistNode(item)) - q->AddCompilationRequirement(true); - else { - // Don't duplicate compilations outside the Various artists node - q->AddCompilationRequirement(false); - q->AddWhere("effective_albumartist", item->key); - } - break; - case GroupBy_FileType: - q->AddWhere("filetype", item->metadata.filetype()); - break; - case GroupBy_Bitrate: - q->AddWhere("bitrate", item->key); - break; - case GroupBy_None: - qLog(Error) << "Unknown GroupBy type" << type << "used in filter"; - break; + case GroupBy_Artist: + if (IsCompilationArtistNode(item)) + q->AddCompilationRequirement(true); + else { + // Don't duplicate compilations outside the Various artists node + q->AddCompilationRequirement(false); + q->AddWhere("artist", item->key); + } + break; + case GroupBy_Album: + q->AddWhere("album", item->key); + break; + case GroupBy_YearAlbum: + q->AddWhere("year", item->metadata.year()); + q->AddWhere("album", item->metadata.album()); + break; + case GroupBy_Year: + q->AddWhere("year", item->key); + break; + case GroupBy_Composer: + q->AddWhere("composer", item->key); + break; + case GroupBy_Performer: + q->AddWhere("performer", item->key); + break; + case GroupBy_Grouping: + q->AddWhere("grouping", item->key); + break; + case GroupBy_Genre: + q->AddWhere("genre", item->key); + break; + case GroupBy_AlbumArtist: + if (IsCompilationArtistNode(item)) + q->AddCompilationRequirement(true); + else { + // Don't duplicate compilations outside the Various artists node + q->AddCompilationRequirement(false); + q->AddWhere("effective_albumartist", item->key); + } + break; + case GroupBy_FileType: + q->AddWhere("filetype", item->metadata.filetype()); + break; + case GroupBy_Bitrate: + q->AddWhere("bitrate", item->key); + break; + case GroupBy_None: + qLog(Error) << "Unknown GroupBy type" << type << "used in filter"; + break; } } -LibraryItem* LibraryModel::InitItem(GroupBy type, bool signal, LibraryItem *parent, - int container_level) { - LibraryItem::Type item_type = - type == GroupBy_None ? LibraryItem::Type_Song : - LibraryItem::Type_Container; +LibraryItem* LibraryModel::InitItem(GroupBy type, bool signal, + LibraryItem* parent, int container_level) { + LibraryItem::Type item_type = type == GroupBy_None + ? LibraryItem::Type_Song + : LibraryItem::Type_Container; if (signal) - beginInsertRows(ItemToIndex(parent), - parent->children.count(),parent->children.count()); + beginInsertRows(ItemToIndex(parent), parent->children.count(), + parent->children.count()); // Initialise the item depending on what type it's meant to be LibraryItem* item = new LibraryItem(item_type, parent); @@ -838,8 +849,8 @@ LibraryItem* LibraryModel::InitItem(GroupBy type, bool signal, LibraryItem *pare return item; } -LibraryItem* LibraryModel::ItemFromQuery(GroupBy type, - bool signal, bool create_divider, +LibraryItem* LibraryModel::ItemFromQuery(GroupBy type, bool signal, + bool create_divider, LibraryItem* parent, const SqlRow& row, int container_level) { LibraryItem* item = InitItem(type, signal, parent, container_level); @@ -847,132 +858,134 @@ LibraryItem* LibraryModel::ItemFromQuery(GroupBy type, int bitrate = 0; switch (type) { - case GroupBy_Artist: - item->key = row.value(0).toString(); - item->display_text = TextOrUnknown(item->key); - item->sort_text = SortTextForArtist(item->key); - break; + case GroupBy_Artist: + item->key = row.value(0).toString(); + item->display_text = TextOrUnknown(item->key); + item->sort_text = SortTextForArtist(item->key); + break; - case GroupBy_YearAlbum: - year = qMax(0, row.value(0).toInt()); - item->metadata.set_year(row.value(0).toInt()); - item->metadata.set_album(row.value(1).toString()); - item->key = PrettyYearAlbum(year, item->metadata.album()); - item->sort_text = SortTextForYear(year) + item->metadata.album(); - break; + case GroupBy_YearAlbum: + year = qMax(0, row.value(0).toInt()); + item->metadata.set_year(row.value(0).toInt()); + item->metadata.set_album(row.value(1).toString()); + item->key = PrettyYearAlbum(year, item->metadata.album()); + item->sort_text = SortTextForYear(year) + item->metadata.album(); + break; - case GroupBy_Year: - year = qMax(0, row.value(0).toInt()); - item->key = QString::number(year); - item->sort_text = SortTextForYear(year) + " "; - break; + case GroupBy_Year: + year = qMax(0, row.value(0).toInt()); + item->key = QString::number(year); + item->sort_text = SortTextForYear(year) + " "; + break; - case GroupBy_Composer: - case GroupBy_Performer: - case GroupBy_Grouping: - case GroupBy_Genre: - case GroupBy_Album: - case GroupBy_AlbumArtist: - item->key = row.value(0).toString(); - item->display_text = TextOrUnknown(item->key); - item->sort_text = SortTextForArtist(item->key); - break; + case GroupBy_Composer: + case GroupBy_Performer: + case GroupBy_Grouping: + case GroupBy_Genre: + case GroupBy_Album: + case GroupBy_AlbumArtist: + item->key = row.value(0).toString(); + item->display_text = TextOrUnknown(item->key); + item->sort_text = SortTextForArtist(item->key); + break; - case GroupBy_FileType: - item->metadata.set_filetype(Song::FileType(row.value(0).toInt())); - item->key = item->metadata.TextForFiletype(); - break; + case GroupBy_FileType: + item->metadata.set_filetype(Song::FileType(row.value(0).toInt())); + item->key = item->metadata.TextForFiletype(); + break; - case GroupBy_Bitrate: - bitrate = qMax(0, row.value(0).toInt()); - item->key = QString::number(bitrate); - item->sort_text = SortTextForBitrate(bitrate) + " "; - break; + case GroupBy_Bitrate: + bitrate = qMax(0, row.value(0).toInt()); + item->key = QString::number(bitrate); + item->sort_text = SortTextForBitrate(bitrate) + " "; + break; - case GroupBy_None: - item->metadata.InitFromQuery(row, true); - item->key = item->metadata.title(); - item->display_text = item->metadata.TitleWithCompilationArtist(); - item->sort_text = SortTextForSong(item->metadata); - break; + case GroupBy_None: + item->metadata.InitFromQuery(row, true); + item->key = item->metadata.title(); + item->display_text = item->metadata.TitleWithCompilationArtist(); + item->sort_text = SortTextForSong(item->metadata); + break; } FinishItem(type, signal, create_divider, parent, item); return item; } -LibraryItem* LibraryModel::ItemFromSong(GroupBy type, - bool signal, bool create_divider, - LibraryItem* parent, const Song& s, - int container_level) { +LibraryItem* LibraryModel::ItemFromSong(GroupBy type, bool signal, + bool create_divider, + LibraryItem* parent, const Song& s, + int container_level) { LibraryItem* item = InitItem(type, signal, parent, container_level); int year = 0; int bitrate = 0; switch (type) { - case GroupBy_Artist: - item->key = s.artist(); - item->display_text = TextOrUnknown(item->key); - item->sort_text = SortTextForArtist(item->key); - break; + case GroupBy_Artist: + item->key = s.artist(); + item->display_text = TextOrUnknown(item->key); + item->sort_text = SortTextForArtist(item->key); + break; - case GroupBy_YearAlbum: - year = qMax(0, s.year()); - item->metadata.set_year(year); - item->metadata.set_album(s.album()); - item->key = PrettyYearAlbum(year, s.album()); - item->sort_text = SortTextForYear(year) + s.album(); - break; + case GroupBy_YearAlbum: + year = qMax(0, s.year()); + item->metadata.set_year(year); + item->metadata.set_album(s.album()); + item->key = PrettyYearAlbum(year, s.album()); + item->sort_text = SortTextForYear(year) + s.album(); + break; - case GroupBy_Year: - year = qMax(0, s.year()); - item->key = QString::number(year); - item->sort_text = SortTextForYear(year) + " "; - break; + case GroupBy_Year: + year = qMax(0, s.year()); + item->key = QString::number(year); + item->sort_text = SortTextForYear(year) + " "; + break; - case GroupBy_Composer: item->key = s.composer(); - case GroupBy_Performer: item->key = s.performer(); - case GroupBy_Grouping: item->key = s.grouping(); - case GroupBy_Genre: if (item->key.isNull()) item->key = s.genre(); - case GroupBy_Album: if (item->key.isNull()) item->key = s.album(); - case GroupBy_AlbumArtist: if (item->key.isNull()) item->key = s.effective_albumartist(); - item->display_text = TextOrUnknown(item->key); - item->sort_text = SortTextForArtist(item->key); - break; + case GroupBy_Composer: + item->key = s.composer(); + case GroupBy_Performer: + item->key = s.performer(); + case GroupBy_Grouping: + item->key = s.grouping(); + case GroupBy_Genre: + if (item->key.isNull()) item->key = s.genre(); + case GroupBy_Album: + if (item->key.isNull()) item->key = s.album(); + case GroupBy_AlbumArtist: + if (item->key.isNull()) item->key = s.effective_albumartist(); + item->display_text = TextOrUnknown(item->key); + item->sort_text = SortTextForArtist(item->key); + break; - case GroupBy_FileType: - item->metadata.set_filetype(s.filetype()); - item->key = s.TextForFiletype(); - break; + case GroupBy_FileType: + item->metadata.set_filetype(s.filetype()); + item->key = s.TextForFiletype(); + break; - case GroupBy_Bitrate: - bitrate = qMax(0, s.bitrate()); - item->key = QString::number(bitrate); - item->sort_text = SortTextForBitrate(bitrate) + " "; - break; + case GroupBy_Bitrate: + bitrate = qMax(0, s.bitrate()); + item->key = QString::number(bitrate); + item->sort_text = SortTextForBitrate(bitrate) + " "; + break; - case GroupBy_None: - item->metadata = s; - item->key = s.title(); - item->display_text = s.TitleWithCompilationArtist(); - item->sort_text = SortTextForSong(s); - break; + case GroupBy_None: + item->metadata = s; + item->key = s.title(); + item->display_text = s.TitleWithCompilationArtist(); + item->sort_text = SortTextForSong(s); + break; } FinishItem(type, signal, create_divider, parent, item); - if (s.url().scheme() == "cdda") - item->lazy_loaded = true; + if (s.url().scheme() == "cdda") item->lazy_loaded = true; return item; } -void LibraryModel::FinishItem(GroupBy type, - bool signal, bool create_divider, - LibraryItem *parent, LibraryItem *item) { - if (type == GroupBy_None) - item->lazy_loaded = true; +void LibraryModel::FinishItem(GroupBy type, bool signal, bool create_divider, + LibraryItem* parent, LibraryItem* item) { + if (type == GroupBy_None) item->lazy_loaded = true; - if (signal) - endInsertRows(); + if (signal) endInsertRows(); // Create the divider entry if we're supposed to if (create_divider && show_dividers_) { @@ -984,16 +997,14 @@ void LibraryModel::FinishItem(GroupBy type, beginInsertRows(ItemToIndex(parent), parent->children.count(), parent->children.count()); - LibraryItem* divider = - new LibraryItem(LibraryItem::Type_Divider, root_); + LibraryItem* divider = new LibraryItem(LibraryItem::Type_Divider, root_); divider->key = divider_key; divider->display_text = DividerDisplayText(type, divider_key); divider->lazy_loaded = true; divider_nodes_[divider_key] = divider; - if (signal) - endInsertRows(); + if (signal) endInsertRows(); } } } @@ -1006,8 +1017,7 @@ QString LibraryModel::TextOrUnknown(const QString& text) { } QString LibraryModel::PrettyYearAlbum(int year, const QString& album) { - if (year <= 0) - return TextOrUnknown(album); + if (year <= 0) return TextOrUnknown(album); return QString::number(year) + " - " + TextOrUnknown(album); } @@ -1042,9 +1052,9 @@ QString LibraryModel::SortTextForBitrate(int bitrate) { return QString("0").repeated(qMax(0, 3 - str.length())) + str; } - QString LibraryModel::SortTextForSong(const Song& song) { - QString ret = QString::number(qMax(0, song.disc()) * 1000 + qMax(0, song.track())); + QString ret = + QString::number(qMax(0, song.disc()) * 1000 + qMax(0, song.track())); ret.prepend(QString("0").repeated(6 - ret.length())); ret.append(song.url().toString()); return ret; @@ -1052,17 +1062,15 @@ QString LibraryModel::SortTextForSong(const Song& song) { Qt::ItemFlags LibraryModel::flags(const QModelIndex& index) const { switch (IndexToItem(index)->type) { - case LibraryItem::Type_Song: - case LibraryItem::Type_Container: - case LibraryItem::Type_SmartPlaylist: - return Qt::ItemIsSelectable | - Qt::ItemIsEnabled | - Qt::ItemIsDragEnabled; - case LibraryItem::Type_Divider: - case LibraryItem::Type_Root: - case LibraryItem::Type_LoadingIndicator: - default: - return Qt::ItemIsEnabled; + case LibraryItem::Type_Song: + case LibraryItem::Type_Container: + case LibraryItem::Type_SmartPlaylist: + return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled; + case LibraryItem::Type_Divider: + case LibraryItem::Type_Root: + case LibraryItem::Type_LoadingIndicator: + default: + return Qt::ItemIsEnabled; } } @@ -1071,14 +1079,12 @@ QStringList LibraryModel::mimeTypes() const { } QMimeData* LibraryModel::mimeData(const QModelIndexList& indexes) const { - if (indexes.isEmpty()) - return nullptr; + if (indexes.isEmpty()) return nullptr; // Special case: a smart playlist was dragged if (IndexToItem(indexes.first())->type == LibraryItem::Type_SmartPlaylist) { GeneratorPtr generator = CreateGenerator(indexes.first()); - if (!generator) - return nullptr; + if (!generator) return nullptr; GeneratorMimeData* data = new GeneratorMimeData(generator); data->setData(kSmartPlaylistsMimeType, QByteArray()); @@ -1091,38 +1097,39 @@ QMimeData* LibraryModel::mimeData(const QModelIndexList& indexes) const { QSet song_ids; data->backend = backend_; - - foreach (const QModelIndex& index, indexes) { + + foreach(const QModelIndex & index, indexes) { GetChildSongs(IndexToItem(index), &urls, &data->songs, &song_ids); } data->setUrls(urls); - data->name_for_new_playlist_ = PlaylistManager::GetNameForNewPlaylist(data->songs); + data->name_for_new_playlist_ = + PlaylistManager::GetNameForNewPlaylist(data->songs); return data; } -bool LibraryModel::CompareItems(const LibraryItem* a, const LibraryItem* b) const { +bool LibraryModel::CompareItems(const LibraryItem* a, + const LibraryItem* b) const { QVariant left(data(a, LibraryModel::Role_SortText)); QVariant right(data(b, LibraryModel::Role_SortText)); - if (left.type() == QVariant::Int) - return left.toInt() < right.toInt(); + if (left.type() == QVariant::Int) return left.toInt() < right.toInt(); return left.toString() < right.toString(); } void LibraryModel::GetChildSongs(LibraryItem* item, QList* urls, - SongList* songs, QSet* song_ids) const { + SongList* songs, QSet* song_ids) const { switch (item->type) { case LibraryItem::Type_Container: { const_cast(this)->LazyPopulate(item); QList children = item->children; - qSort(children.begin(), children.end(), std::bind( - &LibraryModel::CompareItems, this, _1, _2)); + qSort(children.begin(), children.end(), + std::bind(&LibraryModel::CompareItems, this, _1, _2)); - foreach (LibraryItem* child, children) - GetChildSongs(child, urls, songs, song_ids); + foreach(LibraryItem * child, children) + GetChildSongs(child, urls, songs, song_ids); break; } @@ -1144,13 +1151,13 @@ SongList LibraryModel::GetChildSongs(const QModelIndexList& indexes) const { SongList ret; QSet song_ids; - foreach (const QModelIndex& index, indexes) { + foreach(const QModelIndex & index, indexes) { GetChildSongs(IndexToItem(index), &dontcare, &ret, &song_ids); } return ret; } -SongList LibraryModel::GetChildSongs(const QModelIndex &index) const { +SongList LibraryModel::GetChildSongs(const QModelIndex& index) const { return GetChildSongs(QModelIndexList() << index); } @@ -1169,9 +1176,8 @@ void LibraryModel::SetFilterQueryMode(QueryOptions::QueryMode query_mode) { ResetAsync(); } -bool LibraryModel::canFetchMore(const QModelIndex &parent) const { - if (!parent.isValid()) - return false; +bool LibraryModel::canFetchMore(const QModelIndex& parent) const { + if (!parent.isValid()) return false; LibraryItem* item = IndexToItem(parent); return !item->lazy_loaded; @@ -1184,28 +1190,35 @@ void LibraryModel::SetGroupBy(const Grouping& g) { emit GroupingChanged(g); } -const LibraryModel::GroupBy& LibraryModel::Grouping::operator [](int i) const { +const LibraryModel::GroupBy& LibraryModel::Grouping::operator[](int i) const { switch (i) { - case 0: return first; - case 1: return second; - case 2: return third; + case 0: + return first; + case 1: + return second; + case 2: + return third; } qLog(Error) << "LibraryModel::Grouping[] index out of range" << i; return first; } -LibraryModel::GroupBy& LibraryModel::Grouping::operator [](int i) { +LibraryModel::GroupBy& LibraryModel::Grouping::operator[](int i) { switch (i) { - case 0: return first; - case 1: return second; - case 2: return third; + case 0: + return first; + case 1: + return second; + case 2: + return third; } qLog(Error) << "LibraryModel::Grouping[] index out of range" << i; return first; } void LibraryModel::CreateSmartPlaylists() { - smart_playlist_node_ = new LibraryItem(LibraryItem::Type_PlaylistContainer, root_); + smart_playlist_node_ = + new LibraryItem(LibraryItem::Type_PlaylistContainer, root_); smart_playlist_node_->container_level = 0; smart_playlist_node_->sort_text = "\0"; smart_playlist_node_->key = tr("Smart playlists"); @@ -1217,7 +1230,7 @@ void LibraryModel::CreateSmartPlaylists() { // How many defaults do we have to write? int unwritten_defaults = 0; - for (int i=version; i < default_smart_playlists_.count() ; ++i) { + for (int i = version; i < default_smart_playlists_.count(); ++i) { unwritten_defaults += default_smart_playlists_[i].count(); } @@ -1228,9 +1241,11 @@ void LibraryModel::CreateSmartPlaylists() { s.endArray(); // Append the new ones - s.beginWriteArray(backend_->songs_table(), playlist_index + unwritten_defaults); - for (; version < default_smart_playlists_.count() ; ++version) { - foreach (smart_playlists::GeneratorPtr gen, default_smart_playlists_[version]) { + s.beginWriteArray(backend_->songs_table(), + playlist_index + unwritten_defaults); + for (; version < default_smart_playlists_.count(); ++version) { + foreach(smart_playlists::GeneratorPtr gen, + default_smart_playlists_[version]) { SaveGenerator(&s, playlist_index++, gen); } } @@ -1240,13 +1255,14 @@ void LibraryModel::CreateSmartPlaylists() { s.setValue(backend_->songs_table() + "_version", version); const int count = s.beginReadArray(backend_->songs_table()); - for (int i=0 ; idisplay_text = tr(qPrintable(s.value("name").toString())); @@ -1255,8 +1271,7 @@ void LibraryModel::ItemFromSmartPlaylist(const QSettings& s, bool notify) const item->smart_playlist_data = s.value("data").toByteArray(); item->lazy_loaded = true; - if (notify) - item->InsertNotify(smart_playlist_node_); + if (notify) item->InsertNotify(smart_playlist_node_); } void LibraryModel::AddGenerator(GeneratorPtr gen) { @@ -1278,11 +1293,9 @@ void LibraryModel::AddGenerator(GeneratorPtr gen) { } void LibraryModel::UpdateGenerator(const QModelIndex& index, GeneratorPtr gen) { - if (index.parent() != ItemToIndex(smart_playlist_node_)) - return; + if (index.parent() != ItemToIndex(smart_playlist_node_)) return; LibraryItem* item = IndexToItem(index); - if (!item) - return; + if (!item) return; // Update the config QSettings s; @@ -1304,8 +1317,7 @@ void LibraryModel::UpdateGenerator(const QModelIndex& index, GeneratorPtr gen) { } void LibraryModel::DeleteGenerator(const QModelIndex& index) { - if (index.parent() != ItemToIndex(smart_playlist_node_)) - return; + if (index.parent() != ItemToIndex(smart_playlist_node_)) return; // Remove the item from the tree smart_playlist_node_->DeleteNotify(index.row()); @@ -1314,9 +1326,10 @@ void LibraryModel::DeleteGenerator(const QModelIndex& index) { s.beginGroup(kSmartPlaylistsSettingsGroup); // Rewrite all the items to the settings - s.beginWriteArray(backend_->songs_table(), smart_playlist_node_->children.count()); + s.beginWriteArray(backend_->songs_table(), + smart_playlist_node_->children.count()); int i = 0; - foreach (LibraryItem* item, smart_playlist_node_->children) { + foreach(LibraryItem * item, smart_playlist_node_->children) { s.setArrayIndex(i++); s.setValue("name", item->display_text); s.setValue("type", item->key); @@ -1325,7 +1338,8 @@ void LibraryModel::DeleteGenerator(const QModelIndex& index) { s.endArray(); } -void LibraryModel::SaveGenerator(QSettings* s, int i, GeneratorPtr generator) const { +void LibraryModel::SaveGenerator(QSettings* s, int i, + GeneratorPtr generator) const { s->setArrayIndex(i); s->setValue("name", generator->name()); s->setValue("type", generator->type()); @@ -1336,12 +1350,10 @@ GeneratorPtr LibraryModel::CreateGenerator(const QModelIndex& index) const { GeneratorPtr ret; const LibraryItem* item = IndexToItem(index); - if (!item || item->type != LibraryItem::Type_SmartPlaylist) - return ret; + if (!item || item->type != LibraryItem::Type_SmartPlaylist) return ret; ret = Generator::Create(item->key); - if (!ret) - return ret; + if (!ret) return ret; ret->set_name(item->display_text); ret->set_library(backend()); @@ -1353,5 +1365,3 @@ void LibraryModel::TotalSongCountUpdatedSlot(int count) { total_song_count_ = count; emit TotalSongCountUpdated(count); } - - diff --git a/src/library/librarymodel.h b/src/library/librarymodel.h index efd2812e1..ee41ed002 100644 --- a/src/library/librarymodel.h +++ b/src/library/librarymodel.h @@ -36,7 +36,9 @@ class Application; class AlbumCoverLoader; class LibraryDirectoryModel; class LibraryBackend; -namespace smart_playlists { class Search; } +namespace smart_playlists { +class Search; +} class QSettings; @@ -45,8 +47,7 @@ class LibraryModel : public SimpleTreeModel { Q_ENUMS(GroupBy); public: - LibraryModel(LibraryBackend* backend, Application* app, - QObject* parent = 0); + LibraryModel(LibraryBackend* backend, Application* app, QObject* parent = 0); ~LibraryModel(); static const char* kSmartPlaylistsMimeType; @@ -63,7 +64,6 @@ class LibraryModel : public SimpleTreeModel { Role_Artist, Role_IsDivider, Role_Editable, - LastRole }; @@ -84,25 +84,21 @@ class LibraryModel : public SimpleTreeModel { }; struct Grouping { - Grouping(GroupBy f = GroupBy_None, - GroupBy s = GroupBy_None, + Grouping(GroupBy f = GroupBy_None, GroupBy s = GroupBy_None, GroupBy t = GroupBy_None) - : first(f), second(s), third(t) {} + : first(f), second(s), third(t) {} GroupBy first; GroupBy second; GroupBy third; - const GroupBy& operator [](int i) const; - GroupBy& operator [](int i); - bool operator ==(const Grouping& other) const { - return first == other.first && - second == other.second && + const GroupBy& operator[](int i) const; + GroupBy& operator[](int i); + bool operator==(const Grouping& other) const { + return first == other.first && second == other.second && third == other.third; } - bool operator !=(const Grouping& other) const { - return ! (*this == other); - } + bool operator!=(const Grouping& other) const { return !(*this == other); } }; struct QueryResult { @@ -119,9 +115,15 @@ class LibraryModel : public SimpleTreeModel { typedef QList DefaultGenerators; // Call before Init() - void set_show_smart_playlists(bool show_smart_playlists) { show_smart_playlists_ = show_smart_playlists; } - void set_default_smart_playlists(const DefaultGenerators& defaults) { default_smart_playlists_ = defaults; } - void set_show_various_artists(bool show_various_artists) { show_various_artists_ = show_various_artists; } + void set_show_smart_playlists(bool show_smart_playlists) { + show_smart_playlists_ = show_smart_playlists; + } + void set_default_smart_playlists(const DefaultGenerators& defaults) { + default_smart_playlists_ = defaults; + } + void set_show_various_artists(bool show_various_artists) { + show_various_artists_ = show_various_artists; + } // Get information about the library void GetChildSongs(LibraryItem* item, QList* urls, SongList* songs, @@ -135,15 +137,16 @@ class LibraryModel : public SimpleTreeModel { // Smart playlists smart_playlists::GeneratorPtr CreateGenerator(const QModelIndex& index) const; void AddGenerator(smart_playlists::GeneratorPtr gen); - void UpdateGenerator(const QModelIndex& index, smart_playlists::GeneratorPtr gen); + void UpdateGenerator(const QModelIndex& index, + smart_playlists::GeneratorPtr gen); void DeleteGenerator(const QModelIndex& index); // QAbstractItemModel - QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; Qt::ItemFlags flags(const QModelIndex& index) const; QStringList mimeTypes() const; QMimeData* mimeData(const QModelIndexList& indexes) const; - bool canFetchMore(const QModelIndex &parent) const; + bool canFetchMore(const QModelIndex& parent) const; // Whether or not to use album cover art, if it exists, in the library view void set_pretty_covers(bool use_pretty_covers); @@ -161,7 +164,7 @@ class LibraryModel : public SimpleTreeModel { static QString SortTextForBitrate(int bitrate); static QString SortTextForSong(const Song& song); - signals: +signals: void TotalSongCountUpdated(int count); void GroupingChanged(const LibraryModel::Grouping& g); @@ -224,7 +227,8 @@ class LibraryModel : public SimpleTreeModel { // Smart playlists are shown in another top-level node void CreateSmartPlaylists(); - void SaveGenerator(QSettings* s, int i, smart_playlists::GeneratorPtr generator) const; + void SaveGenerator(QSettings* s, int i, + smart_playlists::GeneratorPtr generator) const; void ItemFromSmartPlaylist(const QSettings& s, bool notify) const; // Helpers for ItemFromQuery and ItemFromSong @@ -276,7 +280,7 @@ class LibraryModel : public SimpleTreeModel { QIcon playlist_icon_; int init_task_id_; - + bool use_pretty_covers_; bool show_dividers_; @@ -289,4 +293,4 @@ class LibraryModel : public SimpleTreeModel { Q_DECLARE_METATYPE(LibraryModel::Grouping); -#endif // LIBRARYMODEL_H +#endif // LIBRARYMODEL_H diff --git a/src/library/libraryplaylistitem.cpp b/src/library/libraryplaylistitem.cpp index 625565c81..d05e21d0b 100644 --- a/src/library/libraryplaylistitem.cpp +++ b/src/library/libraryplaylistitem.cpp @@ -21,23 +21,16 @@ #include LibraryPlaylistItem::LibraryPlaylistItem(const QString& type) - : PlaylistItem(type) -{ -} + : PlaylistItem(type) {} LibraryPlaylistItem::LibraryPlaylistItem(const Song& song) - : PlaylistItem("Library"), - song_(song) -{ -} + : PlaylistItem("Library"), song_(song) {} - -QUrl LibraryPlaylistItem::Url() const { - return song_.url(); -} +QUrl LibraryPlaylistItem::Url() const { return song_.url(); } void LibraryPlaylistItem::Reload() { - TagReaderClient::Instance()->ReadFileBlocking(song_.url().toLocalFile(), &song_); + TagReaderClient::Instance()->ReadFileBlocking(song_.url().toLocalFile(), + &song_); } bool LibraryPlaylistItem::InitFromQuery(const SqlRow& query) { @@ -49,13 +42,14 @@ bool LibraryPlaylistItem::InitFromQuery(const SqlRow& query) { QVariant LibraryPlaylistItem::DatabaseValue(DatabaseColumn column) const { switch (column) { - case Column_LibraryId: return song_.id(); - default: return PlaylistItem::DatabaseValue(column); + case Column_LibraryId: + return song_.id(); + default: + return PlaylistItem::DatabaseValue(column); } } Song LibraryPlaylistItem::Metadata() const { - if (HasTemporaryMetadata()) - return temp_metadata_; + if (HasTemporaryMetadata()) return temp_metadata_; return song_; } diff --git a/src/library/libraryplaylistitem.h b/src/library/libraryplaylistitem.h index 1dbc49cc0..dbfd08850 100644 --- a/src/library/libraryplaylistitem.h +++ b/src/library/libraryplaylistitem.h @@ -43,4 +43,4 @@ class LibraryPlaylistItem : public PlaylistItem { Song song_; }; -#endif // LIBRARYPLAYLISTITEM_H +#endif // LIBRARYPLAYLISTITEM_H diff --git a/src/library/libraryquery.cpp b/src/library/libraryquery.cpp index f0ed6f424..ec7f0e5ad 100644 --- a/src/library/libraryquery.cpp +++ b/src/library/libraryquery.cpp @@ -22,18 +22,10 @@ #include #include -QueryOptions::QueryOptions() - : max_age_(-1), - query_mode_(QueryMode_All) -{ -} - +QueryOptions::QueryOptions() : max_age_(-1), query_mode_(QueryMode_All) {} LibraryQuery::LibraryQuery(const QueryOptions& options) - : include_unavailable_(false), - join_with_fts_(false), - limit_(-1) -{ + : include_unavailable_(false), join_with_fts_(false), limit_(-1) { if (!options.filter().isEmpty()) { // We need to munge the filter text a little bit to get it to work as // expected with sqlite's FTS3: @@ -42,10 +34,10 @@ LibraryQuery::LibraryQuery(const QueryOptions& options) // 3) Remove colons which don't correspond to column names. // Split on whitespace - QStringList tokens(options.filter().split( - QRegExp("\\s+"), QString::SkipEmptyParts)); + QStringList tokens( + options.filter().split(QRegExp("\\s+"), QString::SkipEmptyParts)); QString query; - foreach (QString token, tokens) { + foreach(QString token, tokens) { token.remove('('); token.remove(')'); token.remove('"'); @@ -56,8 +48,8 @@ LibraryQuery::LibraryQuery(const QueryOptions& options) if (Song::kFtsColumns.contains("fts" + token.section(':', 0, 0), Qt::CaseInsensitive)) { // Account for multiple colons. - QString columntoken = token.section( - ':', 0, 0, QString::SectionIncludeTrailingSep); + QString columntoken = + token.section(':', 0, 0, QString::SectionIncludeTrailingSep); QString subtoken = token.section(':', 1, -1); subtoken.replace(":", " "); subtoken = subtoken.trimmed(); @@ -84,12 +76,16 @@ LibraryQuery::LibraryQuery(const QueryOptions& options) bound_values_ << cutoff; } - // TODO: currently you cannot use any QueryMode other than All and fts at the same time. - // joining songs, duplicated_songs and songs_fts all together takes a huge amount of + // TODO: currently you cannot use any QueryMode other than All and fts at the + // same time. + // joining songs, duplicated_songs and songs_fts all together takes a huge + // amount of // time. the query takes about 20 seconds on my machine then. why? - // untagged mode could work with additional filtering but I'm disabling it just to be + // untagged mode could work with additional filtering but I'm disabling it + // just to be // consistent - this way filtering is available only in the All mode. - // remember though that when you fix the Duplicates + FTS cooperation, enable the + // remember though that when you fix the Duplicates + FTS cooperation, enable + // the // filtering in both Duplicates and Untagged modes. duplicates_only_ = options.query_mode() == QueryOptions::QueryMode_Duplicates; @@ -100,19 +96,20 @@ LibraryQuery::LibraryQuery(const QueryOptions& options) QString LibraryQuery::GetInnerQuery() { return duplicates_only_ - ? QString(" INNER JOIN (select * from duplicated_songs) dsongs " - "ON (%songs_table.artist = dsongs.dup_artist " - "AND %songs_table.album = dsongs.dup_album " - "AND %songs_table.title = dsongs.dup_title) ") + ? QString( + " INNER JOIN (select * from duplicated_songs) dsongs " + "ON (%songs_table.artist = dsongs.dup_artist " + "AND %songs_table.album = dsongs.dup_album " + "AND %songs_table.title = dsongs.dup_title) ") : QString(); } void LibraryQuery::AddWhere(const QString& column, const QVariant& value, const QString& op) { // ignore 'literal' for IN - if(!op.compare("IN", Qt::CaseInsensitive)) { + if (!op.compare("IN", Qt::CaseInsensitive)) { QStringList final; - foreach(const QString& single_value, value.toStringList()) { + foreach(const QString & single_value, value.toStringList()) { final.append("?"); bound_values_ << single_value; } @@ -121,7 +118,7 @@ void LibraryQuery::AddWhere(const QString& column, const QVariant& value, } else { // Do integers inline - sqlite seems to get confused when you pass integers // to bound parameters - if(value.type() == QVariant::Int) { + if (value.type() == QVariant::Int) { where_clauses_ << QString("%1 %2 %3").arg(column, op, value.toString()); } else { where_clauses_ << QString("%1 %2 ?").arg(column, op); @@ -131,7 +128,8 @@ void LibraryQuery::AddWhere(const QString& column, const QVariant& value, } void LibraryQuery::AddCompilationRequirement(bool compilation) { - where_clauses_ << QString("effective_compilation = %1").arg(compilation ? 1 : 0); + where_clauses_ << QString("effective_compilation = %1") + .arg(compilation ? 1 : 0); } QSqlQuery LibraryQuery::Exec(QSqlDatabase db, const QString& songs_table, @@ -139,11 +137,12 @@ QSqlQuery LibraryQuery::Exec(QSqlDatabase db, const QString& songs_table, QString sql; if (join_with_fts_) { - sql = QString("SELECT %1 FROM %2 INNER JOIN %3 AS fts ON %2.ROWID = fts.ROWID") - .arg(column_spec_, songs_table, fts_table); + sql = QString( + "SELECT %1 FROM %2 INNER JOIN %3 AS fts ON %2.ROWID = fts.ROWID") + .arg(column_spec_, songs_table, fts_table); } else { sql = QString("SELECT %1 FROM %2 %3") - .arg(column_spec_, songs_table, GetInnerQuery()); + .arg(column_spec_, songs_table, GetInnerQuery()); } QStringList where_clauses(where_clauses_); @@ -151,14 +150,11 @@ QSqlQuery LibraryQuery::Exec(QSqlDatabase db, const QString& songs_table, where_clauses << "unavailable = 0"; } - if (!where_clauses.isEmpty()) - sql += " WHERE " + where_clauses.join(" AND "); + if (!where_clauses.isEmpty()) sql += " WHERE " + where_clauses.join(" AND "); - if (!order_by_.isEmpty()) - sql += " ORDER BY " + order_by_; + if (!order_by_.isEmpty()) sql += " ORDER BY " + order_by_; - if (limit_ != -1) - sql += " LIMIT " + QString::number(limit_); + if (limit_ != -1) sql += " LIMIT " + QString::number(limit_); sql.replace("%songs_table", songs_table); sql.replace("%fts_table_noprefix", fts_table.section('.', -1, -1)); @@ -167,27 +163,20 @@ QSqlQuery LibraryQuery::Exec(QSqlDatabase db, const QString& songs_table, query_ = QSqlQuery(sql, db); // Bind values - foreach (const QVariant& value, bound_values_) { - query_.addBindValue(value); - } + foreach(const QVariant & value, bound_values_) { query_.addBindValue(value); } query_.exec(); return query_; } -bool LibraryQuery::Next() { - return query_.next(); -} +bool LibraryQuery::Next() { return query_.next(); } -QVariant LibraryQuery::Value(int column) const { - return query_.value(column); -} +QVariant LibraryQuery::Value(int column) const { return query_.value(column); } bool QueryOptions::Matches(const Song& song) const { if (max_age_ != -1) { const uint cutoff = QDateTime::currentDateTime().toTime_t() - max_age_; - if (song.ctime() <= cutoff) - return false; + if (song.ctime() <= cutoff) return false; } if (!filter_.isNull()) { diff --git a/src/library/libraryquery.h b/src/library/libraryquery.h index d129f9311..c20b71a43 100644 --- a/src/library/libraryquery.h +++ b/src/library/libraryquery.h @@ -31,18 +31,14 @@ class LibraryBackend; struct QueryOptions { // Modes of LibraryQuery: // - use the all songs table - // - use the duplicated songs view; by duplicated we mean those songs - // for which the (artist, album, title) tuple is found more than once + // - use the duplicated songs view; by duplicated we mean those songs + // for which the (artist, album, title) tuple is found more than once // in the songs table // - use the untagged songs view; by untagged we mean those for which // at least one of the (artist, album, title) tags is empty // Please note that additional filtering based on fts table (the filter // attribute) won't work in Duplicates and Untagged modes. - enum QueryMode { - QueryMode_All, - QueryMode_Duplicates, - QueryMode_Untagged - }; + enum QueryMode { QueryMode_All, QueryMode_Duplicates, QueryMode_Untagged }; QueryOptions(); @@ -81,17 +77,21 @@ class LibraryQuery { // Adds a fragment of WHERE clause. When executed, this Query will connect all // the fragments with AND operator. // Please note that IN operator expects a QStringList as value. - void AddWhere(const QString& column, const QVariant& value, const QString& op = "="); + void AddWhere(const QString& column, const QVariant& value, + const QString& op = "="); void AddCompilationRequirement(bool compilation); void SetLimit(int limit) { limit_ = limit; } - void SetIncludeUnavailable(bool include_unavailable) { include_unavailable_ = include_unavailable; } + void SetIncludeUnavailable(bool include_unavailable) { + include_unavailable_ = include_unavailable; + } - QSqlQuery Exec(QSqlDatabase db, const QString& songs_table, const QString& fts_table); + QSqlQuery Exec(QSqlDatabase db, const QString& songs_table, + const QString& fts_table); bool Next(); QVariant Value(int column) const; - operator const QSqlQuery& () const { return query_; } + operator const QSqlQuery&() const { return query_; } private: QString GetInnerQuery(); @@ -108,4 +108,4 @@ class LibraryQuery { QSqlQuery query_; }; -#endif // LIBRARYQUERY_H +#endif // LIBRARYQUERY_H diff --git a/src/library/librarysettingspage.cpp b/src/library/librarysettingspage.cpp index d74ffa499..bafc00c78 100644 --- a/src/library/librarysettingspage.cpp +++ b/src/library/librarysettingspage.cpp @@ -37,12 +37,10 @@ const char* LibrarySettingsPage::kSettingsGroup = "LibraryConfig"; - LibrarySettingsPage::LibrarySettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_LibrarySettingsPage), - initialised_model_(false) -{ + : SettingsPage(dialog), + ui_(new Ui_LibrarySettingsPage), + initialised_model_(false) { ui_->setupUi(this); ui_->list->setItemDelegate(new NativeSeparatorsDelegate(this)); @@ -52,19 +50,20 @@ LibrarySettingsPage::LibrarySettingsPage(SettingsDialog* dialog) connect(ui_->add, SIGNAL(clicked()), SLOT(Add())); connect(ui_->remove, SIGNAL(clicked()), SLOT(Remove())); - connect(ui_->sync_stats_button, SIGNAL(clicked()), SLOT(WriteAllSongsStatisticsToFiles())); + connect(ui_->sync_stats_button, SIGNAL(clicked()), + SLOT(WriteAllSongsStatisticsToFiles())); } -LibrarySettingsPage::~LibrarySettingsPage() { - delete ui_; -} +LibrarySettingsPage::~LibrarySettingsPage() { delete ui_; } void LibrarySettingsPage::Add() { QSettings settings; settings.beginGroup(kSettingsGroup); - QString path(settings.value("last_path", - Utilities::GetConfigPath(Utilities::Path_DefaultMusicLibrary)).toString()); + QString path( + settings.value("last_path", Utilities::GetConfigPath( + Utilities::Path_DefaultMusicLibrary)) + .toString()); path = QFileDialog::getExistingDirectory(this, tr("Add directory..."), path); if (!path.isNull()) { @@ -75,7 +74,8 @@ void LibrarySettingsPage::Add() { } void LibrarySettingsPage::Remove() { - dialog()->library_directory_model()->RemoveDirectory(ui_->list->currentIndex()); + dialog()->library_directory_model()->RemoveDirectory( + ui_->list->currentIndex()); } void LibrarySettingsPage::CurrentRowChanged(const QModelIndex& index) { @@ -93,16 +93,17 @@ void LibrarySettingsPage::Save() { s.beginGroup(LibraryWatcher::kSettingsGroup); s.setValue("startup_scan", ui_->startup_scan->isChecked()); s.setValue("monitor", ui_->monitor->isChecked()); - + QString filter_text = ui_->cover_art_patterns->text(); QStringList filters = filter_text.split(',', QString::SkipEmptyParts); s.setValue("cover_art_patterns", filters); - + s.endGroup(); s.beginGroup(LibraryBackend::kSettingsGroup); s.setValue("save_ratings_in_file", ui_->save_ratings_in_file->isChecked()); - s.setValue("save_statistics_in_file", ui_->save_statistics_in_file->isChecked()); + s.setValue("save_statistics_in_file", + ui_->save_statistics_in_file->isChecked()); s.endGroup(); } @@ -110,8 +111,8 @@ void LibrarySettingsPage::Load() { if (!initialised_model_) { if (ui_->list->selectionModel()) { disconnect(ui_->list->selectionModel(), - SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), - this, SLOT(CurrentRowChanged(QModelIndex))); + SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, + SLOT(CurrentRowChanged(QModelIndex))); } ui_->list->setModel(dialog()->library_directory_model()); @@ -132,27 +133,31 @@ void LibrarySettingsPage::Load() { s.beginGroup(LibraryWatcher::kSettingsGroup); ui_->startup_scan->setChecked(s.value("startup_scan", true).toBool()); ui_->monitor->setChecked(s.value("monitor", true).toBool()); - - QStringList filters = s.value("cover_art_patterns", - QStringList() << "front" << "cover").toStringList(); + + QStringList filters = + s.value("cover_art_patterns", QStringList() << "front" + << "cover").toStringList(); ui_->cover_art_patterns->setText(filters.join(",")); - + s.endGroup(); s.beginGroup(LibraryBackend::kSettingsGroup); - ui_->save_ratings_in_file->setChecked(s.value("save_ratings_in_file", false).toBool()); - ui_->save_statistics_in_file->setChecked(s.value("save_statistics_in_file", false).toBool()); + ui_->save_ratings_in_file->setChecked( + s.value("save_ratings_in_file", false).toBool()); + ui_->save_statistics_in_file->setChecked( + s.value("save_statistics_in_file", false).toBool()); s.endGroup(); } void LibrarySettingsPage::WriteAllSongsStatisticsToFiles() { QMessageBox confirmation_dialog( - QMessageBox::Question, - tr("Write all songs statistics into songs' files"), - tr("Are you sure you want to write song's statistics into song's file for all the songs of your library?"), + QMessageBox::Question, tr("Write all songs statistics into songs' files"), + tr("Are you sure you want to write song's statistics into song's file " + "for all the songs of your library?"), QMessageBox::Yes | QMessageBox::Cancel); if (confirmation_dialog.exec() != QMessageBox::Yes) { return; } - QtConcurrent::run(dialog()->app()->library(), &Library::WriteAllSongsStatisticsToFiles); + QtConcurrent::run(dialog()->app()->library(), + &Library::WriteAllSongsStatisticsToFiles); } diff --git a/src/library/librarysettingspage.h b/src/library/librarysettingspage.h index d0924e2a0..ad8398ffa 100644 --- a/src/library/librarysettingspage.h +++ b/src/library/librarysettingspage.h @@ -28,7 +28,7 @@ class QModelIndex; class LibrarySettingsPage : public SettingsPage { Q_OBJECT -public: + public: LibrarySettingsPage(SettingsDialog* dialog); ~LibrarySettingsPage(); @@ -37,16 +37,16 @@ public: void Load(); void Save(); -private slots: + private slots: void Add(); void Remove(); void WriteAllSongsStatisticsToFiles(); void CurrentRowChanged(const QModelIndex& index); -private: + private: Ui_LibrarySettingsPage* ui_; bool initialised_model_; }; -#endif // LIBRARYSETTINGSPAGE_H +#endif // LIBRARYSETTINGSPAGE_H diff --git a/src/library/libraryview.cpp b/src/library/libraryview.cpp index b4976463d..fe4cf2f41 100644 --- a/src/library/libraryview.cpp +++ b/src/library/libraryview.cpp @@ -50,12 +50,12 @@ using smart_playlists::Wizard; const char* LibraryView::kSettingsGroup = "LibraryView"; -LibraryItemDelegate::LibraryItemDelegate(QObject *parent) - : QStyledItemDelegate(parent) -{ -} +LibraryItemDelegate::LibraryItemDelegate(QObject* parent) + : QStyledItemDelegate(parent) {} -void LibraryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const { +void LibraryItemDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& opt, + const QModelIndex& index) const { const bool is_divider = index.data(LibraryModel::Role_IsDivider).toBool(); if (is_divider) { @@ -113,19 +113,17 @@ void LibraryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &o } } -bool LibraryItemDelegate::helpEvent(QHelpEvent *event, QAbstractItemView *view, - const QStyleOptionViewItem &option, - const QModelIndex &index) { +bool LibraryItemDelegate::helpEvent(QHelpEvent* event, QAbstractItemView* view, + const QStyleOptionViewItem& option, + const QModelIndex& index) { Q_UNUSED(option); - if (!event || !view) - return false; + if (!event || !view) return false; - QHelpEvent *he = static_cast(event); + QHelpEvent* he = static_cast(event); QString text = displayText(index.data(), QLocale::system()); - if (text.isEmpty() || !he) - return false; + if (text.isEmpty() || !he) return false; switch (event->type()) { case QEvent::ToolTip: { @@ -164,14 +162,13 @@ bool LibraryItemDelegate::helpEvent(QHelpEvent *event, QAbstractItemView *view, } LibraryView::LibraryView(QWidget* parent) - : AutoExpandingTreeView(parent), - app_(nullptr), - filter_(nullptr), - total_song_count_(-1), - nomusic_(":nomusic.png"), - context_menu_(nullptr), - is_in_keyboard_search_(false) -{ + : AutoExpandingTreeView(parent), + app_(nullptr), + filter_(nullptr), + total_song_count_(-1), + nomusic_(":nomusic.png"), + context_menu_(nullptr), + is_in_keyboard_search_(false) { setItemDelegate(new LibraryItemDelegate(this)); setAttribute(Qt::WA_MacShowFocusRect, false); setHeaderHidden(true); @@ -183,15 +180,14 @@ LibraryView::LibraryView(QWidget* parent) setStyleSheet("QTreeView::item{padding-top:1px;}"); } -LibraryView::~LibraryView() { -} +LibraryView::~LibraryView() {} void LibraryView::SaveFocus() { QModelIndex current = currentIndex(); QVariant type = model()->data(current, LibraryModel::Role_Type); if (!type.isValid() || !(type.toInt() == LibraryItem::Type_Song || - type.toInt() == LibraryItem::Type_Container || - type.toInt() == LibraryItem::Type_Divider)) { + type.toInt() == LibraryItem::Type_Container || + type.toInt() == LibraryItem::Type_Divider)) { return; } @@ -201,8 +197,8 @@ void LibraryView::SaveFocus() { switch (type.toInt()) { case LibraryItem::Type_Song: { - QModelIndex index = qobject_cast(model()) - ->mapToSource(current); + QModelIndex index = + qobject_cast(model())->mapToSource(current); SongList songs = app_->library_model()->GetChildSongs(index); if (!songs.isEmpty()) { last_selected_song_ = songs.last(); @@ -212,7 +208,8 @@ void LibraryView::SaveFocus() { case LibraryItem::Type_Container: case LibraryItem::Type_Divider: { - QString text = model()->data(current, LibraryModel::Role_SortText).toString(); + QString text = + model()->data(current, LibraryModel::Role_SortText).toString(); last_selected_container_ = text; break; } @@ -228,7 +225,7 @@ void LibraryView::SaveContainerPath(const QModelIndex& child) { QModelIndex current = model()->parent(child); QVariant type = model()->data(current, LibraryModel::Role_Type); if (!type.isValid() || !(type.toInt() == LibraryItem::Type_Container || - type.toInt() == LibraryItem::Type_Divider)) { + type.toInt() == LibraryItem::Type_Divider)) { return; } @@ -238,7 +235,8 @@ void LibraryView::SaveContainerPath(const QModelIndex& child) { } void LibraryView::RestoreFocus() { - if (last_selected_container_.isEmpty() && last_selected_song_.url().isEmpty()) { + if (last_selected_container_.isEmpty() && + last_selected_song_.url().isEmpty()) { return; } RestoreLevelFocus(); @@ -256,9 +254,9 @@ bool LibraryView::RestoreLevelFocus(const QModelIndex& parent) { case LibraryItem::Type_Song: if (!last_selected_song_.url().isEmpty()) { QModelIndex index = qobject_cast(model()) - ->mapToSource(current); + ->mapToSource(current); SongList songs = app_->library_model()->GetChildSongs(index); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { if (song == last_selected_song_) { setCurrentIndex(current); return true; @@ -269,14 +267,17 @@ bool LibraryView::RestoreLevelFocus(const QModelIndex& parent) { case LibraryItem::Type_Container: case LibraryItem::Type_Divider: { - QString text = model()->data(current, LibraryModel::Role_SortText).toString(); - if (!last_selected_container_.isEmpty() && last_selected_container_ == text) { + QString text = + model()->data(current, LibraryModel::Role_SortText).toString(); + if (!last_selected_container_.isEmpty() && + last_selected_container_ == text) { emit expand(current); setCurrentIndex(current); return true; } else if (last_selected_path_.contains(text)) { emit expand(current); - // If a selected container or song were not found, we've got into a wrong subtree + // If a selected container or song were not found, we've got into a + // wrong subtree // (happens with "unknown" all the time) if (!RestoreLevelFocus(current)) { emit collapse(current); @@ -297,8 +298,10 @@ void LibraryView::ReloadSettings() { SetAutoOpen(s.value("auto_open", true).toBool()); if (app_ != nullptr) { - app_->library_model()->set_pretty_covers(s.value("pretty_covers", true).toBool()); - app_->library_model()->set_show_dividers(s.value("show_dividers", true).toBool()); + app_->library_model()->set_pretty_covers( + s.value("pretty_covers", true).toBool()); + app_->library_model()->set_show_dividers( + s.value("show_dividers", true).toBool()); } } @@ -307,15 +310,12 @@ void LibraryView::SetApplication(Application* app) { ReloadSettings(); } -void LibraryView::SetFilter(LibraryFilterWidget* filter) { - filter_ = filter; -} +void LibraryView::SetFilter(LibraryFilterWidget* filter) { filter_ = filter; } void LibraryView::TotalSongCountUpdated(int count) { bool old = total_song_count_; total_song_count_ = count; - if (old != total_song_count_) - update(); + if (old != total_song_count_) update(); if (total_song_count_ == 0) setCursor(Qt::PointingHandCursor); @@ -340,7 +340,8 @@ void LibraryView::paintEvent(QPaintEvent* event) { QFontMetrics metrics(bold_font); - QRect title_rect(0, image_rect.bottom() + 20, rect.width(), metrics.height()); + QRect title_rect(0, image_rect.bottom() + 20, rect.width(), + metrics.height()); p.drawText(title_rect, Qt::AlignHCenter, tr("Your library is empty!")); // Draw the other text @@ -361,47 +362,60 @@ void LibraryView::mouseReleaseEvent(QMouseEvent* e) { } } -void LibraryView::contextMenuEvent(QContextMenuEvent *e) { - if(!context_menu_) { +void LibraryView::contextMenuEvent(QContextMenuEvent* e) { + if (!context_menu_) { context_menu_ = new QMenu(this); - add_to_playlist_ = context_menu_->addAction(IconLoader::Load("media-playback-start"), + add_to_playlist_ = context_menu_->addAction( + IconLoader::Load("media-playback-start"), tr("Append to current playlist"), this, SLOT(AddToPlaylist())); load_ = context_menu_->addAction(IconLoader::Load("media-playback-start"), - tr("Replace current playlist"), this, SLOT(Load())); - open_in_new_playlist_ = context_menu_->addAction(IconLoader::Load("document-new"), - tr("Open in new playlist"), this, SLOT(OpenInNewPlaylist())); + tr("Replace current playlist"), this, + SLOT(Load())); + open_in_new_playlist_ = context_menu_->addAction( + IconLoader::Load("document-new"), tr("Open in new playlist"), this, + SLOT(OpenInNewPlaylist())); context_menu_->addSeparator(); - add_to_playlist_enqueue_ = context_menu_->addAction(IconLoader::Load("go-next"), - tr("Queue track"), this, SLOT(AddToPlaylistEnqueue())); + add_to_playlist_enqueue_ = + context_menu_->addAction(IconLoader::Load("go-next"), tr("Queue track"), + this, SLOT(AddToPlaylistEnqueue())); context_menu_->addSeparator(); - new_smart_playlist_ = context_menu_->addAction(IconLoader::Load("document-new"), - tr("New smart playlist..."), this, SLOT(NewSmartPlaylist())); - edit_smart_playlist_ = context_menu_->addAction(IconLoader::Load("edit-rename"), - tr("Edit smart playlist..."), this, SLOT(EditSmartPlaylist())); - delete_smart_playlist_ = context_menu_->addAction(IconLoader::Load("edit-delete"), - tr("Delete smart playlist"), this, SLOT(DeleteSmartPlaylist())); + new_smart_playlist_ = context_menu_->addAction( + IconLoader::Load("document-new"), tr("New smart playlist..."), this, + SLOT(NewSmartPlaylist())); + edit_smart_playlist_ = context_menu_->addAction( + IconLoader::Load("edit-rename"), tr("Edit smart playlist..."), this, + SLOT(EditSmartPlaylist())); + delete_smart_playlist_ = context_menu_->addAction( + IconLoader::Load("edit-delete"), tr("Delete smart playlist"), this, + SLOT(DeleteSmartPlaylist())); context_menu_->addSeparator(); organise_ = context_menu_->addAction(IconLoader::Load("edit-copy"), - tr("Organise files..."), this, SLOT(Organise())); - copy_to_device_ = context_menu_->addAction(IconLoader::Load("multimedia-player-ipod-mini-blue"), + tr("Organise files..."), this, + SLOT(Organise())); + copy_to_device_ = context_menu_->addAction( + IconLoader::Load("multimedia-player-ipod-mini-blue"), tr("Copy to device..."), this, SLOT(CopyToDevice())); delete_ = context_menu_->addAction(IconLoader::Load("edit-delete"), - tr("Delete from disk..."), this, SLOT(Delete())); + tr("Delete from disk..."), this, + SLOT(Delete())); context_menu_->addSeparator(); edit_track_ = context_menu_->addAction(IconLoader::Load("edit-rename"), - tr("Edit track information..."), this, SLOT(EditTracks())); + tr("Edit track information..."), + this, SLOT(EditTracks())); edit_tracks_ = context_menu_->addAction(IconLoader::Load("edit-rename"), - tr("Edit tracks information..."), this, SLOT(EditTracks())); - show_in_browser_ = context_menu_->addAction(IconLoader::Load("document-open-folder"), - tr("Show in file browser..."), this, SLOT(ShowInBrowser())); + tr("Edit tracks information..."), + this, SLOT(EditTracks())); + show_in_browser_ = context_menu_->addAction( + IconLoader::Load("document-open-folder"), tr("Show in file browser..."), + this, SLOT(ShowInBrowser())); context_menu_->addSeparator(); - show_in_various_ = context_menu_->addAction( - tr("Show in various artists"), this, SLOT(ShowInVarious())); + show_in_various_ = context_menu_->addAction(tr("Show in various artists"), + this, SLOT(ShowInVarious())); no_show_in_various_ = context_menu_->addAction( tr("Don't show in various artists"), this, SLOT(NoShowInVarious())); @@ -409,21 +423,23 @@ void LibraryView::contextMenuEvent(QContextMenuEvent *e) { context_menu_->addMenu(filter_->menu()); - copy_to_device_->setDisabled(app_->device_manager()->connected_devices_model()->rowCount() == 0); - connect(app_->device_manager()->connected_devices_model(), SIGNAL(IsEmptyChanged(bool)), - copy_to_device_, SLOT(setDisabled(bool))); + copy_to_device_->setDisabled( + app_->device_manager()->connected_devices_model()->rowCount() == 0); + connect(app_->device_manager()->connected_devices_model(), + SIGNAL(IsEmptyChanged(bool)), copy_to_device_, + SLOT(setDisabled(bool))); } context_menu_index_ = indexAt(e->pos()); - if (!context_menu_index_.isValid()) - return; + if (!context_menu_index_.isValid()) return; context_menu_index_ = qobject_cast(model()) - ->mapToSource(context_menu_index_); + ->mapToSource(context_menu_index_); QModelIndexList selected_indexes = - qobject_cast(model())->mapSelectionToSource( - selectionModel()->selection()).indexes(); + qobject_cast(model()) + ->mapSelectionToSource(selectionModel()->selection()) + .indexes(); // number of smart playlists selected int smart_playlists = 0; @@ -434,27 +450,34 @@ void LibraryView::contextMenuEvent(QContextMenuEvent *e) { // number of editable non smart playlists selected int regular_editable = 0; - foreach(const QModelIndex& index, selected_indexes) { - int type = app_->library_model()->data(index, LibraryModel::Role_Type).toInt(); + foreach(const QModelIndex & index, selected_indexes) { + int type = + app_->library_model()->data(index, LibraryModel::Role_Type).toInt(); - if(type == LibraryItem::Type_SmartPlaylist) { + if (type == LibraryItem::Type_SmartPlaylist) { smart_playlists++; - } else if(type == LibraryItem::Type_PlaylistContainer) { + } else if (type == LibraryItem::Type_PlaylistContainer) { smart_playlists_header++; } else { regular_elements++; } - if(app_->library_model()->data(index, LibraryModel::Role_Editable).toBool()) { + if (app_->library_model() + ->data(index, LibraryModel::Role_Editable) + .toBool()) { regular_editable++; } } // TODO: check if custom plugin actions should be enabled / visible - const int songs_selected = smart_playlists + smart_playlists_header + regular_elements; - const bool regular_elements_only = songs_selected == regular_elements && regular_elements > 0; - const bool smart_playlists_only = songs_selected == smart_playlists + smart_playlists_header; - const bool only_smart_playlist_selected = smart_playlists == 1 && songs_selected == 1; + const int songs_selected = + smart_playlists + smart_playlists_header + regular_elements; + const bool regular_elements_only = + songs_selected == regular_elements && regular_elements > 0; + const bool smart_playlists_only = + songs_selected == smart_playlists + smart_playlists_header; + const bool only_smart_playlist_selected = + smart_playlists == 1 && songs_selected == 1; // in all modes load_->setEnabled(songs_selected); @@ -493,52 +516,51 @@ void LibraryView::contextMenuEvent(QContextMenuEvent *e) { context_menu_->popup(e->globalPos()); } -void LibraryView::ShowInVarious() { - ShowInVarious(true); -} +void LibraryView::ShowInVarious() { ShowInVarious(true); } -void LibraryView::NoShowInVarious() { - ShowInVarious(false); -} +void LibraryView::NoShowInVarious() { ShowInVarious(false); } void LibraryView::ShowInVarious(bool on) { - if (!context_menu_index_.isValid()) - return; + if (!context_menu_index_.isValid()) return; - // Map is from album name -> all artists sharing that album name, built from each selected - // song. We put through "Various Artists" changes one album at a time, to make sure the old album - // node gets removed (due to all children removed), before the new one gets added + // Map is from album name -> all artists sharing that album name, built from + // each selected + // song. We put through "Various Artists" changes one album at a time, to make + // sure the old album + // node gets removed (due to all children removed), before the new one gets + // added QMultiMap albums; - foreach (const Song& song, GetSelectedSongs()) { + foreach(const Song & song, GetSelectedSongs()) { if (albums.find(song.album(), song.artist()) == albums.end()) - albums.insert( song.album(), song.artist() ); + albums.insert(song.album(), song.artist()); } - // If we have only one album and we are putting it into Various Artists, check to see - // if there are other Artists in this album and prompt the user if they'd like them moved, too - if(on && albums.keys().count() == 1) { + // If we have only one album and we are putting it into Various Artists, check + // to see + // if there are other Artists in this album and prompt the user if they'd like + // them moved, too + if (on && albums.keys().count() == 1) { const QString album = albums.keys().first(); QList all_of_album = app_->library_backend()->GetSongsByAlbum(album); QSet other_artists; - foreach (const Song& s, all_of_album) { - if(!albums.contains(album, s.artist()) && !other_artists.contains(s.artist())) { + foreach(const Song & s, all_of_album) { + if (!albums.contains(album, s.artist()) && + !other_artists.contains(s.artist())) { other_artists.insert(s.artist()); } } if (other_artists.count() > 0) { - if (QMessageBox::question(this, - tr("There are other songs in this album"), - tr("Would you like to move the other songs in this album to Various Artists as well?"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::Yes) == QMessageBox::Yes) { - foreach (const QString& s, other_artists) { - albums.insert(album, s); - } + if (QMessageBox::question(this, tr("There are other songs in this album"), + tr("Would you like to move the other songs in " + "this album to Various Artists as well?"), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::Yes) == QMessageBox::Yes) { + foreach(const QString & s, other_artists) { albums.insert(album, s); } } } } - foreach (const QString& album, QSet::fromList(albums.keys())) { + foreach(const QString & album, QSet::fromList(albums.keys())) { app_->library_backend()->ForceCompilation(album, albums.values(album), on); } } @@ -586,8 +608,9 @@ void LibraryView::scrollTo(const QModelIndex& index, ScrollHint hint) { SongList LibraryView::GetSelectedSongs() const { QModelIndexList selected_indexes = - qobject_cast(model())->mapSelectionToSource( - selectionModel()->selection()).indexes(); + qobject_cast(model()) + ->mapSelectionToSource(selectionModel()->selection()) + .indexes(); return app_->library_model()->GetChildSongs(selected_indexes); } @@ -595,36 +618,44 @@ void LibraryView::Organise() { if (!organise_dialog_) organise_dialog_.reset(new OrganiseDialog(app_->task_manager())); - organise_dialog_->SetDestinationModel(app_->library_model()->directory_model()); + organise_dialog_->SetDestinationModel( + app_->library_model()->directory_model()); organise_dialog_->SetCopy(false); if (organise_dialog_->SetSongs(GetSelectedSongs())) organise_dialog_->show(); else { - QMessageBox::warning(this, tr("Error"), + QMessageBox::warning( + this, tr("Error"), tr("None of the selected songs were suitable for copying to a device")); } } void LibraryView::Delete() { if (QMessageBox::warning(this, tr("Delete files"), - tr("These files will be permanently deleted from disk, are you sure you want to continue?"), - QMessageBox::Yes, QMessageBox::Cancel) != QMessageBox::Yes) + tr("These files will be permanently deleted from " + "disk, are you sure you want to continue?"), + QMessageBox::Yes, + QMessageBox::Cancel) != QMessageBox::Yes) return; // We can cheat and always take the storage of the first directory, since // they'll all be FilesystemMusicStorage in a library and deleting doesn't // check the actual directory. std::shared_ptr storage = - app_->library_model()->directory_model()->index(0, 0).data(MusicStorage::Role_Storage) - .value>(); + app_->library_model() + ->directory_model() + ->index(0, 0) + .data(MusicStorage::Role_Storage) + .value>(); DeleteFiles* delete_files = new DeleteFiles(app_->task_manager(), storage); - connect(delete_files, SIGNAL(Finished(SongList)), SLOT(DeleteFinished(SongList))); + connect(delete_files, SIGNAL(Finished(SongList)), + SLOT(DeleteFinished(SongList))); delete_files->Start(GetSelectedSongs()); } void LibraryView::EditTracks() { - if(!edit_tag_dialog_) { + if (!edit_tag_dialog_) { edit_tag_dialog_.reset(new EditTagDialog(app_, this)); } edit_tag_dialog_->SetSongs(GetSelectedSongs()); @@ -635,15 +666,15 @@ void LibraryView::CopyToDevice() { if (!organise_dialog_) organise_dialog_.reset(new OrganiseDialog(app_->task_manager())); - organise_dialog_->SetDestinationModel(app_->device_manager()->connected_devices_model(), true); + organise_dialog_->SetDestinationModel( + app_->device_manager()->connected_devices_model(), true); organise_dialog_->SetCopy(true); organise_dialog_->SetSongs(GetSelectedSongs()); organise_dialog_->show(); } void LibraryView::DeleteFinished(const SongList& songs_with_errors) { - if (songs_with_errors.isEmpty()) - return; + if (songs_with_errors.isEmpty()) return; OrganiseErrorDialog* dialog = new OrganiseErrorDialog(this); dialog->Show(OrganiseErrorDialog::Type_Delete, songs_with_errors); @@ -653,7 +684,7 @@ void LibraryView::DeleteFinished(const SongList& songs_with_errors) { void LibraryView::FilterReturnPressed() { if (!currentIndex().isValid()) { // Pick the first thing that isn't a divider - for (int row=0 ; rowrowCount() ; ++row) { + for (int row = 0; row < model()->rowCount(); ++row) { QModelIndex idx(model()->index(row, 0)); if (idx.data(LibraryModel::Role_Type) != LibraryItem::Type_Divider) { setCurrentIndex(idx); @@ -662,8 +693,7 @@ void LibraryView::FilterReturnPressed() { } } - if (!currentIndex().isValid()) - return; + if (!currentIndex().isValid()) return; emit doubleClicked(currentIndex()); } @@ -682,7 +712,8 @@ void LibraryView::EditSmartPlaylist() { connect(wizard, SIGNAL(accepted()), SLOT(EditSmartPlaylistFinished())); wizard->show(); - wizard->SetGenerator(app_->library_model()->CreateGenerator(context_menu_index_)); + wizard->SetGenerator( + app_->library_model()->CreateGenerator(context_menu_index_)); } void LibraryView::DeleteSmartPlaylist() { @@ -696,14 +727,13 @@ void LibraryView::NewSmartPlaylistFinished() { void LibraryView::EditSmartPlaylistFinished() { const Wizard* wizard = qobject_cast(sender()); - app_->library_model()->UpdateGenerator(context_menu_index_, wizard->CreateGenerator()); + app_->library_model()->UpdateGenerator(context_menu_index_, + wizard->CreateGenerator()); } void LibraryView::ShowInBrowser() { QList urls; - foreach (const Song& song, GetSelectedSongs()) { - urls << song.url(); - } + foreach(const Song & song, GetSelectedSongs()) { urls << song.url(); } Utilities::OpenInFileBrowser(urls); } diff --git a/src/library/libraryview.h b/src/library/libraryview.h index fb096fa2d..6e229b658 100644 --- a/src/library/libraryview.h +++ b/src/library/libraryview.h @@ -32,18 +32,21 @@ class OrganiseDialog; class QMimeData; -namespace smart_playlists { class Wizard; } +namespace smart_playlists { +class Wizard; +} class LibraryItemDelegate : public QStyledItemDelegate { Q_OBJECT -public: + public: LibraryItemDelegate(QObject* parent); - void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const; -public slots: - bool helpEvent(QHelpEvent *event, QAbstractItemView *view, - const QStyleOptionViewItem &option, const QModelIndex &index); + public slots: + bool helpEvent(QHelpEvent* event, QAbstractItemView* view, + const QStyleOptionViewItem& option, const QModelIndex& index); }; class LibraryView : public AutoExpandingTreeView { @@ -64,7 +67,7 @@ class LibraryView : public AutoExpandingTreeView { void SetFilter(LibraryFilterWidget* filter); // QTreeView - void keyboardSearch(const QString &search); + void keyboardSearch(const QString& search); void scrollTo(const QModelIndex& index, ScrollHint hint = EnsureVisible); public slots: @@ -76,7 +79,7 @@ class LibraryView : public AutoExpandingTreeView { void SaveFocus(); void RestoreFocus(); - signals: +signals: void ShowConfigDialog(); protected: @@ -151,4 +154,4 @@ class LibraryView : public AutoExpandingTreeView { QSet last_selected_path_; }; -#endif // LIBRARYVIEW_H +#endif // LIBRARYVIEW_H diff --git a/src/library/libraryviewcontainer.cpp b/src/library/libraryviewcontainer.cpp index 2df492fea..f58f3e459 100644 --- a/src/library/libraryviewcontainer.cpp +++ b/src/library/libraryviewcontainer.cpp @@ -20,32 +20,26 @@ #include "globalsearch/globalsearch.h" LibraryViewContainer::LibraryViewContainer(QWidget* parent) - : QWidget(parent), - ui_(new Ui_LibraryViewContainer) -{ + : QWidget(parent), ui_(new Ui_LibraryViewContainer) { ui_->setupUi(this); view()->SetFilter(filter()); connect(filter(), SIGNAL(UpPressed()), view(), SLOT(UpAndFocus())); connect(filter(), SIGNAL(DownPressed()), view(), SLOT(DownAndFocus())); - connect(filter(), SIGNAL(ReturnPressed()), view(), SLOT(FilterReturnPressed())); - connect(view(), SIGNAL(FocusOnFilterSignal(QKeyEvent*)), filter(), SLOT(FocusOnFilter(QKeyEvent*))); + connect(filter(), SIGNAL(ReturnPressed()), view(), + SLOT(FilterReturnPressed())); + connect(view(), SIGNAL(FocusOnFilterSignal(QKeyEvent*)), filter(), + SLOT(FocusOnFilter(QKeyEvent*))); ReloadSettings(); } -LibraryViewContainer::~LibraryViewContainer() { - delete ui_; -} +LibraryViewContainer::~LibraryViewContainer() { delete ui_; } -LibraryView* LibraryViewContainer::view() const { - return ui_->view; -} +LibraryView* LibraryViewContainer::view() const { return ui_->view; } LibraryFilterWidget* LibraryViewContainer::filter() const { return ui_->filter; } -void LibraryViewContainer::ReloadSettings() { - view()->ReloadSettings(); -} +void LibraryViewContainer::ReloadSettings() { view()->ReloadSettings(); } diff --git a/src/library/libraryviewcontainer.h b/src/library/libraryviewcontainer.h index 24cf18a5b..751756da6 100644 --- a/src/library/libraryviewcontainer.h +++ b/src/library/libraryviewcontainer.h @@ -27,7 +27,7 @@ class Ui_LibraryViewContainer; class LibraryViewContainer : public QWidget { Q_OBJECT -public: + public: LibraryViewContainer(QWidget* parent = 0); ~LibraryViewContainer(); @@ -36,8 +36,8 @@ public: void ReloadSettings(); -private: + private: Ui_LibraryViewContainer* ui_; }; -#endif // LIBRARYVIEWCONTAINER_H +#endif // LIBRARYVIEWCONTAINER_H diff --git a/src/library/librarywatcher.cpp b/src/library/librarywatcher.cpp index a251f9eb1..8944664c4 100644 --- a/src/library/librarywatcher.cpp +++ b/src/library/librarywatcher.cpp @@ -48,25 +48,27 @@ QStringList LibraryWatcher::sValidImages; const char* LibraryWatcher::kSettingsGroup = "LibraryWatcher"; LibraryWatcher::LibraryWatcher(QObject* parent) - : QObject(parent), - backend_(nullptr), - task_manager_(nullptr), - fs_watcher_(FileSystemWatcherInterface::Create(this)), - stop_requested_(false), - scan_on_startup_(true), - monitor_(true), - rescan_timer_(new QTimer(this)), - rescan_paused_(false), - total_watches_(0), - cue_parser_(new CueParser(backend_, this)) -{ + : QObject(parent), + backend_(nullptr), + task_manager_(nullptr), + fs_watcher_(FileSystemWatcherInterface::Create(this)), + stop_requested_(false), + scan_on_startup_(true), + monitor_(true), + rescan_timer_(new QTimer(this)), + rescan_paused_(false), + total_watches_(0), + cue_parser_(new CueParser(backend_, this)) { Utilities::SetThreadIOPriority(Utilities::IOPRIO_CLASS_IDLE); rescan_timer_->setInterval(1000); rescan_timer_->setSingleShot(true); if (sValidImages.isEmpty()) { - sValidImages << "jpg" << "png" << "gif" << "jpeg"; + sValidImages << "jpg" + << "png" + << "gif" + << "jpeg"; } ReloadSettings(); @@ -74,17 +76,17 @@ LibraryWatcher::LibraryWatcher(QObject* parent) connect(rescan_timer_, SIGNAL(timeout()), SLOT(RescanPathsNow())); } -LibraryWatcher::ScanTransaction::ScanTransaction(LibraryWatcher* watcher, int dir, - bool incremental, bool ignores_mtime) - : progress_(0), - progress_max_(0), - dir_(dir), - incremental_(incremental), - ignores_mtime_(ignores_mtime), - watcher_(watcher), - cached_songs_dirty_(true), - known_subdirs_dirty_(true) -{ +LibraryWatcher::ScanTransaction::ScanTransaction(LibraryWatcher* watcher, + int dir, bool incremental, + bool ignores_mtime) + : progress_(0), + progress_max_(0), + dir_(dir), + incremental_(incremental), + ignores_mtime_(ignores_mtime), + watcher_(watcher), + cached_songs_dirty_(true), + known_subdirs_dirty_(true) { QString description; if (watcher_->device_name_.isEmpty()) description = tr("Updating library"); @@ -99,20 +101,15 @@ LibraryWatcher::ScanTransaction::~ScanTransaction() { // If we're stopping then don't commit the transaction if (watcher_->stop_requested_) return; - if (!new_songs.isEmpty()) - emit watcher_->NewOrUpdatedSongs(new_songs); + if (!new_songs.isEmpty()) emit watcher_->NewOrUpdatedSongs(new_songs); - if (!touched_songs.isEmpty()) - emit watcher_->SongsMTimeUpdated(touched_songs); + if (!touched_songs.isEmpty()) emit watcher_->SongsMTimeUpdated(touched_songs); - if (!deleted_songs.isEmpty()) - emit watcher_->SongsDeleted(deleted_songs); + if (!deleted_songs.isEmpty()) emit watcher_->SongsDeleted(deleted_songs); - if (!readded_songs.isEmpty()) - emit watcher_->SongsReadded(readded_songs); + if (!readded_songs.isEmpty()) emit watcher_->SongsReadded(readded_songs); - if (!new_subdirs.isEmpty()) - emit watcher_->SubdirsDiscovered(new_subdirs); + if (!new_subdirs.isEmpty()) emit watcher_->SubdirsDiscovered(new_subdirs); if (!touched_subdirs.isEmpty()) emit watcher_->SubdirsMTimeUpdated(touched_subdirs); @@ -121,7 +118,7 @@ LibraryWatcher::ScanTransaction::~ScanTransaction() { if (watcher_->monitor_) { // Watch the new subdirectories - foreach (const Subdirectory& subdir, new_subdirs) { + foreach(const Subdirectory & subdir, new_subdirs) { watcher_->AddWatch(watcher_->watched_dirs_[dir_], subdir.path); } } @@ -137,7 +134,8 @@ void LibraryWatcher::ScanTransaction::AddToProgressMax(int n) { watcher_->task_manager_->SetTaskProgress(task_id_, progress_, progress_max_); } -SongList LibraryWatcher::ScanTransaction::FindSongsInSubdirectory(const QString &path) { +SongList LibraryWatcher::ScanTransaction::FindSongsInSubdirectory( + const QString& path) { if (cached_songs_dirty_) { cached_songs_ = watcher_->backend_->FindSongsInDirectory(dir_); cached_songs_dirty_ = false; @@ -145,35 +143,35 @@ SongList LibraryWatcher::ScanTransaction::FindSongsInSubdirectory(const QString // TODO: Make this faster SongList ret; - foreach (const Song& song, cached_songs_) { - if (song.url().toLocalFile().section('/', 0, -2) == path) - ret << song; + foreach(const Song & song, cached_songs_) { + if (song.url().toLocalFile().section('/', 0, -2) == path) ret << song; } return ret; } -void LibraryWatcher::ScanTransaction::SetKnownSubdirs(const SubdirectoryList &subdirs) { +void LibraryWatcher::ScanTransaction::SetKnownSubdirs( + const SubdirectoryList& subdirs) { known_subdirs_ = subdirs; known_subdirs_dirty_ = false; } -bool LibraryWatcher::ScanTransaction::HasSeenSubdir(const QString &path) { +bool LibraryWatcher::ScanTransaction::HasSeenSubdir(const QString& path) { if (known_subdirs_dirty_) SetKnownSubdirs(watcher_->backend_->SubdirsInDirectory(dir_)); - foreach (const Subdirectory& subdir, known_subdirs_) { - if (subdir.path == path && subdir.mtime != 0) - return true; + foreach(const Subdirectory & subdir, known_subdirs_) { + if (subdir.path == path && subdir.mtime != 0) return true; } return false; } -SubdirectoryList LibraryWatcher::ScanTransaction::GetImmediateSubdirs(const QString &path) { +SubdirectoryList LibraryWatcher::ScanTransaction::GetImmediateSubdirs( + const QString& path) { if (known_subdirs_dirty_) SetKnownSubdirs(watcher_->backend_->SubdirsInDirectory(dir_)); SubdirectoryList ret; - foreach (const Subdirectory& subdir, known_subdirs_) { + foreach(const Subdirectory & subdir, known_subdirs_) { if (subdir.path.left(subdir.path.lastIndexOf(QDir::separator())) == path && subdir.mtime != 0) { ret << subdir; @@ -189,7 +187,8 @@ SubdirectoryList LibraryWatcher::ScanTransaction::GetAllSubdirs() { return known_subdirs_; } -void LibraryWatcher::AddDirectory(const Directory& dir, const SubdirectoryList& subdirs) { +void LibraryWatcher::AddDirectory(const Directory& dir, + const SubdirectoryList& subdirs) { watched_dirs_[dir.id] = dir; if (subdirs.isEmpty()) { @@ -205,29 +204,28 @@ void LibraryWatcher::AddDirectory(const Directory& dir, const SubdirectoryList& ScanTransaction transaction(this, dir.id, true); transaction.SetKnownSubdirs(subdirs); transaction.AddToProgressMax(subdirs.count()); - foreach (const Subdirectory& subdir, subdirs) { + foreach(const Subdirectory & subdir, subdirs) { if (stop_requested_) return; - if (scan_on_startup_) - ScanSubdirectory(subdir.path, subdir, &transaction); + if (scan_on_startup_) ScanSubdirectory(subdir.path, subdir, &transaction); - if (monitor_) - AddWatch(dir, subdir.path); + if (monitor_) AddWatch(dir, subdir.path); } } emit CompilationsNeedUpdating(); } -void LibraryWatcher::ScanSubdirectory( - const QString& path, const Subdirectory& subdir, ScanTransaction* t, - bool force_noincremental) { +void LibraryWatcher::ScanSubdirectory(const QString& path, + const Subdirectory& subdir, + ScanTransaction* t, + bool force_noincremental) { QFileInfo path_info(path); // Do not scan symlinked dirs that are already in collection if (path_info.isSymLink()) { QString real_path = path_info.symLinkTarget(); - foreach (const Directory& dir, watched_dirs_) { + foreach(const Directory & dir, watched_dirs_) { if (real_path.startsWith(dir.path)) { t->AddToProgress(1); return; @@ -250,7 +248,7 @@ void LibraryWatcher::ScanSubdirectory( // so we need to look and see if any of our children don't exist any more. // If one has been removed, "rescan" it to get the deleted songs SubdirectoryList previous_subdirs = t->GetImmediateSubdirs(path); - foreach (const Subdirectory& subdir, previous_subdirs) { + foreach(const Subdirectory & subdir, previous_subdirs) { if (!QFile::exists(subdir.path) && subdir.path != path) { t->AddToProgressMax(1); ScanSubdirectory(subdir.path, subdir, t, true); @@ -258,9 +256,11 @@ void LibraryWatcher::ScanSubdirectory( } // First we "quickly" get a list of the files in the directory that we - // think might be music. While we're here, we also look for new subdirectories + // think might be music. While we're here, we also look for new + // subdirectories // and possible album artwork. - QDirIterator it(path, QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot); + QDirIterator it( + path, QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot); while (it.hasNext()) { if (stop_requested_) return; @@ -296,7 +296,7 @@ void LibraryWatcher::ScanSubdirectory( QSet cues_processed; // Now compare the list from the database with the list of files on disk - foreach (const QString& file, files_on_disk) { + foreach(const QString & file, files_on_disk) { if (stop_requested_) return; // associated cue @@ -324,16 +324,19 @@ void LibraryWatcher::ScanSubdirectory( bool cue_deleted = song_cue_mtime == 0 && matching_song.has_cue(); bool cue_added = matching_cue_mtime != 0 && !matching_song.has_cue(); - // watch out for cue songs which have their mtime equal to qMax(media_file_mtime, cue_sheet_mtime) - bool changed = (matching_song.mtime() != qMax(file_info.lastModified().toTime_t(), song_cue_mtime)) - || cue_deleted || cue_added; + // watch out for cue songs which have their mtime equal to + // qMax(media_file_mtime, cue_sheet_mtime) + bool changed = + (matching_song.mtime() != + qMax(file_info.lastModified().toTime_t(), song_cue_mtime)) || + cue_deleted || cue_added; // Also want to look to see whether the album art has changed QString image = ImageForSong(file, album_art); if ((matching_song.art_automatic().isEmpty() && !image.isEmpty()) || - (!matching_song.art_automatic().isEmpty() - && !matching_song.has_embedded_cover() - && !QFile::exists(matching_song.art_automatic()))) { + (!matching_song.art_automatic().isEmpty() && + !matching_song.has_embedded_cover() && + !QFile::exists(matching_song.art_automatic()))) { changed = true; } @@ -342,23 +345,24 @@ void LibraryWatcher::ScanSubdirectory( qLog(Debug) << file << "changed"; // if cue associated... - if(!cue_deleted && (matching_song.has_cue() || cue_added)) { + if (!cue_deleted && (matching_song.has_cue() || cue_added)) { UpdateCueAssociatedSongs(file, path, matching_cue, image, t); - // if no cue or it's about to lose it... + // if no cue or it's about to lose it... } else { - UpdateNonCueAssociatedSong(file, matching_song, image, cue_deleted, t); + UpdateNonCueAssociatedSong(file, matching_song, image, cue_deleted, + t); } } // nothing has changed - mark the song available without re-scanning - if (matching_song.is_unavailable()) - t->readded_songs << matching_song; + if (matching_song.is_unavailable()) t->readded_songs << matching_song; } else { // The song is on disk but not in the DB - SongList song_list = ScanNewFile(file, path, matching_cue, &cues_processed); + SongList song_list = + ScanNewFile(file, path, matching_cue, &cues_processed); - if(song_list.isEmpty()) { + if (song_list.isEmpty()) { continue; } @@ -366,10 +370,9 @@ void LibraryWatcher::ScanSubdirectory( // choose an image for the song(s) QString image = ImageForSong(file, album_art); - foreach (Song song, song_list) { + foreach(Song song, song_list) { song.set_directory_id(t->dir()); - if (song.art_automatic().isEmpty()) - song.set_art_automatic(image); + if (song.art_automatic().isEmpty()) song.set_art_automatic(image); t->new_songs << song; } @@ -377,8 +380,9 @@ void LibraryWatcher::ScanSubdirectory( } // Look for deleted songs - foreach (const Song& song, songs_in_db) { - if (!song.is_unavailable() && !files_on_disk.contains(song.url().toLocalFile())) { + foreach(const Song & song, songs_in_db) { + if (!song.is_unavailable() && + !files_on_disk.contains(song.url().toLocalFile())) { qLog(Debug) << "Song deleted from disk:" << song.url().toLocalFile(); t->deleted_songs << song; } @@ -387,8 +391,8 @@ void LibraryWatcher::ScanSubdirectory( // Add this subdir to the new or touched list Subdirectory updated_subdir; updated_subdir.directory_id = t->dir(); - updated_subdir.mtime = path_info.exists() ? - path_info.lastModified().toTime_t() : 0; + updated_subdir.mtime = + path_info.exists() ? path_info.lastModified().toTime_t() : 0; updated_subdir.path = path; if (subdir.directory_id == -1) @@ -400,14 +404,16 @@ void LibraryWatcher::ScanSubdirectory( // Recurse into the new subdirs that we found t->AddToProgressMax(my_new_subdirs.count()); - foreach (const Subdirectory& my_new_subdir, my_new_subdirs) { + foreach(const Subdirectory & my_new_subdir, my_new_subdirs) { if (stop_requested_) return; ScanSubdirectory(my_new_subdir.path, my_new_subdir, t, true); } } -void LibraryWatcher::UpdateCueAssociatedSongs(const QString& file, const QString& path, - const QString& matching_cue, const QString& image, +void LibraryWatcher::UpdateCueAssociatedSongs(const QString& file, + const QString& path, + const QString& matching_cue, + const QString& image, ScanTransaction* t) { QFile cue(matching_cue); cue.open(QIODevice::ReadOnly); @@ -415,7 +421,7 @@ void LibraryWatcher::UpdateCueAssociatedSongs(const QString& file, const QString SongList old_sections = backend_->GetSongsByUrl(QUrl::fromLocalFile(file)); QHash sections_map; - foreach(const Song& song, old_sections) { + foreach(const Song & song, old_sections) { sections_map[song.beginning_nanosec()] = song; } @@ -427,9 +433,9 @@ void LibraryWatcher::UpdateCueAssociatedSongs(const QString& file, const QString Song matching = sections_map[cue_song.beginning_nanosec()]; // a new section - if(!matching.is_valid()) { + if (!matching.is_valid()) { t->new_songs << cue_song; - // changed section + // changed section } else { PreserveUserSetData(file, image, matching, &cue_song, t); used_ids.insert(matching.id()); @@ -437,23 +443,25 @@ void LibraryWatcher::UpdateCueAssociatedSongs(const QString& file, const QString } // sections that are now missing - foreach(const Song& matching, old_sections) { - if(!used_ids.contains(matching.id())) { + foreach(const Song & matching, old_sections) { + if (!used_ids.contains(matching.id())) { t->deleted_songs << matching; } } } - -void LibraryWatcher::UpdateNonCueAssociatedSong(const QString& file, const Song& matching_song, - const QString& image, bool cue_deleted, +void LibraryWatcher::UpdateNonCueAssociatedSong(const QString& file, + const Song& matching_song, + const QString& image, + bool cue_deleted, ScanTransaction* t) { // if a cue got deleted, we turn it's first section into the new // 'raw' (cueless) song and we just remove the rest of the sections // from the library - if(cue_deleted) { - foreach(const Song& song, backend_->GetSongsByUrl(QUrl::fromLocalFile(file))) { - if(!song.IsMetadataEqual(matching_song)) { + if (cue_deleted) { + foreach(const Song & song, + backend_->GetSongsByUrl(QUrl::fromLocalFile(file))) { + if (!song.IsMetadataEqual(matching_song)) { t->deleted_songs << song; } } @@ -463,21 +471,21 @@ void LibraryWatcher::UpdateNonCueAssociatedSong(const QString& file, const Song& song_on_disk.set_directory_id(t->dir()); TagReaderClient::Instance()->ReadFileBlocking(file, &song_on_disk); - if(song_on_disk.is_valid()) { + if (song_on_disk.is_valid()) { PreserveUserSetData(file, image, matching_song, &song_on_disk, t); } } SongList LibraryWatcher::ScanNewFile(const QString& file, const QString& path, - const QString& matching_cue, QSet* cues_processed) { + const QString& matching_cue, + QSet* cues_processed) { SongList song_list; uint matching_cue_mtime = GetMtimeForCue(matching_cue); // if it's a cue - create virtual tracks - if(matching_cue_mtime) { + if (matching_cue_mtime) { // don't process the same cue many times - if(cues_processed->contains(matching_cue)) - return song_list; + if (cues_processed->contains(matching_cue)) return song_list; QFile cue(matching_cue); cue.open(QIODevice::ReadOnly); @@ -485,7 +493,8 @@ SongList LibraryWatcher::ScanNewFile(const QString& file, const QString& path, // Ignore FILEs pointing to other media files. Also, watch out for incorrect // media files. Playlist parser for CUEs considers every entry in sheet // valid and we don't want invalid media getting into library! - foreach(const Song& cue_song, cue_parser_->Load(&cue, matching_cue, path)) { + foreach(const Song & cue_song, + cue_parser_->Load(&cue, matching_cue, path)) { if (cue_song.url().toLocalFile() == file) { if (TagReaderClient::Instance()->IsMediaFileBlocking(file)) { song_list << cue_song; @@ -493,11 +502,11 @@ SongList LibraryWatcher::ScanNewFile(const QString& file, const QString& path, } } - if(!song_list.isEmpty()) { + if (!song_list.isEmpty()) { *cues_processed << matching_cue; } - // it's a normal media file + // it's a normal media file } else { Song song; TagReaderClient::Instance()->ReadFileBlocking(file, &song); @@ -505,21 +514,21 @@ SongList LibraryWatcher::ScanNewFile(const QString& file, const QString& path, if (song.is_valid()) { song_list << song; } - } return song_list; } -void LibraryWatcher::PreserveUserSetData(const QString& file, const QString& image, - const Song& matching_song, Song* out, ScanTransaction* t) { +void LibraryWatcher::PreserveUserSetData(const QString& file, + const QString& image, + const Song& matching_song, Song* out, + ScanTransaction* t) { out->set_id(matching_song.id()); // Previous versions of Clementine incorrectly overwrote this and // stored it in the DB, so we can't rely on matching_song to // know if it has embedded artwork or not, but we can check here. - if (!out->has_embedded_cover()) - out->set_art_automatic(image); + if (!out->has_embedded_cover()) out->set_art_automatic(image); out->MergeUserSetData(matching_song); @@ -553,17 +562,14 @@ uint LibraryWatcher::GetMtimeForCue(const QString& cue_path) { const QDateTime cue_last_modified = file_info.lastModified(); - return cue_last_modified.isValid() - ? cue_last_modified.toTime_t() - : 0; + return cue_last_modified.isValid() ? cue_last_modified.toTime_t() : 0; } void LibraryWatcher::AddWatch(const Directory& dir, const QString& path) { - if (!QFile::exists(path)) - return; + if (!QFile::exists(path)) return; connect(fs_watcher_, SIGNAL(PathChanged(const QString&)), this, - SLOT(DirectoryChanged(const QString&)), Qt::UniqueConnection); + SLOT(DirectoryChanged(const QString&)), Qt::UniqueConnection); fs_watcher_->AddPath(path); subdir_mapping_[path] = dir; } @@ -573,15 +579,16 @@ void LibraryWatcher::RemoveDirectory(const Directory& dir) { watched_dirs_.remove(dir.id); // Stop watching the directory's subdirectories - foreach (const QString& subdir_path, subdir_mapping_.keys(dir)) { + foreach(const QString & subdir_path, subdir_mapping_.keys(dir)) { fs_watcher_->RemovePath(subdir_path); subdir_mapping_.remove(subdir_path); } } -bool LibraryWatcher::FindSongByPath(const SongList& list, const QString& path, Song* out) { +bool LibraryWatcher::FindSongByPath(const SongList& list, const QString& path, + Song* out) { // TODO: Make this faster - foreach (const Song& song, list) { + foreach(const Song & song, list) { if (song.url().toLocalFile() == path) { *out = song; return true; @@ -590,31 +597,31 @@ bool LibraryWatcher::FindSongByPath(const SongList& list, const QString& path, S return false; } -void LibraryWatcher::DirectoryChanged(const QString &subdir) { +void LibraryWatcher::DirectoryChanged(const QString& subdir) { // Find what dir it was in - QHash::const_iterator it = subdir_mapping_.constFind(subdir); + QHash::const_iterator it = + subdir_mapping_.constFind(subdir); if (it == subdir_mapping_.constEnd()) { return; } Directory dir = *it; - qLog(Debug) << "Subdir" << subdir << "changed under directory" << dir.path << "id" << dir.id; + qLog(Debug) << "Subdir" << subdir << "changed under directory" << dir.path + << "id" << dir.id; // Queue the subdir for rescanning - if (!rescan_queue_[dir.id].contains(subdir)) - rescan_queue_[dir.id] << subdir; + if (!rescan_queue_[dir.id].contains(subdir)) rescan_queue_[dir.id] << subdir; - if (!rescan_paused_) - rescan_timer_->start(); + if (!rescan_paused_) rescan_timer_->start(); } void LibraryWatcher::RescanPathsNow() { - foreach (int dir, rescan_queue_.keys()) { + foreach(int dir, rescan_queue_.keys()) { if (stop_requested_) return; ScanTransaction transaction(this, dir, false); transaction.AddToProgressMax(rescan_queue_[dir].count()); - foreach (const QString& path, rescan_queue_[dir]) { + foreach(const QString & path, rescan_queue_[dir]) { if (stop_requested_) return; Subdirectory subdir; subdir.directory_id = dir; @@ -636,10 +643,10 @@ QString LibraryWatcher::PickBestImage(const QStringList& images) { QStringList filtered; - foreach(const QString& filter_text, best_image_filters_) { + foreach(const QString & filter_text, best_image_filters_) { // the images in the images list are represented by a full path, // so we need to isolate just the filename - foreach(const QString& image, images) { + foreach(const QString & image, images) { QFileInfo file_info(image); QString filename(file_info.fileName()); if (filename.contains(filter_text, Qt::CaseInsensitive)) @@ -649,11 +656,10 @@ QString LibraryWatcher::PickBestImage(const QStringList& images) { /* We assume the filters are give in the order best to worst, so if we've got a result, we go with it. Otherwise we might start capturing more generic rules */ - if (!filtered.isEmpty()) - break; + if (!filtered.isEmpty()) break; } - if (filtered.isEmpty()){ + if (filtered.isEmpty()) { // the filter was too restrictive, just use the original list filtered = images; } @@ -661,10 +667,9 @@ QString LibraryWatcher::PickBestImage(const QStringList& images) { int biggest_size = 0; QString biggest_path; - foreach (const QString& path, filtered) { + foreach(const QString & path, filtered) { QImage image(path); - if (image.isNull()) - continue; + if (image.isNull()) continue; int size = image.width() * image.height(); if (size > biggest_size) { @@ -676,7 +681,8 @@ QString LibraryWatcher::PickBestImage(const QStringList& images) { return biggest_path; } -QString LibraryWatcher::ImageForSong(const QString& path, QMap& album_art) { +QString LibraryWatcher::ImageForSong(const QString& path, + QMap& album_art) { QString dir(DirectoryPart(path)); if (album_art.contains(dir)) { @@ -704,21 +710,21 @@ void LibraryWatcher::ReloadSettings() { monitor_ = s.value("monitor", true).toBool(); best_image_filters_.clear(); - QStringList filters = s.value("cover_art_patterns", - QStringList() << "front" << "cover").toStringList(); - foreach(const QString& filter, filters) { + QStringList filters = + s.value("cover_art_patterns", QStringList() << "front" + << "cover").toStringList(); + foreach(const QString & filter, filters) { QString s = filter.trimmed(); - if (!s.isEmpty()) - best_image_filters_ << s; + if (!s.isEmpty()) best_image_filters_ << s; } if (!monitor_ && was_monitoring_before) { fs_watcher_->Clear(); } else if (monitor_ && !was_monitoring_before) { // Add all directories to all QFileSystemWatchers again - foreach (const Directory& dir, watched_dirs_.values()) { + foreach(const Directory & dir, watched_dirs_.values()) { SubdirectoryList subdirs = backend_->SubdirsInDirectory(dir.id); - foreach (const Subdirectory& subdir, subdirs) { + foreach(const Subdirectory & subdir, subdirs) { AddWatch(dir, subdir.path); } } @@ -732,8 +738,7 @@ void LibraryWatcher::SetRescanPausedAsync(bool pause) { void LibraryWatcher::SetRescanPaused(bool pause) { rescan_paused_ = pause; - if (!rescan_paused_ && !rescan_queue_.isEmpty()) - RescanPathsNow(); + if (!rescan_paused_ && !rescan_queue_.isEmpty()) RescanPathsNow(); } void LibraryWatcher::IncrementalScanAsync() { @@ -744,22 +749,17 @@ void LibraryWatcher::FullScanAsync() { QMetaObject::invokeMethod(this, "FullScanNow", Qt::QueuedConnection); } -void LibraryWatcher::IncrementalScanNow() { - PerformScan(true, false); -} +void LibraryWatcher::IncrementalScanNow() { PerformScan(true, false); } -void LibraryWatcher::FullScanNow() { - PerformScan(false, true); -} +void LibraryWatcher::FullScanNow() { PerformScan(false, true); } void LibraryWatcher::PerformScan(bool incremental, bool ignore_mtimes) { - foreach (const Directory& dir, watched_dirs_.values()) { - ScanTransaction transaction(this, dir.id, - incremental, ignore_mtimes); + foreach(const Directory & dir, watched_dirs_.values()) { + ScanTransaction transaction(this, dir.id, incremental, ignore_mtimes); SubdirectoryList subdirs(transaction.GetAllSubdirs()); transaction.AddToProgressMax(subdirs.count()); - foreach (const Subdirectory& subdir, subdirs) { + foreach(const Subdirectory & subdir, subdirs) { if (stop_requested_) return; ScanSubdirectory(subdir.path, subdir, &transaction); diff --git a/src/library/librarywatcher.h b/src/library/librarywatcher.h index 8678a5c5c..a1abb8bf4 100644 --- a/src/library/librarywatcher.h +++ b/src/library/librarywatcher.h @@ -43,8 +43,12 @@ class LibraryWatcher : public QObject { static const char* kSettingsGroup; void set_backend(LibraryBackend* backend) { backend_ = backend; } - void set_task_manager(TaskManager* task_manager) { task_manager_ = task_manager; } - void set_device_name(const QString& device_name) { device_name_ = device_name; } + void set_task_manager(TaskManager* task_manager) { + task_manager_ = task_manager; + } + void set_device_name(const QString& device_name) { + device_name_ = device_name; + } void IncrementalScanAsync(); void FullScanAsync(); @@ -53,7 +57,7 @@ class LibraryWatcher : public QObject { void Stop() { stop_requested_ = true; } - signals: +signals: void NewOrUpdatedSongs(const SongList& songs); void SongsMTimeUpdated(const SongList& songs); void SongsDeleted(const SongList& songs); @@ -82,8 +86,8 @@ class LibraryWatcher : public QObject { // LibraryBackend::FindSongsInDirectory. class ScanTransaction { public: - ScanTransaction(LibraryWatcher* watcher, int dir, - bool incremental, bool ignores_mtime = false); + ScanTransaction(LibraryWatcher* watcher, int dir, bool incremental, + bool ignores_mtime = false); ~ScanTransaction(); SongList FindSongsInSubdirectory(const QString& path); @@ -108,7 +112,7 @@ class LibraryWatcher : public QObject { private: ScanTransaction(const ScanTransaction&) {} - ScanTransaction& operator =(const ScanTransaction&) { return *this; } + ScanTransaction& operator=(const ScanTransaction&) { return *this; } int task_id_; int progress_; @@ -142,12 +146,14 @@ class LibraryWatcher : public QObject { ScanTransaction* t, bool force_noincremental = false); private: - static bool FindSongByPath(const SongList& list, const QString& path, Song* out); - inline static QString NoExtensionPart( const QString &fileName ); - inline static QString ExtensionPart( const QString &fileName ); - inline static QString DirectoryPart( const QString &fileName ); + static bool FindSongByPath(const SongList& list, const QString& path, + Song* out); + inline static QString NoExtensionPart(const QString& fileName); + inline static QString ExtensionPart(const QString& fileName); + inline static QString DirectoryPart(const QString& fileName); QString PickBestImage(const QStringList& images); - QString ImageForSong(const QString& path, QMap& album_art); + QString ImageForSong(const QString& path, + QMap& album_art); void AddWatch(const Directory& dir, const QString& path); uint GetMtimeForCue(const QString& cue_path); void PerformScan(bool incremental, bool ignore_mtimes); @@ -155,22 +161,26 @@ class LibraryWatcher : public QObject { // Updates the sections of a cue associated and altered (according to mtime) // media file during a scan. void UpdateCueAssociatedSongs(const QString& file, const QString& path, - const QString& matching_cue, const QString& image, - ScanTransaction* t); + const QString& matching_cue, + const QString& image, ScanTransaction* t); // Updates a single non-cue associated and altered (according to mtime) song // during a scan. - void UpdateNonCueAssociatedSong(const QString& file, const Song& matching_song, + void UpdateNonCueAssociatedSong(const QString& file, + const Song& matching_song, const QString& image, bool cue_deleted, - ScanTransaction* t) ; + ScanTransaction* t); // Updates a new song with some metadata taken from it's equivalent old // song (for example rating and score). void PreserveUserSetData(const QString& file, const QString& image, - const Song& matching_song, Song* out, ScanTransaction* t); - // Scans a single media file that's present on the disk but not yet in the library. + const Song& matching_song, Song* out, + ScanTransaction* t); + // Scans a single media file that's present on the disk but not yet in the + // library. // It may result in a multiple files added to the library when the media file // has many sections (like a CUE related media file). SongList ScanNewFile(const QString& file, const QString& path, - const QString& matching_cue, QSet* cues_processed); + const QString& matching_cue, + QSet* cues_processed); private: LibraryBackend* backend_; @@ -193,7 +203,8 @@ class LibraryWatcher : public QObject { QMap watched_dirs_; QTimer* rescan_timer_; - QMap rescan_queue_; // dir id -> list of subdirs to be scanned + QMap + rescan_queue_; // dir id -> list of subdirs to be scanned bool rescan_paused_; int total_watches_; @@ -203,15 +214,17 @@ class LibraryWatcher : public QObject { static QStringList sValidImages; }; -inline QString LibraryWatcher::NoExtensionPart( const QString &fileName ) { - return fileName.contains( '.' ) ? fileName.section( '.', 0, -2 ) : ""; +inline QString LibraryWatcher::NoExtensionPart(const QString& fileName) { + return fileName.contains('.') ? fileName.section('.', 0, -2) : ""; } // Thanks Amarok -inline QString LibraryWatcher::ExtensionPart( const QString &fileName ) { - return fileName.contains( '.' ) ? fileName.mid( fileName.lastIndexOf('.') + 1 ).toLower() : ""; +inline QString LibraryWatcher::ExtensionPart(const QString& fileName) { + return fileName.contains('.') + ? fileName.mid(fileName.lastIndexOf('.') + 1).toLower() + : ""; } -inline QString LibraryWatcher::DirectoryPart( const QString &fileName ) { - return fileName.section( '/', 0, -2 ); +inline QString LibraryWatcher::DirectoryPart(const QString& fileName) { + return fileName.section('/', 0, -2); } -#endif // LIBRARYWATCHER_H +#endif // LIBRARYWATCHER_H diff --git a/src/library/sqlrow.cpp b/src/library/sqlrow.cpp index 25ed7fff7..a573dfa03 100644 --- a/src/library/sqlrow.cpp +++ b/src/library/sqlrow.cpp @@ -21,13 +21,9 @@ #include #include -SqlRow::SqlRow(const QSqlQuery& query) { - Init(query); -} +SqlRow::SqlRow(const QSqlQuery& query) { Init(query); } -SqlRow::SqlRow(const LibraryQuery& query) { - Init(query); -} +SqlRow::SqlRow(const LibraryQuery& query) { Init(query); } void SqlRow::Init(const QSqlQuery& query) { int rows = query.record().count(); @@ -35,4 +31,3 @@ void SqlRow::Init(const QSqlQuery& query) { columns_ << query.value(i); } } - diff --git a/src/main.cpp b/src/main.cpp index 9b5227a3b..c46ab90aa 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -20,13 +20,13 @@ #include #ifdef Q_OS_WIN32 -# define _WIN32_WINNT 0x0600 -# include -# include +#define _WIN32_WINNT 0x0600 +#include +#include #endif // Q_OS_WIN32 #ifdef Q_OS_UNIX -# include +#include #endif // Q_OS_UNIX #include @@ -80,32 +80,32 @@ #include #ifdef HAVE_SPOTIFY_DOWNLOADER - #include +#include #endif #ifdef Q_OS_DARWIN - #include - #include +#include +#include #endif #ifdef HAVE_LIBLASTFM - #include "internet/lastfmservice.h" +#include "internet/lastfmservice.h" #else - class LastFMService; +class LastFMService; #endif #ifdef HAVE_DBUS - #include "core/mpris.h" - #include "core/mpris2.h" - #include - #include +#include "core/mpris.h" +#include "core/mpris2.h" +#include +#include - QDBusArgument& operator<< (QDBusArgument& arg, const QImage& image); - const QDBusArgument& operator>> (const QDBusArgument& arg, QImage& image); +QDBusArgument& operator<<(QDBusArgument& arg, const QImage& image); +const QDBusArgument& operator>>(const QDBusArgument& arg, QImage& image); #endif #ifdef Q_OS_WIN32 -# include +#include #endif // Load sqlite plugin on windows and mac. @@ -119,7 +119,8 @@ void LoadTranslation(const QString& prefix, const QString& path, // without checking if it's a file first. // This was fixed in Qt 4.7 QFileInfo maybe_clementine_directory(path + "/clementine"); - if (maybe_clementine_directory.exists() && !maybe_clementine_directory.isFile()) + if (maybe_clementine_directory.exists() && + !maybe_clementine_directory.isFile()) return; #endif @@ -133,7 +134,8 @@ void LoadTranslation(const QString& prefix, const QString& path, void IncreaseFDLimit() { #ifdef Q_OS_DARWIN - // Bump the soft limit for the number of file descriptors from the default of 256 to + // Bump the soft limit for the number of file descriptors from the default of + // 256 to // the maximum (usually 10240). struct rlimit limit; getrlimit(RLIMIT_NOFILE, &limit); @@ -152,7 +154,7 @@ void IncreaseFDLimit() { #endif } -void SetEnv(const char *key, const QString &value) { +void SetEnv(const char* key, const QString& value) { #ifdef Q_OS_WIN32 putenv(QString("%1=%2").arg(key, value).toLocal8Bit().constData()); #else @@ -167,20 +169,22 @@ void SetGstreamerEnvironment() { QString plugin_path; QString registry_filename; - // On windows and mac we bundle the gstreamer plugins with clementine +// On windows and mac we bundle the gstreamer plugins with clementine #if defined(Q_OS_DARWIN) - scanner_path = QCoreApplication::applicationDirPath() + "/../PlugIns/gst-plugin-scanner"; - plugin_path = QCoreApplication::applicationDirPath() + "/../PlugIns/gstreamer"; + scanner_path = + QCoreApplication::applicationDirPath() + "/../PlugIns/gst-plugin-scanner"; + plugin_path = + QCoreApplication::applicationDirPath() + "/../PlugIns/gstreamer"; #elif defined(Q_OS_WIN32) plugin_path = QCoreApplication::applicationDirPath() + "/gstreamer-plugins"; #endif #if defined(Q_OS_WIN32) || defined(Q_OS_DARWIN) - registry_filename = Utilities::GetConfigPath(Utilities::Path_GstreamerRegistry); + registry_filename = + Utilities::GetConfigPath(Utilities::Path_GstreamerRegistry); #endif - if (!scanner_path.isEmpty()) - SetEnv("GST_PLUGIN_SCANNER", scanner_path); + if (!scanner_path.isEmpty()) SetEnv("GST_PLUGIN_SCANNER", scanner_path); if (!plugin_path.isEmpty()) { SetEnv("GST_PLUGIN_PATH", plugin_path); @@ -194,13 +198,13 @@ void SetGstreamerEnvironment() { #ifdef Q_OS_DARWIN SetEnv("GIO_EXTRA_MODULES", - QCoreApplication::applicationDirPath() + "/../PlugIns/gio-modules"); + QCoreApplication::applicationDirPath() + "/../PlugIns/gio-modules"); #endif } #ifdef HAVE_GIO -# undef signals // Clashes with GIO, and not needed in this file -# include +#undef signals // Clashes with GIO, and not needed in this file +#include void ScanGIOModulePath() { QString gio_module_path; @@ -219,11 +223,11 @@ void ScanGIOModulePath() { void ParseAProto() { const QByteArray data = QByteArray::fromHex( - "08001a8b010a8801b2014566696c653a2f2f2f453a2f4d7573696b2f28414c42554d2" - "9253230476f74616e25323050726f6a6563742532302d253230416d6269656e742532" - "304c6f756e67652e6d786dba012a28414c42554d2920476f74616e2050726f6a65637" - "4202d20416d6269656e74204c6f756e67652e6d786dc001c7a7efd104c801bad685e4" - "04d001eeca32"); + "08001a8b010a8801b2014566696c653a2f2f2f453a2f4d7573696b2f28414c42554d2" + "9253230476f74616e25323050726f6a6563742532302d253230416d6269656e742532" + "304c6f756e67652e6d786dba012a28414c42554d2920476f74616e2050726f6a65637" + "4202d20416d6269656e74204c6f756e67652e6d786dc001c7a7efd104c801bad685e4" + "04d001eeca32"); pb::tagreader::Message message; message.ParseFromArray(data.constData(), data.size()); } @@ -236,11 +240,12 @@ void CheckPortable() { Application::kIsPortable = true; QSettings::setDefaultFormat(QSettings::IniFormat); - QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, f.fileName()); + QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, + f.fileName()); } } -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { if (CrashReporting::SendCrashReport(argc, argv)) { return 0; } @@ -264,7 +269,7 @@ int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("Clementine"); QCoreApplication::setOrganizationDomain("clementine-player.org"); - // This makes us show up nicely in gnome-volume-control +// This makes us show up nicely in gnome-volume-control #if !GLIB_CHECK_VERSION(2, 36, 0) g_type_init(); // Deprecated in glib 2.36.0 #endif @@ -285,12 +290,12 @@ int main(int argc, char *argv[]) { // Parse commandline options - need to do this before starting the // full QApplication so it works without an X server - if (!options.Parse()) - return 1; + if (!options.Parse()) return 1; if (a.isRunning()) { if (options.is_empty()) { - qLog(Info) << "Clementine is already running - activating existing window"; + qLog(Info) + << "Clementine is already running - activating existing window"; } if (a.sendMessage(options.Serialize(), 5000)) { return 0; @@ -301,7 +306,10 @@ int main(int argc, char *argv[]) { #ifdef Q_OS_DARWIN // Must happen after QCoreApplication::setOrganizationName(). - setenv("XDG_CONFIG_HOME", Utilities::GetConfigPath(Utilities::Path_Root).toLocal8Bit().constData(), 1); + setenv( + "XDG_CONFIG_HOME", + Utilities::GetConfigPath(Utilities::Path_Root).toLocal8Bit().constData(), + 1); #endif #ifdef HAVE_LIBLASTFM @@ -313,7 +321,8 @@ int main(int argc, char *argv[]) { // Initialise logging logging::Init(); logging::SetLevels(options.log_levels()); - g_log_set_default_handler(reinterpret_cast(&logging::GLog), nullptr); + g_log_set_default_handler(reinterpret_cast(&logging::GLog), + nullptr); // Output the version, so when people attach log output to bug reports they // don't have to tell us which version they're using. @@ -334,8 +343,8 @@ int main(int argc, char *argv[]) { QSettings qt_settings(QSettings::UserScope, "Trolltech"); qt_settings.beginGroup("Qt"); QApplication::setWheelScrollLines( - qt_settings.value("wheelScrollLines", - QApplication::wheelScrollLines()).toInt()); + qt_settings.value("wheelScrollLines", QApplication::wheelScrollLines()) + .toInt()); } #ifdef Q_OS_DARWIN @@ -362,9 +371,9 @@ int main(int argc, char *argv[]) { SetGstreamerEnvironment(); - // Set the permissions on the config file on Unix - it can contain passwords - // for internet services so it's important that other users can't read it. - // On Windows these are stored in the registry instead. +// Set the permissions on the config file on Unix - it can contain passwords +// for internet services so it's important that other users can't read it. +// On Windows these are stored in the registry instead. #ifdef Q_OS_UNIX { QSettings s; @@ -395,7 +404,7 @@ int main(int argc, char *argv[]) { // that CA to the default list used by QSslSocket, so it always works in // Clementine. QSslSocket::addDefaultCaCertificates( - QSslCertificate::fromPath(":/grooveshark-valicert-ca.pem", QSsl::Pem)); + QSslCertificate::fromPath(":/grooveshark-valicert-ca.pem", QSsl::Pem)); // Has the user forced a different language? QString override_language = options.language(); @@ -405,11 +414,13 @@ int main(int argc, char *argv[]) { override_language = s.value("language").toString(); } - const QString language = override_language.isEmpty() ? - Utilities::SystemLanguageName() : override_language; + const QString language = override_language.isEmpty() + ? Utilities::SystemLanguageName() + : override_language; // Translations - LoadTranslation("qt", QLibraryInfo::location(QLibraryInfo::TranslationsPath), language); + LoadTranslation("qt", QLibraryInfo::location(QLibraryInfo::TranslationsPath), + language); LoadTranslation("clementine", ":/translations", language); LoadTranslation("clementine", a.applicationDirPath(), language); LoadTranslation("clementine", QDir::currentPath(), language); @@ -432,7 +443,8 @@ int main(int argc, char *argv[]) { app.set_language_name(language); Echonest::Config::instance()->setAPIKey("DFLFLJBUF4EGTXHIG"); - Echonest::Config::instance()->setNetworkAccessManager(new NetworkAccessManager); + Echonest::Config::instance()->setNetworkAccessManager( + new NetworkAccessManager); // Network proxy QNetworkProxyFactory::setApplicationProxyFactory( @@ -449,10 +461,11 @@ int main(int argc, char *argv[]) { // whitelisted applications. Clementine will override this setting and insert // itself into the list of whitelisted apps. UbuntuUnityHack hack; -#endif // Q_OS_LINUX +#endif // Q_OS_LINUX // Create the tray icon and OSD - std::unique_ptr tray_icon(SystemTrayIcon::CreateSystemTrayIcon()); + std::unique_ptr tray_icon( + SystemTrayIcon::CreateSystemTrayIcon()); OSD osd(tray_icon.get(), &app); #ifdef HAVE_DBUS @@ -470,7 +483,8 @@ int main(int argc, char *argv[]) { #ifdef HAVE_DBUS QObject::connect(&mpris, SIGNAL(RaiseMainWindow()), &w, SLOT(Raise())); #endif - QObject::connect(&a, SIGNAL(messageReceived(QByteArray)), &w, SLOT(CommandlineOptionsReceived(QByteArray))); + QObject::connect(&a, SIGNAL(messageReceived(QByteArray)), &w, + SLOT(CommandlineOptionsReceived(QByteArray))); w.CommandlineOptionsReceived(options); int ret = a.exec(); diff --git a/src/moodbar/moodbarcontroller.cpp b/src/moodbar/moodbarcontroller.cpp index 6241edca1..8cd0f5180 100644 --- a/src/moodbar/moodbarcontroller.cpp +++ b/src/moodbar/moodbarcontroller.cpp @@ -25,11 +25,9 @@ #include "playlist/playlistmanager.h" MoodbarController::MoodbarController(Application* app, QObject* parent) - : QObject(parent), - app_(app) -{ - connect(app_->playlist_manager(), - SIGNAL(CurrentSongChanged(Song)), SLOT(CurrentSongChanged(Song))); + : QObject(parent), app_(app) { + connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), + SLOT(CurrentSongChanged(Song))); connect(app_->player(), SIGNAL(Stopped()), SLOT(PlaybackStopped())); } @@ -40,23 +38,23 @@ void MoodbarController::CurrentSongChanged(const Song& song) { app_->moodbar_loader()->Load(song.url(), &data, &pipeline); switch (result) { - case MoodbarLoader::CannotLoad: - emit CurrentMoodbarDataChanged(QByteArray()); - break; + case MoodbarLoader::CannotLoad: + emit CurrentMoodbarDataChanged(QByteArray()); + break; - case MoodbarLoader::Loaded: - emit CurrentMoodbarDataChanged(data); - break; + case MoodbarLoader::Loaded: + emit CurrentMoodbarDataChanged(data); + break; - case MoodbarLoader::WillLoadAsync: - // Emit an empty array for now so the GUI reverts to a normal progress - // bar. Our slot will be called when the data is actually loaded. - emit CurrentMoodbarDataChanged(QByteArray()); + case MoodbarLoader::WillLoadAsync: + // Emit an empty array for now so the GUI reverts to a normal progress + // bar. Our slot will be called when the data is actually loaded. + emit CurrentMoodbarDataChanged(QByteArray()); - NewClosure(pipeline, SIGNAL(Finished(bool)), - this, SLOT(AsyncLoadComplete(MoodbarPipeline*,QUrl)), - pipeline, song.url()); - break; + NewClosure(pipeline, SIGNAL(Finished(bool)), this, + SLOT(AsyncLoadComplete(MoodbarPipeline*, QUrl)), pipeline, + song.url()); + break; } } diff --git a/src/moodbar/moodbarcontroller.h b/src/moodbar/moodbarcontroller.h index a236fa9ee..b695aedf8 100644 --- a/src/moodbar/moodbarcontroller.h +++ b/src/moodbar/moodbarcontroller.h @@ -28,20 +28,20 @@ class QUrl; class MoodbarController : public QObject { Q_OBJECT - -public: + + public: MoodbarController(Application* app, QObject* parent = 0); signals: void CurrentMoodbarDataChanged(const QByteArray& data); - -private slots: + + private slots: void CurrentSongChanged(const Song& song); void PlaybackStopped(); void AsyncLoadComplete(MoodbarPipeline* pipeline, const QUrl& url); - -private: + + private: Application* app_; }; -#endif // MOODBARCONTROLLER_H +#endif // MOODBARCONTROLLER_H diff --git a/src/moodbar/moodbaritemdelegate.cpp b/src/moodbar/moodbaritemdelegate.cpp index 4a52d3315..5acd0648d 100644 --- a/src/moodbar/moodbaritemdelegate.cpp +++ b/src/moodbar/moodbaritemdelegate.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -31,18 +31,14 @@ #include #include -MoodbarItemDelegate::Data::Data() - : state_(State_None) -{ -} +MoodbarItemDelegate::Data::Data() : state_(State_None) {} MoodbarItemDelegate::MoodbarItemDelegate(Application* app, PlaylistView* view, QObject* parent) - : QItemDelegate(parent), - app_(app), - view_(view), - style_(MoodbarRenderer::Style_Normal) -{ + : QItemDelegate(parent), + app_(app), + view_(view), + style_(MoodbarRenderer::Style_Normal) { connect(app_, SIGNAL(SettingsChanged()), SLOT(ReloadSettings())); ReloadSettings(); } @@ -52,7 +48,7 @@ void MoodbarItemDelegate::ReloadSettings() { s.beginGroup("Moodbar"); MoodbarRenderer::MoodbarStyle new_style = static_cast( - s.value("style", MoodbarRenderer::Style_Normal).toInt()); + s.value("style", MoodbarRenderer::Style_Normal).toInt()); if (new_style != style_) { style_ = new_style; @@ -60,14 +56,14 @@ void MoodbarItemDelegate::ReloadSettings() { } } -void MoodbarItemDelegate::paint( - QPainter* painter, const QStyleOptionViewItem& option, - const QModelIndex& index) const { - QPixmap pixmap = const_cast(this)->PixmapForIndex( - index, option.rect.size()); +void MoodbarItemDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { + QPixmap pixmap = const_cast(this) + ->PixmapForIndex(index, option.rect.size()); drawBackground(painter, option, index); - + if (!pixmap.isNull()) { // Make a little border for the moodbar const QRect moodbar_rect(option.rect.adjusted(1, 1, -1, -1)); @@ -75,10 +71,11 @@ void MoodbarItemDelegate::paint( } } -QPixmap MoodbarItemDelegate::PixmapForIndex( - const QModelIndex& index, const QSize& size) { +QPixmap MoodbarItemDelegate::PixmapForIndex(const QModelIndex& index, + const QSize& size) { // Pixmaps are keyed off URL. - const QUrl url(index.sibling(index.row(), Playlist::Column_Filename).data().toUrl()); + const QUrl url( + index.sibling(index.row(), Playlist::Column_Filename).data().toUrl()); Data* data = data_[url]; if (!data) { @@ -90,22 +87,22 @@ QPixmap MoodbarItemDelegate::PixmapForIndex( data->desired_size_ = size; switch (data->state_) { - case Data::State_CannotLoad: - case Data::State_LoadingData: - case Data::State_LoadingColors: - case Data::State_LoadingImage: - return data->pixmap_; + case Data::State_CannotLoad: + case Data::State_LoadingData: + case Data::State_LoadingColors: + case Data::State_LoadingImage: + return data->pixmap_; - case Data::State_Loaded: - // Is the pixmap the right size? - if (data->pixmap_.size() != size) { - StartLoadingImage(url, data); - } + case Data::State_Loaded: + // Is the pixmap the right size? + if (data->pixmap_.size() != size) { + StartLoadingImage(url, data); + } - return data->pixmap_; + return data->pixmap_; - case Data::State_None: - break; + case Data::State_None: + break; } // We have to start loading the data from scratch. @@ -121,26 +118,26 @@ void MoodbarItemDelegate::StartLoadingData(const QUrl& url, Data* data) { QByteArray bytes; MoodbarPipeline* pipeline = nullptr; switch (app_->moodbar_loader()->Load(url, &bytes, &pipeline)) { - case MoodbarLoader::CannotLoad: - data->state_ = Data::State_CannotLoad; - break; + case MoodbarLoader::CannotLoad: + data->state_ = Data::State_CannotLoad; + break; - case MoodbarLoader::Loaded: - // We got the data immediately. - StartLoadingColors(url, bytes, data); - break; + case MoodbarLoader::Loaded: + // We got the data immediately. + StartLoadingColors(url, bytes, data); + break; - case MoodbarLoader::WillLoadAsync: - // Maybe in a little while. - NewClosure(pipeline, SIGNAL(Finished(bool)), - this, SLOT(DataLoaded(QUrl,MoodbarPipeline*)), - url, pipeline); - break; + case MoodbarLoader::WillLoadAsync: + // Maybe in a little while. + NewClosure(pipeline, SIGNAL(Finished(bool)), this, + SLOT(DataLoaded(QUrl, MoodbarPipeline*)), url, pipeline); + break; } } -bool MoodbarItemDelegate::RemoveFromCacheIfIndexesInvalid(const QUrl& url, Data* data) { - foreach (const QPersistentModelIndex& index, data->indexes_) { +bool MoodbarItemDelegate::RemoveFromCacheIfIndexesInvalid(const QUrl& url, + Data* data) { + foreach(const QPersistentModelIndex & index, data->indexes_) { if (index.isValid()) { return false; } @@ -151,7 +148,7 @@ bool MoodbarItemDelegate::RemoveFromCacheIfIndexesInvalid(const QUrl& url, Data* } void MoodbarItemDelegate::ReloadAllColors() { - foreach (const QUrl& url, data_.keys()) { + foreach(const QUrl & url, data_.keys()) { Data* data = data_[url]; if (data->state_ == Data::State_Loaded) { @@ -160,7 +157,8 @@ void MoodbarItemDelegate::ReloadAllColors() { } } -void MoodbarItemDelegate::DataLoaded( const QUrl& url, MoodbarPipeline* pipeline) { +void MoodbarItemDelegate::DataLoaded(const QUrl& url, + MoodbarPipeline* pipeline) { Data* data = data_[url]; if (!data) { return; @@ -179,22 +177,23 @@ void MoodbarItemDelegate::DataLoaded( const QUrl& url, MoodbarPipeline* pipeline StartLoadingColors(url, pipeline->data(), data); } -void MoodbarItemDelegate::StartLoadingColors( - const QUrl& url, const QByteArray& bytes, Data* data) { +void MoodbarItemDelegate::StartLoadingColors(const QUrl& url, + const QByteArray& bytes, + Data* data) { data->state_ = Data::State_LoadingColors; QFutureWatcher* watcher = new QFutureWatcher(); - NewClosure(watcher, SIGNAL(finished()), - this, SLOT(ColorsLoaded(QUrl,QFutureWatcher*)), - url, watcher); + NewClosure(watcher, SIGNAL(finished()), this, + SLOT(ColorsLoaded(QUrl, QFutureWatcher*)), url, + watcher); - QFuture future = QtConcurrent::run(MoodbarRenderer::Colors, - bytes, style_, qApp->palette()); + QFuture future = QtConcurrent::run( + MoodbarRenderer::Colors, bytes, style_, qApp->palette()); watcher->setFuture(future); } -void MoodbarItemDelegate::ColorsLoaded( - const QUrl& url, QFutureWatcher* watcher) { +void MoodbarItemDelegate::ColorsLoaded(const QUrl& url, + QFutureWatcher* watcher) { watcher->deleteLater(); Data* data = data_[url]; @@ -216,16 +215,16 @@ void MoodbarItemDelegate::StartLoadingImage(const QUrl& url, Data* data) { data->state_ = Data::State_LoadingImage; QFutureWatcher* watcher = new QFutureWatcher(); - NewClosure(watcher, SIGNAL(finished()), - this, SLOT(ImageLoaded(QUrl,QFutureWatcher*)), - url, watcher); + NewClosure(watcher, SIGNAL(finished()), this, + SLOT(ImageLoaded(QUrl, QFutureWatcher*)), url, watcher); - QFuture future = QtConcurrent::run(MoodbarRenderer::RenderToImage, - data->colors_, data->desired_size_); + QFuture future = QtConcurrent::run( + MoodbarRenderer::RenderToImage, data->colors_, data->desired_size_); watcher->setFuture(future); } -void MoodbarItemDelegate::ImageLoaded(const QUrl& url, QFutureWatcher* watcher) { +void MoodbarItemDelegate::ImageLoaded(const QUrl& url, + QFutureWatcher* watcher) { watcher->deleteLater(); Data* data = data_[url]; @@ -248,13 +247,15 @@ void MoodbarItemDelegate::ImageLoaded(const QUrl& url, QFutureWatcher* w data->pixmap_ = QPixmap::fromImage(image); data->state_ = Data::State_Loaded; - + Playlist* playlist = view_->playlist(); const QSortFilterProxyModel* filter = playlist->proxy(); // Update all the indices with the new pixmap. - foreach (const QPersistentModelIndex& index, data->indexes_) { - if (index.isValid() && index.sibling(index.row(), Playlist::Column_Filename).data().toUrl() == url) { + foreach(const QPersistentModelIndex & index, data->indexes_) { + if (index.isValid() && + index.sibling(index.row(), Playlist::Column_Filename).data().toUrl() == + url) { QModelIndex source_index = index; if (index.model() == filter) { source_index = filter->mapToSource(source_index); diff --git a/src/moodbar/moodbaritemdelegate.h b/src/moodbar/moodbaritemdelegate.h index 413326875..dc3df6bbb 100644 --- a/src/moodbar/moodbaritemdelegate.h +++ b/src/moodbar/moodbaritemdelegate.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -34,20 +34,21 @@ class QModelIndex; class MoodbarItemDelegate : public QItemDelegate { Q_OBJECT -public: - MoodbarItemDelegate(Application* app, PlaylistView* view, QObject* parent = 0); + public: + MoodbarItemDelegate(Application* app, PlaylistView* view, + QObject* parent = 0); void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; -private slots: + private slots: void ReloadSettings(); void DataLoaded(const QUrl& url, MoodbarPipeline* pipeline); void ColorsLoaded(const QUrl& url, QFutureWatcher* watcher); void ImageLoaded(const QUrl& url, QFutureWatcher* watcher); -private: + private: struct Data { Data(); @@ -68,7 +69,7 @@ private: QPixmap pixmap_; }; -private: + private: QPixmap PixmapForIndex(const QModelIndex& index, const QSize& size); void StartLoadingData(const QUrl& url, Data* data); void StartLoadingColors(const QUrl& url, const QByteArray& bytes, Data* data); @@ -78,7 +79,7 @@ private: void ReloadAllColors(); -private: + private: Application* app_; PlaylistView* view_; QCache data_; @@ -86,4 +87,4 @@ private: MoodbarRenderer::MoodbarStyle style_; }; -#endif // MOODBARITEMDELEGATE_H +#endif // MOODBARITEMDELEGATE_H diff --git a/src/moodbar/moodbarloader.cpp b/src/moodbar/moodbarloader.cpp index 2bface572..f81bd00c2 100644 --- a/src/moodbar/moodbarloader.cpp +++ b/src/moodbar/moodbarloader.cpp @@ -35,15 +35,16 @@ #include "core/utilities.h" MoodbarLoader::MoodbarLoader(Application* app, QObject* parent) - : QObject(parent), - cache_(new QNetworkDiskCache(this)), - thread_(new QThread(this)), - kMaxActiveRequests(qMax(1, QThread::idealThreadCount() / 2)), - save_alongside_originals_(false), - disable_moodbar_calculation_(false) -{ - cache_->setCacheDirectory(Utilities::GetConfigPath(Utilities::Path_MoodbarCache)); - cache_->setMaximumCacheSize(60 * 1024 * 1024); // 60MB - enough for 20,000 moodbars + : QObject(parent), + cache_(new QNetworkDiskCache(this)), + thread_(new QThread(this)), + kMaxActiveRequests(qMax(1, QThread::idealThreadCount() / 2)), + save_alongside_originals_(false), + disable_moodbar_calculation_(false) { + cache_->setCacheDirectory( + Utilities::GetConfigPath(Utilities::Path_MoodbarCache)); + cache_->setMaximumCacheSize(60 * 1024 * + 1024); // 60MB - enough for 20,000 moodbars connect(app, SIGNAL(SettingsChanged()), SLOT(ReloadSettings())); ReloadSettings(); @@ -57,7 +58,8 @@ MoodbarLoader::~MoodbarLoader() { void MoodbarLoader::ReloadSettings() { QSettings s; s.beginGroup("Moodbar"); - save_alongside_originals_ = s.value("save_alongside_originals", false).toBool(); + save_alongside_originals_ = + s.value("save_alongside_originals", false).toBool(); disable_moodbar_calculation_ = !s.value("calculate", true).toBool(); MaybeTakeNextRequest(); @@ -76,8 +78,8 @@ QStringList MoodbarLoader::MoodFilenames(const QString& song_filename) { << dir_path + "/" + mood_filename; } -MoodbarLoader::Result MoodbarLoader::Load( - const QUrl& url, QByteArray* data, MoodbarPipeline** async_pipeline) { +MoodbarLoader::Result MoodbarLoader::Load(const QUrl& url, QByteArray* data, + MoodbarPipeline** async_pipeline) { if (url.scheme() != "file") { return CannotLoad; } @@ -91,7 +93,7 @@ MoodbarLoader::Result MoodbarLoader::Load( // Check if a mood file exists for this file already const QString filename(url.toLocalFile()); - foreach (const QString& possible_mood_file, MoodFilenames(filename)) { + foreach(const QString & possible_mood_file, MoodFilenames(filename)) { QFile f(possible_mood_file); if (f.open(QIODevice::ReadOnly)) { qLog(Info) << "Loading moodbar data from" << possible_mood_file; @@ -110,15 +112,13 @@ MoodbarLoader::Result MoodbarLoader::Load( } } - if (!thread_->isRunning()) - thread_->start(QThread::IdlePriority); + if (!thread_->isRunning()) thread_->start(QThread::IdlePriority); // There was no existing file, analyze the audio file and create one. MoodbarPipeline* pipeline = new MoodbarPipeline(url); pipeline->moveToThread(thread_); - NewClosure(pipeline, SIGNAL(Finished(bool)), - this, SLOT(RequestFinished(MoodbarPipeline*,QUrl)), - pipeline, url); + NewClosure(pipeline, SIGNAL(Finished(bool)), this, + SLOT(RequestFinished(MoodbarPipeline*, QUrl)), pipeline, url); requests_[url] = pipeline; queued_requests_ << url; @@ -140,7 +140,6 @@ void MoodbarLoader::MaybeTakeNextRequest() { const QUrl url = queued_requests_.takeFirst(); active_requests_ << url; - qLog(Info) << "Creating moodbar data for" << url.toLocalFile(); QMetaObject::invokeMethod(requests_[url], "Start", Qt::QueuedConnection); } @@ -149,7 +148,8 @@ void MoodbarLoader::RequestFinished(MoodbarPipeline* request, const QUrl& url) { Q_ASSERT(QThread::currentThread() == qApp->thread()); if (request->success()) { - qLog(Info) << "Moodbar data generated successfully for" << url.toLocalFile(); + qLog(Info) << "Moodbar data generated successfully for" + << url.toLocalFile(); // Save the data in the cache QNetworkCacheMetaData metadata; diff --git a/src/moodbar/moodbarloader.h b/src/moodbar/moodbarloader.h index 43f467e1f..0dd0d953a 100644 --- a/src/moodbar/moodbarloader.h +++ b/src/moodbar/moodbarloader.h @@ -31,7 +31,7 @@ class MoodbarPipeline; class MoodbarLoader : public QObject { Q_OBJECT -public: + public: MoodbarLoader(Application* app, QObject* parent = 0); ~MoodbarLoader(); @@ -48,18 +48,19 @@ public: WillLoadAsync }; - Result Load(const QUrl& url, QByteArray* data, MoodbarPipeline** async_pipeline); + Result Load(const QUrl& url, QByteArray* data, + MoodbarPipeline** async_pipeline); -private slots: + private slots: void ReloadSettings(); void RequestFinished(MoodbarPipeline* request, const QUrl& filename); void MaybeTakeNextRequest(); -private: + private: static QStringList MoodFilenames(const QString& song_filename); -private: + private: QNetworkDiskCache* cache_; QThread* thread_; @@ -73,4 +74,4 @@ private: bool disable_moodbar_calculation_; }; -#endif // MOODBARLOADER_H +#endif // MOODBARLOADER_H diff --git a/src/moodbar/moodbarpipeline.cpp b/src/moodbar/moodbarpipeline.cpp index 6937233bf..1de26e6c6 100644 --- a/src/moodbar/moodbarpipeline.cpp +++ b/src/moodbar/moodbarpipeline.cpp @@ -28,17 +28,13 @@ bool MoodbarPipeline::sIsAvailable = false; MoodbarPipeline::MoodbarPipeline(const QUrl& local_filename) - : QObject(nullptr), - local_filename_(local_filename), - pipeline_(nullptr), - convert_element_(nullptr), - success_(false) -{ -} + : QObject(nullptr), + local_filename_(local_filename), + pipeline_(nullptr), + convert_element_(nullptr), + success_(false) {} -MoodbarPipeline::~MoodbarPipeline() { - Cleanup(); -} +MoodbarPipeline::~MoodbarPipeline() { Cleanup(); } bool MoodbarPipeline::IsAvailable() { if (!sIsAvailable) { @@ -61,7 +57,8 @@ bool MoodbarPipeline::IsAvailable() { } GstElement* MoodbarPipeline::CreateElement(const QString& factory_name) { - GstElement* ret = gst_element_factory_make(factory_name.toAscii().constData(), nullptr); + GstElement* ret = + gst_element_factory_make(factory_name.toAscii().constData(), nullptr); if (ret) { gst_bin_add(GST_BIN(pipeline_), ret); @@ -83,39 +80,42 @@ void MoodbarPipeline::Start() { pipeline_ = gst_pipeline_new("moodbar-pipeline"); - GstElement* decodebin = CreateElement("uridecodebin"); - convert_element_ = CreateElement("audioconvert"); + GstElement* decodebin = CreateElement("uridecodebin"); + convert_element_ = CreateElement("audioconvert"); GstElement* fftwspectrum = CreateElement("fftwspectrum"); - GstElement* moodbar = CreateElement("moodbar"); - GstElement* appsink = CreateElement("appsink"); + GstElement* moodbar = CreateElement("moodbar"); + GstElement* appsink = CreateElement("appsink"); - if (!decodebin || !convert_element_ || !fftwspectrum || !moodbar || !appsink) { + if (!decodebin || !convert_element_ || !fftwspectrum || !moodbar || + !appsink) { pipeline_ = nullptr; emit Finished(false); return; } // Join them together - gst_element_link_many(convert_element_, fftwspectrum, moodbar, appsink, nullptr); + gst_element_link_many(convert_element_, fftwspectrum, moodbar, appsink, + nullptr); // Set properties - g_object_set(decodebin, "uri", local_filename_.toEncoded().constData(), nullptr); - g_object_set(fftwspectrum, "def-size", 2048, - "def-step", 1024, - "hiquality", true, nullptr); - g_object_set(moodbar, "height", 1, - "max-width", 1000, nullptr); + g_object_set(decodebin, "uri", local_filename_.toEncoded().constData(), + nullptr); + g_object_set(fftwspectrum, "def-size", 2048, "def-step", 1024, "hiquality", + true, nullptr); + g_object_set(moodbar, "height", 1, "max-width", 1000, nullptr); // Connect signals CHECKED_GCONNECT(decodebin, "pad-added", &NewPadCallback, this); - gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), BusCallbackSync, this); + gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), + BusCallbackSync, this); // Set appsink callbacks GstAppSinkCallbacks callbacks; memset(&callbacks, 0, sizeof(callbacks)); callbacks.new_buffer = NewBufferCallback; - gst_app_sink_set_callbacks(reinterpret_cast(appsink), &callbacks, this, nullptr); + gst_app_sink_set_callbacks(reinterpret_cast(appsink), &callbacks, + this, nullptr); // Start playing gst_element_set_state(pipeline_, GST_STATE_PLAYING); @@ -136,8 +136,8 @@ void MoodbarPipeline::ReportError(GstMessage* msg) { void MoodbarPipeline::NewPadCallback(GstElement*, GstPad* pad, gpointer data) { MoodbarPipeline* self = reinterpret_cast(data); - GstPad* const audiopad = gst_element_get_static_pad( - self->convert_element_, "sink"); + GstPad* const audiopad = + gst_element_get_static_pad(self->convert_element_, "sink"); if (GST_PAD_IS_LINKED(audiopad)) { qLog(Warning) << "audiopad is already linked, unlinking old pad"; @@ -148,7 +148,8 @@ void MoodbarPipeline::NewPadCallback(GstElement*, GstPad* pad, gpointer data) { gst_object_unref(audiopad); } -GstFlowReturn MoodbarPipeline::NewBufferCallback(GstAppSink* app_sink, gpointer data) { +GstFlowReturn MoodbarPipeline::NewBufferCallback(GstAppSink* app_sink, + gpointer data) { MoodbarPipeline* self = reinterpret_cast(data); GstBuffer* buffer = gst_app_sink_pull_buffer(app_sink); @@ -158,7 +159,8 @@ GstFlowReturn MoodbarPipeline::NewBufferCallback(GstAppSink* app_sink, gpointer return GST_FLOW_OK; } -GstBusSyncReply MoodbarPipeline::BusCallbackSync(GstBus*, GstMessage* msg, gpointer data) { +GstBusSyncReply MoodbarPipeline::BusCallbackSync(GstBus*, GstMessage* msg, + gpointer data) { MoodbarPipeline* self = reinterpret_cast(data); switch (GST_MESSAGE_TYPE(msg)) { @@ -187,8 +189,8 @@ void MoodbarPipeline::Cleanup() { Q_ASSERT(QThread::currentThread() != qApp->thread()); if (pipeline_) { - gst_bus_set_sync_handler( - gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), nullptr,nullptr); + gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), + nullptr, nullptr); gst_element_set_state(pipeline_, GST_STATE_NULL); gst_object_unref(pipeline_); pipeline_ = nullptr; diff --git a/src/moodbar/moodbarpipeline.h b/src/moodbar/moodbarpipeline.h index 5978fc89a..63374176e 100644 --- a/src/moodbar/moodbarpipeline.h +++ b/src/moodbar/moodbarpipeline.h @@ -28,7 +28,7 @@ class MoodbarPipeline : public QObject { Q_OBJECT -public: + public: MoodbarPipeline(const QUrl& local_filename); ~MoodbarPipeline(); @@ -37,13 +37,13 @@ public: bool success() const { return success_; } const QByteArray& data() const { return data_; } -public slots: + public slots: void Start(); signals: void Finished(bool success); -private: + private: GstElement* CreateElement(const QString& factory_name); void ReportError(GstMessage* message); @@ -53,9 +53,10 @@ private: static void NewPadCallback(GstElement*, GstPad* pad, gpointer data); static GstFlowReturn NewBufferCallback(GstAppSink* app_sink, gpointer self); static gboolean BusCallback(GstBus*, GstMessage* msg, gpointer data); - static GstBusSyncReply BusCallbackSync(GstBus*, GstMessage* msg, gpointer data); + static GstBusSyncReply BusCallbackSync(GstBus*, GstMessage* msg, + gpointer data); -private: + private: static bool sIsAvailable; QUrl local_filename_; @@ -66,4 +67,4 @@ private: QByteArray data_; }; -#endif // MOODBARPIPELINE_H +#endif // MOODBARPIPELINE_H diff --git a/src/moodbar/moodbarproxystyle.cpp b/src/moodbar/moodbarproxystyle.cpp index 10d98ead1..b24ff1cd0 100644 --- a/src/moodbar/moodbarproxystyle.cpp +++ b/src/moodbar/moodbarproxystyle.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -35,23 +35,23 @@ const int MoodbarProxyStyle::kArrowWidth = 17; const int MoodbarProxyStyle::kArrowHeight = 13; MoodbarProxyStyle::MoodbarProxyStyle(Application* app, QSlider* slider) - : QProxyStyle(slider->style()), - app_(app), - slider_(slider), - enabled_(true), - moodbar_style_(MoodbarRenderer::Style_Normal), - state_(MoodbarOff), - fade_timeline_(new QTimeLine(1000, this)), - moodbar_colors_dirty_(true), - moodbar_pixmap_dirty_(true), - context_menu_(nullptr), - show_moodbar_action_(nullptr), - style_action_group_(nullptr) -{ + : QProxyStyle(slider->style()), + app_(app), + slider_(slider), + enabled_(true), + moodbar_style_(MoodbarRenderer::Style_Normal), + state_(MoodbarOff), + fade_timeline_(new QTimeLine(1000, this)), + moodbar_colors_dirty_(true), + moodbar_pixmap_dirty_(true), + context_menu_(nullptr), + show_moodbar_action_(nullptr), + style_action_group_(nullptr) { slider->setStyle(this); slider->installEventFilter(this); - connect(fade_timeline_, SIGNAL(valueChanged(qreal)), SLOT(FaderValueChanged(qreal))); + connect(fade_timeline_, SIGNAL(valueChanged(qreal)), + SLOT(FaderValueChanged(qreal))); connect(app, SIGNAL(SettingsChanged()), SLOT(ReloadSettings())); ReloadSettings(); @@ -69,7 +69,7 @@ void MoodbarProxyStyle::ReloadSettings() { // Get the style, and redraw if there's a change. MoodbarRenderer::MoodbarStyle new_style = static_cast( - s.value("style", MoodbarRenderer::Style_Normal).toInt()); + s.value("style", MoodbarRenderer::Style_Normal).toInt()); if (new_style != moodbar_style_) { moodbar_style_ = new_style; @@ -80,7 +80,7 @@ void MoodbarProxyStyle::ReloadSettings() { void MoodbarProxyStyle::SetMoodbarData(const QByteArray& data) { data_ = data; - moodbar_colors_dirty_ = true; // Redraw next time + moodbar_colors_dirty_ = true; // Redraw next time NextState(); } @@ -102,7 +102,7 @@ void MoodbarProxyStyle::NextState() { show_moodbar_action_->setChecked(enabled_); } - if ((visible && (state_ == MoodbarOn || state_ == FadingToOn)) || + if ((visible && (state_ == MoodbarOn || state_ == FadingToOn)) || (!visible && (state_ == MoodbarOff || state_ == FadingToOff))) { return; } @@ -128,46 +128,45 @@ void MoodbarProxyStyle::NextState() { state_ = visible ? FadingToOn : FadingToOff; } -void MoodbarProxyStyle::FaderValueChanged(qreal value) { - slider_->update(); -} +void MoodbarProxyStyle::FaderValueChanged(qreal value) { slider_->update(); } bool MoodbarProxyStyle::eventFilter(QObject* object, QEvent* event) { if (object == slider_) { switch (event->type()) { - case QEvent::Resize: - // The widget was resized, we've got to render a new pixmap. - moodbar_pixmap_dirty_ = true; - break; + case QEvent::Resize: + // The widget was resized, we've got to render a new pixmap. + moodbar_pixmap_dirty_ = true; + break; - case QEvent::ContextMenu: - ShowContextMenu(static_cast(event)->globalPos()); - return true; + case QEvent::ContextMenu: + ShowContextMenu(static_cast(event)->globalPos()); + return true; - default: - break; + default: + break; } } return QProxyStyle::eventFilter(object, event); } -void MoodbarProxyStyle::drawComplexControl( - ComplexControl control, const QStyleOptionComplex* option, - QPainter* painter, const QWidget* widget) const { +void MoodbarProxyStyle::drawComplexControl(ComplexControl control, + const QStyleOptionComplex* option, + QPainter* painter, + const QWidget* widget) const { if (control != CC_Slider || widget != slider_) { QProxyStyle::drawComplexControl(control, option, painter, widget); return; } - const_cast(this)->Render( - control, qstyleoption_cast(option), - painter, widget); + const_cast(this) + ->Render(control, qstyleoption_cast(option), + painter, widget); } -void MoodbarProxyStyle::Render( - ComplexControl control, const QStyleOptionSlider* option, - QPainter* painter, const QWidget* widget) { +void MoodbarProxyStyle::Render(ComplexControl control, + const QStyleOptionSlider* option, + QPainter* painter, const QWidget* widget) { const qreal fade_value = fade_timeline_->currentValue(); @@ -178,71 +177,74 @@ void MoodbarProxyStyle::Render( state_ = MoodbarOff; } - switch (state_) { - case FadingToOn: - case FadingToOff: - // Update the cached pixmaps if necessary - if (fade_source_.isNull()) { - // Draw the normal slider into the fade source pixmap. - fade_source_ = QPixmap(option->rect.size()); - fade_source_.fill(option->palette.color(QPalette::Active, QPalette::Background)); + case FadingToOn: + case FadingToOff: + // Update the cached pixmaps if necessary + if (fade_source_.isNull()) { + // Draw the normal slider into the fade source pixmap. + fade_source_ = QPixmap(option->rect.size()); + fade_source_.fill( + option->palette.color(QPalette::Active, QPalette::Background)); - QPainter p(&fade_source_); - QStyleOptionSlider opt_copy(*option); - opt_copy.rect.moveTo(0, 0); + QPainter p(&fade_source_); + QStyleOptionSlider opt_copy(*option); + opt_copy.rect.moveTo(0, 0); - QProxyStyle::drawComplexControl(control, &opt_copy, &p, widget); + QProxyStyle::drawComplexControl(control, &opt_copy, &p, widget); - p.end(); - } - - if (fade_target_.isNull()) { - if (state_ == FadingToOn) { - EnsureMoodbarRendered(); + p.end(); } - fade_target_ = moodbar_pixmap_; - QPainter p(&fade_target_); - DrawArrow(option, &p); - p.end(); - } - // Blend the pixmaps into each other - painter->drawPixmap(option->rect, fade_source_); - painter->setOpacity(fade_value); - painter->drawPixmap(option->rect, fade_target_); - painter->setOpacity(1.0); - break; + if (fade_target_.isNull()) { + if (state_ == FadingToOn) { + EnsureMoodbarRendered(); + } + fade_target_ = moodbar_pixmap_; + QPainter p(&fade_target_); + DrawArrow(option, &p); + p.end(); + } - case MoodbarOff: - // It's a normal slider widget. - QProxyStyle::drawComplexControl(control, option, painter, widget); - break; + // Blend the pixmaps into each other + painter->drawPixmap(option->rect, fade_source_); + painter->setOpacity(fade_value); + painter->drawPixmap(option->rect, fade_target_); + painter->setOpacity(1.0); + break; - case MoodbarOn: - EnsureMoodbarRendered(); - painter->drawPixmap(option->rect, moodbar_pixmap_); - DrawArrow(option, painter); - break; + case MoodbarOff: + // It's a normal slider widget. + QProxyStyle::drawComplexControl(control, option, painter, widget); + break; + + case MoodbarOn: + EnsureMoodbarRendered(); + painter->drawPixmap(option->rect, moodbar_pixmap_); + DrawArrow(option, painter); + break; } } void MoodbarProxyStyle::EnsureMoodbarRendered() { if (moodbar_colors_dirty_) { - moodbar_colors_ = MoodbarRenderer::Colors(data_, moodbar_style_, slider_->palette()); + moodbar_colors_ = + MoodbarRenderer::Colors(data_, moodbar_style_, slider_->palette()); moodbar_colors_dirty_ = false; moodbar_pixmap_dirty_ = true; } if (moodbar_pixmap_dirty_) { - moodbar_pixmap_ = MoodbarPixmap(moodbar_colors_, slider_->size(), slider_->palette()); + moodbar_pixmap_ = + MoodbarPixmap(moodbar_colors_, slider_->size(), slider_->palette()); moodbar_pixmap_dirty_ = false; } } -QRect MoodbarProxyStyle::subControlRect( - ComplexControl cc, const QStyleOptionComplex* opt, - SubControl sc, const QWidget* widget) const { +QRect MoodbarProxyStyle::subControlRect(ComplexControl cc, + const QStyleOptionComplex* opt, + SubControl sc, + const QWidget* widget) const { if (cc != QStyle::CC_Slider || widget != slider_) { return QProxyStyle::subControlRect(cc, opt, sc, widget); } @@ -256,16 +258,16 @@ QRect MoodbarProxyStyle::subControlRect( case FadingToOn: switch (sc) { case SC_SliderGroove: - return opt->rect.adjusted(kMarginSize, kMarginSize, - -kMarginSize, -kMarginSize); + return opt->rect.adjusted(kMarginSize, kMarginSize, -kMarginSize, + -kMarginSize); case SC_SliderHandle: { const QStyleOptionSlider* slider_opt = qstyleoption_cast(opt); - const int x = - (slider_opt->sliderValue - slider_opt->minimum) * (opt->rect.width() - kArrowWidth) / - (slider_opt->maximum - slider_opt->minimum); + const int x = (slider_opt->sliderValue - slider_opt->minimum) * + (opt->rect.width() - kArrowWidth) / + (slider_opt->maximum - slider_opt->minimum); return QRect(QPoint(opt->rect.left() + x, opt->rect.top()), QSize(kArrowWidth, kArrowHeight)); @@ -282,12 +284,12 @@ QRect MoodbarProxyStyle::subControlRect( void MoodbarProxyStyle::DrawArrow(const QStyleOptionSlider* option, QPainter* painter) const { // Get the dimensions of the arrow - const QRect rect = subControlRect(CC_Slider, option, SC_SliderHandle, slider_); + const QRect rect = + subControlRect(CC_Slider, option, SC_SliderHandle, slider_); // Make a polygon QPolygon poly; - poly << rect.topLeft() - << rect.topRight() + poly << rect.topLeft() << rect.topRight() << QPoint(rect.center().x(), rect.bottom()); // Draw it @@ -301,7 +303,8 @@ void MoodbarProxyStyle::DrawArrow(const QStyleOptionSlider* option, } QPixmap MoodbarProxyStyle::MoodbarPixmap(const ColorVector& colors, - const QSize& size, const QPalette& palette) { + const QSize& size, + const QPalette& palette) { QRect rect(QPoint(0, 0), size); QRect border_rect(rect); border_rect.adjust(kMarginSize, kMarginSize, -kMarginSize, -kMarginSize); @@ -316,8 +319,8 @@ QPixmap MoodbarProxyStyle::MoodbarPixmap(const ColorVector& colors, MoodbarRenderer::Render(colors, &p, inner_rect); // Draw the border - p.setPen(QPen(Qt::black, - kBorderSize, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin)); + p.setPen( + QPen(Qt::black, kBorderSize, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin)); p.drawRect(border_rect.adjusted(0, 0, -1, -1)); // Draw the outer bit @@ -334,7 +337,7 @@ void MoodbarProxyStyle::ShowContextMenu(const QPoint& pos) { if (!context_menu_) { context_menu_ = new QMenu(slider_); show_moodbar_action_ = context_menu_->addAction( - tr("Show moodbar"), this, SLOT(SetMoodbarEnabled(bool))); + tr("Show moodbar"), this, SLOT(SetMoodbarEnabled(bool))); show_moodbar_action_->setCheckable(true); show_moodbar_action_->setChecked(enabled_); @@ -342,23 +345,26 @@ void MoodbarProxyStyle::ShowContextMenu(const QPoint& pos) { QMenu* styles_menu = context_menu_->addMenu(tr("Moodbar style")); style_action_group_ = new QActionGroup(styles_menu); - for (int i=0 ; iaddAction(MoodbarRenderer::StyleName(style)); + QAction* action = + style_action_group_->addAction(MoodbarRenderer::StyleName(style)); action->setCheckable(true); action->setData(i); } styles_menu->addActions(style_action_group_->actions()); - connect(styles_menu, SIGNAL(triggered(QAction*)), SLOT(ChangeStyle(QAction*))); + connect(styles_menu, SIGNAL(triggered(QAction*)), + SLOT(ChangeStyle(QAction*))); } // Update the currently selected style - foreach (QAction* action, style_action_group_->actions()) { - if (MoodbarRenderer::MoodbarStyle(action->data().toInt()) == moodbar_style_) { + foreach(QAction * action, style_action_group_->actions()) { + if (MoodbarRenderer::MoodbarStyle(action->data().toInt()) == + moodbar_style_) { action->setChecked(true); break; } diff --git a/src/moodbar/moodbarproxystyle.h b/src/moodbar/moodbarproxystyle.h index 8b7ab0396..e43b2c7c8 100644 --- a/src/moodbar/moodbarproxystyle.h +++ b/src/moodbar/moodbarproxystyle.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -33,39 +33,35 @@ class QTimeLine; class MoodbarProxyStyle : public QProxyStyle { Q_OBJECT -public: + public: MoodbarProxyStyle(Application* app, QSlider* slider); // QProxyStyle - void drawComplexControl(ComplexControl control, const QStyleOptionComplex* option, - QPainter* painter, const QWidget* widget) const; + void drawComplexControl(ComplexControl control, + const QStyleOptionComplex* option, QPainter* painter, + const QWidget* widget) const; QRect subControlRect(ComplexControl cc, const QStyleOptionComplex* opt, SubControl sc, const QWidget* widget) const; // QObject bool eventFilter(QObject* object, QEvent* event); -public slots: + public slots: // An empty byte array means there's no moodbar, so just show a normal slider. void SetMoodbarData(const QByteArray& data); // If the moodbar is disabled then a normal slider will always be shown. void SetMoodbarEnabled(bool enabled); -private: + private: static const int kMarginSize; static const int kBorderSize; static const int kArrowWidth; static const int kArrowHeight; - enum State { - MoodbarOn, - MoodbarOff, - FadingToOn, - FadingToOff - }; + enum State { MoodbarOn, MoodbarOff, FadingToOn, FadingToOff }; -private: + private: void NextState(); void Render(ComplexControl control, const QStyleOptionSlider* option, @@ -74,15 +70,15 @@ private: void DrawArrow(const QStyleOptionSlider* option, QPainter* painter) const; void ShowContextMenu(const QPoint& pos); - static QPixmap MoodbarPixmap(const ColorVector& colors, - const QSize& size, const QPalette& palette); + static QPixmap MoodbarPixmap(const ColorVector& colors, const QSize& size, + const QPalette& palette); -private slots: + private slots: void ReloadSettings(); void FaderValueChanged(qreal value); void ChangeStyle(QAction* action); -private: + private: Application* app_; QSlider* slider_; @@ -106,4 +102,4 @@ private: QActionGroup* style_action_group_; }; -#endif // MOODBARPROXYSTYLE_H +#endif // MOODBARPROXYSTYLE_H diff --git a/src/moodbar/moodbarrenderer.cpp b/src/moodbar/moodbarrenderer.cpp index 82eb4754e..bb6807dc8 100644 --- a/src/moodbar/moodbarrenderer.cpp +++ b/src/moodbar/moodbarrenderer.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -22,26 +22,35 @@ const int MoodbarRenderer::kNumHues = 12; -ColorVector MoodbarRenderer::Colors( - const QByteArray& data, MoodbarStyle style, const QPalette& palette) { +ColorVector MoodbarRenderer::Colors(const QByteArray& data, MoodbarStyle style, + const QPalette& palette) { const int samples = data.size() / 3; // Set some parameters based on the moodbar style StyleProperties properties; - switch(style) { - case Style_Angry: properties = StyleProperties(samples / 360 * 9, 45, -45, 200, 100); break; - case Style_Frozen: properties = StyleProperties(samples / 360 * 1, 140, 160, 50, 100); break; - case Style_Happy: properties = StyleProperties(samples / 360 * 2, 0, 359, 150, 250); break; - case Style_Normal: properties = StyleProperties(samples / 360 * 3, 0, 359, 100, 100); break; + switch (style) { + case Style_Angry: + properties = StyleProperties(samples / 360 * 9, 45, -45, 200, 100); + break; + case Style_Frozen: + properties = StyleProperties(samples / 360 * 1, 140, 160, 50, 100); + break; + case Style_Happy: + properties = StyleProperties(samples / 360 * 2, 0, 359, 150, 250); + break; + case Style_Normal: + properties = StyleProperties(samples / 360 * 3, 0, 359, 100, 100); + break; case Style_SystemPalette: default: { - const QColor highlight_color(palette.color(QPalette::Active, QPalette::Highlight)); + const QColor highlight_color( + palette.color(QPalette::Active, QPalette::Highlight)); - properties.threshold_ = samples / 360 * 3; + properties.threshold_ = samples / 360 * 3; properties.range_start_ = (highlight_color.hsvHue() - 20 + 360) % 360; properties.range_delta_ = 20; - properties.sat_ = highlight_color.hsvSaturation(); - properties.val_ = highlight_color.value() / 2; + properties.sat_ = highlight_color.hsvSaturation(); + properties.val_ = highlight_color.value() / 2; } } @@ -56,7 +65,7 @@ ColorVector MoodbarRenderer::Colors( ColorVector colors; // Read the colors, keeping track of some histograms - for (int i=0; i properties.threshold_ ? n++ : n ) - * properties.range_delta_ / total + properties.range_start_) % 360; + ((hue_distribution[i] > properties.threshold_ ? n++ : n) * + properties.range_delta_ / total + + properties.range_start_) % + 360; } // Now huedist is a hue mapper: huedist[h] is the new hue value // for a bar with hue h - for (ColorVector::iterator it = colors.begin() ; it != colors.end() ; ++it) { + for (ColorVector::iterator it = colors.begin(); it != colors.end(); ++it) { const int hue = qMax(0, it->hue()); *it = QColor::fromHsv( - qBound(0, hue_distribution[hue], 359), - qBound(0, it->saturation() * properties.sat_ / 100, 255), - qBound(0, it->value() * properties.val_ / 100, 255)); + qBound(0, hue_distribution[hue], 359), + qBound(0, it->saturation() * properties.sat_ / 100, 255), + qBound(0, it->value() * properties.val_ / 100, 255)); } return colors; } -void MoodbarRenderer::Render(const ColorVector& colors, QPainter* p, const QRect& rect) { +void MoodbarRenderer::Render(const ColorVector& colors, QPainter* p, + const QRect& rect) { // Sample the colors and map them to screen pixels. ColorVector screen_colors; - for (int x=0; xsetPen(QColor::fromHsv( - h, - qBound(0, int(float(s) * coeff), 255), + h, qBound(0, int(float(s) * coeff), 255), qBound(0, int(255.f - (255.f - float(v)) * coeff2), 255))); p->drawPoint(rect.left() + x, rect.top() + y); @@ -142,7 +152,8 @@ void MoodbarRenderer::Render(const ColorVector& colors, QPainter* p, const QRect } } -QImage MoodbarRenderer::RenderToImage(const ColorVector& colors, const QSize& size) { +QImage MoodbarRenderer::RenderToImage(const ColorVector& colors, + const QSize& size) { QImage image(size, QImage::Format_ARGB32_Premultiplied); QPainter p(&image); Render(colors, &p, image.rect()); @@ -152,12 +163,18 @@ QImage MoodbarRenderer::RenderToImage(const ColorVector& colors, const QSize& si QString MoodbarRenderer::StyleName(MoodbarStyle style) { switch (style) { - case Style_Normal: return QObject::tr("Normal"); - case Style_Angry: return QObject::tr("Angry"); - case Style_Frozen: return QObject::tr("Frozen"); - case Style_Happy: return QObject::tr("Happy"); - case Style_SystemPalette: return QObject::tr("System colors"); + case Style_Normal: + return QObject::tr("Normal"); + case Style_Angry: + return QObject::tr("Angry"); + case Style_Frozen: + return QObject::tr("Frozen"); + case Style_Happy: + return QObject::tr("Happy"); + case Style_SystemPalette: + return QObject::tr("System colors"); - default: return QString(); + default: + return QString(); } } diff --git a/src/moodbar/moodbarrenderer.h b/src/moodbar/moodbarrenderer.h index 8521bdd6b..d91c04bcb 100644 --- a/src/moodbar/moodbarrenderer.h +++ b/src/moodbar/moodbarrenderer.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -27,7 +27,7 @@ class QPalette; typedef QVector ColorVector; class MoodbarRenderer { -public: + public: // These values are persisted. Remember to change appearancesettingspage.ui // when changing them. enum MoodbarStyle { @@ -36,7 +36,6 @@ public: Style_Frozen, Style_Happy, Style_SystemPalette, - StyleCount }; @@ -49,14 +48,17 @@ public: static void Render(const ColorVector& colors, QPainter* p, const QRect& rect); static QImage RenderToImage(const ColorVector& colors, const QSize& size); -private: + private: MoodbarRenderer(); struct StyleProperties { StyleProperties(int threshold = 0, int range_start = 0, int range_delta = 0, int sat = 0, int val = 0) - : threshold_(threshold), range_start_(range_start), range_delta_(range_delta), - sat_(sat), val_(val) {} + : threshold_(threshold), + range_start_(range_start), + range_delta_(range_delta), + sat_(sat), + val_(val) {} int threshold_; int range_start_; @@ -68,4 +70,4 @@ private: Q_DECLARE_METATYPE(QVector) -#endif // MOODBARRENDERER_H +#endif // MOODBARRENDERER_H diff --git a/src/musicbrainz/acoustidclient.cpp b/src/musicbrainz/acoustidclient.cpp index 448bf5ed0..2e9351631 100644 --- a/src/musicbrainz/acoustidclient.cpp +++ b/src/musicbrainz/acoustidclient.cpp @@ -29,25 +29,21 @@ const char* AcoustidClient::kClientId = "qsZGpeLx"; const char* AcoustidClient::kUrl = "http://api.acoustid.org/v2/lookup"; -const int AcoustidClient::kDefaultTimeout = 5000; // msec +const int AcoustidClient::kDefaultTimeout = 5000; // msec AcoustidClient::AcoustidClient(QObject* parent) - : QObject(parent), - network_(new NetworkAccessManager(this)), - timeouts_(new NetworkTimeouts(kDefaultTimeout, this)) -{ -} + : QObject(parent), + network_(new NetworkAccessManager(this)), + timeouts_(new NetworkTimeouts(kDefaultTimeout, this)) {} -void AcoustidClient::SetTimeout(int msec) { - timeouts_->SetTimeout(msec); -} +void AcoustidClient::SetTimeout(int msec) { timeouts_->SetTimeout(msec); } -void AcoustidClient::Start(int id, const QString& fingerprint, int duration_msec) { +void AcoustidClient::Start(int id, const QString& fingerprint, + int duration_msec) { typedef QPair Param; QList parameters; - parameters << Param("format", "json") - << Param("client", kClientId) + parameters << Param("format", "json") << Param("client", kClientId) << Param("duration", QString::number(duration_msec / kMsecPerSec)) << Param("meta", "recordingids") << Param("fingerprint", fingerprint); @@ -64,9 +60,7 @@ void AcoustidClient::Start(int id, const QString& fingerprint, int duration_msec timeouts_->AddReply(reply); } -void AcoustidClient::Cancel(int id) { - delete requests_.take(id); -} +void AcoustidClient::Cancel(int id) { delete requests_.take(id); } void AcoustidClient::CancelAll() { qDeleteAll(requests_.values()); @@ -77,7 +71,8 @@ void AcoustidClient::RequestFinished(QNetworkReply* reply, int id) { reply->deleteLater(); requests_.remove(id); - if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) { + if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != + 200) { emit Finished(id, QString()); return; } @@ -96,11 +91,11 @@ void AcoustidClient::RequestFinished(QNetworkReply* reply, int id) { return; } QVariantList results = result["results"].toList(); - foreach (const QVariant& v, results) { + foreach(const QVariant & v, results) { QVariantMap r = v.toMap(); if (r.contains("recordings")) { QVariantList recordings = r["recordings"].toList(); - foreach (const QVariant& recording, recordings) { + foreach(const QVariant & recording, recordings) { QVariantMap o = recording.toMap(); if (o.contains("id")) { emit Finished(id, o["id"].toString()); diff --git a/src/musicbrainz/acoustidclient.h b/src/musicbrainz/acoustidclient.h index aa54d5a62..5b27d9bb3 100644 --- a/src/musicbrainz/acoustidclient.h +++ b/src/musicbrainz/acoustidclient.h @@ -37,7 +37,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: + public: AcoustidClient(QObject* parent = 0); // Network requests will be aborted after this interval. @@ -58,10 +58,10 @@ public: signals: void Finished(int id, const QString& mbid); -private slots: + private slots: void RequestFinished(QNetworkReply* reply, int id); -private: + private: static const char* kClientId; static const char* kUrl; static const int kDefaultTimeout; @@ -71,4 +71,4 @@ private: QMap requests_; }; -#endif // ACOUSTIDCLIENT_H +#endif // ACOUSTIDCLIENT_H diff --git a/src/musicbrainz/chromaprinter.cpp b/src/musicbrainz/chromaprinter.cpp index 6a0a6a60a..ebb2ef882 100644 --- a/src/musicbrainz/chromaprinter.cpp +++ b/src/musicbrainz/chromaprinter.cpp @@ -34,23 +34,19 @@ static const int kDecodeRate = 11025; static const int kDecodeChannels = 1; Chromaprinter::Chromaprinter(const QString& filename) - : filename_(filename), - event_loop_(nullptr), - convert_element_(nullptr), - finishing_(false) { -} + : filename_(filename), + event_loop_(nullptr), + convert_element_(nullptr), + finishing_(false) {} -Chromaprinter::~Chromaprinter() { -} +Chromaprinter::~Chromaprinter() {} -GstElement* Chromaprinter::CreateElement(const QString &factory_name, - GstElement *bin) { +GstElement* Chromaprinter::CreateElement(const QString& factory_name, + GstElement* bin) { GstElement* ret = gst_element_factory_make( - factory_name.toAscii().constData(), - factory_name.toAscii().constData()); + factory_name.toAscii().constData(), factory_name.toAscii().constData()); - if (ret && bin) - gst_bin_add(GST_BIN(bin), ret); + if (ret && bin) gst_bin_add(GST_BIN(bin), ret); if (!ret) { qLog(Warning) << "Couldn't create the gstreamer element" << factory_name; @@ -69,11 +65,11 @@ QString Chromaprinter::CreateFingerprint() { event_loop_ = g_main_loop_new(context, FALSE); pipeline_ = gst_pipeline_new("pipeline"); - GstElement* src = CreateElement("filesrc", pipeline_); - GstElement* decode = CreateElement("decodebin2", pipeline_); - GstElement* convert = CreateElement("audioconvert", pipeline_); + GstElement* src = CreateElement("filesrc", pipeline_); + GstElement* decode = CreateElement("decodebin2", pipeline_); + GstElement* convert = CreateElement("audioconvert", pipeline_); GstElement* resample = CreateElement("audioresample", pipeline_); - GstElement* sink = CreateElement("appsink", pipeline_); + GstElement* sink = CreateElement("appsink", pipeline_); if (!src || !decode || !convert || !resample || !sink) { return QString(); @@ -87,18 +83,16 @@ QString Chromaprinter::CreateFingerprint() { // Chromaprint expects mono floats at a sample rate of 11025Hz. GstCaps* caps = gst_caps_new_simple( - "audio/x-raw-int", - "width", G_TYPE_INT, 16, - "channels", G_TYPE_INT, kDecodeChannels, - "rate", G_TYPE_INT, kDecodeRate, - nullptr); + "audio/x-raw-int", "width", G_TYPE_INT, 16, "channels", G_TYPE_INT, + kDecodeChannels, "rate", G_TYPE_INT, kDecodeRate, nullptr); gst_element_link_filtered(resample, sink, caps); gst_caps_unref(caps); GstAppSinkCallbacks callbacks; memset(&callbacks, 0, sizeof(callbacks)); callbacks.new_buffer = NewBufferCallback; - gst_app_sink_set_callbacks(reinterpret_cast(sink), &callbacks, this, nullptr); + gst_app_sink_set_callbacks(reinterpret_cast(sink), &callbacks, + this, nullptr); g_object_set(G_OBJECT(sink), "sync", FALSE, nullptr); g_object_set(G_OBJECT(sink), "emit-signals", TRUE, nullptr); @@ -107,8 +101,10 @@ QString Chromaprinter::CreateFingerprint() { // Connect signals CHECKED_GCONNECT(decode, "new-decoded-pad", &NewPadCallback, this); - gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), BusCallbackSync, this); - guint bus_callback_id = gst_bus_add_watch(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), BusCallback, this); + gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), + BusCallbackSync, this); + guint bus_callback_id = gst_bus_add_watch( + gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), BusCallback, this); QTime time; time.start(); @@ -125,9 +121,11 @@ QString Chromaprinter::CreateFingerprint() { buffer_.close(); QByteArray data = buffer_.data(); - ChromaprintContext* chromaprint = chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT); + ChromaprintContext* chromaprint = + chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT); chromaprint_start(chromaprint, kDecodeRate, kDecodeChannels); - chromaprint_feed(chromaprint, reinterpret_cast(data.data()), data.size() / 2); + chromaprint_feed(chromaprint, reinterpret_cast(data.data()), + data.size() / 2); chromaprint_finish(chromaprint); void* fprint = nullptr; @@ -137,8 +135,8 @@ QString Chromaprinter::CreateFingerprint() { if (ret == 1) { void* encoded = nullptr; int encoded_size = 0; - chromaprint_encode_fingerprint( - fprint, size, CHROMAPRINT_ALGORITHM_DEFAULT, &encoded, &encoded_size, 1); + chromaprint_encode_fingerprint(fprint, size, CHROMAPRINT_ALGORITHM_DEFAULT, + &encoded, &encoded_size, 1); fingerprint.append(reinterpret_cast(encoded), encoded_size); @@ -148,14 +146,15 @@ QString Chromaprinter::CreateFingerprint() { chromaprint_free(chromaprint); int codegen_time = time.elapsed(); - qLog(Debug) << "Decode time:" << decode_time << "Codegen time:" << codegen_time; + qLog(Debug) << "Decode time:" << decode_time + << "Codegen time:" << codegen_time; // Cleanup callbacks.new_buffer = nullptr; - gst_app_sink_set_callbacks( - reinterpret_cast(sink), &callbacks, this, nullptr); - gst_bus_set_sync_handler( - gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), nullptr, nullptr); + gst_app_sink_set_callbacks(reinterpret_cast(sink), &callbacks, + this, nullptr); + gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(pipeline_)), + nullptr, nullptr); g_source_remove(bus_callback_id); gst_element_set_state(pipeline_, GST_STATE_NULL); gst_object_unref(pipeline_); @@ -163,10 +162,11 @@ QString Chromaprinter::CreateFingerprint() { return fingerprint; } -void Chromaprinter::NewPadCallback(GstElement*, GstPad* pad, gboolean, gpointer data) { +void Chromaprinter::NewPadCallback(GstElement*, GstPad* pad, gboolean, + gpointer data) { Chromaprinter* instance = reinterpret_cast(data); - GstPad* const audiopad = gst_element_get_static_pad( - instance->convert_element_, "sink"); + GstPad* const audiopad = + gst_element_get_static_pad(instance->convert_element_, "sink"); if (GST_PAD_IS_LINKED(audiopad)) { qLog(Warning) << "audiopad is already linked, unlinking old pad"; @@ -208,7 +208,8 @@ gboolean Chromaprinter::BusCallback(GstBus*, GstMessage* msg, gpointer data) { return GST_BUS_DROP; } -GstBusSyncReply Chromaprinter::BusCallbackSync(GstBus*, GstMessage* msg, gpointer data) { +GstBusSyncReply Chromaprinter::BusCallbackSync(GstBus*, GstMessage* msg, + gpointer data) { Chromaprinter* instance = reinterpret_cast(data); if (instance->finishing_) { return GST_BUS_PASS; @@ -230,7 +231,8 @@ GstBusSyncReply Chromaprinter::BusCallbackSync(GstBus*, GstMessage* msg, gpointe return GST_BUS_PASS; } -GstFlowReturn Chromaprinter::NewBufferCallback(GstAppSink* app_sink, gpointer self) { +GstFlowReturn Chromaprinter::NewBufferCallback(GstAppSink* app_sink, + gpointer self) { Chromaprinter* me = reinterpret_cast(self); if (me->finishing_) { return GST_FLOW_OK; diff --git a/src/musicbrainz/chromaprinter.h b/src/musicbrainz/chromaprinter.h index a9c32265f..93b22e515 100644 --- a/src/musicbrainz/chromaprinter.h +++ b/src/musicbrainz/chromaprinter.h @@ -35,7 +35,7 @@ class Chromaprinter { // You should create one Chromaprinter for each file you want to fingerprint. // This class works well with QtConcurrentMap. -public: + public: Chromaprinter(const QString& filename); ~Chromaprinter(); @@ -44,17 +44,19 @@ public: // could be created. QString CreateFingerprint(); -private: - GstElement* CreateElement(const QString& factory_name, GstElement* bin = NULL); + private: + GstElement* CreateElement(const QString& factory_name, + GstElement* bin = NULL); void ReportError(GstMessage* message); static void NewPadCallback(GstElement*, GstPad* pad, gboolean, gpointer data); static gboolean BusCallback(GstBus*, GstMessage* msg, gpointer data); - static GstBusSyncReply BusCallbackSync(GstBus*, GstMessage* msg, gpointer data); + static GstBusSyncReply BusCallbackSync(GstBus*, GstMessage* msg, + gpointer data); static GstFlowReturn NewBufferCallback(GstAppSink* app_sink, gpointer self); -private: + private: QString filename_; GMainLoop* event_loop_; @@ -65,4 +67,4 @@ private: bool finishing_; }; -#endif // CHROMAPRINTER_H +#endif // CHROMAPRINTER_H diff --git a/src/musicbrainz/musicbrainzclient.cpp b/src/musicbrainz/musicbrainzclient.cpp index 4cb1c73a2..f8edfc9ba 100644 --- a/src/musicbrainz/musicbrainzclient.cpp +++ b/src/musicbrainz/musicbrainzclient.cpp @@ -27,17 +27,17 @@ #include "core/network.h" #include "core/utilities.h" -const char* MusicBrainzClient::kTrackUrl = "https://musicbrainz.org/ws/2/recording/"; -const char* MusicBrainzClient::kDiscUrl = "https://musicbrainz.org/ws/2/discid/"; +const char* MusicBrainzClient::kTrackUrl = + "https://musicbrainz.org/ws/2/recording/"; +const char* MusicBrainzClient::kDiscUrl = + "https://musicbrainz.org/ws/2/discid/"; const char* MusicBrainzClient::kDateRegex = "^[12]\\d{3}"; -const int MusicBrainzClient::kDefaultTimeout = 5000; // msec +const int MusicBrainzClient::kDefaultTimeout = 5000; // msec MusicBrainzClient::MusicBrainzClient(QObject* parent) - : QObject(parent), - network_(new NetworkAccessManager(this)), - timeouts_(new NetworkTimeouts(kDefaultTimeout, this)) -{ -} + : QObject(parent), + network_(new NetworkAccessManager(this)), + timeouts_(new NetworkTimeouts(kDefaultTimeout, this)) {} void MusicBrainzClient::Start(int id, const QString& mbid) { typedef QPair Param; @@ -74,9 +74,7 @@ void MusicBrainzClient::StartDiscIdRequest(const QString& discid) { timeouts_->AddReply(reply); } -void MusicBrainzClient::Cancel(int id) { - delete requests_.take(id); -} +void MusicBrainzClient::Cancel(int id) { delete requests_.take(id); } void MusicBrainzClient::CancelAll() { qDeleteAll(requests_.values()); @@ -90,7 +88,8 @@ void MusicBrainzClient::DiscIdRequestFinished(QNetworkReply* reply) { QString artist; QString album; - if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) { + if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != + 200) { emit Finished(artist, album, ret); return; } @@ -116,14 +115,16 @@ void MusicBrainzClient::DiscIdRequestFinished(QNetworkReply* reply) { while (!reader.atEnd()) { QXmlStreamReader::TokenType token = reader.readNext(); - if (token == QXmlStreamReader::StartElement && reader.name() == "recording") { + if (token == QXmlStreamReader::StartElement && + reader.name() == "recording") { ResultList tracks = ParseTrack(&reader); - foreach (const Result& track, tracks) { + foreach(const Result & track, tracks) { if (!track.title_.isEmpty()) { ret << track; } } - } else if (token == QXmlStreamReader::EndElement && reader.name() == "track-list") { + } else if (token == QXmlStreamReader::EndElement && + reader.name() == "track-list") { break; } } @@ -131,22 +132,23 @@ void MusicBrainzClient::DiscIdRequestFinished(QNetworkReply* reply) { emit Finished(artist, album, UniqueResults(ret)); } - void MusicBrainzClient::RequestFinished(QNetworkReply* reply, int id) { reply->deleteLater(); requests_.remove(id); ResultList ret; - if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) { + if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != + 200) { emit Finished(id, ret); return; } QXmlStreamReader reader(reply); while (!reader.atEnd()) { - if (reader.readNext() == QXmlStreamReader::StartElement && reader.name() == "recording") { + if (reader.readNext() == QXmlStreamReader::StartElement && + reader.name() == "recording") { ResultList tracks = ParseTrack(&reader); - foreach (const Result& track, tracks) { + foreach(const Result & track, tracks) { if (!track.title_.isEmpty()) { ret << track; } @@ -157,7 +159,8 @@ void MusicBrainzClient::RequestFinished(QNetworkReply* reply, int id) { emit Finished(id, UniqueResults(ret)); } -MusicBrainzClient::ResultList MusicBrainzClient::ParseTrack(QXmlStreamReader* reader) { +MusicBrainzClient::ResultList MusicBrainzClient::ParseTrack( + QXmlStreamReader* reader) { Result result; QList releases; @@ -187,7 +190,7 @@ MusicBrainzClient::ResultList MusicBrainzClient::ParseTrack(QXmlStreamReader* re if (releases.isEmpty()) { ret << result; } else { - foreach (const Release& release, releases) { + foreach(const Release & release, releases) { ret << release.CopyAndMergeInto(result); } } @@ -208,7 +211,8 @@ void MusicBrainzClient::ParseArtist(QXmlStreamReader* reader, QString* artist) { } } -MusicBrainzClient::Release MusicBrainzClient::ParseRelease(QXmlStreamReader* reader) { +MusicBrainzClient::Release MusicBrainzClient::ParseRelease( + QXmlStreamReader* reader) { Release ret; while (!reader->atEnd()) { @@ -224,7 +228,8 @@ MusicBrainzClient::Release MusicBrainzClient::ParseRelease(QXmlStreamReader* rea ret.year_ = regex.cap(0).toInt(); } } else if (name == "track-list") { - ret.track_ = reader->attributes().value("offset").toString().toInt() + 1; + ret.track_ = + reader->attributes().value("offset").toString().toInt() + 1; Utilities::ConsumeCurrentElement(reader); } } @@ -237,7 +242,8 @@ MusicBrainzClient::Release MusicBrainzClient::ParseRelease(QXmlStreamReader* rea return ret; } -MusicBrainzClient::ResultList MusicBrainzClient::UniqueResults(const ResultList& results) { +MusicBrainzClient::ResultList MusicBrainzClient::UniqueResults( + const ResultList& results) { ResultList ret = QSet::fromList(results).toList(); qSort(ret); return ret; diff --git a/src/musicbrainz/musicbrainzclient.h b/src/musicbrainz/musicbrainzclient.h index e7065daf4..a16182224 100644 --- a/src/musicbrainz/musicbrainzclient.h +++ b/src/musicbrainz/musicbrainzclient.h @@ -37,16 +37,16 @@ class MusicBrainzClient : public QObject { // IDs are provided by the caller when a request is started and included in // the Finished signal - they have no meaning to MusicBrainzClient. -public: + public: MusicBrainzClient(QObject* parent = 0); struct Result { Result() : duration_msec_(0), track_(0), year_(-1) {} - bool operator <(const Result& other) const { - #define cmp(field) \ - if (field < other.field) return true; \ - if (field > other.field) return false; + bool operator<(const Result& other) const { +#define cmp(field) \ + if (field < other.field) return true; \ + if (field > other.field) return false; cmp(track_); cmp(year_); @@ -54,16 +54,13 @@ public: cmp(artist_); return false; - #undef cmp +#undef cmp } - bool operator ==(const Result& other) const { - return title_ == other.title_ && - artist_ == other.artist_ && - album_ == other.album_ && - duration_msec_ == other.duration_msec_ && - track_ == other.track_ && - year_ == other.year_; + bool operator==(const Result& other) const { + return title_ == other.title_ && artist_ == other.artist_ && + album_ == other.album_ && duration_msec_ == other.duration_msec_ && + track_ == other.track_ && year_ == other.year_; } QString title_; @@ -75,7 +72,6 @@ public: }; typedef QList ResultList; - // Starts a request and returns immediately. Finished() will be emitted // later with the same ID. void Start(int id, const QString& mbid); @@ -96,11 +92,11 @@ signals: void Finished(const QString& artist, const QString album, const MusicBrainzClient::ResultList& result); -private slots: + private slots: void RequestFinished(QNetworkReply* reply, int id); void DiscIdRequestFinished(QNetworkReply* reply); -private: + private: struct Release { Release() : track_(0), year_(0) {} @@ -122,7 +118,7 @@ private: static Release ParseRelease(QXmlStreamReader* reader); static ResultList UniqueResults(const ResultList& results); -private: + private: static const char* kTrackUrl; static const char* kDiscUrl; static const char* kDateRegex; @@ -134,12 +130,8 @@ private: }; inline uint qHash(const MusicBrainzClient::Result& result) { - return qHash(result.album_) ^ - qHash(result.artist_) ^ - result.duration_msec_ ^ - qHash(result.title_) ^ - result.track_ ^ - result.year_; + return qHash(result.album_) ^ qHash(result.artist_) ^ result.duration_msec_ ^ + qHash(result.title_) ^ result.track_ ^ result.year_; } -#endif // MUSICBRAINZCLIENT_H +#endif // MUSICBRAINZCLIENT_H diff --git a/src/musicbrainz/tagfetcher.cpp b/src/musicbrainz/tagfetcher.cpp index 0c9991618..6836e98e3 100644 --- a/src/musicbrainz/tagfetcher.cpp +++ b/src/musicbrainz/tagfetcher.cpp @@ -28,13 +28,15 @@ #include TagFetcher::TagFetcher(QObject* parent) - : QObject(parent), - fingerprint_watcher_(nullptr), - acoustid_client_(new AcoustidClient(this)), - musicbrainz_client_(new MusicBrainzClient(this)) -{ - connect(acoustid_client_, SIGNAL(Finished(int,QString)), SLOT(PuidFound(int,QString))); - connect(musicbrainz_client_, SIGNAL(Finished(int,MusicBrainzClient::ResultList)), SLOT(TagsFetched(int,MusicBrainzClient::ResultList))); + : QObject(parent), + fingerprint_watcher_(nullptr), + acoustid_client_(new AcoustidClient(this)), + musicbrainz_client_(new MusicBrainzClient(this)) { + connect(acoustid_client_, SIGNAL(Finished(int, QString)), + SLOT(PuidFound(int, QString))); + connect(musicbrainz_client_, + SIGNAL(Finished(int, MusicBrainzClient::ResultList)), + SLOT(TagsFetched(int, MusicBrainzClient::ResultList))); } QString TagFetcher::GetFingerprint(const Song& song) { @@ -49,9 +51,10 @@ void TagFetcher::StartFetch(const SongList& songs) { QFuture future = QtConcurrent::mapped(songs_, GetFingerprint); fingerprint_watcher_ = new QFutureWatcher(this); fingerprint_watcher_->setFuture(future); - connect(fingerprint_watcher_, SIGNAL(resultReadyAt(int)), SLOT(FingerprintFound(int))); + connect(fingerprint_watcher_, SIGNAL(resultReadyAt(int)), + SLOT(FingerprintFound(int))); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { emit Progress(song, tr("Fingerprinting song")); } } @@ -70,7 +73,8 @@ void TagFetcher::Cancel() { } void TagFetcher::FingerprintFound(int index) { - QFutureWatcher* watcher = reinterpret_cast*>(sender()); + QFutureWatcher* watcher = + reinterpret_cast*>(sender()); if (!watcher || index >= songs_.count()) { return; } @@ -84,7 +88,8 @@ void TagFetcher::FingerprintFound(int index) { } emit Progress(song, tr("Identifying song")); - acoustid_client_->Start(index, fingerprint, song.length_nanosec() / kNsecPerMsec); + acoustid_client_->Start(index, fingerprint, + song.length_nanosec() / kNsecPerMsec); } void TagFetcher::PuidFound(int index, const QString& puid) { @@ -103,7 +108,8 @@ void TagFetcher::PuidFound(int index, const QString& puid) { musicbrainz_client_->Start(index, puid); } -void TagFetcher::TagsFetched(int index, const MusicBrainzClient::ResultList& results) { +void TagFetcher::TagsFetched(int index, + const MusicBrainzClient::ResultList& results) { if (index >= songs_.count()) { return; } @@ -111,7 +117,7 @@ void TagFetcher::TagsFetched(int index, const MusicBrainzClient::ResultList& res const Song& original_song = songs_[index]; SongList songs_guessed; - foreach (const MusicBrainzClient::Result& result, results) { + foreach(const MusicBrainzClient::Result & result, results) { Song song; song.Init(result.title_, result.artist_, result.album_, result.duration_msec_ * kNsecPerMsec); diff --git a/src/musicbrainz/tagfetcher.h b/src/musicbrainz/tagfetcher.h index 468624a35..85a5656e1 100644 --- a/src/musicbrainz/tagfetcher.h +++ b/src/musicbrainz/tagfetcher.h @@ -32,12 +32,12 @@ class TagFetcher : public QObject { // High level interface to Fingerprinter, AcoustidClient and // MusicBrainzClient. -public: + public: TagFetcher(QObject* parent = 0); void StartFetch(const SongList& songs); -public slots: + public slots: void Cancel(); signals: @@ -45,12 +45,12 @@ signals: void ResultAvailable(const Song& original_song, const SongList& songs_guessed); -private slots: + private slots: void FingerprintFound(int index); void PuidFound(int index, const QString& puid); void TagsFetched(int index, const MusicBrainzClient::ResultList& result); -private: + private: static QString GetFingerprint(const Song& song); QFutureWatcher* fingerprint_watcher_; @@ -60,4 +60,4 @@ private: SongList songs_; }; -#endif // TAGFETCHER_H +#endif // TAGFETCHER_H diff --git a/src/networkremote/avahi.cpp b/src/networkremote/avahi.cpp index f30e0e0bf..d126aa2a4 100644 --- a/src/networkremote/avahi.cpp +++ b/src/networkremote/avahi.cpp @@ -9,65 +9,45 @@ namespace { -void AddService( - const QString domain, - const QString type, - const QByteArray name, - quint16 port, - QDBusPendingReply path_reply); +void AddService(const QString domain, const QString type, const QByteArray name, + quint16 port, QDBusPendingReply path_reply); void Commit(OrgFreedesktopAvahiEntryGroupInterface* interface); void LogCommit(QDBusPendingReply<> reply); } // namespace -void Avahi::PublishInternal( - const QString& domain, - const QString& type, - const QByteArray& name, - quint16 port) { +void Avahi::PublishInternal(const QString& domain, const QString& type, + const QByteArray& name, quint16 port) { OrgFreedesktopAvahiServerInterface server_interface( - "org.freedesktop.Avahi", - "/", - QDBusConnection::systemBus()); + "org.freedesktop.Avahi", "/", QDBusConnection::systemBus()); QDBusPendingReply reply = server_interface.EntryGroupNew(); QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(reply); - NewClosure( - watcher, - SIGNAL(finished(QDBusPendingCallWatcher*)), - &AddService, - domain, type, name, port, reply); - QObject::connect( - watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - watcher, SLOT(deleteLater())); + NewClosure(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), &AddService, + domain, type, name, port, reply); + QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), watcher, + SLOT(deleteLater())); } namespace { -void AddService( - const QString domain, - const QString type, - const QByteArray name, - quint16 port, - QDBusPendingReply path_reply) { +void AddService(const QString domain, const QString type, const QByteArray name, + quint16 port, QDBusPendingReply path_reply) { if (path_reply.isError()) { - qLog(Warning) - << "Failed to create Avahi entry group:" - << path_reply.error(); - qLog(Info) - << "This might be because 'disable-user-service-publishing'" - << "is set to 'yes' in avahi-daemon.conf"; + qLog(Warning) << "Failed to create Avahi entry group:" + << path_reply.error(); + qLog(Info) << "This might be because 'disable-user-service-publishing'" + << "is set to 'yes' in avahi-daemon.conf"; return; } qLog(Debug) << path_reply.error(); OrgFreedesktopAvahiEntryGroupInterface* entry_group_interface = - new OrgFreedesktopAvahiEntryGroupInterface( - "org.freedesktop.Avahi", - path_reply.value().path(), - QDBusConnection::systemBus()); + new OrgFreedesktopAvahiEntryGroupInterface("org.freedesktop.Avahi", + path_reply.value().path(), + QDBusConnection::systemBus()); QDBusPendingReply<> reply = entry_group_interface->AddService( - -1, // Interface (all) - -1, // Protocol (v4 & v6) - 0, // Flags + -1, // Interface (all) + -1, // Protocol (v4 & v6) + 0, // Flags // Service name, eg. Clementine QString::fromUtf8(name.constData(), name.size()), type, // Service type, eg. _clementine._tcp @@ -76,31 +56,22 @@ void AddService( port, // Port our service is running on QList()); // TXT record QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(reply); - NewClosure( - watcher, - SIGNAL(finished(QDBusPendingCallWatcher*)), - &Commit, - entry_group_interface); + NewClosure(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), &Commit, + entry_group_interface); - QObject::connect( - watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - watcher, SLOT(deleteLater())); + QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), watcher, + SLOT(deleteLater())); } void Commit(OrgFreedesktopAvahiEntryGroupInterface* interface) { QDBusPendingReply<> reply = interface->Commit(); QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(reply); - QObject::connect( - watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - watcher, SLOT(deleteLater())); - QObject::connect( - watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - interface, SLOT(deleteLater())); - NewClosure( - watcher, - SIGNAL(finished(QDBusPendingCallWatcher*)), - &LogCommit, - reply); + QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), watcher, + SLOT(deleteLater())); + QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), + interface, SLOT(deleteLater())); + NewClosure(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), &LogCommit, + reply); } void LogCommit(QDBusPendingReply<> reply) { @@ -108,4 +79,3 @@ void LogCommit(QDBusPendingReply<> reply) { } } // namespace - diff --git a/src/networkremote/avahi.h b/src/networkremote/avahi.h index c53b0aa90..d36f7f346 100644 --- a/src/networkremote/avahi.h +++ b/src/networkremote/avahi.h @@ -5,11 +5,8 @@ class Avahi : public Zeroconf { protected: - virtual void PublishInternal( - const QString& domain, - const QString& type, - const QByteArray& name, - quint16 port); + virtual void PublishInternal(const QString& domain, const QString& type, + const QByteArray& name, quint16 port); }; #endif // AVAHI_H diff --git a/src/networkremote/bonjour.h b/src/networkremote/bonjour.h index 450ab61ac..49c8f9f41 100644 --- a/src/networkremote/bonjour.h +++ b/src/networkremote/bonjour.h @@ -15,11 +15,8 @@ class Bonjour : public Zeroconf { virtual ~Bonjour(); protected: - virtual void PublishInternal( - const QString& domain, - const QString& type, - const QByteArray& name, - quint16 port); + virtual void PublishInternal(const QString& domain, const QString& type, + const QByteArray& name, quint16 port); private: NetServicePublicationDelegate* delegate_; diff --git a/src/networkremote/incomingdataparser.cpp b/src/networkremote/incomingdataparser.cpp index 83af30466..80e2aca3d 100644 --- a/src/networkremote/incomingdataparser.cpp +++ b/src/networkremote/incomingdataparser.cpp @@ -27,39 +27,30 @@ #include "playlist/playlist.h" #ifdef HAVE_LIBLASTFM -# include "internet/lastfmservice.h" +#include "internet/lastfmservice.h" #endif -IncomingDataParser::IncomingDataParser(Application* app) - :app_(app) -{ +IncomingDataParser::IncomingDataParser(Application* app) : app_(app) { // Connect all the signals - // due the player is in a different thread, we cannot access these functions directly - connect(this, SIGNAL(Play()), - app_->player(), SLOT(Play())); - connect(this, SIGNAL(PlayPause()), - app_->player(), SLOT(PlayPause())); - connect(this, SIGNAL(Pause()), - app_->player(), SLOT(Pause())); - connect(this, SIGNAL(Stop()), - app_->player(), SLOT(Stop())); - connect(this, SIGNAL(StopAfterCurrent()), - app_->player(), SLOT(StopAfterCurrent())); - connect(this, SIGNAL(Next()), - app_->player(), SLOT(Next())); - connect(this, SIGNAL(Previous()), - app_->player(), SLOT(Previous())); - connect(this, SIGNAL(SetVolume(int)), - app_->player(), SLOT(SetVolume(int))); - connect(this, SIGNAL(PlayAt(int,Engine::TrackChangeFlags,bool)), - app_->player(), SLOT(PlayAt(int,Engine::TrackChangeFlags,bool))); - connect(this, SIGNAL(SeekTo(int)), - app_->player(), SLOT(SeekTo(int))); + // due the player is in a different thread, we cannot access these functions + // directly + connect(this, SIGNAL(Play()), app_->player(), SLOT(Play())); + connect(this, SIGNAL(PlayPause()), app_->player(), SLOT(PlayPause())); + connect(this, SIGNAL(Pause()), app_->player(), SLOT(Pause())); + connect(this, SIGNAL(Stop()), app_->player(), SLOT(Stop())); + connect(this, SIGNAL(StopAfterCurrent()), app_->player(), + SLOT(StopAfterCurrent())); + connect(this, SIGNAL(Next()), app_->player(), SLOT(Next())); + connect(this, SIGNAL(Previous()), app_->player(), SLOT(Previous())); + connect(this, SIGNAL(SetVolume(int)), app_->player(), SLOT(SetVolume(int))); + connect(this, SIGNAL(PlayAt(int, Engine::TrackChangeFlags, bool)), + app_->player(), SLOT(PlayAt(int, Engine::TrackChangeFlags, bool))); + connect(this, SIGNAL(SeekTo(int)), app_->player(), SLOT(SeekTo(int))); - connect(this, SIGNAL(SetActivePlaylist(int)), - app_->playlist_manager(), SLOT(SetActivePlaylist(int))); - connect(this, SIGNAL(ShuffleCurrent()), - app_->playlist_manager(), SLOT(ShuffleCurrent())); + connect(this, SIGNAL(SetActivePlaylist(int)), app_->playlist_manager(), + SLOT(SetActivePlaylist(int))); + connect(this, SIGNAL(ShuffleCurrent()), app_->playlist_manager(), + SLOT(ShuffleCurrent())); connect(this, SIGNAL(SetRepeatMode(PlaylistSequence::RepeatMode)), app_->playlist_manager()->sequence(), SLOT(SetRepeatMode(PlaylistSequence::RepeatMode))); @@ -72,31 +63,26 @@ IncomingDataParser::IncomingDataParser(Application* app) connect(this, SIGNAL(RemoveSongs(int, const QList&)), app_->playlist_manager(), SLOT(RemoveItemsWithoutUndo(int, const QList&))); - connect(this, SIGNAL(Open(int)), - app_->playlist_manager(), SLOT(Open(int))); - connect(this, SIGNAL(Close(int)), - app_->playlist_manager(), SLOT(Close(int))); + connect(this, SIGNAL(Open(int)), app_->playlist_manager(), SLOT(Open(int))); + connect(this, SIGNAL(Close(int)), app_->playlist_manager(), SLOT(Close(int))); - connect(this, SIGNAL(RateCurrentSong(double)), - app_->playlist_manager(), SLOT(RateCurrentSong(double))); + connect(this, SIGNAL(RateCurrentSong(double)), app_->playlist_manager(), + SLOT(RateCurrentSong(double))); #ifdef HAVE_LIBLASTFM - connect(this, SIGNAL(Love()), - InternetModel::Service(), SLOT(Love())); - connect(this, SIGNAL(Ban()), - InternetModel::Service(), SLOT(Ban())); + connect(this, SIGNAL(Love()), InternetModel::Service(), + SLOT(Love())); + connect(this, SIGNAL(Ban()), InternetModel::Service(), + SLOT(Ban())); #endif } -IncomingDataParser::~IncomingDataParser() { -} +IncomingDataParser::~IncomingDataParser() {} -bool IncomingDataParser::close_connection() { - return close_connection_; -} +bool IncomingDataParser::close_connection() { return close_connection_; } void IncomingDataParser::Parse(const pb::remote::Message& msg) { - close_connection_ = false; + close_connection_ = false; RemoteClient* client = qobject_cast(sender()); @@ -186,7 +172,8 @@ void IncomingDataParser::Parse(const pb::remote::Message& msg) { case pb::remote::RATE_SONG: RateSong(msg); break; - default: break; + default: + break; } } @@ -221,7 +208,8 @@ void IncomingDataParser::SetRepeatMode(const pb::remote::Repeat& repeat) { case pb::remote::Repeat_Playlist: emit SetRepeatMode(PlaylistSequence::Repeat_Playlist); break; - default: break; + default: + break; } } @@ -239,7 +227,8 @@ void IncomingDataParser::SetShuffleMode(const pb::remote::Shuffle& shuffle) { case pb::remote::Shuffle_Albums: emit SetShuffleMode(PlaylistSequence::Shuffle_Albums); break; - default: break; + default: + break; } } @@ -259,16 +248,16 @@ void IncomingDataParser::InsertUrls(const pb::remote::Message& msg) { } void IncomingDataParser::RemoveSongs(const pb::remote::Message& msg) { - const pb::remote::RequestRemoveSongs& request = msg.request_remove_songs(); + const pb::remote::RequestRemoveSongs& request = msg.request_remove_songs(); - // Extract urls - QList songs; - for (int i = 0; i songs; + for (int i = 0; i < request.songs().size(); i++) { + songs.append(request.songs(i)); + } - // Insert the urls - emit RemoveSongs(request.playlist_id(), songs); + // Insert the urls + emit RemoveSongs(request.playlist_id(), songs); } void IncomingDataParser::ClientConnect(const pb::remote::Message& msg) { @@ -277,32 +266,32 @@ void IncomingDataParser::ClientConnect(const pb::remote::Message& msg) { emit SendClementineInfo(); // Check if we should send the first data - if (!msg.request_connect().has_send_playlist_songs() // legacy - || msg.request_connect().send_playlist_songs()) { + if (!msg.request_connect().has_send_playlist_songs() // legacy + || msg.request_connect().send_playlist_songs()) { emit SendFirstData(true); } else { emit SendFirstData(false); } } -void IncomingDataParser::SendPlaylists(const pb::remote::Message &msg) { - if (!msg.has_request_playlists() - || !msg.request_playlists().include_closed()) { +void IncomingDataParser::SendPlaylists(const pb::remote::Message& msg) { + if (!msg.has_request_playlists() || + !msg.request_playlists().include_closed()) { emit SendAllActivePlaylists(); } else { emit SendAllPlaylists(); } } -void IncomingDataParser::OpenPlaylist(const pb::remote::Message &msg) { +void IncomingDataParser::OpenPlaylist(const pb::remote::Message& msg) { emit Open(msg.request_open_playlist().playlist_id()); } -void IncomingDataParser::ClosePlaylist(const pb::remote::Message &msg) { +void IncomingDataParser::ClosePlaylist(const pb::remote::Message& msg) { emit Close(msg.request_close_playlist().playlist_id()); } -void IncomingDataParser::RateSong(const pb::remote::Message &msg) { - double rating = (double) msg.request_rate_song().rating(); +void IncomingDataParser::RateSong(const pb::remote::Message& msg) { + double rating = (double)msg.request_rate_song().rating(); emit RateCurrentSong(rating); } diff --git a/src/networkremote/incomingdataparser.h b/src/networkremote/incomingdataparser.h index 285c97e6a..47cd4e94d 100644 --- a/src/networkremote/incomingdataparser.h +++ b/src/networkremote/incomingdataparser.h @@ -8,13 +8,13 @@ class IncomingDataParser : public QObject { Q_OBJECT -public: + public: IncomingDataParser(Application* app); ~IncomingDataParser(); bool close_connection(); -public slots: + public slots: void Parse(const pb::remote::Message& msg); signals: @@ -42,15 +42,17 @@ signals: void ShuffleCurrent(); void SetRepeatMode(PlaylistSequence::RepeatMode mode); void SetShuffleMode(PlaylistSequence::ShuffleMode mode); - void InsertUrls(int id, const QList& urls, int pos, bool play_now, bool enqueue); + void InsertUrls(int id, const QList& urls, int pos, bool play_now, + bool enqueue); void RemoveSongs(int id, const QList& indices); void SeekTo(int seconds); - void SendSongs(const pb::remote::RequestDownloadSongs& request, RemoteClient* client); + void SendSongs(const pb::remote::RequestDownloadSongs& request, + RemoteClient* client); void ResponseSongOffer(RemoteClient* client, bool accepted); void SendLibrary(RemoteClient* client); void RateCurrentSong(double); -private: + private: Application* app_; bool close_connection_; @@ -67,4 +69,4 @@ private: void RateSong(const pb::remote::Message& msg); }; -#endif // INCOMINGDATAPARSER_H +#endif // INCOMINGDATAPARSER_H diff --git a/src/networkremote/networkremote.cpp b/src/networkremote/networkremote.cpp index 38aa955fd..2f211d719 100644 --- a/src/networkremote/networkremote.cpp +++ b/src/networkremote/networkremote.cpp @@ -31,22 +31,16 @@ const char* NetworkRemote::kSettingsGroup = "NetworkRemote"; const quint16 NetworkRemote::kDefaultServerPort = 5500; NetworkRemote::NetworkRemote(Application* app, QObject* parent) - : QObject(parent), - signals_connected_(false), - app_(app) { -} + : QObject(parent), signals_connected_(false), app_(app) {} - -NetworkRemote::~NetworkRemote() { - StopServer(); -} +NetworkRemote::~NetworkRemote() { StopServer(); } void NetworkRemote::ReadSettings() { QSettings s; s.beginGroup(NetworkRemote::kSettingsGroup); use_remote_ = s.value("use_remote", false).toBool(); - port_ = s.value("port", kDefaultServerPort).toInt(); + port_ = s.value("port", kDefaultServerPort).toInt(); // Use only non public ips must be true be default only_non_public_ip_ = s.value("only_non_public_ip", true).toBool(); @@ -68,8 +62,10 @@ void NetworkRemote::SetupServer() { SLOT(CurrentSongChanged(const Song&, const QString&, const QImage&))); // Only connect the signals once - connect(server_.get(), SIGNAL(newConnection()), this, SLOT(AcceptConnection())); - connect(server_ipv6_.get(), SIGNAL(newConnection()), this, SLOT(AcceptConnection())); + connect(server_.get(), SIGNAL(newConnection()), this, + SLOT(AcceptConnection())); + connect(server_ipv6_.get(), SIGNAL(newConnection()), this, + SLOT(AcceptConnection())); } void NetworkRemote::StartServer() { @@ -96,8 +92,7 @@ void NetworkRemote::StartServer() { if (Zeroconf::GetZeroconf()) { QString name = QString("Clementine on %1").arg(QHostInfo::localHostName()); - Zeroconf::GetZeroconf()->Publish( - "local", "_clementine._tcp", name, port_); + Zeroconf::GetZeroconf()->Publish("local", "_clementine._tcp", name, port_); } } @@ -136,17 +131,18 @@ void NetworkRemote::AcceptConnection() { outgoing_data_creator_.get(), SLOT(ActiveChanged(Playlist*))); connect(app_->playlist_manager(), SIGNAL(PlaylistChanged(Playlist*)), outgoing_data_creator_.get(), SLOT(PlaylistChanged(Playlist*))); - connect(app_->playlist_manager(), SIGNAL(PlaylistAdded(int,QString,bool)), - outgoing_data_creator_.get(), SLOT(PlaylistAdded(int,QString,bool))); - connect(app_->playlist_manager(), SIGNAL(PlaylistRenamed(int,QString)), - outgoing_data_creator_.get(), SLOT(PlaylistRenamed(int,QString))); + connect(app_->playlist_manager(), SIGNAL(PlaylistAdded(int, QString, bool)), + outgoing_data_creator_.get(), + SLOT(PlaylistAdded(int, QString, bool))); + connect(app_->playlist_manager(), SIGNAL(PlaylistRenamed(int, QString)), + outgoing_data_creator_.get(), SLOT(PlaylistRenamed(int, QString))); connect(app_->playlist_manager(), SIGNAL(PlaylistClosed(int)), outgoing_data_creator_.get(), SLOT(PlaylistClosed(int))); connect(app_->playlist_manager(), SIGNAL(PlaylistDeleted(int)), outgoing_data_creator_.get(), SLOT(PlaylistDeleted(int))); - connect(app_->player(), SIGNAL(VolumeChanged(int)), outgoing_data_creator_.get(), - SLOT(VolumeChanged(int))); + connect(app_->player(), SIGNAL(VolumeChanged(int)), + outgoing_data_creator_.get(), SLOT(VolumeChanged(int))); connect(app_->player()->engine(), SIGNAL(StateChanged(Engine::State)), outgoing_data_creator_.get(), SLOT(StateChanged(Engine::State))); @@ -163,26 +159,24 @@ void NetworkRemote::AcceptConnection() { outgoing_data_creator_.get(), SLOT(GetLyrics())); connect(incoming_data_parser_.get(), - SIGNAL(SendSongs(pb::remote::RequestDownloadSongs,RemoteClient*)), + SIGNAL(SendSongs(pb::remote::RequestDownloadSongs, RemoteClient*)), outgoing_data_creator_.get(), - SLOT(SendSongs(pb::remote::RequestDownloadSongs,RemoteClient*))); + SLOT(SendSongs(pb::remote::RequestDownloadSongs, RemoteClient*))); connect(incoming_data_parser_.get(), SIGNAL(ResponseSongOffer(RemoteClient*, bool)), outgoing_data_creator_.get(), SLOT(ResponseSongOffer(RemoteClient*, bool))); - connect(incoming_data_parser_.get(), - SIGNAL(SendLibrary(RemoteClient*)), - outgoing_data_creator_.get(), - SLOT(SendLibrary(RemoteClient*))); + connect(incoming_data_parser_.get(), SIGNAL(SendLibrary(RemoteClient*)), + outgoing_data_creator_.get(), SLOT(SendLibrary(RemoteClient*))); } QTcpServer* server = qobject_cast(sender()); QTcpSocket* client_socket = server->nextPendingConnection(); // Check if our ip is in private scope if (only_non_public_ip_ && !IpIsPrivate(client_socket->peerAddress())) { - qLog(Info) << "Got a connection from public ip" << - client_socket->peerAddress().toString(); + qLog(Info) << "Got a connection from public ip" + << client_socket->peerAddress().toString(); client_socket->close(); } else { CreateRemoteClient(client_socket); @@ -219,11 +213,9 @@ void NetworkRemote::CreateRemoteClient(QTcpSocket* client_socket) { } void NetworkRemote::EnableKittens(bool aww) { - if (outgoing_data_creator_.get()) - outgoing_data_creator_->EnableKittens(aww); + if (outgoing_data_creator_.get()) outgoing_data_creator_->EnableKittens(aww); } -void NetworkRemote::SendKitten(quint64 id, const QImage &kitten) { - if (outgoing_data_creator_.get()) - outgoing_data_creator_->SendKitten(kitten); +void NetworkRemote::SendKitten(quint64 id, const QImage& kitten) { + if (outgoing_data_creator_.get()) outgoing_data_creator_->SendKitten(kitten); } diff --git a/src/networkremote/networkremote.h b/src/networkremote/networkremote.h index 716538251..06c8afb73 100644 --- a/src/networkremote/networkremote.h +++ b/src/networkremote/networkremote.h @@ -13,15 +13,15 @@ #include "remoteclient.h" class NetworkRemote : public QObject { - Q_OBJECT -public: + Q_OBJECT + public: static const char* kSettingsGroup; static const quint16 kDefaultServerPort; explicit NetworkRemote(Application* app, QObject* parent = 0); ~NetworkRemote(); -public slots: + public slots: void SetupServer(); void StartServer(); void ReloadSettings(); @@ -29,7 +29,7 @@ public slots: void EnableKittens(bool aww); void SendKitten(quint64 id, const QImage& kitten); -private: + private: std::unique_ptr server_; std::unique_ptr server_ipv6_; std::unique_ptr incoming_data_parser_; @@ -49,4 +49,4 @@ private: bool IpIsPrivate(const QHostAddress& address); }; -#endif // NETWORKREMOTE_H +#endif // NETWORKREMOTE_H diff --git a/src/networkremote/networkremotehelper.cpp b/src/networkremote/networkremotehelper.cpp index 8df9013db..6c7496555 100644 --- a/src/networkremote/networkremotehelper.cpp +++ b/src/networkremote/networkremotehelper.cpp @@ -22,35 +22,30 @@ NetworkRemoteHelper* NetworkRemoteHelper::sInstance = nullptr; -NetworkRemoteHelper::NetworkRemoteHelper(Application* app) - : app_(app) -{ +NetworkRemoteHelper::NetworkRemoteHelper(Application* app) : app_(app) { app_ = app; - connect(this, SIGNAL(ReloadSettingsSig()), - app_->network_remote(), SLOT(ReloadSettings())); - connect(this, SIGNAL(StartServerSig()), - app_->network_remote(), SLOT(StartServer())); - connect(this, SIGNAL(SetupServerSig()), - app_->network_remote(), SLOT(SetupServer())); + connect(this, SIGNAL(ReloadSettingsSig()), app_->network_remote(), + SLOT(ReloadSettings())); + connect(this, SIGNAL(StartServerSig()), app_->network_remote(), + SLOT(StartServer())); + connect(this, SIGNAL(SetupServerSig()), app_->network_remote(), + SLOT(SetupServer())); // Start the server once the playlistmanager is initialized - connect(app_->playlist_manager(), SIGNAL(PlaylistManagerInitialized()), - this, SLOT(StartServer())); + connect(app_->playlist_manager(), SIGNAL(PlaylistManagerInitialized()), this, + SLOT(StartServer())); sInstance = this; } -NetworkRemoteHelper::~NetworkRemoteHelper() { -} +NetworkRemoteHelper::~NetworkRemoteHelper() {} void NetworkRemoteHelper::StartServer() { emit SetupServerSig(); emit StartServerSig(); } -void NetworkRemoteHelper::ReloadSettings() { - emit ReloadSettingsSig(); -} +void NetworkRemoteHelper::ReloadSettings() { emit ReloadSettingsSig(); } // For using in Settingsdialog, we haven't the appication there NetworkRemoteHelper* NetworkRemoteHelper::Instance() { diff --git a/src/networkremote/networkremotehelper.h b/src/networkremote/networkremotehelper.h index 3c0943f9d..8bb36efee 100644 --- a/src/networkremote/networkremotehelper.h +++ b/src/networkremote/networkremotehelper.h @@ -6,8 +6,8 @@ #include "networkremote.h" class NetworkRemoteHelper : public QObject { - Q_OBJECT -public: + Q_OBJECT + public: static NetworkRemoteHelper* Instance(); NetworkRemoteHelper(Application* app); @@ -15,7 +15,7 @@ public: void ReloadSettings(); -private slots: + private slots: void StartServer(); signals: @@ -23,9 +23,9 @@ signals: void StartServerSig(); void ReloadSettingsSig(); -private: + private: static NetworkRemoteHelper* sInstance; Application* app_; }; -#endif // NETWORKREMOTEHELPER_H +#endif // NETWORKREMOTEHELPER_H diff --git a/src/networkremote/outgoingdatacreator.cpp b/src/networkremote/outgoingdatacreator.cpp index eaed5a2e6..61347095e 100644 --- a/src/networkremote/outgoingdatacreator.cpp +++ b/src/networkremote/outgoingdatacreator.cpp @@ -29,22 +29,20 @@ #include #include "core/database.h" -const quint32 OutgoingDataCreator::kFileChunkSize = 100000; // in Bytes +const quint32 OutgoingDataCreator::kFileChunkSize = 100000; // in Bytes OutgoingDataCreator::OutgoingDataCreator(Application* app) - : app_(app), - aww_(false), - ultimate_reader_(new UltimateLyricsReader(this)), - fetcher_(new SongInfoFetcher(this)) -{ + : app_(app), + aww_(false), + ultimate_reader_(new UltimateLyricsReader(this)), + fetcher_(new SongInfoFetcher(this)) { // Create Keep Alive Timer keep_alive_timer_ = new QTimer(this); connect(keep_alive_timer_, SIGNAL(timeout()), this, SLOT(SendKeepAlive())); keep_alive_timeout_ = 10000; } -OutgoingDataCreator::~OutgoingDataCreator() { -} +OutgoingDataCreator::~OutgoingDataCreator() {} void OutgoingDataCreator::SetClients(QList* clients) { clients_ = clients; @@ -54,17 +52,18 @@ void OutgoingDataCreator::SetClients(QList* clients) { // Create the song position timer track_position_timer_ = new QTimer(this); - connect(track_position_timer_, SIGNAL(timeout()), this, SLOT(UpdateTrackPosition())); + connect(track_position_timer_, SIGNAL(timeout()), this, + SLOT(UpdateTrackPosition())); // Parse the ultimate lyrics xml file ultimate_reader_->SetThread(this->thread()); provider_list_ = ultimate_reader_->Parse(":lyrics/ultimate_providers.xml"); // Set up the lyrics parser - connect(fetcher_, SIGNAL(ResultReady(int,SongInfoFetcher::Result)), - SLOT(SendLyrics(int,SongInfoFetcher::Result))); + connect(fetcher_, SIGNAL(ResultReady(int, SongInfoFetcher::Result)), + SLOT(SendLyrics(int, SongInfoFetcher::Result))); - foreach (SongInfoProvider* provider, provider_list_) { + foreach(SongInfoProvider * provider, provider_list_) { fetcher_->AddProvider(provider); } @@ -99,32 +98,34 @@ void OutgoingDataCreator::CheckEnabledProviders() { << "darklyrics.com"; QVariant saved_order = s.value("search_order", default_order); - foreach (const QVariant& name, saved_order.toList()) { + foreach(const QVariant & name, saved_order.toList()) { SongInfoProvider* provider = ProviderByName(name.toString()); - if (provider) - ordered_providers << provider; + if (provider) ordered_providers << provider; } // Enable all the providers in the list and rank them int relevance = 100; - foreach (SongInfoProvider* provider, ordered_providers) { + foreach(SongInfoProvider * provider, ordered_providers) { provider->set_enabled(true); qobject_cast(provider)->set_relevance(relevance--); } - // Any lyric providers we don't have in ordered_providers are considered disabled - foreach (SongInfoProvider* provider, fetcher_->providers()) { - if (qobject_cast(provider) && !ordered_providers.contains(provider)) { + // Any lyric providers we don't have in ordered_providers are considered + // disabled + foreach(SongInfoProvider * provider, fetcher_->providers()) { + if (qobject_cast(provider) && + !ordered_providers.contains(provider)) { provider->set_enabled(false); } } } -SongInfoProvider* OutgoingDataCreator::ProviderByName(const QString& name) const { - foreach (SongInfoProvider* provider, fetcher_->providers()) { - if (UltimateLyricsProvider* lyrics = qobject_cast(provider)) { - if (lyrics->name() == name) - return provider; +SongInfoProvider* OutgoingDataCreator::ProviderByName(const QString& name) + const { + foreach(SongInfoProvider * provider, fetcher_->providers()) { + if (UltimateLyricsProvider* lyrics = + qobject_cast(provider)) { + if (lyrics->name() == name) return provider; } } return nullptr; @@ -168,23 +169,29 @@ void OutgoingDataCreator::SendClementineInfo() { msg.mutable_response_clementine_info(); SetEngineState(info); - QString version = QString("%1 %2").arg(QCoreApplication::applicationName(), - QCoreApplication::applicationVersion()); + QString version = + QString("%1 %2").arg(QCoreApplication::applicationName(), + QCoreApplication::applicationVersion()); info->set_version(version.toAscii()); SendDataToClients(&msg); } -void OutgoingDataCreator::SetEngineState(pb::remote::ResponseClementineInfo* msg) { - switch(app_->player()->GetState()) { - case Engine::Idle: msg->set_state(pb::remote::Idle); - break; +void OutgoingDataCreator::SetEngineState( + pb::remote::ResponseClementineInfo* msg) { + switch (app_->player()->GetState()) { + case Engine::Idle: + msg->set_state(pb::remote::Idle); + break; case Engine::Error: - case Engine::Empty: msg->set_state(pb::remote::Empty); - break; - case Engine::Playing: msg->set_state(pb::remote::Playing); - break; - case Engine::Paused: msg->set_state(pb::remote::Paused); - break; + case Engine::Empty: + msg->set_state(pb::remote::Empty); + break; + case Engine::Playing: + msg->set_state(pb::remote::Playing); + break; + case Engine::Paused: + msg->set_state(pb::remote::Paused); + break; } } @@ -200,11 +207,10 @@ void OutgoingDataCreator::SendAllPlaylists() { pb::remote::ResponsePlaylists* playlists = msg.mutable_response_playlists(); // Get all playlists, even ones that are hidden in the UI. - foreach (const PlaylistBackend::Playlist& p, - app_->playlist_backend()->GetAllPlaylists()) { + foreach(const PlaylistBackend::Playlist & p, + app_->playlist_backend()->GetAllPlaylists()) { bool playlist_open = app_->playlist_manager()->IsPlaylistOpen(p.id); - int item_count = playlist_open ? - app_playlists.at(p.id)->rowCount() : 0; + int item_count = playlist_open ? app_playlists.at(p.id)->rowCount() : 0; // Create a new playlist pb::remote::Playlist* playlist = playlists->add_playlist(); @@ -230,7 +236,7 @@ void OutgoingDataCreator::SendAllActivePlaylists() { pb::remote::ResponsePlaylists* playlists = msg.mutable_response_playlists(); QListIterator it(app_playlists); - while(it.hasNext()) { + while (it.hasNext()) { // Get the next Playlist Playlist* p = it.next(); QString playlist_name = app_->playlist_manager()->GetPlaylistName(p->id()); @@ -258,17 +264,14 @@ void OutgoingDataCreator::ActiveChanged(Playlist* playlist) { SendDataToClients(&msg); } -void OutgoingDataCreator::PlaylistAdded(int id, const QString& name, bool favorite) { +void OutgoingDataCreator::PlaylistAdded(int id, const QString& name, + bool favorite) { SendAllActivePlaylists(); } -void OutgoingDataCreator::PlaylistDeleted(int id) { - SendAllActivePlaylists(); -} +void OutgoingDataCreator::PlaylistDeleted(int id) { SendAllActivePlaylists(); } -void OutgoingDataCreator::PlaylistClosed(int id) { - SendAllActivePlaylists(); -} +void OutgoingDataCreator::PlaylistClosed(int id) { SendAllActivePlaylists(); } void OutgoingDataCreator::PlaylistRenamed(int id, const QString& new_name) { SendAllActivePlaylists(); @@ -313,9 +316,11 @@ void OutgoingDataCreator::SendFirstData(bool send_playlist_songs) { SendDataToClients(&msg); } -void OutgoingDataCreator::CurrentSongChanged(const Song& song, const QString& uri, const QImage& img) { - current_song_ = song; - current_uri_ = uri; +void OutgoingDataCreator::CurrentSongChanged(const Song& song, + const QString& uri, + const QImage& img) { + current_song_ = song; + current_uri_ = uri; if (!aww_) { current_image_ = img; @@ -331,27 +336,26 @@ void OutgoingDataCreator::SendSongMetadata() { // If there is no song, create an empty node, otherwise fill it with data int i = app_->playlist_manager()->active()->current_row(); - CreateSong( - current_song_, current_image_, i, - msg.mutable_response_current_metadata()->mutable_song_metadata()); + CreateSong(current_song_, current_image_, i, + msg.mutable_response_current_metadata()->mutable_song_metadata()); SendDataToClients(&msg); } -void OutgoingDataCreator::CreateSong( - const Song& song, - const QImage& art, - const int index, - pb::remote::SongMetadata* song_metadata) { +void OutgoingDataCreator::CreateSong(const Song& song, const QImage& art, + const int index, + pb::remote::SongMetadata* song_metadata) { if (song.is_valid()) { song_metadata->set_id(song.id()); song_metadata->set_index(index); song_metadata->set_title(DataCommaSizeFromQString(song.PrettyTitle())); song_metadata->set_artist(DataCommaSizeFromQString(song.artist())); song_metadata->set_album(DataCommaSizeFromQString(song.album())); - song_metadata->set_albumartist(DataCommaSizeFromQString(song.albumartist())); + song_metadata->set_albumartist( + DataCommaSizeFromQString(song.albumartist())); song_metadata->set_length(song.length_nanosec() / kNsecPerSec); - song_metadata->set_pretty_length(DataCommaSizeFromQString(song.PrettyLength())); + song_metadata->set_pretty_length( + DataCommaSizeFromQString(song.PrettyLength())); song_metadata->set_genre(DataCommaSizeFromQString(song.genre())); song_metadata->set_pretty_year(DataCommaSizeFromQString(song.PrettyYear())); song_metadata->set_track(song.track()); @@ -384,7 +388,6 @@ void OutgoingDataCreator::CreateSong( } } - void OutgoingDataCreator::VolumeChanged(int volume) { // Create the message pb::remote::Message msg; @@ -396,7 +399,7 @@ void OutgoingDataCreator::VolumeChanged(int volume) { void OutgoingDataCreator::SendPlaylistSongs(int id) { // Get the PlaylistQByteArray(data.data(), data.size() Playlist* playlist = app_->playlist_manager()->playlist(id); - if(!playlist) { + if (!playlist) { qLog(Info) << "Could not find playlist with id = " << id; return; } @@ -407,7 +410,7 @@ void OutgoingDataCreator::SendPlaylistSongs(int id) { // Create the Response message pb::remote::ResponsePlaylistSongs* pb_response_playlist_songs = - msg.mutable_response_playlist_songs(); + msg.mutable_response_playlist_songs(); // Create a new playlist pb::remote::Playlist* pb_playlist = @@ -419,8 +422,8 @@ void OutgoingDataCreator::SendPlaylistSongs(int id) { SongList song_list = playlist->GetAllSongs(); QListIterator it(song_list); QImage null_img; - while(it.hasNext()) { - Song song = it.next(); + while (it.hasNext()) { + Song song = it.next(); pb::remote::SongMetadata* pb_song = pb_response_playlist_songs->add_songs(); CreateSong(song, null_img, index, pb_song); ++index; @@ -445,18 +448,22 @@ void OutgoingDataCreator::StateChanged(Engine::State state) { pb::remote::Message msg; switch (state) { - case Engine::Playing: msg.set_type(pb::remote::PLAY); - track_position_timer_->start(1000); - break; - case Engine::Paused: msg.set_type(pb::remote::PAUSE); - track_position_timer_->stop(); - break; - case Engine::Empty: msg.set_type(pb::remote::STOP); // Empty is called when player stopped - track_position_timer_->stop(); - break; - default: msg.set_type(pb::remote::STOP); - track_position_timer_->stop(); - break; + case Engine::Playing: + msg.set_type(pb::remote::PLAY); + track_position_timer_->start(1000); + break; + case Engine::Paused: + msg.set_type(pb::remote::PAUSE); + track_position_timer_->stop(); + break; + case Engine::Empty: + msg.set_type(pb::remote::STOP); // Empty is called when player stopped + track_position_timer_->stop(); + break; + default: + msg.set_type(pb::remote::STOP); + track_position_timer_->stop(); + break; }; SendDataToClients(&msg); @@ -467,18 +474,18 @@ void OutgoingDataCreator::SendRepeatMode(PlaylistSequence::RepeatMode mode) { msg.set_type(pb::remote::REPEAT); switch (mode) { - case PlaylistSequence::Repeat_Off: - msg.mutable_repeat()->set_repeat_mode(pb::remote::Repeat_Off); - break; - case PlaylistSequence::Repeat_Track: - msg.mutable_repeat()->set_repeat_mode(pb::remote::Repeat_Track); - break; - case PlaylistSequence::Repeat_Album: - msg.mutable_repeat()->set_repeat_mode(pb::remote::Repeat_Album); - break; - case PlaylistSequence::Repeat_Playlist: - msg.mutable_repeat()->set_repeat_mode(pb::remote::Repeat_Playlist); - break; + case PlaylistSequence::Repeat_Off: + msg.mutable_repeat()->set_repeat_mode(pb::remote::Repeat_Off); + break; + case PlaylistSequence::Repeat_Track: + msg.mutable_repeat()->set_repeat_mode(pb::remote::Repeat_Track); + break; + case PlaylistSequence::Repeat_Album: + msg.mutable_repeat()->set_repeat_mode(pb::remote::Repeat_Album); + break; + case PlaylistSequence::Repeat_Playlist: + msg.mutable_repeat()->set_repeat_mode(pb::remote::Repeat_Playlist); + break; } SendDataToClients(&msg); @@ -489,18 +496,18 @@ void OutgoingDataCreator::SendShuffleMode(PlaylistSequence::ShuffleMode mode) { msg.set_type(pb::remote::SHUFFLE); switch (mode) { - case PlaylistSequence::Shuffle_Off: - msg.mutable_shuffle()->set_shuffle_mode(pb::remote::Shuffle_Off); - break; - case PlaylistSequence::Shuffle_All: - msg.mutable_shuffle()->set_shuffle_mode(pb::remote::Shuffle_All); - break; - case PlaylistSequence::Shuffle_InsideAlbum: - msg.mutable_shuffle()->set_shuffle_mode(pb::remote::Shuffle_InsideAlbum); - break; - case PlaylistSequence::Shuffle_Albums: - msg.mutable_shuffle()->set_shuffle_mode(pb::remote::Shuffle_Albums); - break; + case PlaylistSequence::Shuffle_Off: + msg.mutable_shuffle()->set_shuffle_mode(pb::remote::Shuffle_Off); + break; + case PlaylistSequence::Shuffle_All: + msg.mutable_shuffle()->set_shuffle_mode(pb::remote::Shuffle_All); + break; + case PlaylistSequence::Shuffle_InsideAlbum: + msg.mutable_shuffle()->set_shuffle_mode(pb::remote::Shuffle_InsideAlbum); + break; + case PlaylistSequence::Shuffle_Albums: + msg.mutable_shuffle()->set_shuffle_mode(pb::remote::Shuffle_Albums); + break; } SendDataToClients(&msg); @@ -517,9 +524,10 @@ void OutgoingDataCreator::UpdateTrackPosition() { msg.set_type(pb::remote::UPDATE_TRACK_POSITION); int position = std::floor( - float(app_->player()->engine()->position_nanosec()) / kNsecPerSec + 0.5); + float(app_->player()->engine()->position_nanosec()) / kNsecPerSec + 0.5); - if (app_->player()->engine()->position_nanosec() > current_song_.length_nanosec()) + if (app_->player()->engine()->position_nanosec() > + current_song_.length_nanosec()) position = last_track_position_; msg.mutable_response_update_track_position()->set_position(position); @@ -532,24 +540,24 @@ void OutgoingDataCreator::UpdateTrackPosition() { void OutgoingDataCreator::DisconnectAllClients() { pb::remote::Message msg; msg.set_type(pb::remote::DISCONNECT); - msg.mutable_response_disconnect()->set_reason_disconnect(pb::remote::Server_Shutdown); + msg.mutable_response_disconnect()->set_reason_disconnect( + pb::remote::Server_Shutdown); SendDataToClients(&msg); } -void OutgoingDataCreator::GetLyrics() { - fetcher_->FetchInfo(current_song_); -} +void OutgoingDataCreator::GetLyrics() { fetcher_->FetchInfo(current_song_); } -void OutgoingDataCreator::SendLyrics(int id, const SongInfoFetcher::Result& result) { +void OutgoingDataCreator::SendLyrics(int id, + const SongInfoFetcher::Result& result) { pb::remote::Message msg; msg.set_type(pb::remote::LYRICS); pb::remote::ResponseLyrics* response = msg.mutable_response_lyrics(); - foreach (const CollapsibleInfoPane::Data& data, result.info_) { + foreach(const CollapsibleInfoPane::Data & data, result.info_) { // If the size is zero, do not send the provider - UltimateLyricsLyric* editor = qobject_cast(data.content_object_); - if (editor->toPlainText().length() == 0) - continue; + UltimateLyricsLyric* editor = + qobject_cast(data.content_object_); + if (editor->toPlainText().length() == 0) continue; pb::remote::Lyric* lyric = response->mutable_lyrics()->Add(); @@ -562,36 +570,35 @@ void OutgoingDataCreator::SendLyrics(int id, const SongInfoFetcher::Result& resu results_.take(id); } -void OutgoingDataCreator::SendSongs(const pb::remote::RequestDownloadSongs &request, - RemoteClient* client) { +void OutgoingDataCreator::SendSongs( + const pb::remote::RequestDownloadSongs& request, RemoteClient* client) { if (!download_queue_.contains(client)) { - download_queue_.insert(client, QQueue() ); + download_queue_.insert(client, QQueue()); } switch (request.download_item()) { - case pb::remote::CurrentItem: { - DownloadItem item(current_song_, 1 , 1); - download_queue_[client].append(item); - break; - } - case pb::remote::ItemAlbum: - SendAlbum(client, current_song_); - break; - case pb::remote::APlaylist: - SendPlaylist(client, request.playlist_id()); - break; - default: - break; + case pb::remote::CurrentItem: { + DownloadItem item(current_song_, 1, 1); + download_queue_[client].append(item); + break; + } + case pb::remote::ItemAlbum: + SendAlbum(client, current_song_); + break; + case pb::remote::APlaylist: + SendPlaylist(client, request.playlist_id()); + break; + default: + break; } // Send first file OfferNextSong(client); } -void OutgoingDataCreator::OfferNextSong(RemoteClient *client) { - if (!download_queue_.contains(client)) - return; +void OutgoingDataCreator::OfferNextSong(RemoteClient* client) { + if (!download_queue_.contains(client)) return; pb::remote::Message msg; @@ -603,7 +610,8 @@ void OutgoingDataCreator::OfferNextSong(RemoteClient *client) { DownloadItem item = download_queue_[client].head(); msg.set_type(pb::remote::SONG_FILE_CHUNK); - pb::remote::ResponseSongFileChunk* chunk = msg.mutable_response_song_file_chunk(); + pb::remote::ResponseSongFileChunk* chunk = + msg.mutable_response_song_file_chunk(); // Song offer is chunk no 0 chunk->set_chunk_count(0); @@ -611,19 +619,17 @@ void OutgoingDataCreator::OfferNextSong(RemoteClient *client) { chunk->set_file_count(item.song_count_); chunk->set_file_number(item.song_no_); - CreateSong(item.song_, QImage() , -1, - chunk->mutable_song_metadata()); + CreateSong(item.song_, QImage(), -1, chunk->mutable_song_metadata()); } client->SendData(&msg); } -void OutgoingDataCreator::ResponseSongOffer(RemoteClient *client, bool accepted) { - if (!download_queue_.contains(client)) - return; +void OutgoingDataCreator::ResponseSongOffer(RemoteClient* client, + bool accepted) { + if (!download_queue_.contains(client)) return; - if (download_queue_.value(client).isEmpty()) - return; + if (download_queue_.value(client).isEmpty()) return; // Get the item and send the single song DownloadItem item = download_queue_[client].dequeue(); @@ -634,11 +640,10 @@ void OutgoingDataCreator::ResponseSongOffer(RemoteClient *client, bool accepted) OfferNextSong(client); } -void OutgoingDataCreator::SendSingleSong(RemoteClient* client, const Song &song, +void OutgoingDataCreator::SendSingleSong(RemoteClient* client, const Song& song, int song_no, int song_count) { // Only local files!!! - if (!(song.url().scheme() == "file")) - return; + if (!(song.url().scheme() == "file")) return; // Open the file QFile file(song.url().toLocalFile()); @@ -651,13 +656,14 @@ void OutgoingDataCreator::SendSingleSong(RemoteClient* client, const Song &song, QByteArray data; pb::remote::Message msg; - pb::remote::ResponseSongFileChunk* chunk = msg.mutable_response_song_file_chunk(); + pb::remote::ResponseSongFileChunk* chunk = + msg.mutable_response_song_file_chunk(); msg.set_type(pb::remote::SONG_FILE_CHUNK); QImage null_image; // Calculate the number of chunks - int chunk_count = qRound((file.size() / kFileChunkSize) + 0.5); + int chunk_count = qRound((file.size() / kFileChunkSize) + 0.5); int chunk_number = 1; while (!file.atEnd()) { @@ -678,8 +684,8 @@ void OutgoingDataCreator::SendSingleSong(RemoteClient* client, const Song &song, if (chunk_number == 1) { int i = app_->playlist_manager()->active()->current_row(); CreateSong( - song, null_image, i, - msg.mutable_response_song_file_chunk()->mutable_song_metadata()); + song, null_image, i, + msg.mutable_response_song_file_chunk()->mutable_song_metadata()); } // Send data directly to the client @@ -695,22 +701,21 @@ void OutgoingDataCreator::SendSingleSong(RemoteClient* client, const Song &song, file.close(); } -void OutgoingDataCreator::SendAlbum(RemoteClient *client, const Song &song) { +void OutgoingDataCreator::SendAlbum(RemoteClient* client, const Song& song) { // No streams! - if (song.url().scheme() != "file") - return; + if (song.url().scheme() != "file") return; SongList album = app_->library_backend()->GetSongsByAlbum(song.album()); - foreach (Song s, album) { - DownloadItem item(s, album.indexOf(s)+1, album.size()); + foreach(Song s, album) { + DownloadItem item(s, album.indexOf(s) + 1, album.size()); download_queue_[client].append(item); } } -void OutgoingDataCreator::SendPlaylist(RemoteClient *client, int playlist_id) { +void OutgoingDataCreator::SendPlaylist(RemoteClient* client, int playlist_id) { Playlist* playlist = app_->playlist_manager()->playlist(playlist_id); - if(!playlist) { + if (!playlist) { qLog(Info) << "Could not find playlist with id = " << playlist_id; return; } @@ -718,22 +723,22 @@ void OutgoingDataCreator::SendPlaylist(RemoteClient *client, int playlist_id) { // Count the local songs int count = 0; - foreach (Song s, song_list) { + foreach(Song s, song_list) { if (s.url().scheme() == "file") { count++; } } - foreach (Song s, song_list) { + foreach(Song s, song_list) { // Only local files! if (s.url().scheme() == "file") { - DownloadItem item(s, song_list.indexOf(s)+1, count); + DownloadItem item(s, song_list.indexOf(s) + 1, count); download_queue_[client].append(item); } } } -void OutgoingDataCreator::SendLibrary(RemoteClient *client) { +void OutgoingDataCreator::SendLibrary(RemoteClient* client) { // Get a temporary file name QString temp_file_name = Utilities::GetTemporaryFileName(); @@ -744,7 +749,10 @@ void OutgoingDataCreator::SendLibrary(RemoteClient *client) { app_->database()->AttachDatabaseOnDbConnection("songs_export", adb, db); // Copy the content of the song table to this temporary database - QSqlQuery q(QString("create table songs_export.songs as SELECT * FROM songs where unavailable = 0;"), db); + QSqlQuery q(QString( + "create table songs_export.songs as SELECT * FROM songs " + "where unavailable = 0;"), + db); if (app_->database()->CheckErrors(q)) return; @@ -762,11 +770,12 @@ void OutgoingDataCreator::SendLibrary(RemoteClient *client) { QByteArray data; pb::remote::Message msg; - pb::remote::ResponseLibraryChunk* chunk = msg.mutable_response_library_chunk(); + pb::remote::ResponseLibraryChunk* chunk = + msg.mutable_response_library_chunk(); msg.set_type(pb::remote::LIBRARY_CHUNK); // Calculate the number of chunks - int chunk_count = qRound((file.size() / kFileChunkSize) + 0.5); + int chunk_count = qRound((file.size() / kFileChunkSize) + 0.5); int chunk_number = 1; while (!file.atEnd()) { @@ -794,9 +803,7 @@ void OutgoingDataCreator::SendLibrary(RemoteClient *client) { file.remove(); } -void OutgoingDataCreator::EnableKittens(bool aww) { - aww_ = aww; -} +void OutgoingDataCreator::EnableKittens(bool aww) { aww_ = aww; } void OutgoingDataCreator::SendKitten(const QImage& kitten) { if (aww_) { @@ -804,4 +811,3 @@ void OutgoingDataCreator::SendKitten(const QImage& kitten) { SendSongMetadata(); } } - diff --git a/src/networkremote/outgoingdatacreator.h b/src/networkremote/outgoingdatacreator.h index fb243a3db..5a2083727 100644 --- a/src/networkremote/outgoingdatacreator.h +++ b/src/networkremote/outgoingdatacreator.h @@ -33,15 +33,13 @@ struct DownloadItem { Song song_; int song_no_; int song_count_; - DownloadItem(Song s, int no, int count) : - song_(s), - song_no_(no), - song_count_(count) { } + DownloadItem(Song s, int no, int count) + : song_(s), song_no_(no), song_count_(count) {} }; class OutgoingDataCreator : public QObject { - Q_OBJECT -public: + Q_OBJECT + public: OutgoingDataCreator(Application* app); ~OutgoingDataCreator(); @@ -49,7 +47,7 @@ public: void SetClients(QList* clients); -public slots: + public slots: void SendClementineInfo(); void SendAllPlaylists(); void SendAllActivePlaylists(); @@ -62,7 +60,8 @@ public slots: void PlaylistClosed(int id); void PlaylistRenamed(int id, const QString& new_name); void ActiveChanged(Playlist*); - void CurrentSongChanged(const Song& song, const QString& uri, const QImage& img); + void CurrentSongChanged(const Song& song, const QString& uri, + const QImage& img); void SendSongMetadata(); void StateChanged(Engine::State); void SendKeepAlive(); @@ -72,13 +71,14 @@ public slots: void DisconnectAllClients(); void GetLyrics(); void SendLyrics(int id, const SongInfoFetcher::Result& result); - void SendSongs(const pb::remote::RequestDownloadSongs& request, RemoteClient* client); + void SendSongs(const pb::remote::RequestDownloadSongs& request, + RemoteClient* client); void ResponseSongOffer(RemoteClient* client, bool accepted); void SendLibrary(RemoteClient* client); void EnableKittens(bool aww); void SendKitten(const QImage& kitten); -private: + private: Application* app_; QList* clients_; Song current_song_; @@ -99,17 +99,15 @@ private: void SendDataToClients(pb::remote::Message* msg); void SetEngineState(pb::remote::ResponseClementineInfo* msg); - void CreateSong( - const Song& song, - const QImage& art, - const int index, - pb::remote::SongMetadata* song_metadata); + void CreateSong(const Song& song, const QImage& art, const int index, + pb::remote::SongMetadata* song_metadata); void CheckEnabledProviders(); SongInfoProvider* ProviderByName(const QString& name) const; - void SendSingleSong(RemoteClient* client, const Song& song, int song_no, int song_count); + void SendSingleSong(RemoteClient* client, const Song& song, int song_no, + int song_count); void SendAlbum(RemoteClient* client, const Song& song); void SendPlaylist(RemoteClient* client, int playlist_id); void OfferNextSong(RemoteClient* client); }; -#endif // OUTGOINGDATACREATOR_H +#endif // OUTGOINGDATACREATOR_H diff --git a/src/networkremote/remoteclient.cpp b/src/networkremote/remoteclient.cpp index 6079828c4..cd05bdade 100644 --- a/src/networkremote/remoteclient.cpp +++ b/src/networkremote/remoteclient.cpp @@ -24,10 +24,7 @@ #include RemoteClient::RemoteClient(Application* app, QTcpSocket* client) - : app_(app), - downloader_(false), - client_(client) -{ + : app_(app), downloader_(false), client_(client) { // Open the buffer buffer_.setData(QByteArray()); buffer_.open(QIODevice::ReadWrite); @@ -41,7 +38,7 @@ RemoteClient::RemoteClient(Application* app, QTcpSocket* client) s.beginGroup(NetworkRemote::kSettingsGroup); use_auth_code_ = s.value("use_auth_code", false).toBool(); - auth_code_ = s.value("auth_code", 0).toInt(); + auth_code_ = s.value("auth_code", 0).toInt(); allow_downloads_ = s.value("allow_downloads", false).toBool(); s.endGroup(); @@ -56,9 +53,7 @@ RemoteClient::~RemoteClient() { client_->waitForDisconnected(2000); } -void RemoteClient::setDownloader(bool downloader) { - downloader_ = downloader; -} +void RemoteClient::setDownloader(bool downloader) { downloader_ = downloader; } void RemoteClient::IncomingData() { while (client_->bytesAvailable()) { @@ -80,8 +75,7 @@ void RemoteClient::IncomingData() { } // Read some of the message - buffer_.write( - client_->read(expected_length_ - buffer_.size())); + buffer_.write(client_->read(expected_length_ - buffer_.size())); // Did we get everything? if (buffer_.size() == expected_length_) { @@ -97,7 +91,7 @@ void RemoteClient::IncomingData() { } } -void RemoteClient::ParseMessage(const QByteArray &data) { +void RemoteClient::ParseMessage(const QByteArray& data) { pb::remote::Message msg; if (!msg.ParseFromArray(data.constData(), data.size())) { qLog(Info) << "Couldn't parse data"; @@ -153,7 +147,7 @@ void RemoteClient::DisconnectClient(pb::remote::ReasonDisconnect reason) { } // Sends data to client without check if authenticated -void RemoteClient::SendDataToClient(pb::remote::Message *msg) { +void RemoteClient::SendDataToClient(pb::remote::Message* msg) { // Set the default version msg->set_version(msg->default_instance().version()); @@ -180,13 +174,11 @@ void RemoteClient::SendDataToClient(pb::remote::Message *msg) { } } -void RemoteClient::SendData(pb::remote::Message *msg) { +void RemoteClient::SendData(pb::remote::Message* msg) { // Check if client is authenticated before sending the data if (authenticated_) { SendDataToClient(msg); } } -QAbstractSocket::SocketState RemoteClient::State() { - return client_->state(); -} +QAbstractSocket::SocketState RemoteClient::State() { return client_->state(); } diff --git a/src/networkremote/remoteclient.h b/src/networkremote/remoteclient.h index 1acf6ffef..b1812b571 100644 --- a/src/networkremote/remoteclient.h +++ b/src/networkremote/remoteclient.h @@ -9,8 +9,8 @@ #include "remotecontrolmessages.pb.h" class RemoteClient : public QObject { - Q_OBJECT -public: + Q_OBJECT + public: RemoteClient(Application* app, QTcpSocket* client); ~RemoteClient(); @@ -21,13 +21,13 @@ public: bool isDownloader() { return downloader_; } void DisconnectClient(pb::remote::ReasonDisconnect reason); -private slots: + private slots: void IncomingData(); signals: void Parse(const pb::remote::Message& msg); -private: + private: void ParseMessage(const QByteArray& data); // Sends data to client without check if authenticated @@ -47,4 +47,4 @@ private: QBuffer buffer_; }; -#endif // REMOTECLIENT_H +#endif // REMOTECLIENT_H diff --git a/src/networkremote/tinysvcmdns.cpp b/src/networkremote/tinysvcmdns.cpp index 3c438178a..2b102e5cc 100644 --- a/src/networkremote/tinysvcmdns.cpp +++ b/src/networkremote/tinysvcmdns.cpp @@ -18,32 +18,32 @@ void TinySVCMDNS::CreateMdnsd(uint32_t ipv4, QString ipv6) { mdnsd* mdnsd = mdnsd_start_bind(ipv4); // Set our hostname - mdnsd_set_hostname( - mdnsd, - QString(host + ".local").toUtf8().constData(), - ipv4); + mdnsd_set_hostname(mdnsd, QString(host + ".local").toUtf8().constData(), + ipv4); // Add to the list mdnsd_.append(mdnsd); } -TinySVCMDNS::TinySVCMDNS() { +TinySVCMDNS::TinySVCMDNS() { // Get all network interfaces - QList network_interfaces = QNetworkInterface::allInterfaces(); - foreach (QNetworkInterface network_interface, network_interfaces) { + QList network_interfaces = + QNetworkInterface::allInterfaces(); + foreach(QNetworkInterface network_interface, network_interfaces) { // Only use up and non loopback interfaces - if (network_interface.flags().testFlag(network_interface.IsUp) - && !network_interface.flags().testFlag(network_interface.IsLoopBack)) - { + if (network_interface.flags().testFlag(network_interface.IsUp) && + !network_interface.flags().testFlag(network_interface.IsLoopBack)) { uint32_t ipv4 = 0; QString ipv6; qLog(Debug) << "Interface" << network_interface.humanReadableName(); - - // Now check all network addresses for this device - QList network_address_entries = network_interface.addressEntries(); - foreach (QNetworkAddressEntry network_address_entry, network_address_entries) { + // Now check all network addresses for this device + QList network_address_entries = + network_interface.addressEntries(); + + foreach(QNetworkAddressEntry network_address_entry, + network_address_entries) { QHostAddress host_address = network_address_entry.ip(); if (host_address.protocol() == QAbstractSocket::IPv4Protocol) { ipv4 = qToBigEndian(host_address.toIPv4Address()); @@ -53,7 +53,7 @@ TinySVCMDNS::TinySVCMDNS() { qLog(Debug) << " ipv6:" << host_address.toString(); } } - + // Now start the service CreateMdnsd(ipv4, ipv6); } @@ -61,30 +61,18 @@ TinySVCMDNS::TinySVCMDNS() { } TinySVCMDNS::~TinySVCMDNS() { - foreach(mdnsd* mdnsd, mdnsd_) { - mdnsd_stop(mdnsd); - } + foreach(mdnsd * mdnsd, mdnsd_) { mdnsd_stop(mdnsd); } } -void TinySVCMDNS::PublishInternal( - const QString& domain, - const QString& type, - const QByteArray& name, - quint16 port) { +void TinySVCMDNS::PublishInternal(const QString& domain, const QString& type, + const QByteArray& name, quint16 port) { // Some pointless text, so tinymDNS publishes the service correctly. - const char* txt[] = { - "cat=nyan", - nullptr - }; - - foreach(mdnsd* mdnsd, mdnsd_) { - mdnsd_register_svc( - mdnsd, - name.constData(), - QString(type + ".local").toUtf8().constData(), - port, - nullptr, - txt); + const char* txt[] = {"cat=nyan", nullptr}; + + foreach(mdnsd * mdnsd, mdnsd_) { + mdnsd_register_svc(mdnsd, name.constData(), + QString(type + ".local").toUtf8().constData(), port, + nullptr, txt); } } diff --git a/src/networkremote/tinysvcmdns.h b/src/networkremote/tinysvcmdns.h index 9d96beebd..a7dc16cb9 100644 --- a/src/networkremote/tinysvcmdns.h +++ b/src/networkremote/tinysvcmdns.h @@ -12,11 +12,8 @@ class TinySVCMDNS : public Zeroconf { virtual ~TinySVCMDNS(); protected: - virtual void PublishInternal( - const QString& domain, - const QString& type, - const QByteArray& name, - quint16 port); + virtual void PublishInternal(const QString& domain, const QString& type, + const QByteArray& name, quint16 port); private: void CreateMdnsd(uint32_t ipv4, QString ipv6); diff --git a/src/networkremote/zeroconf.cpp b/src/networkremote/zeroconf.cpp index a67c810c0..f46b73d79 100644 --- a/src/networkremote/zeroconf.cpp +++ b/src/networkremote/zeroconf.cpp @@ -18,21 +18,19 @@ Zeroconf* Zeroconf::sInstance = nullptr; -Zeroconf::~Zeroconf() { - -} +Zeroconf::~Zeroconf() {} Zeroconf* Zeroconf::GetZeroconf() { if (!sInstance) { - #ifdef HAVE_DBUS - sInstance = new Avahi; - #endif // HAVE_DBUS - #ifdef Q_OS_DARWIN - sInstance = new Bonjour; - #endif - #ifdef Q_OS_WIN32 - sInstance = new TinySVCMDNS; - #endif +#ifdef HAVE_DBUS + sInstance = new Avahi; +#endif // HAVE_DBUS +#ifdef Q_OS_DARWIN + sInstance = new Bonjour; +#endif +#ifdef Q_OS_WIN32 + sInstance = new TinySVCMDNS; +#endif } return sInstance; @@ -41,7 +39,7 @@ Zeroconf* Zeroconf::GetZeroconf() { QByteArray Zeroconf::TruncateName(const QString& name) { QTextCodec* codec = QTextCodec::codecForName("UTF-8"); QByteArray truncated_utf8; - foreach (QChar c, name) { + foreach(QChar c, name) { QByteArray rendered = codec->fromUnicode(&c, 1, nullptr); if (truncated_utf8.size() + rendered.size() >= 63) { break; @@ -53,15 +51,8 @@ QByteArray Zeroconf::TruncateName(const QString& name) { return truncated_utf8; } -void Zeroconf::Publish( - const QString& domain, - const QString& type, - const QString& name, - quint16 port) { +void Zeroconf::Publish(const QString& domain, const QString& type, + const QString& name, quint16 port) { QByteArray truncated_name = TruncateName(name); - PublishInternal( - domain, - type, - truncated_name, - port); + PublishInternal(domain, type, truncated_name, port); } diff --git a/src/networkremote/zeroconf.h b/src/networkremote/zeroconf.h index 047dd51aa..e81704629 100644 --- a/src/networkremote/zeroconf.h +++ b/src/networkremote/zeroconf.h @@ -7,11 +7,8 @@ class Zeroconf { public: virtual ~Zeroconf(); - void Publish( - const QString& domain, - const QString& type, - const QString& name, - quint16 port); + void Publish(const QString& domain, const QString& type, const QString& name, + quint16 port); static Zeroconf* GetZeroconf(); @@ -19,11 +16,8 @@ class Zeroconf { static QByteArray TruncateName(const QString& name); protected: - virtual void PublishInternal( - const QString& domain, - const QString& type, - const QByteArray& name, - quint16 port) = 0; + virtual void PublishInternal(const QString& domain, const QString& type, + const QByteArray& name, quint16 port) = 0; private: static Zeroconf* sInstance; diff --git a/src/playlist/dynamicplaylistcontrols.cpp b/src/playlist/dynamicplaylistcontrols.cpp index ca29687b5..8c2a30bcd 100644 --- a/src/playlist/dynamicplaylistcontrols.cpp +++ b/src/playlist/dynamicplaylistcontrols.cpp @@ -18,10 +18,8 @@ #include "dynamicplaylistcontrols.h" #include "ui_dynamicplaylistcontrols.h" -DynamicPlaylistControls::DynamicPlaylistControls(QWidget *parent) - : QWidget(parent), - ui_(new Ui_DynamicPlaylistControls) -{ +DynamicPlaylistControls::DynamicPlaylistControls(QWidget* parent) + : QWidget(parent), ui_(new Ui_DynamicPlaylistControls) { ui_->setupUi(this); connect(ui_->expand, SIGNAL(clicked()), SIGNAL(Expand())); @@ -29,6 +27,4 @@ DynamicPlaylistControls::DynamicPlaylistControls(QWidget *parent) connect(ui_->off, SIGNAL(clicked()), SIGNAL(TurnOff())); } -DynamicPlaylistControls::~DynamicPlaylistControls() { - delete ui_; -} +DynamicPlaylistControls::~DynamicPlaylistControls() { delete ui_; } diff --git a/src/playlist/dynamicplaylistcontrols.h b/src/playlist/dynamicplaylistcontrols.h index e44b5d6d5..9ef5e521f 100644 --- a/src/playlist/dynamicplaylistcontrols.h +++ b/src/playlist/dynamicplaylistcontrols.h @@ -25,7 +25,7 @@ class Ui_DynamicPlaylistControls; class DynamicPlaylistControls : public QWidget { Q_OBJECT -public: + public: DynamicPlaylistControls(QWidget* parent = 0); ~DynamicPlaylistControls(); @@ -34,8 +34,8 @@ signals: void Repopulate(); void TurnOff(); -private: + private: Ui_DynamicPlaylistControls* ui_; }; -#endif // DYNAMICPLAYLISTCONTROLS_H +#endif // DYNAMICPLAYLISTCONTROLS_H diff --git a/src/playlist/playlist.cpp b/src/playlist/playlist.cpp index 5799b688a..113973894 100644 --- a/src/playlist/playlist.cpp +++ b/src/playlist/playlist.cpp @@ -92,46 +92,44 @@ const char* Playlist::kSettingsGroup = "Playlist"; const int Playlist::kUndoStackSize = 20; const int Playlist::kUndoItemLimit = 500; -Playlist::Playlist(PlaylistBackend* backend, - TaskManager* task_manager, - LibraryBackend* library, - int id, - const QString& special_type, - bool favorite, - QObject *parent) - : QAbstractListModel(parent), - is_loading_(false), - proxy_(new PlaylistFilter(this)), - queue_(new Queue(this)), - backend_(backend), - task_manager_(task_manager), - library_(library), - id_(id), - favorite_(favorite), - current_is_paused_(false), - current_virtual_index_(-1), - is_shuffled_(false), - scrobble_point_(-1), - lastfm_status_(LastFM_New), - have_incremented_playcount_(false), - playlist_sequence_(nullptr), - ignore_sorting_(false), - undo_stack_(new QUndoStack(this)), - special_type_(special_type) -{ +Playlist::Playlist(PlaylistBackend* backend, TaskManager* task_manager, + LibraryBackend* library, int id, const QString& special_type, + bool favorite, QObject* parent) + : QAbstractListModel(parent), + is_loading_(false), + proxy_(new PlaylistFilter(this)), + queue_(new Queue(this)), + backend_(backend), + task_manager_(task_manager), + library_(library), + id_(id), + favorite_(favorite), + current_is_paused_(false), + current_virtual_index_(-1), + is_shuffled_(false), + scrobble_point_(-1), + lastfm_status_(LastFM_New), + have_incremented_playcount_(false), + playlist_sequence_(nullptr), + ignore_sorting_(false), + undo_stack_(new QUndoStack(this)), + special_type_(special_type) { undo_stack_->setUndoLimit(kUndoStackSize); - connect(this, SIGNAL(rowsInserted(const QModelIndex&, int, int)), SIGNAL(PlaylistChanged())); - connect(this, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), SIGNAL(PlaylistChanged())); + connect(this, SIGNAL(rowsInserted(const QModelIndex&, int, int)), + SIGNAL(PlaylistChanged())); + connect(this, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), + SIGNAL(PlaylistChanged())); Restore(); proxy_->setSourceModel(this); queue_->setSourceModel(this); - connect(queue_, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), - SLOT(TracksAboutToBeDequeued(QModelIndex,int,int))); - connect(queue_, SIGNAL(rowsRemoved(QModelIndex,int,int)), SLOT(TracksDequeued())); + connect(queue_, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int)), + SLOT(TracksAboutToBeDequeued(QModelIndex, int, int))); + connect(queue_, SIGNAL(rowsRemoved(QModelIndex, int, int)), + SLOT(TracksDequeued())); connect(queue_, SIGNAL(rowsInserted(const QModelIndex&, int, int)), SLOT(TracksEnqueued(const QModelIndex&, int, int))); @@ -146,24 +144,21 @@ Playlist::~Playlist() { library_items_by_id_.clear(); } -template -void Playlist::InsertSongItems(const SongList& songs, int pos, bool play_now, bool enqueue) { +template +void Playlist::InsertSongItems(const SongList& songs, int pos, bool play_now, + bool enqueue) { PlaylistItemList items; - foreach (const Song& song, songs) { - items << PlaylistItemPtr(new T(song)); - } + foreach(const Song & song, songs) { items << PlaylistItemPtr(new T(song)); } InsertItems(items, pos, play_now, enqueue); } QVariant Playlist::headerData(int section, Qt::Orientation, int role) const { - if (role != Qt::DisplayRole && role != Qt::ToolTipRole) - return QVariant(); + if (role != Qt::DisplayRole && role != Qt::ToolTipRole) return QVariant(); - const QString name = column_name((Playlist::Column) section); - if (!name.isEmpty()) - return name; + const QString name = column_name((Playlist::Column)section); + if (!name.isEmpty()) return name; return QVariant(); } @@ -193,10 +188,9 @@ bool Playlist::column_is_editable(Playlist::Column column) { bool Playlist::set_column_value(Song& song, Playlist::Column column, const QVariant& value) { - if (!song.IsEditable()) - return false; + if (!song.IsEditable()) return false; - switch(column) { + switch (column) { case Column_Title: song.set_title(value.toString()); break; @@ -245,7 +239,8 @@ bool Playlist::set_column_value(Song& song, Playlist::Column column, QVariant Playlist::data(const QModelIndex& index, int role) const { switch (role) { case Role_IsCurrent: - return current_item_index_.isValid() && index.row() == current_item_index_.row(); + return current_item_index_.isValid() && + index.row() == current_item_index_.row(); case Role_IsPaused: return current_is_paused_; @@ -271,37 +266,61 @@ QVariant Playlist::data(const QModelIndex& index, int role) const { switch (index.column()) { case Column_Title: return song.PrettyTitle(); - case Column_Artist: return song.artist(); - case Column_Album: return song.album(); - case Column_Length: return song.length_nanosec(); - case Column_Track: return song.track(); - case Column_Disc: return song.disc(); - case Column_Year: return song.year(); - case Column_Genre: return song.genre(); - case Column_AlbumArtist: return song.playlist_albumartist(); - case Column_Composer: return song.composer(); - case Column_Performer: return song.performer(); - case Column_Grouping: return song.grouping(); + case Column_Artist: + return song.artist(); + case Column_Album: + return song.album(); + case Column_Length: + return song.length_nanosec(); + case Column_Track: + return song.track(); + case Column_Disc: + return song.disc(); + case Column_Year: + return song.year(); + case Column_Genre: + return song.genre(); + case Column_AlbumArtist: + return song.playlist_albumartist(); + case Column_Composer: + return song.composer(); + case Column_Performer: + return song.performer(); + case Column_Grouping: + return song.grouping(); - case Column_Rating: return song.rating(); - case Column_PlayCount: return song.playcount(); - case Column_SkipCount: return song.skipcount(); - case Column_LastPlayed: return song.lastplayed(); - case Column_Score: return song.score(); + case Column_Rating: + return song.rating(); + case Column_PlayCount: + return song.playcount(); + case Column_SkipCount: + return song.skipcount(); + case Column_LastPlayed: + return song.lastplayed(); + case Column_Score: + return song.score(); - case Column_BPM: return song.bpm(); - case Column_Bitrate: return song.bitrate(); - case Column_Samplerate: return song.samplerate(); - case Column_Filename: return song.url(); - case Column_BaseFilename: return song.basefilename(); - case Column_Filesize: return song.filesize(); - case Column_Filetype: return song.filetype(); - case Column_DateModified: return song.mtime(); - case Column_DateCreated: return song.ctime(); + case Column_BPM: + return song.bpm(); + case Column_Bitrate: + return song.bitrate(); + case Column_Samplerate: + return song.samplerate(); + case Column_Filename: + return song.url(); + case Column_BaseFilename: + return song.basefilename(); + case Column_Filesize: + return song.filesize(); + case Column_Filetype: + return song.filetype(); + case Column_DateModified: + return song.mtime(); + case Column_DateCreated: + return song.ctime(); case Column_Comment: - if (role == Qt::DisplayRole) - return song.comment().simplified(); + if (role == Qt::DisplayRole) return song.comment().simplified(); return song.comment(); case Column_Source: @@ -312,7 +331,8 @@ QVariant Playlist::data(const QModelIndex& index, int role) const { } case Qt::TextAlignmentRole: - return QVariant(column_alignments_.value(index.column(), (Qt::AlignLeft | Qt::AlignVCenter))); + return QVariant(column_alignments_.value( + index.column(), (Qt::AlignLeft | Qt::AlignVCenter))); case Qt::ForegroundRole: if (data(index, Role_IsCurrent).toBool()) { @@ -351,36 +371,37 @@ void Playlist::MoodbarUpdated(const QModelIndex& index) { index.sibling(index.row(), Column_Mood)); } -bool Playlist::setData(const QModelIndex& index, const QVariant& value, int role) { +bool Playlist::setData(const QModelIndex& index, const QVariant& value, + int role) { int row = index.row(); PlaylistItemPtr item = item_at(row); Song song = item->Metadata(); - if (index.data() == value) - return false; + if (index.data() == value) return false; - if(!set_column_value(song, (Column)index.column(), value)) - return false; + if (!set_column_value(song, (Column)index.column(), value)) return false; - if((Column)index.column() == Column_Score) { + if ((Column)index.column() == Column_Score) { // The score is only saved in the database, not the file library_->AddOrUpdateSongs(SongList() << song); emit EditingFinished(index); } else { - TagReaderReply* reply = TagReaderClient::Instance()->SaveFile( - song.url().toLocalFile(), song); + TagReaderReply* reply = + TagReaderClient::Instance()->SaveFile(song.url().toLocalFile(), song); - NewClosure(reply, SIGNAL(Finished(bool)), - this, SLOT(SongSaveComplete(TagReaderReply*,QPersistentModelIndex)), + NewClosure(reply, SIGNAL(Finished(bool)), this, + SLOT(SongSaveComplete(TagReaderReply*, QPersistentModelIndex)), reply, QPersistentModelIndex(index)); } return true; } -void Playlist::SongSaveComplete(TagReaderReply* reply, const QPersistentModelIndex& index) { +void Playlist::SongSaveComplete(TagReaderReply* reply, + const QPersistentModelIndex& index) { if (reply->is_successful() && index.isValid()) { QFuture future = item_at(index.row())->BackgroundReload(); - ModelFutureWatcher* watcher = new ModelFutureWatcher(index, this); + ModelFutureWatcher* watcher = + new ModelFutureWatcher(index, this); watcher->setFuture(future); connect(watcher, SIGNAL(finished()), SLOT(ItemReloadComplete())); } @@ -389,7 +410,8 @@ void Playlist::SongSaveComplete(TagReaderReply* reply, const QPersistentModelInd } void Playlist::ItemReloadComplete() { - ModelFutureWatcher* watcher = static_cast*>(sender()); + ModelFutureWatcher* watcher = + static_cast*>(sender()); watcher->deleteLater(); const QPersistentModelIndex& index = watcher->index(); if (index.isValid()) { @@ -416,22 +438,22 @@ void Playlist::ShuffleModeChanged(PlaylistSequence::ShuffleMode mode) { } bool Playlist::FilterContainsVirtualIndex(int i) const { - if (i<0 || i>=virtual_items_.count()) - return false; + if (i < 0 || i >= virtual_items_.count()) return false; return proxy_->filterAcceptsRow(virtual_items_[i], QModelIndex()); } int Playlist::NextVirtualIndex(int i, bool ignore_repeat_track) const { PlaylistSequence::RepeatMode repeat_mode = playlist_sequence_->repeat_mode(); - PlaylistSequence::ShuffleMode shuffle_mode = playlist_sequence_->shuffle_mode(); + PlaylistSequence::ShuffleMode shuffle_mode = + playlist_sequence_->shuffle_mode(); bool album_only = repeat_mode == PlaylistSequence::Repeat_Album || shuffle_mode == PlaylistSequence::Shuffle_InsideAlbum; // This one's easy - if we have to repeat the current track then just return i if (repeat_mode == PlaylistSequence::Repeat_Track && !ignore_repeat_track) { if (!FilterContainsVirtualIndex(i)) - return virtual_items_.count(); // It's not in the filter any more + return virtual_items_.count(); // It's not in the filter any more return i; } @@ -441,20 +463,19 @@ int Playlist::NextVirtualIndex(int i, bool ignore_repeat_track) const { ++i; // Advance i until we find any track that is in the filter - while (i < virtual_items_.count() && !FilterContainsVirtualIndex(i)) - ++i; + while (i < virtual_items_.count() && !FilterContainsVirtualIndex(i)) ++i; return i; } // We need to advance i until we get something else on the same album Song last_song = current_item_metadata(); - for (int j=i+1 ; jMetadata(); if (((last_song.is_compilation() && this_song.is_compilation()) || last_song.artist() == this_song.artist()) && last_song.album() == this_song.album() && FilterContainsVirtualIndex(j)) { - return j; // Found one + return j; // Found one } } @@ -464,14 +485,14 @@ int Playlist::NextVirtualIndex(int i, bool ignore_repeat_track) const { int Playlist::PreviousVirtualIndex(int i, bool ignore_repeat_track) const { PlaylistSequence::RepeatMode repeat_mode = playlist_sequence_->repeat_mode(); - PlaylistSequence::ShuffleMode shuffle_mode = playlist_sequence_->shuffle_mode(); + PlaylistSequence::ShuffleMode shuffle_mode = + playlist_sequence_->shuffle_mode(); bool album_only = repeat_mode == PlaylistSequence::Repeat_Album || shuffle_mode == PlaylistSequence::Shuffle_InsideAlbum; // This one's easy - if we have to repeat the current track then just return i if (repeat_mode == PlaylistSequence::Repeat_Track && !ignore_repeat_track) { - if (!FilterContainsVirtualIndex(i)) - return -1; + if (!FilterContainsVirtualIndex(i)) return -1; return i; } @@ -481,20 +502,19 @@ int Playlist::PreviousVirtualIndex(int i, bool ignore_repeat_track) const { --i; // Decrement i until we find any track that is in the filter - while (i>=0 && !FilterContainsVirtualIndex(i)) - --i; + while (i >= 0 && !FilterContainsVirtualIndex(i)) --i; return i; } // We need to decrement i until we get something else on the same album Song last_song = current_item_metadata(); - for (int j=i-1 ; j>=0; --j) { + for (int j = i - 1; j >= 0; --j) { Song this_song = item_at(virtual_items_[j])->Metadata(); if (((last_song.is_compilation() && this_song.is_compilation()) || last_song.artist() == this_song.artist()) && last_song.album() == this_song.album() && FilterContainsVirtualIndex(j)) { - return j; // Found one + return j; // Found one } } @@ -504,15 +524,15 @@ int Playlist::PreviousVirtualIndex(int i, bool ignore_repeat_track) const { int Playlist::next_row(bool ignore_repeat_track) const { // Did we want to stop after this track? - if (stop_after_.isValid() && current_row() == stop_after_.row()) - return -1; + if (stop_after_.isValid() && current_row() == stop_after_.row()) return -1; // Any queued items take priority if (!queue_->is_empty()) { return queue_->PeekNext(); } - int next_virtual_index = NextVirtualIndex(current_virtual_index_, ignore_repeat_track); + int next_virtual_index = + NextVirtualIndex(current_virtual_index_, ignore_repeat_track); if (next_virtual_index >= virtual_items_.count()) { // We've gone off the end of the playlist. @@ -537,7 +557,8 @@ int Playlist::next_row(bool ignore_repeat_track) const { } int Playlist::previous_row(bool ignore_repeat_track) const { - int prev_virtual_index = PreviousVirtualIndex(current_virtual_index_,ignore_repeat_track); + int prev_virtual_index = + PreviousVirtualIndex(current_virtual_index_, ignore_repeat_track); if (prev_virtual_index < 0) { // We've gone off the beginning of the playlist. @@ -549,22 +570,22 @@ int Playlist::previous_row(bool ignore_repeat_track) const { break; default: - prev_virtual_index = PreviousVirtualIndex(virtual_items_.count(),ignore_repeat_track); + prev_virtual_index = + PreviousVirtualIndex(virtual_items_.count(), ignore_repeat_track); break; } } // Still off the beginning? Then just give up - if (prev_virtual_index < 0) - return -1; + if (prev_virtual_index < 0) return -1; return virtual_items_[prev_virtual_index]; } int Playlist::dynamic_history_length() const { - return dynamic_playlist_ && last_played_item_index_.isValid() - ? last_played_item_index_.row() + 1 - : 0; + return dynamic_playlist_ && last_played_item_index_.isValid() + ? last_played_item_index_.row() + 1 + : 0; } void Playlist::set_current_row(int i) { @@ -572,18 +593,18 @@ void Playlist::set_current_row(int i) { ClearStreamMetadata(); current_item_index_ = QPersistentModelIndex(index(i, 0, QModelIndex())); - + // if the given item is the first in the queue, remove it from the queue if (current_item_index_.row() == queue_->PeekNext()) { queue_->TakeNext(); } - if (current_item_index_ == old_current_item_index) - return; + if (current_item_index_ == old_current_item_index) return; if (old_current_item_index.isValid()) { - emit dataChanged(old_current_item_index, - old_current_item_index.sibling(old_current_item_index.row(), ColumnCount-1)); + emit dataChanged(old_current_item_index, + old_current_item_index.sibling( + old_current_item_index.row(), ColumnCount - 1)); } if (current_item_index_.isValid()) { @@ -616,20 +637,21 @@ void Playlist::set_current_row(int i) { // Move the new item one position ahead of the last item in the history. MoveItemWithoutUndo(current_item_index_.row(), dynamic_history_length()); - + // Compute the number of new items that have to be inserted. This is not - // necessarily 1 because the user might have added or removed items - // manually. Note that the future excludes the current item. - const int count = dynamic_history_length() + 1 + dynamic_playlist_->GetDynamicFuture() - items_.count(); + // necessarily 1 because the user might have added or removed items + // manually. Note that the future excludes the current item. + const int count = dynamic_history_length() + 1 + + dynamic_playlist_->GetDynamicFuture() - items_.count(); if (count > 0) { InsertDynamicItems(count); } // Shrink the history, again this is not necessarily by 1, because the user // might have moved items by hand. - const int remove_count = dynamic_history_length() - dynamic_playlist_->GetDynamicHistory(); - if (0 < remove_count) - RemoveItemsWithoutUndo(0, remove_count); + const int remove_count = + dynamic_history_length() - dynamic_playlist_->GetDynamicHistory(); + if (0 < remove_count) RemoveItemsWithoutUndo(0, remove_count); // the above actions make all commands on the undo stack invalid, so we // better clear it. @@ -640,26 +662,26 @@ void Playlist::set_current_row(int i) { last_played_item_index_ = current_item_index_; Save(); } - + UpdateScrobblePoint(); } void Playlist::InsertDynamicItems(int count) { - GeneratorInserter* inserter = new GeneratorInserter(task_manager_, library_, this); + GeneratorInserter* inserter = + new GeneratorInserter(task_manager_, library_, this); connect(inserter, SIGNAL(Error(QString)), SIGNAL(LoadTracksError(QString))); - connect(inserter, SIGNAL(PlayRequested(QModelIndex)), SIGNAL(PlayRequested(QModelIndex))); + connect(inserter, SIGNAL(PlayRequested(QModelIndex)), + SIGNAL(PlayRequested(QModelIndex))); inserter->Load(this, -1, false, false, dynamic_playlist_, count); } -Qt::ItemFlags Playlist::flags(const QModelIndex &index) const { +Qt::ItemFlags Playlist::flags(const QModelIndex& index) const { Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; - if(column_is_editable((Column)index.column())) - flags |= Qt::ItemIsEditable; + if (column_is_editable((Column)index.column())) flags |= Qt::ItemIsEditable; - if (index.isValid()) - return flags | Qt::ItemIsDragEnabled; + if (index.isValid()) return flags | Qt::ItemIsDragEnabled; return Qt::ItemIsDropEnabled; } @@ -673,9 +695,9 @@ Qt::DropActions Playlist::supportedDropActions() const { return Qt::MoveAction | Qt::CopyAction | Qt::LinkAction; } -bool Playlist::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int, const QModelIndex&) { - if (action == Qt::IgnoreAction) - return false; +bool Playlist::dropMimeData(const QMimeData* data, Qt::DropAction action, + int row, int, const QModelIndex&) { + if (action == Qt::IgnoreAction) return false; using smart_playlists::GeneratorMimeData; @@ -693,24 +715,35 @@ bool Playlist::dropMimeData(const QMimeData* data, Qt::DropAction action, int ro // Dragged from a library // We want to check if these songs are from the actual local file backend, // if they are we treat them differently. - if (song_data->backend && song_data->backend->songs_table() == Library::kSongsTable) - InsertSongItems(song_data->songs, row, play_now, enqueue_now); - else if (song_data->backend && song_data->backend->songs_table() == MagnatuneService::kSongsTable) - InsertSongItems(song_data->songs, row, play_now, enqueue_now); - else if (song_data->backend && song_data->backend->songs_table() == JamendoService::kSongsTable) - InsertSongItems(song_data->songs, row, play_now, enqueue_now); + if (song_data->backend && + song_data->backend->songs_table() == Library::kSongsTable) + InsertSongItems(song_data->songs, row, play_now, + enqueue_now); + else if (song_data->backend && + song_data->backend->songs_table() == MagnatuneService::kSongsTable) + InsertSongItems(song_data->songs, row, play_now, + enqueue_now); + else if (song_data->backend && + song_data->backend->songs_table() == JamendoService::kSongsTable) + InsertSongItems(song_data->songs, row, play_now, + enqueue_now); else - InsertSongItems(song_data->songs, row, play_now, enqueue_now); - } else if (const InternetMimeData* internet_data = qobject_cast(data)) { + InsertSongItems(song_data->songs, row, play_now, + enqueue_now); + } else if (const InternetMimeData* internet_data = + qobject_cast(data)) { // Dragged from the Internet pane - InsertInternetItems(internet_data->model, internet_data->indexes, - row, play_now, enqueue_now); - } else if (const InternetSongMimeData* internet_song_data = qobject_cast(data)) { + InsertInternetItems(internet_data->model, internet_data->indexes, row, + play_now, enqueue_now); + } else if (const InternetSongMimeData* internet_song_data = + qobject_cast(data)) { InsertInternetItems(internet_song_data->service, internet_song_data->songs, row, play_now, enqueue_now); - } else if (const GeneratorMimeData* generator_data = qobject_cast(data)) { + } else if (const GeneratorMimeData* generator_data = + qobject_cast(data)) { InsertSmartPlaylist(generator_data->generator_, row, play_now, enqueue_now); - } else if (const PlaylistItemMimeData* item_data = qobject_cast(data)) { + } else if (const PlaylistItemMimeData* item_data = + qobject_cast(data)) { InsertItems(item_data->items_, row, play_now, enqueue_now); } else if (data->hasFormat(kRowsMimetype)) { // Dragged from the playlist @@ -723,24 +756,26 @@ bool Playlist::dropMimeData(const QMimeData* data, Qt::DropAction action, int ro qint64 own_pid = QCoreApplication::applicationPid(); QDataStream stream(data->data(kRowsMimetype)); - stream.readRawData(reinterpret_cast(&source_playlist), sizeof(source_playlist)); + stream.readRawData(reinterpret_cast(&source_playlist), + sizeof(source_playlist)); stream >> source_rows; if (!stream.atEnd()) { stream.readRawData((char*)&pid, sizeof(pid)); } else { - pid = ! own_pid; + pid = !own_pid; } - qStableSort(source_rows); // Make sure we take them in order + qStableSort(source_rows); // Make sure we take them in order if (source_playlist == this) { // Dragged from this playlist - rearrange the items - undo_stack_->push(new PlaylistUndoCommands::MoveItems(this, source_rows, row)); + undo_stack_->push( + new PlaylistUndoCommands::MoveItems(this, source_rows, row)); } else if (pid == own_pid) { // Drag from a different playlist PlaylistItemList items; - foreach (int row, source_rows) - items << source_playlist->item_at(row); + foreach(int row, source_rows) + items << source_playlist->item_at(row); if (items.count() > kUndoItemLimit) { // Too big to keep in the undo stack. Also clear the stack because it @@ -748,12 +783,13 @@ bool Playlist::dropMimeData(const QMimeData* data, Qt::DropAction action, int ro InsertItemsWithoutUndo(items, row, false); undo_stack_->clear(); } else { - undo_stack_->push(new PlaylistUndoCommands::InsertItems(this, items, row)); + undo_stack_->push( + new PlaylistUndoCommands::InsertItems(this, items, row)); } // Remove the items from the source playlist if it was a move event if (action == Qt::MoveAction) { - foreach (int row, source_rows) { + foreach(int row, source_rows) { source_playlist->undo_stack()->push( new PlaylistUndoCommands::RemoveItems(source_playlist, row, 1)); } @@ -772,7 +808,8 @@ bool Playlist::dropMimeData(const QMimeData* data, Qt::DropAction action, int ro return true; } -void Playlist::InsertUrls(const QList &urls, int pos, bool play_now, bool enqueue) { +void Playlist::InsertUrls(const QList& urls, int pos, bool play_now, + bool enqueue) { SongLoaderInserter* inserter = new SongLoaderInserter( task_manager_, library_, backend_->app()->player()); connect(inserter, SIGNAL(Error(QString)), SIGNAL(LoadTracksError(QString))); @@ -780,13 +817,15 @@ void Playlist::InsertUrls(const QList &urls, int pos, bool play_now, bool inserter->Load(this, pos, play_now, enqueue, urls); } -void Playlist::InsertSmartPlaylist(GeneratorPtr generator, int pos, bool play_now, bool enqueue) { +void Playlist::InsertSmartPlaylist(GeneratorPtr generator, int pos, + bool play_now, bool enqueue) { // Hack: If the generator hasn't got a library set then use the main one if (!generator->library()) { generator->set_library(library_); } - GeneratorInserter* inserter = new GeneratorInserter(task_manager_, library_, this); + GeneratorInserter* inserter = + new GeneratorInserter(task_manager_, library_, this); connect(inserter, SIGNAL(Error(QString)), SIGNAL(LoadTracksError(QString))); inserter->Load(this, pos, play_now, enqueue, generator); @@ -820,36 +859,36 @@ void Playlist::MoveItemsWithoutUndo(const QList& source_rows, int pos) { // insertion point changes int offset = 0; int start = pos; - foreach (int source_row, source_rows) { - moved_items << items_.takeAt(source_row-offset); + foreach(int source_row, source_rows) { + moved_items << items_.takeAt(source_row - offset); if (pos > source_row) { - start --; + start--; } offset++; } - + // Put the items back in - for (int i=start ; iRemoveForegroundColor(kDynamicHistoryPriority); items_.insert(i, moved_items[i - start]); } // Update persistent indexes - foreach (const QModelIndex& pidx, persistentIndexList()) { + foreach(const QModelIndex & pidx, persistentIndexList()) { const int dest_offset = source_rows.indexOf(pidx.row()); if (dest_offset != -1) { // This index was moved - changePersistentIndex(pidx, index(start + dest_offset, pidx.column(), QModelIndex())); + changePersistentIndex( + pidx, index(start + dest_offset, pidx.column(), QModelIndex())); } else { int d = 0; - foreach (int source_row, source_rows) { - if (pidx.row() > source_row) - d --; + foreach(int source_row, source_rows) { + if (pidx.row() > source_row) d--; } - if (pidx.row() + d >= start) - d += source_rows.count(); + if (pidx.row() + d >= start) d += source_rows.count(); - changePersistentIndex(pidx, index(pidx.row() + d, pidx.column(), QModelIndex())); + changePersistentIndex( + pidx, index(pidx.row() + d, pidx.column(), QModelIndex())); } } current_virtual_index_ = virtual_items_.indexOf(current_row()); @@ -863,10 +902,10 @@ void Playlist::MoveItemsWithoutUndo(int start, const QList& dest_rows) { PlaylistItemList moved_items; int pos = start; - foreach (int dest_row, dest_rows) { + foreach(int dest_row, dest_rows) { if (dest_row < pos) start--; } - + if (start < 0) { start = items_.count() - dest_rows.count(); } @@ -877,28 +916,28 @@ void Playlist::MoveItemsWithoutUndo(int start, const QList& dest_rows) { // Put the items back in int offset = 0; - foreach (int dest_row, dest_rows) { + foreach(int dest_row, dest_rows) { items_.insert(dest_row, moved_items[offset]); - offset ++; + offset++; } // Update persistent indexes - foreach (const QModelIndex& pidx, persistentIndexList()) { + foreach(const QModelIndex & pidx, persistentIndexList()) { if (pidx.row() >= start && pidx.row() < start + dest_rows.count()) { // This index was moved const int i = pidx.row() - start; - changePersistentIndex(pidx, index(dest_rows[i], pidx.column(), QModelIndex())); + changePersistentIndex(pidx, + index(dest_rows[i], pidx.column(), QModelIndex())); } else { int d = 0; - if (pidx.row() >= start + dest_rows.count()) - d -= dest_rows.count(); + if (pidx.row() >= start + dest_rows.count()) d -= dest_rows.count(); - foreach (int dest_row, dest_rows) { - if (pidx.row() + d > dest_row) - d ++; + foreach(int dest_row, dest_rows) { + if (pidx.row() + d > dest_row) d++; } - changePersistentIndex(pidx, index(pidx.row() + d, pidx.column(), QModelIndex())); + changePersistentIndex( + pidx, index(pidx.row() + d, pidx.column(), QModelIndex())); } } current_virtual_index_ = virtual_items_.indexOf(current_row()); @@ -907,46 +946,46 @@ void Playlist::MoveItemsWithoutUndo(int start, const QList& dest_rows) { Save(); } -void Playlist::InsertItems(const PlaylistItemList& itemsIn, int pos, bool play_now, bool enqueue) { - if (itemsIn.isEmpty()) - return; +void Playlist::InsertItems(const PlaylistItemList& itemsIn, int pos, + bool play_now, bool enqueue) { + if (itemsIn.isEmpty()) return; PlaylistItemList items = itemsIn; // exercise vetoes SongList songs; - foreach(PlaylistItemPtr item, items) { - songs << item->Metadata(); - } + foreach(PlaylistItemPtr item, items) { songs << item->Metadata(); } const int song_count = songs.length(); QSet vetoed; - foreach(SongInsertVetoListener* listener, veto_listeners_) { - foreach(const Song& song, listener->AboutToInsertSongs(GetAllSongs(), songs)) { + foreach(SongInsertVetoListener * listener, veto_listeners_) { + foreach(const Song & song, + listener->AboutToInsertSongs(GetAllSongs(), songs)) { // avoid veto-ing a song multiple times vetoed.insert(song); } if (vetoed.count() == song_count) { - // all songs were vetoed and there's nothing more to do (there's no need for an undo step) + // all songs were vetoed and there's nothing more to do (there's no need + // for an undo step) return; } } - if(!vetoed.isEmpty()) { + if (!vetoed.isEmpty()) { QMutableListIterator it(items); while (it.hasNext()) { PlaylistItemPtr item = it.next(); const Song& current = item->Metadata(); - if(vetoed.contains(current)) { + if (vetoed.contains(current)) { vetoed.remove(current); it.remove(); } } // check for empty items once again after veto - if(items.isEmpty()) { + if (items.isEmpty()) { return; } } @@ -959,23 +998,22 @@ void Playlist::InsertItems(const PlaylistItemList& itemsIn, int pos, bool play_n InsertItemsWithoutUndo(items, pos, enqueue); undo_stack_->clear(); } else { - undo_stack_->push(new PlaylistUndoCommands::InsertItems(this, items, pos, enqueue)); + undo_stack_->push( + new PlaylistUndoCommands::InsertItems(this, items, pos, enqueue)); } - if (play_now) - emit PlayRequested(index(start, 0)); + if (play_now) emit PlayRequested(index(start, 0)); } -void Playlist::InsertItemsWithoutUndo(const PlaylistItemList& items, - int pos, bool enqueue) { - if (items.isEmpty()) - return; +void Playlist::InsertItemsWithoutUndo(const PlaylistItemList& items, int pos, + bool enqueue) { + if (items.isEmpty()) return; const int start = pos == -1 ? items_.count() : pos; const int end = start + items.count() - 1; beginInsertRows(QModelIndex(), start, end); - for (int i=start ; i<=end ; ++i) { + for (int i = start; i <= end; ++i) { PlaylistItemPtr item = items[i - start]; items_.insert(i, item); virtual_items_ << virtual_items_.count(); @@ -997,7 +1035,7 @@ void Playlist::InsertItemsWithoutUndo(const PlaylistItemList& items, if (enqueue) { QModelIndexList indexes; - for (int i=start ; i<=end ; ++i) { + for (int i = start; i <= end; ++i) { indexes << index(i, 0); } queue_->ToggleTracks(indexes); @@ -1007,17 +1045,20 @@ void Playlist::InsertItemsWithoutUndo(const PlaylistItemList& items, ReshuffleIndices(); } -void Playlist::InsertLibraryItems(const SongList& songs, int pos, bool play_now, bool enqueue) { +void Playlist::InsertLibraryItems(const SongList& songs, int pos, bool play_now, + bool enqueue) { InsertSongItems(songs, pos, play_now, enqueue); } -void Playlist::InsertSongs(const SongList& songs, int pos, bool play_now, bool enqueue) { +void Playlist::InsertSongs(const SongList& songs, int pos, bool play_now, + bool enqueue) { InsertSongItems(songs, pos, play_now, enqueue); } -void Playlist::InsertSongsOrLibraryItems(const SongList& songs, int pos, bool play_now, bool enqueue) { +void Playlist::InsertSongsOrLibraryItems(const SongList& songs, int pos, + bool play_now, bool enqueue) { PlaylistItemList items; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { if (song.id() == -1) items << PlaylistItemPtr(new SongPlaylistItem(song)); else @@ -1027,22 +1068,23 @@ void Playlist::InsertSongsOrLibraryItems(const SongList& songs, int pos, bool pl } void Playlist::InsertInternetItems(const InternetModel* model, - const QModelIndexList& items, - int pos, bool play_now, bool enqueue) { + const QModelIndexList& items, int pos, + bool play_now, bool enqueue) { PlaylistItemList playlist_items; QList song_urls; - foreach (const QModelIndex& item, items) { + foreach(const QModelIndex & item, items) { switch (item.data(InternetModel::Role_PlayBehaviour).toInt()) { - case InternetModel::PlayBehaviour_SingleItem: - playlist_items << shared_ptr(new InternetPlaylistItem( - model->ServiceForIndex(item), - item.data(InternetModel::Role_SongMetadata).value())); - break; + case InternetModel::PlayBehaviour_SingleItem: + playlist_items << shared_ptr(new InternetPlaylistItem( + model->ServiceForIndex(item), + item.data(InternetModel::Role_SongMetadata) + .value())); + break; - case InternetModel::PlayBehaviour_UseSongLoader: - song_urls << item.data(InternetModel::Role_Url).toUrl(); - break; + case InternetModel::PlayBehaviour_UseSongLoader: + song_urls << item.data(InternetModel::Role_Url).toUrl(); + break; } } @@ -1055,11 +1097,12 @@ void Playlist::InsertInternetItems(const InternetModel* model, } void Playlist::InsertInternetItems(InternetService* service, - const SongList& songs, - int pos, bool play_now, bool enqueue) { + const SongList& songs, int pos, + bool play_now, bool enqueue) { PlaylistItemList playlist_items; - foreach (const Song& song, songs) { - playlist_items << shared_ptr(new InternetPlaylistItem(service, song)); + foreach(const Song & song, songs) { + playlist_items << shared_ptr( + new InternetPlaylistItem(service, song)); } InsertItems(playlist_items, pos, play_now, enqueue); @@ -1075,9 +1118,9 @@ void Playlist::UpdateItems(const SongList& songs) { // our list because we will not need to check it again. // And we also update undo actions. QLinkedList songs_list; - foreach (const Song& song, songs) songs_list.append(song); + foreach(const Song & song, songs) songs_list.append(song); - for (int i=0; i it(songs_list); while (it.hasNext()) { @@ -1085,8 +1128,8 @@ void Playlist::UpdateItems(const SongList& songs) { PlaylistItemPtr& item = items_[i]; if (item->Metadata().url() == song.url() && (item->Metadata().filetype() == Song::Type_Unknown || - // Stream may change and may need to be updated too - item->Metadata().filetype() == Song::Type_Stream)) { + // Stream may change and may need to be updated too + item->Metadata().filetype() == Song::Type_Stream)) { PlaylistItemPtr new_item; if (song.id() == -1) { new_item = PlaylistItemPtr(new SongPlaylistItem(song)); @@ -1095,12 +1138,13 @@ void Playlist::UpdateItems(const SongList& songs) { library_items_by_id_.insertMulti(song.id(), new_item); } items_[i] = new_item; - emit dataChanged(index(i, 0), index(i, ColumnCount-1)); + emit dataChanged(index(i, 0), index(i, ColumnCount - 1)); // Also update undo actions - for (int i=0; icount(); i++) { - QUndoCommand *undo_action = const_cast(undo_stack_->command(i)); - PlaylistUndoCommands::InsertItems *undo_action_insert = - dynamic_cast(undo_action); + for (int i = 0; i < undo_stack_->count(); i++) { + QUndoCommand* undo_action = + const_cast(undo_stack_->command(i)); + PlaylistUndoCommands::InsertItems* undo_action_insert = + dynamic_cast(undo_action); if (undo_action_insert) { bool found_and_updated = undo_action_insert->UpdateItem(new_item); if (found_and_updated) break; @@ -1115,20 +1159,18 @@ void Playlist::UpdateItems(const SongList& songs) { } QMimeData* Playlist::mimeData(const QModelIndexList& indexes) const { - if (indexes.isEmpty()) - return nullptr; - + if (indexes.isEmpty()) return nullptr; + // We only want one index per row, but we can't just take column 0 because // the user might have hidden it. const int first_column = indexes.first().column(); - + QMimeData* data = new QMimeData; QList urls; QList rows; - foreach (const QModelIndex& index, indexes) { - if (index.column() != first_column) - continue; + foreach(const QModelIndex & index, indexes) { + if (index.column() != first_column) continue; urls << items_[index.row()]->Url(); rows << index.row(); @@ -1158,42 +1200,71 @@ bool Playlist::CompareItems(int column, Qt::SortOrder order, shared_ptr a = order == Qt::AscendingOrder ? _a : _b; shared_ptr 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; +#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; switch (column) { - case Column_Title: strcmp(title); - case Column_Artist: strcmp(artist); - case Column_Album: strcmp(album); - case Column_Length: cmp(length_nanosec); - case Column_Track: cmp(track); - case Column_Disc: cmp(disc); - case Column_Year: cmp(year); - case Column_Genre: strcmp(genre); - case Column_AlbumArtist: strcmp(playlist_albumartist); - case Column_Composer: strcmp(composer); - case Column_Performer: strcmp(performer); - case Column_Grouping: strcmp(grouping); + case Column_Title: + strcmp(title); + case Column_Artist: + strcmp(artist); + case Column_Album: + strcmp(album); + case Column_Length: + cmp(length_nanosec); + case Column_Track: + cmp(track); + case Column_Disc: + cmp(disc); + case Column_Year: + cmp(year); + case Column_Genre: + strcmp(genre); + case Column_AlbumArtist: + strcmp(playlist_albumartist); + case Column_Composer: + strcmp(composer); + case Column_Performer: + strcmp(performer); + case Column_Grouping: + strcmp(grouping); - case Column_Rating: cmp(rating); - case Column_PlayCount: cmp(playcount); - case Column_SkipCount: cmp(skipcount); - case Column_LastPlayed: cmp(lastplayed); - case Column_Score: cmp(score); + case Column_Rating: + cmp(rating); + case Column_PlayCount: + cmp(playcount); + case Column_SkipCount: + cmp(skipcount); + case Column_LastPlayed: + cmp(lastplayed); + case Column_Score: + cmp(score); - case Column_BPM: cmp(bpm); - case Column_Bitrate: cmp(bitrate); - case Column_Samplerate: cmp(samplerate); - case Column_Filename: cmp(url); - case Column_BaseFilename: cmp(basefilename); - case Column_Filesize: cmp(filesize); - case Column_Filetype: cmp(filetype); - case Column_DateModified: cmp(mtime); - case Column_DateCreated: cmp(ctime); + case Column_BPM: + cmp(bpm); + case Column_Bitrate: + cmp(bitrate); + case Column_Samplerate: + cmp(samplerate); + case Column_Filename: + cmp(url); + case Column_BaseFilename: + cmp(basefilename); + case Column_Filesize: + cmp(filesize); + case Column_Filetype: + cmp(filetype); + case Column_DateModified: + cmp(mtime); + case Column_DateCreated: + cmp(ctime); - case Column_Comment: strcmp(comment); - case Column_Source: cmp(url); + case Column_Comment: + strcmp(comment); + case Column_Source: + cmp(url); } #undef cmp @@ -1204,39 +1275,69 @@ bool Playlist::CompareItems(int column, Qt::SortOrder order, QString Playlist::column_name(Column column) { switch (column) { - case Column_Title: return tr("Title"); - case Column_Artist: return tr("Artist"); - case Column_Album: return tr("Album"); - case Column_Length: return tr("Length"); - case Column_Track: return tr("Track"); - case Column_Disc: return tr("Disc"); - case Column_Year: return tr("Year"); - case Column_Genre: return tr("Genre"); - case Column_AlbumArtist: return tr("Album artist"); - case Column_Composer: return tr("Composer"); - case Column_Performer: return tr("Performer"); - case Column_Grouping: return tr("Grouping"); + case Column_Title: + return tr("Title"); + case Column_Artist: + return tr("Artist"); + case Column_Album: + return tr("Album"); + case Column_Length: + return tr("Length"); + case Column_Track: + return tr("Track"); + case Column_Disc: + return tr("Disc"); + case Column_Year: + return tr("Year"); + case Column_Genre: + return tr("Genre"); + case Column_AlbumArtist: + return tr("Album artist"); + case Column_Composer: + return tr("Composer"); + case Column_Performer: + return tr("Performer"); + case Column_Grouping: + return tr("Grouping"); - case Column_Rating: return tr("Rating"); - case Column_PlayCount: return tr("Play count"); - case Column_SkipCount: return tr("Skip count"); - case Column_LastPlayed: return tr("Last played", "A playlist's tag."); - case Column_Score: return tr("Score"); + case Column_Rating: + return tr("Rating"); + case Column_PlayCount: + return tr("Play count"); + case Column_SkipCount: + return tr("Skip count"); + case Column_LastPlayed: + return tr("Last played", "A playlist's tag."); + case Column_Score: + return tr("Score"); - case Column_BPM: return tr("BPM"); - case Column_Bitrate: return tr("Bit rate"); - case Column_Samplerate: return tr("Sample rate"); - case Column_Filename: return tr("File name"); - case Column_BaseFilename: return tr("File name (without path)"); - case Column_Filesize: return tr("File size"); - case Column_Filetype: return tr("File type"); - case Column_DateModified: return tr("Date modified"); - case Column_DateCreated: return tr("Date created"); + case Column_BPM: + return tr("BPM"); + case Column_Bitrate: + return tr("Bit rate"); + case Column_Samplerate: + return tr("Sample rate"); + case Column_Filename: + return tr("File name"); + case Column_BaseFilename: + return tr("File name (without path)"); + case Column_Filesize: + return tr("File size"); + case Column_Filetype: + return tr("File type"); + case Column_DateModified: + return tr("Date modified"); + case Column_DateCreated: + return tr("Date created"); - case Column_Comment: return tr("Comment"); - case Column_Source: return tr("Source"); - case Column_Mood: return tr("Mood"); - default: return QString(); + case Column_Comment: + return tr("Comment"); + case Column_Source: + return tr("Source"); + case Column_Mood: + return tr("Mood"); + default: + return QString(); } return ""; } @@ -1249,25 +1350,25 @@ QString Playlist::abbreviated_column_name(Column column) { case Column_SkipCount: case Column_Track: return QString("%1#").arg(column_name[0]); - default: + default: return column_name; } return ""; } void Playlist::sort(int column, Qt::SortOrder order) { - if (ignore_sorting_) - return; + if (ignore_sorting_) return; PlaylistItemList new_items(items_); PlaylistItemList::iterator begin = new_items.begin(); - if(dynamic_playlist_ && current_item_index_.isValid()) + if (dynamic_playlist_ && current_item_index_.isValid()) begin += current_item_index_.row() + 1; qStableSort(begin, new_items.end(), std::bind(&Playlist::CompareItems, column, order, _1, _2)); - undo_stack_->push(new PlaylistUndoCommands::SortItems(this, column, order, new_items)); + undo_stack_->push( + new PlaylistUndoCommands::SortItems(this, column, order, new_items)); } void Playlist::ReOrderWithoutUndo(const PlaylistItemList& new_items) { @@ -1275,15 +1376,15 @@ void Playlist::ReOrderWithoutUndo(const PlaylistItemList& new_items) { // This is a slow and nasty way to keep the persistent indices QMap > old_persistent_mappings; - foreach (const QModelIndex& index, persistentIndexList()) { + foreach(const QModelIndex & index, persistentIndexList()) { old_persistent_mappings[index.row()] = items_[index.row()]; } - + items_ = new_items; QMapIterator > it(old_persistent_mappings); while (it.hasNext()) { it.next(); - for (int col=0 ; colSavePlaylistAsync(id_, items_, last_played_row(), dynamic_playlist_); + backend_->SavePlaylistAsync(id_, items_, last_played_row(), + dynamic_playlist_); } namespace { @@ -1331,8 +1425,7 @@ typedef QFutureWatcher > PlaylistItemFutureWatcher; } void Playlist::Restore() { - if (!backend_) - return; + if (!backend_) return; items_.clear(); virtual_items_.clear(); @@ -1345,12 +1438,13 @@ void Playlist::Restore() { } void Playlist::ItemsLoaded() { - PlaylistItemFutureWatcher* watcher = static_cast(sender()); + PlaylistItemFutureWatcher* watcher = + static_cast(sender()); watcher->deleteLater(); PlaylistItemList items = watcher->future().results(); - // backend returns empty elements for library items which it couldn't + // backend returns empty elements for library items which it couldn't // match (because they got deleted); we don't need those QMutableListIterator it(items); while (it.hasNext()) { @@ -1399,14 +1493,12 @@ void Playlist::ItemsLoaded() { s.beginGroup(kSettingsGroup); // should we gray out deleted songs asynchronously on startup? - if(s.value("greyoutdeleted", false).toBool()) { + if (s.value("greyoutdeleted", false).toBool()) { QtConcurrent::run(this, &Playlist::InvalidateDeletedSongs); } } -static bool DescendingIntLessThan(int a, int b) { - return a > b; -} +static bool DescendingIntLessThan(int a, int b) { return a > b; } void Playlist::RemoveItemsWithoutUndo(const QList& indicesIn) { // Sort the indices descending because removing elements 'backwards' @@ -1414,12 +1506,12 @@ void Playlist::RemoveItemsWithoutUndo(const QList& indicesIn) { QList indices = indicesIn; qSort(indices.begin(), indices.end(), DescendingIntLessThan); - for(int j = 0; j < indices.count(); j++) { + for (int j = 0; j < indices.count(); j++) { int beginning = indices[j], end = indices[j]; // Splits the indices into sequences. For example this: [1, 2, 4], // will get split into [1, 2] and [4]. - while(j != indices.count() - 1 && indices[j] == indices[j + 1] + 1) { + while (j != indices.count() - 1 && indices[j] == indices[j + 1] + 1) { beginning--; j++; } @@ -1447,7 +1539,7 @@ bool Playlist::removeRows(int row, int count, const QModelIndex& parent) { } bool Playlist::removeRows(QList& rows) { - if(rows.isEmpty()) { + if (rows.isEmpty()) { return false; } @@ -1456,16 +1548,16 @@ bool Playlist::removeRows(QList& rows) { qSort(rows.begin(), rows.end(), qGreater()); QList part; - while(!rows.isEmpty()) { + while (!rows.isEmpty()) { // we're splitting the input list into sequences of consecutive // numbers part.append(rows.takeFirst()); - while(!rows.isEmpty() && rows.first() == part.last() - 1) { + while (!rows.isEmpty() && rows.first() == part.last() - 1) { part.append(rows.takeFirst()); } // and now we're removing the current sequence - if(!removeRows(part.last(), part.size())) { + if (!removeRows(part.last(), part.size())) { return false; } @@ -1479,11 +1571,11 @@ PlaylistItemList Playlist::RemoveItemsWithoutUndo(int row, int count) { if (row < 0 || row >= items_.size() || row + count > items_.size()) { return PlaylistItemList(); } - beginRemoveRows(QModelIndex(), row, row+count-1); + beginRemoveRows(QModelIndex(), row, row + count - 1); // Remove items PlaylistItemList ret; - for (int i=0 ; iUrl() != url) - return; + if (current_item()->Url() != url) return; // Don't update the metadata if it's only a minor change from before if (current_item()->Metadata().artist() == song.artist() && @@ -1551,13 +1645,13 @@ void Playlist::SetStreamMetadata(const QUrl& url, const Song& song) { } void Playlist::ClearStreamMetadata() { - if (!current_item()) - return; + if (!current_item()) return; current_item()->ClearTemporaryMetadata(); UpdateScrobblePoint(); - emit dataChanged(index(current_item_index_.row(), 0), index(current_item_index_.row(), ColumnCount-1)); + emit dataChanged(index(current_item_index_.row(), 0), + index(current_item_index_.row(), ColumnCount - 1)); } bool Playlist::stop_after_current() const { @@ -1567,21 +1661,20 @@ bool Playlist::stop_after_current() const { PlaylistItemPtr Playlist::current_item() const { // QList[] runs in constant time, so no need to cache current_item - if (current_item_index_.isValid() && current_item_index_.row() <= items_.length()) + if (current_item_index_.isValid() && + current_item_index_.row() <= items_.length()) return items_[current_item_index_.row()]; - return PlaylistItemPtr(); + return PlaylistItemPtr(); } - + PlaylistItem::Options Playlist::current_item_options() const { - if (!current_item()) - return PlaylistItem::Default; + if (!current_item()) return PlaylistItem::Default; return current_item()->options(); } Song Playlist::current_item_metadata() const { - if (!current_item()) - return Song(); + if (!current_item()) return Song(); return current_item()->Metadata(); } @@ -1590,11 +1683,10 @@ void Playlist::UpdateScrobblePoint() { const qint64 length = current_item_metadata().length_nanosec(); if (length == 0) { - scrobble_point_ = 240ll * kNsecPerSec; // 4 minutes + scrobble_point_ = 240ll * kNsecPerSec; // 4 minutes } else { - scrobble_point_ = qBound(31ll * kNsecPerSec, - length/2, - 240ll * kNsecPerSec); + scrobble_point_ = + qBound(31ll * kNsecPerSec, length / 2, 240ll * kNsecPerSec); } set_lastfm_status(LastFM_New); @@ -1630,16 +1722,14 @@ void Playlist::TurnOffDynamicPlaylist() { } void Playlist::RepopulateDynamicPlaylist() { - if (!dynamic_playlist_) - return; + if (!dynamic_playlist_) return; RemoveItemsNotInQueue(); InsertSmartPlaylist(dynamic_playlist_); } void Playlist::ExpandDynamicPlaylist() { - if (!dynamic_playlist_) - return; + if (!dynamic_playlist_) return; InsertDynamicItems(5); } @@ -1654,31 +1744,27 @@ void Playlist::RemoveItemsNotInQueue() { forever { // Find a place to start - first row that isn't in the queue forever { - if (start >= rowCount()) - return; - if (!queue_->ContainsSourceRow(start)) - break; - start ++; + if (start >= rowCount()) return; + if (!queue_->ContainsSourceRow(start)) break; + start++; } // Figure out how many rows to remove - keep going until we find a row // that is in the queue int count = 1; forever { - if (start + count >= rowCount()) - break; - if (queue_->ContainsSourceRow(start + count)) - break; - count ++; + if (start + count >= rowCount()) break; + if (queue_->ContainsSourceRow(start + count)) break; + count++; } RemoveItemsWithoutUndo(start, count); - start ++; + start++; } } void Playlist::ReloadItems(const QList& rows) { - foreach (int row, rows) { + foreach(int row, rows) { PlaylistItemPtr item = item_at(row); item->Reload(); @@ -1686,7 +1772,7 @@ void Playlist::ReloadItems(const QList& rows) { if (row == current_row()) { InformOfCurrentSongChange(); } else { - emit dataChanged(index(row, 0), index(row, ColumnCount-1)); + emit dataChanged(index(row, 0), index(row, ColumnCount - 1)); } } @@ -1696,7 +1782,7 @@ void Playlist::ReloadItems(const QList& rows) { void Playlist::RateSong(const QModelIndex& index, double rating) { int row = index.row(); - if(has_item_at(row)) { + if (has_item_at(row)) { PlaylistItemPtr item = item_at(row); if (item && item->IsLocalLibraryItem() && item->Metadata().id() != -1) { library_->UpdateSongRatingAsync(item->Metadata().id(), rating); @@ -1706,11 +1792,13 @@ void Playlist::RateSong(const QModelIndex& index, double rating) { void Playlist::AddSongInsertVetoListener(SongInsertVetoListener* listener) { veto_listeners_.append(listener); - connect(listener, SIGNAL(destroyed()), this, SLOT(SongInsertVetoListenerDestroyed())); + connect(listener, SIGNAL(destroyed()), this, + SLOT(SongInsertVetoListenerDestroyed())); } void Playlist::RemoveSongInsertVetoListener(SongInsertVetoListener* listener) { - disconnect(listener, SIGNAL(destroyed()), this, SLOT(SongInsertVetoListenerDestroyed())); + disconnect(listener, SIGNAL(destroyed()), this, + SLOT(SongInsertVetoListenerDestroyed())); veto_listeners_.removeAll(listener); } @@ -1722,11 +1810,11 @@ void Playlist::Shuffle() { PlaylistItemList new_items(items_); int begin = 0; - if(dynamic_playlist_ && current_item_index_.isValid()) + if (dynamic_playlist_ && current_item_index_.isValid()) begin += current_item_index_.row() + 1; const int count = items_.count(); - for (int i=begin; i < count; ++i) { + for (int i = begin; i < count; ++i) { int new_pos = i + (rand() % (count - i)); std::swap(new_items[i], new_items[new_pos]); @@ -1737,13 +1825,12 @@ void Playlist::Shuffle() { namespace { bool AlbumShuffleComparator(const QMap& album_key_positions, - const QMap& album_keys, - int left, int right) { + const QMap& album_keys, int left, + int right) { const int left_pos = album_key_positions[album_keys[left]]; const int right_pos = album_key_positions[album_keys[right]]; - if (left_pos == right_pos) - return left < right; + if (left_pos == right_pos) return left < right; return left_pos < right_pos; } } @@ -1769,54 +1856,54 @@ void Playlist::ReshuffleIndices() { std::advance(begin, current_virtual_index_ + 1); switch (playlist_sequence_->shuffle_mode()) { - case PlaylistSequence::Shuffle_Off: - // Handled above. - break; + case PlaylistSequence::Shuffle_Off: + // Handled above. + break; - case PlaylistSequence::Shuffle_All: - case PlaylistSequence::Shuffle_InsideAlbum: - std::random_shuffle(begin, end); - break; + case PlaylistSequence::Shuffle_All: + case PlaylistSequence::Shuffle_InsideAlbum: + std::random_shuffle(begin, end); + break; - case PlaylistSequence::Shuffle_Albums: { - QMap album_keys; // real index -> key - QSet album_key_set; // unique keys + case PlaylistSequence::Shuffle_Albums: { + QMap album_keys; // real index -> key + QSet album_key_set; // unique keys - // Find all the unique albums in the playlist - for (QList::iterator it = begin ; it != end ; ++it) { - const int index = *it; - const QString key = items_[index]->Metadata().AlbumKey(); - album_keys[index] = key; - album_key_set << key; - } - - // Shuffle them - QStringList shuffled_album_keys = album_key_set.toList(); - std::random_shuffle(shuffled_album_keys.begin(), - shuffled_album_keys.end()); - - // If the user is currently playing a song, force its album to be first. - if (current_virtual_index_ != -1) { - const QString key = items_[current_row()]->Metadata().AlbumKey(); - const int pos = shuffled_album_keys.indexOf(key); - if (pos >= 1) { - std::swap(shuffled_album_keys[0], shuffled_album_keys[pos]); + // Find all the unique albums in the playlist + for (QList::iterator it = begin; it != end; ++it) { + const int index = *it; + const QString key = items_[index]->Metadata().AlbumKey(); + album_keys[index] = key; + album_key_set << key; } + + // Shuffle them + QStringList shuffled_album_keys = album_key_set.toList(); + std::random_shuffle(shuffled_album_keys.begin(), + shuffled_album_keys.end()); + + // If the user is currently playing a song, force its album to be first. + if (current_virtual_index_ != -1) { + const QString key = items_[current_row()]->Metadata().AlbumKey(); + const int pos = shuffled_album_keys.indexOf(key); + if (pos >= 1) { + std::swap(shuffled_album_keys[0], shuffled_album_keys[pos]); + } + } + + // Create album key -> position mapping for fast lookup + QMap album_key_positions; + for (int i = 0; i < shuffled_album_keys.count(); ++i) { + album_key_positions[shuffled_album_keys[i]] = i; + } + + // Sort the virtual items + std::stable_sort(begin, end, + std::bind(AlbumShuffleComparator, album_key_positions, + album_keys, _1, _2)); + + break; } - - // Create album key -> position mapping for fast lookup - QMap album_key_positions; - for (int i=0 ; ishuffle_mode()); } -QSortFilterProxyModel* Playlist::proxy() const { - return proxy_; -} +QSortFilterProxyModel* Playlist::proxy() const { return proxy_; } SongList Playlist::GetAllSongs() const { SongList ret; - foreach (PlaylistItemPtr item, items_) { - ret << item->Metadata(); - } + foreach(PlaylistItemPtr item, items_) { ret << item->Metadata(); } return ret; } -PlaylistItemList Playlist::GetAllItems() const { - return items_; -} +PlaylistItemList Playlist::GetAllItems() const { return items_; } quint64 Playlist::GetTotalLength() const { quint64 ret = 0; - foreach (PlaylistItemPtr item, items_) { + foreach(PlaylistItemPtr item, items_) { quint64 length = item->Metadata().length_nanosec(); - if (length > 0) - ret += length; + if (length > 0) ret += length; } return ret; } @@ -1859,35 +1939,38 @@ PlaylistItemList Playlist::library_items_by_id(int id) const { } void Playlist::TracksAboutToBeDequeued(const QModelIndex&, int begin, int end) { - for (int i=begin ; i<=end ; ++i) { - temp_dequeue_change_indexes_ << queue_->mapToSource(queue_->index(i, Column_Title)); + for (int i = begin; i <= end; ++i) { + temp_dequeue_change_indexes_ + << queue_->mapToSource(queue_->index(i, Column_Title)); } } void Playlist::TracksDequeued() { - foreach (const QModelIndex& index, temp_dequeue_change_indexes_) { + foreach(const QModelIndex & index, temp_dequeue_change_indexes_) { emit dataChanged(index, index); } temp_dequeue_change_indexes_.clear(); } void Playlist::TracksEnqueued(const QModelIndex&, int begin, int end) { - const QModelIndex& b = queue_->mapToSource(queue_->index(begin, Column_Title)); + const QModelIndex& b = + queue_->mapToSource(queue_->index(begin, Column_Title)); const QModelIndex& e = queue_->mapToSource(queue_->index(end, Column_Title)); emit dataChanged(b, e); } void Playlist::QueueLayoutChanged() { - for (int i=0 ; irowCount() ; ++i) { - const QModelIndex& index = queue_->mapToSource(queue_->index(i, Column_Title)); + for (int i = 0; i < queue_->rowCount(); ++i) { + const QModelIndex& index = + queue_->mapToSource(queue_->index(i, Column_Title)); emit dataChanged(index, index); } } void Playlist::ItemChanged(PlaylistItemPtr item) { - for (int row=0 ; rowMetadata(); - if(!song.is_stream()) { + if (!song.is_stream()) { bool exists = QFile::exists(song.url().toLocalFile()); - if(!exists && !item->HasForegroundColor(kInvalidSongPriority)) { + if (!exists && !item->HasForegroundColor(kInvalidSongPriority)) { // gray out the song if it's not there item->SetForegroundColor(kInvalidSongPriority, kInvalidSongColor); invalidated_rows.append(row); - } else if(exists && item->HasForegroundColor(kInvalidSongPriority)) { + } else if (exists && item->HasForegroundColor(kInvalidSongPriority)) { item->RemoveForegroundColor(kInvalidSongPriority); invalidated_rows.append(row); } @@ -1936,7 +2019,7 @@ void Playlist::RemoveDeletedSongs() { PlaylistItemPtr item = items_[row]; Song song = item->Metadata(); - if(!song.is_stream() && !QFile::exists(song.url().toLocalFile())) { + if (!song.is_stream() && !QFile::exists(song.url().toLocalFile())) { rows_to_remove.append(row); } } @@ -1945,13 +2028,11 @@ void Playlist::RemoveDeletedSongs() { } struct SongSimilarHash { - long operator() (const Song& song) const { - return HashSimilar(song); - } + long operator()(const Song& song) const { return HashSimilar(song); } }; struct SongSimilarEqual { - long operator() (const Song& song1, const Song& song2) const { + long operator()(const Song& song1, const Song& song2) const { return song1.IsSimilar(song2); } }; @@ -1988,23 +2069,22 @@ void Playlist::RemoveDuplicateSongs() { removeRows(rows_to_remove); } - bool Playlist::ApplyValidityOnCurrentSong(const QUrl& url, bool valid) { PlaylistItemPtr current = current_item(); - if(current) { + if (current) { Song current_song = current->Metadata(); // if validity has changed, reload the item - if(!current_song.is_stream() && - !current_song.is_cdda() && + if (!current_song.is_stream() && !current_song.is_cdda() && current_song.url() == url && - current_song.is_valid() != QFile::exists(current_song.url().toLocalFile())) { + current_song.is_valid() != + QFile::exists(current_song.url().toLocalFile())) { ReloadItems(QList() << current_row()); } // gray out the song if it's now broken; otherwise undo the gray color - if(valid) { + if (valid) { current->RemoveForegroundColor(kInvalidSongPriority); } else { current->SetForegroundColor(kInvalidSongPriority, kInvalidSongColor); diff --git a/src/playlist/playlist.h b/src/playlist/playlist.h index cf7721dee..7567385e6 100644 --- a/src/playlist/playlist.h +++ b/src/playlist/playlist.h @@ -39,12 +39,12 @@ class QSortFilterProxyModel; class QUndoStack; namespace PlaylistUndoCommands { - class InsertItems; - class RemoveItems; - class MoveItems; - class ReOrderItems; - class SortItems; - class ShuffleItems; +class InsertItems; +class RemoveItems; +class MoveItems; +class ReOrderItems; +class SortItems; +class ShuffleItems; } typedef QMap ColumnAlignmentMap; @@ -57,11 +57,13 @@ Q_DECLARE_METATYPE(ColumnAlignmentMap); class SongInsertVetoListener : public QObject { Q_OBJECT -public: + public: // Listener returns a list of 'invalid' songs. 'old_songs' are songs that are - // currently in the playlist and 'new_songs' are the songs about to be added if + // currently in the playlist and 'new_songs' are the songs about to be added + // if // nobody exercises a veto. - virtual SongList AboutToInsertSongs(const SongList& old_songs, const SongList& new_songs) = 0; + virtual SongList AboutToInsertSongs(const SongList& old_songs, + const SongList& new_songs) = 0; }; class Playlist : public QAbstractListModel { @@ -73,12 +75,9 @@ class Playlist : public QAbstractListModel { friend class PlaylistUndoCommands::ReOrderItems; public: - Playlist(PlaylistBackend* backend, - TaskManager* task_manager, - LibraryBackend* library, - int id, - const QString& special_type = QString(), - bool favorite = false, + Playlist(PlaylistBackend* backend, TaskManager* task_manager, + LibraryBackend* library, int id, + const QString& special_type = QString(), bool favorite = false, QObject* parent = 0); ~Playlist(); @@ -94,7 +93,6 @@ class Playlist : public QAbstractListModel { Column_Disc, Column_Year, Column_Genre, - Column_BPM, Column_Bitrate, Column_Samplerate, @@ -104,21 +102,16 @@ class Playlist : public QAbstractListModel { Column_Filetype, Column_DateCreated, Column_DateModified, - Column_Rating, Column_PlayCount, Column_SkipCount, Column_LastPlayed, Column_Score, - Column_Comment, - Column_Source, Column_Mood, - Column_Performer, Column_Grouping, - ColumnCount }; @@ -131,12 +124,12 @@ class Playlist : public QAbstractListModel { }; enum LastFMStatus { - LastFM_New = 0, // Haven't scrobbled yet, but we want to later - LastFM_Scrobbled, // Scrobbled ok - LastFM_Seeked, // The user seeked so don't scrobble - LastFM_Error, // Tried to scrobble but got an error - LastFM_Invalid, // The song isn't suitable for scrobbling - LastFM_Queued, // Track added to the queue for scrobbling + LastFM_New = 0, // Haven't scrobbled yet, but we want to later + LastFM_Scrobbled, // Scrobbled ok + LastFM_Seeked, // The user seeked so don't scrobble + LastFM_Error, // Tried to scrobble but got an error + LastFM_Invalid, // The song isn't suitable for scrobbling + LastFM_Queued, // Track added to the queue for scrobbling }; static const char* kCddaMimeType; @@ -154,14 +147,15 @@ class Playlist : public QAbstractListModel { static const int kUndoStackSize; static const int kUndoItemLimit; - static bool CompareItems(int column, Qt::SortOrder order, - PlaylistItemPtr a, PlaylistItemPtr b); + static bool CompareItems(int column, Qt::SortOrder order, PlaylistItemPtr a, + PlaylistItemPtr b); static QString column_name(Column column); static QString abbreviated_column_name(Column column); static bool column_is_editable(Playlist::Column column); - static bool set_column_value(Song& song, Column column, const QVariant& value); + static bool set_column_value(Song& song, Column column, + const QVariant& value); // Persistence void Save() const; @@ -192,7 +186,9 @@ class Playlist : public QAbstractListModel { void set_special_type(const QString& v) { special_type_ = v; } const PlaylistItemPtr& item_at(int index) const { return items_[index]; } - const bool has_item_at(int index) const { return index >= 0 && index < rowCount(); } + const bool has_item_at(int index) const { + return index >= 0 && index < rowCount(); + } PlaylistItemPtr current_item() const; @@ -203,7 +199,7 @@ class Playlist : public QAbstractListModel { SongList GetAllSongs() const; PlaylistItemList GetAllItems() const; - quint64 GetTotalLength() const; // in seconds + quint64 GetTotalLength() const; // in seconds void set_sequence(PlaylistSequence* v); PlaylistSequence* sequence() const { return playlist_sequence_; } @@ -213,28 +209,42 @@ class Playlist : public QAbstractListModel { // Scrobbling qint64 scrobble_point_nanosec() const { return scrobble_point_; } LastFMStatus get_lastfm_status() const { return lastfm_status_; } - bool have_incremented_playcount() const { return have_incremented_playcount_; } - void set_lastfm_status(LastFMStatus status) {lastfm_status_ = status; } + bool have_incremented_playcount() const { + return have_incremented_playcount_; + } + void set_lastfm_status(LastFMStatus status) { lastfm_status_ = status; } void set_have_incremented_playcount() { have_incremented_playcount_ = true; } // Changing the playlist - void InsertItems (const PlaylistItemList& items, int pos = -1, bool play_now = false, bool enqueue = false); - void InsertLibraryItems (const SongList& items, int pos = -1, bool play_now = false, bool enqueue = false); - void InsertSongs (const SongList& items, int pos = -1, bool play_now = false, bool enqueue = false); - void InsertSongsOrLibraryItems(const SongList& items, int pos = -1, bool play_now = false, bool enqueue = false); - void InsertSmartPlaylist (smart_playlists::GeneratorPtr gen, int pos = -1, bool play_now = false, bool enqueue = false); - void InsertInternetItems (InternetService* service, - const SongList& songs, int pos = -1, bool play_now = false, bool enqueue = false); + void InsertItems(const PlaylistItemList& items, int pos = -1, + bool play_now = false, bool enqueue = false); + void InsertLibraryItems(const SongList& items, int pos = -1, + bool play_now = false, bool enqueue = false); + void InsertSongs(const SongList& items, int pos = -1, bool play_now = false, + bool enqueue = false); + void InsertSongsOrLibraryItems(const SongList& items, int pos = -1, + bool play_now = false, bool enqueue = false); + void InsertSmartPlaylist(smart_playlists::GeneratorPtr gen, int pos = -1, + bool play_now = false, bool enqueue = false); + void InsertInternetItems(InternetService* service, const SongList& songs, + int pos = -1, bool play_now = false, + bool enqueue = false); void ReshuffleIndices(); - - // If this playlist contains the current item, this method will apply the "valid" flag on it. - // If the "valid" flag is false, the song will be greyed out. Otherwise the grey color will + + // If this playlist contains the current item, this method will apply the + // "valid" flag on it. + // If the "valid" flag is false, the song will be greyed out. Otherwise the + // grey color will // be undone. - // If the song is a local file and it's valid but non existent or invalid but exists, the - // song will be reloaded to even out the situation because obviously something has changed. - // This returns true if this playlist had current item when the method was invoked. + // If the song is a local file and it's valid but non existent or invalid but + // exists, the + // song will be reloaded to even out the situation because obviously something + // has changed. + // This returns true if this playlist had current item when the method was + // invoked. bool ApplyValidityOnCurrentSong(const QUrl& url, bool valid); - // Grays out and reloads all deleted songs in all playlists. Also, "ungreys" those songs + // Grays out and reloads all deleted songs in all playlists. Also, "ungreys" + // those songs // which were once deleted but now got restored somehow. void InvalidateDeletedSongs(); // Removes from the playlist all local files that don't exist anymore. @@ -257,18 +267,25 @@ class Playlist : public QAbstractListModel { void MoodbarUpdated(const QModelIndex& index); // QAbstractListModel - int rowCount(const QModelIndex& = QModelIndex()) const { return items_.count(); } - int columnCount(const QModelIndex& = QModelIndex()) const { return ColumnCount; } + int rowCount(const QModelIndex& = QModelIndex()) const { + return items_.count(); + } + int columnCount(const QModelIndex& = QModelIndex()) const { + return ColumnCount; + } QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - bool setData(const QModelIndex &index, const QVariant &value, int role); - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - Qt::ItemFlags flags(const QModelIndex &index) const; + bool setData(const QModelIndex& index, const QVariant& value, int role); + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const; + Qt::ItemFlags flags(const QModelIndex& index) const; QStringList mimeTypes() const; Qt::DropActions supportedDropActions() const; QMimeData* mimeData(const QModelIndexList& indexes) const; - bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); + bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, + int column, const QModelIndex& parent); void sort(int column, Qt::SortOrder order); - bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()); + bool removeRows(int row, int count, + const QModelIndex& parent = QModelIndex()); public slots: void set_current_row(int index); @@ -294,11 +311,13 @@ class Playlist : public QAbstractListModel { void SetColumnAlignment(const ColumnAlignmentMap& alignment); - void InsertUrls(const QList& urls, int pos = -1, bool play_now = false, bool enqueue = false); - // Removes items with given indices from the playlist. This operation is not undoable. + void InsertUrls(const QList& urls, int pos = -1, bool play_now = false, + bool enqueue = false); + // Removes items with given indices from the playlist. This operation is not + // undoable. void RemoveItemsWithoutUndo(const QList& indices); - signals: +signals: void RestoreFinished(); void CurrentSongChanged(const Song& metadata); void EditingFinished(const QModelIndex& index); @@ -320,14 +339,15 @@ class Playlist : public QAbstractListModel { void TurnOnDynamicPlaylist(smart_playlists::GeneratorPtr gen); void InsertInternetItems(const InternetModel* model, - const QModelIndexList& items, - int pos, bool play_now, bool enqueue); + const QModelIndexList& items, int pos, bool play_now, + bool enqueue); - template - void InsertSongItems(const SongList& songs, int pos, bool play_now, bool enqueue); + template + void InsertSongItems(const SongList& songs, int pos, bool play_now, + bool enqueue); + + void InsertDynamicItems(int count); - void InsertDynamicItems(int count) ; - // Modify the playlist without changing the undo stack. These are used by // our friends in PlaylistUndoCommands void InsertItemsWithoutUndo(const PlaylistItemList& items, int pos, @@ -348,7 +368,8 @@ class Playlist : public QAbstractListModel { void TracksDequeued(); void TracksEnqueued(const QModelIndex&, int begin, int end); void QueueLayoutChanged(); - void SongSaveComplete(TagReaderReply* reply, const QPersistentModelIndex& index); + void SongSaveComplete(TagReaderReply* reply, + const QPersistentModelIndex& index); void ItemReloadComplete(); void ItemsLoaded(); void SongInsertVetoListenerDestroyed(); @@ -368,8 +389,8 @@ class Playlist : public QAbstractListModel { bool favorite_; PlaylistItemList items_; - QList virtual_items_; // Contains the indices into items_ in the order - // that they will be played. + QList virtual_items_; // Contains the indices into items_ in the order + // that they will be played. // A map of library ID to playlist item - for fast lookups when library // items change. QMultiMap library_items_by_id_; @@ -401,7 +422,7 @@ class Playlist : public QAbstractListModel { QString special_type_; }; -//QDataStream& operator <<(QDataStream&, const Playlist*); -//QDataStream& operator >>(QDataStream&, Playlist*&); +// QDataStream& operator <<(QDataStream&, const Playlist*); +// QDataStream& operator >>(QDataStream&, Playlist*&); -#endif // PLAYLIST_H +#endif // PLAYLIST_H diff --git a/src/playlist/playlistbackend.cpp b/src/playlist/playlistbackend.cpp index f8a604016..5b63d295d 100644 --- a/src/playlist/playlistbackend.cpp +++ b/src/playlist/playlistbackend.cpp @@ -45,11 +45,7 @@ using smart_playlists::GeneratorPtr; const int PlaylistBackend::kSongTableJoins = 4; PlaylistBackend::PlaylistBackend(Application* app, QObject* parent) - : QObject(parent), - app_(app), - db_(app_->database()) -{ -} + : QObject(parent), app_(app), db_(app_->database()) {} PlaylistBackend::PlaylistList PlaylistBackend::GetAllPlaylists() { return GetPlaylists(GetPlaylists_All); @@ -63,7 +59,8 @@ PlaylistBackend::PlaylistList PlaylistBackend::GetAllFavoritePlaylists() { return GetPlaylists(GetPlaylists_Favorite); } -PlaylistBackend::PlaylistList PlaylistBackend::GetPlaylists(GetPlaylistsFlags flags) { +PlaylistBackend::PlaylistList PlaylistBackend::GetPlaylists( + GetPlaylistsFlags flags) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); @@ -81,15 +78,16 @@ PlaylistBackend::PlaylistList PlaylistBackend::GetPlaylists(GetPlaylistsFlags fl condition = " WHERE " + condition_list.join(" OR "); } - QSqlQuery q("SELECT ROWID, name, last_played, dynamic_playlist_type," - " dynamic_playlist_data, dynamic_playlist_backend," - " special_type, ui_path, is_favorite" - " FROM playlists" - " " + condition + - " ORDER BY ui_order", db); + QSqlQuery q( + "SELECT ROWID, name, last_played, dynamic_playlist_type," + " dynamic_playlist_data, dynamic_playlist_backend," + " special_type, ui_path, is_favorite" + " FROM playlists" + " " + + condition + " ORDER BY ui_order", + db); q.exec(); - if (db_->CheckErrors(q)) - return ret; + if (db_->CheckErrors(q)) return ret; while (q.next()) { Playlist p; @@ -112,15 +110,16 @@ PlaylistBackend::Playlist PlaylistBackend::GetPlaylist(int id) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q("SELECT ROWID, name, last_played, dynamic_playlist_type," - " dynamic_playlist_data, dynamic_playlist_backend," - " special_type, ui_path, is_favorite" - " FROM playlists" - " WHERE ROWID=:id", db); + QSqlQuery q( + "SELECT ROWID, name, last_played, dynamic_playlist_type," + " dynamic_playlist_data, dynamic_playlist_backend," + " special_type, ui_path, is_favorite" + " FROM playlists" + " WHERE ROWID=:id", + db); q.bindValue(":id", id); q.exec(); - if (db_->CheckErrors(q)) - return Playlist(); + if (db_->CheckErrors(q)) return Playlist(); q.next(); @@ -142,10 +141,17 @@ QList PlaylistBackend::GetPlaylistRows(int playlist) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QString query = "SELECT songs.ROWID, " + Song::JoinSpec("songs") + "," - " magnatune_songs.ROWID, " + Song::JoinSpec("magnatune_songs") + "," - " jamendo_songs.ROWID, " + Song::JoinSpec("jamendo_songs") + "," - " p.ROWID, " + Song::JoinSpec("p") + "," + QString query = "SELECT songs.ROWID, " + Song::JoinSpec("songs") + + "," + " magnatune_songs.ROWID, " + + Song::JoinSpec("magnatune_songs") + + "," + " jamendo_songs.ROWID, " + + Song::JoinSpec("jamendo_songs") + + "," + " p.ROWID, " + + Song::JoinSpec("p") + + "," " p.type, p.radio_service" " FROM playlist_items AS p" " LEFT JOIN songs" @@ -159,8 +165,7 @@ QList PlaylistBackend::GetPlaylistRows(int playlist) { q.bindValue(":playlist", playlist); q.exec(); - if (db_->CheckErrors(q)) - return QList(); + if (db_->CheckErrors(q)) return QList(); QList rows; @@ -179,8 +184,8 @@ QFuture PlaylistBackend::GetPlaylistItems(int playlist) { // same CUE so we're caching results of parsing CUEs std::shared_ptr state_ptr(new NewSongFromQueryState()); return QtConcurrent::mapped( - rows, std::bind( - &PlaylistBackend::NewPlaylistItemFromQuery, this, _1, state_ptr)); + rows, std::bind(&PlaylistBackend::NewPlaylistItemFromQuery, this, _1, + state_ptr)); } QFuture PlaylistBackend::GetPlaylistSongs(int playlist) { @@ -190,7 +195,8 @@ QFuture PlaylistBackend::GetPlaylistSongs(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(new NewSongFromQueryState()); - return QtConcurrent::mapped(rows, std::bind(&PlaylistBackend::NewSongFromQuery, this, _1, state_ptr)); + return QtConcurrent::mapped( + rows, std::bind(&PlaylistBackend::NewSongFromQuery, this, _1, state_ptr)); } PlaylistItemPtr PlaylistBackend::NewPlaylistItemFromQuery( @@ -198,7 +204,8 @@ PlaylistItemPtr PlaylistBackend::NewPlaylistItemFromQuery( // The song tables get joined first, plus one each for the song ROWIDs const int playlist_row = (Song::kColumns.count() + 1) * kSongTableJoins; - PlaylistItemPtr item(PlaylistItem::NewFromType(row.value(playlist_row).toString())); + PlaylistItemPtr item( + PlaylistItem::NewFromType(row.value(playlist_row).toString())); if (item) { item->InitFromQuery(row); return RestoreCueData(item, state); @@ -218,20 +225,20 @@ PlaylistItemPtr PlaylistBackend::RestoreCueData( PlaylistItemPtr item, std::shared_ptr state) { // we need library to run a CueParser; also, this method applies only to // file-type PlaylistItems - if(item->type() != "File") { + if (item->type() != "File") { return item; } CueParser cue_parser(app_->library_backend()); Song song = item->Metadata(); // we're only interested in .cue songs here - if(!song.has_cue()) { + if (!song.has_cue()) { return item; } QString cue_path = song.cue_path(); // if .cue was deleted - reload the song - if(!QFile::exists(cue_path)) { + if (!QFile::exists(cue_path)) { item->Reload(); return item; } @@ -240,20 +247,21 @@ PlaylistItemPtr PlaylistBackend::RestoreCueData( { QMutexLocker locker(&state->mutex_); - if(!state->cached_cues_.contains(cue_path)) { + if (!state->cached_cues_.contains(cue_path)) { QFile cue(cue_path); cue.open(QIODevice::ReadOnly); - song_list = cue_parser.Load(&cue, cue_path, QDir(cue_path.section('/', 0, -2))); + song_list = + cue_parser.Load(&cue, cue_path, QDir(cue_path.section('/', 0, -2))); state->cached_cues_[cue_path] = song_list; } else { song_list = state->cached_cues_[cue_path]; } } - foreach(const Song& from_list, song_list) { - if(from_list.url().toEncoded() == song.url().toEncoded() && - from_list.beginning_nanosec() == song.beginning_nanosec()) { + foreach(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 PlaylistItemPtr(new SongPlaylistItem(from_list)); @@ -265,13 +273,13 @@ PlaylistItemPtr PlaylistBackend::RestoreCueData( return item; } -void PlaylistBackend::SavePlaylistAsync(int playlist, const PlaylistItemList &items, +void PlaylistBackend::SavePlaylistAsync(int playlist, + const PlaylistItemList& items, int last_played, GeneratorPtr dynamic) { - metaObject()->invokeMethod(this, "SavePlaylist", Qt::QueuedConnection, - Q_ARG(int, playlist), - Q_ARG(PlaylistItemList, items), - Q_ARG(int, last_played), - Q_ARG(smart_playlists::GeneratorPtr, dynamic)); + metaObject()->invokeMethod( + this, "SavePlaylist", Qt::QueuedConnection, Q_ARG(int, playlist), + Q_ARG(PlaylistItemList, items), Q_ARG(int, last_played), + Q_ARG(smart_playlists::GeneratorPtr, dynamic)); } void PlaylistBackend::SavePlaylist(int playlist, const PlaylistItemList& items, @@ -280,28 +288,32 @@ void PlaylistBackend::SavePlaylist(int playlist, const PlaylistItemList& items, QSqlDatabase db(db_->Connect()); QSqlQuery clear("DELETE FROM playlist_items WHERE playlist = :playlist", db); - QSqlQuery insert("INSERT INTO playlist_items" - " (playlist, type, library_id, radio_service, " + - Song::kColumnSpec + ")" - " VALUES (:playlist, :type, :library_id, :radio_service, " + - Song::kBindSpec + ")", db); - QSqlQuery update("UPDATE playlists SET " - " last_played=:last_played," - " dynamic_playlist_type=:dynamic_type," - " dynamic_playlist_data=:dynamic_data," - " dynamic_playlist_backend=:dynamic_backend" - " WHERE ROWID=:playlist", db); + QSqlQuery insert( + "INSERT INTO playlist_items" + " (playlist, type, library_id, radio_service, " + + Song::kColumnSpec + + ")" + " VALUES (:playlist, :type, :library_id, :radio_service, " + + Song::kBindSpec + ")", + db); + QSqlQuery update( + "UPDATE playlists SET " + " last_played=:last_played," + " dynamic_playlist_type=:dynamic_type," + " dynamic_playlist_data=:dynamic_data," + " dynamic_playlist_backend=:dynamic_backend" + " WHERE ROWID=:playlist", + db); ScopedTransaction transaction(&db); // Clear the existing items in the playlist clear.bindValue(":playlist", playlist); clear.exec(); - if (db_->CheckErrors(clear)) - return; + if (db_->CheckErrors(clear)) return; // Save the new ones - foreach (PlaylistItemPtr item, items) { + foreach(PlaylistItemPtr item, items) { insert.bindValue(":playlist", playlist); item->BindToQuery(&insert); @@ -322,24 +334,24 @@ void PlaylistBackend::SavePlaylist(int playlist, const PlaylistItemList& items, } update.bindValue(":playlist", playlist); update.exec(); - if (db_->CheckErrors(update)) - return; + if (db_->CheckErrors(update)) return; transaction.Commit(); } -int PlaylistBackend::CreatePlaylist(const QString &name, +int PlaylistBackend::CreatePlaylist(const QString& name, const QString& special_type) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q("INSERT INTO playlists (name, special_type)" - " VALUES (:name, :special_type)", db); + QSqlQuery q( + "INSERT INTO playlists (name, special_type)" + " VALUES (:name, :special_type)", + db); q.bindValue(":name", name); q.bindValue(":special_type", special_type); q.exec(); - if (db_->CheckErrors(q)) - return -1; + if (db_->CheckErrors(q)) return -1; return q.lastInsertId().toInt(); } @@ -356,17 +368,15 @@ void PlaylistBackend::RemovePlaylist(int id) { ScopedTransaction transaction(&db); delete_playlist.exec(); - if (db_->CheckErrors(delete_playlist)) - return; + if (db_->CheckErrors(delete_playlist)) return; delete_items.exec(); - if (db_->CheckErrors(delete_items)) - return; + if (db_->CheckErrors(delete_items)) return; transaction.Commit(); } -void PlaylistBackend::RenamePlaylist(int id, const QString &new_name) { +void PlaylistBackend::RenamePlaylist(int id, const QString& new_name) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); QSqlQuery q("UPDATE playlists SET name=:name WHERE ROWID=:id", db); @@ -380,7 +390,8 @@ void PlaylistBackend::RenamePlaylist(int id, const QString &new_name) { void PlaylistBackend::FavoritePlaylist(int id, bool is_favorite) { QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); - QSqlQuery q("UPDATE playlists SET is_favorite=:is_favorite WHERE ROWID=:id", db); + QSqlQuery q("UPDATE playlists SET is_favorite=:is_favorite WHERE ROWID=:id", + db); q.bindValue(":is_favorite", is_favorite ? 1 : 0); q.bindValue(":id", id); @@ -395,16 +406,14 @@ void PlaylistBackend::SetPlaylistOrder(const QList& ids) { QSqlQuery q("UPDATE playlists SET ui_order=-1", db); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; q = QSqlQuery("UPDATE playlists SET ui_order=:index WHERE ROWID=:id", db); - for (int i=0 ; iCheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; } transaction.Commit(); @@ -420,8 +429,7 @@ void PlaylistBackend::SetPlaylistUiPath(int id, const QString& path) { q.bindValue(":path", path); q.bindValue(":id", id); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; transaction.Commit(); } diff --git a/src/playlist/playlistbackend.h b/src/playlist/playlistbackend.h index eebf07303..e0d941578 100644 --- a/src/playlist/playlistbackend.h +++ b/src/playlist/playlistbackend.h @@ -37,11 +37,7 @@ class PlaylistBackend : public QObject { Q_INVOKABLE PlaylistBackend(Application* app, QObject* parent = 0); struct Playlist { - Playlist() - : id(-1), - favorite(false), - last_played(0) { - } + Playlist() : id(-1), favorite(false), last_played(0) {} int id; QString name; @@ -73,7 +69,8 @@ class PlaylistBackend : public QObject { int CreatePlaylist(const QString& name, const QString& special_type); void SavePlaylistAsync(int playlist, const PlaylistItemList& items, - int last_played, smart_playlists::GeneratorPtr dynamic); + int last_played, + smart_playlists::GeneratorPtr dynamic); void RenamePlaylist(int id, const QString& new_name); void FavoritePlaylist(int id, bool is_favorite); void RemovePlaylist(int id); @@ -92,9 +89,12 @@ class PlaylistBackend : public QObject { QList GetPlaylistRows(int playlist); - 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, + std::shared_ptr state); + PlaylistItemPtr NewPlaylistItemFromQuery( + const SqlRow& row, std::shared_ptr state); + PlaylistItemPtr RestoreCueData(PlaylistItemPtr item, + std::shared_ptr state); enum GetPlaylistsFlags { GetPlaylists_OpenInUi = 1, @@ -107,4 +107,4 @@ class PlaylistBackend : public QObject { Database* db_; }; -#endif // PLAYLISTBACKEND_H +#endif // PLAYLISTBACKEND_H diff --git a/src/playlist/playlistcontainer.cpp b/src/playlist/playlistcontainer.cpp index 4ef863718..70e0b9327 100644 --- a/src/playlist/playlistcontainer.cpp +++ b/src/playlist/playlistcontainer.cpp @@ -37,19 +37,18 @@ const char* PlaylistContainer::kSettingsGroup = "Playlist"; const int PlaylistContainer::kFilterDelayMs = 100; const int PlaylistContainer::kFilterDelayPlaylistSizeThreshold = 5000; -PlaylistContainer::PlaylistContainer(QWidget *parent) - : QWidget(parent), - ui_(new Ui_PlaylistContainer), - manager_(nullptr), - undo_(nullptr), - redo_(nullptr), - playlist_(nullptr), - starting_up_(true), - tab_bar_visible_(false), - tab_bar_animation_(new QTimeLine(500, this)), - no_matches_label_(nullptr), - filter_timer_(new QTimer(this)) -{ +PlaylistContainer::PlaylistContainer(QWidget* parent) + : QWidget(parent), + ui_(new Ui_PlaylistContainer), + manager_(nullptr), + undo_(nullptr), + redo_(nullptr), + playlist_(nullptr), + starting_up_(true), + tab_bar_visible_(false), + tab_bar_animation_(new QTimeLine(500, this)), + no_matches_label_(nullptr), + filter_timer_(new QTimer(this)) { ui_->setupUi(this); no_matches_label_ = new QLabel(ui_->playlist); @@ -61,9 +60,12 @@ PlaylistContainer::PlaylistContainer(QWidget *parent) // Set the colour of the no matches label to the disabled text colour QPalette no_matches_palette = no_matches_label_->palette(); - const QColor no_matches_color = no_matches_palette.color(QPalette::Disabled, QPalette::Text); - no_matches_palette.setColor(QPalette::Normal, QPalette::WindowText, no_matches_color); - no_matches_palette.setColor(QPalette::Inactive, QPalette::WindowText, no_matches_color); + const QColor no_matches_color = + no_matches_palette.color(QPalette::Disabled, QPalette::Text); + no_matches_palette.setColor(QPalette::Normal, QPalette::WindowText, + no_matches_color); + no_matches_palette.setColor(QPalette::Inactive, QPalette::WindowText, + no_matches_color); no_matches_label_->setPalette(no_matches_palette); // Make it bold @@ -77,7 +79,8 @@ PlaylistContainer::PlaylistContainer(QWidget *parent) ui_->tab_bar->setExpanding(false); ui_->tab_bar->setMovable(true); - connect(tab_bar_animation_, SIGNAL(frameChanged(int)), SLOT(SetTabBarHeight(int))); + connect(tab_bar_animation_, SIGNAL(frameChanged(int)), + SLOT(SetTabBarHeight(int))); ui_->tab_bar->setMaximumHeight(0); // Connections @@ -87,21 +90,18 @@ PlaylistContainer::PlaylistContainer(QWidget *parent) // set up timer for delayed filter updates filter_timer_->setSingleShot(true); filter_timer_->setInterval(kFilterDelayMs); - connect(filter_timer_,SIGNAL(timeout()),this,SLOT(UpdateFilter())); + connect(filter_timer_, SIGNAL(timeout()), this, SLOT(UpdateFilter())); // Replace playlist search filter with native search box. connect(ui_->filter, SIGNAL(textChanged(QString)), SLOT(MaybeUpdateFilter())); - connect(ui_->playlist, SIGNAL(FocusOnFilterSignal(QKeyEvent*)), SLOT(FocusOnFilter(QKeyEvent*))); + connect(ui_->playlist, SIGNAL(FocusOnFilterSignal(QKeyEvent*)), + SLOT(FocusOnFilter(QKeyEvent*))); ui_->filter->installEventFilter(this); } -PlaylistContainer::~PlaylistContainer() { - delete ui_; -} +PlaylistContainer::~PlaylistContainer() { delete ui_; } -PlaylistView* PlaylistContainer::view() const { - return ui_->playlist; -} +PlaylistView* PlaylistContainer::view() const { return ui_->playlist; } void PlaylistContainer::SetActions(QAction* new_playlist, QAction* load_playlist, @@ -118,55 +118,55 @@ void PlaylistContainer::SetActions(QAction* new_playlist, connect(save_playlist, SIGNAL(triggered()), SLOT(SavePlaylist())); connect(load_playlist, SIGNAL(triggered()), SLOT(LoadPlaylist())); connect(next_playlist, SIGNAL(triggered()), SLOT(GoToNextPlaylistTab())); - connect(previous_playlist, SIGNAL(triggered()), SLOT(GoToPreviousPlaylistTab())); + connect(previous_playlist, SIGNAL(triggered()), + SLOT(GoToPreviousPlaylistTab())); } -void PlaylistContainer::SetManager(PlaylistManager *manager) { +void PlaylistContainer::SetManager(PlaylistManager* manager) { manager_ = manager; ui_->tab_bar->SetManager(manager); - connect(ui_->tab_bar, SIGNAL(CurrentIdChanged(int)), - manager, SLOT(SetCurrentPlaylist(int))); - connect(ui_->tab_bar, SIGNAL(Rename(int,QString)), - manager, SLOT(Rename(int,QString))); - connect(ui_->tab_bar, SIGNAL(Close(int)), - manager, SLOT(Close(int))); - connect(ui_->tab_bar, SIGNAL(PlaylistFavorited(int, bool)), - manager, SLOT(Favorite(int, bool))); + connect(ui_->tab_bar, SIGNAL(CurrentIdChanged(int)), manager, + SLOT(SetCurrentPlaylist(int))); + connect(ui_->tab_bar, SIGNAL(Rename(int, QString)), manager, + SLOT(Rename(int, QString))); + connect(ui_->tab_bar, SIGNAL(Close(int)), manager, SLOT(Close(int))); + connect(ui_->tab_bar, SIGNAL(PlaylistFavorited(int, bool)), manager, + SLOT(Favorite(int, bool))); - connect(ui_->tab_bar, SIGNAL(PlaylistOrderChanged(QList)), - manager, SLOT(ChangePlaylistOrder(QList))); + connect(ui_->tab_bar, SIGNAL(PlaylistOrderChanged(QList)), manager, + SLOT(ChangePlaylistOrder(QList))); connect(manager, SIGNAL(CurrentChanged(Playlist*)), SLOT(SetViewModel(Playlist*))); - connect(manager, SIGNAL(PlaylistAdded(int,QString,bool)), - SLOT(PlaylistAdded(int,QString,bool))); - connect(manager, SIGNAL(PlaylistClosed(int)), - SLOT(PlaylistClosed(int))); - connect(manager, SIGNAL(PlaylistRenamed(int,QString)), - SLOT(PlaylistRenamed(int,QString))); + connect(manager, SIGNAL(PlaylistAdded(int, QString, bool)), + SLOT(PlaylistAdded(int, QString, bool))); + connect(manager, SIGNAL(PlaylistClosed(int)), SLOT(PlaylistClosed(int))); + connect(manager, SIGNAL(PlaylistRenamed(int, QString)), + SLOT(PlaylistRenamed(int, QString))); } void PlaylistContainer::SetViewModel(Playlist* playlist) { if (view()->selectionModel()) { - disconnect(view()->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), - this, SLOT(SelectionChanged())); + disconnect(view()->selectionModel(), + SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, + SLOT(SelectionChanged())); } if (playlist_ && playlist_->proxy()) { - disconnect(playlist_->proxy(), SIGNAL(modelReset()), + disconnect(playlist_->proxy(), SIGNAL(modelReset()), this, + SLOT(UpdateNoMatchesLabel())); + disconnect(playlist_->proxy(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(UpdateNoMatchesLabel())); - disconnect(playlist_->proxy(), SIGNAL(rowsInserted(QModelIndex,int,int)), - this, SLOT(UpdateNoMatchesLabel())); - disconnect(playlist_->proxy(), SIGNAL(rowsRemoved(QModelIndex,int,int)), + disconnect(playlist_->proxy(), SIGNAL(rowsRemoved(QModelIndex, int, int)), this, SLOT(UpdateNoMatchesLabel())); } if (playlist_) { - disconnect(playlist_, SIGNAL(modelReset()), - this, SLOT(UpdateNoMatchesLabel())); - disconnect(playlist_, SIGNAL(rowsInserted(QModelIndex,int,int)), - this, SLOT(UpdateNoMatchesLabel())); - disconnect(playlist_, SIGNAL(rowsRemoved(QModelIndex,int,int)), - this, SLOT(UpdateNoMatchesLabel())); + disconnect(playlist_, SIGNAL(modelReset()), this, + SLOT(UpdateNoMatchesLabel())); + disconnect(playlist_, SIGNAL(rowsInserted(QModelIndex, int, int)), this, + SLOT(UpdateNoMatchesLabel())); + disconnect(playlist_, SIGNAL(rowsRemoved(QModelIndex, int, int)), this, + SLOT(UpdateNoMatchesLabel())); } playlist_ = playlist; @@ -176,23 +176,30 @@ void PlaylistContainer::SetViewModel(Playlist* playlist) { view()->setModel(playlist->proxy()); view()->SetItemDelegates(manager_->library_backend()); view()->SetPlaylist(playlist); - view()->selectionModel()->select(manager_->current_selection(), QItemSelectionModel::ClearAndSelect); + view()->selectionModel()->select(manager_->current_selection(), + QItemSelectionModel::ClearAndSelect); playlist->IgnoreSorting(false); - connect(view()->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), - this, SLOT(SelectionChanged())); + connect(view()->selectionModel(), + SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, + SLOT(SelectionChanged())); emit ViewSelectionModelChanged(); // Update filter ui_->filter->setText(playlist->proxy()->filterRegExp().pattern()); // Update the no matches label - connect(playlist_->proxy(), SIGNAL(modelReset()), SLOT(UpdateNoMatchesLabel())); - connect(playlist_->proxy(), SIGNAL(rowsInserted(QModelIndex,int,int)), SLOT(UpdateNoMatchesLabel())); - connect(playlist_->proxy(), SIGNAL(rowsRemoved(QModelIndex,int,int)), SLOT(UpdateNoMatchesLabel())); + connect(playlist_->proxy(), SIGNAL(modelReset()), + SLOT(UpdateNoMatchesLabel())); + connect(playlist_->proxy(), SIGNAL(rowsInserted(QModelIndex, int, int)), + SLOT(UpdateNoMatchesLabel())); + connect(playlist_->proxy(), SIGNAL(rowsRemoved(QModelIndex, int, int)), + SLOT(UpdateNoMatchesLabel())); connect(playlist_, SIGNAL(modelReset()), SLOT(UpdateNoMatchesLabel())); - connect(playlist_, SIGNAL(rowsInserted(QModelIndex,int,int)), SLOT(UpdateNoMatchesLabel())); - connect(playlist_, SIGNAL(rowsRemoved(QModelIndex,int,int)), SLOT(UpdateNoMatchesLabel())); + connect(playlist_, SIGNAL(rowsInserted(QModelIndex, int, int)), + SLOT(UpdateNoMatchesLabel())); + connect(playlist_, SIGNAL(rowsRemoved(QModelIndex, int, int)), + SLOT(UpdateNoMatchesLabel())); UpdateNoMatchesLabel(); // Ensure that tab is current @@ -213,7 +220,6 @@ void PlaylistContainer::SetViewModel(Playlist* playlist) { ui_->redo->setDefaultAction(redo_); emit UndoRedoActionsChanged(undo_, redo_); - } void PlaylistContainer::ActivePlaying() { @@ -224,22 +230,20 @@ void PlaylistContainer::ActivePaused() { UpdateActiveIcon(QIcon(":tiny-pause.png")); } -void PlaylistContainer::ActiveStopped() { - UpdateActiveIcon(QIcon()); -} +void PlaylistContainer::ActiveStopped() { UpdateActiveIcon(QIcon()); } void PlaylistContainer::UpdateActiveIcon(const QIcon& icon) { // Unset all existing icons - for (int i=0 ; itab_bar->count() ; ++i) { + for (int i = 0; i < ui_->tab_bar->count(); ++i) { ui_->tab_bar->setTabIcon(i, QIcon()); } // Set our icon - if (!icon.isNull()) - ui_->tab_bar->set_icon_by_id(manager_->active_id(), icon); + if (!icon.isNull()) ui_->tab_bar->set_icon_by_id(manager_->active_id(), icon); } -void PlaylistContainer::PlaylistAdded(int id, const QString &name, bool favorite) { +void PlaylistContainer::PlaylistAdded(int id, const QString& name, + bool favorite) { const int index = ui_->tab_bar->count(); ui_->tab_bar->InsertTab(id, index, name, favorite); @@ -268,26 +272,21 @@ void PlaylistContainer::PlaylistAdded(int id, const QString &name, bool favorite void PlaylistContainer::PlaylistClosed(int id) { ui_->tab_bar->RemoveTab(id); - if (ui_->tab_bar->count() <= 1) - SetTabBarVisible(false); + if (ui_->tab_bar->count() <= 1) SetTabBarVisible(false); } -void PlaylistContainer::PlaylistRenamed(int id, const QString &new_name) { +void PlaylistContainer::PlaylistRenamed(int id, const QString& new_name) { ui_->tab_bar->set_text_by_id(id, new_name); } -void PlaylistContainer::NewPlaylist() { - manager_->New(tr("Playlist")); -} +void PlaylistContainer::NewPlaylist() { manager_->New(tr("Playlist")); } void PlaylistContainer::LoadPlaylist() { QString filename = settings_.value("last_load_playlist").toString(); - filename = QFileDialog::getOpenFileName( - this, tr("Load playlist"), filename, - manager_->parser()->filters()); + filename = QFileDialog::getOpenFileName(this, tr("Load playlist"), filename, + manager_->parser()->filters()); - if (filename.isNull()) - return; + if (filename.isNull()) return; settings_.setValue("last_load_playlist", filename); @@ -303,34 +302,33 @@ void PlaylistContainer::SavePlaylist(int id = -1) { void PlaylistContainer::GoToNextPlaylistTab() { // Get the next tab' id - int id_next = - ui_->tab_bar->id_of((ui_->tab_bar->currentIndex()+1)%ui_->tab_bar->count()); + int id_next = ui_->tab_bar->id_of((ui_->tab_bar->currentIndex() + 1) % + ui_->tab_bar->count()); // Switch to next tab manager_->SetCurrentPlaylist(id_next); } void PlaylistContainer::GoToPreviousPlaylistTab() { // Get the next tab' id - int id_previous = - ui_->tab_bar->id_of((ui_->tab_bar->currentIndex()+ui_->tab_bar->count()-1) - % ui_->tab_bar->count()); + int id_previous = ui_->tab_bar->id_of( + (ui_->tab_bar->currentIndex() + ui_->tab_bar->count() - 1) % + ui_->tab_bar->count()); // Switch to next tab manager_->SetCurrentPlaylist(id_previous); } void PlaylistContainer::Save() { - if (starting_up_) - return; + if (starting_up_) return; settings_.setValue("current_playlist", ui_->tab_bar->current_id()); } void PlaylistContainer::SetTabBarVisible(bool visible) { - if (tab_bar_visible_ == visible) - return; + if (tab_bar_visible_ == visible) return; tab_bar_visible_ = visible; - tab_bar_animation_->setDirection(visible ? QTimeLine::Forward : QTimeLine::Backward); + tab_bar_animation_->setDirection(visible ? QTimeLine::Forward + : QTimeLine::Backward); tab_bar_animation_->start(); } @@ -363,7 +361,9 @@ void PlaylistContainer::UpdateNoMatchesLabel() { QString text; if (has_rows && !has_results) { - text = tr("No matches found. Clear the search box to show the whole playlist again."); + text = + tr("No matches found. Clear the search box to show the whole playlist " + "again."); } if (!text.isEmpty()) { @@ -380,7 +380,7 @@ void PlaylistContainer::resizeEvent(QResizeEvent* e) { RepositionNoMatchesLabel(); } -void PlaylistContainer::FocusOnFilter(QKeyEvent *event) { +void PlaylistContainer::FocusOnFilter(QKeyEvent* event) { ui_->filter->setFocus(); if (event->key() == Qt::Key_Escape) { ui_->filter->clear(); @@ -390,12 +390,12 @@ void PlaylistContainer::FocusOnFilter(QKeyEvent *event) { } void PlaylistContainer::RepositionNoMatchesLabel(bool force) { - if (!force && !no_matches_label_->isVisible()) - return; + if (!force && !no_matches_label_->isVisible()) return; const int kBorder = 10; - QPoint pos = ui_->playlist->viewport()->mapTo(ui_->playlist, QPoint(kBorder, kBorder)); + QPoint pos = + ui_->playlist->viewport()->mapTo(ui_->playlist, QPoint(kBorder, kBorder)); QSize size = ui_->playlist->viewport()->size(); size.setWidth(size.width() - kBorder * 2); size.setHeight(size.height() - kBorder * 2); @@ -408,11 +408,11 @@ void PlaylistContainer::SelectionChanged() { manager_->SelectionChanged(view()->selectionModel()->selection()); } -bool PlaylistContainer::eventFilter(QObject *objectWatched, QEvent *event) { - if(objectWatched == ui_->filter) { +bool PlaylistContainer::eventFilter(QObject* objectWatched, QEvent* event) { + if (objectWatched == ui_->filter) { if (event->type() == QEvent::KeyPress) { - QKeyEvent *e = static_cast(event); - switch(e->key()) { + QKeyEvent* e = static_cast(event); + switch (e->key()) { case Qt::Key_Up: case Qt::Key_Down: case Qt::Key_PageUp: diff --git a/src/playlist/playlistcontainer.h b/src/playlist/playlistcontainer.h index 24412fac5..e3a680ae8 100644 --- a/src/playlist/playlistcontainer.h +++ b/src/playlist/playlistcontainer.h @@ -35,20 +35,20 @@ class QLabel; class PlaylistContainer : public QWidget { Q_OBJECT -public: - PlaylistContainer(QWidget *parent = 0); + public: + PlaylistContainer(QWidget* parent = 0); ~PlaylistContainer(); static const char* kSettingsGroup; void SetActions(QAction* new_playlist, QAction* load_playlist, - QAction* save_playlist, - QAction* next_playlist, QAction* previous_playlist); + QAction* save_playlist, QAction* next_playlist, + QAction* previous_playlist); void SetManager(PlaylistManager* manager); PlaylistView* view() const; - bool eventFilter(QObject *objectWatched, QEvent *event); + bool eventFilter(QObject* objectWatched, QEvent* event); signals: void TabChanged(int id); @@ -57,11 +57,11 @@ signals: void UndoRedoActionsChanged(QAction* undo, QAction* redo); void ViewSelectionModelChanged(); -protected: + protected: // QWidget - void resizeEvent(QResizeEvent *); + void resizeEvent(QResizeEvent*); -private slots: + private slots: void NewPlaylist(); void LoadPlaylist(); void SavePlaylist() { SavePlaylist(-1); } @@ -86,15 +86,15 @@ private slots: void SelectionChanged(); void MaybeUpdateFilter(); void UpdateFilter(); - void FocusOnFilter(QKeyEvent *event); + void FocusOnFilter(QKeyEvent* event); void UpdateNoMatchesLabel(); -private: + private: void UpdateActiveIcon(const QIcon& icon); void RepositionNoMatchesLabel(bool force = false); -private: + private: static const int kFilterDelayMs; static const int kFilterDelayPlaylistSizeThreshold; @@ -116,4 +116,4 @@ private: QTimer* filter_timer_; }; -#endif // PLAYLISTCONTAINER_H +#endif // PLAYLISTCONTAINER_H diff --git a/src/playlist/playlistdelegates.cpp b/src/playlist/playlistdelegates.cpp index b49b46ee3..a9cc47a71 100644 --- a/src/playlist/playlistdelegates.cpp +++ b/src/playlist/playlistdelegates.cpp @@ -44,23 +44,22 @@ #include "core/mac_utilities.h" #endif // Q_OS_DARWIN -const int QueuedItemDelegate::kQueueBoxBorder = 1; -const int QueuedItemDelegate::kQueueBoxCornerRadius = 3; -const int QueuedItemDelegate::kQueueBoxLength = 30; -const QRgb QueuedItemDelegate::kQueueBoxGradientColor1 = qRgb(102, 150, 227); -const QRgb QueuedItemDelegate::kQueueBoxGradientColor2 = qRgb(77, 121, 200); -const int QueuedItemDelegate::kQueueOpacitySteps = 10; +const int QueuedItemDelegate::kQueueBoxBorder = 1; +const int QueuedItemDelegate::kQueueBoxCornerRadius = 3; +const int QueuedItemDelegate::kQueueBoxLength = 30; +const QRgb QueuedItemDelegate::kQueueBoxGradientColor1 = qRgb(102, 150, 227); +const QRgb QueuedItemDelegate::kQueueBoxGradientColor2 = qRgb(77, 121, 200); +const int QueuedItemDelegate::kQueueOpacitySteps = 10; const float QueuedItemDelegate::kQueueOpacityLowerBound = 0.4; -const int PlaylistDelegateBase::kMinHeight = 19; +const int PlaylistDelegateBase::kMinHeight = 19; -QueuedItemDelegate::QueuedItemDelegate(QObject *parent, int indicator_column) - : QStyledItemDelegate(parent), - indicator_column_(indicator_column) -{ -} +QueuedItemDelegate::QueuedItemDelegate(QObject* parent, int indicator_column) + : QStyledItemDelegate(parent), indicator_column_(indicator_column) {} -void QueuedItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { +void QueuedItemDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { QStyledItemDelegate::paint(painter, option, index); if (index.column() == indicator_column_) { @@ -73,7 +72,7 @@ void QueuedItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op opacity += kQueueOpacityLowerBound; painter->setOpacity(opacity); - DrawBox(painter, option.rect, option.font, QString::number(queue_pos+1), + DrawBox(painter, option.rect, option.font, QString::number(queue_pos + 1), kQueueBoxLength); painter->setOpacity(1.0); @@ -81,15 +80,14 @@ void QueuedItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op } } -void QueuedItemDelegate::DrawBox( - QPainter* painter, const QRect& line_rect, const QFont& font, - const QString& text, int width) const { +void QueuedItemDelegate::DrawBox(QPainter* painter, const QRect& line_rect, + const QFont& font, const QString& text, + int width) const { QFont smaller = font; smaller.setPointSize(smaller.pointSize() - 1); smaller.setBold(true); - if (width == -1) - width = QFontMetrics(font).width(text + " "); + if (width == -1) width = QFontMetrics(font).width(text + " "); QRect rect(line_rect); rect.setLeft(rect.right() - width - kQueueBoxBorder); @@ -123,36 +121,33 @@ int QueuedItemDelegate::queue_indicator_size(const QModelIndex& index) const { if (index.column() == indicator_column_) { const int queue_pos = index.data(Playlist::Role_QueuePosition).toInt(); if (queue_pos != -1) { - return kQueueBoxLength + kQueueBoxBorder*2; + return kQueueBoxLength + kQueueBoxBorder * 2; } } return 0; } +PlaylistDelegateBase::PlaylistDelegateBase(QObject* parent, + const QString& suffix) + : QueuedItemDelegate(parent), + view_(qobject_cast(parent)), + suffix_(suffix) {} -PlaylistDelegateBase::PlaylistDelegateBase(QObject* parent, const QString& suffix) - : QueuedItemDelegate(parent), - view_(qobject_cast(parent)), - suffix_(suffix) -{ -} - -QString PlaylistDelegateBase::displayText(const QVariant& value, const QLocale&) const { +QString PlaylistDelegateBase::displayText(const QVariant& value, + const QLocale&) const { QString text; switch (static_cast(value.type())) { case QMetaType::Int: { int v = value.toInt(); - if (v > 0) - text = QString::number(v); + if (v > 0) text = QString::number(v); break; } case QMetaType::Float: case QMetaType::Double: { double v = value.toDouble(); - if (v > 0) - text = QString::number(v); + if (v > 0) text = QString::number(v); break; } @@ -161,19 +156,20 @@ QString PlaylistDelegateBase::displayText(const QVariant& value, const QLocale&) break; } - if (!text.isNull() && !suffix_.isNull()) - text += " " + suffix_; + if (!text.isNull() && !suffix_.isNull()) text += " " + suffix_; return text; } -QSize PlaylistDelegateBase::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { +QSize PlaylistDelegateBase::sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const { QSize size = QueuedItemDelegate::sizeHint(option, index); - if (size.height() < kMinHeight) - size.setHeight(kMinHeight); + if (size.height() < kMinHeight) size.setHeight(kMinHeight); return size; } -void PlaylistDelegateBase::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { +void PlaylistDelegateBase::paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { QueuedItemDelegate::paint(painter, Adjusted(option, index), index); // Stop after indicator @@ -187,9 +183,9 @@ void PlaylistDelegateBase::paint(QPainter* painter, const QStyleOptionViewItem& } } -QStyleOptionViewItemV4 PlaylistDelegateBase::Adjusted(const QStyleOptionViewItem& option, const QModelIndex& index) const { - if (!view_) - return option; +QStyleOptionViewItemV4 PlaylistDelegateBase::Adjusted( + const QStyleOptionViewItem& option, const QModelIndex& index) const { + if (!view_) return option; QPoint top_left(-view_->horizontalScrollBar()->value(), -view_->verticalScrollBar()->value()); @@ -208,19 +204,18 @@ QStyleOptionViewItemV4 PlaylistDelegateBase::Adjusted(const QStyleOptionViewItem return ret; } -bool PlaylistDelegateBase::helpEvent(QHelpEvent *event, QAbstractItemView *view, - const QStyleOptionViewItem &option, - const QModelIndex &index) { +bool PlaylistDelegateBase::helpEvent(QHelpEvent* event, QAbstractItemView* view, + const QStyleOptionViewItem& option, + const QModelIndex& index) { // This function is copied from QAbstractItemDelegate, and changed to show // displayText() in the tooltip, rather than the index's naked // Qt::ToolTipRole text. Q_UNUSED(option); - if (!event || !view) - return false; + if (!event || !view) return false; - QHelpEvent *he = static_cast(event); + QHelpEvent* he = static_cast(event); QString text = displayText(index.data(), QLocale::system()); // Special case: we want newlines in the comment tooltip @@ -232,8 +227,7 @@ bool PlaylistDelegateBase::helpEvent(QHelpEvent *event, QAbstractItemView *view, text.replace("\n", "
"); } - if (text.isEmpty() || !he) - return false; + if (text.isEmpty() || !he) return false; switch (event->type()) { case QEvent::ToolTip: { @@ -244,9 +238,9 @@ bool PlaylistDelegateBase::helpEvent(QHelpEvent *event, QAbstractItemView *view, real_text = sizeHint(option, index); displayed_text = view->visualRect(index); is_elided = displayed_text.width() < real_text.width(); - if(is_elided) { + if (is_elided) { QToolTip::showText(he->globalPos(), text, view); - } else { // in case that another text was previously displayed + } else { // in case that another text was previously displayed QToolTip::hideText(); } return true; @@ -265,83 +259,80 @@ bool PlaylistDelegateBase::helpEvent(QHelpEvent *event, QAbstractItemView *view, return false; } - -QString LengthItemDelegate::displayText(const QVariant& value, const QLocale&) const { +QString LengthItemDelegate::displayText(const QVariant& value, + const QLocale&) const { bool ok = false; qint64 nanoseconds = value.toLongLong(&ok); - if (ok && nanoseconds > 0) - return Utilities::PrettyTimeNanosec(nanoseconds); + if (ok && nanoseconds > 0) return Utilities::PrettyTimeNanosec(nanoseconds); return QString::null; } - -QString SizeItemDelegate::displayText(const QVariant& value, const QLocale&) const { +QString SizeItemDelegate::displayText(const QVariant& value, + const QLocale&) const { bool ok = false; int bytes = value.toInt(&ok); - if (ok) - return Utilities::PrettySize(bytes); + if (ok) return Utilities::PrettySize(bytes); return QString(); } -QString DateItemDelegate::displayText(const QVariant &value, const QLocale &locale) const { +QString DateItemDelegate::displayText(const QVariant& value, + const QLocale& locale) const { bool ok = false; int time = value.toInt(&ok); - if (!ok || time == -1) - return QString::null; + if (!ok || time == -1) return QString::null; - return QDateTime::fromTime_t(time).toString( - QLocale::system().dateTimeFormat(QLocale::ShortFormat)); + return QDateTime::fromTime_t(time) + .toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat)); } -QString LastPlayedItemDelegate::displayText(const QVariant& value, const QLocale& locale) const { +QString LastPlayedItemDelegate::displayText(const QVariant& value, + const QLocale& locale) const { bool ok = false; const int time = value.toInt(&ok); - if (!ok || time == -1) - return tr("Never"); + if (!ok || time == -1) return tr("Never"); return Utilities::Ago(time, locale); } -QString FileTypeItemDelegate::displayText(const QVariant &value, const QLocale &locale) const { +QString FileTypeItemDelegate::displayText(const QVariant& value, + const QLocale& locale) const { bool ok = false; Song::FileType type = Song::FileType(value.toInt(&ok)); - if (!ok) - return tr("Unknown"); + if (!ok) return tr("Unknown"); return Song::TextForFiletype(type); } -QWidget* TextItemDelegate::createEditor( - QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const { +QWidget* TextItemDelegate::createEditor(QWidget* parent, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { return new QLineEdit(parent); } RatingItemDelegate::RatingItemDelegate(QObject* parent) - : PlaylistDelegateBase(parent) -{ -} + : PlaylistDelegateBase(parent) {} -void RatingItemDelegate::paint( - QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { +void RatingItemDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { // Draw the background const QStyleOptionViewItemV3* vopt = qstyleoption_cast(&option); - vopt->widget->style()->drawPrimitive( - QStyle::PE_PanelItemViewItem, vopt, painter, vopt->widget); + vopt->widget->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, vopt, + painter, vopt->widget); // Don't draw anything else if the user can't set the rating of this item - if (!index.data(Playlist::Role_CanSetRating).toBool()) - return; + if (!index.data(Playlist::Role_CanSetRating).toBool()) return; - const bool hover = mouse_over_index_.isValid() && ( - mouse_over_index_ == index || ( - selected_indexes_.contains(mouse_over_index_) && - selected_indexes_.contains(index))); + const bool hover = mouse_over_index_.isValid() && + (mouse_over_index_ == index || + (selected_indexes_.contains(mouse_over_index_) && + selected_indexes_.contains(index))); const double rating = (hover ? RatingPainter::RatingForPos(mouse_over_pos_, option.rect) @@ -350,27 +341,27 @@ void RatingItemDelegate::paint( painter_.Paint(painter, option.rect, rating); } -QSize RatingItemDelegate::sizeHint( - const QStyleOptionViewItem& option, const QModelIndex& index) const { +QSize RatingItemDelegate::sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const { QSize size = PlaylistDelegateBase::sizeHint(option, index); size.setWidth(size.height() * RatingPainter::kStarCount); return size; } -QString RatingItemDelegate::displayText( - const QVariant& value, const QLocale&) const { - if (value.isNull() || value.toDouble() <= 0) - return QString(); +QString RatingItemDelegate::displayText(const QVariant& value, + const QLocale&) const { + if (value.isNull() || value.toDouble() <= 0) return QString(); // Round to the nearest 0.5 - const double rating = float(int(value.toDouble() * RatingPainter::kStarCount * 2 + 0.5)) / 2; + const double rating = + float(int(value.toDouble() * RatingPainter::kStarCount * 2 + 0.5)) / 2; return QString::number(rating, 'f', 1); } -TagCompletionModel::TagCompletionModel(LibraryBackend* backend, Playlist::Column column) - : QStringListModel() -{ +TagCompletionModel::TagCompletionModel(LibraryBackend* backend, + Playlist::Column column) + : QStringListModel() { QString col = database_column(column); if (!col.isEmpty()) { setStringList(backend->GetAll(col)); @@ -379,13 +370,20 @@ TagCompletionModel::TagCompletionModel(LibraryBackend* backend, Playlist::Column QString TagCompletionModel::database_column(Playlist::Column column) { switch (column) { - case Playlist::Column_Artist: return "artist"; - case Playlist::Column_Album: return "album"; - case Playlist::Column_AlbumArtist: return "albumartist"; - case Playlist::Column_Composer: return "composer"; - case Playlist::Column_Performer: return "performer"; - case Playlist::Column_Grouping: return "grouping"; - case Playlist::Column_Genre: return "genre"; + case Playlist::Column_Artist: + return "artist"; + case Playlist::Column_Album: + return "album"; + case Playlist::Column_AlbumArtist: + return "albumartist"; + case Playlist::Column_Composer: + return "composer"; + case Playlist::Column_Performer: + return "performer"; + case Playlist::Column_Grouping: + return "grouping"; + case Playlist::Column_Genre: + return "genre"; default: qLog(Warning) << "Unknown column" << column; return QString(); @@ -399,11 +397,9 @@ static TagCompletionModel* InitCompletionModel(LibraryBackend* backend, TagCompleter::TagCompleter(LibraryBackend* backend, Playlist::Column column, QLineEdit* editor) - : QCompleter(editor), - editor_(editor) -{ - QFuture future = QtConcurrent::run( - &InitCompletionModel, backend, column); + : QCompleter(editor), editor_(editor) { + QFuture future = + QtConcurrent::run(&InitCompletionModel, backend, column); QFutureWatcher* watcher = new QFutureWatcher(this); watcher->setFuture(future); @@ -414,8 +410,7 @@ TagCompleter::TagCompleter(LibraryBackend* backend, Playlist::Column column, void TagCompleter::ModelReady() { QFutureWatcher* watcher = dynamic_cast*>(sender()); - if (!watcher) - return; + if (!watcher) return; TagCompletionModel* model = watcher->result(); setModel(model); @@ -423,8 +418,9 @@ void TagCompleter::ModelReady() { editor_->setCompleter(this); } -QWidget* TagCompletionItemDelegate::createEditor( - QWidget* parent, const QStyleOptionViewItem&, const QModelIndex&) const { +QWidget* TagCompletionItemDelegate::createEditor(QWidget* parent, + const QStyleOptionViewItem&, + const QModelIndex&) const { QLineEdit* editor = new QLineEdit(parent); new TagCompleter(backend_, column_, editor); @@ -432,7 +428,8 @@ QWidget* TagCompletionItemDelegate::createEditor( return editor; } -QString NativeSeparatorsDelegate::displayText(const QVariant& value, const QLocale&) const { +QString NativeSeparatorsDelegate::displayText(const QVariant& value, + const QLocale&) const { const QString string_value = value.toString(); QUrl url; @@ -451,15 +448,15 @@ QString NativeSeparatorsDelegate::displayText(const QVariant& value, const QLoca } SongSourceDelegate::SongSourceDelegate(QObject* parent, Player* player) - : PlaylistDelegateBase(parent), - player_(player) { -} + : PlaylistDelegateBase(parent), player_(player) {} -QString SongSourceDelegate::displayText(const QVariant& value, const QLocale&) const { +QString SongSourceDelegate::displayText(const QVariant& value, + const QLocale&) const { return QString(); } -QPixmap SongSourceDelegate::LookupPixmap(const QUrl& url, const QSize& size) const { +QPixmap SongSourceDelegate::LookupPixmap(const QUrl& url, + const QSize& size) const { QPixmap pixmap; if (cache_.find(url.scheme(), &pixmap)) { return pixmap; @@ -485,8 +482,9 @@ QPixmap SongSourceDelegate::LookupPixmap(const QUrl& url, const QSize& size) con return pixmap; } -void SongSourceDelegate::paint( - QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { +void SongSourceDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { // Draw the background PlaylistDelegateBase::paint(painter, option, index); @@ -504,7 +502,8 @@ void SongSourceDelegate::paint( #endif // Draw the pixmap in the middle of the rectangle - QRect draw_rect(QPoint(0, 0), option_copy.decorationSize / device_pixel_ratio); + QRect draw_rect(QPoint(0, 0), + option_copy.decorationSize / device_pixel_ratio); draw_rect.moveCenter(option_copy.rect.center()); painter->drawPixmap(draw_rect, pixmap); diff --git a/src/playlist/playlistdelegates.h b/src/playlist/playlistdelegates.h index 7239dd9e2..c935b6b2e 100644 --- a/src/playlist/playlistdelegates.h +++ b/src/playlist/playlistdelegates.h @@ -31,15 +31,17 @@ class Player; class QueuedItemDelegate : public QStyledItemDelegate { -public: - QueuedItemDelegate(QObject* parent, int indicator_column = Playlist::Column_Title); - void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; - void DrawBox(QPainter* painter, const QRect& line_rect, - const QFont& font, const QString& text, int width = -1) const; + public: + QueuedItemDelegate(QObject* parent, + int indicator_column = Playlist::Column_Title); + void paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const; + void DrawBox(QPainter* painter, const QRect& line_rect, const QFont& font, + const QString& text, int width = -1) const; int queue_indicator_size(const QModelIndex& index) const; -private: + private: static const int kQueueBoxBorder; static const int kQueueBoxCornerRadius; static const int kQueueBoxLength; @@ -55,17 +57,20 @@ class PlaylistDelegateBase : public QueuedItemDelegate { Q_OBJECT public: PlaylistDelegateBase(QObject* parent, const QString& suffix = QString()); - void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const; QString displayText(const QVariant& value, const QLocale& locale) const; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; + QSize sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const; - QStyleOptionViewItemV4 Adjusted(const QStyleOptionViewItem& option, const QModelIndex& index) const; + QStyleOptionViewItemV4 Adjusted(const QStyleOptionViewItem& option, + const QModelIndex& index) const; static const int kMinHeight; public slots: - bool helpEvent(QHelpEvent *event, QAbstractItemView *view, - const QStyleOptionViewItem &option, const QModelIndex &index); + bool helpEvent(QHelpEvent* event, QAbstractItemView* view, + const QStyleOptionViewItem& option, const QModelIndex& index); protected: QTreeView* view_; @@ -91,7 +96,7 @@ class DateItemDelegate : public PlaylistDelegateBase { }; class LastPlayedItemDelegate : public PlaylistDelegateBase { -public: + public: LastPlayedItemDelegate(QObject* parent) : PlaylistDelegateBase(parent) {} QString displayText(const QVariant& value, const QLocale& locale) const; }; @@ -106,29 +111,31 @@ class TextItemDelegate : public PlaylistDelegateBase { public: TextItemDelegate(QObject* parent) : PlaylistDelegateBase(parent) {} QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, - const QModelIndex& index) const; + const QModelIndex& index) const; }; class RatingItemDelegate : public PlaylistDelegateBase { -public: + public: RatingItemDelegate(QObject* parent); - void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const; + QSize sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const; QString displayText(const QVariant& value, const QLocale& locale) const; void set_mouse_over(const QModelIndex& index, const QModelIndexList& selected_indexes, const QPoint& pos) { - mouse_over_index_ = index; - selected_indexes_ = selected_indexes; - mouse_over_pos_ = pos; + mouse_over_index_ = index; + selected_indexes_ = selected_indexes; + mouse_over_pos_ = pos; } void set_mouse_out() { mouse_over_index_ = QModelIndex(); } bool is_mouse_over() const { return mouse_over_index_.isValid(); } QModelIndex mouse_over_index() const { return mouse_over_index_; } -private: + private: RatingPainter painter_; QModelIndex mouse_over_index_; @@ -137,34 +144,35 @@ private: }; class TagCompletionModel : public QStringListModel { -public: + public: TagCompletionModel(LibraryBackend* backend, Playlist::Column column); -private: + private: static QString database_column(Playlist::Column column); }; class TagCompleter : public QCompleter { Q_OBJECT -public: + public: TagCompleter(LibraryBackend* backend, Playlist::Column column, QLineEdit* editor); -private slots: + private slots: void ModelReady(); -private: + private: QLineEdit* editor_; }; class TagCompletionItemDelegate : public PlaylistDelegateBase { public: - TagCompletionItemDelegate(QObject* parent, LibraryBackend* backend, Playlist::Column column) : - PlaylistDelegateBase(parent), backend_(backend), column_(column) {}; + TagCompletionItemDelegate(QObject* parent, LibraryBackend* backend, + Playlist::Column column) + : PlaylistDelegateBase(parent), backend_(backend), column_(column) {}; QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, - const QModelIndex& index) const; + const QModelIndex& index) const; private: LibraryBackend* backend_; @@ -181,7 +189,8 @@ class SongSourceDelegate : public PlaylistDelegateBase { public: SongSourceDelegate(QObject* parent, Player* player); QString displayText(const QVariant& value, const QLocale& locale) const; - void paint(QPainter* paint, const QStyleOptionViewItem& option, const QModelIndex& index) const; + void paint(QPainter* paint, const QStyleOptionViewItem& option, + const QModelIndex& index) const; private: QPixmap LookupPixmap(const QUrl& url, const QSize& size) const; @@ -190,4 +199,4 @@ class SongSourceDelegate : public PlaylistDelegateBase { mutable QPixmapCache cache_; }; -#endif // PLAYLISTDELEGATES_H +#endif // PLAYLISTDELEGATES_H diff --git a/src/playlist/playlistfilter.cpp b/src/playlist/playlistfilter.cpp index d96dc0d3f..68e7c88c3 100644 --- a/src/playlist/playlistfilter.cpp +++ b/src/playlist/playlistfilter.cpp @@ -20,11 +20,10 @@ #include -PlaylistFilter::PlaylistFilter(QObject *parent) - : QSortFilterProxyModel(parent), - filter_tree_(new NopFilter), - query_hash_(0) -{ +PlaylistFilter::PlaylistFilter(QObject* parent) + : QSortFilterProxyModel(parent), + filter_tree_(new NopFilter), + query_hash_(0) { setDynamicSortFilter(true); column_names_["title"] = Playlist::Column_Title; @@ -47,25 +46,21 @@ PlaylistFilter::PlaylistFilter(QObject *parent) column_names_["filename"] = Playlist::Column_Filename; column_names_["rating"] = Playlist::Column_Rating; - numerical_columns_ << Playlist::Column_Length - << Playlist::Column_Track - << Playlist::Column_Disc - << Playlist::Column_Year - << Playlist::Column_Score - << Playlist::Column_BPM - << Playlist::Column_Bitrate - << Playlist::Column_Rating; + numerical_columns_ << Playlist::Column_Length << Playlist::Column_Track + << Playlist::Column_Disc << Playlist::Column_Year + << Playlist::Column_Score << Playlist::Column_BPM + << Playlist::Column_Bitrate << Playlist::Column_Rating; } -PlaylistFilter::~PlaylistFilter() { -} +PlaylistFilter::~PlaylistFilter() {} void PlaylistFilter::sort(int column, Qt::SortOrder order) { // Pass this through to the Playlist, it does sorting itself sourceModel()->sort(column, order); } -bool PlaylistFilter::filterAcceptsRow(int row, const QModelIndex &parent) const { +bool PlaylistFilter::filterAcceptsRow(int row, + const QModelIndex& parent) const { QString filter = filterRegExp().pattern(); uint hash = qHash(filter); @@ -78,5 +73,5 @@ bool PlaylistFilter::filterAcceptsRow(int row, const QModelIndex &parent) const } // Test the row - return filter_tree_->accept(row,parent,sourceModel()); + return filter_tree_->accept(row, parent, sourceModel()); } diff --git a/src/playlist/playlistfilter.h b/src/playlist/playlistfilter.h index 70a04db77..ae1ee03af 100644 --- a/src/playlist/playlistfilter.h +++ b/src/playlist/playlistfilter.h @@ -30,7 +30,7 @@ class FilterTree; class PlaylistFilter : public QSortFilterProxyModel { Q_OBJECT -public: + public: PlaylistFilter(QObject* parent = 0); ~PlaylistFilter(); @@ -39,9 +39,9 @@ public: // QSortFilterProxyModel // public so Playlist::NextVirtualIndex and friends can get at it - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const; -private: + private: // Mutable because they're modified from filterAcceptsRow() const mutable QScopedPointer filter_tree_; mutable uint query_hash_; @@ -50,4 +50,4 @@ private: QSet numerical_columns_; }; -#endif // PLAYLISTFILTER_H +#endif // PLAYLISTFILTER_H diff --git a/src/playlist/playlistfilterparser.cpp b/src/playlist/playlistfilterparser.cpp index d4dadadab..b5628524c 100644 --- a/src/playlist/playlistfilterparser.cpp +++ b/src/playlist/playlistfilterparser.cpp @@ -34,6 +34,7 @@ class DefaultComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return element.contains(search_term_); } + private: QString search_term_; }; @@ -44,6 +45,7 @@ class EqComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return search_term_ == element; } + private: QString search_term_; }; @@ -54,6 +56,7 @@ class NeComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return search_term_ != element; } + private: QString search_term_; }; @@ -64,6 +67,7 @@ class LexicalGtComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return element > search_term_; } + private: QString search_term_; }; @@ -74,6 +78,7 @@ class LexicalGeComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return element >= search_term_; } + private: QString search_term_; }; @@ -84,6 +89,7 @@ class LexicalLtComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return element < search_term_; } + private: QString search_term_; }; @@ -94,6 +100,7 @@ class LexicalLeComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return element <= search_term_; } + private: QString search_term_; }; @@ -104,6 +111,7 @@ class GtComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return element.toInt() > search_term_; } + private: int search_term_; }; @@ -114,6 +122,7 @@ class GeComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return element.toInt() >= search_term_; } + private: int search_term_; }; @@ -124,6 +133,7 @@ class LtComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return element.toInt() < search_term_; } + private: int search_term_; }; @@ -134,6 +144,7 @@ class LeComparator : public SearchTermComparator { virtual bool Matches(const QString& element) const { return element.toInt() <= search_term_; } + private: int search_term_; }; @@ -149,10 +160,11 @@ class DropTailComparatorDecorator : public SearchTermComparator { virtual bool Matches(const QString& element) const { if (element.length() > 9) - return cmp_->Matches(element.left(element.length()-9)); + return cmp_->Matches(element.left(element.length() - 9)); else return cmp_->Matches(element); } + private: QScopedPointer cmp_; }; @@ -164,6 +176,7 @@ class RatingComparatorDecorator : public SearchTermComparator { return cmp_->Matches( QString::number(static_cast(element.toDouble() * 10.0 + 0.5))); } + private: QScopedPointer cmp_; }; @@ -171,32 +184,39 @@ class RatingComparatorDecorator : public SearchTermComparator { // filter that applies a SearchTermComparator to all fields of a playlist entry class FilterTerm : public FilterTree { public: - explicit FilterTerm(SearchTermComparator* comparator, const QList& columns) : cmp_(comparator), columns_(columns) {} + explicit FilterTerm(SearchTermComparator* comparator, + const QList& columns) + : cmp_(comparator), columns_(columns) {} - virtual bool accept(int row, const QModelIndex& parent, const QAbstractItemModel* const model) const { - foreach (int i, columns_) { + virtual bool accept(int row, const QModelIndex& parent, + const QAbstractItemModel* const model) const { + foreach(int i, columns_) { QModelIndex idx(model->index(row, i, parent)); - if (cmp_->Matches(idx.data().toString().toLower())) - return true; + if (cmp_->Matches(idx.data().toString().toLower())) return true; } return false; } virtual FilterType type() { return Term; } + private: QScopedPointer cmp_; QList columns_; }; -// filter that applies a SearchTermComparator to one specific field of a playlist entry +// filter that applies a SearchTermComparator to one specific field of a +// playlist entry class FilterColumnTerm : public FilterTree { public: - FilterColumnTerm(int column, SearchTermComparator* comparator) : col(column), cmp_(comparator) {} + FilterColumnTerm(int column, SearchTermComparator* comparator) + : col(column), cmp_(comparator) {} - virtual bool accept(int row, const QModelIndex& parent, const QAbstractItemModel* const model) const { + virtual bool accept(int row, const QModelIndex& parent, + const QAbstractItemModel* const model) const { QModelIndex idx(model->index(row, col, parent)); return cmp_->Matches(idx.data().toString().toLower()); } virtual FilterType type() { return Column; } + private: int col; QScopedPointer cmp_; @@ -206,26 +226,29 @@ class NotFilter : public FilterTree { public: explicit NotFilter(const FilterTree* inv) : child_(inv) {} - virtual bool accept(int row, const QModelIndex& parent, const QAbstractItemModel* const model) const { + virtual bool accept(int row, const QModelIndex& parent, + const QAbstractItemModel* const model) const { return !child_->accept(row, parent, model); } virtual FilterType type() { return Not; } + private: QScopedPointer child_; }; -class OrFilter : public FilterTree { +class OrFilter : public FilterTree { public: ~OrFilter() { qDeleteAll(children_); } virtual void add(FilterTree* child) { children_.append(child); } - virtual bool accept(int row, const QModelIndex& parent, const QAbstractItemModel* const model) const { - foreach (FilterTree* child, children_) { - if (child->accept(row, parent, model)) - return true; + virtual bool accept(int row, const QModelIndex& parent, + const QAbstractItemModel* const model) const { + foreach(FilterTree * child, children_) { + if (child->accept(row, parent, model)) return true; } return false; } FilterType type() { return Or; } + private: QList children_; }; @@ -234,22 +257,25 @@ class AndFilter : public FilterTree { public: virtual ~AndFilter() { qDeleteAll(children_); } virtual void add(FilterTree* child) { children_.append(child); } - virtual bool accept(int row, const QModelIndex& parent, const QAbstractItemModel* const model) const { - foreach (FilterTree* child, children_) { - if (!child->accept(row, parent, model)) - return false; + virtual bool accept(int row, const QModelIndex& parent, + const QAbstractItemModel* const model) const { + foreach(FilterTree * child, children_) { + if (!child->accept(row, parent, model)) return false; } return true; } FilterType type() { return And; } + private: QList children_; }; -FilterParser::FilterParser(const QString& filter, const QMap& columns, const QSet& numerical_cols) - : filterstring_(filter), columns_(columns), numerical_columns_(numerical_cols) -{ -} +FilterParser::FilterParser(const QString& filter, + const QMap& columns, + const QSet& numerical_cols) + : filterstring_(filter), + columns_(columns), + numerical_columns_(numerical_cols) {} FilterTree* FilterParser::parse() { iter_ = filterstring_.constBegin(); @@ -265,8 +291,7 @@ void FilterParser::advance() { FilterTree* FilterParser::parseOrGroup() { advance(); - if (iter_ == end_) - return new NopFilter; + if (iter_ == end_) return new NopFilter; OrFilter* group = new OrFilter; group->add(parseAndGroup()); @@ -280,15 +305,13 @@ FilterTree* FilterParser::parseOrGroup() { FilterTree* FilterParser::parseAndGroup() { advance(); - if (iter_ == end_) - return new NopFilter; + if (iter_ == end_) return new NopFilter; AndFilter* group = new AndFilter(); do { group->add(parseSearchExpression()); advance(); - if (iter_ != end_ && *iter_ == QChar(')')) - break; + if (iter_ != end_ && *iter_ == QChar(')')) break; if (checkOr(false)) { break; } @@ -308,7 +331,8 @@ bool FilterParser::checkAnd() { if (iter_ != end_ && *iter_ == QChar('D')) { buf_ += *iter_; iter_++; - if (iter_ != end_ && (iter_->isSpace() || *iter_ == QChar('-') || *iter_ == '(')) { + if (iter_ != end_ && + (iter_->isSpace() || *iter_ == QChar('-') || *iter_ == '(')) { advance(); buf_.clear(); return true; @@ -337,7 +361,8 @@ bool FilterParser::checkOr(bool step_over) { if (iter_ != end_ && *iter_ == 'R') { buf_ += *iter_; iter_++; - if (iter_ != end_ && (iter_->isSpace() || *iter_ == '-' || *iter_ == '(')) { + if (iter_ != end_ && + (iter_->isSpace() || *iter_ == '-' || *iter_ == '(')) { if (step_over) { buf_.clear(); advance(); @@ -353,8 +378,7 @@ bool FilterParser::checkOr(bool step_over) { FilterTree* FilterParser::parseSearchExpression() { advance(); - if (iter_ == end_) - return new NopFilter; + if (iter_ == end_) return new NopFilter; if (*iter_ == '(') { iter_++; advance(); @@ -369,8 +393,7 @@ FilterTree* FilterParser::parseSearchExpression() { } else if (*iter_ == '-') { ++iter_; FilterTree* tree = parseSearchExpression(); - if (tree->type() != FilterTree::Nop) - return new NotFilter(tree); + if (tree->type() != FilterTree::Nop) return new NotFilter(tree); return tree; } else { return parseSearchTerm(); @@ -395,17 +418,14 @@ FilterTree* FilterParser::parseSearchTerm() { col = buf_.toLower(); buf_.clear(); prefix.clear(); // prefix isn't allowed here - let's ignore it - } else if (iter_->isSpace() || - *iter_ == '(' || - *iter_ == ')' || - *iter_ == '-') { - break; + } else if (iter_->isSpace() || *iter_ == '(' || *iter_ == ')' || + *iter_ == '-') { + break; } else if (buf_.isEmpty()) { // we don't know whether there is a column part in this search term // thus we assume the latter and just try and read a prefix - if (prefix.isEmpty() && - (*iter_ == '>' || *iter_ == '<' || *iter_ == '=' || - *iter_ == '!')) { + if (prefix.isEmpty() && (*iter_ == '>' || *iter_ == '<' || + *iter_ == '=' || *iter_ == '!')) { prefix += *iter_; } else if (prefix != "=" && *iter_ == '=') { prefix += *iter_; @@ -481,8 +501,7 @@ FilterTree* FilterParser::createSearchTermTreeNode( cmp = new RatingComparatorDecorator(cmp); } return new FilterColumnTerm(columns_[col], cmp); - } - else { + } else { return new FilterTerm(cmp, columns_.values()); } } @@ -504,7 +523,7 @@ int FilterParser::parseTime(const QString& time_str) const { int seconds = 0; int accum = 0; int colon_count = 0; - foreach (const QChar& c, time_str) { + foreach(const QChar & c, time_str) { if (c.isDigit()) { accum = accum * 10 + c.digitValue(); } else if (c == ':') { diff --git a/src/playlist/playlistfilterparser.h b/src/playlist/playlistfilterparser.h index e921ee172..f6fa21454 100644 --- a/src/playlist/playlistfilterparser.h +++ b/src/playlist/playlistfilterparser.h @@ -29,26 +29,22 @@ class QAbstractItemModel; class FilterTree { public: virtual ~FilterTree() {} - virtual bool accept(int row, const QModelIndex& parent, const QAbstractItemModel* const model) const = 0; - enum FilterType { - Nop = 0, - Or, - And, - Not, - Column, - Term - }; + virtual bool accept(int row, const QModelIndex& parent, + const QAbstractItemModel* const model) const = 0; + enum FilterType { Nop = 0, Or, And, Not, Column, Term }; virtual FilterType type() = 0; }; // trivial filter that accepts *anything* class NopFilter : public FilterTree { public: - virtual bool accept(int row, const QModelIndex& parent, const QAbstractItemModel* const model) const { return true; } + virtual bool accept(int row, const QModelIndex& parent, + const QAbstractItemModel* const model) const { + return true; + } virtual FilterType type() { return Nop; } }; - // A utility class to parse search filter strings into a decision tree // that can decide whether a playlist entry matches the filter. // @@ -64,10 +60,8 @@ class NopFilter : public FilterTree { // col ::= "title" | "artist" | ... class FilterParser { public: - FilterParser( - const QString& filter, - const QMap& columns, - const QSet& numerical_cols); + FilterParser(const QString& filter, const QMap& columns, + const QSet& numerical_cols); FilterTree* parse(); @@ -84,8 +78,9 @@ class FilterParser { FilterTree* parseSearchExpression(); FilterTree* parseSearchTerm(); - FilterTree* createSearchTermTreeNode( - const QString& col, const QString& prefix, const QString& search) const; + FilterTree* createSearchTermTreeNode(const QString& col, + const QString& prefix, + const QString& search) const; int parseTime(const QString& time_str) const; QString::const_iterator iter_; diff --git a/src/playlist/playlistheader.cpp b/src/playlist/playlistheader.cpp index 49d24c244..51a79c2dc 100644 --- a/src/playlist/playlistheader.cpp +++ b/src/playlist/playlistheader.cpp @@ -28,24 +28,25 @@ PlaylistHeader::PlaylistHeader(Qt::Orientation orientation, PlaylistView* view, : StretchHeaderView(orientation, parent), view_(view), menu_(new QMenu(this)), - show_mapper_(new QSignalMapper(this)) -{ + show_mapper_(new QSignalMapper(this)) { hide_action_ = menu_->addAction(tr("&Hide..."), this, SLOT(HideCurrent())); - stretch_action_ = menu_->addAction(tr("&Stretch columns to fit window"), this, SLOT(ToggleStretchEnabled())); + stretch_action_ = menu_->addAction(tr("&Stretch columns to fit window"), this, + SLOT(ToggleStretchEnabled())); menu_->addSeparator(); - QMenu* align_menu = new QMenu(tr("&Align text"), this); + QMenu* align_menu = new QMenu(tr("&Align text"), this); QActionGroup* align_group = new QActionGroup(this); - align_left_action_ = new QAction(tr("&Left"), align_group); - align_center_action_ = new QAction(tr("&Center"), align_group); - align_right_action_ = new QAction(tr("&Right"), align_group); + align_left_action_ = new QAction(tr("&Left"), align_group); + align_center_action_ = new QAction(tr("&Center"), align_group); + align_right_action_ = new QAction(tr("&Right"), align_group); align_left_action_->setCheckable(true); align_center_action_->setCheckable(true); align_right_action_->setCheckable(true); align_menu->addActions(align_group->actions()); - connect(align_group, SIGNAL(triggered(QAction*)), SLOT(SetColumnAlignment(QAction*))); + connect(align_group, SIGNAL(triggered(QAction*)), + SLOT(SetColumnAlignment(QAction*))); menu_->addMenu(align_menu); menu_->addSeparator(); @@ -54,7 +55,8 @@ PlaylistHeader::PlaylistHeader(Qt::Orientation orientation, PlaylistView* view, stretch_action_->setChecked(is_stretch_enabled()); connect(show_mapper_, SIGNAL(mapped(int)), SLOT(ToggleVisible(int))); - connect(this, SIGNAL(StretchEnabledChanged(bool)), stretch_action_, SLOT(setChecked(bool))); + connect(this, SIGNAL(StretchEnabledChanged(bool)), stretch_action_, + SLOT(setChecked(bool))); } void PlaylistHeader::contextMenuEvent(QContextMenuEvent* e) { @@ -66,18 +68,22 @@ void PlaylistHeader::contextMenuEvent(QContextMenuEvent* e) { else { hide_action_->setVisible(true); - QString title(model()->headerData(menu_section_, Qt::Horizontal).toString()); + QString title( + model()->headerData(menu_section_, Qt::Horizontal).toString()); hide_action_->setText(tr("&Hide %1").arg(title)); Qt::Alignment alignment = view_->column_alignment(menu_section_); - if (alignment & Qt::AlignLeft) align_left_action_->setChecked(true); - else if (alignment & Qt::AlignHCenter) align_center_action_->setChecked(true); - else if (alignment & Qt::AlignRight) align_right_action_->setChecked(true); + if (alignment & Qt::AlignLeft) + align_left_action_->setChecked(true); + else if (alignment & Qt::AlignHCenter) + align_center_action_->setChecked(true); + else if (alignment & Qt::AlignRight) + align_right_action_->setChecked(true); } qDeleteAll(show_actions_); show_actions_.clear(); - for (int i=0 ; iSetColumnAlignment(menu_section_, alignment); } @@ -123,6 +128,4 @@ void PlaylistHeader::ToggleVisible(int section) { emit SectionVisibilityChanged(section, !isSectionHidden(section)); } -void PlaylistHeader::enterEvent(QEvent*) { - emit MouseEntered(); -} +void PlaylistHeader::enterEvent(QEvent*) { emit MouseEntered(); } diff --git a/src/playlist/playlistheader.h b/src/playlist/playlistheader.h index 0280b1724..bdd1039ad 100644 --- a/src/playlist/playlistheader.h +++ b/src/playlist/playlistheader.h @@ -36,7 +36,7 @@ class PlaylistHeader : public StretchHeaderView { void contextMenuEvent(QContextMenuEvent* e); void enterEvent(QEvent*); - signals: +signals: void SectionVisibilityChanged(int logical, bool visible); void MouseEntered(); @@ -63,4 +63,4 @@ class PlaylistHeader : public StretchHeaderView { QSignalMapper* show_mapper_; }; -#endif // PLAYLISTHEADER_H +#endif // PLAYLISTHEADER_H diff --git a/src/playlist/playlistitem.cpp b/src/playlist/playlistitem.cpp index cbd803cc0..aa82c5595 100644 --- a/src/playlist/playlistitem.cpp +++ b/src/playlist/playlistitem.cpp @@ -31,19 +31,13 @@ #include #include - -PlaylistItem::~PlaylistItem() { -} +PlaylistItem::~PlaylistItem() {} PlaylistItem* PlaylistItem::NewFromType(const QString& type) { - if (type == "Library") - return new LibraryPlaylistItem(type); - if (type == "Magnatune") - return new MagnatunePlaylistItem(type); - if (type == "Jamendo") - return new JamendoPlaylistItem(type); - if (type == "Stream" || type == "File") - return new SongPlaylistItem(type); + if (type == "Library") return new LibraryPlaylistItem(type); + if (type == "Magnatune") return new MagnatunePlaylistItem(type); + if (type == "Jamendo") return new JamendoPlaylistItem(type); + if (type == "Stream" || type == "File") return new SongPlaylistItem(type); if (type == "Internet" || type == "Radio") return new InternetPlaylistItem("Internet"); @@ -51,9 +45,9 @@ PlaylistItem* PlaylistItem::NewFromType(const QString& type) { return nullptr; } -PlaylistItem* PlaylistItem::NewFromSongsTable(const QString& table, const Song& song) { - if (table == Library::kSongsTable) - return new LibraryPlaylistItem(song); +PlaylistItem* PlaylistItem::NewFromSongsTable(const QString& table, + const Song& song) { + if (table == Library::kSongsTable) return new LibraryPlaylistItem(song); if (table == MagnatuneService::kSongsTable) return new MagnatunePlaylistItem(song); if (table == JamendoService::kSongsTable) @@ -76,13 +70,9 @@ void PlaylistItem::SetTemporaryMetadata(const Song& metadata) { temp_metadata_.set_filetype(Song::Type_Stream); } -void PlaylistItem::ClearTemporaryMetadata() { - temp_metadata_ = Song(); -} +void PlaylistItem::ClearTemporaryMetadata() { temp_metadata_ = Song(); } -static void ReloadPlaylistItem(PlaylistItemPtr item) { - item->Reload(); -} +static void ReloadPlaylistItem(PlaylistItemPtr item) { item->Reload(); } QFuture PlaylistItem::BackgroundReload() { return QtConcurrent::run(ReloadPlaylistItem, shared_from_this()); @@ -99,8 +89,8 @@ void PlaylistItem::RemoveBackgroundColor(short priority) { } QColor PlaylistItem::GetCurrentBackgroundColor() const { return background_colors_.isEmpty() - ? QColor() - : background_colors_[background_colors_.keys().last()]; + ? QColor() + : background_colors_[background_colors_.keys().last()]; } bool PlaylistItem::HasCurrentBackgroundColor() const { return !background_colors_.isEmpty(); @@ -117,8 +107,8 @@ void PlaylistItem::RemoveForegroundColor(short priority) { } QColor PlaylistItem::GetCurrentForegroundColor() const { return foreground_colors_.isEmpty() - ? QColor() - : foreground_colors_[foreground_colors_.keys().last()]; + ? QColor() + : foreground_colors_[foreground_colors_.keys().last()]; } bool PlaylistItem::HasCurrentForegroundColor() const { return !foreground_colors_.isEmpty(); diff --git a/src/playlist/playlistitem.h b/src/playlist/playlistitem.h index 467d10c09..8863c4edf 100644 --- a/src/playlist/playlistitem.h +++ b/src/playlist/playlistitem.h @@ -32,12 +32,12 @@ class SqlRow; class PlaylistItem : public std::enable_shared_from_this { public: - PlaylistItem(const QString& type) - : type_(type) {} + PlaylistItem(const QString& type) : type_(type) {} virtual ~PlaylistItem(); static PlaylistItem* NewFromType(const QString& type); - static PlaylistItem* NewFromSongsTable(const QString& table, const Song& song); + static PlaylistItem* NewFromSongsTable(const QString& table, + const Song& song); enum Option { Default = 0x00, @@ -93,13 +93,11 @@ class PlaylistItem : public std::enable_shared_from_this { virtual bool IsLocalLibraryItem() const { return false; } protected: - enum DatabaseColumn { - Column_LibraryId, - Column_InternetService, - }; + enum DatabaseColumn { Column_LibraryId, Column_InternetService, }; virtual QVariant DatabaseValue(DatabaseColumn) const { - return QVariant(QVariant::String); } + return QVariant(QVariant::String); + } virtual Song DatabaseSongMetadata() const { return Song(); } QString type_; @@ -116,4 +114,4 @@ Q_DECLARE_METATYPE(PlaylistItemPtr) Q_DECLARE_METATYPE(QList) Q_DECLARE_OPERATORS_FOR_FLAGS(PlaylistItem::Options) -#endif // PLAYLISTITEM_H +#endif // PLAYLISTITEM_H diff --git a/src/playlist/playlistitemmimedata.h b/src/playlist/playlistitemmimedata.h index 6d0a0eb18..2be3b59d3 100644 --- a/src/playlist/playlistitemmimedata.h +++ b/src/playlist/playlistitemmimedata.h @@ -24,13 +24,12 @@ class PlaylistItemMimeData : public MimeData { Q_OBJECT -public: + public: PlaylistItemMimeData(const PlaylistItemPtr& item) - : items_(PlaylistItemList() << item) {} - PlaylistItemMimeData(const PlaylistItemList& items) - : items_(items) {} + : items_(PlaylistItemList() << item) {} + PlaylistItemMimeData(const PlaylistItemList& items) : items_(items) {} PlaylistItemList items_; }; -#endif // PLAYLISTITEMMIMEDATA_H +#endif // PLAYLISTITEMMIMEDATA_H diff --git a/src/playlist/playlistlistcontainer.cpp b/src/playlist/playlistlistcontainer.cpp index 468647d28..42bc73a5c 100644 --- a/src/playlist/playlistlistcontainer.cpp +++ b/src/playlist/playlistlistcontainer.cpp @@ -34,15 +34,14 @@ #include class PlaylistListSortFilterModel : public QSortFilterProxyModel { -public: + public: explicit PlaylistListSortFilterModel(QObject* parent) - : QSortFilterProxyModel(parent) { - } + : QSortFilterProxyModel(parent) {} bool lessThan(const QModelIndex& left, const QModelIndex& right) const { // Compare the display text first. - const int ret = left.data().toString().localeAwareCompare( - right.data().toString()); + const int ret = + left.data().toString().localeAwareCompare(right.data().toString()); if (ret < 0) return true; if (ret > 0) return false; @@ -52,26 +51,25 @@ public: } }; - PlaylistListContainer::PlaylistListContainer(QWidget* parent) - : QWidget(parent), - app_(nullptr), - ui_(new Ui_PlaylistListContainer), - menu_(nullptr), - action_new_folder_(new QAction(this)), - action_remove_(new QAction(this)), - action_save_playlist_(new QAction(this)), - model_(new PlaylistListModel(this)), - proxy_(new PlaylistListSortFilterModel(this)), - loaded_icons_(false), - active_playlist_id_(-1) -{ + : QWidget(parent), + app_(nullptr), + ui_(new Ui_PlaylistListContainer), + menu_(nullptr), + action_new_folder_(new QAction(this)), + action_remove_(new QAction(this)), + action_save_playlist_(new QAction(this)), + model_(new PlaylistListModel(this)), + proxy_(new PlaylistListSortFilterModel(this)), + loaded_icons_(false), + active_playlist_id_(-1) { ui_->setupUi(this); ui_->tree->setAttribute(Qt::WA_MacShowFocusRect, false); action_new_folder_->setText(tr("New folder")); action_remove_->setText(tr("Delete")); - action_save_playlist_->setText(tr("Save playlist", "Save playlist menu action.")); + action_save_playlist_->setText( + tr("Save playlist", "Save playlist menu action.")); ui_->new_folder->setDefaultAction(action_new_folder_); ui_->remove->setDefaultAction(action_remove_); @@ -80,8 +78,8 @@ PlaylistListContainer::PlaylistListContainer(QWidget* parent) connect(action_new_folder_, SIGNAL(triggered()), SLOT(NewFolderClicked())); connect(action_remove_, SIGNAL(triggered()), SLOT(DeleteClicked())); connect(action_save_playlist_, SIGNAL(triggered()), SLOT(SavePlaylist())); - connect(model_, SIGNAL(PlaylistPathChanged(int,QString)), - SLOT(PlaylistPathChanged(int,QString))); + connect(model_, SIGNAL(PlaylistPathChanged(int, QString)), + SLOT(PlaylistPathChanged(int, QString))); proxy_->setSourceModel(model_); proxy_->setDynamicSortFilter(true); @@ -89,14 +87,13 @@ PlaylistListContainer::PlaylistListContainer(QWidget* parent) ui_->tree->setModel(proxy_); connect(ui_->tree, SIGNAL(doubleClicked(QModelIndex)), - SLOT(ItemDoubleClicked(QModelIndex))); + SLOT(ItemDoubleClicked(QModelIndex))); - model_->invisibleRootItem()->setData(PlaylistListModel::Type_Folder, PlaylistListModel::Role_Type); + model_->invisibleRootItem()->setData(PlaylistListModel::Type_Folder, + PlaylistListModel::Role_Type); } -PlaylistListContainer::~PlaylistListContainer() { - delete ui_; -} +PlaylistListContainer::~PlaylistListContainer() { delete ui_; } void PlaylistListContainer::showEvent(QShowEvent* e) { // Loading icons is expensive so only do it when the view is first opened @@ -120,17 +117,17 @@ void PlaylistListContainer::showEvent(QShowEvent* e) { } void PlaylistListContainer::RecursivelySetIcons(QStandardItem* parent) const { - for (int i=0 ; irowCount() ; ++i) { + for (int i = 0; i < parent->rowCount(); ++i) { QStandardItem* child = parent->child(i); switch (child->data(PlaylistListModel::Role_Type).toInt()) { - case PlaylistListModel::Type_Folder: - child->setIcon(model_->folder_icon()); - RecursivelySetIcons(child); - break; + case PlaylistListModel::Type_Folder: + child->setIcon(model_->folder_icon()); + RecursivelySetIcons(child); + break; - case PlaylistListModel::Type_Playlist: - child->setIcon(model_->playlist_icon()); - break; + case PlaylistListModel::Type_Playlist: + child->setIcon(model_->playlist_icon()); + break; } } } @@ -140,27 +137,27 @@ void PlaylistListContainer::SetApplication(Application* app) { PlaylistManager* manager = app_->playlist_manager(); Player* player = app_->player(); - connect(manager, SIGNAL(PlaylistAdded(int,QString,bool)), - SLOT(AddPlaylist(int,QString,bool))); - connect(manager, SIGNAL(PlaylistFavorited(int,bool)), - SLOT(PlaylistFavoriteStateChanged(int,bool))); - connect(manager, SIGNAL(PlaylistRenamed(int,QString)), - SLOT(PlaylistRenamed(int,QString))); + connect(manager, SIGNAL(PlaylistAdded(int, QString, bool)), + SLOT(AddPlaylist(int, QString, bool))); + connect(manager, SIGNAL(PlaylistFavorited(int, bool)), + SLOT(PlaylistFavoriteStateChanged(int, bool))); + connect(manager, SIGNAL(PlaylistRenamed(int, QString)), + SLOT(PlaylistRenamed(int, QString))); connect(manager, SIGNAL(CurrentChanged(Playlist*)), SLOT(CurrentChanged(Playlist*))); connect(manager, SIGNAL(ActiveChanged(Playlist*)), SLOT(ActiveChanged(Playlist*))); - connect(model_, SIGNAL(PlaylistRenamed(int,QString)), - manager, SLOT(Rename(int,QString))); + connect(model_, SIGNAL(PlaylistRenamed(int, QString)), manager, + SLOT(Rename(int, QString))); connect(player, SIGNAL(Paused()), SLOT(ActivePaused())); connect(player, SIGNAL(Playing()), SLOT(ActivePlaying())); connect(player, SIGNAL(Stopped()), SLOT(ActiveStopped())); // Get all playlists, even ones that are hidden in the UI. - foreach (const PlaylistBackend::Playlist& p, - app->playlist_backend()->GetAllFavoritePlaylists()) { + foreach(const PlaylistBackend::Playlist & p, + app->playlist_backend()->GetAllFavoritePlaylists()) { QStandardItem* playlist_item = model_->NewPlaylist(p.name, p.id); QStandardItem* parent_folder = model_->FolderByPath(p.ui_path); parent_folder->appendRow(playlist_item); @@ -179,7 +176,8 @@ void PlaylistListContainer::NewFolderClicked() { model_->invisibleRootItem()->appendRow(model_->NewFolder(name)); } -void PlaylistListContainer::AddPlaylist(int id, const QString& name, bool favorite) { +void PlaylistListContainer::AddPlaylist(int id, const QString& name, + bool favorite) { if (!favorite) { return; } @@ -218,19 +216,22 @@ void PlaylistListContainer::RemovePlaylist(int id) { } void PlaylistListContainer::SavePlaylist() { - const QModelIndex& current_index = proxy_->mapToSource(ui_->tree->currentIndex()); + const QModelIndex& current_index = + proxy_->mapToSource(ui_->tree->currentIndex()); // Is it a playlist? if (current_index.data(PlaylistListModel::Role_Type).toInt() == PlaylistListModel::Type_Playlist) { - const int playlist_id = current_index.data(PlaylistListModel::Role_PlaylistId).toInt(); + const int playlist_id = + current_index.data(PlaylistListModel::Role_PlaylistId).toInt(); QStandardItem* item = model_->PlaylistById(playlist_id); QString playlist_name = item ? item->text() : tr("Playlist"); app_->playlist_manager()->SaveWithUI(playlist_id, playlist_name); } } -void PlaylistListContainer::PlaylistFavoriteStateChanged(int id, bool favorite) { +void PlaylistListContainer::PlaylistFavoriteStateChanged(int id, + bool favorite) { if (favorite) { const QString& name = app_->playlist_manager()->GetPlaylistName(id); AddPlaylist(id, name, favorite); @@ -262,11 +263,12 @@ void PlaylistListContainer::CurrentChanged(Playlist* new_playlist) { QModelIndex index = proxy_->mapFromSource(item->index()); ui_->tree->selectionModel()->setCurrentIndex( - index, QItemSelectionModel::ClearAndSelect); + index, QItemSelectionModel::ClearAndSelect); ui_->tree->scrollTo(index); } -void PlaylistListContainer::PlaylistPathChanged(int id, const QString& new_path) { +void PlaylistListContainer::PlaylistPathChanged(int id, + const QString& new_path) { // Update the path in the database app_->playlist_backend()->SetPlaylistUiPath(id, new_path); Playlist* playlist = app_->playlist_manager()->playlist(id); @@ -283,7 +285,7 @@ void PlaylistListContainer::ItemDoubleClicked(const QModelIndex& proxy_index) { if (index.data(PlaylistListModel::Role_Type).toInt() == PlaylistListModel::Type_Playlist) { app_->playlist_manager()->SetCurrentOrOpen( - index.data(PlaylistListModel::Role_PlaylistId).toInt()); + index.data(PlaylistListModel::Role_PlaylistId).toInt()); } } @@ -291,30 +293,31 @@ void PlaylistListContainer::DeleteClicked() { QSet ids; QList folders_to_delete; - foreach (const QModelIndex& proxy_index, - ui_->tree->selectionModel()->selectedRows(0)) { + foreach(const QModelIndex & proxy_index, + ui_->tree->selectionModel()->selectedRows(0)) { const QModelIndex& index = proxy_->mapToSource(proxy_index); // Is it a playlist? switch (index.data(PlaylistListModel::Role_Type).toInt()) { - case PlaylistListModel::Type_Playlist: - ids << index.data(PlaylistListModel::Role_PlaylistId).toInt(); - break; + case PlaylistListModel::Type_Playlist: + ids << index.data(PlaylistListModel::Role_PlaylistId).toInt(); + break; - case PlaylistListModel::Type_Folder: - // Find all the playlists inside. - RecursivelyFindPlaylists(index, &ids); - folders_to_delete << index; - break; + case PlaylistListModel::Type_Folder: + // Find all the playlists inside. + RecursivelyFindPlaylists(index, &ids); + folders_to_delete << index; + break; } } // Make sure the user really wants to unfavorite all these playlists. if (ids.count() > 1) { - const int button = - QMessageBox::question(this, tr("Remove playlists"), - tr("You are about to remove %1 playlists from your favorites, are you sure?").arg(ids.count()), - QMessageBox::Yes, QMessageBox::Cancel); + const int button = QMessageBox::question( + this, tr("Remove playlists"), + tr("You are about to remove %1 playlists from your favorites, are you " + "sure?").arg(ids.count()), + QMessageBox::Yes, QMessageBox::Cancel); if (button != QMessageBox::Yes) { return; @@ -322,30 +325,28 @@ void PlaylistListContainer::DeleteClicked() { } // Unfavorite the playlists - foreach (int id, ids) { - app_->playlist_manager()->Favorite(id, false); - } + foreach(int id, ids) { app_->playlist_manager()->Favorite(id, false); } // Delete the top-level folders. - foreach (const QPersistentModelIndex& index, folders_to_delete) { + foreach(const QPersistentModelIndex & index, folders_to_delete) { if (index.isValid()) { model_->removeRow(index.row(), index.parent()); } } } -void PlaylistListContainer::RecursivelyFindPlaylists( - const QModelIndex& parent, QSet* ids) const { +void PlaylistListContainer::RecursivelyFindPlaylists(const QModelIndex& parent, + QSet* ids) const { switch (parent.data(PlaylistListModel::Role_Type).toInt()) { - case PlaylistListModel::Type_Playlist: - ids->insert(parent.data(PlaylistListModel::Role_PlaylistId).toInt()); - break; + case PlaylistListModel::Type_Playlist: + ids->insert(parent.data(PlaylistListModel::Role_PlaylistId).toInt()); + break; - case PlaylistListModel::Type_Folder: - for (int i=0 ; irowCount(parent) ; ++i) { - RecursivelyFindPlaylists(parent.child(i, 0), ids); - } - break; + case PlaylistListModel::Type_Folder: + for (int i = 0; i < parent.model()->rowCount(parent); ++i) { + RecursivelyFindPlaylists(parent.child(i, 0), ids); + } + break; } } @@ -367,8 +368,8 @@ void PlaylistListContainer::ActivePlaying() { new_pixmap.fill(Qt::transparent); QPainter p(&new_pixmap); - p.drawPixmap((new_pixmap.width() - pixmap.width()) / 2, 0, - pixmap.width(), pixmap.height(), pixmap); + p.drawPixmap((new_pixmap.width() - pixmap.width()) / 2, 0, pixmap.width(), + pixmap.height(), pixmap); p.end(); padded_play_icon_.addPixmap(new_pixmap); diff --git a/src/playlist/playlistlistcontainer.h b/src/playlist/playlistlistcontainer.h index ecebb073d..b9b4dcd27 100644 --- a/src/playlist/playlistlistcontainer.h +++ b/src/playlist/playlistlistcontainer.h @@ -34,17 +34,17 @@ class Ui_PlaylistListContainer; class PlaylistListContainer : public QWidget { Q_OBJECT -public: + public: PlaylistListContainer(QWidget* parent = 0); ~PlaylistListContainer(); void SetApplication(Application* app); -protected: + protected: void showEvent(QShowEvent* e); void contextMenuEvent(QContextMenuEvent* e); -private slots: + private slots: // From the UI void NewFolderClicked(); void DeleteClicked(); @@ -68,12 +68,13 @@ private slots: void ActivePaused(); void ActiveStopped(); -private: + private: QStandardItem* ItemForPlaylist(const QString& name, int id); QStandardItem* ItemForFolder(const QString& name) const; void RecursivelySetIcons(QStandardItem* parent) const; - void RecursivelyFindPlaylists(const QModelIndex& parent, QSet* ids) const; + void RecursivelyFindPlaylists(const QModelIndex& parent, + QSet* ids) const; void UpdateActiveIcon(int id, const QIcon& icon); @@ -94,4 +95,4 @@ private: int active_playlist_id_; }; -#endif // PLAYLISTLISTCONTAINER_H +#endif // PLAYLISTLISTCONTAINER_H diff --git a/src/playlist/playlistlistmodel.cpp b/src/playlist/playlistlistmodel.cpp index 8d96528e7..dced9a74d 100644 --- a/src/playlist/playlistlistmodel.cpp +++ b/src/playlist/playlistlistmodel.cpp @@ -3,16 +3,14 @@ #include -PlaylistListModel::PlaylistListModel(QObject *parent) : - QStandardItemModel(parent), - dropping_rows_(false) -{ - connect(this, SIGNAL(dataChanged(QModelIndex,QModelIndex)), - SLOT(RowsChanged(QModelIndex,QModelIndex))); - connect(this, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), - SLOT(RowsAboutToBeRemoved(QModelIndex,int,int))); - connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), - SLOT(RowsInserted(QModelIndex,int,int))); +PlaylistListModel::PlaylistListModel(QObject* parent) + : QStandardItemModel(parent), dropping_rows_(false) { + connect(this, SIGNAL(dataChanged(QModelIndex, QModelIndex)), + SLOT(RowsChanged(QModelIndex, QModelIndex))); + connect(this, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int)), + SLOT(RowsAboutToBeRemoved(QModelIndex, int, int))); + connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)), + SLOT(RowsInserted(QModelIndex, int, int))); } void PlaylistListModel::SetIcons(const QIcon& playlist_icon, @@ -25,7 +23,8 @@ bool PlaylistListModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) { dropping_rows_ = true; - bool ret = QStandardItemModel::dropMimeData(data, action, row, column, parent); + bool ret = + QStandardItemModel::dropMimeData(data, action, row, column, parent); dropping_rows_ = false; return ret; @@ -50,8 +49,8 @@ void PlaylistListModel::RowsChanged(const QModelIndex& begin, AddRowMappings(begin, end); } -void PlaylistListModel::RowsInserted(const QModelIndex& parent, - int start, int end) { +void PlaylistListModel::RowsInserted(const QModelIndex& parent, int start, + int end) { // RowsChanged will take care of these when dropping. if (!dropping_rows_) { AddRowMappings(index(start, 0, parent), index(end, 0, parent)); @@ -62,52 +61,53 @@ void PlaylistListModel::AddRowMappings(const QModelIndex& begin, const QModelIndex& end) { const QString parent_path = ItemPath(itemFromIndex(begin)); - for (int i=begin.row() ; i<=end.row() ; ++i) { + for (int i = begin.row(); i <= end.row(); ++i) { const QModelIndex index = begin.sibling(i, 0); QStandardItem* item = itemFromIndex(index); AddRowItem(item, parent_path); } } -void PlaylistListModel::AddRowItem(QStandardItem* item, const QString& parent_path) { +void PlaylistListModel::AddRowItem(QStandardItem* item, + const QString& parent_path) { switch (item->data(Role_Type).toInt()) { - case Type_Playlist: { - const int id = item->data(Role_PlaylistId).toInt(); - playlists_by_id_[id] = item; - if (dropping_rows_) { - emit PlaylistPathChanged(id, parent_path); + case Type_Playlist: { + const int id = item->data(Role_PlaylistId).toInt(); + playlists_by_id_[id] = item; + if (dropping_rows_) { + emit PlaylistPathChanged(id, parent_path); + } + + break; } - break; - } - - case Type_Folder: - for (int j=0; jrowCount(); ++j) { - QStandardItem* child_item = item->child(j); - AddRowItem(child_item, parent_path); - } - break; + case Type_Folder: + for (int j = 0; j < item->rowCount(); ++j) { + QStandardItem* child_item = item->child(j); + AddRowItem(child_item, parent_path); + } + break; } } void PlaylistListModel::RowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) { - for (int i=start ; i<=end ; ++i) { + for (int i = start; i <= end; ++i) { const QModelIndex idx = index(i, 0, parent); const QStandardItem* item = itemFromIndex(idx); switch (idx.data(Role_Type).toInt()) { - case Type_Playlist: { - const int id = idx.data(Role_PlaylistId).toInt(); - QMap::Iterator it = playlists_by_id_.find(id); - if (it != playlists_by_id_.end() && it.value() == item) { - playlists_by_id_.erase(it); + case Type_Playlist: { + const int id = idx.data(Role_PlaylistId).toInt(); + QMap::Iterator it = playlists_by_id_.find(id); + if (it != playlists_by_id_.end() && it.value() == item) { + playlists_by_id_.erase(it); + } + break; } - break; - } - case Type_Folder: - break; + case Type_Folder: + break; } } } @@ -126,11 +126,11 @@ QStandardItem* PlaylistListModel::FolderByPath(const QString& path) { QStandardItem* parent = invisibleRootItem(); const QStringList parts = path.split('/', QString::SkipEmptyParts); - foreach (const QString& part, parts) { + foreach(const QString & part, parts) { QStandardItem* matching_child = nullptr; const int child_count = parent->rowCount(); - for (int i=0 ; ichild(i)->data(Qt::DisplayRole).toString() == part) { matching_child = parent->child(i); break; @@ -160,33 +160,34 @@ QStandardItem* PlaylistListModel::NewFolder(const QString& name) const { return ret; } -QStandardItem* PlaylistListModel::NewPlaylist(const QString& name, int id) const { +QStandardItem* PlaylistListModel::NewPlaylist(const QString& name, + int id) const { QStandardItem* ret = new QStandardItem; ret->setText(name); ret->setData(PlaylistListModel::Type_Playlist, PlaylistListModel::Role_Type); ret->setData(id, PlaylistListModel::Role_PlaylistId); ret->setIcon(playlist_icon_); - ret->setFlags(Qt::ItemIsDragEnabled | - Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); + ret->setFlags(Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | + Qt::ItemIsSelectable | Qt::ItemIsEditable); return ret; } -bool PlaylistListModel::setData(const QModelIndex& index, - const QVariant& value, int role) { +bool PlaylistListModel::setData(const QModelIndex& index, const QVariant& value, + int role) { if (!QStandardItemModel::setData(index, value, role)) { return false; } switch (index.data(Role_Type).toInt()) { - case Type_Playlist: - emit PlaylistRenamed(index.data(Role_PlaylistId).toInt(), - value.toString()); - break; + case Type_Playlist: + emit PlaylistRenamed(index.data(Role_PlaylistId).toInt(), + value.toString()); + break; - case Type_Folder: - // Walk all the children and modify their paths. - UpdatePathsRecursive(index); - break; + case Type_Folder: + // Walk all the children and modify their paths. + UpdatePathsRecursive(index); + break; } return true; @@ -194,15 +195,15 @@ bool PlaylistListModel::setData(const QModelIndex& index, void PlaylistListModel::UpdatePathsRecursive(const QModelIndex& parent) { switch (parent.data(Role_Type).toInt()) { - case Type_Playlist: - emit PlaylistPathChanged(parent.data(Role_PlaylistId).toInt(), - ItemPath(itemFromIndex(parent))); - break; + case Type_Playlist: + emit PlaylistPathChanged(parent.data(Role_PlaylistId).toInt(), + ItemPath(itemFromIndex(parent))); + break; - case Type_Folder: - for (int i=0 ; i folders_by_path_; }; -#endif // PLAYLISTLISTMODEL_H +#endif // PLAYLISTLISTMODEL_H diff --git a/src/playlist/playlistlistview.cpp b/src/playlist/playlistlistview.cpp index e0db25b20..411458d23 100644 --- a/src/playlist/playlistlistview.cpp +++ b/src/playlist/playlistlistview.cpp @@ -20,10 +20,7 @@ #include PlaylistListView::PlaylistListView(QWidget* parent) - : AutoExpandingTreeView(parent) -{ -} - + : AutoExpandingTreeView(parent) {} void PlaylistListView::paintEvent(QPaintEvent* event) { if (model()->rowCount() <= 0) { @@ -36,9 +33,11 @@ void PlaylistListView::paintEvent(QPaintEvent* event) { bold_font.setBold(true); p.setFont(bold_font); - p.drawText(rect, Qt::AlignHCenter | Qt::TextWordWrap, tr("\n\n" - "You can favorite playlists by clicking the star icon next to a playlist name\n\n" - "Favorited playlists will be saved here")); + p.drawText(rect, Qt::AlignHCenter | Qt::TextWordWrap, + tr("\n\n" + "You can favorite playlists by clicking the star icon next " + "to a playlist name\n\n" + "Favorited playlists will be saved here")); } else { AutoExpandingTreeView::paintEvent(event); } diff --git a/src/playlist/playlistmanager.cpp b/src/playlist/playlistmanager.cpp index da69a0c78..1c0dbd25d 100644 --- a/src/playlist/playlistmanager.cpp +++ b/src/playlist/playlistmanager.cpp @@ -38,16 +38,15 @@ using smart_playlists::GeneratorPtr; -PlaylistManager::PlaylistManager(Application* app, QObject *parent) - : PlaylistManagerInterface(app, parent), - app_(app), - playlist_backend_(nullptr), - library_backend_(nullptr), - sequence_(nullptr), - parser_(nullptr), - current_(-1), - active_(-1) -{ +PlaylistManager::PlaylistManager(Application* app, QObject* parent) + : PlaylistManagerInterface(app, parent), + app_(app), + playlist_backend_(nullptr), + library_backend_(nullptr), + sequence_(nullptr), + parser_(nullptr), + current_(-1), + active_(-1) { connect(app_->player(), SIGNAL(Paused()), SLOT(SetActivePaused())); connect(app_->player(), SIGNAL(Playing()), SLOT(SetActivePlaying())); connect(app_->player(), SIGNAL(Stopped()), SLOT(SetActiveStopped())); @@ -56,9 +55,7 @@ PlaylistManager::PlaylistManager(Application* app, QObject *parent) } PlaylistManager::~PlaylistManager() { - foreach (const Data& data, playlists_.values()) { - delete data.p; - } + foreach(const Data & data, playlists_.values()) { delete data.p; } } void PlaylistManager::Init(LibraryBackend* library_backend, @@ -71,17 +68,20 @@ void PlaylistManager::Init(LibraryBackend* library_backend, parser_ = new PlaylistParser(library_backend, this); playlist_container_ = playlist_container; - connect(library_backend_, SIGNAL(SongsDiscovered(SongList)), SLOT(SongsDiscovered(SongList))); - connect(library_backend_, SIGNAL(SongsStatisticsChanged(SongList)), SLOT(SongsDiscovered(SongList))); - connect(library_backend_, SIGNAL(SongsRatingChanged(SongList)), SLOT(SongsDiscovered(SongList))); + connect(library_backend_, SIGNAL(SongsDiscovered(SongList)), + SLOT(SongsDiscovered(SongList))); + connect(library_backend_, SIGNAL(SongsStatisticsChanged(SongList)), + SLOT(SongsDiscovered(SongList))); + connect(library_backend_, SIGNAL(SongsRatingChanged(SongList)), + SLOT(SongsDiscovered(SongList))); - foreach (const PlaylistBackend::Playlist& p, playlist_backend->GetAllOpenPlaylists()) { + foreach(const PlaylistBackend::Playlist & p, + playlist_backend->GetAllOpenPlaylists()) { AddPlaylist(p.id, p.name, p.special_type, p.ui_path, p.favorite); } // If no playlist exists then make a new one - if (playlists_.isEmpty()) - New(tr("Playlist")); + if (playlists_.isEmpty()) New(tr("Playlist")); emit PlaylistManagerInitialized(); } @@ -89,9 +89,7 @@ void PlaylistManager::Init(LibraryBackend* library_backend, QList PlaylistManager::GetAllPlaylists() const { QList result; - foreach(const Data& data, playlists_.values()) { - result.append(data.p); - } + foreach(const Data & data, playlists_.values()) { result.append(data.p); } return result; } @@ -103,21 +101,24 @@ QItemSelection PlaylistManager::selection(int id) const { Playlist* PlaylistManager::AddPlaylist(int id, const QString& name, const QString& special_type, - const QString& ui_path, - bool favorite) { + const QString& ui_path, bool favorite) { Playlist* ret = new Playlist(playlist_backend_, app_->task_manager(), library_backend_, id, special_type, favorite); ret->set_sequence(sequence_); ret->set_ui_path(ui_path); - connect(ret, SIGNAL(CurrentSongChanged(Song)), SIGNAL(CurrentSongChanged(Song))); + connect(ret, SIGNAL(CurrentSongChanged(Song)), + SIGNAL(CurrentSongChanged(Song))); connect(ret, SIGNAL(PlaylistChanged()), SLOT(OneOfPlaylistsChanged())); connect(ret, SIGNAL(PlaylistChanged()), SLOT(UpdateSummaryText())); - connect(ret, SIGNAL(EditingFinished(QModelIndex)), SIGNAL(EditingFinished(QModelIndex))); + connect(ret, SIGNAL(EditingFinished(QModelIndex)), + SIGNAL(EditingFinished(QModelIndex))); connect(ret, SIGNAL(LoadTracksError(QString)), SIGNAL(Error(QString))); - connect(ret, SIGNAL(PlayRequested(QModelIndex)), SIGNAL(PlayRequested(QModelIndex))); - connect(playlist_container_->view(), SIGNAL(ColumnAlignmentChanged(ColumnAlignmentMap)), - ret, SLOT(SetColumnAlignment(ColumnAlignmentMap))); + connect(ret, SIGNAL(PlayRequested(QModelIndex)), + SIGNAL(PlayRequested(QModelIndex))); + connect(playlist_container_->view(), + SIGNAL(ColumnAlignmentChanged(ColumnAlignmentMap)), ret, + SLOT(SetColumnAlignment(ColumnAlignmentMap))); playlists_[id] = Data(ret, name); @@ -135,13 +136,11 @@ Playlist* PlaylistManager::AddPlaylist(int id, const QString& name, void PlaylistManager::New(const QString& name, const SongList& songs, const QString& special_type) { - if (name.isNull()) - return; + if (name.isNull()) return; int id = playlist_backend_->CreatePlaylist(name, special_type); - if (id == -1) - qFatal("Couldn't create playlist"); + if (id == -1) qFatal("Couldn't create playlist"); Playlist* playlist = AddPlaylist(id, name, special_type, QString(), false); playlist->InsertSongsOrLibraryItems(songs); @@ -163,8 +162,8 @@ void PlaylistManager::Load(const QString& filename) { if (result == SongLoader::Error || (result == SongLoader::Success && loader->songs().isEmpty())) { - app_->AddError(tr("The playlist '%1' was empty or could not be loaded.").arg( - info.completeBaseName())); + app_->AddError(tr("The playlist '%1' was empty or could not be loaded.") + .arg(info.completeBaseName())); delete loader; return; } @@ -181,8 +180,8 @@ void PlaylistManager::LoadFinished(bool success) { QString localfile = loader->url().toLocalFile(); QFileInfo info(localfile); if (!success || loader->songs().isEmpty()) { - app_->AddError(tr("The playlist '%1' was empty or could not be loaded.").arg( - info.completeBaseName())); + app_->AddError(tr("The playlist '%1' was empty or could not be loaded.") + .arg(info.completeBaseName())); } New(info.baseName(), loader->songs()); @@ -192,20 +191,21 @@ void PlaylistManager::Save(int id, const QString& filename) { if (playlists_.contains(id)) { parser_->Save(playlist(id)->GetAllSongs(), filename); } else { - // Playlist is not in the playlist manager: probably save action was triggered + // Playlist is not in the playlist manager: probably save action was + // triggered // from the left side bar and the playlist isn't loaded. QFuture future = playlist_backend_->GetPlaylistSongs(id); QFutureWatcher* watcher = new QFutureWatcher(this); watcher->setFuture(future); - NewClosure(watcher, SIGNAL(finished()), - this, SLOT(ItemsLoadedForSavePlaylist(QFutureWatcher*, QString)), watcher, filename); + NewClosure(watcher, SIGNAL(finished()), this, + SLOT(ItemsLoadedForSavePlaylist(QFutureWatcher*, QString)), + watcher, filename); } } -void PlaylistManager::ItemsLoadedForSavePlaylist( - QFutureWatcher* watcher, - const QString& filename) { +void PlaylistManager::ItemsLoadedForSavePlaylist(QFutureWatcher* watcher, + const QString& filename) { SongList song_list = watcher->future().results(); parser_->Save(song_list, filename); @@ -220,35 +220,30 @@ void PlaylistManager::SaveWithUI(int id, const QString& suggested_filename) { // Strip off filename components until we find something that's a folder forever { QFileInfo fileinfo(filename); - if (filename.isEmpty() || fileinfo.isDir()) - break; + if (filename.isEmpty() || fileinfo.isDir()) break; filename = filename.section('/', 0, -2); } // Use the home directory as a fallback in case the path is empty. - if (filename.isEmpty()) - filename = QDir::homePath(); + if (filename.isEmpty()) filename = QDir::homePath(); // Add the suggested filename - filename += "/" + suggested_filename + - "." + parser()->default_extension(); + filename += "/" + suggested_filename + "." + parser()->default_extension(); QString default_filter = parser()->default_filter(); filename = QFileDialog::getSaveFileName( - nullptr, tr("Save playlist", "Title of the playlist save dialog."), filename, - parser()->filters(), &default_filter); + nullptr, tr("Save playlist", "Title of the playlist save dialog."), + filename, parser()->filters(), &default_filter); - if (filename.isNull()) - return; + if (filename.isNull()) return; settings_.setValue("last_save_playlist", filename); Save(id == -1 ? current_id() : id, filename); } - void PlaylistManager::Rename(int id, const QString& new_name) { Q_ASSERT(playlists_.contains(id)); @@ -261,12 +256,14 @@ void PlaylistManager::Rename(int id, const QString& new_name) { void PlaylistManager::Favorite(int id, bool favorite) { if (playlists_.contains(id)) { - // If playlists_ contains this playlist, its means it's opened: star or unstar it. + // If playlists_ contains this playlist, its means it's opened: star or + // unstar it. playlist_backend_->FavoritePlaylist(id, favorite); playlists_[id].p->set_favorite(favorite); } else { Q_ASSERT(!favorite); - // Otherwise it means user wants to remove this playlist from the left panel, + // Otherwise it means user wants to remove this playlist from the left + // panel, // while it's not visible in the playlist tabbar either, because it has been // closed: delete it. playlist_backend_->RemovePlaylist(id); @@ -276,23 +273,19 @@ void PlaylistManager::Favorite(int id, bool favorite) { bool PlaylistManager::Close(int id) { // Won't allow removing the last playlist - if (playlists_.count() <= 1 || !playlists_.contains(id)) - return false; + if (playlists_.count() <= 1 || !playlists_.contains(id)) return false; int next_id = -1; - foreach (int possible_next_id, playlists_.keys()) { + foreach(int possible_next_id, playlists_.keys()) { if (possible_next_id != id) { next_id = possible_next_id; break; } } - if (next_id == -1) - return false; + if (next_id == -1) return false; - if (id == active_) - SetActivePlaylist(next_id); - if (id == current_) - SetCurrentPlaylist(next_id); + if (id == active_) SetActivePlaylist(next_id); + if (id == current_) SetCurrentPlaylist(next_id); Data data = playlists_.take(id); emit PlaylistClosed(id); @@ -331,8 +324,7 @@ void PlaylistManager::SetActivePlaylist(int id) { // Kinda a hack: unset the current item from the old active playlist before // setting the new one - if (active_ != -1 && active_ != id) - active()->set_current_row(-1); + if (active_ != -1 && active_ != id) active()->set_current_row(-1); active_ = id; emit ActiveChanged(active()); @@ -350,31 +342,22 @@ void PlaylistManager::SetActiveToCurrent() { } } -void PlaylistManager::ClearCurrent() { - current()->Clear(); -} +void PlaylistManager::ClearCurrent() { current()->Clear(); } -void PlaylistManager::ShuffleCurrent() { - current()->Shuffle(); -} +void PlaylistManager::ShuffleCurrent() { current()->Shuffle(); } void PlaylistManager::RemoveDuplicatesCurrent() { current()->RemoveDuplicateSongs(); } -void PlaylistManager::SetActivePlaying() { - active()->Playing(); -} +void PlaylistManager::SetActivePlaying() { active()->Playing(); } -void PlaylistManager::SetActivePaused() { - active()->Paused(); -} +void PlaylistManager::SetActivePaused() { active()->Paused(); } -void PlaylistManager::SetActiveStopped() { - active()->Stopped(); -} +void PlaylistManager::SetActiveStopped() { active()->Stopped(); } -void PlaylistManager::SetActiveStreamMetadata(const QUrl &url, const Song &song) { +void PlaylistManager::SetActiveStreamMetadata(const QUrl& url, + const Song& song) { active()->SetStreamMetadata(url, song); } @@ -396,15 +379,15 @@ void PlaylistManager::UpdateSummaryText() { int selected = 0; // Get the length of the selected tracks - foreach (const QItemSelectionRange& range, playlists_[current_id()].selection) { - if (!range.isValid()) - continue; + foreach(const QItemSelectionRange & range, + playlists_[current_id()].selection) { + if (!range.isValid()) continue; selected += range.bottom() - range.top() + 1; - for (int i=range.top() ; i<=range.bottom() ; ++i) { - qint64 length = range.model()->index(i, Playlist::Column_Length).data().toLongLong(); - if (length > 0) - nanoseconds += length; + for (int i = range.top(); i <= range.bottom(); ++i) { + qint64 length = + range.model()->index(i, Playlist::Column_Length).data().toLongLong(); + if (length > 0) nanoseconds += length; } } @@ -433,12 +416,11 @@ void PlaylistManager::SongsDiscovered(const SongList& songs) { // Some songs might've changed in the library, let's update any playlist // items we have that match those songs - foreach (const Song& song, songs) { - foreach (const Data& data, playlists_) { + foreach(const Song & song, songs) { + foreach(const Data & data, playlists_) { PlaylistItemList items = data.p->library_items_by_id(song.id()); - foreach (PlaylistItemPtr item, items) { - if (item->Metadata().directory_id() != song.directory_id()) - continue; + foreach(PlaylistItemPtr item, items) { + if (item->Metadata().directory_id() != song.directory_id()) continue; static_cast(item.get())->SetMetadata(song); data.p->ItemChanged(item); } @@ -446,7 +428,8 @@ void PlaylistManager::SongsDiscovered(const SongList& songs) { } } -void PlaylistManager::PlaySmartPlaylist(GeneratorPtr generator, bool as_new, bool clear) { +void PlaylistManager::PlaySmartPlaylist(GeneratorPtr generator, bool as_new, + bool clear) { if (as_new) { New(generator->name()); } @@ -460,34 +443,35 @@ void PlaylistManager::PlaySmartPlaylist(GeneratorPtr generator, bool as_new, boo // When Player has processed the new song chosen by the user... void PlaylistManager::SongChangeRequestProcessed(const QUrl& url, bool valid) { - foreach(Playlist* playlist, GetAllPlaylists()) { - if(playlist->ApplyValidityOnCurrentSong(url, valid)) { + foreach(Playlist * playlist, GetAllPlaylists()) { + if (playlist->ApplyValidityOnCurrentSong(url, valid)) { return; } } } -void PlaylistManager::InsertUrls(int id, const QList &urls, int pos, +void PlaylistManager::InsertUrls(int id, const QList& urls, int pos, bool play_now, bool enqueue) { Q_ASSERT(playlists_.contains(id)); playlists_[id].p->InsertUrls(urls, pos, play_now, enqueue); } -void PlaylistManager::RemoveItemsWithoutUndo(int id, const QList &indices) { +void PlaylistManager::RemoveItemsWithoutUndo(int id, + const QList& indices) { Q_ASSERT(playlists_.contains(id)); playlists_[id].p->RemoveItemsWithoutUndo(indices); } void PlaylistManager::InvalidateDeletedSongs() { - foreach(Playlist* playlist, GetAllPlaylists()) { + foreach(Playlist * playlist, GetAllPlaylists()) { playlist->InvalidateDeletedSongs(); } } void PlaylistManager::RemoveDeletedSongs() { - foreach(Playlist* playlist, GetAllPlaylists()) { + foreach(Playlist * playlist, GetAllPlaylists()) { playlist->RemoveDeletedSongs(); } } @@ -500,15 +484,11 @@ QString PlaylistManager::GetNameForNewPlaylist(const SongList& songs) { QSet artists; QSet albums; - foreach(const Song& song, songs) { - artists << (song.artist().isEmpty() - ? tr("Unknown") - : song.artist()); - albums << (song.album().isEmpty() - ? tr("Unknown") - : song.album()); + foreach(const Song & song, songs) { + artists << (song.artist().isEmpty() ? tr("Unknown") : song.artist()); + albums << (song.album().isEmpty() ? tr("Unknown") : song.album()); - if(artists.size() > 1) { + if (artists.size() > 1) { break; } } @@ -516,13 +496,13 @@ QString PlaylistManager::GetNameForNewPlaylist(const SongList& songs) { bool various_artists = artists.size() > 1; QString result; - if(various_artists) { + if (various_artists) { result = tr("Various artists"); } else { result = artists.values().first(); } - if(!various_artists && albums.size() == 1) { + if (!various_artists && albums.size() == 1) { result += " - " + albums.toList().first(); } @@ -547,6 +527,4 @@ void PlaylistManager::SetCurrentOrOpen(int id) { SetCurrentPlaylist(id); } -bool PlaylistManager::IsPlaylistOpen(int id) { - return playlists_.contains(id); -} +bool PlaylistManager::IsPlaylistOpen(int id) { return playlists_.contains(id); } diff --git a/src/playlist/playlistmanager.h b/src/playlist/playlistmanager.h index 6be882f7f..f20f37e3b 100644 --- a/src/playlist/playlistmanager.h +++ b/src/playlist/playlistmanager.h @@ -42,9 +42,9 @@ class QUrl; class PlaylistManagerInterface : public QObject { Q_OBJECT -public: + public: PlaylistManagerInterface(Application* app, QObject* parent) - : QObject(parent) {} + : QObject(parent) {} virtual int current_id() const = 0; virtual int active_id() const = 0; @@ -72,7 +72,7 @@ public: virtual PlaylistParser* parser() const = 0; virtual PlaylistContainer* playlist_container() const = 0; -public slots: + public slots: virtual void New(const QString& name, const SongList& songs = SongList(), const QString& special_type = QString()) = 0; virtual void Load(const QString& filename) = 0; @@ -104,7 +104,8 @@ public slots: // Rate current song using 0 - 5 scale. virtual void RateCurrentSong(int rating) = 0; - virtual void PlaySmartPlaylist(smart_playlists::GeneratorPtr generator, bool as_new, bool clear) = 0; + virtual void PlaySmartPlaylist(smart_playlists::GeneratorPtr generator, + bool as_new, bool clear) = 0; signals: void PlaylistManagerInitialized(); @@ -133,8 +134,8 @@ signals: class PlaylistManager : public PlaylistManagerInterface { Q_OBJECT -public: - PlaylistManager(Application* app, QObject *parent = 0); + public: + PlaylistManager(Application* app, QObject* parent = 0); ~PlaylistManager(); int current_id() const { return current_; } @@ -162,7 +163,9 @@ public: QItemSelection active_selection() const { return selection(active_id()); } QString GetPlaylistName(int index) const { return playlists_[index].name; } - bool IsPlaylistFavorite(int index) const { return playlists_[index].p->is_favorite(); } + bool IsPlaylistFavorite(int index) const { + return playlists_[index].p->is_favorite(); + } void Init(LibraryBackend* library_backend, PlaylistBackend* playlist_backend, PlaylistSequence* sequence, PlaylistContainer* playlist_container); @@ -173,7 +176,7 @@ public: PlaylistParser* parser() const { return parser_; } PlaylistContainer* playlist_container() const { return playlist_container_; } -public slots: + public slots: void New(const QString& name, const SongList& songs = SongList(), const QString& special_type = QString()); void Load(const QString& filename); @@ -207,15 +210,18 @@ public slots: // Rate current song using 0 - 5 scale. void RateCurrentSong(int rating); - void PlaySmartPlaylist(smart_playlists::GeneratorPtr generator, bool as_new, bool clear); + void PlaySmartPlaylist(smart_playlists::GeneratorPtr generator, bool as_new, + bool clear); void SongChangeRequestProcessed(const QUrl& url, bool valid); - void InsertUrls(int id, const QList& urls, int pos = -1, bool play_now = false, bool enqueue = false); - // Removes items with given indices from the playlist. This operation is not undoable. + void InsertUrls(int id, const QList& urls, int pos = -1, + bool play_now = false, bool enqueue = false); + // Removes items with given indices from the playlist. This operation is not + // undoable. void RemoveItemsWithoutUndo(int id, const QList& indices); -private slots: + private slots: void SetActivePlaying(); void SetActivePaused(); void SetActiveStopped(); @@ -224,15 +230,18 @@ private slots: void UpdateSummaryText(); void SongsDiscovered(const SongList& songs); void LoadFinished(bool success); - void ItemsLoadedForSavePlaylist(QFutureWatcher* watcher, const QString& filename); + void ItemsLoadedForSavePlaylist(QFutureWatcher* watcher, + const QString& filename); -private: - Playlist* AddPlaylist(int id, const QString& name, const QString& special_type, - const QString& ui_path, bool favorite); + private: + Playlist* AddPlaylist(int id, const QString& name, + const QString& special_type, const QString& ui_path, + bool favorite); -private: + private: struct Data { - Data(Playlist* _p = NULL, const QString& _name = QString()) : p(_p), name(_name) {} + Data(Playlist* _p = NULL, const QString& _name = QString()) + : p(_p), name(_name) {} Playlist* p; QString name; QItemSelection selection; @@ -254,4 +263,4 @@ private: int active_; }; -#endif // PLAYLISTMANAGER_H +#endif // PLAYLISTMANAGER_H diff --git a/src/playlist/playlistsequence.cpp b/src/playlist/playlistsequence.cpp index 225a1dbde..5cf1986da 100644 --- a/src/playlist/playlistsequence.cpp +++ b/src/playlist/playlistsequence.cpp @@ -27,22 +27,23 @@ const char* PlaylistSequence::kSettingsGroup = "PlaylistSequence"; -PlaylistSequence::PlaylistSequence(QWidget *parent, SettingsProvider *settings) - : QWidget(parent), - ui_(new Ui_PlaylistSequence), - settings_(settings ? settings : new DefaultSettingsProvider), - repeat_menu_(new QMenu(this)), - shuffle_menu_(new QMenu(this)), - loading_(false), - repeat_mode_(Repeat_Off), - shuffle_mode_(Shuffle_Off), - dynamic_(false) -{ +PlaylistSequence::PlaylistSequence(QWidget* parent, SettingsProvider* settings) + : QWidget(parent), + ui_(new Ui_PlaylistSequence), + settings_(settings ? settings : new DefaultSettingsProvider), + repeat_menu_(new QMenu(this)), + shuffle_menu_(new QMenu(this)), + loading_(false), + repeat_mode_(Repeat_Off), + shuffle_mode_(Shuffle_Off), + dynamic_(false) { ui_->setupUi(this); // Icons - ui_->repeat->setIcon(AddDesaturatedIcon(IconLoader::Load("media-playlist-repeat"))); - ui_->shuffle->setIcon(AddDesaturatedIcon(IconLoader::Load("media-playlist-shuffle"))); + ui_->repeat->setIcon( + AddDesaturatedIcon(IconLoader::Load("media-playlist-repeat"))); + ui_->shuffle->setIcon( + AddDesaturatedIcon(IconLoader::Load("media-playlist-shuffle"))); settings_->set_group(kSettingsGroup); @@ -62,20 +63,22 @@ PlaylistSequence::PlaylistSequence(QWidget *parent, SettingsProvider *settings) shuffle_menu_->addActions(shuffle_group->actions()); ui_->shuffle->setMenu(shuffle_menu_); - connect(repeat_group, SIGNAL(triggered(QAction*)), SLOT(RepeatActionTriggered(QAction*))); - connect(shuffle_group, SIGNAL(triggered(QAction*)), SLOT(ShuffleActionTriggered(QAction*))); + connect(repeat_group, SIGNAL(triggered(QAction*)), + SLOT(RepeatActionTriggered(QAction*))); + connect(shuffle_group, SIGNAL(triggered(QAction*)), + SLOT(ShuffleActionTriggered(QAction*))); Load(); } -PlaylistSequence::~PlaylistSequence() { - delete ui_; -} +PlaylistSequence::~PlaylistSequence() { delete ui_; } void PlaylistSequence::Load() { - loading_ = true; // Stops these setter functions calling Save() - SetShuffleMode(ShuffleMode(settings_->value("shuffle_mode", Shuffle_Off).toInt())); - SetRepeatMode(RepeatMode(settings_->value("repeat_mode", Repeat_Off).toInt())); + loading_ = true; // Stops these setter functions calling Save() + SetShuffleMode( + ShuffleMode(settings_->value("shuffle_mode", Shuffle_Off).toInt())); + SetRepeatMode( + RepeatMode(settings_->value("repeat_mode", Repeat_Off).toInt())); loading_ = false; } @@ -88,7 +91,7 @@ void PlaylistSequence::Save() { QIcon PlaylistSequence::AddDesaturatedIcon(const QIcon& icon) { QIcon ret; - foreach (const QSize& size, icon.availableSizes()) { + foreach(const QSize & size, icon.availableSizes()) { QPixmap on(icon.pixmap(size)); QPixmap off(DesaturatedPixmap(on)); @@ -112,8 +115,8 @@ QPixmap PlaylistSequence::DesaturatedPixmap(const QPixmap& pixmap) { void PlaylistSequence::RepeatActionTriggered(QAction* action) { RepeatMode mode = Repeat_Off; - if (action == ui_->action_repeat_track) mode = Repeat_Track; - if (action == ui_->action_repeat_album) mode = Repeat_Album; + if (action == ui_->action_repeat_track) mode = Repeat_Track; + if (action == ui_->action_repeat_album) mode = Repeat_Album; if (action == ui_->action_repeat_playlist) mode = Repeat_Playlist; SetRepeatMode(mode); @@ -121,9 +124,9 @@ void PlaylistSequence::RepeatActionTriggered(QAction* action) { void PlaylistSequence::ShuffleActionTriggered(QAction* action) { ShuffleMode mode = Shuffle_Off; - if (action == ui_->action_shuffle_all) mode = Shuffle_All; + if (action == ui_->action_shuffle_all) mode = Shuffle_All; if (action == ui_->action_shuffle_inside_album) mode = Shuffle_InsideAlbum; - if (action == ui_->action_shuffle_albums) mode = Shuffle_Albums; + if (action == ui_->action_shuffle_albums) mode = Shuffle_Albums; SetShuffleMode(mode); } @@ -131,11 +134,19 @@ void PlaylistSequence::ShuffleActionTriggered(QAction* action) { void PlaylistSequence::SetRepeatMode(RepeatMode mode) { ui_->repeat->setChecked(mode != Repeat_Off); - switch(mode) { - case Repeat_Off: ui_->action_repeat_off->setChecked(true); break; - case Repeat_Track: ui_->action_repeat_track->setChecked(true); break; - case Repeat_Album: ui_->action_repeat_album->setChecked(true); break; - case Repeat_Playlist: ui_->action_repeat_playlist->setChecked(true); break; + switch (mode) { + case Repeat_Off: + ui_->action_repeat_off->setChecked(true); + break; + case Repeat_Track: + ui_->action_repeat_track->setChecked(true); + break; + case Repeat_Album: + ui_->action_repeat_album->setChecked(true); + break; + case Repeat_Playlist: + ui_->action_repeat_playlist->setChecked(true); + break; } if (mode != repeat_mode_) { @@ -150,13 +161,20 @@ void PlaylistSequence::SetShuffleMode(ShuffleMode mode) { ui_->shuffle->setChecked(mode != Shuffle_Off); switch (mode) { - case Shuffle_Off: ui_->action_shuffle_off->setChecked(true); break; - case Shuffle_All: ui_->action_shuffle_all->setChecked(true); break; - case Shuffle_InsideAlbum: ui_->action_shuffle_inside_album->setChecked(true); break; - case Shuffle_Albums: ui_->action_shuffle_albums->setChecked(true); break; + case Shuffle_Off: + ui_->action_shuffle_off->setChecked(true); + break; + case Shuffle_All: + ui_->action_shuffle_all->setChecked(true); + break; + case Shuffle_InsideAlbum: + ui_->action_shuffle_inside_album->setChecked(true); + break; + case Shuffle_Albums: + ui_->action_shuffle_albums->setChecked(true); + break; } - if (mode != shuffle_mode_) { shuffle_mode_ = mode; emit ShuffleModeChanged(mode); @@ -167,7 +185,8 @@ void PlaylistSequence::SetShuffleMode(ShuffleMode mode) { void PlaylistSequence::SetUsingDynamicPlaylist(bool dynamic) { dynamic_ = dynamic; - const QString not_available(tr("Not available while using a dynamic playlist")); + const QString not_available( + tr("Not available while using a dynamic playlist")); setEnabled(!dynamic); ui_->shuffle->setToolTip(dynamic ? not_available : tr("Shuffle")); @@ -182,29 +201,43 @@ PlaylistSequence::RepeatMode PlaylistSequence::repeat_mode() const { return dynamic_ ? Repeat_Off : repeat_mode_; } -//called from global shortcut +// called from global shortcut void PlaylistSequence::CycleShuffleMode() { ShuffleMode mode = Shuffle_Off; - //we cycle through the shuffle modes + // we cycle through the shuffle modes switch (shuffle_mode()) { - case Shuffle_Off: mode = Shuffle_All; break; - case Shuffle_All: mode = Shuffle_InsideAlbum; break; - case Shuffle_InsideAlbum: mode = Shuffle_Albums; break; - case Shuffle_Albums: break; + case Shuffle_Off: + mode = Shuffle_All; + break; + case Shuffle_All: + mode = Shuffle_InsideAlbum; + break; + case Shuffle_InsideAlbum: + mode = Shuffle_Albums; + break; + case Shuffle_Albums: + break; } SetShuffleMode(mode); } -//called from global shortcut +// called from global shortcut void PlaylistSequence::CycleRepeatMode() { RepeatMode mode = Repeat_Off; - //we cycle through the repeat modes + // we cycle through the repeat modes switch (repeat_mode()) { - case Repeat_Off: mode = Repeat_Track; break; - case Repeat_Track: mode = Repeat_Album; break; - case Repeat_Album: mode = Repeat_Playlist; break; - case Repeat_Playlist: break; + case Repeat_Off: + mode = Repeat_Track; + break; + case Repeat_Track: + mode = Repeat_Album; + break; + case Repeat_Album: + mode = Repeat_Playlist; + break; + case Repeat_Playlist: + break; } SetRepeatMode(mode); diff --git a/src/playlist/playlistsequence.h b/src/playlist/playlistsequence.h index 0141b09cf..c607d740e 100644 --- a/src/playlist/playlistsequence.h +++ b/src/playlist/playlistsequence.h @@ -32,7 +32,7 @@ class PlaylistSequence : public QWidget { Q_OBJECT public: - PlaylistSequence(QWidget *parent = 0, SettingsProvider* settings = 0); + PlaylistSequence(QWidget* parent = 0, SettingsProvider* settings = 0); ~PlaylistSequence(); enum RepeatMode { @@ -63,7 +63,7 @@ class PlaylistSequence : public QWidget { void CycleRepeatMode(); void SetUsingDynamicPlaylist(bool dynamic); - signals: +signals: void RepeatModeChanged(PlaylistSequence::RepeatMode mode); void ShuffleModeChanged(PlaylistSequence::ShuffleMode mode); @@ -90,4 +90,4 @@ class PlaylistSequence : public QWidget { bool dynamic_; }; -#endif // PLAYLISTSEQUENCE_H +#endif // PLAYLISTSEQUENCE_H diff --git a/src/playlist/playlisttabbar.cpp b/src/playlist/playlisttabbar.cpp index 4f5b898d0..341100873 100644 --- a/src/playlist/playlisttabbar.cpp +++ b/src/playlist/playlisttabbar.cpp @@ -38,22 +38,24 @@ const char* PlaylistTabBar::kSettingsGroup = "PlaylistTabBar"; -PlaylistTabBar::PlaylistTabBar(QWidget *parent) - : QTabBar(parent), - manager_(nullptr), - menu_(new QMenu(this)), - menu_index_(-1), - suppress_current_changed_(false), - rename_editor_(new RenameTabLineEdit(this)) -{ +PlaylistTabBar::PlaylistTabBar(QWidget* parent) + : QTabBar(parent), + manager_(nullptr), + menu_(new QMenu(this)), + menu_index_(-1), + suppress_current_changed_(false), + rename_editor_(new RenameTabLineEdit(this)) { setAcceptDrops(true); setElideMode(Qt::ElideRight); setUsesScrollButtons(true); setTabsClosable(true); - close_ = menu_->addAction(IconLoader::Load("list-remove"), tr("Close playlist"), this, SLOT(Close())); - rename_ = menu_->addAction(IconLoader::Load("edit-rename"), tr("Rename playlist..."), this, SLOT(Rename())); - save_ = menu_->addAction(IconLoader::Load("document-save"), tr("Save playlist..."), this, SLOT(Save())); + close_ = menu_->addAction(IconLoader::Load("list-remove"), + tr("Close playlist"), this, SLOT(Close())); + rename_ = menu_->addAction(IconLoader::Load("edit-rename"), + tr("Rename playlist..."), this, SLOT(Rename())); + save_ = menu_->addAction(IconLoader::Load("document-save"), + tr("Save playlist..."), this, SLOT(Save())); menu_->addSeparator(); rename_editor_->setVisible(false); @@ -61,29 +63,28 @@ PlaylistTabBar::PlaylistTabBar(QWidget *parent) connect(rename_editor_, SIGNAL(EditingCanceled()), SLOT(HideEditor())); connect(this, SIGNAL(currentChanged(int)), SLOT(CurrentIndexChanged(int))); - connect(this, SIGNAL(tabMoved(int,int)), SLOT(TabMoved())); + connect(this, SIGNAL(tabMoved(int, int)), SLOT(TabMoved())); // We can't just emit Close signal, we need to extract the playlist id first connect(this, SIGNAL(tabCloseRequested(int)), SLOT(CloseFromTabIndex(int))); } -void PlaylistTabBar::SetActions( - QAction* new_playlist, QAction* load_playlist) { +void PlaylistTabBar::SetActions(QAction* new_playlist, QAction* load_playlist) { menu_->insertAction(0, new_playlist); menu_->insertAction(0, load_playlist); new_ = new_playlist; } -void PlaylistTabBar::SetManager(PlaylistManager *manager) { +void PlaylistTabBar::SetManager(PlaylistManager* manager) { manager_ = manager; connect(manager_, SIGNAL(PlaylistFavorited(int, bool)), - SLOT(PlaylistFavoritedSlot(int, bool))); + SLOT(PlaylistFavoritedSlot(int, bool))); } void PlaylistTabBar::contextMenuEvent(QContextMenuEvent* e) { - //we need to finish the renaming action before showing context menu + // we need to finish the renaming action before showing context menu if (rename_editor_->isVisible()) { - //discard any change + // discard any change HideEditor(); } @@ -105,19 +106,18 @@ void PlaylistTabBar::mouseReleaseEvent(QMouseEvent* e) { QTabBar::mouseReleaseEvent(e); } -void PlaylistTabBar::mouseDoubleClickEvent(QMouseEvent *e) { +void PlaylistTabBar::mouseDoubleClickEvent(QMouseEvent* e) { int index = tabAt(e->pos()); - //discard a double click with the middle button + // discard a double click with the middle button if (e->button() != Qt::MidButton) { if (index == -1) { new_->activate(QAction::Trigger); - } - else { - //update current tab + } else { + // update current tab menu_index_ = index; - //set position + // set position rename_editor_->setGeometry(tabRect(index)); rename_editor_->setText(tabText(index)); rename_editor_->setVisible(true); @@ -129,16 +129,14 @@ void PlaylistTabBar::mouseDoubleClickEvent(QMouseEvent *e) { } void PlaylistTabBar::Rename() { - if (menu_index_ == -1) - return; + if (menu_index_ == -1) return; QString name = tabText(menu_index_); - name = QInputDialog::getText( - this, tr("Rename playlist"), tr("Enter a new name for this playlist"), - QLineEdit::Normal, name); + name = QInputDialog::getText(this, tr("Rename playlist"), + tr("Enter a new name for this playlist"), + QLineEdit::Normal, name); - if (name.isNull()) - return; + if (name.isNull()) return; emit Rename(tabData(menu_index_).toInt(), name); } @@ -149,16 +147,16 @@ void PlaylistTabBar::RenameInline() { } void PlaylistTabBar::HideEditor() { - //editingFinished() will be called twice due to Qt bug #40, so we reuse the same instance, don't delete it + // editingFinished() will be called twice due to Qt bug #40, so we reuse the + // same instance, don't delete it rename_editor_->setVisible(false); - //hack to give back focus to playlist view + // hack to give back focus to playlist view manager_->SetCurrentPlaylist(manager_->current()->id()); } void PlaylistTabBar::Close() { - if (menu_index_ == -1) - return; + if (menu_index_ == -1) return; const int playlist_id = tabData(menu_index_).toInt(); @@ -174,12 +172,14 @@ void PlaylistTabBar::Close() { confirmation_box.setWindowTitle(tr("Remove playlist")); confirmation_box.setIcon(QMessageBox::Question); confirmation_box.setText( - tr("You are about to remove a playlist which is not part of your favorite playlists: " + tr("You are about to remove a playlist which is not part of your " + "favorite playlists: " "the playlist will be deleted (this action cannot be undone). \n" "Are you sure you want to continue?")); confirmation_box.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel); - QCheckBox dont_prompt_again(tr("Warn me when closing a playlist tab"), &confirmation_box); + QCheckBox dont_prompt_again(tr("Warn me when closing a playlist tab"), + &confirmation_box); dont_prompt_again.setChecked(ask_for_delete); dont_prompt_again.blockSignals(true); dont_prompt_again.setToolTip( @@ -188,13 +188,13 @@ void PlaylistTabBar::Close() { QGridLayout* grid = qobject_cast(confirmation_box.layout()); QDialogButtonBox* buttons = confirmation_box.findChild(); if (grid && buttons) { - const int index = grid->indexOf(buttons); - int row, column, row_span, column_span = 0; - grid->getItemPosition(index, &row, &column, &row_span, &column_span); - QLayoutItem* buttonsItem = grid->takeAt(index); - grid->addWidget(&dont_prompt_again, row, column, row_span, column_span, - Qt::AlignLeft | Qt::AlignTop); - grid->addItem(buttonsItem, ++row, column, row_span, column_span); + const int index = grid->indexOf(buttons); + int row, column, row_span, column_span = 0; + grid->getItemPosition(index, &row, &column, &row_span, &column_span); + QLayoutItem* buttonsItem = grid->takeAt(index); + grid->addWidget(&dont_prompt_again, row, column, row_span, column_span, + Qt::AlignLeft | Qt::AlignTop); + grid->addItem(buttonsItem, ++row, column, row_span, column_span); } else { confirmation_box.addButton(&dont_prompt_again, QMessageBox::ActionRole); } @@ -231,21 +231,18 @@ void PlaylistTabBar::CloseFromTabIndex(int index) { } void PlaylistTabBar::Save() { - if (menu_index_ == -1) - return; + if (menu_index_ == -1) return; emit Save(tabData(menu_index_).toInt()); } int PlaylistTabBar::current_id() const { - if (currentIndex() == -1) - return -1; + if (currentIndex() == -1) return -1; return tabData(currentIndex()).toInt(); } - int PlaylistTabBar::index_of(int id) const { - for (int i=0 ; i= count()) { @@ -265,40 +260,38 @@ int PlaylistTabBar::id_of(int index) const { return tabData(index).toInt(); } -void PlaylistTabBar::set_icon_by_id(int id, const QIcon &icon) { +void PlaylistTabBar::set_icon_by_id(int id, const QIcon& icon) { setTabIcon(index_of(id), icon); } -void PlaylistTabBar::RemoveTab(int id) { - removeTab(index_of(id)); -} +void PlaylistTabBar::RemoveTab(int id) { removeTab(index_of(id)); } -void PlaylistTabBar::set_text_by_id(int id, const QString &text) { +void PlaylistTabBar::set_text_by_id(int id, const QString& text) { setTabText(index_of(id), text); setTabToolTip(index_of(id), text); } void PlaylistTabBar::CurrentIndexChanged(int index) { - if (!suppress_current_changed_) - emit CurrentIdChanged(tabData(index).toInt()); + if (!suppress_current_changed_) emit CurrentIdChanged(tabData(index).toInt()); } -void PlaylistTabBar::InsertTab(int id, int index, const QString& text, bool favorite) { +void PlaylistTabBar::InsertTab(int id, int index, const QString& text, + bool favorite) { suppress_current_changed_ = true; insertTab(index, text); setTabData(index, id); setTabToolTip(index, text); FavoriteWidget* widget = new FavoriteWidget(id, favorite); - widget->setToolTip(tr( - "Click here to favorite this playlist so it will be saved and remain accessible " - "through the \"Playlists\" panel on the left side bar")); + widget->setToolTip( + tr("Click here to favorite this playlist so it will be saved and remain " + "accessible " + "through the \"Playlists\" panel on the left side bar")); connect(widget, SIGNAL(FavoriteStateChanged(int, bool)), - SIGNAL(PlaylistFavorited(int, bool))); + SIGNAL(PlaylistFavorited(int, bool))); setTabButton(index, QTabBar::LeftSide, widget); suppress_current_changed_ = false; - if (currentIndex() == index) - emit CurrentIdChanged(id); + if (currentIndex() == index) emit CurrentIdChanged(id); // Update playlist tab order/visibility TabMoved(); @@ -306,7 +299,7 @@ void PlaylistTabBar::InsertTab(int id, int index, const QString& text, bool favo void PlaylistTabBar::TabMoved() { QList ids; - for (int i=0 ; itimerId() == drag_hover_timer_.timerId()) { drag_hover_timer_.stop(); - if (drag_hover_tab_ != -1) - setCurrentIndex(drag_hover_tab_); + if (drag_hover_tab_ != -1) setCurrentIndex(drag_hover_tab_); } } void PlaylistTabBar::dropEvent(QDropEvent* e) { if (drag_hover_tab_ == -1) { - const MimeData *mime_data = qobject_cast(e->mimeData()); - if(mime_data && !mime_data->name_for_new_playlist_.isEmpty()) { + const MimeData* mime_data = qobject_cast(e->mimeData()); + if (mime_data && !mime_data->name_for_new_playlist_.isEmpty()) { manager_->New(mime_data->name_for_new_playlist_); } else { manager_->New(tr("Playlist")); @@ -361,13 +353,14 @@ void PlaylistTabBar::dropEvent(QDropEvent* e) { setCurrentIndex(drag_hover_tab_); } - manager_->current()->dropMimeData(e->mimeData(), e->proposedAction(), -1, 0, QModelIndex()); + manager_->current()->dropMimeData(e->mimeData(), e->proposedAction(), -1, 0, + QModelIndex()); } bool PlaylistTabBar::event(QEvent* e) { switch (e->type()) { case QEvent::ToolTip: { - QHelpEvent *he = static_cast(e); + QHelpEvent* he = static_cast(e); QRect displayed_tab; QSize real_tab; @@ -377,7 +370,7 @@ bool PlaylistTabBar::event(QEvent* e) { displayed_tab = tabRect(tabAt(he->pos())); // Check whether the tab is elided or not is_elided = displayed_tab.width() < real_tab.width(); - if(!is_elided) { + if (!is_elided) { // If it's not elided, don't show the tooltip QToolTip::hideText(); } else { @@ -392,7 +385,8 @@ bool PlaylistTabBar::event(QEvent* e) { void PlaylistTabBar::PlaylistFavoritedSlot(int id, bool favorite) { const int index = index_of(id); - FavoriteWidget* favorite_widget = qobject_cast(tabButton(index, QTabBar::LeftSide)); + FavoriteWidget* favorite_widget = + qobject_cast(tabButton(index, QTabBar::LeftSide)); if (favorite_widget) { favorite_widget->SetFavorite(favorite); } diff --git a/src/playlist/playlisttabbar.h b/src/playlist/playlisttabbar.h index 63ad8146e..5cd1081ac 100644 --- a/src/playlist/playlisttabbar.h +++ b/src/playlist/playlisttabbar.h @@ -30,8 +30,8 @@ class QMenu; class PlaylistTabBar : public QTabBar { Q_OBJECT -public: - PlaylistTabBar(QWidget *parent = 0); + public: + PlaylistTabBar(QWidget* parent = 0); static const int kDragHoverTimeout = 500; static const char* kSettingsGroup; @@ -61,7 +61,7 @@ signals: void PlaylistOrderChanged(const QList& ids); void PlaylistFavorited(int id, bool favorite); -protected: + protected: void contextMenuEvent(QContextMenuEvent* e); void mouseReleaseEvent(QMouseEvent* e); void mouseDoubleClickEvent(QMouseEvent* e); @@ -72,7 +72,7 @@ protected: void timerEvent(QTimerEvent* e); bool event(QEvent* e); -private slots: + private slots: void CurrentIndexChanged(int index); void Rename(); void RenameInline(); @@ -85,7 +85,7 @@ private slots: void TabMoved(); void Save(); -private: + private: PlaylistManager* manager_; QMenu* menu_; @@ -104,4 +104,4 @@ private: RenameTabLineEdit* rename_editor_; }; -#endif // PLAYLISTTABBAR_H +#endif // PLAYLISTTABBAR_H diff --git a/src/playlist/playlistundocommands.cpp b/src/playlist/playlistundocommands.cpp index e505489b4..57c6f917f 100644 --- a/src/playlist/playlistundocommands.cpp +++ b/src/playlist/playlistundocommands.cpp @@ -20,20 +20,11 @@ namespace PlaylistUndoCommands { -Base::Base(Playlist *playlist) - : QUndoCommand(0), - playlist_(playlist) -{ -} +Base::Base(Playlist* playlist) : QUndoCommand(0), playlist_(playlist) {} - -InsertItems::InsertItems(Playlist *playlist, const PlaylistItemList& items, +InsertItems::InsertItems(Playlist* playlist, const PlaylistItemList& items, int pos, bool enqueue) - : Base(playlist), - items_(items), - pos_(pos), - enqueue_(enqueue) -{ + : Base(playlist), items_(items), pos_(pos), enqueue_(enqueue) { setText(tr("add %n songs", "", items_.count())); } @@ -42,13 +33,12 @@ void InsertItems::redo() { } void InsertItems::undo() { - const int start = pos_ == -1 ? - playlist_->rowCount() - items_.count() : pos_; + const int start = pos_ == -1 ? playlist_->rowCount() - items_.count() : pos_; playlist_->RemoveItemsWithoutUndo(start, items_.count()); } bool InsertItems::UpdateItem(const PlaylistItemPtr& updated_item) { - for (int i=0; iMetadata().url() == updated_item->Metadata().url()) { items_[i] = updated_item; @@ -58,84 +48,63 @@ bool InsertItems::UpdateItem(const PlaylistItemPtr& updated_item) { return false; } - -RemoveItems::RemoveItems(Playlist *playlist, int pos, int count) - : Base(playlist) -{ +RemoveItems::RemoveItems(Playlist* playlist, int pos, int count) + : Base(playlist) { setText(tr("remove %n songs", "", count)); ranges_ << Range(pos, count); } void RemoveItems::redo() { - for (int i=0 ; iRemoveItemsWithoutUndo( - ranges_[i].pos_, ranges_[i].count_); + for (int i = 0; i < ranges_.count(); ++i) + ranges_[i].items_ = + playlist_->RemoveItemsWithoutUndo(ranges_[i].pos_, ranges_[i].count_); } void RemoveItems::undo() { - for (int i=ranges_.count()-1 ; i>=0 ; --i) + for (int i = ranges_.count() - 1; i >= 0; --i) playlist_->InsertItemsWithoutUndo(ranges_[i].items_, ranges_[i].pos_); } -bool RemoveItems::mergeWith(const QUndoCommand *other) { +bool RemoveItems::mergeWith(const QUndoCommand* other) { const RemoveItems* remove_command = static_cast(other); ranges_.append(remove_command->ranges_); int sum = 0; - foreach (const Range& range, ranges_) - sum += range.count_; + foreach(const Range & range, ranges_) + sum += range.count_; setText(tr("remove %n songs", "", sum)); return true; } - -MoveItems::MoveItems(Playlist *playlist, const QList &source_rows, int pos) - : Base(playlist), - source_rows_(source_rows), - pos_(pos) -{ +MoveItems::MoveItems(Playlist* playlist, const QList& source_rows, int pos) + : Base(playlist), source_rows_(source_rows), pos_(pos) { setText(tr("move %n songs", "", source_rows.count())); } -void MoveItems::redo() { - playlist_->MoveItemsWithoutUndo(source_rows_, pos_); -} +void MoveItems::redo() { playlist_->MoveItemsWithoutUndo(source_rows_, pos_); } -void MoveItems::undo() { - playlist_->MoveItemsWithoutUndo(pos_, source_rows_); -} +void MoveItems::undo() { playlist_->MoveItemsWithoutUndo(pos_, source_rows_); } +ReOrderItems::ReOrderItems(Playlist* playlist, + const PlaylistItemList& new_items) + : Base(playlist), old_items_(playlist->items_), new_items_(new_items) {} -ReOrderItems::ReOrderItems(Playlist* playlist, const PlaylistItemList& new_items) - : Base(playlist), - old_items_(playlist->items_), - new_items_(new_items) { } +void ReOrderItems::undo() { playlist_->ReOrderWithoutUndo(old_items_); } -void ReOrderItems::undo() { - playlist_->ReOrderWithoutUndo(old_items_); -} +void ReOrderItems::redo() { playlist_->ReOrderWithoutUndo(new_items_); } -void ReOrderItems::redo() { - playlist_->ReOrderWithoutUndo(new_items_); -} - - -SortItems::SortItems(Playlist* playlist, int column, Qt::SortOrder order, +SortItems::SortItems(Playlist* playlist, int column, Qt::SortOrder order, const PlaylistItemList& new_items) - : ReOrderItems(playlist, new_items), - column_(column), - order_(order) -{ + : ReOrderItems(playlist, new_items), column_(column), order_(order) { setText(tr("sort songs")); } - -ShuffleItems::ShuffleItems(Playlist* playlist, const PlaylistItemList& new_items) - : ReOrderItems(playlist, new_items) -{ +ShuffleItems::ShuffleItems(Playlist* playlist, + const PlaylistItemList& new_items) + : ReOrderItems(playlist, new_items) { setText(tr("shuffle songs")); } -} // namespace +} // namespace diff --git a/src/playlist/playlistundocommands.h b/src/playlist/playlistundocommands.h index 0a0f9fe47..f2860e9a6 100644 --- a/src/playlist/playlistundocommands.h +++ b/src/playlist/playlistundocommands.h @@ -26,98 +26,97 @@ class Playlist; namespace PlaylistUndoCommands { - enum Types { - Type_RemoveItems = 0, - }; +enum Types { Type_RemoveItems = 0, }; - class Base : public QUndoCommand { - Q_DECLARE_TR_FUNCTIONS(PlaylistUndoCommands); +class Base : public QUndoCommand { + Q_DECLARE_TR_FUNCTIONS(PlaylistUndoCommands); - public: - Base(Playlist* playlist); + public: + Base(Playlist* playlist); - protected: - Playlist* playlist_; - }; + protected: + Playlist* playlist_; +}; - class InsertItems : public Base { - public: - InsertItems(Playlist* playlist, const PlaylistItemList& items, int pos, - bool enqueue = false); +class InsertItems : public Base { + public: + InsertItems(Playlist* playlist, const PlaylistItemList& items, int pos, + bool enqueue = false); - void undo(); - void redo(); - // When load is async, items have already been pushed, so we need to update them. - // This function try to find the equivalent item, and replace it with the - // new (completely loaded) one. - // return true if the was found (and updated), false otherwise - bool UpdateItem(const PlaylistItemPtr& updated_item); + void undo(); + void redo(); + // When load is async, items have already been pushed, so we need to update + // them. + // This function try to find the equivalent item, and replace it with the + // new (completely loaded) one. + // return true if the was found (and updated), false otherwise + bool UpdateItem(const PlaylistItemPtr& updated_item); - private: + private: + PlaylistItemList items_; + int pos_; + bool enqueue_; +}; + +class RemoveItems : public Base { + public: + RemoveItems(Playlist* playlist, int pos, int count); + + int id() const { return Type_RemoveItems; } + + void undo(); + void redo(); + bool mergeWith(const QUndoCommand* other); + + private: + struct Range { + Range(int pos, int count) : pos_(pos), count_(count) {} + int pos_; + int count_; PlaylistItemList items_; - int pos_; - bool enqueue_; }; - class RemoveItems : public Base { - public: - RemoveItems(Playlist* playlist, int pos, int count); + QList ranges_; +}; - int id() const { return Type_RemoveItems; } +class MoveItems : public Base { + public: + MoveItems(Playlist* playlist, const QList& source_rows, int pos); - void undo(); - void redo(); - bool mergeWith(const QUndoCommand *other); + void undo(); + void redo(); - private: - struct Range { - Range(int pos, int count) : pos_(pos), count_(count) {} - int pos_; - int count_; - PlaylistItemList items_; - }; + private: + QList source_rows_; + int pos_; +}; - QList ranges_; - }; +class ReOrderItems : public Base { + public: + ReOrderItems(Playlist* playlist, const PlaylistItemList& new_items); - class MoveItems : public Base { - public: - MoveItems(Playlist* playlist, const QList& source_rows, int pos); + void undo(); + void redo(); - void undo(); - void redo(); + private: + PlaylistItemList old_items_; + PlaylistItemList new_items_; +}; - private: - QList source_rows_; - int pos_; - }; +class SortItems : public ReOrderItems { + public: + SortItems(Playlist* playlist, int column, Qt::SortOrder order, + const PlaylistItemList& new_items); - class ReOrderItems : public Base { - public: - ReOrderItems(Playlist* playlist, const PlaylistItemList& new_items); + private: + int column_; + Qt::SortOrder order_; +}; - void undo(); - void redo(); +class ShuffleItems : public ReOrderItems { + public: + ShuffleItems(Playlist* playlist, const PlaylistItemList& new_items); +}; +} // namespace - private: - PlaylistItemList old_items_; - PlaylistItemList new_items_; - }; - - class SortItems : public ReOrderItems { - public: - SortItems(Playlist* playlist, int column, Qt::SortOrder order, - const PlaylistItemList& new_items); - - private: - int column_; - Qt::SortOrder order_; - }; - - class ShuffleItems : public ReOrderItems { - public: - ShuffleItems(Playlist* playlist, const PlaylistItemList& new_items); - }; -} //namespace - -#endif // PLAYLISTUNDOCOMMANDS_H +#endif // PLAYLISTUNDOCOMMANDS_H diff --git a/src/playlist/playlistview.cpp b/src/playlist/playlistview.cpp index b29b35b61..5d459c272 100644 --- a/src/playlist/playlistview.cpp +++ b/src/playlist/playlistview.cpp @@ -43,38 +43,40 @@ #include #ifdef HAVE_MOODBAR -# include "moodbar/moodbaritemdelegate.h" +#include "moodbar/moodbaritemdelegate.h" #endif const int PlaylistView::kStateVersion = 6; const int PlaylistView::kGlowIntensitySteps = 24; -const int PlaylistView::kAutoscrollGraceTimeout = 30; // seconds +const int PlaylistView::kAutoscrollGraceTimeout = 30; // seconds const int PlaylistView::kDropIndicatorWidth = 2; const int PlaylistView::kDropIndicatorGradientWidth = 5; -const char* PlaylistView::kSettingBackgroundImageType = "playlistview_background_type"; -const char* PlaylistView::kSettingBackgroundImageFilename = "playlistview_background_image_file"; +const char* PlaylistView::kSettingBackgroundImageType = + "playlistview_background_type"; +const char* PlaylistView::kSettingBackgroundImageFilename = + "playlistview_background_image_file"; const int PlaylistView::kDefaultBlurRadius = 0; const int PlaylistView::kDefaultOpacityLevel = 40; - PlaylistProxyStyle::PlaylistProxyStyle(QStyle* base) - : QProxyStyle(base), - cleanlooks_(new QCleanlooksStyle){ -} + : QProxyStyle(base), cleanlooks_(new QCleanlooksStyle) {} -void PlaylistProxyStyle::drawControl( - ControlElement element, const QStyleOption* option, QPainter* painter, - const QWidget* widget) const { +void PlaylistProxyStyle::drawControl(ControlElement element, + const QStyleOption* option, + QPainter* painter, + const QWidget* widget) const { if (element == CE_Header) { - const QStyleOptionHeader* header_option = qstyleoption_cast(option); + const QStyleOptionHeader* header_option = + qstyleoption_cast(option); const QRect& rect = header_option->rect; const QString& text = header_option->text; const QFontMetrics& font_metrics = header_option->fontMetrics; // spaces added to make transition less abrupt if (rect.width() < font_metrics.width(text + " ")) { - const Playlist::Column column = static_cast(header_option->section); + const Playlist::Column column = + static_cast(header_option->section); QStyleOptionHeader new_option(*header_option); new_option.text = Playlist::abbreviated_column_name(column); QProxyStyle::drawControl(element, &new_option, painter, widget); @@ -88,7 +90,10 @@ void PlaylistProxyStyle::drawControl( QProxyStyle::drawControl(element, option, painter, widget); } -void PlaylistProxyStyle::drawPrimitive(PrimitiveElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const { +void PlaylistProxyStyle::drawPrimitive(PrimitiveElement element, + const QStyleOption* option, + QPainter* painter, + const QWidget* widget) const { if (element == QStyle::PE_PanelItemViewRow || element == QStyle::PE_PanelItemViewItem) cleanlooks_->drawPrimitive(element, option, painter, widget); @@ -96,57 +101,62 @@ void PlaylistProxyStyle::drawPrimitive(PrimitiveElement element, const QStyleOpt QProxyStyle::drawPrimitive(element, option, painter, widget); } - -PlaylistView::PlaylistView(QWidget *parent) - : QTreeView(parent), - app_(nullptr), - style_(new PlaylistProxyStyle(style())), - playlist_(nullptr), - header_(new PlaylistHeader(Qt::Horizontal, this, this)), - setting_initial_header_layout_(false), - upgrading_from_qheaderview_(false), - read_only_settings_(true), - upgrading_from_version_(-1), - background_image_type_(Default), - previous_background_image_opacity_(0.0), - fade_animation_(new QTimeLine(1000, this)), - last_height_(-1), - last_width_(-1), - force_background_redraw_(false), - glow_enabled_(true), - currently_glowing_(false), - glow_intensity_step_(0), - rating_delegate_(nullptr), - inhibit_autoscroll_timer_(new QTimer(this)), - inhibit_autoscroll_(false), - currently_autoscrolling_(false), - row_height_(-1), - currenttrack_play_(":currenttrack_play.png"), - currenttrack_pause_(":currenttrack_pause.png"), - cached_current_row_row_(-1), - drop_indicator_row_(-1), - drag_over_(false), - dynamic_controls_(new DynamicPlaylistControls(this)) -{ +PlaylistView::PlaylistView(QWidget* parent) + : QTreeView(parent), + app_(nullptr), + style_(new PlaylistProxyStyle(style())), + playlist_(nullptr), + header_(new PlaylistHeader(Qt::Horizontal, this, this)), + setting_initial_header_layout_(false), + upgrading_from_qheaderview_(false), + read_only_settings_(true), + upgrading_from_version_(-1), + background_image_type_(Default), + previous_background_image_opacity_(0.0), + fade_animation_(new QTimeLine(1000, this)), + last_height_(-1), + last_width_(-1), + force_background_redraw_(false), + glow_enabled_(true), + currently_glowing_(false), + glow_intensity_step_(0), + rating_delegate_(nullptr), + inhibit_autoscroll_timer_(new QTimer(this)), + inhibit_autoscroll_(false), + currently_autoscrolling_(false), + row_height_(-1), + currenttrack_play_(":currenttrack_play.png"), + currenttrack_pause_(":currenttrack_pause.png"), + cached_current_row_row_(-1), + drop_indicator_row_(-1), + drag_over_(false), + dynamic_controls_(new DynamicPlaylistControls(this)) { setHeader(header_); header_->setMovable(true); setStyle(style_); setMouseTracking(true); - connect(header_, SIGNAL(sectionResized(int,int,int)), SLOT(SaveGeometry())); - connect(header_, SIGNAL(sectionMoved(int,int,int)), SLOT(SaveGeometry())); - connect(header_, SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), SLOT(SaveGeometry())); - connect(header_, SIGNAL(SectionVisibilityChanged(int,bool)), SLOT(SaveGeometry())); - connect(header_, SIGNAL(sectionResized(int,int,int)), SLOT(InvalidateCachedCurrentPixmap())); - connect(header_, SIGNAL(sectionMoved(int,int,int)), SLOT(InvalidateCachedCurrentPixmap())); - connect(header_, SIGNAL(SectionVisibilityChanged(int,bool)), SLOT(InvalidateCachedCurrentPixmap())); + connect(header_, SIGNAL(sectionResized(int, int, int)), SLOT(SaveGeometry())); + connect(header_, SIGNAL(sectionMoved(int, int, int)), SLOT(SaveGeometry())); + connect(header_, SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), + SLOT(SaveGeometry())); + connect(header_, SIGNAL(SectionVisibilityChanged(int, bool)), + SLOT(SaveGeometry())); + connect(header_, SIGNAL(sectionResized(int, int, int)), + SLOT(InvalidateCachedCurrentPixmap())); + connect(header_, SIGNAL(sectionMoved(int, int, int)), + SLOT(InvalidateCachedCurrentPixmap())); + connect(header_, SIGNAL(SectionVisibilityChanged(int, bool)), + SLOT(InvalidateCachedCurrentPixmap())); connect(header_, SIGNAL(StretchEnabledChanged(bool)), SLOT(SaveSettings())); - connect(header_, SIGNAL(StretchEnabledChanged(bool)), SLOT(StretchChanged(bool))); + connect(header_, SIGNAL(StretchEnabledChanged(bool)), + SLOT(StretchChanged(bool))); connect(header_, SIGNAL(MouseEntered()), SLOT(RatingHoverOut())); inhibit_autoscroll_timer_->setInterval(kAutoscrollGraceTimeout * 1000); inhibit_autoscroll_timer_->setSingleShot(true); - connect(inhibit_autoscroll_timer_, SIGNAL(timeout()), SLOT(InhibitAutoscrollTimeout())); + connect(inhibit_autoscroll_timer_, SIGNAL(timeout()), + SLOT(InhibitAutoscrollTimeout())); horizontalScrollBar()->installEventFilter(this); verticalScrollBar()->installEventFilter(this); @@ -161,11 +171,12 @@ PlaylistView::PlaylistView(QWidget *parent) setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); #endif // For fading - connect(fade_animation_, SIGNAL(valueChanged(qreal)), SLOT(FadePreviousBackgroundImage(qreal))); - fade_animation_->setDirection(QTimeLine::Backward); // 1.0 -> 0.0 + connect(fade_animation_, SIGNAL(valueChanged(qreal)), + SLOT(FadePreviousBackgroundImage(qreal))); + fade_animation_->setDirection(QTimeLine::Backward); // 1.0 -> 0.0 } -void PlaylistView::SetApplication(Application *app) { +void PlaylistView::SetApplication(Application* app) { Q_ASSERT(app); app_ = app; connect(app_->current_art_loader(), @@ -182,38 +193,57 @@ void PlaylistView::SetItemDelegates(LibraryBackend* backend) { setItemDelegate(new PlaylistDelegateBase(this)); setItemDelegateForColumn(Playlist::Column_Title, new TextItemDelegate(this)); - setItemDelegateForColumn(Playlist::Column_Album, + setItemDelegateForColumn( + Playlist::Column_Album, new TagCompletionItemDelegate(this, backend, Playlist::Column_Album)); - setItemDelegateForColumn(Playlist::Column_Artist, + setItemDelegateForColumn( + Playlist::Column_Artist, new TagCompletionItemDelegate(this, backend, Playlist::Column_Artist)); setItemDelegateForColumn(Playlist::Column_AlbumArtist, - new TagCompletionItemDelegate(this, backend, Playlist::Column_AlbumArtist)); - setItemDelegateForColumn(Playlist::Column_Genre, + new TagCompletionItemDelegate( + this, backend, Playlist::Column_AlbumArtist)); + setItemDelegateForColumn( + Playlist::Column_Genre, new TagCompletionItemDelegate(this, backend, Playlist::Column_Genre)); - setItemDelegateForColumn(Playlist::Column_Composer, + setItemDelegateForColumn( + Playlist::Column_Composer, new TagCompletionItemDelegate(this, backend, Playlist::Column_Composer)); - setItemDelegateForColumn(Playlist::Column_Performer, + setItemDelegateForColumn( + Playlist::Column_Performer, new TagCompletionItemDelegate(this, backend, Playlist::Column_Performer)); - setItemDelegateForColumn(Playlist::Column_Grouping, + setItemDelegateForColumn( + Playlist::Column_Grouping, new TagCompletionItemDelegate(this, backend, Playlist::Column_Grouping)); - setItemDelegateForColumn(Playlist::Column_Length, new LengthItemDelegate(this)); - setItemDelegateForColumn(Playlist::Column_Filesize, new SizeItemDelegate(this)); - setItemDelegateForColumn(Playlist::Column_Filetype, new FileTypeItemDelegate(this)); - setItemDelegateForColumn(Playlist::Column_DateCreated, new DateItemDelegate(this)); - setItemDelegateForColumn(Playlist::Column_DateModified, new DateItemDelegate(this)); - setItemDelegateForColumn(Playlist::Column_BPM, new PlaylistDelegateBase(this, tr("bpm"))); - setItemDelegateForColumn(Playlist::Column_Samplerate, new PlaylistDelegateBase(this, ("Hz"))); - setItemDelegateForColumn(Playlist::Column_Bitrate, new PlaylistDelegateBase(this, tr("kbps"))); - setItemDelegateForColumn(Playlist::Column_Filename, new NativeSeparatorsDelegate(this)); + setItemDelegateForColumn(Playlist::Column_Length, + new LengthItemDelegate(this)); + setItemDelegateForColumn(Playlist::Column_Filesize, + new SizeItemDelegate(this)); + setItemDelegateForColumn(Playlist::Column_Filetype, + new FileTypeItemDelegate(this)); + setItemDelegateForColumn(Playlist::Column_DateCreated, + new DateItemDelegate(this)); + setItemDelegateForColumn(Playlist::Column_DateModified, + new DateItemDelegate(this)); + setItemDelegateForColumn(Playlist::Column_BPM, + new PlaylistDelegateBase(this, tr("bpm"))); + setItemDelegateForColumn(Playlist::Column_Samplerate, + new PlaylistDelegateBase(this, ("Hz"))); + setItemDelegateForColumn(Playlist::Column_Bitrate, + new PlaylistDelegateBase(this, tr("kbps"))); + setItemDelegateForColumn(Playlist::Column_Filename, + new NativeSeparatorsDelegate(this)); setItemDelegateForColumn(Playlist::Column_Rating, rating_delegate_); - setItemDelegateForColumn(Playlist::Column_LastPlayed, new LastPlayedItemDelegate(this)); + setItemDelegateForColumn(Playlist::Column_LastPlayed, + new LastPlayedItemDelegate(this)); #ifdef HAVE_MOODBAR - setItemDelegateForColumn(Playlist::Column_Mood, new MoodbarItemDelegate(app_, this, this)); + setItemDelegateForColumn(Playlist::Column_Mood, + new MoodbarItemDelegate(app_, this, this)); #endif if (app_ && app_->player()) { - setItemDelegateForColumn(Playlist::Column_Source, new SongSourceDelegate(this, app_->player())); + setItemDelegateForColumn(Playlist::Column_Source, + new SongSourceDelegate(this, app_->player())); } else { header_->HideSection(Playlist::Column_Source); } @@ -221,18 +251,18 @@ void PlaylistView::SetItemDelegates(LibraryBackend* backend) { void PlaylistView::SetPlaylist(Playlist* playlist) { if (playlist_) { - disconnect(playlist_, SIGNAL(CurrentSongChanged(Song)), - this, SLOT(MaybeAutoscroll())); - disconnect(playlist_, SIGNAL(DynamicModeChanged(bool)), - this, SLOT(DynamicModeChanged(bool))); + disconnect(playlist_, SIGNAL(CurrentSongChanged(Song)), this, + SLOT(MaybeAutoscroll())); + disconnect(playlist_, SIGNAL(DynamicModeChanged(bool)), this, + SLOT(DynamicModeChanged(bool))); disconnect(playlist_, SIGNAL(destroyed()), this, SLOT(PlaylistDestroyed())); - disconnect(dynamic_controls_, SIGNAL(Expand()), - playlist_, SLOT(ExpandDynamicPlaylist())); - disconnect(dynamic_controls_, SIGNAL(Repopulate()), - playlist_, SLOT(RepopulateDynamicPlaylist())); - disconnect(dynamic_controls_, SIGNAL(TurnOff()), - playlist_, SLOT(TurnOffDynamicPlaylist())); + disconnect(dynamic_controls_, SIGNAL(Expand()), playlist_, + SLOT(ExpandDynamicPlaylist())); + disconnect(dynamic_controls_, SIGNAL(Repopulate()), playlist_, + SLOT(RepopulateDynamicPlaylist())); + disconnect(dynamic_controls_, SIGNAL(TurnOff()), playlist_, + SLOT(TurnOffDynamicPlaylist())); } playlist_ = playlist; @@ -245,19 +275,23 @@ void PlaylistView::SetPlaylist(Playlist* playlist) { connect(playlist_, SIGNAL(RestoreFinished()), SLOT(JumpToLastPlayedTrack())); connect(playlist_, SIGNAL(CurrentSongChanged(Song)), SLOT(MaybeAutoscroll())); - connect(playlist_, SIGNAL(DynamicModeChanged(bool)), SLOT(DynamicModeChanged(bool))); + connect(playlist_, SIGNAL(DynamicModeChanged(bool)), + SLOT(DynamicModeChanged(bool))); connect(playlist_, SIGNAL(destroyed()), SLOT(PlaylistDestroyed())); - connect(dynamic_controls_, SIGNAL(Expand()), playlist_, SLOT(ExpandDynamicPlaylist())); - connect(dynamic_controls_, SIGNAL(Repopulate()), playlist_, SLOT(RepopulateDynamicPlaylist())); - connect(dynamic_controls_, SIGNAL(TurnOff()), playlist_, SLOT(TurnOffDynamicPlaylist())); + connect(dynamic_controls_, SIGNAL(Expand()), playlist_, + SLOT(ExpandDynamicPlaylist())); + connect(dynamic_controls_, SIGNAL(Repopulate()), playlist_, + SLOT(RepopulateDynamicPlaylist())); + connect(dynamic_controls_, SIGNAL(TurnOff()), playlist_, + SLOT(TurnOffDynamicPlaylist())); } -void PlaylistView::setModel(QAbstractItemModel *m) { +void PlaylistView::setModel(QAbstractItemModel* m) { if (model()) { - disconnect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), - this, SLOT(InvalidateCachedCurrentPixmap())); - disconnect(model(), SIGNAL(layoutAboutToBeChanged()), - this, SLOT(RatingHoverOut())); + disconnect(model(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, + SLOT(InvalidateCachedCurrentPixmap())); + disconnect(model(), SIGNAL(layoutAboutToBeChanged()), this, + SLOT(RatingHoverOut())); // When changing the model, always invalidate the current pixmap. // If a remote client uses "stop after", without invaliding the stop // mark would not appear. @@ -266,10 +300,10 @@ void PlaylistView::setModel(QAbstractItemModel *m) { QTreeView::setModel(m); - connect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), - this, SLOT(InvalidateCachedCurrentPixmap())); - connect(model(), SIGNAL(layoutAboutToBeChanged()), - this, SLOT(RatingHoverOut())); + connect(model(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, + SLOT(InvalidateCachedCurrentPixmap())); + connect(model(), SIGNAL(layoutAboutToBeChanged()), this, + SLOT(RatingHoverOut())); } void PlaylistView::LoadGeometry() { @@ -335,7 +369,7 @@ void PlaylistView::LoadGeometry() { // Make sure at least one column is visible bool all_hidden = true; - for (int i=0 ; icount() ; ++i) { + for (int i = 0; i < header_->count(); ++i) { if (!header_->isSectionHidden(i) && header_->sectionSize(i) > 0) { all_hidden = false; break; @@ -347,8 +381,7 @@ void PlaylistView::LoadGeometry() { } void PlaylistView::SaveGeometry() { - if (read_only_settings_) - return; + if (read_only_settings_) return; QSettings settings; settings.beginGroup(Playlist::kSettingsGroup); @@ -375,11 +408,11 @@ QList PlaylistView::LoadBarPixmap(const QString& filename) { // Animation steps QList ret; - for(int i=0 ; i(this)->current_paint_region_ = QRegion(); } -void PlaylistView::drawRow(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { +void PlaylistView::drawRow(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { QStyleOptionViewItemV4 opt(option); bool is_current = index.data(Playlist::Role_IsCurrent).toBool(); @@ -406,7 +441,7 @@ void PlaylistView::drawRow(QPainter* painter, const QStyleOptionViewItem& option int step = glow_intensity_step_; if (step >= kGlowIntensitySteps) - step = 2*(kGlowIntensitySteps-1) - step + 1; + step = 2 * (kGlowIntensitySteps - 1) - step + 1; int row_height = opt.rect.height(); if (row_height != row_height_) { @@ -425,7 +460,9 @@ void PlaylistView::drawRow(QPainter* painter, const QStyleOptionViewItem& option // Draw the bar painter->drawPixmap(opt.rect.topLeft(), currenttrack_bar_left_[step]); - painter->drawPixmap(opt.rect.topRight() - currenttrack_bar_right_[0].rect().topRight(), currenttrack_bar_right_[step]); + painter->drawPixmap( + opt.rect.topRight() - currenttrack_bar_right_[0].rect().topRight(), + currenttrack_bar_right_[step]); painter->drawPixmap(middle, currenttrack_bar_mid_[step]); // Draw the play icon @@ -435,11 +472,12 @@ void PlaylistView::drawRow(QPainter* painter, const QStyleOptionViewItem& option is_paused ? currenttrack_pause_ : currenttrack_play_); // Set the font - opt.palette.setColor(QPalette::Text, QApplication::palette().color(QPalette::HighlightedText)); + opt.palette.setColor(QPalette::Text, QApplication::palette().color( + QPalette::HighlightedText)); opt.palette.setColor(QPalette::Highlight, Qt::transparent); opt.palette.setColor(QPalette::AlternateBase, Qt::transparent); opt.font.setItalic(true); - opt.decorationSize = QSize(20,20); + opt.decorationSize = QSize(20, 20); // Draw the actual row data on top. We cache this, because it's fairly // expensive (1-2ms), and we do it many times per second. @@ -457,7 +495,8 @@ void PlaylistView::drawRow(QPainter* painter, const QStyleOptionViewItem& option painter->drawPixmap(opt.rect, cached_current_row_); } else { if (whole_region) { - const_cast(this)->UpdateCachedCurrentRowPixmap(opt, index); + const_cast(this) + ->UpdateCachedCurrentRowPixmap(opt, index); painter->drawPixmap(opt.rect, cached_current_row_); } else { QTreeView::drawRow(painter, opt, index); @@ -487,8 +526,7 @@ void PlaylistView::InvalidateCachedCurrentPixmap() { void PlaylistView::timerEvent(QTimerEvent* event) { QTreeView::timerEvent(event); - if (event->timerId() == glow_timer_.timerId()) - GlowIntensityChanged(); + if (event->timerId() == glow_timer_.timerId()) GlowIntensityChanged(); } void PlaylistView::GlowIntensityChanged() { @@ -509,9 +547,7 @@ void PlaylistView::StartGlowing() { glow_timer_.start(1500 / kGlowIntensitySteps, this); } -void PlaylistView::hideEvent(QHideEvent*) { - glow_timer_.stop(); -} +void PlaylistView::hideEvent(QHideEvent*) { glow_timer_.stop(); } void PlaylistView::showEvent(QShowEvent*) { if (currently_glowing_ && glow_enabled_) @@ -519,7 +555,8 @@ void PlaylistView::showEvent(QShowEvent*) { MaybeAutoscroll(); } -bool CompareSelectionRanges(const QItemSelectionRange& a, const QItemSelectionRange& b) { +bool CompareSelectionRanges(const QItemSelectionRange& a, + const QItemSelectionRange& b) { return b.bottom() < a.bottom(); } @@ -536,26 +573,28 @@ void PlaylistView::keyPressEvent(QKeyEvent* event) { #endif } else if (event == QKeySequence::Copy) { CopyCurrentSongToClipboard(); - } else if (event->key() == Qt::Key_Enter || - event->key() == Qt::Key_Return) { - if (currentIndex().isValid()) - emit PlayItem(currentIndex()); + } else if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { + if (currentIndex().isValid()) emit PlayItem(currentIndex()); event->accept(); - } else if(event->modifiers() != Qt::ControlModifier //Ctrl+Space selects the item - && event->key() == Qt::Key_Space) { + } else if (event->modifiers() != + Qt::ControlModifier // Ctrl+Space selects the item + && + event->key() == Qt::Key_Space) { emit PlayPause(); event->accept(); - } else if(event->key() == Qt::Key_Left) { + } else if (event->key() == Qt::Key_Left) { emit SeekTrack(-1); event->accept(); - } else if(event->key() == Qt::Key_Right) { + } else if (event->key() == Qt::Key_Right) { emit SeekTrack(1); event->accept(); - } else if(event->modifiers() == Qt::NoModifier // No modifier keys currently pressed... - // ... and key pressed is something related to text - && ( (event->key() >= Qt::Key_A && event->key() <= Qt::Key_Z) - || event->key() == Qt::Key_Backspace - || event->key() == Qt::Key_Escape)) { + } else if (event->modifiers() == + Qt::NoModifier // No modifier keys currently pressed... + // ... and key pressed is something related to text + && + ((event->key() >= Qt::Key_A && event->key() <= Qt::Key_Z) || + event->key() == Qt::Key_Backspace || + event->key() == Qt::Key_Escape)) { emit FocusOnFilterSignal(event); event->accept(); } else { @@ -583,7 +622,7 @@ void PlaylistView::RemoveSelected() { // Store the last selected row, which is the first in the list int last_row = selection.first().bottom(); - foreach (const QItemSelectionRange& range, selection) { + foreach(const QItemSelectionRange & range, selection) { rows_removed += range.height(); model()->removeRows(range.top(), range.height(), range.parent()); } @@ -592,31 +631,35 @@ void PlaylistView::RemoveSelected() { // Index of the first column for the row to select QModelIndex new_index = model()->index(new_row, 0); - // Select the new current item, we want always the item after the last selected + // Select the new current item, we want always the item after the last + // selected if (new_index.isValid()) { // Update visual selection with the entire row - selectionModel()->select(QItemSelection(new_index, model()->index(new_row, model()->columnCount()-1)), - QItemSelectionModel::Select); + selectionModel()->select( + QItemSelection(new_index, + model()->index(new_row, model()->columnCount() - 1)), + QItemSelectionModel::Select); // Update keyboard selected row, if it's not the first row if (new_row != 0) - keyPressEvent(new QKeyEvent(QEvent::KeyPress, Qt::Key_Down, Qt::NoModifier)); + keyPressEvent( + new QKeyEvent(QEvent::KeyPress, Qt::Key_Down, Qt::NoModifier)); } else { // We're removing the last item, select the new last row - selectionModel()->select(QItemSelection(model()->index(model()->rowCount()-1, 0), - model()->index(model()->rowCount()-1, model()->columnCount()-1)), - QItemSelectionModel::Select); + selectionModel()->select( + QItemSelection(model()->index(model()->rowCount() - 1, 0), + model()->index(model()->rowCount() - 1, + model()->columnCount() - 1)), + QItemSelectionModel::Select); } } QList PlaylistView::GetEditableColumns() { QList columns; QHeaderView* h = header(); - for (int col=0; colcount(); col++) { - if (h->isSectionHidden(col)) - continue; + for (int col = 0; col < h->count(); col++) { + if (h->isSectionHidden(col)) continue; QModelIndex index = model()->index(0, col); - if (index.flags() & Qt::ItemIsEditable) - columns << h->visualIndex(col); + if (index.flags() & Qt::ItemIsEditable) columns << h->visualIndex(col); } qSort(columns); return columns; @@ -627,10 +670,10 @@ QModelIndex PlaylistView::NextEditableIndex(const QModelIndex& current) { QHeaderView* h = header(); int index = columns.indexOf(h->visualIndex(current.column())); - if(index+1 >= columns.size()) - return model()->index(current.row()+1, h->logicalIndex(columns.first())); + if (index + 1 >= columns.size()) + return model()->index(current.row() + 1, h->logicalIndex(columns.first())); - return model()->index(current.row(), h->logicalIndex(columns[index+1])); + return model()->index(current.row(), h->logicalIndex(columns[index + 1])); } QModelIndex PlaylistView::PrevEditableIndex(const QModelIndex& current) { @@ -638,13 +681,14 @@ QModelIndex PlaylistView::PrevEditableIndex(const QModelIndex& current) { QHeaderView* h = header(); int index = columns.indexOf(h->visualIndex(current.column())); - if(index-1 < 0) - return model()->index(current.row()-1, h->logicalIndex(columns.last())); + if (index - 1 < 0) + return model()->index(current.row() - 1, h->logicalIndex(columns.last())); - return model()->index(current.row(), h->logicalIndex(columns[index-1])); + return model()->index(current.row(), h->logicalIndex(columns[index - 1])); } -void PlaylistView::closeEditor(QWidget* editor, QAbstractItemDelegate::EndEditHint hint) { +void PlaylistView::closeEditor(QWidget* editor, + QAbstractItemDelegate::EndEditHint hint) { if (hint == QAbstractItemDelegate::NoHint) { QTreeView::closeEditor(editor, QAbstractItemDelegate::SubmitModelCache); } else if (hint == QAbstractItemDelegate::EditNextItem || @@ -698,7 +742,7 @@ void PlaylistView::RatingHoverIn(const QModelIndex& index, const QPoint& pos) { update(index); update(old_index); - foreach (const QModelIndex& index, selectedIndexes()) { + foreach(const QModelIndex & index, selectedIndexes()) { if (index.column() == Playlist::Column_Rating) { update(index); } @@ -720,7 +764,7 @@ void PlaylistView::RatingHoverOut() { setCursor(QCursor()); update(old_index); - foreach (const QModelIndex& index, selectedIndexes()) { + foreach(const QModelIndex & index, selectedIndexes()) { if (index.column() == Playlist::Column_Rating) { update(index); } @@ -741,14 +785,15 @@ void PlaylistView::mousePressEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton && index.isValid() && index.data(Playlist::Role_CanSetRating).toBool()) { // Calculate which star was clicked - double new_rating = RatingPainter::RatingForPos( - event->pos(), visualRect(index)); + double new_rating = + RatingPainter::RatingForPos(event->pos(), visualRect(index)); if (selectedIndexes().contains(index)) { // Update all the selected items - foreach (const QModelIndex& index, selectedIndexes()) { + foreach(const QModelIndex & index, selectedIndexes()) { if (index.data(Playlist::Role_CanSetRating).toBool()) { - playlist_->RateSong(playlist_->proxy()->mapToSource(index), new_rating); + playlist_->RateSong(playlist_->proxy()->mapToSource(index), + new_rating); } } } else { @@ -785,23 +830,21 @@ void PlaylistView::InhibitAutoscrollTimeout() { } void PlaylistView::MaybeAutoscroll() { - if (!inhibit_autoscroll_) - JumpToCurrentlyPlayingTrack(); + if (!inhibit_autoscroll_) JumpToCurrentlyPlayingTrack(); } void PlaylistView::JumpToCurrentlyPlayingTrack() { Q_ASSERT(playlist_); - // Usage of the "Jump to the currently playing track" action shall enable autoscroll + // Usage of the "Jump to the currently playing track" action shall enable + // autoscroll inhibit_autoscroll_ = false; - if (playlist_->current_row() == -1) - return; + if (playlist_->current_row() == -1) return; QModelIndex current = playlist_->proxy()->mapFromSource( playlist_->index(playlist_->current_row(), 0)); - if (!current.isValid()) - return; + if (!current.isValid()) return; currently_autoscrolling_ = true; @@ -814,13 +857,11 @@ void PlaylistView::JumpToCurrentlyPlayingTrack() { void PlaylistView::JumpToLastPlayedTrack() { Q_ASSERT(playlist_); - if (playlist_->last_played_row() == -1) - return; + if (playlist_->last_played_row() == -1) return; QModelIndex last_played = playlist_->proxy()->mapFromSource( playlist_->index(playlist_->last_played_row(), 0)); - if (!last_played.isValid()) - return; + if (!last_played.isValid()) return; // Select last played song last_current_item_ = last_played; @@ -844,26 +885,26 @@ void PlaylistView::paintEvent(QPaintEvent* event) { // dragLeaveEvent, dropEvent and scrollContentsBy. // Draw background - if (background_image_type_ == Custom || background_image_type_ == AlbumCover) { + if (background_image_type_ == Custom || + background_image_type_ == AlbumCover) { if (!background_image_.isNull() || !previous_background_image_.isNull()) { QPainter background_painter(viewport()); // Check if we should recompute the background image - if (height() != last_height_ || width() != last_width_ - || force_background_redraw_) { + if (height() != last_height_ || width() != last_width_ || + force_background_redraw_) { if (background_image_.isNull()) { cached_scaled_background_image_ = QPixmap(); } else { - cached_scaled_background_image_ = QPixmap::fromImage( - background_image_.scaled( - width(), height(), - Qt::KeepAspectRatioByExpanding, + cached_scaled_background_image_ = + QPixmap::fromImage(background_image_.scaled( + width(), height(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)); } last_height_ = height(); - last_width_ = width(); + last_width_ = width(); force_background_redraw_ = false; } @@ -871,18 +912,21 @@ void PlaylistView::paintEvent(QPaintEvent* event) { if (!cached_scaled_background_image_.isNull()) { // Set opactiy only if needed, as this deactivate hardware acceleration if (!qFuzzyCompare(previous_background_image_opacity_, qreal(0.0))) { - background_painter.setOpacity(1.0 - previous_background_image_opacity_); + background_painter.setOpacity(1.0 - + previous_background_image_opacity_); } - background_painter.drawPixmap((width() - cached_scaled_background_image_.width()) / 2, - (height() - cached_scaled_background_image_.height()) / 2, - cached_scaled_background_image_); + background_painter.drawPixmap( + (width() - cached_scaled_background_image_.width()) / 2, + (height() - cached_scaled_background_image_.height()) / 2, + cached_scaled_background_image_); } // Draw the previous background image if we're fading if (!previous_background_image_.isNull()) { background_painter.setOpacity(previous_background_image_opacity_); - background_painter.drawPixmap((width() - previous_background_image_.width()) / 2, - (height() - previous_background_image_.height()) / 2, - previous_background_image_); + background_painter.drawPixmap( + (width() - previous_background_image_.width()) / 2, + (height() - previous_background_image_.height()) / 2, + previous_background_image_); } } } @@ -911,7 +955,7 @@ void PlaylistView::paintEvent(QPaintEvent* event) { int drop_pos = -1; switch (dropIndicatorPosition()) { case QAbstractItemView::OnItem: - return; // Don't draw anything + return; // Don't draw anything case QAbstractItemView::AboveItem: drop_pos = visualRect(drop_index).top(); @@ -925,8 +969,8 @@ void PlaylistView::paintEvent(QPaintEvent* event) { if (model()->rowCount() == 0) drop_pos = 1; else - drop_pos = 1 + visualRect( - model()->index(model()->rowCount() - 1, first_column)).bottom(); + drop_pos = 1 + visualRect(model()->index(model()->rowCount() - 1, + first_column)).bottom(); break; } @@ -944,37 +988,35 @@ void PlaylistView::paintEvent(QPaintEvent* event) { gradient.setColorAt(1.0, shadow_fadeout_color); QPen gradient_pen(QBrush(gradient), kDropIndicatorGradientWidth * 2); p.setPen(gradient_pen); - p.drawLine(QPoint(0, drop_pos), - QPoint(width(), drop_pos)); + p.drawLine(QPoint(0, drop_pos), QPoint(width(), drop_pos)); // Now draw the line on top QPen line_pen(line_color, kDropIndicatorWidth); p.setPen(line_pen); - p.drawLine(QPoint(0, drop_pos), - QPoint(width(), drop_pos)); + p.drawLine(QPoint(0, drop_pos), QPoint(width(), drop_pos)); } -void PlaylistView::dragMoveEvent(QDragMoveEvent *event) { +void PlaylistView::dragMoveEvent(QDragMoveEvent* event) { QTreeView::dragMoveEvent(event); QModelIndex index(indexAt(event->pos())); drop_indicator_row_ = index.isValid() ? index.row() : 0; } -void PlaylistView::dragEnterEvent(QDragEnterEvent *event) { +void PlaylistView::dragEnterEvent(QDragEnterEvent* event) { QTreeView::dragEnterEvent(event); cached_tree_ = QPixmap(); drag_over_ = true; } -void PlaylistView::dragLeaveEvent(QDragLeaveEvent *event) { +void PlaylistView::dragLeaveEvent(QDragLeaveEvent* event) { QTreeView::dragLeaveEvent(event); cached_tree_ = QPixmap(); drag_over_ = false; drop_indicator_row_ = -1; } -void PlaylistView::dropEvent(QDropEvent *event) { +void PlaylistView::dropEvent(QDropEvent* event) { QTreeView::dropEvent(event); cached_tree_ = QPixmap(); drop_indicator_row_ = -1; @@ -996,10 +1038,8 @@ void PlaylistView::ReloadSettings() { upgrading_from_qheaderview_ = false; } - if (currently_glowing_ && glow_enabled_ && isVisible()) - StartGlowing(); - if (!glow_enabled_) - StopGlowing(); + if (currently_glowing_ && glow_enabled_ && isVisible()) StartGlowing(); + if (!glow_enabled_) StopGlowing(); if (setting_initial_header_layout_) { header_->SetColumnWidth(Playlist::Column_Length, 0.06); @@ -1022,13 +1062,15 @@ void PlaylistView::ReloadSettings() { emit ColumnAlignmentChanged(column_alignment_); // Background: - QVariant q_playlistview_background_type = s.value(kSettingBackgroundImageType); + QVariant q_playlistview_background_type = + s.value(kSettingBackgroundImageType); BackgroundImageType background_type(Default); // bg_enabled should also be checked for backward compatibility (in releases // <= 1.0, there was just a boolean to activate/deactivate the background) QVariant bg_enabled = s.value("bg_enabled"); if (q_playlistview_background_type.isValid()) { - background_type = static_cast(q_playlistview_background_type.toInt()); + background_type = static_cast( + q_playlistview_background_type.toInt()); } else if (bg_enabled.isValid()) { if (bg_enabled.toBool()) { background_type = Default; @@ -1036,7 +1078,8 @@ void PlaylistView::ReloadSettings() { background_type = None; } } - QString background_image_filename = s.value(kSettingBackgroundImageFilename).toString(); + QString background_image_filename = + s.value(kSettingBackgroundImageFilename).toString(); int blur_radius = s.value("blur_radius", kDefaultBlurRadius).toInt(); int opacity_level = s.value("opacity_level", kDefaultOpacityLevel).toInt(); // Check if background properties have changed. @@ -1046,8 +1089,7 @@ void PlaylistView::ReloadSettings() { // "force_background_redraw". if (background_image_filename != background_image_filename_ || background_type != background_image_type_ || - blur_radius_ != blur_radius || - opacity_level_ != opacity_level) { + blur_radius_ != blur_radius || opacity_level_ != opacity_level) { // Store background properties background_image_type_ = background_type; background_image_filename_ = background_image_filename; @@ -1066,15 +1108,15 @@ void PlaylistView::ReloadSettings() { cached_scaled_background_image_ = QPixmap(); previous_background_image_ = QPixmap(); } - setProperty("default_background_enabled", background_image_type_ == Default); + setProperty("default_background_enabled", + background_image_type_ == Default); emit BackgroundPropertyChanged(); force_background_redraw_ = true; } } void PlaylistView::SaveSettings() { - if (read_only_settings_) - return; + if (read_only_settings_) return; QSettings s; s.beginGroup(Playlist::kSettingsGroup); @@ -1084,7 +1126,8 @@ void PlaylistView::SaveSettings() { } void PlaylistView::StretchChanged(bool stretch) { - setHorizontalScrollBarPolicy(stretch ? Qt::ScrollBarAlwaysOff : Qt::ScrollBarAsNeeded); + setHorizontalScrollBarPolicy(stretch ? Qt::ScrollBarAlwaysOff + : Qt::ScrollBarAsNeeded); SaveGeometry(); } @@ -1127,31 +1170,29 @@ void PlaylistView::rowsInserted(const QModelIndex& parent, int start, int end) { if (at_end) { // If the rows were inserted at the end of the playlist then let's scroll // the view so the user can see. - scrollTo(model()->index(start, 0, parent), QAbstractItemView::PositionAtTop); + scrollTo(model()->index(start, 0, parent), + QAbstractItemView::PositionAtTop); } } ColumnAlignmentMap PlaylistView::DefaultColumnAlignment() { ColumnAlignmentMap ret; - ret[Playlist::Column_Length] = - ret[Playlist::Column_Track] = - ret[Playlist::Column_Disc] = - ret[Playlist::Column_Year] = - ret[Playlist::Column_BPM] = - ret[Playlist::Column_Bitrate] = - ret[Playlist::Column_Samplerate] = - ret[Playlist::Column_Filesize] = - ret[Playlist::Column_PlayCount] = - ret[Playlist::Column_SkipCount] = (Qt::AlignRight | Qt::AlignVCenter); - ret[Playlist::Column_Score] = (Qt::AlignCenter); + ret[Playlist::Column_Length] = ret[Playlist::Column_Track] = + ret[Playlist::Column_Disc] = ret[Playlist::Column_Year] = + ret[Playlist::Column_BPM] = ret[Playlist::Column_Bitrate] = + ret[Playlist::Column_Samplerate] = + ret[Playlist::Column_Filesize] = + ret[Playlist::Column_PlayCount] = + ret[Playlist::Column_SkipCount] = + (Qt::AlignRight | Qt::AlignVCenter); + ret[Playlist::Column_Score] = (Qt::AlignCenter); return ret; } void PlaylistView::SetColumnAlignment(int section, Qt::Alignment alignment) { - if (section < 0) - return; + if (section < 0) return; column_alignment_[section] = alignment; emit ColumnAlignmentChanged(column_alignment_); @@ -1166,21 +1207,23 @@ void PlaylistView::CopyCurrentSongToClipboard() const { // Get the display text of all visible columns. QStringList columns; - for (int i=0 ; icount() ; ++i) { + for (int i = 0; i < header()->count(); ++i) { if (header()->isSectionHidden(i)) { continue; } - const QVariant data = model()->data( - currentIndex().sibling(currentIndex().row(), i)); + const QVariant data = + model()->data(currentIndex().sibling(currentIndex().row(), i)); if (data.type() == QVariant::String) { columns << data.toString(); } } // Get the song's URL - const QUrl url = model()->data(currentIndex().sibling( - currentIndex().row(), Playlist::Column_Filename)).toUrl(); + const QUrl url = model() + ->data(currentIndex().sibling(currentIndex().row(), + Playlist::Column_Filename)) + .toUrl(); QMimeData* mime_data = new QMimeData; mime_data->setUrls(QList() << url); @@ -1189,11 +1232,9 @@ void PlaylistView::CopyCurrentSongToClipboard() const { QApplication::clipboard()->setMimeData(mime_data); } -void PlaylistView::CurrentSongChanged(const Song& song, - const QString& uri, +void PlaylistView::CurrentSongChanged(const Song& song, const QString& uri, const QImage& song_art) { - if (current_song_cover_art_ == song_art) - return; + if (current_song_cover_art_ == song_art) return; current_song_cover_art_ = song_art; if (background_image_type_ == AlbumCover) { @@ -1220,12 +1261,15 @@ void PlaylistView::set_background_image(const QImage& image) { if (!background_image_.isNull()) { // Apply opacity filter uchar* bits = background_image_.bits(); - for (int i = 0; i < background_image_.height() * background_image_.bytesPerLine(); i+=4) { - bits[i+3] = (opacity_level_ / 100.0) * 255; + for (int i = 0; + i < background_image_.height() * background_image_.bytesPerLine(); + i += 4) { + bits[i + 3] = (opacity_level_ / 100.0) * 255; } if (blur_radius_ != 0) { - QImage blurred(background_image_.size(), QImage::Format_ARGB32_Premultiplied); + QImage blurred(background_image_.size(), + QImage::Format_ARGB32_Premultiplied); blurred.fill(Qt::transparent); QPainter blur_painter(&blurred); qt_blurImage(&blur_painter, background_image_, blur_radius_, true, false); @@ -1265,8 +1309,7 @@ void PlaylistView::focusInEvent(QFocusEvent* event) { // only 1 item in the view it is now impossible to select that item without // using the mouse. const QModelIndex& current = selectionModel()->currentIndex(); - if (current.isValid() && - selectionModel()->selectedIndexes().isEmpty()) { + if (current.isValid() && selectionModel()->selectedIndexes().isEmpty()) { QItemSelection new_selection( current.sibling(current.row(), 0), current.sibling(current.row(), diff --git a/src/playlist/playlistview.h b/src/playlist/playlistview.h index 8ce39747c..df444053a 100644 --- a/src/playlist/playlistview.h +++ b/src/playlist/playlistview.h @@ -36,7 +36,6 @@ class RadioLoadingIndicator; class RatingItemDelegate; class QTimeLine; - // This proxy style works around a bug/feature introduced in Qt 4.7's QGtkStyle // that uses Gtk to paint row backgrounds, ignoring any custom brush or palette // the caller set in the QStyleOption. That breaks our currently playing track @@ -44,27 +43,21 @@ class QTimeLine; // This proxy style uses QCleanlooksStyle to paint the affected elements. // This class is used by the global search view as well. class PlaylistProxyStyle : public QProxyStyle { -public: + public: PlaylistProxyStyle(QStyle* base); void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const; void drawPrimitive(PrimitiveElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const; -private: + private: std::unique_ptr cleanlooks_; }; - class PlaylistView : public QTreeView { Q_OBJECT public: - enum BackgroundImageType { - Default, - None, - Custom, - AlbumCover - }; + enum BackgroundImageType { Default, None, Custom, AlbumCover }; PlaylistView(QWidget* parent = 0); @@ -86,12 +79,15 @@ class PlaylistView : public QTreeView { void SetReadOnlySettings(bool read_only) { read_only_settings_ = read_only; } Playlist* playlist() const { return playlist_; } - BackgroundImageType background_image_type() const { return background_image_type_; } + BackgroundImageType background_image_type() const { + return background_image_type_; + } Qt::Alignment column_alignment(int section) const; // QTreeView void drawTree(QPainter* painter, const QRegion& region) const; - void drawRow(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; + void drawRow(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const; void setModel(QAbstractItemModel* model); public slots: @@ -105,15 +101,16 @@ class PlaylistView : public QTreeView { void SetColumnAlignment(int section, Qt::Alignment alignment); void CopyCurrentSongToClipboard() const; - void CurrentSongChanged(const Song& new_song, const QString& uri, const QImage& cover_art); + void CurrentSongChanged(const Song& new_song, const QString& uri, + const QImage& cover_art); void PlayerStopped(); - signals: +signals: void PlayItem(const QModelIndex& index); void PlayPause(); void RightClicked(const QPoint& global_pos, const QModelIndex& index); void SeekTrack(int gap); - void FocusOnFilterSignal(QKeyEvent *event); + void FocusOnFilterSignal(QKeyEvent* event); void BackgroundPropertyChanged(); void ColumnAlignmentChanged(const ColumnAlignmentMap& alignment); @@ -127,11 +124,11 @@ class PlaylistView : public QTreeView { void mouseMoveEvent(QMouseEvent* event); void mousePressEvent(QMouseEvent* event); void leaveEvent(QEvent*); - void paintEvent(QPaintEvent *event); - void dragMoveEvent(QDragMoveEvent *event); - void dragEnterEvent(QDragEnterEvent *event); - void dragLeaveEvent(QDragLeaveEvent *event); - void dropEvent(QDropEvent *event); + void paintEvent(QPaintEvent* event); + void dragMoveEvent(QDragMoveEvent* event); + void dragEnterEvent(QDragEnterEvent* event); + void dragLeaveEvent(QDragLeaveEvent* event); + void dropEvent(QDropEvent* event); void resizeEvent(QResizeEvent* event); bool eventFilter(QObject* object, QEvent* event); void focusInEvent(QFocusEvent* event); @@ -165,8 +162,12 @@ class PlaylistView : public QTreeView { void UpdateCachedCurrentRowPixmap(QStyleOptionViewItemV4 option, const QModelIndex& index); - void set_background_image_type(BackgroundImageType bg) { background_image_type_ = bg; emit BackgroundPropertyChanged(); } - // Save image as the background_image_ after applying some modifications (opacity, ...). + void set_background_image_type(BackgroundImageType bg) { + background_image_type_ = bg; + emit BackgroundPropertyChanged(); + } + // Save image as the background_image_ after applying some modifications + // (opacity, ...). // Should be used instead of modifying background_image_ directly void set_background_image(const QImage& image); @@ -226,7 +227,7 @@ class PlaylistView : public QTreeView { bool inhibit_autoscroll_; bool currently_autoscrolling_; - int row_height_; // Used to invalidate the currenttrack_bar pixmaps + int row_height_; // Used to invalidate the currenttrack_bar pixmaps QList currenttrack_bar_left_; QList currenttrack_bar_mid_; QList currenttrack_bar_right_; @@ -247,4 +248,4 @@ class PlaylistView : public QTreeView { ColumnAlignmentMap column_alignment_; }; -#endif // PLAYLISTVIEW_H +#endif // PLAYLISTVIEW_H diff --git a/src/playlist/queue.cpp b/src/playlist/queue.cpp index c7783bfd4..167937c67 100644 --- a/src/playlist/queue.cpp +++ b/src/playlist/queue.cpp @@ -23,17 +23,13 @@ const char* Queue::kRowsMimetype = "application/x-clementine-queue-rows"; -Queue::Queue(QObject* parent) - : QAbstractProxyModel(parent) -{ -} +Queue::Queue(QObject* parent) : QAbstractProxyModel(parent) {} QModelIndex Queue::mapFromSource(const QModelIndex& source_index) const { - if (!source_index.isValid()) - return QModelIndex(); + if (!source_index.isValid()) return QModelIndex(); const int source_row = source_index.row(); - for (int i=0 ; iindex(row, 0)); - if (!proxy_index.isValid()) - continue; + if (!proxy_index.isValid()) continue; emit dataChanged(proxy_index, proxy_index); } } void Queue::SourceLayoutChanged() { - for (int i=0 ; i& proxy_rows, int pos) { // Take the items out of the list first, keeping track of whether the // insertion point changes int offset = 0; - foreach (int row, proxy_rows) { - moved_items << source_indexes_.takeAt(row-offset); - if (pos != -1 && pos >= row) - pos --; + foreach(int row, proxy_rows) { + moved_items << source_indexes_.takeAt(row - offset); + if (pos != -1 && pos >= row) pos--; offset++; } // Put the items back in const int start = pos == -1 ? source_indexes_.count() : pos; - for (int i=start ; i row) - d --; + foreach(int row, proxy_rows) { + if (pidx.row() > row) d--; } - if (pidx.row() + d >= start) - d += proxy_rows.count(); + if (pidx.row() + d >= start) d += proxy_rows.count(); - changePersistentIndex(pidx, index(pidx.row() + d, pidx.column(), QModelIndex())); + changePersistentIndex( + pidx, index(pidx.row() + d, pidx.column(), QModelIndex())); } } layoutChanged(); } -void Queue::MoveUp(int row) { - Move(QList() << row, row - 1); -} +void Queue::MoveUp(int row) { Move(QList() << row, row - 1); } -void Queue::MoveDown(int row) { - Move(QList() << row, row + 2); -} +void Queue::MoveDown(int row) { Move(QList() << row, row + 2); } QStringList Queue::mimeTypes() const { return QStringList() << kRowsMimetype << Playlist::kRowsMimetype; @@ -235,9 +222,8 @@ QMimeData* Queue::mimeData(const QModelIndexList& indexes) const { QMimeData* data = new QMimeData; QList rows; - foreach (const QModelIndex& index, indexes) { - if (index.column() != 0) - continue; + foreach(const QModelIndex & index, indexes) { + if (index.column() != 0) continue; rows << index.row(); } @@ -253,9 +239,9 @@ QMimeData* Queue::mimeData(const QModelIndexList& indexes) const { return data; } -bool Queue::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int, const QModelIndex&) { - if (action == Qt::IgnoreAction) - return false; +bool Queue::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, + int, const QModelIndex&) { + if (action == Qt::IgnoreAction) return false; if (data->hasFormat(kRowsMimetype)) { // Dragged from the queue @@ -263,7 +249,7 @@ bool Queue::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, QList proxy_rows; QDataStream stream(data->data(kRowsMimetype)); stream >> proxy_rows; - qStableSort(proxy_rows); // Make sure we take them in order + qStableSort(proxy_rows); // Make sure we take them in order Move(proxy_rows, row); } else if (data->hasFormat(Playlist::kRowsMimetype)) { @@ -276,7 +262,7 @@ bool Queue::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, stream >> source_rows; QModelIndexList source_indexes; - foreach (int source_row, source_rows) { + foreach(int source_row, source_rows) { const QModelIndex source_index = sourceModel()->index(source_row, 0); const QModelIndex proxy_index = mapFromSource(source_index); if (proxy_index.isValid()) { @@ -289,8 +275,9 @@ bool Queue::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, if (!source_indexes.isEmpty()) { const int insert_point = row == -1 ? source_indexes_.count() : row; - beginInsertRows(QModelIndex(), insert_point, insert_point + source_indexes.count() - 1); - for (int i=0 ; i& proxy_rows) { - //order the rows + // order the rows qStableSort(proxy_rows); - //reflects immediately changes in the playlist + // reflects immediately changes in the playlist layoutAboutToBeChanged(); int removed_rows = 0; - foreach (int row, proxy_rows) { - //after the first row, the row number needs to be updated - const int real_row = row-removed_rows; + foreach(int row, proxy_rows) { + // after the first row, the row number needs to be updated + const int real_row = row - removed_rows; beginRemoveRows(QModelIndex(), real_row, real_row); source_indexes_.removeAt(real_row); endRemoveRows(); diff --git a/src/playlist/queue.h b/src/playlist/queue.h index 67fa1f6a1..56c66d3f3 100644 --- a/src/playlist/queue.h +++ b/src/playlist/queue.h @@ -25,7 +25,7 @@ class Queue : public QAbstractProxyModel { Q_OBJECT -public: + public: Queue(QObject* parent = 0); static const char* kRowsMimetype; @@ -51,24 +51,27 @@ public: QModelIndex mapToSource(const QModelIndex& proxy_index) const; // QAbstractItemModel - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex &child) const; - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const; + QModelIndex index(int row, int column, + const QModelIndex& parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex& child) const; + int rowCount(const QModelIndex& parent = QModelIndex()) const; + int columnCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& proxy_index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; QStringList mimeTypes() const; Qt::DropActions supportedDropActions() const; QMimeData* mimeData(const QModelIndexList& indexes) const; - bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); - Qt::ItemFlags flags(const QModelIndex &index) const; + bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, + int column, const QModelIndex& parent); + Qt::ItemFlags flags(const QModelIndex& index) const; -private slots: - void SourceDataChanged(const QModelIndex& top_left, const QModelIndex& bottom_right); + private slots: + void SourceDataChanged(const QModelIndex& top_left, + const QModelIndex& bottom_right); void SourceLayoutChanged(); -private: + private: QList source_indexes_; }; -#endif // QUEUE_H +#endif // QUEUE_H diff --git a/src/playlist/queuemanager.cpp b/src/playlist/queuemanager.cpp index 319feec50..00e601cd5 100644 --- a/src/playlist/queuemanager.cpp +++ b/src/playlist/queuemanager.cpp @@ -26,12 +26,11 @@ #include #include -QueueManager::QueueManager(QWidget *parent) - : QDialog(parent), - ui_(new Ui_QueueManager), - playlists_(nullptr), - current_playlist_(nullptr) -{ +QueueManager::QueueManager(QWidget* parent) + : QDialog(parent), + ui_(new Ui_QueueManager), + playlists_(nullptr), + current_playlist_(nullptr) { ui_->setupUi(this); ui_->list->setItemDelegate(new QueuedItemDelegate(this, 0)); @@ -41,7 +40,7 @@ QueueManager::QueueManager(QWidget *parent) ui_->remove->setIcon(IconLoader::Load("edit-delete")); ui_->clear->setIcon(IconLoader::Load("edit-clear-list")); - //Set a standard shortcut + // Set a standard shortcut ui_->remove->setShortcut(QKeySequence::Delete); // Button connections @@ -54,43 +53,47 @@ QueueManager::QueueManager(QWidget *parent) connect(close, SIGNAL(activated()), SLOT(close())); } -QueueManager::~QueueManager() { - delete ui_; -} +QueueManager::~QueueManager() { delete ui_; } void QueueManager::SetPlaylistManager(PlaylistManager* manager) { playlists_ = manager; - connect(playlists_, SIGNAL(CurrentChanged(Playlist*)), SLOT(CurrentPlaylistChanged(Playlist*))); + connect(playlists_, SIGNAL(CurrentChanged(Playlist*)), + SLOT(CurrentPlaylistChanged(Playlist*))); CurrentPlaylistChanged(playlists_->current()); } void QueueManager::CurrentPlaylistChanged(Playlist* playlist) { if (current_playlist_) { - disconnect(current_playlist_->queue(), SIGNAL(rowsInserted(QModelIndex,int,int)), - this, SLOT(UpdateButtonState())); - disconnect(current_playlist_->queue(), SIGNAL(rowsRemoved(QModelIndex,int,int)), - this, SLOT(UpdateButtonState())); - disconnect(current_playlist_->queue(), SIGNAL(layoutChanged()), - this, SLOT(UpdateButtonState())); - disconnect(current_playlist_, SIGNAL(destroyed()), - this, SLOT(PlaylistDestroyed())); + disconnect(current_playlist_->queue(), + SIGNAL(rowsInserted(QModelIndex, int, int)), this, + SLOT(UpdateButtonState())); + disconnect(current_playlist_->queue(), + SIGNAL(rowsRemoved(QModelIndex, int, int)), this, + SLOT(UpdateButtonState())); + disconnect(current_playlist_->queue(), SIGNAL(layoutChanged()), this, + SLOT(UpdateButtonState())); + disconnect(current_playlist_, SIGNAL(destroyed()), this, + SLOT(PlaylistDestroyed())); } current_playlist_ = playlist; - connect(current_playlist_->queue(), SIGNAL(rowsInserted(QModelIndex,int,int)), - this, SLOT(UpdateButtonState())); - connect(current_playlist_->queue(), SIGNAL(rowsRemoved(QModelIndex,int,int)), - this, SLOT(UpdateButtonState())); - connect(current_playlist_->queue(), SIGNAL(layoutChanged()), - this, SLOT(UpdateButtonState())); - connect(current_playlist_, SIGNAL(destroyed()), - this, SLOT(PlaylistDestroyed())); + connect(current_playlist_->queue(), + SIGNAL(rowsInserted(QModelIndex, int, int)), this, + SLOT(UpdateButtonState())); + connect(current_playlist_->queue(), + SIGNAL(rowsRemoved(QModelIndex, int, int)), this, + SLOT(UpdateButtonState())); + connect(current_playlist_->queue(), SIGNAL(layoutChanged()), this, + SLOT(UpdateButtonState())); + connect(current_playlist_, SIGNAL(destroyed()), this, + SLOT(PlaylistDestroyed())); ui_->list->setModel(current_playlist_->queue()); - connect(ui_->list->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), + connect(ui_->list->selectionModel(), + SIGNAL(currentChanged(QModelIndex, QModelIndex)), SLOT(UpdateButtonState())); } @@ -98,10 +101,9 @@ void QueueManager::MoveUp() { QModelIndexList indexes = ui_->list->selectionModel()->selectedRows(); qStableSort(indexes); - if (indexes.isEmpty() || indexes.first().row() == 0) - return; + if (indexes.isEmpty() || indexes.first().row() == 0) return; - foreach (const QModelIndex& index, indexes) { + foreach(const QModelIndex & index, indexes) { current_playlist_->queue()->MoveUp(index.row()); } } @@ -110,24 +112,23 @@ void QueueManager::MoveDown() { QModelIndexList indexes = ui_->list->selectionModel()->selectedRows(); qStableSort(indexes); - if (indexes.isEmpty() || indexes.last().row() == current_playlist_->queue()->rowCount()-1) + if (indexes.isEmpty() || + indexes.last().row() == current_playlist_->queue()->rowCount() - 1) return; - for (int i=indexes.count()-1 ; i>=0 ; --i) { + for (int i = indexes.count() - 1; i >= 0; --i) { current_playlist_->queue()->MoveDown(indexes[i].row()); } } -void QueueManager::Clear() { - current_playlist_->queue()->Clear(); -} +void QueueManager::Clear() { current_playlist_->queue()->Clear(); } void QueueManager::Remove() { - //collect the rows to be removed + // collect the rows to be removed QList row_list; - foreach (const QModelIndex& index, ui_->list->selectionModel()->selectedRows()) { - if (index.isValid()) - row_list << index.row(); + foreach(const QModelIndex & index, + ui_->list->selectionModel()->selectedRows()) { + if (index.isValid()) row_list << index.row(); } current_playlist_->queue()->Remove(row_list); @@ -138,7 +139,8 @@ void QueueManager::UpdateButtonState() { if (current.isValid()) { ui_->move_up->setEnabled(current.row() != 0); - ui_->move_down->setEnabled(current.row() != current_playlist_->queue()->rowCount()-1); + ui_->move_down->setEnabled(current.row() != + current_playlist_->queue()->rowCount() - 1); ui_->remove->setEnabled(true); } else { ui_->move_up->setEnabled(false); diff --git a/src/playlist/queuemanager.h b/src/playlist/queuemanager.h index a136f2c33..1457eb94e 100644 --- a/src/playlist/queuemanager.h +++ b/src/playlist/queuemanager.h @@ -29,13 +29,13 @@ class QModelIndex; class QueueManager : public QDialog { Q_OBJECT -public: + public: QueueManager(QWidget* parent = 0); ~QueueManager(); void SetPlaylistManager(PlaylistManager* manager); -private slots: + private slots: void CurrentPlaylistChanged(Playlist* playlist); void PlaylistDestroyed(); void UpdateButtonState(); @@ -45,11 +45,11 @@ private slots: void Remove(); void Clear(); -private: + private: Ui_QueueManager* ui_; PlaylistManager* playlists_; Playlist* current_playlist_; }; -#endif // QUEUEMANAGER_H +#endif // QUEUEMANAGER_H diff --git a/src/playlist/songloaderinserter.cpp b/src/playlist/songloaderinserter.cpp index bdc99ec7f..01d115533 100644 --- a/src/playlist/songloaderinserter.cpp +++ b/src/playlist/songloaderinserter.cpp @@ -34,32 +34,31 @@ SongLoaderInserter::SongLoaderInserter(TaskManager* task_manager, async_load_id_(0), async_progress_(0), library_(library), - player_(player) { -} + player_(player) {} SongLoaderInserter::~SongLoaderInserter() { qDeleteAll(pending_); qDeleteAll(pending_async_); } -void SongLoaderInserter::Load(Playlist *destination, - int row, bool play_now, bool enqueue, - const QList &urls) { +void SongLoaderInserter::Load(Playlist* destination, int row, bool play_now, + bool enqueue, const QList& urls) { destination_ = destination; row_ = row; play_now_ = play_now; enqueue_ = enqueue; connect(destination, SIGNAL(destroyed()), SLOT(DestinationDestroyed())); - connect(this, SIGNAL(EffectiveLoadFinished(const SongList&)), - destination, SLOT(UpdateItems(const SongList&))); + connect(this, SIGNAL(EffectiveLoadFinished(const SongList&)), destination, + SLOT(UpdateItems(const SongList&))); - foreach (const QUrl& url, urls) { + foreach(const QUrl & url, urls) { SongLoader* loader = new SongLoader(library_, player_, this); // we're connecting this before we're even sure if this is an async load // to avoid race conditions (signal emission before we're listening to it) - connect(loader, SIGNAL(LoadFinished(bool)), SLOT(PendingLoadFinished(bool))); + connect(loader, SIGNAL(LoadFinished(bool)), + SLOT(PendingLoadFinished(bool))); SongLoader::Result ret = loader->Load(url); if (ret == SongLoader::WillLoadAsync) { @@ -79,7 +78,8 @@ void SongLoaderInserter::Load(Playlist *destination, else { async_progress_ = 0; async_load_id_ = task_manager_->StartTask(tr("Loading tracks")); - task_manager_->SetTaskProgress(async_load_id_, async_progress_, pending_.count()); + task_manager_->SetTaskProgress(async_load_id_, async_progress_, + pending_.count()); } } @@ -87,8 +87,8 @@ void SongLoaderInserter::Load(Playlist *destination, // First, we add tracks (without metadata) into the playlist // In the meantine, MusicBrainz will be queried to get songs' metadata. // AudioCDTagsLoaded will be called next, and playlist's items will be updated. -void SongLoaderInserter::LoadAudioCD(Playlist *destination, - int row, bool play_now, bool enqueue) { +void SongLoaderInserter::LoadAudioCD(Playlist* destination, int row, + bool play_now, bool enqueue) { destination_ = destination; row_ = row; play_now_ = play_now; @@ -106,14 +106,11 @@ void SongLoaderInserter::LoadAudioCD(Playlist *destination, PartiallyFinished(); } -void SongLoaderInserter::DestinationDestroyed() { - destination_ = nullptr; -} +void SongLoaderInserter::DestinationDestroyed() { destination_ = nullptr; } void SongLoaderInserter::AudioCDTagsLoaded(bool success) { SongLoader* loader = qobject_cast(sender()); - if (!loader || !destination_) - return; + if (!loader || !destination_) return; if (success) destination_->UpdateItems(loader->songs()); @@ -124,8 +121,7 @@ void SongLoaderInserter::AudioCDTagsLoaded(bool success) { void SongLoaderInserter::PendingLoadFinished(bool success) { SongLoader* loader = qobject_cast(sender()); - if (!loader || !pending_.contains(loader)) - return; + if (!loader || !pending_.contains(loader)) return; pending_.remove(loader); pending_async_.insert(loader); @@ -139,7 +135,8 @@ void SongLoaderInserter::PendingLoadFinished(bool success) { task_manager_->SetTaskFinished(async_load_id_); async_progress_ = 0; async_load_id_ = task_manager_->StartTask(tr("Loading tracks info")); - task_manager_->SetTaskProgress(async_load_id_, async_progress_, pending_async_.count()); + task_manager_->SetTaskProgress(async_load_id_, async_progress_, + pending_async_.count()); PartiallyFinished(); QtConcurrent::run(this, &SongLoaderInserter::EffectiveLoad); } @@ -154,7 +151,7 @@ void SongLoaderInserter::PartiallyFinished() { } void SongLoaderInserter::EffectiveLoad() { - foreach (SongLoader* loader, pending_async_) { + foreach(SongLoader * loader, pending_async_) { loader->EffectiveSongsLoad(); task_manager_->SetTaskProgress(async_load_id_, ++async_progress_); emit EffectiveLoadFinished(loader->songs()); diff --git a/src/playlist/songloaderinserter.h b/src/playlist/songloaderinserter.h index 01f6e8c9a..d273e4161 100644 --- a/src/playlist/songloaderinserter.h +++ b/src/playlist/songloaderinserter.h @@ -34,10 +34,9 @@ class QModelIndex; class SongLoaderInserter : public QObject { Q_OBJECT -public: + public: SongLoaderInserter(TaskManager* task_manager, - LibraryBackendInterface* library, - const Player* player); + LibraryBackendInterface* library, const Player* player); ~SongLoaderInserter(); void Load(Playlist* destination, int row, bool play_now, bool enqueue, @@ -48,17 +47,17 @@ signals: void Error(const QString& message); void EffectiveLoadFinished(const SongList& songs); -private slots: + private slots: void PendingLoadFinished(bool success); void DestinationDestroyed(); void AudioCDTagsLoaded(bool success); -private: + private: void PartiallyFinished(); void EffectiveLoad(); void Finished(); -private: + private: TaskManager* task_manager_; Playlist* destination_; @@ -76,4 +75,4 @@ private: const Player* player_; }; -#endif // SONGLOADERINSERTER_H +#endif // SONGLOADERINSERTER_H diff --git a/src/playlist/songmimedata.h b/src/playlist/songmimedata.h index f35d6a265..065b00fa6 100644 --- a/src/playlist/songmimedata.h +++ b/src/playlist/songmimedata.h @@ -28,12 +28,11 @@ class LibraryBackendInterface; class SongMimeData : public MimeData { Q_OBJECT -public: - SongMimeData() - : backend(NULL) {} + public: + SongMimeData() : backend(NULL) {} LibraryBackendInterface* backend; SongList songs; }; -#endif // SONGMIMEDATA_H +#endif // SONGMIMEDATA_H diff --git a/src/playlist/songplaylistitem.cpp b/src/playlist/songplaylistitem.cpp index ac0bc103b..446147f1b 100644 --- a/src/playlist/songplaylistitem.cpp +++ b/src/playlist/songplaylistitem.cpp @@ -25,16 +25,10 @@ #include #include -SongPlaylistItem::SongPlaylistItem(const QString& type) - : PlaylistItem(type) -{ -} +SongPlaylistItem::SongPlaylistItem(const QString& type) : PlaylistItem(type) {} SongPlaylistItem::SongPlaylistItem(const Song& song) - : PlaylistItem(song.is_stream() ? "Stream" : "File"), - song_(song) -{ -} + : PlaylistItem(song.is_stream() ? "Stream" : "File"), song_(song) {} bool SongPlaylistItem::InitFromQuery(const SqlRow& query) { song_.InitFromQuery(query, false, (Song::kColumns.count() + 1) * 3); @@ -46,21 +40,16 @@ bool SongPlaylistItem::InitFromQuery(const SqlRow& query) { return true; } -QUrl SongPlaylistItem::Url() const { - return song_.url(); -} +QUrl SongPlaylistItem::Url() const { return song_.url(); } void SongPlaylistItem::Reload() { - if (song_.url().scheme() != "file") - return; + if (song_.url().scheme() != "file") return; - TagReaderClient::Instance()->ReadFileBlocking(song_.url().toLocalFile(), &song_); + TagReaderClient::Instance()->ReadFileBlocking(song_.url().toLocalFile(), + &song_); } Song SongPlaylistItem::Metadata() const { - if (HasTemporaryMetadata()) - return temp_metadata_; + if (HasTemporaryMetadata()) return temp_metadata_; return song_; } - - diff --git a/src/playlist/songplaylistitem.h b/src/playlist/songplaylistitem.h index 9ad0b42da..36861c8f8 100644 --- a/src/playlist/songplaylistitem.h +++ b/src/playlist/songplaylistitem.h @@ -43,4 +43,4 @@ class SongPlaylistItem : public PlaylistItem { Song song_; }; -#endif // SONGPLAYLISTITEM_H +#endif // SONGPLAYLISTITEM_H diff --git a/src/playlistparsers/asxiniparser.cpp b/src/playlistparsers/asxiniparser.cpp index 79e5a155c..081d7b535 100644 --- a/src/playlistparsers/asxiniparser.cpp +++ b/src/playlistparsers/asxiniparser.cpp @@ -22,15 +22,14 @@ #include AsxIniParser::AsxIniParser(LibraryBackendInterface* library, QObject* parent) - : ParserBase(library, parent) -{ -} + : ParserBase(library, parent) {} -bool AsxIniParser::TryMagic(const QByteArray &data) const { +bool AsxIniParser::TryMagic(const QByteArray& data) const { return data.toLower().contains("[reference]"); } -SongList AsxIniParser::Load(QIODevice *device, const QString& playlist_path, const QDir &dir) const { +SongList AsxIniParser::Load(QIODevice* device, const QString& playlist_path, + const QDir& dir) const { SongList ret; while (!device->atEnd()) { @@ -50,12 +49,13 @@ SongList AsxIniParser::Load(QIODevice *device, const QString& playlist_path, con return ret; } -void AsxIniParser::Save(const SongList &songs, QIODevice *device, const QDir &dir) const { +void AsxIniParser::Save(const SongList& songs, QIODevice* device, + const QDir& dir) const { QTextStream s(device); s << "[Reference]" << endl; int n = 1; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { s << "Ref" << n << "=" << URLOrRelativeFilename(song.url(), dir) << endl; ++n; } diff --git a/src/playlistparsers/asxiniparser.h b/src/playlistparsers/asxiniparser.h index fe2264178..73de87d59 100644 --- a/src/playlistparsers/asxiniparser.h +++ b/src/playlistparsers/asxiniparser.h @@ -23,16 +23,18 @@ class AsxIniParser : public ParserBase { Q_OBJECT -public: + public: AsxIniParser(LibraryBackendInterface* library, QObject* parent = 0); QString name() const { return "ASX/INI"; } QStringList file_extensions() const { return QStringList() << "asxini"; } - bool TryMagic(const QByteArray &data) const; + bool TryMagic(const QByteArray& data) const; - SongList Load(QIODevice *device, const QString& playlist_path = "", const QDir &dir = QDir()) const; - void Save(const SongList &songs, QIODevice *device, const QDir &dir = QDir()) const; + SongList Load(QIODevice* device, const QString& playlist_path = "", + const QDir& dir = QDir()) const; + void Save(const SongList& songs, QIODevice* device, + const QDir& dir = QDir()) const; }; -#endif // ASXINIPARSER_H +#endif // ASXINIPARSER_H diff --git a/src/playlistparsers/asxparser.cpp b/src/playlistparsers/asxparser.cpp index 6d714b798..846533e94 100644 --- a/src/playlistparsers/asxparser.cpp +++ b/src/playlistparsers/asxparser.cpp @@ -28,11 +28,9 @@ #include ASXParser::ASXParser(LibraryBackendInterface* library, QObject* parent) - : XMLParser(library, parent) -{ -} + : XMLParser(library, parent) {} -SongList ASXParser::Load(QIODevice *device, const QString& playlist_path, +SongList ASXParser::Load(QIODevice* device, const QString& playlist_path, const QDir& dir) const { // We have to load everything first so we can munge the "XML". QByteArray data = device->readAll(); @@ -80,7 +78,6 @@ SongList ASXParser::Load(QIODevice *device, const QString& playlist_path, return ret; } - Song ASXParser::ParseTrack(QXmlStreamReader* reader, const QDir& dir) const { QString title, artist, album, ref; @@ -120,7 +117,8 @@ return_song: return song; } -void ASXParser::Save(const SongList& songs, QIODevice* device, const QDir&) const { +void ASXParser::Save(const SongList& songs, QIODevice* device, + const QDir&) const { QXmlStreamWriter writer(device); writer.setAutoFormatting(true); writer.setAutoFormattingIndent(2); @@ -128,7 +126,7 @@ void ASXParser::Save(const SongList& songs, QIODevice* device, const QDir&) cons { StreamElement asx("asx", &writer); writer.writeAttribute("version", "3.0"); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { StreamElement entry("entry", &writer); writer.writeTextElement("title", song.title()); { @@ -143,6 +141,6 @@ void ASXParser::Save(const SongList& songs, QIODevice* device, const QDir&) cons writer.writeEndDocument(); } -bool ASXParser::TryMagic(const QByteArray &data) const { +bool ASXParser::TryMagic(const QByteArray& data) const { return data.toLower().contains(" #include -const char* CueParser::kFileLineRegExp = "(\\S+)\\s+(?:\"([^\"]+)\"|(\\S+))\\s*(?:\"([^\"]+)\"|(\\S+))?"; +const char* CueParser::kFileLineRegExp = + "(\\S+)\\s+(?:\"([^\"]+)\"|(\\S+))\\s*(?:\"([^\"]+)\"|(\\S+))?"; const char* CueParser::kIndexRegExp = "(\\d{2,3}):(\\d{2}):(\\d{2})"; const char* CueParser::kPerformer = "performer"; @@ -43,15 +44,15 @@ const char* CueParser::kGenre = "genre"; const char* CueParser::kDate = "date"; CueParser::CueParser(LibraryBackendInterface* library, QObject* parent) - : ParserBase(library, parent) -{ -} + : ParserBase(library, parent) {} -SongList CueParser::Load(QIODevice* device, const QString& playlist_path, const QDir& dir) const { +SongList CueParser::Load(QIODevice* device, const QString& playlist_path, + const QDir& dir) const { SongList ret; QTextStream text_stream(device); - text_stream.setCodec(QTextCodec::codecForUtfText(device->peek(1024), QTextCodec::codecForName("UTF-8"))); + text_stream.setCodec(QTextCodec::codecForUtfText( + device->peek(1024), QTextCodec::codecForName("UTF-8"))); QString dir_path = dir.absolutePath(); // read the first line already @@ -76,7 +77,7 @@ SongList CueParser::Load(QIODevice* device, const QString& playlist_path, const QStringList splitted = SplitCueLine(line); // uninteresting or incorrect line - if(splitted.size() < 2) { + if (splitted.size() < 2) { continue; } @@ -84,59 +85,59 @@ SongList CueParser::Load(QIODevice* device, const QString& playlist_path, const QString line_value = splitted[1]; // PERFORMER - if(line_name == kPerformer) { + if (line_name == kPerformer) { album_artist = line_value; - // TITLE - } else if(line_name == kTitle) { + // TITLE + } else if (line_name == kTitle) { album = line_value; - // SONGWRITER - } else if(line_name == kSongWriter) { + // SONGWRITER + } else if (line_name == kSongWriter) { album_composer = line_value; - // FILE - } else if(line_name == kFile) { + // FILE + } else if (line_name == kFile) { file = QDir::isAbsolutePath(line_value) - ? line_value - : dir.absoluteFilePath(line_value); + ? line_value + : dir.absoluteFilePath(line_value); - if(splitted.size() > 2) { + if (splitted.size() > 2) { file_type = splitted[2]; } - // REM - } else if(line_name == kRem) { - if(splitted.size() < 3) { - break; - } + // REM + } else if (line_name == kRem) { + if (splitted.size() < 3) { + break; + } - // REM GENRE - if (line_value.toLower() == kGenre) { - genre = splitted[2]; + // REM GENRE + if (line_value.toLower() == kGenre) { + genre = splitted[2]; // REM DATE - } else if(line_value.toLower() == kDate) { - date = splitted[2]; - } + } else if (line_value.toLower() == kDate) { + date = splitted[2]; + } - // end of the header -> go into the track mode - } else if(line_name == kTrack) { + // end of the header -> go into the track mode + } else if (line_name == kTrack) { files++; break; - } // just ignore the rest of possible field types for now... - } while(!(line = text_stream.readLine()).isNull()); + } while (!(line = text_stream.readLine()).isNull()); - if(line.isNull()) { - qLog(Warning) << "the .cue file from " << dir_path << " defines no tracks!"; + if (line.isNull()) { + qLog(Warning) << "the .cue file from " << dir_path + << " defines no tracks!"; return ret; } @@ -155,83 +156,88 @@ SongList CueParser::Load(QIODevice* device, const QString& playlist_path, const QStringList splitted = SplitCueLine(line); // uninteresting or incorrect line - if(splitted.size() < 2) { + if (splitted.size() < 2) { continue; } QString line_name = splitted[0].toLower(); QString line_value = splitted[1]; - QString line_additional = splitted.size() > 2 ? splitted[2].toLower() : ""; + QString line_additional = + splitted.size() > 2 ? splitted[2].toLower() : ""; - if(line_name == kTrack) { + if (line_name == kTrack) { - // the beginning of another track's definition - we're saving the current one + // the beginning of another track's definition - we're saving the + // current one // for later (if it's valid of course) - // please note that the same code is repeated just after this 'do-while' loop - if(valid_file && !index.isEmpty() && (track_type.isEmpty() || track_type == kAudioTrackType)) { - entries.append(CueEntry(file, index, title, artist, album_artist, album, composer, album_composer, genre, date)); + // please note that the same code is repeated just after this 'do-while' + // loop + if (valid_file && !index.isEmpty() && + (track_type.isEmpty() || track_type == kAudioTrackType)) { + entries.append(CueEntry(file, index, title, artist, album_artist, + album, composer, album_composer, genre, + date)); } // clear the state track_type = index = artist = title = ""; - if(!line_additional.isEmpty()) { + if (!line_additional.isEmpty()) { track_type = line_additional; } - } else if(line_name == kIndex) { + } else if (line_name == kIndex) { // we need the index's position field - if(!line_additional.isEmpty()) { + if (!line_additional.isEmpty()) { // if there's none "01" index, we'll just take the first one // also, we'll take the "01" index even if it's the last one - if(line_value == "01" || index.isEmpty()) { + if (line_value == "01" || index.isEmpty()) { index = line_additional; - } - } - } else if(line_name == kPerformer) { + } else if (line_name == kPerformer) { artist = line_value; - } else if(line_name == kTitle) { + } else if (line_name == kTitle) { title = line_value; - } else if(line_name == kSongWriter) { + } else if (line_name == kSongWriter) { composer = line_value; - // end of track's for the current file -> parse next one - } else if(line_name == kFile) { + // end of track's for the current file -> parse next one + } else if (line_name == kFile) { break; - } // just ignore the rest of possible field types for now... - } while(!(line = text_stream.readLine()).isNull()); + } while (!(line = text_stream.readLine()).isNull()); // we didn't add the last song yet... - if(valid_file && !index.isEmpty() && (track_type.isEmpty() || track_type == kAudioTrackType)) { - entries.append(CueEntry(file, index, title, artist, album_artist, album, composer, album_composer, genre, date)); + if (valid_file && !index.isEmpty() && + (track_type.isEmpty() || track_type == kAudioTrackType)) { + entries.append(CueEntry(file, index, title, artist, album_artist, album, + composer, album_composer, genre, date)); } } QDateTime cue_mtime = QFileInfo(playlist_path).lastModified(); // finalize parsing songs - for(int i = 0; i < entries.length(); i++) { + for (int i = 0; i < entries.length(); i++) { CueEntry entry = entries.at(i); Song song = LoadSong(entry.file, IndexToMarker(entry.index), dir); // cue song has mtime equal to qMax(media_file_mtime, cue_sheet_mtime) - if(cue_mtime.isValid()) { + if (cue_mtime.isValid()) { song.set_mtime(qMax(cue_mtime.toTime_t(), song.mtime())); } song.set_cue_path(playlist_path); @@ -240,20 +246,22 @@ SongList CueParser::Load(QIODevice* device, const QString& playlist_path, const // the current .cue metadata // set track number only in single-file mode - if(files == 1) { + if (files == 1) { song.set_track(i + 1); } - // the last TRACK for every FILE gets it's 'end' marker from the media file's + // the last TRACK for every FILE gets it's 'end' marker from the media + // file's // length - if(i + 1 < entries.size() && entries.at(i).file == entries.at(i + 1).file) { + if (i + 1 < entries.size() && + entries.at(i).file == entries.at(i + 1).file) { // incorrect indices? - if(!UpdateSong(entry, entries.at(i + 1).index, &song)) { + if (!UpdateSong(entry, entries.at(i + 1).index, &song)) { continue; } } else { // incorrect index? - if(!UpdateLastSong(entry, &song)) { + if (!UpdateLastSong(entry, &song)) { continue; } } @@ -264,11 +272,13 @@ SongList CueParser::Load(QIODevice* device, const QString& playlist_path, const return ret; } -// This and the kFileLineRegExp do most of the "dirty" work, namely: splitting the raw .cue -// line into logical parts and getting rid of all the unnecessary whitespaces and quoting. +// This and the kFileLineRegExp do most of the "dirty" work, namely: splitting +// the raw .cue +// line into logical parts and getting rid of all the unnecessary whitespaces +// and quoting. QStringList CueParser::SplitCueLine(const QString& line) const { QRegExp line_regexp(kFileLineRegExp); - if(!line_regexp.exactMatch(line.trimmed())) { + if (!line_regexp.exactMatch(line.trimmed())) { return QStringList(); } @@ -276,20 +286,21 @@ QStringList CueParser::SplitCueLine(const QString& line) const { return line_regexp.capturedTexts().filter(QRegExp(".+")).mid(1, -1); } -// Updates the song with data from the .cue entry. This one mustn't be used for the +// Updates the song with data from the .cue entry. This one mustn't be used for +// the // last song in the .cue file. -bool CueParser::UpdateSong(const CueEntry& entry, const QString& next_index, Song* song) const { +bool CueParser::UpdateSong(const CueEntry& entry, const QString& next_index, + Song* song) const { qint64 beginning = IndexToMarker(entry.index); qint64 end = IndexToMarker(next_index); // incorrect indices (we won't be able to calculate beginning or end) - if(beginning == -1 || end == -1) { + if (beginning == -1 || end == -1) { return false; } // believe the CUE: Init() forces validity - song->Init(entry.title, entry.PrettyArtist(), - entry.album, beginning, end); + song->Init(entry.title, entry.PrettyArtist(), entry.album, beginning, end); song->set_albumartist(entry.album_artist); song->set_composer(entry.PrettyComposer()); song->set_genre(entry.genre); @@ -298,13 +309,14 @@ bool CueParser::UpdateSong(const CueEntry& entry, const QString& next_index, Son return true; } -// Updates the song with data from the .cue entry. This one must be used only for the +// Updates the song with data from the .cue entry. This one must be used only +// for the // last song in the .cue file. bool CueParser::UpdateLastSong(const CueEntry& entry, Song* song) const { qint64 beginning = IndexToMarker(entry.index); // incorrect index (we won't be able to calculate beginning) - if(beginning == -1) { + if (beginning == -1) { return false; } @@ -328,30 +340,32 @@ bool CueParser::UpdateLastSong(const CueEntry& entry, Song* song) const { qint64 CueParser::IndexToMarker(const QString& index) const { QRegExp index_regexp(kIndexRegExp); - if(!index_regexp.exactMatch(index)) { + if (!index_regexp.exactMatch(index)) { return -1; } QStringList splitted = index_regexp.capturedTexts().mid(1, -1); - qlonglong frames = splitted.at(0).toLongLong() * 60 * 75 + splitted.at(1).toLongLong() * 75 + + qlonglong frames = splitted.at(0).toLongLong() * 60 * 75 + + splitted.at(1).toLongLong() * 75 + splitted.at(2).toLongLong(); return (frames * kNsecPerSec) / 75; } -void CueParser::Save(const SongList &songs, QIODevice *device, const QDir &dir) const { +void CueParser::Save(const SongList& songs, QIODevice* device, + const QDir& dir) const { // TODO } // Looks for a track starting with one of the .cue's keywords. -bool CueParser::TryMagic(const QByteArray &data) const { +bool CueParser::TryMagic(const QByteArray& data) const { QStringList splitted = QString::fromUtf8(data.constData()).split('\n'); - for(int i = 0; i < splitted.length(); i++) { + for (int i = 0; i < splitted.length(); i++) { QString line = splitted.at(i).trimmed(); - if(line.startsWith(kPerformer, Qt::CaseInsensitive) || - line.startsWith(kTitle, Qt::CaseInsensitive) || - line.startsWith(kFile, Qt::CaseInsensitive) || - line.startsWith(kTrack, Qt::CaseInsensitive)) { + if (line.startsWith(kPerformer, Qt::CaseInsensitive) || + line.startsWith(kTitle, Qt::CaseInsensitive) || + line.startsWith(kFile, Qt::CaseInsensitive) || + line.startsWith(kTrack, Qt::CaseInsensitive)) { return true; } } diff --git a/src/playlistparsers/cueparser.h b/src/playlistparsers/cueparser.h index f3c773a70..2ba8f5826 100644 --- a/src/playlistparsers/cueparser.h +++ b/src/playlistparsers/cueparser.h @@ -51,8 +51,10 @@ class CueParser : public ParserBase { bool TryMagic(const QByteArray& data) const; - SongList Load(QIODevice* device, const QString& playlist_path = "", const QDir& dir = QDir()) const; - void Save(const SongList& songs, QIODevice* device, const QDir& dir = QDir()) const; + SongList Load(QIODevice* device, const QString& playlist_path = "", + const QDir& dir = QDir()) const; + void Save(const SongList& songs, QIODevice* device, + const QDir& dir = QDir()) const; private: // A single TRACK entry in .cue file. @@ -72,12 +74,16 @@ class CueParser : public ParserBase { QString genre; QString date; - QString PrettyArtist() const { return artist.isEmpty() ? album_artist : artist; } - QString PrettyComposer() const { return composer.isEmpty() ? album_composer : composer; } + QString PrettyArtist() const { + return artist.isEmpty() ? album_artist : artist; + } + QString PrettyComposer() const { + return composer.isEmpty() ? album_composer : composer; + } CueEntry(QString& file, QString& index, QString& title, QString& artist, - QString& album_artist, QString& album, QString& composer, QString& album_composer, - QString& genre, QString& date) { + QString& album_artist, QString& album, QString& composer, + QString& album_composer, QString& genre, QString& date) { this->file = file; this->index = index; this->title = title; @@ -91,7 +97,8 @@ class CueParser : public ParserBase { } }; - bool UpdateSong(const CueEntry& entry, const QString& next_index, Song* song) const; + bool UpdateSong(const CueEntry& entry, const QString& next_index, + Song* song) const; bool UpdateLastSong(const CueEntry& entry, Song* song) const; QStringList SplitCueLine(const QString& line) const; diff --git a/src/playlistparsers/m3uparser.cpp b/src/playlistparsers/m3uparser.cpp index 53807b379..827753b88 100644 --- a/src/playlistparsers/m3uparser.cpp +++ b/src/playlistparsers/m3uparser.cpp @@ -23,11 +23,10 @@ #include M3UParser::M3UParser(LibraryBackendInterface* library, QObject* parent) - : ParserBase(library, parent) -{ -} + : ParserBase(library, parent) {} -SongList M3UParser::Load(QIODevice* device, const QString& playlist_path, const QDir& dir) const { +SongList M3UParser::Load(QIODevice* device, const QString& playlist_path, + const QDir& dir) const { SongList ret; M3UType type = STANDARD; @@ -79,7 +78,8 @@ SongList M3UParser::Load(QIODevice* device, const QString& playlist_path, const return ret; } -bool M3UParser::ParseMetadata(const QString& line, M3UParser::Metadata* metadata) const { +bool M3UParser::ParseMetadata(const QString& line, + M3UParser::Metadata* metadata) const { // Extended info, eg. // #EXTINF:123,Sample Artist - Sample title QString info = line.section(':', 1); @@ -102,21 +102,23 @@ bool M3UParser::ParseMetadata(const QString& line, M3UParser::Metadata* metadata return true; } -void M3UParser::Save(const SongList &songs, QIODevice *device, const QDir &dir) const { +void M3UParser::Save(const SongList& songs, QIODevice* device, + const QDir& dir) const { device->write("#EXTM3U\n"); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { if (song.url().isEmpty()) { continue; } QString meta = QString("#EXTINF:%1,%2 - %3\n") - .arg(song.length_nanosec() / kNsecPerSec) - .arg(song.artist()).arg(song.title()); + .arg(song.length_nanosec() / kNsecPerSec) + .arg(song.artist()) + .arg(song.title()); device->write(meta.toUtf8()); device->write(URLOrRelativeFilename(song.url(), dir).toUtf8()); device->write("\n"); } } -bool M3UParser::TryMagic(const QByteArray &data) const { +bool M3UParser::TryMagic(const QByteArray& data) const { return data.contains("#EXTM3U") || data.contains("#EXTINF"); } diff --git a/src/playlistparsers/m3uparser.h b/src/playlistparsers/m3uparser.h index 28008007f..53ef2185f 100644 --- a/src/playlistparsers/m3uparser.h +++ b/src/playlistparsers/m3uparser.h @@ -31,13 +31,18 @@ class M3UParser : public ParserBase { M3UParser(LibraryBackendInterface* library, QObject* parent = 0); QString name() const { return "M3U"; } - QStringList file_extensions() const { return QStringList() << "m3u" << "m3u8"; } + QStringList file_extensions() const { + return QStringList() << "m3u" + << "m3u8"; + } QString mime_type() const { return "text/uri-list"; } - bool TryMagic(const QByteArray &data) const; + bool TryMagic(const QByteArray& data) const; - SongList Load(QIODevice* device, const QString& playlist_path = "", const QDir& dir = QDir()) const; - void Save(const SongList &songs, QIODevice* device, const QDir& dir = QDir()) const; + SongList Load(QIODevice* device, const QString& playlist_path = "", + const QDir& dir = QDir()) const; + void Save(const SongList& songs, QIODevice* device, + const QDir& dir = QDir()) const; private: enum M3UType { diff --git a/src/playlistparsers/parserbase.cpp b/src/playlistparsers/parserbase.cpp index 7c57fe476..578dbbfd5 100644 --- a/src/playlistparsers/parserbase.cpp +++ b/src/playlistparsers/parserbase.cpp @@ -23,11 +23,8 @@ #include -ParserBase::ParserBase(LibraryBackendInterface* library, QObject *parent) - : QObject(parent), - library_(library) -{ -} +ParserBase::ParserBase(LibraryBackendInterface* library, QObject* parent) + : QObject(parent), library_(library) {} void ParserBase::LoadSong(const QString& filename_or_url, qint64 beginning, const QDir& dir, Song* song) const { @@ -79,22 +76,22 @@ void ParserBase::LoadSong(const QString& filename_or_url, qint64 beginning, } } -Song ParserBase::LoadSong(const QString& filename_or_url, qint64 beginning, const QDir& dir) const { +Song ParserBase::LoadSong(const QString& filename_or_url, qint64 beginning, + const QDir& dir) const { Song song; LoadSong(filename_or_url, beginning, dir, &song); return song; } -QString ParserBase::URLOrRelativeFilename(const QUrl& url, const QDir& dir) const { - if (url.scheme() != "file") - return url.toString(); +QString ParserBase::URLOrRelativeFilename(const QUrl& url, + const QDir& dir) const { + if (url.scheme() != "file") return url.toString(); const QString filename = url.toLocalFile(); if (QDir::isAbsolutePath(filename)) { const QString relative = dir.relativeFilePath(filename); - if (!relative.contains("..")) - return relative; + if (!relative.contains("..")) return relative; } return filename; } diff --git a/src/playlistparsers/parserbase.h b/src/playlistparsers/parserbase.h index cf141a5b3..ca91d168d 100644 --- a/src/playlistparsers/parserbase.h +++ b/src/playlistparsers/parserbase.h @@ -28,7 +28,7 @@ class LibraryBackendInterface; class ParserBase : public QObject { Q_OBJECT -public: + public: ParserBase(LibraryBackendInterface* library, QObject* parent = 0); virtual QString name() const = 0; @@ -37,33 +37,41 @@ public: virtual bool TryMagic(const QByteArray& data) const = 0; - // Loads all songs from playlist found at path 'playlist_path' in directory 'dir'. + // Loads all songs from playlist found at path 'playlist_path' in directory + // 'dir'. // The 'device' argument is an opened and ready to read from represantation of // this playlist. - // This method might not return all of the songs found in the playlist. Any playlist - // parser may decide to leave out some entries if it finds them incomplete or invalid. - // This means that the final resulting SongList should be considered valid (at least + // This method might not return all of the songs found in the playlist. Any + // playlist + // parser may decide to leave out some entries if it finds them incomplete or + // invalid. + // This means that the final resulting SongList should be considered valid (at + // least // from the parser's point of view). - virtual SongList Load(QIODevice* device, const QString& playlist_path = "", const QDir& dir = QDir()) const = 0; - virtual void Save(const SongList& songs, QIODevice* device, const QDir& dir = QDir()) const = 0; + virtual SongList Load(QIODevice* device, const QString& playlist_path = "", + const QDir& dir = QDir()) const = 0; + virtual void Save(const SongList& songs, QIODevice* device, + const QDir& dir = QDir()) const = 0; -protected: + protected: // Loads a song. If filename_or_url is a URL (with a scheme other than // "file") then it is set on the song and the song marked as a stream. // If it is a filename or a file:// URL then it is made absolute and canonical // and set as a file:// url on the song. Also sets the song's metadata by // searching in the Library, or loading from the file as a fallback. // This function should always be used when loading a playlist. - Song LoadSong(const QString& filename_or_url, qint64 beginning, const QDir& dir) const; - void LoadSong(const QString& filename_or_url, qint64 beginning, const QDir& dir, Song* song) const; + Song LoadSong(const QString& filename_or_url, qint64 beginning, + const QDir& dir) const; + void LoadSong(const QString& filename_or_url, qint64 beginning, + const QDir& dir, Song* song) const; // If the URL is a file:// URL then returns its path relative to the // directory. Otherwise returns the URL as is. // This function should always be used when saving a playlist. QString URLOrRelativeFilename(const QUrl& url, const QDir& dir) const; -private: + private: LibraryBackendInterface* library_; }; -#endif // PARSERBASE_H +#endif // PARSERBASE_H diff --git a/src/playlistparsers/playlistparser.cpp b/src/playlistparsers/playlistparser.cpp index cb998c462..46d319d7d 100644 --- a/src/playlistparsers/playlistparser.cpp +++ b/src/playlistparsers/playlistparser.cpp @@ -29,9 +29,9 @@ const int PlaylistParser::kMagicSize = 512; -PlaylistParser::PlaylistParser(LibraryBackendInterface* library, QObject *parent) - : QObject(parent) -{ +PlaylistParser::PlaylistParser(LibraryBackendInterface* library, + QObject* parent) + : QObject(parent) { default_parser_ = new XSPFParser(library, this); parsers_ << new M3UParser(library, this); parsers_ << default_parser_; @@ -45,9 +45,7 @@ PlaylistParser::PlaylistParser(LibraryBackendInterface* library, QObject *parent QStringList PlaylistParser::file_extensions() const { QStringList ret; - foreach (ParserBase* parser, parsers_) { - ret << parser->file_extensions(); - } + foreach(ParserBase * parser, parsers_) { ret << parser->file_extensions(); } qStableSort(ret); return ret; @@ -56,7 +54,7 @@ QStringList PlaylistParser::file_extensions() const { QString PlaylistParser::filters() const { QStringList filters; QStringList all_extensions; - foreach (ParserBase* parser, parsers_) { + foreach(ParserBase * parser, parsers_) { filters << FilterForParser(parser, &all_extensions); } @@ -65,13 +63,13 @@ QString PlaylistParser::filters() const { return filters.join(";;"); } -QString PlaylistParser::FilterForParser(const ParserBase *parser, QStringList *all_extensions) const { +QString PlaylistParser::FilterForParser(const ParserBase* parser, + QStringList* all_extensions) const { QStringList extensions; - foreach (const QString& extension, parser->file_extensions()) - extensions << "*." + extension; + foreach(const QString & extension, parser->file_extensions()) + extensions << "*." + extension; - if (all_extensions) - *all_extensions << extensions; + if (all_extensions) *all_extensions << extensions; return tr("%1 playlists (%2)").arg(parser->name(), extensions.join(" ")); } @@ -85,16 +83,15 @@ QString PlaylistParser::default_filter() const { } ParserBase* PlaylistParser::ParserForExtension(const QString& suffix) const { - foreach (ParserBase* p, parsers_) { - if (p->file_extensions().contains(suffix)) - return p; + foreach(ParserBase * p, parsers_) { + if (p->file_extensions().contains(suffix)) return p; } return nullptr; } ParserBase* PlaylistParser::ParserForMagic(const QByteArray& data, const QString& mime_type) const { - foreach (ParserBase* p, parsers_) { + foreach(ParserBase * p, parsers_) { if ((!mime_type.isEmpty() && mime_type == p->mime_type()) || p->TryMagic(data)) return p; @@ -131,7 +128,8 @@ SongList PlaylistParser::LoadFromDevice(QIODevice* device, return parser->Load(device, path_hint, dir_hint); } -void PlaylistParser::Save(const SongList& songs, const QString& filename) const { +void PlaylistParser::Save(const SongList& songs, + const QString& filename) const { QFileInfo info(filename); // Find a parser that supports this file extension diff --git a/src/playlistparsers/playlistparser.h b/src/playlistparsers/playlistparser.h index b987b8faa..00a82a9f3 100644 --- a/src/playlistparsers/playlistparser.h +++ b/src/playlistparsers/playlistparser.h @@ -29,7 +29,7 @@ class LibraryBackendInterface; class PlaylistParser : public QObject { Q_OBJECT -public: + public: PlaylistParser(LibraryBackendInterface* library, QObject* parent = 0); static const int kMagicSize; @@ -45,17 +45,18 @@ public: ParserBase* ParserForExtension(const QString& suffix) const; SongList LoadFromFile(const QString& filename) const; - SongList LoadFromDevice(QIODevice* device, const QString& path_hint = QString(), + SongList LoadFromDevice(QIODevice* device, + const QString& path_hint = QString(), const QDir& dir_hint = QDir()) const; void Save(const SongList& songs, const QString& filename) const; -private: + private: QString FilterForParser(const ParserBase* parser, QStringList* all_extensions = NULL) const; -private: + private: QList parsers_; ParserBase* default_parser_; }; -#endif // PLAYLISTPARSER_H +#endif // PLAYLISTPARSER_H diff --git a/src/playlistparsers/plsparser.cpp b/src/playlistparsers/plsparser.cpp index 0c105a89e..dd87927c9 100644 --- a/src/playlistparsers/plsparser.cpp +++ b/src/playlistparsers/plsparser.cpp @@ -23,11 +23,10 @@ #include PLSParser::PLSParser(LibraryBackendInterface* library, QObject* parent) - : ParserBase(library, parent) -{ -} + : ParserBase(library, parent) {} -SongList PLSParser::Load(QIODevice *device, const QString& playlist_path, const QDir &dir) const { +SongList PLSParser::Load(QIODevice* device, const QString& playlist_path, + const QDir& dir) const { QMap songs; QRegExp n_re("\\d+$"); @@ -44,8 +43,7 @@ SongList PLSParser::Load(QIODevice *device, const QString& playlist_path, const Song song = LoadSong(value, 0, dir); // Use the title and length we've already loaded if any - if (!songs[n].title().isEmpty()) - song.set_title(songs[n].title()); + if (!songs[n].title().isEmpty()) song.set_title(songs[n].title()); if (songs[n].length_nanosec() != -1) song.set_length_nanosec(songs[n].length_nanosec()); @@ -63,14 +61,15 @@ SongList PLSParser::Load(QIODevice *device, const QString& playlist_path, const return songs.values(); } -void PLSParser::Save(const SongList &songs, QIODevice *device, const QDir &dir) const { +void PLSParser::Save(const SongList& songs, QIODevice* device, + const QDir& dir) const { QTextStream s(device); s << "[playlist]" << endl; s << "Version=2" << endl; s << "NumberOfEntries=" << songs.count() << endl; int n = 1; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { s << "File" << n << "=" << URLOrRelativeFilename(song.url(), dir) << endl; s << "Title" << n << "=" << song.title() << endl; s << "Length" << n << "=" << song.length_nanosec() / kNsecPerSec << endl; diff --git a/src/playlistparsers/plsparser.h b/src/playlistparsers/plsparser.h index 1867baffb..ddc8e8c2d 100644 --- a/src/playlistparsers/plsparser.h +++ b/src/playlistparsers/plsparser.h @@ -23,16 +23,18 @@ class PLSParser : public ParserBase { Q_OBJECT -public: + public: PLSParser(LibraryBackendInterface* library, QObject* parent = 0); QString name() const { return "PLS"; } QStringList file_extensions() const { return QStringList() << "pls"; } - bool TryMagic(const QByteArray &data) const; + bool TryMagic(const QByteArray& data) const; - SongList Load(QIODevice* device, const QString& playlist_path = "", const QDir& dir = QDir()) const; - void Save(const SongList& songs, QIODevice* device, const QDir& dir = QDir()) const; + SongList Load(QIODevice* device, const QString& playlist_path = "", + const QDir& dir = QDir()) const; + void Save(const SongList& songs, QIODevice* device, + const QDir& dir = QDir()) const; }; -#endif // PLSPARSER_H +#endif // PLSPARSER_H diff --git a/src/playlistparsers/wplparser.cpp b/src/playlistparsers/wplparser.cpp index 8f53fd181..3b72424e3 100644 --- a/src/playlistparsers/wplparser.cpp +++ b/src/playlistparsers/wplparser.cpp @@ -22,9 +22,7 @@ #include WplParser::WplParser(LibraryBackendInterface* library, QObject* parent) - : XMLParser(library, parent) -{ -} + : XMLParser(library, parent) {} bool WplParser::TryMagic(const QByteArray& data) const { return data.contains(""); @@ -89,7 +87,8 @@ void WplParser::Save(const SongList& songs, QIODevice* device, { StreamElement head("head", &writer); - WriteMeta("Generator", "Clementine -- " CLEMENTINE_VERSION_DISPLAY, &writer); + WriteMeta("Generator", "Clementine -- " CLEMENTINE_VERSION_DISPLAY, + &writer); WriteMeta("ItemCount", QString::number(songs.count()), &writer); } @@ -97,7 +96,7 @@ void WplParser::Save(const SongList& songs, QIODevice* device, StreamElement body("body", &writer); { StreamElement seq("seq", &writer); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { writer.writeStartElement("media"); writer.writeAttribute("src", URLOrRelativeFilename(song.url(), dir)); writer.writeEndElement(); diff --git a/src/playlistparsers/wplparser.h b/src/playlistparsers/wplparser.h index 54d02d5ca..7853fbefa 100644 --- a/src/playlistparsers/wplparser.h +++ b/src/playlistparsers/wplparser.h @@ -34,11 +34,11 @@ class WplParser : public XMLParser { const QDir& dir) const; void Save(const SongList& songs, QIODevice* device, const QDir& dir) const; -private: + private: void ParseSeq(const QDir& dir, QXmlStreamReader* reader, SongList* songs) const; void WriteMeta(const QString& name, const QString& content, QXmlStreamWriter* writer) const; }; -#endif // WPLPARSER_H +#endif // WPLPARSER_H diff --git a/src/playlistparsers/xmlparser.cpp b/src/playlistparsers/xmlparser.cpp index 68d4d59d5..791869eb9 100644 --- a/src/playlistparsers/xmlparser.cpp +++ b/src/playlistparsers/xmlparser.cpp @@ -25,5 +25,4 @@ #include XMLParser::XMLParser(LibraryBackendInterface* library, QObject* parent) - : ParserBase(library, parent) { -} + : ParserBase(library, parent) {} diff --git a/src/playlistparsers/xmlparser.h b/src/playlistparsers/xmlparser.h index 33750b028..193e4d27c 100644 --- a/src/playlistparsers/xmlparser.h +++ b/src/playlistparsers/xmlparser.h @@ -32,13 +32,12 @@ class XMLParser : public ParserBase { class StreamElement { public: - StreamElement(const QString& name, QXmlStreamWriter* stream) : stream_(stream) { + StreamElement(const QString& name, QXmlStreamWriter* stream) + : stream_(stream) { stream->writeStartElement(name); } - ~StreamElement() { - stream_->writeEndElement(); - } + ~StreamElement() { stream_->writeEndElement(); } private: QXmlStreamWriter* stream_; diff --git a/src/playlistparsers/xspfparser.cpp b/src/playlistparsers/xspfparser.cpp index f394dce84..526b0794f 100644 --- a/src/playlistparsers/xspfparser.cpp +++ b/src/playlistparsers/xspfparser.cpp @@ -27,11 +27,9 @@ #include XSPFParser::XSPFParser(LibraryBackendInterface* library, QObject* parent) - : XMLParser(library, parent) -{ -} + : XMLParser(library, parent) {} -SongList XSPFParser::Load(QIODevice *device, const QString& playlist_path, +SongList XSPFParser::Load(QIODevice* device, const QString& playlist_path, const QDir& dir) const { SongList ret; @@ -102,7 +100,8 @@ return_song: return song; } -void XSPFParser::Save(const SongList& songs, QIODevice* device, const QDir&) const { +void XSPFParser::Save(const SongList& songs, QIODevice* device, + const QDir&) const { QXmlStreamWriter writer(device); writer.setAutoFormatting(true); writer.setAutoFormattingIndent(2); @@ -112,7 +111,7 @@ void XSPFParser::Save(const SongList& songs, QIODevice* device, const QDir&) con writer.writeDefaultNamespace("http://xspf.org/ns/0/"); StreamElement tracklist("trackList", &writer); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { StreamElement track("track", &writer); writer.writeTextElement("location", song.url().toString()); writer.writeTextElement("title", song.title()); @@ -123,10 +122,12 @@ void XSPFParser::Save(const SongList& songs, QIODevice* device, const QDir&) con writer.writeTextElement("album", song.album()); } if (song.length_nanosec() != -1) { - writer.writeTextElement("duration", QString::number(song.length_nanosec() / kNsecPerMsec)); + writer.writeTextElement( + "duration", QString::number(song.length_nanosec() / kNsecPerMsec)); } - QString art = song.art_manual().isEmpty() ? song.art_automatic() : song.art_manual(); + QString art = + song.art_manual().isEmpty() ? song.art_automatic() : song.art_manual(); // Ignore images that are in our resource bundle. if (!art.startsWith(":") && !art.isEmpty()) { // Convert local files to URLs. @@ -139,6 +140,6 @@ void XSPFParser::Save(const SongList& songs, QIODevice* device, const QDir&) con writer.writeEndDocument(); } -bool XSPFParser::TryMagic(const QByteArray &data) const { +bool XSPFParser::TryMagic(const QByteArray& data) const { return data.contains(" - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -26,17 +26,14 @@ #include AddPodcastByUrl::AddPodcastByUrl(Application* app, QWidget* parent) - : AddPodcastPage(app, parent), - ui_(new Ui_AddPodcastByUrl), - loader_(new PodcastUrlLoader(this)) -{ + : AddPodcastPage(app, parent), + ui_(new Ui_AddPodcastByUrl), + loader_(new PodcastUrlLoader(this)) { ui_->setupUi(this); connect(ui_->go, SIGNAL(clicked()), SLOT(GoClicked())); } -AddPodcastByUrl::~AddPodcastByUrl() { - delete ui_; -} +AddPodcastByUrl::~AddPodcastByUrl() { delete ui_; } void AddPodcastByUrl::SetUrlAndGo(const QUrl& url) { ui_->url->setText(url.toString()); @@ -56,9 +53,8 @@ void AddPodcastByUrl::GoClicked() { PodcastUrlLoaderReply* reply = loader_->Load(ui_->url->text()); ui_->url->setText(reply->url().toString()); - NewClosure(reply, SIGNAL(Finished(bool)), - this, SLOT(RequestFinished(PodcastUrlLoaderReply*)), - reply); + NewClosure(reply, SIGNAL(Finished(bool)), this, + SLOT(RequestFinished(PodcastUrlLoaderReply*)), reply); } void AddPodcastByUrl::RequestFinished(PodcastUrlLoaderReply* reply) { @@ -73,15 +69,16 @@ void AddPodcastByUrl::RequestFinished(PodcastUrlLoaderReply* reply) { } switch (reply->result_type()) { - case PodcastUrlLoaderReply::Type_Podcast: - foreach (const Podcast& podcast, reply->podcast_results()) { - model()->appendRow(model()->CreatePodcastItem(podcast)); - } - break; + case PodcastUrlLoaderReply::Type_Podcast: + foreach(const Podcast & podcast, reply->podcast_results()) { + model()->appendRow(model()->CreatePodcastItem(podcast)); + } + break; - case PodcastUrlLoaderReply::Type_Opml: - model()->CreateOpmlContainerItems(reply->opml_results(), model()->invisibleRootItem()); - break; + case PodcastUrlLoaderReply::Type_Opml: + model()->CreateOpmlContainerItems(reply->opml_results(), + model()->invisibleRootItem()); + break; } } @@ -92,8 +89,9 @@ void AddPodcastByUrl::Show() { } const QClipboard* clipboard = QApplication::clipboard(); - foreach (const QString& contents, QStringList() << clipboard->text(QClipboard::Clipboard) - << clipboard->text(QClipboard::Selection)) { + foreach(const QString & contents, + QStringList() << clipboard->text(QClipboard::Clipboard) + << clipboard->text(QClipboard::Selection)) { if (contents.contains("://")) { ui_->url->setText(contents); return; diff --git a/src/podcasts/addpodcastbyurl.h b/src/podcasts/addpodcastbyurl.h index 2da080874..fe3185b81 100644 --- a/src/podcasts/addpodcastbyurl.h +++ b/src/podcasts/addpodcastbyurl.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -30,8 +30,8 @@ class QUrl; class AddPodcastByUrl : public AddPodcastPage { Q_OBJECT - -public: + + public: AddPodcastByUrl(Application* app, QWidget* parent = 0); ~AddPodcastByUrl(); @@ -40,13 +40,13 @@ public: void SetOpml(const OpmlContainer& opml); void SetUrlAndGo(const QUrl& url); -private slots: + private slots: void GoClicked(); void RequestFinished(PodcastUrlLoaderReply* reply); -private: + private: Ui_AddPodcastByUrl* ui_; PodcastUrlLoader* loader_; }; -#endif // ADDPODCASTBYURL_H +#endif // ADDPODCASTBYURL_H diff --git a/src/podcasts/addpodcastdialog.cpp b/src/podcasts/addpodcastdialog.cpp index 97677e980..b18b4e51c 100644 --- a/src/podcasts/addpodcastdialog.cpp +++ b/src/podcasts/addpodcastdialog.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -32,14 +32,14 @@ #include #include -const char* AddPodcastDialog::kBbcOpmlUrl = "http://www.bbc.co.uk/podcasts.opml"; +const char* AddPodcastDialog::kBbcOpmlUrl = + "http://www.bbc.co.uk/podcasts.opml"; AddPodcastDialog::AddPodcastDialog(Application* app, QWidget* parent) - : QDialog(parent), - app_(app), - ui_(new Ui_AddPodcastDialog), - last_opml_path_(QDir::homePath()) -{ + : QDialog(parent), + app_(app), + ui_(new Ui_AddPodcastDialog), + last_opml_path_(QDir::homePath()) { ui_->setupUi(this); ui_->details->SetApplication(app); ui_->results->SetExpandOnReset(false); @@ -48,29 +48,33 @@ AddPodcastDialog::AddPodcastDialog(Application* app, QWidget* parent) fader_ = new WidgetFadeHelper(ui_->details_scroll_area); - connect(ui_->provider_list, SIGNAL(currentRowChanged(int)), SLOT(ChangePage(int))); + connect(ui_->provider_list, SIGNAL(currentRowChanged(int)), + SLOT(ChangePage(int))); connect(ui_->details, SIGNAL(LoadingFinished()), fader_, SLOT(StartFade())); - connect(ui_->results, SIGNAL(doubleClicked(QModelIndex)), SLOT(PodcastDoubleClicked(QModelIndex))); + connect(ui_->results, SIGNAL(doubleClicked(QModelIndex)), + SLOT(PodcastDoubleClicked(QModelIndex))); // Create Add and Remove Podcast buttons - add_button_ = new QPushButton(IconLoader::Load("list-add"), tr("Add Podcast"), this); + add_button_ = + new QPushButton(IconLoader::Load("list-add"), tr("Add Podcast"), this); add_button_->setEnabled(false); connect(add_button_, SIGNAL(clicked()), SLOT(AddPodcast())); ui_->button_box->addButton(add_button_, QDialogButtonBox::ActionRole); - remove_button_ = new QPushButton(IconLoader::Load("list-remove"), tr("Unsubscribe"), this); + remove_button_ = + new QPushButton(IconLoader::Load("list-remove"), tr("Unsubscribe"), this); remove_button_->setEnabled(false); connect(remove_button_, SIGNAL(clicked()), SLOT(RemovePodcast())); ui_->button_box->addButton(remove_button_, QDialogButtonBox::ActionRole); QPushButton* settings_button = new QPushButton( - IconLoader::Load("configure"), tr("Configure podcasts..."), this); + IconLoader::Load("configure"), tr("Configure podcasts..."), this); connect(settings_button, SIGNAL(clicked()), SLOT(OpenSettingsPage())); ui_->button_box->addButton(settings_button, QDialogButtonBox::ResetRole); // Create an Open OPML file button QPushButton* open_opml_button = new QPushButton( - IconLoader::Load("document-open"), tr("Open OPML file..."), this); + IconLoader::Load("document-open"), tr("Open OPML file..."), this); connect(open_opml_button, SIGNAL(clicked()), this, SLOT(OpenOPMLFile())); ui_->button_box->addButton(open_opml_button, QDialogButtonBox::ResetRole); @@ -86,9 +90,7 @@ AddPodcastDialog::AddPodcastDialog(Application* app, QWidget* parent) ui_->provider_list->setCurrentRow(0); } -AddPodcastDialog::~AddPodcastDialog() { - delete ui_; -} +AddPodcastDialog::~AddPodcastDialog() { delete ui_; } void AddPodcastDialog::ShowWithUrl(const QUrl& url) { by_url_page_->SetUrlAndGo(url); @@ -107,7 +109,8 @@ void AddPodcastDialog::AddPage(AddPodcastPage* page) { page_is_busy_.append(false); ui_->stack->addWidget(page); - new QListWidgetItem(page->windowIcon(), page->windowTitle(), ui_->provider_list); + new QListWidgetItem(page->windowIcon(), page->windowTitle(), + ui_->provider_list); connect(page, SIGNAL(Busy(bool)), SLOT(PageBusyChanged(bool))); } @@ -120,9 +123,10 @@ void AddPodcastDialog::ChangePage(int index) { ui_->results->setModel(page->model()); ui_->results_stack->setCurrentWidget( - page_is_busy_[index] ? ui_->busy_page : ui_->results_page); + page_is_busy_[index] ? ui_->busy_page : ui_->results_page); - connect(ui_->results->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), + connect(ui_->results->selectionModel(), + SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), SLOT(ChangePodcast(QModelIndex))); ChangePodcast(QModelIndex()); CurrentPageBusyChanged(page_is_busy_[index]); @@ -169,8 +173,7 @@ void AddPodcastDialog::ChangePodcast(const QModelIndex& current) { void AddPodcastDialog::PageBusyChanged(bool busy) { const int index = pages_.indexOf(qobject_cast(sender())); - if (index == -1) - return; + if (index == -1) return; page_is_busy_[index] = busy; @@ -180,7 +183,8 @@ void AddPodcastDialog::PageBusyChanged(bool busy) { } void AddPodcastDialog::CurrentPageBusyChanged(bool busy) { - ui_->results_stack->setCurrentWidget(busy ? ui_->busy_page : ui_->results_page); + ui_->results_stack->setCurrentWidget(busy ? ui_->busy_page + : ui_->results_page); ui_->stack->setDisabled(busy); QTimer::singleShot(0, this, SLOT(SelectFirstPodcast())); @@ -188,10 +192,11 @@ void AddPodcastDialog::CurrentPageBusyChanged(bool busy) { void AddPodcastDialog::SelectFirstPodcast() { // Select the first item if there was one. - const PodcastDiscoveryModel* model = pages_[ui_->provider_list->currentRow()]->model(); + const PodcastDiscoveryModel* model = + pages_[ui_->provider_list->currentRow()]->model(); if (model->rowCount() > 0) { ui_->results->selectionModel()->setCurrentIndex( - model->index(0, 0), QItemSelectionModel::ClearAndSelect); + model->index(0, 0), QItemSelectionModel::ClearAndSelect); } } @@ -209,7 +214,7 @@ void AddPodcastDialog::PodcastDoubleClicked(const QModelIndex& index) { current_podcast_ = podcast_variant.value(); app_->podcast_backend()->Subscribe(¤t_podcast_); - + add_button_->setEnabled(false); remove_button_->setEnabled(true); } @@ -227,7 +232,7 @@ void AddPodcastDialog::OpenSettingsPage() { void AddPodcastDialog::OpenOPMLFile() { const QString filename = QFileDialog::getOpenFileName( - this, tr("Open OPML file"), last_opml_path_, "OPML files (*.opml)"); + this, tr("Open OPML file"), last_opml_path_, "OPML files (*.opml)"); if (filename.isEmpty()) { return; diff --git a/src/podcasts/addpodcastdialog.h b/src/podcasts/addpodcastdialog.h index fbbf1fc18..19c994370 100644 --- a/src/podcasts/addpodcastdialog.h +++ b/src/podcasts/addpodcastdialog.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -33,8 +33,8 @@ class QModelIndex; class AddPodcastDialog : public QDialog { Q_OBJECT - -public: + + public: AddPodcastDialog(Application* app, QWidget* parent = 0); ~AddPodcastDialog(); @@ -46,7 +46,7 @@ public: void ShowWithUrl(const QUrl& url); void ShowWithOpml(const OpmlContainer& opml); -private slots: + private slots: void OpenSettingsPage(); void AddPodcast(); void PodcastDoubleClicked(const QModelIndex& index); @@ -61,10 +61,10 @@ private slots: void OpenOPMLFile(); -private: + private: void AddPage(AddPodcastPage* page); - -private: + + private: Application* app_; Ui_AddPodcastDialog* ui_; @@ -82,4 +82,4 @@ private: QString last_opml_path_; }; -#endif // ADDPODCASTDIALOG_H +#endif // ADDPODCASTDIALOG_H diff --git a/src/podcasts/addpodcastpage.cpp b/src/podcasts/addpodcastpage.cpp index f9076dfed..d27eb01fa 100644 --- a/src/podcasts/addpodcastpage.cpp +++ b/src/podcasts/addpodcastpage.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -19,10 +19,7 @@ #include "podcastdiscoverymodel.h" AddPodcastPage::AddPodcastPage(Application* app, QWidget* parent) - : QWidget(parent), - model_(new PodcastDiscoveryModel(app, this)) -{ -} + : QWidget(parent), model_(new PodcastDiscoveryModel(app, this)) {} void AddPodcastPage::SetModel(PodcastDiscoveryModel* model) { delete model_; diff --git a/src/podcasts/addpodcastpage.h b/src/podcasts/addpodcastpage.h index 79736545b..43c674a6d 100644 --- a/src/podcasts/addpodcastpage.h +++ b/src/podcasts/addpodcastpage.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -26,7 +26,7 @@ class PodcastDiscoveryModel; class AddPodcastPage : public QWidget { Q_OBJECT -public: + public: AddPodcastPage(Application* app, QWidget* parent = 0); PodcastDiscoveryModel* model() const { return model_; } @@ -37,11 +37,11 @@ public: signals: void Busy(bool busy); -protected: + protected: void SetModel(PodcastDiscoveryModel* model); -private: + private: PodcastDiscoveryModel* model_; }; -#endif // ADDPODCASTPAGE_H +#endif // ADDPODCASTPAGE_H diff --git a/src/podcasts/fixedopmlpage.cpp b/src/podcasts/fixedopmlpage.cpp index 6ec42b041..9c4c78341 100644 --- a/src/podcasts/fixedopmlpage.cpp +++ b/src/podcasts/fixedopmlpage.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -25,11 +25,10 @@ FixedOpmlPage::FixedOpmlPage(const QUrl& opml_url, const QString& title, const QIcon& icon, Application* app, QWidget* parent) - : AddPodcastPage(app, parent), - loader_(new PodcastUrlLoader(this)), - opml_url_(opml_url), - done_initial_load_(false) -{ + : AddPodcastPage(app, parent), + loader_(new PodcastUrlLoader(this)), + opml_url_(opml_url), + done_initial_load_(false) { setWindowTitle(title); setWindowIcon(icon); } @@ -40,9 +39,8 @@ void FixedOpmlPage::Show() { done_initial_load_ = true; PodcastUrlLoaderReply* reply = loader_->Load(opml_url_); - NewClosure(reply, SIGNAL(Finished(bool)), - this, SLOT(LoadFinished(PodcastUrlLoaderReply*)), - reply); + NewClosure(reply, SIGNAL(Finished(bool)), this, + SLOT(LoadFinished(PodcastUrlLoaderReply*)), reply); } } @@ -57,14 +55,15 @@ void FixedOpmlPage::LoadFinished(PodcastUrlLoaderReply* reply) { } switch (reply->result_type()) { - case PodcastUrlLoaderReply::Type_Podcast: - foreach (const Podcast& podcast, reply->podcast_results()) { - model()->appendRow(model()->CreatePodcastItem(podcast)); - } - break; + case PodcastUrlLoaderReply::Type_Podcast: + foreach(const Podcast & podcast, reply->podcast_results()) { + model()->appendRow(model()->CreatePodcastItem(podcast)); + } + break; - case PodcastUrlLoaderReply::Type_Opml: - model()->CreateOpmlContainerItems(reply->opml_results(), model()->invisibleRootItem()); - break; + case PodcastUrlLoaderReply::Type_Opml: + model()->CreateOpmlContainerItems(reply->opml_results(), + model()->invisibleRootItem()); + break; } } diff --git a/src/podcasts/fixedopmlpage.h b/src/podcasts/fixedopmlpage.h index af0315079..c801a5c15 100644 --- a/src/podcasts/fixedopmlpage.h +++ b/src/podcasts/fixedopmlpage.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -28,21 +28,21 @@ class PodcastUrlLoaderReply; class FixedOpmlPage : public AddPodcastPage { Q_OBJECT -public: + public: FixedOpmlPage(const QUrl& opml_url, const QString& title, const QIcon& icon, Application* app, QWidget* parent = 0); bool has_visible_widget() const { return false; } void Show(); -private slots: + private slots: void LoadFinished(PodcastUrlLoaderReply* reply); -private: + private: PodcastUrlLoader* loader_; QUrl opml_url_; bool done_initial_load_; }; -#endif // FIXEDOPMLPAGE_H +#endif // FIXEDOPMLPAGE_H diff --git a/src/podcasts/gpoddersearchpage.cpp b/src/podcasts/gpoddersearchpage.cpp index 024d72692..e862c9659 100644 --- a/src/podcasts/gpoddersearchpage.cpp +++ b/src/podcasts/gpoddersearchpage.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -25,11 +25,10 @@ #include GPodderSearchPage::GPodderSearchPage(Application* app, QWidget* parent) - : AddPodcastPage(app, parent), - ui_(new Ui_GPodderSearchPage), - network_(new NetworkAccessManager(this)), - api_(new mygpo::ApiRequest(network_)) -{ + : AddPodcastPage(app, parent), + ui_(new Ui_GPodderSearchPage), + network_(new NetworkAccessManager(this)), + api_(new mygpo::ApiRequest(network_)) { ui_->setupUi(this); connect(ui_->search, SIGNAL(clicked()), SLOT(SearchClicked())); } @@ -43,15 +42,12 @@ void GPodderSearchPage::SearchClicked() { emit Busy(true); mygpo::PodcastListPtr list(api_->search(ui_->query->text())); - NewClosure(list, SIGNAL(finished()), - this, SLOT(SearchFinished(mygpo::PodcastListPtr)), - list); - NewClosure(list, SIGNAL(parseError()), - this, SLOT(SearchFailed(mygpo::PodcastListPtr)), - list); - NewClosure(list, SIGNAL(requestError(QNetworkReply::NetworkError)), - this, SLOT(SearchFailed(mygpo::PodcastListPtr)), - list); + NewClosure(list, SIGNAL(finished()), this, + SLOT(SearchFinished(mygpo::PodcastListPtr)), list); + NewClosure(list, SIGNAL(parseError()), this, + SLOT(SearchFailed(mygpo::PodcastListPtr)), list); + NewClosure(list, SIGNAL(requestError(QNetworkReply::NetworkError)), this, + SLOT(SearchFailed(mygpo::PodcastListPtr)), list); } void GPodderSearchPage::SearchFinished(mygpo::PodcastListPtr list) { @@ -59,7 +55,7 @@ void GPodderSearchPage::SearchFinished(mygpo::PodcastListPtr list) { model()->clear(); - foreach (mygpo::PodcastPtr gpo_podcast, list->list()) { + foreach(mygpo::PodcastPtr gpo_podcast, list->list()) { Podcast podcast; podcast.InitFromGpo(gpo_podcast.data()); @@ -73,10 +69,10 @@ void GPodderSearchPage::SearchFailed(mygpo::PodcastListPtr list) { model()->clear(); if (QMessageBox::warning( - nullptr, tr("Failed to fetch podcasts"), - tr("There was a problem communicating with gpodder.net"), - QMessageBox::Retry | QMessageBox::Close, - QMessageBox::Retry) != QMessageBox::Retry) { + nullptr, tr("Failed to fetch podcasts"), + tr("There was a problem communicating with gpodder.net"), + QMessageBox::Retry | QMessageBox::Close, + QMessageBox::Retry) != QMessageBox::Retry) { return; } @@ -84,6 +80,4 @@ void GPodderSearchPage::SearchFailed(mygpo::PodcastListPtr list) { SearchClicked(); } -void GPodderSearchPage::Show() { - ui_->query->setFocus(); -} +void GPodderSearchPage::Show() { ui_->query->setFocus(); } diff --git a/src/podcasts/gpoddersearchpage.h b/src/podcasts/gpoddersearchpage.h index 02dc750a2..c16fa25f7 100644 --- a/src/podcasts/gpoddersearchpage.h +++ b/src/podcasts/gpoddersearchpage.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -29,23 +29,22 @@ class Ui_GPodderSearchPage; class GPodderSearchPage : public AddPodcastPage { Q_OBJECT -public: + public: GPodderSearchPage(Application* app, QWidget* parent = 0); ~GPodderSearchPage(); void Show(); -private slots: + private slots: void SearchClicked(); void SearchFinished(mygpo::PodcastListPtr list); void SearchFailed(mygpo::PodcastListPtr list); -private: + private: Ui_GPodderSearchPage* ui_; QNetworkAccessManager* network_; mygpo::ApiRequest* api_; - }; -#endif // GPODDERSEARCHPAGE_H +#endif // GPODDERSEARCHPAGE_H diff --git a/src/podcasts/gpoddersync.cpp b/src/podcasts/gpoddersync.cpp index 4110f56cb..6dfcd9dad 100644 --- a/src/podcasts/gpoddersync.cpp +++ b/src/podcasts/gpoddersync.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -33,25 +33,27 @@ #include const char* GPodderSync::kSettingsGroup = "Podcasts"; -const int GPodderSync::kFlushUpdateQueueDelay = 30 * kMsecPerSec; // 30 seconds -const int GPodderSync::kGetUpdatesInterval = 30*60 * kMsecPerSec; // 30 minutes +const int GPodderSync::kFlushUpdateQueueDelay = 30 * kMsecPerSec; // 30 seconds +const int GPodderSync::kGetUpdatesInterval = + 30 * 60 * kMsecPerSec; // 30 minutes GPodderSync::GPodderSync(Application* app, QObject* parent) - : QObject(parent), - app_(app), - network_(new NetworkAccessManager(this)), - backend_(app_->podcast_backend()), - loader_(new PodcastUrlLoader(this)), - get_updates_timer_(new QTimer(this)), - flush_queue_timer_(new QTimer(this)), - flushing_queue_(false) -{ + : QObject(parent), + app_(app), + network_(new NetworkAccessManager(this)), + backend_(app_->podcast_backend()), + loader_(new PodcastUrlLoader(this)), + get_updates_timer_(new QTimer(this)), + flush_queue_timer_(new QTimer(this)), + flushing_queue_(false) { ReloadSettings(); LoadQueue(); connect(app_, SIGNAL(SettingsChanged()), SLOT(ReloadSettings())); - connect(backend_, SIGNAL(SubscriptionAdded(Podcast)), SLOT(SubscriptionAdded(Podcast))); - connect(backend_, SIGNAL(SubscriptionRemoved(Podcast)), SLOT(SubscriptionRemoved(Podcast))); + connect(backend_, SIGNAL(SubscriptionAdded(Podcast)), + SLOT(SubscriptionAdded(Podcast))); + connect(backend_, SIGNAL(SubscriptionRemoved(Podcast)), + SLOT(SubscriptionRemoved(Podcast))); get_updates_timer_->setInterval(kGetUpdatesInterval); connect(get_updates_timer_, SIGNAL(timeout()), SLOT(GetUpdatesNow())); @@ -67,17 +69,17 @@ GPodderSync::GPodderSync(Application* app, QObject* parent) } } -GPodderSync::~GPodderSync() { -} +GPodderSync::~GPodderSync() {} QString GPodderSync::DeviceId() { - return QString("%1-%2").arg(qApp->applicationName(), - QHostInfo::localHostName()).toLower(); + return QString("%1-%2") + .arg(qApp->applicationName(), QHostInfo::localHostName()) + .toLower(); } QString GPodderSync::DefaultDeviceName() { - return tr("%1 on %2").arg(qApp->applicationName(), - QHostInfo::localHostName()); + return tr("%1 on %2") + .arg(qApp->applicationName(), QHostInfo::localHostName()); } bool GPodderSync::is_logged_in() const { @@ -97,22 +99,22 @@ void GPodderSync::ReloadSettings() { } } -QNetworkReply* GPodderSync::Login(const QString& username, const QString& password, +QNetworkReply* GPodderSync::Login(const QString& username, + const QString& password, const QString& device_name) { api_.reset(new mygpo::ApiRequest(username, password, network_)); QNetworkReply* reply = api_->renameDevice( - username, DeviceId(), device_name, - Utilities::IsLaptop() ? mygpo::Device::LAPTOP - : mygpo::Device::DESKTOP); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(LoginFinished(QNetworkReply*,QString,QString)), - reply, username, password); + username, DeviceId(), device_name, + Utilities::IsLaptop() ? mygpo::Device::LAPTOP : mygpo::Device::DESKTOP); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(LoginFinished(QNetworkReply*, QString, QString)), reply, + username, password); return reply; } -void GPodderSync::LoginFinished(QNetworkReply* reply, - const QString& username, const QString& password) { +void GPodderSync::LoginFinished(QNetworkReply* reply, const QString& username, + const QString& password) { reply->deleteLater(); if (reply->error() == QNetworkReply::NoError) { @@ -141,24 +143,21 @@ void GPodderSync::Logout() { } void GPodderSync::GetUpdatesNow() { - if (!is_logged_in()) - return; + if (!is_logged_in()) return; qlonglong timestamp = 0; if (last_successful_get_.isValid()) { timestamp = last_successful_get_.toTime_t(); } - mygpo::DeviceUpdatesPtr reply(api_->deviceUpdates(username_, DeviceId(), timestamp)); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(DeviceUpdatesFinished(mygpo::DeviceUpdatesPtr)), - reply); - NewClosure(reply, SIGNAL(parseError()), - this, SLOT(DeviceUpdatesFailed(mygpo::DeviceUpdatesPtr)), - reply); - NewClosure(reply, SIGNAL(requestError(QNetworkReply::NetworkError)), - this, SLOT(DeviceUpdatesFailed(mygpo::DeviceUpdatesPtr)), - reply); + mygpo::DeviceUpdatesPtr reply( + api_->deviceUpdates(username_, DeviceId(), timestamp)); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(DeviceUpdatesFinished(mygpo::DeviceUpdatesPtr)), reply); + NewClosure(reply, SIGNAL(parseError()), this, + SLOT(DeviceUpdatesFailed(mygpo::DeviceUpdatesPtr)), reply); + NewClosure(reply, SIGNAL(requestError(QNetworkReply::NetworkError)), this, + SLOT(DeviceUpdatesFailed(mygpo::DeviceUpdatesPtr)), reply); } void GPodderSync::DeviceUpdatesFailed(mygpo::DeviceUpdatesPtr reply) { @@ -169,18 +168,19 @@ void GPodderSync::DeviceUpdatesFinished(mygpo::DeviceUpdatesPtr reply) { // Remember episode actions for each podcast, so when we add a new podcast // we can apply the actions immediately. QMap > episodes_by_podcast; - foreach (mygpo::EpisodePtr episode, reply->updateList()) { + foreach(mygpo::EpisodePtr episode, reply->updateList()) { episodes_by_podcast[episode->podcastUrl()].append(episode); } - foreach (mygpo::PodcastPtr podcast, reply->addList()) { + foreach(mygpo::PodcastPtr podcast, reply->addList()) { const QUrl url(podcast->url()); // Are we subscribed to this podcast already? Podcast existing_podcast = backend_->GetSubscriptionByUrl(url); if (existing_podcast.is_valid()) { // Just apply actions to this existing podcast - ApplyActions(episodes_by_podcast[url], existing_podcast.mutable_episodes()); + ApplyActions(episodes_by_podcast[url], + existing_podcast.mutable_episodes()); backend_->UpdateEpisodes(existing_podcast.episodes()); continue; } @@ -188,13 +188,14 @@ void GPodderSync::DeviceUpdatesFinished(mygpo::DeviceUpdatesPtr reply) { // Start loading the podcast. Remember actions and apply them after we // have a list of the episodes. PodcastUrlLoaderReply* loader_reply = loader_->Load(url); - NewClosure(loader_reply, SIGNAL(Finished(bool)), - this, SLOT(NewPodcastLoaded(PodcastUrlLoaderReply*,QUrl,QList)), + NewClosure(loader_reply, SIGNAL(Finished(bool)), this, + SLOT(NewPodcastLoaded(PodcastUrlLoaderReply*, QUrl, + QList)), loader_reply, url, episodes_by_podcast[url]); } // Unsubscribe from podcasts that were removed. - foreach (const QUrl& url, reply->removeList()) { + foreach(const QUrl & url, reply->removeList()) { backend_->Unsubscribe(backend_->GetSubscriptionByUrl(url)); } @@ -205,7 +206,8 @@ void GPodderSync::DeviceUpdatesFinished(mygpo::DeviceUpdatesPtr reply) { s.setValue("gpodder_last_get", last_successful_get_); } -void GPodderSync::NewPodcastLoaded(PodcastUrlLoaderReply* reply, const QUrl& url, +void GPodderSync::NewPodcastLoaded(PodcastUrlLoaderReply* reply, + const QUrl& url, const QList& actions) { reply->deleteLater(); @@ -221,7 +223,7 @@ void GPodderSync::NewPodcastLoaded(PodcastUrlLoaderReply* reply, const QUrl& url } // Apply the actions to the episodes in the podcast. - foreach (Podcast podcast, reply->podcast_results()) { + foreach(Podcast podcast, reply->podcast_results()) { ApplyActions(actions, podcast.mutable_episodes()); // Add the subscription @@ -229,23 +231,23 @@ void GPodderSync::NewPodcastLoaded(PodcastUrlLoaderReply* reply, const QUrl& url } } -void GPodderSync::ApplyActions(const QList >& actions, - PodcastEpisodeList* episodes) { - for (PodcastEpisodeList::iterator it = episodes->begin() ; - it != episodes->end() ; ++it) { +void GPodderSync::ApplyActions( + const QList >& actions, + PodcastEpisodeList* episodes) { + for (PodcastEpisodeList::iterator it = episodes->begin(); + it != episodes->end(); ++it) { // Find an action for this episode - foreach (mygpo::EpisodePtr action, actions) { - if (action->url() != it->url()) - continue; + foreach(mygpo::EpisodePtr action, actions) { + if (action->url() != it->url()) continue; switch (action->status()) { - case mygpo::Episode::PLAY: - case mygpo::Episode::DOWNLOAD: - it->set_listened(true); - break; + case mygpo::Episode::PLAY: + case mygpo::Episode::DOWNLOAD: + it->set_listened(true); + break; - default: - break; + default: + break; } break; } @@ -253,8 +255,7 @@ void GPodderSync::ApplyActions(const QList >& act } void GPodderSync::SubscriptionAdded(const Podcast& podcast) { - if (!is_logged_in()) - return; + if (!is_logged_in()) return; const QUrl& url = podcast.url(); @@ -266,8 +267,7 @@ void GPodderSync::SubscriptionAdded(const Podcast& podcast) { } void GPodderSync::SubscriptionRemoved(const Podcast& podcast) { - if (!is_logged_in()) - return; + if (!is_logged_in()) return; const QUrl& url = podcast.url(); @@ -279,72 +279,72 @@ void GPodderSync::SubscriptionRemoved(const Podcast& podcast) { } namespace { - template - void WriteContainer(const T& container, QSettings* s, const char* array_name, - const char* item_name) { - s->beginWriteArray(array_name, container.count()); - int index = 0; - foreach (const typename T::value_type& item, container) { - s->setArrayIndex(index ++); - s->setValue(item_name, item); - } - s->endArray(); +template +void WriteContainer(const T& container, QSettings* s, const char* array_name, + const char* item_name) { + s->beginWriteArray(array_name, container.count()); + int index = 0; + foreach(const typename T::value_type & item, container) { + s->setArrayIndex(index++); + s->setValue(item_name, item); } + s->endArray(); +} - template - void ReadContainer(T* container, QSettings* s, const char* array_name, - const char* item_name) { - container->clear(); - const int count = s->beginReadArray(array_name); - for (int i=0 ; isetArrayIndex(i); - *container << s->value(item_name).value(); - } - s->endArray(); +template +void ReadContainer(T* container, QSettings* s, const char* array_name, + const char* item_name) { + container->clear(); + const int count = s->beginReadArray(array_name); + for (int i = 0; i < count; ++i) { + s->setArrayIndex(i); + *container << s->value(item_name).value(); } + s->endArray(); +} } void GPodderSync::SaveQueue() { QSettings s; s.beginGroup(kSettingsGroup); - WriteContainer(queued_add_subscriptions_, &s, "gpodder_queued_add_subscriptions", "url"); - WriteContainer(queued_remove_subscriptions_, &s, "gpodder_queued_remove_subscriptions", "url"); + WriteContainer(queued_add_subscriptions_, &s, + "gpodder_queued_add_subscriptions", "url"); + WriteContainer(queued_remove_subscriptions_, &s, + "gpodder_queued_remove_subscriptions", "url"); } void GPodderSync::LoadQueue() { QSettings s; s.beginGroup(kSettingsGroup); - ReadContainer(&queued_add_subscriptions_, &s, "gpodder_queued_add_subscriptions", "url"); - ReadContainer(&queued_remove_subscriptions_, &s, "gpodder_queued_remove_subscriptions", "url"); + ReadContainer(&queued_add_subscriptions_, &s, + "gpodder_queued_add_subscriptions", "url"); + ReadContainer(&queued_remove_subscriptions_, &s, + "gpodder_queued_remove_subscriptions", "url"); } void GPodderSync::FlushUpdateQueue() { - if (!is_logged_in() || flushing_queue_) - return; + if (!is_logged_in() || flushing_queue_) return; - QSet all_urls = queued_add_subscriptions_ + queued_remove_subscriptions_; - if (all_urls.isEmpty()) - return; + QSet all_urls = + queued_add_subscriptions_ + queued_remove_subscriptions_; + if (all_urls.isEmpty()) return; flushing_queue_ = true; - mygpo::AddRemoveResultPtr reply( - api_->addRemoveSubscriptions(username_, DeviceId(), - queued_add_subscriptions_.toList(), - queued_remove_subscriptions_.toList())); + mygpo::AddRemoveResultPtr reply(api_->addRemoveSubscriptions( + username_, DeviceId(), queued_add_subscriptions_.toList(), + queued_remove_subscriptions_.toList())); qLog(Info) << "Sending" << all_urls.count() << "changes to gpodder.net"; - NewClosure(reply, SIGNAL(finished()), - this, SLOT(AddRemoveFinished(mygpo::AddRemoveResultPtr,QList)), + NewClosure(reply, SIGNAL(finished()), this, + SLOT(AddRemoveFinished(mygpo::AddRemoveResultPtr, QList)), reply, all_urls.toList()); - NewClosure(reply, SIGNAL(parseError()), - this, SLOT(AddRemoveFailed(mygpo::AddRemoveResultPtr)), - reply); - NewClosure(reply, SIGNAL(requestError(QNetworkReply::NetworkError)), - this, SLOT(AddRemoveFailed(mygpo::AddRemoveResultPtr)), - reply); + NewClosure(reply, SIGNAL(parseError()), this, + SLOT(AddRemoveFailed(mygpo::AddRemoveResultPtr)), reply); + NewClosure(reply, SIGNAL(requestError(QNetworkReply::NetworkError)), this, + SLOT(AddRemoveFailed(mygpo::AddRemoveResultPtr)), reply); } void GPodderSync::AddRemoveFailed(mygpo::AddRemoveResultPtr reply) { @@ -357,7 +357,7 @@ void GPodderSync::AddRemoveFinished(mygpo::AddRemoveResultPtr reply, flushing_queue_ = false; // Remove the URLs from the queue. - foreach (const QUrl& url, affected_urls) { + foreach(const QUrl & url, affected_urls) { queued_add_subscriptions_.remove(url); queued_remove_subscriptions_.remove(url); } @@ -365,7 +365,8 @@ void GPodderSync::AddRemoveFinished(mygpo::AddRemoveResultPtr reply, SaveQueue(); // Did more change in the mean time? - if (!queued_add_subscriptions_.isEmpty() || !queued_remove_subscriptions_.isEmpty()) { + if (!queued_add_subscriptions_.isEmpty() || + !queued_remove_subscriptions_.isEmpty()) { flush_queue_timer_->start(); } } @@ -378,7 +379,7 @@ void GPodderSync::DoInitialSync() { // Send our complete list of subscriptions queued_remove_subscriptions_.clear(); queued_add_subscriptions_.clear(); - foreach (const Podcast& podcast, backend_->GetAllSubscriptions()) { + foreach(const Podcast & podcast, backend_->GetAllSubscriptions()) { queued_add_subscriptions_.insert(podcast.url()); } diff --git a/src/podcasts/gpoddersync.h b/src/podcasts/gpoddersync.h index 9ba6b1e6e..0a3683925 100644 --- a/src/podcasts/gpoddersync.h +++ b/src/podcasts/gpoddersync.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -42,7 +42,7 @@ class QTimer; class GPodderSync : public QObject { Q_OBJECT -public: + public: GPodderSync(Application* app, QObject* parent = 0); ~GPodderSync(); @@ -65,13 +65,13 @@ public: // Clears any saved username and password from QSettings. void Logout(); -public slots: + public slots: void GetUpdatesNow(); -private slots: + private slots: void ReloadSettings(); - void LoginFinished(QNetworkReply* reply, - const QString& username, const QString& password); + void LoginFinished(QNetworkReply* reply, const QString& username, + const QString& password); void DeviceUpdatesFinished(mygpo::DeviceUpdatesPtr reply); void DeviceUpdatesFailed(mygpo::DeviceUpdatesPtr reply); @@ -90,13 +90,13 @@ private slots: const QList& affected_urls); void AddRemoveFailed(mygpo::AddRemoveResultPtr reply); -private: + private: void LoadQueue(); void SaveQueue(); void DoInitialSync(); -private: + private: Application* app_; QNetworkAccessManager* network_; QScopedPointer api_; @@ -115,4 +115,4 @@ private: bool flushing_queue_; }; -#endif // GPODDERSYNC_H +#endif // GPODDERSYNC_H diff --git a/src/podcasts/gpoddertoptagsmodel.cpp b/src/podcasts/gpoddertoptagsmodel.cpp index 9a4ec569e..a42277cfd 100644 --- a/src/podcasts/gpoddertoptagsmodel.cpp +++ b/src/podcasts/gpoddertoptagsmodel.cpp @@ -24,16 +24,12 @@ #include -GPodderTopTagsModel::GPodderTopTagsModel(mygpo::ApiRequest* api, Application* app, - QObject* parent) - : PodcastDiscoveryModel(app, parent), - api_(api) -{ -} +GPodderTopTagsModel::GPodderTopTagsModel(mygpo::ApiRequest* api, + Application* app, QObject* parent) + : PodcastDiscoveryModel(app, parent), api_(api) {} bool GPodderTopTagsModel::hasChildren(const QModelIndex& parent) const { - if (parent.isValid() && - parent.data(Role_Type).toInt() == Type_Folder) { + if (parent.isValid() && parent.data(Role_Type).toInt() == Type_Folder) { return true; } @@ -41,8 +37,7 @@ bool GPodderTopTagsModel::hasChildren(const QModelIndex& parent) const { } bool GPodderTopTagsModel::canFetchMore(const QModelIndex& parent) const { - if (parent.isValid() && - parent.data(Role_Type).toInt() == Type_Folder && + if (parent.isValid() && parent.data(Role_Type).toInt() == Type_Folder && parent.data(Role_HasLazyLoaded).toBool() == false) { return true; } @@ -51,8 +46,7 @@ bool GPodderTopTagsModel::canFetchMore(const QModelIndex& parent) const { } void GPodderTopTagsModel::fetchMore(const QModelIndex& parent) { - if (!parent.isValid() || - parent.data(Role_Type).toInt() != Type_Folder || + if (!parent.isValid() || parent.data(Role_Type).toInt() != Type_Folder || parent.data(Role_HasLazyLoaded).toBool()) { return; } @@ -61,32 +55,31 @@ void GPodderTopTagsModel::fetchMore(const QModelIndex& parent) { // Create a little Loading... item. itemFromIndex(parent)->appendRow(CreateLoadingIndicator()); - mygpo::PodcastListPtr list( - api_->podcastsOfTag(GPodderTopTagsPage::kMaxTagCount, parent.data().toString())); + mygpo::PodcastListPtr list(api_->podcastsOfTag( + GPodderTopTagsPage::kMaxTagCount, parent.data().toString())); - NewClosure(list, SIGNAL(finished()), - this, SLOT(PodcastsOfTagFinished(QModelIndex,mygpo::PodcastList*)), + NewClosure(list, SIGNAL(finished()), this, + SLOT(PodcastsOfTagFinished(QModelIndex, mygpo::PodcastList*)), parent, list.data()); - NewClosure(list, SIGNAL(parseError()), - this, SLOT(PodcastsOfTagFailed(QModelIndex,mygpo::PodcastList*)), + NewClosure(list, SIGNAL(parseError()), this, + SLOT(PodcastsOfTagFailed(QModelIndex, mygpo::PodcastList*)), parent, list.data()); - NewClosure(list, SIGNAL(requestError(QNetworkReply::NetworkError)), - this, SLOT(PodcastsOfTagFailed(QModelIndex,mygpo::PodcastList*)), + NewClosure(list, SIGNAL(requestError(QNetworkReply::NetworkError)), this, + SLOT(PodcastsOfTagFailed(QModelIndex, mygpo::PodcastList*)), parent, list.data()); } void GPodderTopTagsModel::PodcastsOfTagFinished(const QModelIndex& parent, mygpo::PodcastList* list) { QStandardItem* parent_item = itemFromIndex(parent); - if (!parent_item) - return; + if (!parent_item) return; // Remove the Loading... item. while (parent_item->hasChildren()) { parent_item->removeRow(0); } - foreach (mygpo::PodcastPtr gpo_podcast, list->list()) { + foreach(mygpo::PodcastPtr gpo_podcast, list->list()) { Podcast podcast; podcast.InitFromGpo(gpo_podcast.data()); @@ -97,8 +90,7 @@ void GPodderTopTagsModel::PodcastsOfTagFinished(const QModelIndex& parent, void GPodderTopTagsModel::PodcastsOfTagFailed(const QModelIndex& parent, mygpo::PodcastList* list) { QStandardItem* parent_item = itemFromIndex(parent); - if (!parent_item) - return; + if (!parent_item) return; // Remove the Loading... item. while (parent_item->hasChildren()) { @@ -106,10 +98,10 @@ void GPodderTopTagsModel::PodcastsOfTagFailed(const QModelIndex& parent, } if (QMessageBox::warning( - nullptr, tr("Failed to fetch podcasts"), - tr("There was a problem communicating with gpodder.net"), - QMessageBox::Retry | QMessageBox::Close, - QMessageBox::Retry) != QMessageBox::Retry) { + nullptr, tr("Failed to fetch podcasts"), + tr("There was a problem communicating with gpodder.net"), + QMessageBox::Retry | QMessageBox::Close, + QMessageBox::Retry) != QMessageBox::Retry) { return; } diff --git a/src/podcasts/gpoddertoptagsmodel.h b/src/podcasts/gpoddertoptagsmodel.h index a3794b660..0e0fbce8c 100644 --- a/src/podcasts/gpoddertoptagsmodel.h +++ b/src/podcasts/gpoddertoptagsmodel.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -21,20 +21,19 @@ #include "podcastdiscoverymodel.h" namespace mygpo { - class ApiRequest; - class PodcastList; +class ApiRequest; +class PodcastList; } class GPodderTopTagsModel : public PodcastDiscoveryModel { Q_OBJECT -public: + public: GPodderTopTagsModel(mygpo::ApiRequest* api, Application* app, QObject* parent = 0); enum Role { Role_HasLazyLoaded = PodcastDiscoveryModel::RoleCount, - RoleCount }; @@ -42,12 +41,13 @@ public: bool canFetchMore(const QModelIndex& parent) const; void fetchMore(const QModelIndex& parent); -private slots: - void PodcastsOfTagFinished(const QModelIndex& parent, mygpo::PodcastList* list); + private slots: + void PodcastsOfTagFinished(const QModelIndex& parent, + mygpo::PodcastList* list); void PodcastsOfTagFailed(const QModelIndex& parent, mygpo::PodcastList* list); -private: + private: mygpo::ApiRequest* api_; }; -#endif // GPODDERTOPTAGSMODEL_H +#endif // GPODDERTOPTAGSMODEL_H diff --git a/src/podcasts/gpoddertoptagspage.cpp b/src/podcasts/gpoddertoptagspage.cpp index 47c24b357..0936a14f7 100644 --- a/src/podcasts/gpoddertoptagspage.cpp +++ b/src/podcasts/gpoddertoptagspage.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -24,22 +24,18 @@ const int GPodderTopTagsPage::kMaxTagCount = 100; - GPodderTopTagsPage::GPodderTopTagsPage(Application* app, QWidget* parent) - : AddPodcastPage(app, parent), - network_(new NetworkAccessManager(this)), - api_(new mygpo::ApiRequest(network_)), - done_initial_load_(false) -{ + : AddPodcastPage(app, parent), + network_(new NetworkAccessManager(this)), + api_(new mygpo::ApiRequest(network_)), + done_initial_load_(false) { setWindowTitle(tr("gpodder.net directory")); setWindowIcon(QIcon(":providers/mygpo32.png")); SetModel(new GPodderTopTagsModel(api_, app, this)); } -GPodderTopTagsPage::~GPodderTopTagsPage() { - delete api_; -} +GPodderTopTagsPage::~GPodderTopTagsPage() { delete api_; } void GPodderTopTagsPage::Show() { if (!done_initial_load_) { @@ -48,22 +44,19 @@ void GPodderTopTagsPage::Show() { done_initial_load_ = true; mygpo::TagListPtr tag_list(api_->topTags(kMaxTagCount)); - NewClosure(tag_list, SIGNAL(finished()), - this, SLOT(TagListLoaded(mygpo::TagListPtr)), - tag_list); - NewClosure(tag_list, SIGNAL(parseError()), - this, SLOT(TagListFailed(mygpo::TagListPtr)), - tag_list); + NewClosure(tag_list, SIGNAL(finished()), this, + SLOT(TagListLoaded(mygpo::TagListPtr)), tag_list); + NewClosure(tag_list, SIGNAL(parseError()), this, + SLOT(TagListFailed(mygpo::TagListPtr)), tag_list); NewClosure(tag_list, SIGNAL(requestError(QNetworkReply::NetworkError)), - this, SLOT(TagListFailed(mygpo::TagListPtr)), - tag_list); + this, SLOT(TagListFailed(mygpo::TagListPtr)), tag_list); } } void GPodderTopTagsPage::TagListLoaded(mygpo::TagListPtr tag_list) { emit Busy(false); - foreach (mygpo::TagPtr tag, tag_list->list()) { + foreach(mygpo::TagPtr tag, tag_list->list()) { model()->appendRow(model()->CreateFolder(tag->tag())); } } @@ -73,10 +66,10 @@ void GPodderTopTagsPage::TagListFailed(mygpo::TagListPtr list) { done_initial_load_ = false; if (QMessageBox::warning( - nullptr, tr("Failed to fetch directory"), - tr("There was a problem communicating with gpodder.net"), - QMessageBox::Retry | QMessageBox::Close, - QMessageBox::Retry) != QMessageBox::Retry) { + nullptr, tr("Failed to fetch directory"), + tr("There was a problem communicating with gpodder.net"), + QMessageBox::Retry | QMessageBox::Close, + QMessageBox::Retry) != QMessageBox::Retry) { return; } diff --git a/src/podcasts/gpoddertoptagspage.h b/src/podcasts/gpoddertoptagspage.h index 320297945..79cc932fb 100644 --- a/src/podcasts/gpoddertoptagspage.h +++ b/src/podcasts/gpoddertoptagspage.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -29,7 +29,7 @@ class QNetworkAccessManager; class GPodderTopTagsPage : public AddPodcastPage { Q_OBJECT -public: + public: GPodderTopTagsPage(Application* app, QWidget* parent = 0); ~GPodderTopTagsPage(); @@ -38,15 +38,15 @@ public: virtual bool has_visible_widget() const { return false; } virtual void Show(); -private slots: + private slots: void TagListLoaded(mygpo::TagListPtr tag_list); void TagListFailed(mygpo::TagListPtr tag_list); -private: + private: QNetworkAccessManager* network_; mygpo::ApiRequest* api_; bool done_initial_load_; }; -#endif // GPODDERTOPTAGSPAGE_H +#endif // GPODDERTOPTAGSPAGE_H diff --git a/src/podcasts/itunessearchpage.cpp b/src/podcasts/itunessearchpage.cpp index 4c4a92e8c..945c14c6a 100644 --- a/src/podcasts/itunessearchpage.cpp +++ b/src/podcasts/itunessearchpage.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -28,20 +28,18 @@ #include const char* ITunesSearchPage::kUrlBase = - "http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?country=US&media=podcast"; + "http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/" + "wa/wsSearch?country=US&media=podcast"; ITunesSearchPage::ITunesSearchPage(Application* app, QWidget* parent) - : AddPodcastPage(app, parent), - ui_(new Ui_ITunesSearchPage), - network_(new NetworkAccessManager(this)) -{ + : AddPodcastPage(app, parent), + ui_(new Ui_ITunesSearchPage), + network_(new NetworkAccessManager(this)) { ui_->setupUi(this); connect(ui_->search, SIGNAL(clicked()), SLOT(SearchClicked())); } -ITunesSearchPage::~ITunesSearchPage() { - delete ui_; -} +ITunesSearchPage::~ITunesSearchPage() { delete ui_; } void ITunesSearchPage::SearchClicked() { emit Busy(true); @@ -50,9 +48,8 @@ void ITunesSearchPage::SearchClicked() { url.addQueryItem("term", ui_->query->text()); QNetworkReply* reply = network_->get(QNetworkRequest(url)); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(SearchFinished(QNetworkReply*)), - reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(SearchFinished(QNetworkReply*)), reply); } void ITunesSearchPage::SearchFinished(QNetworkReply* reply) { @@ -63,7 +60,8 @@ void ITunesSearchPage::SearchFinished(QNetworkReply* reply) { // Was there a network error? if (reply->error() != QNetworkReply::NoError) { - QMessageBox::warning(this, tr("Failed to fetch podcasts"), reply->errorString()); + QMessageBox::warning(this, tr("Failed to fetch podcasts"), + reply->errorString()); return; } @@ -72,8 +70,9 @@ void ITunesSearchPage::SearchFinished(QNetworkReply* reply) { // Was it valid JSON? if (data.isNull()) { - QMessageBox::warning(this, tr("Failed to fetch podcasts"), - tr("There was a problem parsing the response from the iTunes Store")); + QMessageBox::warning( + this, tr("Failed to fetch podcasts"), + tr("There was a problem parsing the response from the iTunes Store")); return; } @@ -84,7 +83,7 @@ void ITunesSearchPage::SearchFinished(QNetworkReply* reply) { return; } - foreach (const QVariant& result_variant, data.toMap()["results"].toList()) { + foreach(const QVariant & result_variant, data.toMap()["results"].toList()) { QVariantMap result(result_variant.toMap()); if (result["kind"].toString() != "podcast") { continue; @@ -102,6 +101,4 @@ void ITunesSearchPage::SearchFinished(QNetworkReply* reply) { } } -void ITunesSearchPage::Show() { - ui_->query->setFocus(); -} +void ITunesSearchPage::Show() { ui_->query->setFocus(); } diff --git a/src/podcasts/itunessearchpage.h b/src/podcasts/itunessearchpage.h index d898138c7..dce87da5c 100644 --- a/src/podcasts/itunessearchpage.h +++ b/src/podcasts/itunessearchpage.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -28,7 +28,7 @@ class QNetworkReply; class ITunesSearchPage : public AddPodcastPage { Q_OBJECT -public: + public: ITunesSearchPage(Application* app, QWidget* parent); ~ITunesSearchPage(); @@ -36,14 +36,14 @@ public: static const char* kUrlBase; -private slots: + private slots: void SearchClicked(); void SearchFinished(QNetworkReply* reply); -private: + private: Ui_ITunesSearchPage* ui_; QNetworkAccessManager* network_; }; -#endif // ITUNESSEARCHPAGE_H +#endif // ITUNESSEARCHPAGE_H diff --git a/src/podcasts/opmlcontainer.h b/src/podcasts/opmlcontainer.h index 425542352..9e2d30fb6 100644 --- a/src/podcasts/opmlcontainer.h +++ b/src/podcasts/opmlcontainer.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -21,7 +21,7 @@ #include "podcast.h" class OpmlContainer { -public: + public: // Only set for the top-level container QUrl url; @@ -32,4 +32,4 @@ public: Q_DECLARE_METATYPE(OpmlContainer) -#endif // OPMLCONTAINER_H +#endif // OPMLCONTAINER_H diff --git a/src/podcasts/podcast.cpp b/src/podcasts/podcast.cpp index e666a499d..ee277d296 100644 --- a/src/podcasts/podcast.cpp +++ b/src/podcasts/podcast.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -23,16 +23,27 @@ #include -const QStringList Podcast::kColumns = QStringList() - << "url" << "title" << "description" << "copyright" << "link" - << "image_url_large" << "image_url_small" << "author" << "owner_name" - << "owner_email" << "last_updated" << "last_update_error" << "extra"; +const QStringList Podcast::kColumns = QStringList() << "url" + << "title" + << "description" + << "copyright" + << "link" + << "image_url_large" + << "image_url_small" + << "author" + << "owner_name" + << "owner_email" + << "last_updated" + << "last_update_error" + << "extra"; const QString Podcast::kColumnSpec = Podcast::kColumns.join(", "); -const QString Podcast::kJoinSpec = Utilities::Prepend("p.", Podcast::kColumns).join(", "); -const QString Podcast::kBindSpec = Utilities::Prepend(":", Podcast::kColumns).join(", "); -const QString Podcast::kUpdateSpec = Utilities::Updateify(Podcast::kColumns).join(", "); - +const QString Podcast::kJoinSpec = + Utilities::Prepend("p.", Podcast::kColumns).join(", "); +const QString Podcast::kBindSpec = + Utilities::Prepend(":", Podcast::kColumns).join(", "); +const QString Podcast::kUpdateSpec = + Utilities::Updateify(Podcast::kColumns).join(", "); struct Podcast::Private : public QSharedData { Private(); @@ -61,26 +72,15 @@ struct Podcast::Private : public QSharedData { PodcastEpisodeList episodes_; }; -Podcast::Private::Private() - : database_id_(-1) -{ -} +Podcast::Private::Private() : database_id_(-1) {} +Podcast::Podcast() : d(new Private) {} -Podcast::Podcast() - : d(new Private) -{ -} +Podcast::Podcast(const Podcast& other) : d(other.d) {} -Podcast::Podcast(const Podcast& other) - : d(other.d) -{ -} +Podcast::~Podcast() {} -Podcast::~Podcast() { -} - -Podcast& Podcast::operator =(const Podcast& other) { +Podcast& Podcast::operator=(const Podcast& other) { d = other.d; return *this; } @@ -97,7 +97,9 @@ const QString& Podcast::author() const { return d->author_; } const QString& Podcast::owner_name() const { return d->owner_name_; } const QString& Podcast::owner_email() const { return d->owner_email_; } const QDateTime& Podcast::last_updated() const { return d->last_updated_; } -const QString& Podcast::last_update_error() const { return d->last_update_error_; } +const QString& Podcast::last_update_error() const { + return d->last_update_error_; +} const QVariantMap& Podcast::extra() const { return d->extra_; } QVariant Podcast::extra(const QString& key) const { return d->extra_[key]; } @@ -113,14 +115,20 @@ void Podcast::set_author(const QString& v) { d->author_ = v; } void Podcast::set_owner_name(const QString& v) { d->owner_name_ = v; } void Podcast::set_owner_email(const QString& v) { d->owner_email_ = v; } void Podcast::set_last_updated(const QDateTime& v) { d->last_updated_ = v; } -void Podcast::set_last_update_error(const QString& v) { d->last_update_error_ = v; } +void Podcast::set_last_update_error(const QString& v) { + d->last_update_error_ = v; +} void Podcast::set_extra(const QVariantMap& v) { d->extra_ = v; } -void Podcast::set_extra(const QString& key, const QVariant& value) { d->extra_[key] = value; } +void Podcast::set_extra(const QString& key, const QVariant& value) { + d->extra_[key] = value; +} const PodcastEpisodeList& Podcast::episodes() const { return d->episodes_; } PodcastEpisodeList* Podcast::mutable_episodes() { return &d->episodes_; } void Podcast::set_episodes(const PodcastEpisodeList& v) { d->episodes_ = v; } -void Podcast::add_episode(const PodcastEpisode& episode) { d->episodes_.append(episode); } +void Podcast::add_episode(const PodcastEpisode& episode) { + d->episodes_.append(episode); +} void Podcast::InitFromQuery(const QSqlQuery& query) { d->database_id_ = query.value(0).toInt(); diff --git a/src/podcasts/podcast.h b/src/podcasts/podcast.h index e793af409..d607ee03d 100644 --- a/src/podcasts/podcast.h +++ b/src/podcasts/podcast.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -26,11 +26,11 @@ #include namespace mygpo { - class Podcast; +class Podcast; } class Podcast { -public: + public: Podcast(); Podcast(const Podcast& other); ~Podcast(); @@ -82,8 +82,12 @@ public: // Small images are suitable for 16x16 icons in lists. Large images are // used in detailed information displays. - const QUrl& ImageUrlLarge() const { return image_url_large().isValid() ? image_url_large() : image_url_small(); } - const QUrl& ImageUrlSmall() const { return image_url_small().isValid() ? image_url_small() : image_url_large(); } + const QUrl& ImageUrlLarge() const { + return image_url_large().isValid() ? image_url_large() : image_url_small(); + } + const QUrl& ImageUrlSmall() const { + return image_url_small().isValid() ? image_url_small() : image_url_large(); + } // These are stored in a different database table, and aren't loaded or // persisted by InitFromQuery or BindToQuery. @@ -92,9 +96,9 @@ public: void set_episodes(const PodcastEpisodeList& v); void add_episode(const PodcastEpisode& episode); - Podcast& operator =(const Podcast& other); + Podcast& operator=(const Podcast& other); -private: + private: struct Private; QSharedDataPointer d; }; @@ -103,4 +107,4 @@ Q_DECLARE_METATYPE(Podcast) typedef QList PodcastList; Q_DECLARE_METATYPE(QList) -#endif // PODCAST_H +#endif // PODCAST_H diff --git a/src/podcasts/podcastbackend.cpp b/src/podcasts/podcastbackend.cpp index cd3b13578..18dc23cb5 100644 --- a/src/podcasts/podcastbackend.cpp +++ b/src/podcasts/podcastbackend.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -24,11 +24,7 @@ #include PodcastBackend::PodcastBackend(Application* app, QObject* parent) - : QObject(parent), - app_(app), - db_(app->database()) -{ -} + : QObject(parent), app_(app), db_(app->database()) {} void PodcastBackend::Subscribe(Podcast* podcast) { // If this podcast is already in the database, do nothing @@ -48,13 +44,15 @@ void PodcastBackend::Subscribe(Podcast* podcast) { ScopedTransaction t(&db); // Insert the podcast. - QSqlQuery q("INSERT INTO podcasts (" + Podcast::kColumnSpec + ")" - " VALUES (" + Podcast::kBindSpec + ")", db); + QSqlQuery q("INSERT INTO podcasts (" + Podcast::kColumnSpec + + ")" + " VALUES (" + + Podcast::kBindSpec + ")", + db); podcast->BindToQuery(&q); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; // Update the database ID. const int database_id = q.lastInsertId().toInt(); @@ -62,7 +60,7 @@ void PodcastBackend::Subscribe(Podcast* podcast) { // Update the IDs of any episodes. PodcastEpisodeList* episodes = podcast->mutable_episodes(); - for (auto it = episodes->begin() ; it != episodes->end() ; ++it) { + for (auto it = episodes->begin(); it != episodes->end(); ++it) { it->set_podcast_database_id(database_id); } @@ -88,30 +86,31 @@ void PodcastBackend::Unsubscribe(const Podcast& podcast) { QSqlQuery q("DELETE FROM podcasts WHERE ROWID = :id", db); q.bindValue(":id", podcast.database_id()); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; // Remove all episodes in the podcast q = QSqlQuery("DELETE FROM podcast_episodes WHERE podcast_id = :id", db); q.bindValue(":id", podcast.database_id()); q.exec(); - if (db_->CheckErrors(q)) - return; + if (db_->CheckErrors(q)) return; t.Commit(); emit SubscriptionRemoved(podcast); } -void PodcastBackend::AddEpisodes(PodcastEpisodeList* episodes, QSqlDatabase* db) { - QSqlQuery q("INSERT INTO podcast_episodes (" + PodcastEpisode::kColumnSpec + ")" - " VALUES (" + PodcastEpisode::kBindSpec + ")", *db); +void PodcastBackend::AddEpisodes(PodcastEpisodeList* episodes, + QSqlDatabase* db) { + QSqlQuery q("INSERT INTO podcast_episodes (" + PodcastEpisode::kColumnSpec + + ")" + " VALUES (" + + PodcastEpisode::kBindSpec + ")", + *db); - for (auto it = episodes->begin() ; it != episodes->end() ; ++it) { + for (auto it = episodes->begin(); it != episodes->end(); ++it) { it->BindToQuery(&q); q.exec(); - if (db_->CheckErrors(q)) - continue; + if (db_->CheckErrors(q)) continue; const int database_id = q.lastInsertId().toInt(); it->set_database_id(database_id); @@ -134,12 +133,14 @@ void PodcastBackend::UpdateEpisodes(const PodcastEpisodeList& episodes) { QSqlDatabase db(db_->Connect()); ScopedTransaction t(&db); - QSqlQuery q("UPDATE podcast_episodes" - " SET listened = :listened," - " listened_date = :listened_date," - " downloaded = :downloaded," - " local_url = :local_url" - " WHERE ROWID = :id", db); + QSqlQuery q( + "UPDATE podcast_episodes" + " SET listened = :listened," + " listened_date = :listened_date," + " downloaded = :downloaded," + " local_url = :local_url" + " WHERE ROWID = :id", + db); for (const PodcastEpisode& episode : episodes) { q.bindValue(":listened", episode.listened()); @@ -164,8 +165,7 @@ PodcastList PodcastBackend::GetAllSubscriptions() { QSqlQuery q("SELECT ROWID, " + Podcast::kColumnSpec + " FROM podcasts", db); q.exec(); - if (db_->CheckErrors(q)) - return ret; + if (db_->CheckErrors(q)) return ret; while (q.next()) { Podcast podcast; @@ -183,8 +183,9 @@ Podcast PodcastBackend::GetSubscriptionById(int id) { QSqlDatabase db(db_->Connect()); QSqlQuery q("SELECT ROWID, " + Podcast::kColumnSpec + - " FROM podcasts" - " WHERE ROWID = :id", db); + " FROM podcasts" + " WHERE ROWID = :id", + db); q.bindValue(":id", id); q.exec(); if (!db_->CheckErrors(q) && q.next()) { @@ -201,8 +202,9 @@ Podcast PodcastBackend::GetSubscriptionByUrl(const QUrl& url) { QSqlDatabase db(db_->Connect()); QSqlQuery q("SELECT ROWID, " + Podcast::kColumnSpec + - " FROM podcasts" - " WHERE url = :url", db); + " FROM podcasts" + " WHERE url = :url", + db); q.bindValue(":url", url.toEncoded()); q.exec(); if (!db_->CheckErrors(q) && q.next()) { @@ -219,12 +221,12 @@ PodcastEpisodeList PodcastBackend::GetEpisodes(int podcast_id) { QSqlDatabase db(db_->Connect()); QSqlQuery q("SELECT ROWID, " + PodcastEpisode::kColumnSpec + - " FROM podcast_episodes" - " WHERE podcast_id = :id", db); + " FROM podcast_episodes" + " WHERE podcast_id = :id", + db); q.bindValue(":db", podcast_id); q.exec(); - if (db_->CheckErrors(q)) - return ret; + if (db_->CheckErrors(q)) return ret; while (q.next()) { PodcastEpisode episode; @@ -242,8 +244,9 @@ PodcastEpisode PodcastBackend::GetEpisodeById(int id) { QSqlDatabase db(db_->Connect()); QSqlQuery q("SELECT ROWID, " + PodcastEpisode::kColumnSpec + - " FROM podcast_episodes" - " WHERE ROWID = :id", db); + " FROM podcast_episodes" + " WHERE ROWID = :id", + db); q.bindValue(":db", id); q.exec(); if (!db_->CheckErrors(q) && q.next()) { @@ -260,8 +263,9 @@ PodcastEpisode PodcastBackend::GetEpisodeByUrl(const QUrl& url) { QSqlDatabase db(db_->Connect()); QSqlQuery q("SELECT ROWID, " + PodcastEpisode::kColumnSpec + - " FROM podcast_episodes" - " WHERE url = :url", db); + " FROM podcast_episodes" + " WHERE url = :url", + db); q.bindValue(":url", url.toEncoded()); q.exec(); if (!db_->CheckErrors(q) && q.next()) { @@ -278,9 +282,10 @@ PodcastEpisode PodcastBackend::GetEpisodeByUrlOrLocalUrl(const QUrl& url) { QSqlDatabase db(db_->Connect()); QSqlQuery q("SELECT ROWID, " + PodcastEpisode::kColumnSpec + - " FROM podcast_episodes" - " WHERE url = :url" - " OR local_url = :url", db); + " FROM podcast_episodes" + " WHERE url = :url" + " OR local_url = :url", + db); q.bindValue(":url", url.toEncoded()); q.exec(); if (!db_->CheckErrors(q) && q.next()) { @@ -290,20 +295,21 @@ PodcastEpisode PodcastBackend::GetEpisodeByUrlOrLocalUrl(const QUrl& url) { return ret; } -PodcastEpisodeList PodcastBackend::GetOldDownloadedEpisodes(const QDateTime& max_listened_date) { +PodcastEpisodeList PodcastBackend::GetOldDownloadedEpisodes( + const QDateTime& max_listened_date) { PodcastEpisodeList ret; QMutexLocker l(db_->Mutex()); QSqlDatabase db(db_->Connect()); QSqlQuery q("SELECT ROWID, " + PodcastEpisode::kColumnSpec + - " FROM podcast_episodes" - " WHERE downloaded = 'true'" - " AND listened_date <= :max_listened_date", db); + " FROM podcast_episodes" + " WHERE downloaded = 'true'" + " AND listened_date <= :max_listened_date", + db); q.bindValue(":max_listened_date", max_listened_date.toTime_t()); q.exec(); - if (db_->CheckErrors(q)) - return ret; + if (db_->CheckErrors(q)) return ret; while (q.next()) { PodcastEpisode episode; @@ -321,12 +327,12 @@ PodcastEpisodeList PodcastBackend::GetNewDownloadedEpisodes() { QSqlDatabase db(db_->Connect()); QSqlQuery q("SELECT ROWID, " + PodcastEpisode::kColumnSpec + - " FROM podcast_episodes" - " WHERE downloaded = 'true'" - " AND listened = 'false'", db); + " FROM podcast_episodes" + " WHERE downloaded = 'true'" + " AND listened = 'false'", + db); q.exec(); - if (db_->CheckErrors(q)) - return ret; + if (db_->CheckErrors(q)) return ret; while (q.next()) { PodcastEpisode episode; diff --git a/src/podcasts/podcastbackend.h b/src/podcasts/podcastbackend.h index 87f5264a0..c5d1325d1 100644 --- a/src/podcasts/podcastbackend.h +++ b/src/podcasts/podcastbackend.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -28,7 +28,7 @@ class Database; class PodcastBackend : public QObject { Q_OBJECT -public: + public: PodcastBackend(Application* app, QObject* parent = 0); // Adds the podcast and any included Episodes to the database. Updates the @@ -58,7 +58,8 @@ public: // Returns a list of episodes that have local data (downloaded=true) but were // last listened to before the given QDateTime. This query is NOT indexed so // it involves a full search of the table. - PodcastEpisodeList GetOldDownloadedEpisodes(const QDateTime& max_listened_date); + PodcastEpisodeList GetOldDownloadedEpisodes( + const QDateTime& max_listened_date); PodcastEpisodeList GetNewDownloadedEpisodes(); // Adds episodes to the database. Every episode must have a valid @@ -68,7 +69,7 @@ public: // Updates the editable fields (listened, listened_date, downloaded, and // local_url) on episodes that must already exist in the database. void UpdateEpisodes(const PodcastEpisodeList& episodes); - + signals: void SubscriptionAdded(const Podcast& podcast); void SubscriptionRemoved(const Podcast& podcast); @@ -79,14 +80,14 @@ signals: // Emitted when existing episodes are updated. void EpisodesUpdated(const PodcastEpisodeList& episodes); -private: + private: // Adds each episode to the database, setting their IDs after inserting each // one. void AddEpisodes(PodcastEpisodeList* episodes, QSqlDatabase* db); -private: + private: Application* app_; Database* db_; }; -#endif // PODCASTBACKEND_H +#endif // PODCASTBACKEND_H diff --git a/src/podcasts/podcastdiscoverymodel.cpp b/src/podcasts/podcastdiscoverymodel.cpp index 1283674bd..b16b9ef01 100644 --- a/src/podcasts/podcastdiscoverymodel.cpp +++ b/src/podcasts/podcastdiscoverymodel.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -26,18 +26,19 @@ #include PodcastDiscoveryModel::PodcastDiscoveryModel(Application* app, QObject* parent) - : QStandardItemModel(parent), - app_(app), - icon_loader_(new StandardItemIconLoader(app->album_cover_loader(), this)), - default_icon_(":providers/podcast16.png") -{ + : QStandardItemModel(parent), + app_(app), + icon_loader_(new StandardItemIconLoader(app->album_cover_loader(), this)), + default_icon_(":providers/podcast16.png") { icon_loader_->SetModel(this); } QVariant PodcastDiscoveryModel::data(const QModelIndex& index, int role) const { if (index.isValid() && role == Qt::DecorationRole && - QStandardItemModel::data(index, Role_StartedLoadingImage).toBool() == false) { - const QUrl image_url = QStandardItemModel::data(index, Role_ImageUrl).toUrl(); + QStandardItemModel::data(index, Role_StartedLoadingImage).toBool() == + false) { + const QUrl image_url = + QStandardItemModel::data(index, Role_ImageUrl).toUrl(); if (image_url.isValid()) { const_cast(this)->LazyLoadImage(image_url, index); } @@ -46,7 +47,8 @@ QVariant PodcastDiscoveryModel::data(const QModelIndex& index, int role) const { return QStandardItemModel::data(index, role); } -QStandardItem* PodcastDiscoveryModel::CreatePodcastItem(const Podcast& podcast) { +QStandardItem* PodcastDiscoveryModel::CreatePodcastItem( + const Podcast& podcast) { QStandardItem* item = new QStandardItem; item->setIcon(default_icon_); item->setText(podcast.title()); @@ -68,25 +70,28 @@ QStandardItem* PodcastDiscoveryModel::CreateFolder(const QString& name) { return item; } -QStandardItem* PodcastDiscoveryModel::CreateOpmlContainerItem(const OpmlContainer& container) { +QStandardItem* PodcastDiscoveryModel::CreateOpmlContainerItem( + const OpmlContainer& container) { QStandardItem* item = CreateFolder(container.name); CreateOpmlContainerItems(container, item); return item; } -void PodcastDiscoveryModel::CreateOpmlContainerItems(const OpmlContainer& container, QStandardItem* parent) { - foreach (const OpmlContainer& child, container.containers) { +void PodcastDiscoveryModel::CreateOpmlContainerItems( + const OpmlContainer& container, QStandardItem* parent) { + foreach(const OpmlContainer & child, container.containers) { QStandardItem* child_item = CreateOpmlContainerItem(child); parent->appendRow(child_item); } - foreach (const Podcast& child, container.feeds) { + foreach(const Podcast & child, container.feeds) { QStandardItem* child_item = CreatePodcastItem(child); parent->appendRow(child_item); } } -void PodcastDiscoveryModel::LazyLoadImage(const QUrl& url, const QModelIndex& index) { +void PodcastDiscoveryModel::LazyLoadImage(const QUrl& url, + const QModelIndex& index) { QStandardItem* item = itemFromIndex(index); item->setData(true, Role_StartedLoadingImage); icon_loader_->LoadIcon(url.toString(), QString(), item); diff --git a/src/podcasts/podcastdiscoverymodel.h b/src/podcasts/podcastdiscoverymodel.h index c791c9c46..28be25e3c 100644 --- a/src/podcasts/podcastdiscoverymodel.h +++ b/src/podcasts/podcastdiscoverymodel.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -31,25 +31,21 @@ class StandardItemIconLoader; class PodcastDiscoveryModel : public QStandardItemModel { Q_OBJECT -public: + public: PodcastDiscoveryModel(Application* app, QObject* parent = 0); - enum Type { - Type_Folder, - Type_Podcast, - Type_LoadingIndicator - }; + enum Type { Type_Folder, Type_Podcast, Type_LoadingIndicator }; enum Role { Role_Podcast = Qt::UserRole, Role_Type, Role_ImageUrl, Role_StartedLoadingImage, - RoleCount }; - void CreateOpmlContainerItems(const OpmlContainer& container, QStandardItem* parent); + void CreateOpmlContainerItems(const OpmlContainer& container, + QStandardItem* parent); QStandardItem* CreateOpmlContainerItem(const OpmlContainer& container); QStandardItem* CreatePodcastItem(const Podcast& podcast); QStandardItem* CreateFolder(const QString& name); @@ -57,10 +53,10 @@ public: QVariant data(const QModelIndex& index, int role) const; -private: + private: void LazyLoadImage(const QUrl& url, const QModelIndex& index); - -private: + + private: Application* app_; StandardItemIconLoader* icon_loader_; @@ -68,4 +64,4 @@ private: QIcon folder_icon_; }; -#endif // PODCASTDISCOVERYMODEL_H +#endif // PODCASTDISCOVERYMODEL_H diff --git a/src/podcasts/podcastdownloader.cpp b/src/podcasts/podcastdownloader.cpp index 4b5127fd9..c2982404c 100644 --- a/src/podcasts/podcastdownloader.cpp +++ b/src/podcasts/podcastdownloader.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -34,7 +34,8 @@ #include const char* PodcastDownloader::kSettingsGroup = "Podcasts"; -const int PodcastDownloader::kAutoDeleteCheckIntervalMsec = 15 * 60 * kMsecPerSec; // 15 minutes +const int PodcastDownloader::kAutoDeleteCheckIntervalMsec = + 15 * 60 * kMsecPerSec; // 15 minutes struct PodcastDownloader::Task { Task() : file(nullptr) {} @@ -45,17 +46,16 @@ struct PodcastDownloader::Task { }; PodcastDownloader::PodcastDownloader(Application* app, QObject* parent) - : QObject(parent), - app_(app), - backend_(app_->podcast_backend()), - network_(new NetworkAccessManager(this)), - disallowed_filename_characters_("[^a-zA-Z0-9_~ -]"), - auto_download_(false), - delete_after_secs_(0), - current_task_(nullptr), - last_progress_signal_(0), - auto_delete_timer_(new QTimer(this)) -{ + : QObject(parent), + app_(app), + backend_(app_->podcast_backend()), + network_(new NetworkAccessManager(this)), + disallowed_filename_characters_("[^a-zA-Z0-9_~ -]"), + auto_download_(false), + delete_after_secs_(0), + current_task_(nullptr), + last_progress_signal_(0), + auto_delete_timer_(new QTimer(this)) { connect(backend_, SIGNAL(EpisodesAdded(PodcastEpisodeList)), SLOT(EpisodesAdded(PodcastEpisodeList))); connect(backend_, SIGNAL(SubscriptionAdded(Podcast)), @@ -91,8 +91,7 @@ void PodcastDownloader::ReloadSettings() { } void PodcastDownloader::DownloadEpisode(const PodcastEpisode& episode) { - if (downloading_episode_ids_.contains(episode.database_id())) - return; + if (downloading_episode_ids_.contains(episode.database_id())) return; downloading_episode_ids_.insert(episode.database_id()); Task* task = new Task; @@ -109,7 +108,8 @@ void PodcastDownloader::DownloadEpisode(const PodcastEpisode& episode) { } void PodcastDownloader::DeleteEpisode(const PodcastEpisode& episode) { - if (!episode.downloaded() || downloading_episode_ids_.contains(episode.database_id())) + if (!episode.downloaded() || + downloading_episode_ids_.contains(episode.database_id())) return; // Delete the local file @@ -127,7 +127,7 @@ void PodcastDownloader::DeleteEpisode(const PodcastEpisode& episode) { void PodcastDownloader::FinishAndDelete(Task* task) { Podcast podcast = - backend_->GetSubscriptionById(task->episode.podcast_database_id()); + backend_->GetSubscriptionById(task->episode.podcast_database_id()); Song song = task->episode.ToSong(podcast); downloading_episode_ids_.remove(task->episode.database_id()); @@ -140,13 +140,13 @@ void PodcastDownloader::FinishAndDelete(Task* task) { NextTask(); } -QString PodcastDownloader::FilenameForEpisode(const QString& directory, - const PodcastEpisode& episode) const { +QString PodcastDownloader::FilenameForEpisode( + const QString& directory, const PodcastEpisode& episode) const { const QString file_extension = QFileInfo(episode.url().path()).suffix(); int count = 0; // The file name contains the publication date and episode title - QString base_filename = + QString base_filename = episode.publication_date().date().toString(Qt::ISODate) + "-" + SanitiseFilenameComponent(episode.title()); @@ -156,11 +156,11 @@ QString PodcastDownloader::FilenameForEpisode(const QString& directory, QString filename; if (count == 0) { - filename = QString("%1/%2.%3").arg( - directory, base_filename, file_extension); + filename = + QString("%1/%2.%3").arg(directory, base_filename, file_extension); } else { filename = QString("%1/%2 (%3).%4").arg( - directory, base_filename, QString::number(count), file_extension); + directory, base_filename, QString::number(count), file_extension); } if (!QFile::exists(filename)) { @@ -184,8 +184,8 @@ void PodcastDownloader::StartDownloading(Task* task) { return; } - const QString directory = download_dir_ + "/" + - SanitiseFilenameComponent(podcast.title()); + const QString directory = + download_dir_ + "/" + SanitiseFilenameComponent(podcast.title()); const QString filepath = FilenameForEpisode(directory, task->episode); // Open the output file @@ -220,25 +220,21 @@ void PodcastDownloader::NextTask() { void PodcastDownloader::ReplyReadyRead() { QNetworkReply* reply = qobject_cast(sender())->reply(); - if (!reply || !current_task_ || !current_task_->file) - return; + if (!reply || !current_task_ || !current_task_->file) return; forever { const qint64 bytes = reply->bytesAvailable(); - if (bytes <= 0) - break; + if (bytes <= 0) break; current_task_->file->write(reply->read(bytes)); } } void PodcastDownloader::ReplyDownloadProgress(qint64 received, qint64 total) { - if (!current_task_ || !current_task_->file || total < 1024) - return; + if (!current_task_ || !current_task_->file || total < 1024) return; const time_t current_time = QDateTime::currentDateTime().toTime_t(); - if (last_progress_signal_ == current_time) - return; + if (last_progress_signal_ == current_time) return; last_progress_signal_ = current_time; emit ProgressChanged(current_task_->episode, Downloading, @@ -247,8 +243,7 @@ void PodcastDownloader::ReplyDownloadProgress(qint64 received, qint64 total) { void PodcastDownloader::ReplyFinished() { RedirectFollower* reply = qobject_cast(sender()); - if (!reply || !current_task_ || !current_task_->file) - return; + if (!reply || !current_task_ || !current_task_->file) return; reply->deleteLater(); @@ -266,7 +261,8 @@ void PodcastDownloader::ReplyFinished() { // Tell the database the episode has been updated. Get it from the DB again // in case the listened field changed in the mean time. - PodcastEpisode episode = backend_->GetEpisodeById(current_task_->episode.database_id()); + PodcastEpisode episode = + backend_->GetEpisodeById(current_task_->episode.database_id()); episode.set_downloaded(true); episode.set_local_url(QUrl::fromLocalFile(current_task_->file->fileName())); backend_->UpdateEpisodes(PodcastEpisodeList() << episode); @@ -274,8 +270,11 @@ void PodcastDownloader::ReplyFinished() { FinishAndDelete(current_task_); } -QString PodcastDownloader::SanitiseFilenameComponent(const QString& text) const { - return QString(text).replace(disallowed_filename_characters_, " ").simplified(); +QString PodcastDownloader::SanitiseFilenameComponent(const QString& text) + const { + return QString(text) + .replace(disallowed_filename_characters_, " ") + .simplified(); } void PodcastDownloader::SubscriptionAdded(const Podcast& podcast) { @@ -298,14 +297,13 @@ void PodcastDownloader::AutoDelete() { QDateTime max_date = QDateTime::currentDateTime(); max_date.addSecs(-delete_after_secs_); - PodcastEpisodeList old_episodes = backend_->GetOldDownloadedEpisodes(max_date); - if (old_episodes.isEmpty()) - return; + PodcastEpisodeList old_episodes = + backend_->GetOldDownloadedEpisodes(max_date); + if (old_episodes.isEmpty()) return; qLog(Info) << "Deleting" << old_episodes.count() << "episodes because they were last listened to" - << (delete_after_secs_ / kSecsPerDay) - << "days ago"; + << (delete_after_secs_ / kSecsPerDay) << "days ago"; for (const PodcastEpisode& episode : old_episodes) { DeleteEpisode(episode); diff --git a/src/podcasts/podcastdownloader.h b/src/podcasts/podcastdownloader.h index 32804c32a..4476c62a5 100644 --- a/src/podcasts/podcastdownloader.h +++ b/src/podcasts/podcastdownloader.h @@ -41,22 +41,17 @@ class QNetworkAccessManager; class PodcastDownloader : public QObject { Q_OBJECT -public: + public: PodcastDownloader(Application* app, QObject* parent = 0); - enum State { - NotDownloading, - Queued, - Downloading, - Finished - }; + enum State { NotDownloading, Queued, Downloading, Finished }; static const char* kSettingsGroup; static const int kAutoDeleteCheckIntervalMsec; QString DefaultDownloadDir() const; -public slots: + public slots: // Adds the episode to the download queue void DownloadEpisode(const PodcastEpisode& episode); @@ -67,7 +62,7 @@ signals: void ProgressChanged(const PodcastEpisode& episode, PodcastDownloader::State state, int percent); -private slots: + private slots: void ReloadSettings(); void SubscriptionAdded(const Podcast& podcast); @@ -79,7 +74,7 @@ private slots: void AutoDelete(); -private: + private: struct Task; void StartDownloading(Task* task); @@ -90,7 +85,7 @@ private: const PodcastEpisode& episode) const; QString SanitiseFilenameComponent(const QString& text) const; -private: + private: Application* app_; PodcastBackend* backend_; QNetworkAccessManager* network_; @@ -110,4 +105,4 @@ private: QTimer* auto_delete_timer_; }; -#endif // PODCASTDOWNLOADER_H +#endif // PODCASTDOWNLOADER_H diff --git a/src/podcasts/podcastepisode.cpp b/src/podcasts/podcastepisode.cpp index 4924a7810..b4e806e57 100644 --- a/src/podcasts/podcastepisode.cpp +++ b/src/podcasts/podcastepisode.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -26,15 +26,26 @@ #include #include -const QStringList PodcastEpisode::kColumns = QStringList() - << "podcast_id" << "title" << "description" << "author" - << "publication_date" << "duration_secs" << "url" << "listened" - << "listened_date" << "downloaded" << "local_url" << "extra"; +const QStringList PodcastEpisode::kColumns = QStringList() << "podcast_id" + << "title" + << "description" + << "author" + << "publication_date" + << "duration_secs" + << "url" + << "listened" + << "listened_date" + << "downloaded" + << "local_url" + << "extra"; const QString PodcastEpisode::kColumnSpec = PodcastEpisode::kColumns.join(", "); -const QString PodcastEpisode::kJoinSpec = Utilities::Prepend("e.", PodcastEpisode::kColumns).join(", "); -const QString PodcastEpisode::kBindSpec = Utilities::Prepend(":", PodcastEpisode::kColumns).join(", "); -const QString PodcastEpisode::kUpdateSpec = Utilities::Updateify(PodcastEpisode::kColumns).join(", "); +const QString PodcastEpisode::kJoinSpec = + Utilities::Prepend("e.", PodcastEpisode::kColumns).join(", "); +const QString PodcastEpisode::kBindSpec = + Utilities::Prepend(":", PodcastEpisode::kColumns).join(", "); +const QString PodcastEpisode::kUpdateSpec = + Utilities::Updateify(PodcastEpisode::kColumns).join(", "); struct PodcastEpisode::Private : public QSharedData { Private(); @@ -59,61 +70,68 @@ struct PodcastEpisode::Private : public QSharedData { }; PodcastEpisode::Private::Private() - : database_id_(-1), - podcast_database_id_(-1), - duration_secs_(-1), - listened_(false), - downloaded_(false) -{ -} + : database_id_(-1), + podcast_database_id_(-1), + duration_secs_(-1), + listened_(false), + downloaded_(false) {} -PodcastEpisode::PodcastEpisode() - : d(new Private) -{ -} +PodcastEpisode::PodcastEpisode() : d(new Private) {} -PodcastEpisode::PodcastEpisode(const PodcastEpisode& other) - : d(other.d) -{ -} +PodcastEpisode::PodcastEpisode(const PodcastEpisode& other) : d(other.d) {} -PodcastEpisode::~PodcastEpisode() { -} +PodcastEpisode::~PodcastEpisode() {} -PodcastEpisode& PodcastEpisode::operator =(const PodcastEpisode& other) { +PodcastEpisode& PodcastEpisode::operator=(const PodcastEpisode& other) { d = other.d; return *this; } int PodcastEpisode::database_id() const { return d->database_id_; } -int PodcastEpisode::podcast_database_id() const { return d->podcast_database_id_; } +int PodcastEpisode::podcast_database_id() const { + return d->podcast_database_id_; +} const QString& PodcastEpisode::title() const { return d->title_; } const QString& PodcastEpisode::description() const { return d->description_; } const QString& PodcastEpisode::author() const { return d->author_; } -const QDateTime& PodcastEpisode::publication_date() const { return d->publication_date_; } +const QDateTime& PodcastEpisode::publication_date() const { + return d->publication_date_; +} int PodcastEpisode::duration_secs() const { return d->duration_secs_; } const QUrl& PodcastEpisode::url() const { return d->url_; } bool PodcastEpisode::listened() const { return d->listened_; } -const QDateTime& PodcastEpisode::listened_date() const { return d->listened_date_; } +const QDateTime& PodcastEpisode::listened_date() const { + return d->listened_date_; +} bool PodcastEpisode::downloaded() const { return d->downloaded_; } const QUrl& PodcastEpisode::local_url() const { return d->local_url_; } const QVariantMap& PodcastEpisode::extra() const { return d->extra_; } -QVariant PodcastEpisode::extra(const QString& key) const { return d->extra_[key]; } +QVariant PodcastEpisode::extra(const QString& key) const { + return d->extra_[key]; +} void PodcastEpisode::set_database_id(int v) { d->database_id_ = v; } -void PodcastEpisode::set_podcast_database_id(int v) { d->podcast_database_id_ = v; } +void PodcastEpisode::set_podcast_database_id(int v) { + d->podcast_database_id_ = v; +} void PodcastEpisode::set_title(const QString& v) { d->title_ = v; } void PodcastEpisode::set_description(const QString& v) { d->description_ = v; } void PodcastEpisode::set_author(const QString& v) { d->author_ = v; } -void PodcastEpisode::set_publication_date(const QDateTime& v) { d->publication_date_ = v; } +void PodcastEpisode::set_publication_date(const QDateTime& v) { + d->publication_date_ = v; +} void PodcastEpisode::set_duration_secs(int v) { d->duration_secs_ = v; } void PodcastEpisode::set_url(const QUrl& v) { d->url_ = v; } void PodcastEpisode::set_listened(bool v) { d->listened_ = v; } -void PodcastEpisode::set_listened_date(const QDateTime& v) { d->listened_date_ = v; } +void PodcastEpisode::set_listened_date(const QDateTime& v) { + d->listened_date_ = v; +} void PodcastEpisode::set_downloaded(bool v) { d->downloaded_ = v; } void PodcastEpisode::set_local_url(const QUrl& v) { d->local_url_ = v; } void PodcastEpisode::set_extra(const QVariantMap& v) { d->extra_ = v; } -void PodcastEpisode::set_extra(const QString& key, const QVariant& value) { d->extra_[key] = value; } +void PodcastEpisode::set_extra(const QString& key, const QVariant& value) { + d->extra_[key] = value; +} void PodcastEpisode::InitFromQuery(const QSqlQuery& query) { d->database_id_ = query.value(0).toInt(); @@ -175,8 +193,7 @@ Song PodcastEpisode::ToSong(const Podcast& podcast) const { ret.set_album(podcast.title().simplified()); ret.set_art_automatic(podcast.ImageUrlLarge().toString()); - if (author().isEmpty()) - ret.set_artist(podcast.title().simplified()); + if (author().isEmpty()) ret.set_artist(podcast.title().simplified()); } return ret; } diff --git a/src/podcasts/podcastepisode.h b/src/podcasts/podcastepisode.h index 92505f98c..d084c6543 100644 --- a/src/podcasts/podcastepisode.h +++ b/src/podcasts/podcastepisode.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -28,7 +28,7 @@ class Podcast; class PodcastEpisode { -public: + public: PodcastEpisode(); PodcastEpisode(const PodcastEpisode& other); ~PodcastEpisode(); @@ -76,9 +76,9 @@ public: void set_extra(const QVariantMap& v); void set_extra(const QString& key, const QVariant& value); - PodcastEpisode& operator =(const PodcastEpisode& other); + PodcastEpisode& operator=(const PodcastEpisode& other); -private: + private: struct Private; QSharedDataPointer d; }; @@ -87,4 +87,4 @@ Q_DECLARE_METATYPE(PodcastEpisode) typedef QList PodcastEpisodeList; Q_DECLARE_METATYPE(QList) -#endif // PODCASTEPISODE_H +#endif // PODCASTEPISODE_H diff --git a/src/podcasts/podcastinfowidget.cpp b/src/podcasts/podcastinfowidget.cpp index 8ac024859..8331ed38c 100644 --- a/src/podcasts/podcastinfowidget.cpp +++ b/src/podcasts/podcastinfowidget.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -21,11 +21,10 @@ #include "covers/albumcoverloader.h" PodcastInfoWidget::PodcastInfoWidget(QWidget* parent) - : QWidget(parent), - ui_(new Ui_PodcastInfoWidget), - app_(nullptr), - image_id_(0) -{ + : QWidget(parent), + ui_(new Ui_PodcastInfoWidget), + app_(nullptr), + image_id_(0) { ui_->setupUi(this); cover_options_.desired_height_ = 180; @@ -36,38 +35,38 @@ PodcastInfoWidget::PodcastInfoWidget(QWidget* parent) const bool light = palette().color(QPalette::Base).value() > 128; const QColor color = palette().color(QPalette::Dark); QPalette label_palette(palette()); - label_palette.setColor(QPalette::WindowText, light ? color.darker(150) : color.lighter(125)); + label_palette.setColor(QPalette::WindowText, + light ? color.darker(150) : color.lighter(125)); - foreach (QLabel* label, findChildren()) { + foreach(QLabel * label, findChildren()) { if (label->property("field_label").toBool()) { label->setPalette(label_palette); } } } -PodcastInfoWidget::~PodcastInfoWidget() { -} +PodcastInfoWidget::~PodcastInfoWidget() {} void PodcastInfoWidget::SetApplication(Application* app) { app_ = app; - connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64,QImage)), - SLOT(ImageLoaded(quint64,QImage))); + connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)), + SLOT(ImageLoaded(quint64, QImage))); } namespace { - template - void SetText(const QString& value, T* label, QLabel* buddy_label = nullptr) { - const bool visible = !value.isEmpty(); +template +void SetText(const QString& value, T* label, QLabel* buddy_label = nullptr) { + const bool visible = !value.isEmpty(); - label->setVisible(visible); - if (buddy_label) { - buddy_label->setVisible(visible); - } - - if (visible) { - label->setText(value); - } + label->setVisible(visible); + if (buddy_label) { + buddy_label->setVisible(visible); } + + if (visible) { + label->setText(value); + } +} } void PodcastInfoWidget::SetPodcast(const Podcast& podcast) { @@ -81,7 +80,7 @@ void PodcastInfoWidget::SetPodcast(const Podcast& podcast) { if (podcast.ImageUrlLarge().isValid()) { // Start loading an image for this item. image_id_ = app_->album_cover_loader()->LoadImageAsync( - cover_options_, podcast.ImageUrlLarge().toString(), QString()); + cover_options_, podcast.ImageUrlLarge().toString(), QString()); } ui_->image->hide(); @@ -92,7 +91,8 @@ void PodcastInfoWidget::SetPodcast(const Podcast& podcast) { SetText(podcast.author(), ui_->author, ui_->author_label); SetText(podcast.owner_name(), ui_->owner, ui_->owner_label); SetText(podcast.link().toString(), ui_->website, ui_->website_label); - SetText(podcast.extra("gpodder:subscribers").toString(), ui_->subscribers, ui_->subscribers_label); + SetText(podcast.extra("gpodder:subscribers").toString(), ui_->subscribers, + ui_->subscribers_label); if (!image_id_) { emit LoadingFinished(); diff --git a/src/podcasts/podcastinfowidget.h b/src/podcasts/podcastinfowidget.h index c5ade4750..158dce9bd 100644 --- a/src/podcasts/podcastinfowidget.h +++ b/src/podcasts/podcastinfowidget.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -31,7 +31,7 @@ class QLabel; class PodcastInfoWidget : public QWidget { Q_OBJECT -public: + public: PodcastInfoWidget(QWidget* parent = 0); ~PodcastInfoWidget(); @@ -42,10 +42,10 @@ public: signals: void LoadingFinished(); -private slots: + private slots: void ImageLoaded(quint64 id, const QImage& image); -private: + private: Ui_PodcastInfoWidget* ui_; AlbumCoverLoaderOptions cover_options_; @@ -55,4 +55,4 @@ private: quint64 image_id_; }; -#endif // PODCASTINFOWIDGET_H +#endif // PODCASTINFOWIDGET_H diff --git a/src/podcasts/podcastparser.cpp b/src/podcasts/podcastparser.cpp index 4cb5afe32..06e570d3f 100644 --- a/src/podcasts/podcastparser.cpp +++ b/src/podcasts/podcastparser.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -24,7 +24,8 @@ #include const char* PodcastParser::kAtomNamespace = "http://www.w3.org/2005/Atom"; -const char* PodcastParser::kItunesNamespace = "http://www.itunes.com/dtds/podcast-1.0.dtd"; +const char* PodcastParser::kItunesNamespace = + "http://www.itunes.com/dtds/podcast-1.0.dtd"; PodcastParser::PodcastParser() { supported_mime_types_ << "application/rss+xml" @@ -39,7 +40,7 @@ bool PodcastParser::SupportsContentType(const QString& content_type) const { return true; } - foreach (const QString& mime_type, supported_mime_types()) { + foreach(const QString & mime_type, supported_mime_types()) { if (content_type.contains(mime_type)) { return true; } @@ -49,8 +50,7 @@ bool PodcastParser::SupportsContentType(const QString& content_type) const { bool PodcastParser::TryMagic(const QByteArray& data) const { QString str(QString::fromUtf8(data)); - return str.contains(QRegExp("atEnd()) { QXmlStreamReader::TokenType type = reader->readNext(); switch (type) { - case QXmlStreamReader::StartElement: { - const QStringRef name = reader->name(); - if (name == "title") { - ret->set_title(reader->readElementText()); - } else if (name == "link" && reader->namespaceUri().isEmpty()) { - ret->set_link(QUrl::fromEncoded(reader->readElementText().toAscii())); - } else if (name == "description") { - ret->set_description(reader->readElementText()); - } else if (name == "owner" && reader->namespaceUri() == kItunesNamespace) { - ParseItunesOwner(reader, ret); - } else if (name == "image") { - ParseImage(reader, ret); - } else if (name == "copyright") { - ret->set_copyright(reader->readElementText()); - } else if (name == "link" && reader->namespaceUri() == kAtomNamespace && - ret->url().isEmpty() && reader->attributes().value("rel") == "self") { - ret->set_url(QUrl::fromEncoded(reader->readElementText().toAscii())); - } else if (name == "item") { - ParseItem(reader, ret); - } else { - Utilities::ConsumeCurrentElement(reader); + case QXmlStreamReader::StartElement: { + const QStringRef name = reader->name(); + if (name == "title") { + ret->set_title(reader->readElementText()); + } else if (name == "link" && reader->namespaceUri().isEmpty()) { + ret->set_link(QUrl::fromEncoded(reader->readElementText().toAscii())); + } else if (name == "description") { + ret->set_description(reader->readElementText()); + } else if (name == "owner" && + reader->namespaceUri() == kItunesNamespace) { + ParseItunesOwner(reader, ret); + } else if (name == "image") { + ParseImage(reader, ret); + } else if (name == "copyright") { + ret->set_copyright(reader->readElementText()); + } else if (name == "link" && reader->namespaceUri() == kAtomNamespace && + ret->url().isEmpty() && + reader->attributes().value("rel") == "self") { + ret->set_url(QUrl::fromEncoded(reader->readElementText().toAscii())); + } else if (name == "item") { + ParseItem(reader, ret); + } else { + Utilities::ConsumeCurrentElement(reader); + } + break; } - break; - } - case QXmlStreamReader::EndElement: - return; + case QXmlStreamReader::EndElement: + return; - default: - break; + default: + break; } } } @@ -140,46 +142,48 @@ void PodcastParser::ParseImage(QXmlStreamReader* reader, Podcast* ret) const { while (!reader->atEnd()) { QXmlStreamReader::TokenType type = reader->readNext(); switch (type) { - case QXmlStreamReader::StartElement: { - const QStringRef name = reader->name(); - if (name == "url") { - ret->set_image_url_large(QUrl::fromEncoded(reader->readElementText().toAscii())); - } else { - Utilities::ConsumeCurrentElement(reader); + case QXmlStreamReader::StartElement: { + const QStringRef name = reader->name(); + if (name == "url") { + ret->set_image_url_large( + QUrl::fromEncoded(reader->readElementText().toAscii())); + } else { + Utilities::ConsumeCurrentElement(reader); + } + break; } - break; - } - case QXmlStreamReader::EndElement: - return; + case QXmlStreamReader::EndElement: + return; - default: - break; + default: + break; } } } -void PodcastParser::ParseItunesOwner(QXmlStreamReader* reader, Podcast* ret) const { +void PodcastParser::ParseItunesOwner(QXmlStreamReader* reader, + Podcast* ret) const { while (!reader->atEnd()) { QXmlStreamReader::TokenType type = reader->readNext(); switch (type) { - case QXmlStreamReader::StartElement: { - const QStringRef name = reader->name(); - if (name == "name") { - ret->set_owner_name(reader->readElementText()); - } else if (name == "email") { - ret->set_owner_email(reader->readElementText()); - } else { - Utilities::ConsumeCurrentElement(reader); + case QXmlStreamReader::StartElement: { + const QStringRef name = reader->name(); + if (name == "name") { + ret->set_owner_name(reader->readElementText()); + } else if (name == "email") { + ret->set_owner_email(reader->readElementText()); + } else { + Utilities::ConsumeCurrentElement(reader); + } + break; } - break; - } - case QXmlStreamReader::EndElement: - return; + case QXmlStreamReader::EndElement: + return; - default: - break; + default: + break; } } } @@ -190,52 +194,55 @@ void PodcastParser::ParseItem(QXmlStreamReader* reader, Podcast* ret) const { while (!reader->atEnd()) { QXmlStreamReader::TokenType type = reader->readNext(); switch (type) { - case QXmlStreamReader::StartElement: { - const QStringRef name = reader->name(); - if (name == "title") { - episode.set_title(reader->readElementText()); - } else if (name == "description") { - episode.set_description(reader->readElementText()); - } else if (name == "pubDate") { - episode.set_publication_date(Utilities::ParseRFC822DateTime(reader->readElementText())); - } else if (name == "duration" && reader->namespaceUri() == kItunesNamespace) { - // http://www.apple.com/itunes/podcasts/specs.html - QStringList parts = reader->readElementText().split(':'); - if (parts.count() == 2) { - episode.set_duration_secs(parts[0].toInt() * 60 + - parts[1].toInt()); - } else if (parts.count() >= 3) { - episode.set_duration_secs(parts[0].toInt() * 60*60 + - parts[1].toInt() * 60 + - parts[2].toInt()); + case QXmlStreamReader::StartElement: { + const QStringRef name = reader->name(); + if (name == "title") { + episode.set_title(reader->readElementText()); + } else if (name == "description") { + episode.set_description(reader->readElementText()); + } else if (name == "pubDate") { + episode.set_publication_date( + Utilities::ParseRFC822DateTime(reader->readElementText())); + } else if (name == "duration" && + reader->namespaceUri() == kItunesNamespace) { + // http://www.apple.com/itunes/podcasts/specs.html + QStringList parts = reader->readElementText().split(':'); + if (parts.count() == 2) { + episode.set_duration_secs(parts[0].toInt() * 60 + parts[1].toInt()); + } else if (parts.count() >= 3) { + episode.set_duration_secs(parts[0].toInt() * 60 * 60 + + parts[1].toInt() * 60 + parts[2].toInt()); + } + } else if (name == "enclosure") { + const QString type = reader->attributes().value("type").toString(); + if (type.startsWith("audio/") || type.startsWith("x-audio/")) { + episode.set_url(QUrl::fromEncoded( + reader->attributes().value("url").toString().toAscii())); + } + Utilities::ConsumeCurrentElement(reader); + } else if (name == "author" && + reader->namespaceUri() == kItunesNamespace) { + episode.set_author(reader->readElementText()); + } else { + Utilities::ConsumeCurrentElement(reader); } - } else if (name == "enclosure") { - const QString type = reader->attributes().value("type").toString(); - if (type.startsWith("audio/") || type.startsWith("x-audio/")) { - episode.set_url(QUrl::fromEncoded(reader->attributes().value("url").toString().toAscii())); + break; + } + + case QXmlStreamReader::EndElement: + if (!episode.url().isEmpty()) { + ret->add_episode(episode); } - Utilities::ConsumeCurrentElement(reader); - } else if (name == "author" && reader->namespaceUri() == kItunesNamespace) { - episode.set_author(reader->readElementText()); - } else { - Utilities::ConsumeCurrentElement(reader); - } - break; - } + return; - case QXmlStreamReader::EndElement: - if (!episode.url().isEmpty()) { - ret->add_episode(episode); - } - return; - - default: - break; + default: + break; } } } -bool PodcastParser::ParseOpml(QXmlStreamReader* reader, OpmlContainer* ret) const { +bool PodcastParser::ParseOpml(QXmlStreamReader* reader, + OpmlContainer* ret) const { if (!Utilities::ParseUntilElement(reader, "body")) { return false; } @@ -243,61 +250,63 @@ bool PodcastParser::ParseOpml(QXmlStreamReader* reader, OpmlContainer* ret) cons ParseOutline(reader, ret); // OPML files sometimes consist of a single top level container. - while (ret->feeds.count() == 0 && - ret->containers.count() == 1) { + while (ret->feeds.count() == 0 && ret->containers.count() == 1) { *ret = ret->containers[0]; } return true; } -void PodcastParser::ParseOutline(QXmlStreamReader* reader, OpmlContainer* ret) const { +void PodcastParser::ParseOutline(QXmlStreamReader* reader, + OpmlContainer* ret) const { while (!reader->atEnd()) { QXmlStreamReader::TokenType type = reader->readNext(); switch (type) { - case QXmlStreamReader::StartElement: { - const QStringRef name = reader->name(); - if (name != "outline") { - Utilities::ConsumeCurrentElement(reader); - continue; - } - - QXmlStreamAttributes attributes = reader->attributes(); - - if (attributes.value("type").toString() == "rss") { - // Parse the feed and add it to this container - Podcast podcast; - podcast.set_description(attributes.value("description").toString()); - podcast.set_title(attributes.value("text").toString()); - podcast.set_image_url_large(QUrl::fromEncoded(attributes.value("imageHref").toString().toAscii())); - podcast.set_url(QUrl::fromEncoded(attributes.value("xmlUrl").toString().toAscii())); - ret->feeds.append(podcast); - - // Consume any children and the EndElement. - Utilities::ConsumeCurrentElement(reader); - } else { - // Create a new child container - OpmlContainer child; - - // Take the name from the fullname attribute first if it exists. - child.name = attributes.value("fullname").toString(); - if (child.name.isEmpty()) { - child.name = attributes.value("text").toString(); + case QXmlStreamReader::StartElement: { + const QStringRef name = reader->name(); + if (name != "outline") { + Utilities::ConsumeCurrentElement(reader); + continue; } - // Parse its contents and add it to this container - ParseOutline(reader, &child); - ret->containers.append(child); + QXmlStreamAttributes attributes = reader->attributes(); + + if (attributes.value("type").toString() == "rss") { + // Parse the feed and add it to this container + Podcast podcast; + podcast.set_description(attributes.value("description").toString()); + podcast.set_title(attributes.value("text").toString()); + podcast.set_image_url_large(QUrl::fromEncoded( + attributes.value("imageHref").toString().toAscii())); + podcast.set_url(QUrl::fromEncoded( + attributes.value("xmlUrl").toString().toAscii())); + ret->feeds.append(podcast); + + // Consume any children and the EndElement. + Utilities::ConsumeCurrentElement(reader); + } else { + // Create a new child container + OpmlContainer child; + + // Take the name from the fullname attribute first if it exists. + child.name = attributes.value("fullname").toString(); + if (child.name.isEmpty()) { + child.name = attributes.value("text").toString(); + } + + // Parse its contents and add it to this container + ParseOutline(reader, &child); + ret->containers.append(child); + } + + break; } - break; - } + case QXmlStreamReader::EndElement: + return; - case QXmlStreamReader::EndElement: - return; - - default: - break; + default: + break; } } } diff --git a/src/podcasts/podcastparser.h b/src/podcasts/podcastparser.h index b5273e544..378cc2455 100644 --- a/src/podcasts/podcastparser.h +++ b/src/podcasts/podcastparser.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -30,13 +30,15 @@ class QXmlStreamReader; // Returns either a Podcast or an OpmlContainer depending on what was inside // the XML document. class PodcastParser { -public: + public: PodcastParser(); static const char* kAtomNamespace; static const char* kItunesNamespace; - const QStringList& supported_mime_types() const { return supported_mime_types_; } + const QStringList& supported_mime_types() const { + return supported_mime_types_; + } bool SupportsContentType(const QString& content_type) const; // You should check the type of the returned QVariant to see whether it @@ -48,7 +50,7 @@ public: // still return a null QVariant. bool TryMagic(const QByteArray& data) const; -private: + private: bool ParseRss(QXmlStreamReader* reader, Podcast* ret) const; void ParseChannel(QXmlStreamReader* reader, Podcast* ret) const; void ParseImage(QXmlStreamReader* reader, Podcast* ret) const; @@ -58,8 +60,8 @@ private: bool ParseOpml(QXmlStreamReader* reader, OpmlContainer* ret) const; void ParseOutline(QXmlStreamReader* reader, OpmlContainer* ret) const; -private: + private: QStringList supported_mime_types_; }; -#endif // PODCASTPARSER_H +#endif // PODCASTPARSER_H diff --git a/src/podcasts/podcastservice.cpp b/src/podcasts/podcastservice.cpp index c05ef0f26..916982d9a 100644 --- a/src/podcasts/podcastservice.cpp +++ b/src/podcasts/podcastservice.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -41,49 +41,50 @@ const char* PodcastService::kServiceName = "Podcasts"; const char* PodcastService::kSettingsGroup = "Podcasts"; - class PodcastSortProxyModel : public QSortFilterProxyModel { -public: + public: PodcastSortProxyModel(QObject* parent = nullptr); -protected: + protected: bool lessThan(const QModelIndex& left, const QModelIndex& right) const; }; - PodcastService::PodcastService(Application* app, InternetModel* parent) - : InternetService(kServiceName, app, parent, parent), - use_pretty_covers_(true), - icon_loader_(new StandardItemIconLoader(app->album_cover_loader(), this)), - backend_(app->podcast_backend()), - model_(new PodcastServiceModel(this)), - proxy_(new PodcastSortProxyModel(this)), - context_menu_(nullptr), - root_(nullptr), - organise_dialog_(new OrganiseDialog(app_->task_manager())) -{ + : InternetService(kServiceName, app, parent, parent), + use_pretty_covers_(true), + icon_loader_(new StandardItemIconLoader(app->album_cover_loader(), this)), + backend_(app->podcast_backend()), + model_(new PodcastServiceModel(this)), + proxy_(new PodcastSortProxyModel(this)), + context_menu_(nullptr), + root_(nullptr), + organise_dialog_(new OrganiseDialog(app_->task_manager())) { icon_loader_->SetModel(model_); proxy_->setSourceModel(model_); proxy_->setDynamicSortFilter(true); proxy_->sort(0); - connect(backend_, SIGNAL(SubscriptionAdded(Podcast)), SLOT(SubscriptionAdded(Podcast))); - connect(backend_, SIGNAL(SubscriptionRemoved(Podcast)), SLOT(SubscriptionRemoved(Podcast))); - connect(backend_, SIGNAL(EpisodesAdded(PodcastEpisodeList)), SLOT(EpisodesAdded(PodcastEpisodeList))); - connect(backend_, SIGNAL(EpisodesUpdated(PodcastEpisodeList)), SLOT(EpisodesUpdated(PodcastEpisodeList))); + connect(backend_, SIGNAL(SubscriptionAdded(Podcast)), + SLOT(SubscriptionAdded(Podcast))); + connect(backend_, SIGNAL(SubscriptionRemoved(Podcast)), + SLOT(SubscriptionRemoved(Podcast))); + connect(backend_, SIGNAL(EpisodesAdded(PodcastEpisodeList)), + SLOT(EpisodesAdded(PodcastEpisodeList))); + connect(backend_, SIGNAL(EpisodesUpdated(PodcastEpisodeList)), + SLOT(EpisodesUpdated(PodcastEpisodeList))); - connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), SLOT(CurrentSongChanged(Song))); + connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), + SLOT(CurrentSongChanged(Song))); } -PodcastService::~PodcastService() { -} +PodcastService::~PodcastService() {} PodcastSortProxyModel::PodcastSortProxyModel(QObject* parent) - : QSortFilterProxyModel(parent) { -} + : QSortFilterProxyModel(parent) {} -bool PodcastSortProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { - const int left_type = left.data(InternetModel::Role_Type).toInt(); +bool PodcastSortProxyModel::lessThan(const QModelIndex& left, + const QModelIndex& right) const { + const int left_type = left.data(InternetModel::Role_Type).toInt(); const int right_type = right.data(InternetModel::Role_Type).toInt(); // The special Add Podcast item comes first @@ -97,18 +98,21 @@ bool PodcastSortProxyModel::lessThan(const QModelIndex& left, const QModelIndex& return QSortFilterProxyModel::lessThan(left, right); switch (left_type) { - case PodcastService::Type_Podcast: - return left.data().toString().localeAwareCompare(right.data().toString()) < 0; + case PodcastService::Type_Podcast: + return left.data().toString().localeAwareCompare( + right.data().toString()) < 0; - case PodcastService::Type_Episode: { - const PodcastEpisode left_episode = left.data(PodcastService::Role_Episode).value(); - const PodcastEpisode right_episode = right.data(PodcastService::Role_Episode).value(); + case PodcastService::Type_Episode: { + const PodcastEpisode left_episode = + left.data(PodcastService::Role_Episode).value(); + const PodcastEpisode right_episode = + right.data(PodcastService::Role_Episode).value(); - return left_episode.publication_date() > right_episode.publication_date(); - } + return left_episode.publication_date() > right_episode.publication_date(); + } - default: - return QSortFilterProxyModel::lessThan(left, right); + default: + return QSortFilterProxyModel::lessThan(left, right); } } @@ -134,22 +138,21 @@ void PodcastService::CopyToDevice(const PodcastEpisodeList& episodes_list) { songs.append(episode.ToSong(podcast)); } - organise_dialog_->SetDestinationModel(app_->device_manager()->connected_devices_model(), true); + organise_dialog_->SetDestinationModel( + app_->device_manager()->connected_devices_model(), true); organise_dialog_->SetCopy(true); - if (organise_dialog_->SetSongs(songs)) - organise_dialog_->show(); + if (organise_dialog_->SetSongs(songs)) organise_dialog_->show(); } void PodcastService::CopyToDevice(const QModelIndexList& episode_indexes, - const QModelIndexList& podcast_indexes) { + const QModelIndexList& podcast_indexes) { PodcastEpisode episode_tmp; - SongList songs; + SongList songs; PodcastEpisodeList episodes; Podcast podcast; for (const QModelIndex& index : episode_indexes) { episode_tmp = index.data(Role_Episode).value(); - if (episode_tmp.downloaded()) - episodes << episode_tmp; + if (episode_tmp.downloaded()) episodes << episode_tmp; } for (const QModelIndex& podcast : podcast_indexes) { @@ -165,26 +168,28 @@ void PodcastService::CopyToDevice(const QModelIndexList& episode_indexes, songs.append(episode.ToSong(podcast)); } - organise_dialog_->SetDestinationModel(app_->device_manager()->connected_devices_model(), true); + organise_dialog_->SetDestinationModel( + app_->device_manager()->connected_devices_model(), true); organise_dialog_->SetCopy(true); - if (organise_dialog_->SetSongs(songs)) - organise_dialog_->show(); + if (organise_dialog_->SetSongs(songs)) organise_dialog_->show(); } void PodcastService::LazyPopulate(QStandardItem* parent) { switch (parent->data(InternetModel::Role_Type).toInt()) { - case InternetModel::Type_Service: - PopulatePodcastList(model_->invisibleRootItem()); - model()->merged_model()->AddSubModel(parent->index(), proxy_); - break; + case InternetModel::Type_Service: + PopulatePodcastList(model_->invisibleRootItem()); + model()->merged_model()->AddSubModel(parent->index(), proxy_); + break; } } void PodcastService::PopulatePodcastList(QStandardItem* parent) { // Do this here since the downloader won't be created yet in the ctor. - connect(app_->podcast_downloader(), - SIGNAL(ProgressChanged(PodcastEpisode, PodcastDownloader::State, int)), - SLOT(DownloadProgressChanged(PodcastEpisode, PodcastDownloader::State, int))); + connect( + app_->podcast_downloader(), + SIGNAL(ProgressChanged(PodcastEpisode, PodcastDownloader::State, int)), + SLOT(DownloadProgressChanged(PodcastEpisode, PodcastDownloader::State, + int))); if (default_icon_.isNull()) { default_icon_ = QIcon(":providers/podcast16.png"); @@ -195,7 +200,8 @@ void PodcastService::PopulatePodcastList(QStandardItem* parent) { } } -void PodcastService::UpdatePodcastText(QStandardItem* item, int unlistened_count) const { +void PodcastService::UpdatePodcastText(QStandardItem* item, + int unlistened_count) const { const Podcast podcast = item->data(Role_Podcast).value(); QString title = podcast.title().simplified(); @@ -216,7 +222,8 @@ void PodcastService::UpdatePodcastText(QStandardItem* item, int unlistened_count void PodcastService::UpdateEpisodeText(QStandardItem* item, PodcastDownloader::State state, int percent) { - const PodcastEpisode episode = item->data(Role_Episode).value(); + const PodcastEpisode episode = + item->data(Role_Episode).value(); QString title = episode.title().simplified(); QString tooltip; @@ -238,26 +245,27 @@ void PodcastService::UpdateEpisodeText(QStandardItem* item, // Queued or downloading episodes get icons, tooltips, and maybe a title. switch (state) { - case PodcastDownloader::Queued: - if (queued_icon_.isNull()) { - queued_icon_ = QIcon(":icons/22x22/user-away.png"); - } - icon = queued_icon_; - tooltip = tr("Download queued"); - break; + case PodcastDownloader::Queued: + if (queued_icon_.isNull()) { + queued_icon_ = QIcon(":icons/22x22/user-away.png"); + } + icon = queued_icon_; + tooltip = tr("Download queued"); + break; - case PodcastDownloader::Downloading: - if (downloading_icon_.isNull()) { - downloading_icon_ = IconLoader::Load("go-down"); - } - icon = downloading_icon_; - tooltip = tr("Downloading (%1%)...").arg(percent); - title = QString("[ %1% ] %2").arg(QString::number(percent), episode.title()); - break; + case PodcastDownloader::Downloading: + if (downloading_icon_.isNull()) { + downloading_icon_ = IconLoader::Load("go-down"); + } + icon = downloading_icon_; + tooltip = tr("Downloading (%1%)...").arg(percent); + title = + QString("[ %1% ] %2").arg(QString::number(percent), episode.title()); + break; - case PodcastDownloader::Finished: - case PodcastDownloader::NotDownloading: - break; + case PodcastDownloader::Finished: + case PodcastDownloader::NotDownloading: + break; } item->setFont(font); @@ -270,7 +278,8 @@ QStandardItem* PodcastService::CreatePodcastItem(const Podcast& podcast) { // Add the episodes in this podcast and gather aggregate stats. int unlistened_count = 0; - for (const PodcastEpisode& episode : backend_->GetEpisodes(podcast.database_id())) { + for (const PodcastEpisode& episode : + backend_->GetEpisodes(podcast.database_id())) { if (!episode.listened()) { unlistened_count++; } @@ -281,7 +290,8 @@ QStandardItem* PodcastService::CreatePodcastItem(const Podcast& podcast) { item->setIcon(default_icon_); item->setData(Type_Podcast, InternetModel::Role_Type); item->setData(QVariant::fromValue(podcast), Role_Podcast); - item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsSelectable); + item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | + Qt::ItemIsSelectable); UpdatePodcastText(item, unlistened_count); // Load the podcast's image if it has one @@ -294,13 +304,16 @@ QStandardItem* PodcastService::CreatePodcastItem(const Podcast& podcast) { return item; } -QStandardItem* PodcastService::CreatePodcastEpisodeItem(const PodcastEpisode& episode) { +QStandardItem* PodcastService::CreatePodcastEpisodeItem( + const PodcastEpisode& episode) { QStandardItem* item = new QStandardItem; item->setText(episode.title().simplified()); item->setData(Type_Episode, InternetModel::Role_Type); item->setData(QVariant::fromValue(episode), Role_Episode); - item->setData(InternetModel::PlayBehaviour_UseSongLoader, InternetModel::Role_PlayBehaviour); - item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsSelectable); + item->setData(InternetModel::PlayBehaviour_UseSongLoader, + InternetModel::Role_PlayBehaviour); + item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | + Qt::ItemIsSelectable); UpdateEpisodeText(item); @@ -312,47 +325,48 @@ QStandardItem* PodcastService::CreatePodcastEpisodeItem(const PodcastEpisode& ep void PodcastService::ShowContextMenu(const QPoint& global_pos) { if (!context_menu_) { context_menu_ = new QMenu; - context_menu_->addAction( - IconLoader::Load("list-add"), tr("Add podcast..."), - this, SLOT(AddPodcast())); - context_menu_->addAction( - IconLoader::Load("view-refresh"), tr("Update all podcasts"), - app_->podcast_updater(), SLOT(UpdateAllPodcastsNow())); + context_menu_->addAction(IconLoader::Load("list-add"), tr("Add podcast..."), + this, SLOT(AddPodcast())); + context_menu_->addAction(IconLoader::Load("view-refresh"), + tr("Update all podcasts"), app_->podcast_updater(), + SLOT(UpdateAllPodcastsNow())); context_menu_->addSeparator(); context_menu_->addActions(GetPlaylistActions()); context_menu_->addSeparator(); update_selected_action_ = context_menu_->addAction( - IconLoader::Load("view-refresh"), tr("Update this podcast"), - this, SLOT(UpdateSelectedPodcast())); - download_selected_action_ = context_menu_->addAction( - IconLoader::Load("download"), "", - this, SLOT(DownloadSelectedEpisode())); + IconLoader::Load("view-refresh"), tr("Update this podcast"), this, + SLOT(UpdateSelectedPodcast())); + download_selected_action_ = + context_menu_->addAction(IconLoader::Load("download"), "", this, + SLOT(DownloadSelectedEpisode())); delete_downloaded_action_ = context_menu_->addAction( - IconLoader::Load("edit-delete"), tr("Delete downloaded data"), - this, SLOT(DeleteDownloadedData())); + IconLoader::Load("edit-delete"), tr("Delete downloaded data"), this, + SLOT(DeleteDownloadedData())); copy_to_device_ = context_menu_->addAction( - IconLoader::Load("multimedia-player-ipod-mini-blue"), tr("Copy to device..."), - this, SLOT(CopyToDevice())); + IconLoader::Load("multimedia-player-ipod-mini-blue"), + tr("Copy to device..."), this, SLOT(CopyToDevice())); remove_selected_action_ = context_menu_->addAction( - IconLoader::Load("list-remove"), tr("Unsubscribe"), - this, SLOT(RemoveSelectedPodcast())); + IconLoader::Load("list-remove"), tr("Unsubscribe"), this, + SLOT(RemoveSelectedPodcast())); context_menu_->addSeparator(); - set_new_action_ = context_menu_->addAction( - tr("Mark as new"), this, SLOT(SetNew())); - set_listened_action_ = context_menu_->addAction( - tr("Mark as listened"), this, SLOT(SetListened())); + set_new_action_ = + context_menu_->addAction(tr("Mark as new"), this, SLOT(SetNew())); + set_listened_action_ = context_menu_->addAction(tr("Mark as listened"), + this, SLOT(SetListened())); context_menu_->addSeparator(); - context_menu_->addAction( - IconLoader::Load("configure"), tr("Configure podcasts..."), - this, SLOT(ShowConfig())); + context_menu_->addAction(IconLoader::Load("configure"), + tr("Configure podcasts..."), this, + SLOT(ShowConfig())); - copy_to_device_->setDisabled(app_->device_manager()->connected_devices_model()->rowCount() == 0); - connect(app_->device_manager()->connected_devices_model(), SIGNAL(IsEmptyChanged(bool)), - copy_to_device_, SLOT(setDisabled(bool))); + copy_to_device_->setDisabled( + app_->device_manager()->connected_devices_model()->rowCount() == 0); + connect(app_->device_manager()->connected_devices_model(), + SIGNAL(IsEmptyChanged(bool)), copy_to_device_, + SLOT(setDisabled(bool))); } selected_episodes_.clear(); @@ -362,28 +376,28 @@ void PodcastService::ShowContextMenu(const QPoint& global_pos) { for (const QModelIndex& index : model()->selected_indexes()) { switch (index.data(InternetModel::Role_Type).toInt()) { - case Type_Podcast: { - const int id = index.data(Role_Podcast).value().database_id(); - if (!podcast_ids.contains(id)) { - selected_podcasts_.append(index); - explicitly_selected_podcasts_.append(index); - podcast_ids.insert(id); + case Type_Podcast: { + const int id = index.data(Role_Podcast).value().database_id(); + if (!podcast_ids.contains(id)) { + selected_podcasts_.append(index); + explicitly_selected_podcasts_.append(index); + podcast_ids.insert(id); + } + break; } - break; - } - case Type_Episode: { - selected_episodes_.append(index); + case Type_Episode: { + selected_episodes_.append(index); - // Add the parent podcast as well. - const QModelIndex parent = index.parent(); - const int id = parent.data(Role_Podcast).value().database_id(); - if (!podcast_ids.contains(id)) { - selected_podcasts_.append(parent); - podcast_ids.insert(id); + // Add the parent podcast as well. + const QModelIndex parent = index.parent(); + const int id = parent.data(Role_Podcast).value().database_id(); + if (!podcast_ids.contains(id)) { + selected_podcasts_.append(parent); + podcast_ids.insert(id); + } + break; } - break; - } } } @@ -396,7 +410,8 @@ void PodcastService::ShowContextMenu(const QPoint& global_pos) { set_listened_action_->setEnabled(episodes || podcasts); if (selected_episodes_.count() == 1) { - const PodcastEpisode episode = selected_episodes_[0].data(Role_Episode).value(); + const PodcastEpisode episode = + selected_episodes_[0].data(Role_Episode).value(); const bool downloaded = episode.downloaded(); const bool listened = episode.listened(); @@ -418,7 +433,8 @@ void PodcastService::ShowContextMenu(const QPoint& global_pos) { } if (selected_episodes_.count() > 1) { - download_selected_action_->setText(tr("Download %n episodes", "", selected_episodes_.count())); + download_selected_action_->setText( + tr("Download %n episodes", "", selected_episodes_.count())); } else { download_selected_action_->setText(tr("Download this episode")); } @@ -433,7 +449,7 @@ void PodcastService::ShowContextMenu(const QPoint& global_pos) { void PodcastService::UpdateSelectedPodcast() { for (const QModelIndex& index : selected_podcasts_) { app_->podcast_updater()->UpdatePodcastNow( - index.data(Role_Podcast).value()); + index.data(Role_Podcast).value()); } } @@ -483,8 +499,9 @@ void PodcastService::SubscriptionRemoved(const Podcast& podcast) { // Remove any episode ID -> item mappings for the episodes in this podcast. for (int i = 0; i < item->rowCount(); ++i) { QStandardItem* episode_item = item->child(i); - const int episode_id = - episode_item->data(Role_Episode).value().database_id(); + const int episode_id = episode_item->data(Role_Episode) + .value() + .database_id(); episodes_by_database_id_.remove(episode_id); } @@ -500,8 +517,7 @@ void PodcastService::EpisodesAdded(const PodcastEpisodeList& episodes) { for (const PodcastEpisode& episode : episodes) { const int database_id = episode.podcast_database_id(); QStandardItem* parent = podcasts_by_database_id_[database_id]; - if (!parent) - continue; + if (!parent) continue; parent->appendRow(CreatePodcastEpisodeItem(episode)); @@ -527,8 +543,7 @@ void PodcastService::EpisodesUpdated(const PodcastEpisodeList& episodes) { const int podcast_database_id = episode.podcast_database_id(); QStandardItem* item = episodes_by_database_id_[episode.database_id()]; QStandardItem* parent = podcasts_by_database_id_[podcast_database_id]; - if (!item || !parent) - continue; + if (!item || !parent) continue; // Update the episode data on the item, and update the item's text. item->setData(QVariant::fromValue(episode), Role_Episode); @@ -538,7 +553,8 @@ void PodcastService::EpisodesUpdated(const PodcastEpisodeList& episodes) { if (!seen_podcast_ids.contains(podcast_database_id)) { // Update the unlistened count text once for each podcast int unlistened_count = 0; - for (const PodcastEpisode& episode : backend_->GetEpisodes(podcast_database_id)) { + for (const PodcastEpisode& episode : + backend_->GetEpisodes(podcast_database_id)) { if (!episode.listened()) { unlistened_count++; } @@ -553,14 +569,14 @@ void PodcastService::EpisodesUpdated(const PodcastEpisodeList& episodes) { void PodcastService::DownloadSelectedEpisode() { for (const QModelIndex& index : selected_episodes_) { app_->podcast_downloader()->DownloadEpisode( - index.data(Role_Episode).value()); + index.data(Role_Episode).value()); } } void PodcastService::DeleteDownloadedData() { for (const QModelIndex& index : selected_episodes_) { app_->podcast_downloader()->DeleteEpisode( - index.data(Role_Episode).value()); + index.data(Role_Episode).value()); } } @@ -568,8 +584,7 @@ void PodcastService::DownloadProgressChanged(const PodcastEpisode& episode, PodcastDownloader::State state, int percent) { QStandardItem* item = episodes_by_database_id_[episode.database_id()]; - if (!item) - return; + if (!item) return; UpdateEpisodeText(item, state, percent); } @@ -581,8 +596,7 @@ void PodcastService::ShowConfig() { void PodcastService::CurrentSongChanged(const Song& metadata) { // Check whether this song is one of our podcast episodes. PodcastEpisode episode = backend_->GetEpisodeByUrlOrLocalUrl(metadata.url()); - if (!episode.is_valid()) - return; + if (!episode.is_valid()) return; // Mark it as listened if it's not already if (!episode.listened()) { diff --git a/src/podcasts/podcastservice.h b/src/podcasts/podcastservice.h index 40e135748..1cf0f63fc 100644 --- a/src/podcasts/podcastservice.h +++ b/src/podcasts/podcastservice.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -37,7 +37,7 @@ class QSortFilterProxyModel; class PodcastService : public InternetService { Q_OBJECT -public: + public: PodcastService(Application* app, InternetModel* parent); ~PodcastService(); @@ -50,11 +50,8 @@ public: Type_Episode }; - enum Role { - Role_Podcast = InternetModel::RoleCount, - Role_Episode - }; - + enum Role { Role_Podcast = InternetModel::RoleCount, Role_Episode }; + QStandardItem* CreateRootItem(); void LazyPopulate(QStandardItem* parent); @@ -65,11 +62,11 @@ public: // subscription to the podcast and displays it in the UI. If the QVariant // contains an OPML file then this displays it in the Add Podcast dialog. void SubscribeAndShow(const QVariant& podcast_or_opml); - -public slots: + + public slots: void AddPodcast(); -private slots: + private slots: void UpdateSelectedPodcast(); void RemoveSelectedPodcast(); void DownloadSelectedEpisode(); @@ -84,24 +81,24 @@ private slots: void EpisodesUpdated(const PodcastEpisodeList& episodes); void DownloadProgressChanged(const PodcastEpisode& episode, - PodcastDownloader::State state, - int percent); + PodcastDownloader::State state, int percent); void CurrentSongChanged(const Song& metadata); void CopyToDevice(); void CopyToDevice(const PodcastEpisodeList& episodes_list); void CopyToDevice(const QModelIndexList& episode_indexes, - const QModelIndexList& podcast_indexes); + const QModelIndexList& podcast_indexes); -private: + private: void EnsureAddPodcastDialogCreated(); void PopulatePodcastList(QStandardItem* parent); void UpdatePodcastText(QStandardItem* item, int unlistened_count) const; - void UpdateEpisodeText(QStandardItem* item, - PodcastDownloader::State state = PodcastDownloader::NotDownloading, - int percent = 0); + void UpdateEpisodeText( + QStandardItem* item, + PodcastDownloader::State state = PodcastDownloader::NotDownloading, + int percent = 0); QStandardItem* CreatePodcastItem(const Podcast& podcast); QStandardItem* CreatePodcastEpisodeItem(const PodcastEpisode& episode); @@ -109,14 +106,12 @@ private: QModelIndex MapToMergedModel(const QModelIndex& index) const; void SetListened(const QModelIndexList& episode_indexes, - const QModelIndexList& podcast_indexes, - bool listened); - void SetListened(const PodcastEpisodeList& episodes_list, - bool listened); + const QModelIndexList& podcast_indexes, bool listened); + void SetListened(const PodcastEpisodeList& episodes_list, bool listened); void LazyLoadRoot(); -private: + private: bool use_pretty_covers_; StandardItemIconLoader* icon_loader_; @@ -153,4 +148,4 @@ private: QScopedPointer add_podcast_dialog_; }; -#endif // PODCASTSERVICE_H +#endif // PODCASTSERVICE_H diff --git a/src/podcasts/podcastservicemodel.cpp b/src/podcasts/podcastservicemodel.cpp index 1aab9cb07..5bd7ecb6b 100644 --- a/src/podcasts/podcastservicemodel.cpp +++ b/src/podcasts/podcastservicemodel.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -20,23 +20,21 @@ #include "playlist/songmimedata.h" PodcastServiceModel::PodcastServiceModel(QObject* parent) - : QStandardItemModel(parent) -{ -} + : QStandardItemModel(parent) {} QMimeData* PodcastServiceModel::mimeData(const QModelIndexList& indexes) const { SongMimeData* data = new SongMimeData; QList urls; - foreach (const QModelIndex& index, indexes) { + foreach(const QModelIndex & index, indexes) { switch (index.data(InternetModel::Role_Type).toInt()) { - case PodcastService::Type_Episode: - MimeDataForEpisode(index, data, &urls); - break; + case PodcastService::Type_Episode: + MimeDataForEpisode(index, data, &urls); + break; - case PodcastService::Type_Podcast: - MimeDataForPodcast(index, data, &urls); - break; + case PodcastService::Type_Podcast: + MimeDataForPodcast(index, data, &urls); + break; } } @@ -45,10 +43,10 @@ QMimeData* PodcastServiceModel::mimeData(const QModelIndexList& indexes) const { } void PodcastServiceModel::MimeDataForEpisode(const QModelIndex& index, - SongMimeData* data, QList* urls) const { + SongMimeData* data, + QList* urls) const { QVariant episode_variant = index.data(PodcastService::Role_Episode); - if (!episode_variant.isValid()) - return; + if (!episode_variant.isValid()) return; PodcastEpisode episode(episode_variant.value()); @@ -66,7 +64,8 @@ void PodcastServiceModel::MimeDataForEpisode(const QModelIndex& index, } void PodcastServiceModel::MimeDataForPodcast(const QModelIndex& index, - SongMimeData* data, QList* urls) const { + SongMimeData* data, + QList* urls) const { // Get the podcast Podcast podcast; QVariant podcast_variant = index.data(PodcastService::Role_Podcast); @@ -76,10 +75,10 @@ void PodcastServiceModel::MimeDataForPodcast(const QModelIndex& index, // Add each child episode const int children = index.model()->rowCount(index); - for (int i=0 ; i()); Song song = episode.ToSong(podcast); diff --git a/src/podcasts/podcastservicemodel.h b/src/podcasts/podcastservicemodel.h index 463150f8b..15f78451c 100644 --- a/src/podcasts/podcastservicemodel.h +++ b/src/podcasts/podcastservicemodel.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -25,16 +25,16 @@ class SongMimeData; class PodcastServiceModel : public QStandardItemModel { Q_OBJECT -public: + public: PodcastServiceModel(QObject* parent = 0); - + QMimeData* mimeData(const QModelIndexList& indexes) const; -private: - void MimeDataForPodcast(const QModelIndex& index, - SongMimeData* data, QList* urls) const; - void MimeDataForEpisode(const QModelIndex& index, - SongMimeData* data, QList* urls) const; + private: + void MimeDataForPodcast(const QModelIndex& index, SongMimeData* data, + QList* urls) const; + void MimeDataForEpisode(const QModelIndex& index, SongMimeData* data, + QList* urls) const; }; -#endif // PODCASTSERVICEMODEL_H +#endif // PODCASTSERVICEMODEL_H diff --git a/src/podcasts/podcastsettingspage.cpp b/src/podcasts/podcastsettingspage.cpp index f8f92e029..778135d12 100644 --- a/src/podcasts/podcastsettingspage.cpp +++ b/src/podcasts/podcastsettingspage.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -33,40 +33,38 @@ const char* PodcastSettingsPage::kSettingsGroup = "Podcasts"; PodcastSettingsPage::PodcastSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_PodcastSettingsPage) -{ + : SettingsPage(dialog), ui_(new Ui_PodcastSettingsPage) { ui_->setupUi(this); connect(ui_->login, SIGNAL(clicked()), SLOT(LoginClicked())); connect(ui_->login_state, SIGNAL(LoginClicked()), SLOT(LoginClicked())); connect(ui_->login_state, SIGNAL(LogoutClicked()), SLOT(LogoutClicked())); - connect(ui_->download_dir_browse, SIGNAL(clicked()), SLOT(DownloadDirBrowse())); + connect(ui_->download_dir_browse, SIGNAL(clicked()), + SLOT(DownloadDirBrowse())); ui_->login_state->AddCredentialField(ui_->username); ui_->login_state->AddCredentialField(ui_->device_name); ui_->login_state->AddCredentialField(ui_->password); ui_->login_state->AddCredentialGroup(ui_->login_group); - ui_->check_interval->setItemData(0, 0); // manually - ui_->check_interval->setItemData(1, 10*60); // 10 minutes - ui_->check_interval->setItemData(2, 20*60); // 20 minutes - ui_->check_interval->setItemData(3, 30*60); // 30 minutes - ui_->check_interval->setItemData(4, 60*60); // 1 hour - ui_->check_interval->setItemData(5, 2*60*60); // 2 hours - ui_->check_interval->setItemData(6, 6*60*60); // 6 hours - ui_->check_interval->setItemData(7, 12*60*60); // 12 hours + ui_->check_interval->setItemData(0, 0); // manually + ui_->check_interval->setItemData(1, 10 * 60); // 10 minutes + ui_->check_interval->setItemData(2, 20 * 60); // 20 minutes + ui_->check_interval->setItemData(3, 30 * 60); // 30 minutes + ui_->check_interval->setItemData(4, 60 * 60); // 1 hour + ui_->check_interval->setItemData(5, 2 * 60 * 60); // 2 hours + ui_->check_interval->setItemData(6, 6 * 60 * 60); // 6 hours + ui_->check_interval->setItemData(7, 12 * 60 * 60); // 12 hours } -PodcastSettingsPage::~PodcastSettingsPage() { - delete ui_; -} +PodcastSettingsPage::~PodcastSettingsPage() { delete ui_; } void PodcastSettingsPage::Load() { QSettings s; s.beginGroup(kSettingsGroup); const int update_interval = s.value("update_interval_secs", 0).toInt(); - ui_->check_interval->setCurrentIndex(ui_->check_interval->findData(update_interval)); + ui_->check_interval->setCurrentIndex( + ui_->check_interval->findData(update_interval)); const QString default_download_dir = dialog()->app()->podcast_downloader()->DefaultDownloadDir(); @@ -76,10 +74,13 @@ void PodcastSettingsPage::Load() { ui_->auto_download->setChecked(s.value("auto_download", false).toBool()); ui_->delete_after->setValue(s.value("delete_after", 0).toInt() / kSecsPerDay); ui_->username->setText(s.value("gpodder_username").toString()); - ui_->device_name->setText(s.value("gpodder_device_name", GPodderSync::DefaultDeviceName()).toString()); + ui_->device_name->setText( + s.value("gpodder_device_name", GPodderSync::DefaultDeviceName()) + .toString()); if (dialog()->app()->gpodder_sync()->is_logged_in()) { - ui_->login_state->SetLoggedIn(LoginStateWidget::LoggedIn, ui_->username->text()); + ui_->login_state->SetLoggedIn(LoginStateWidget::LoggedIn, + ui_->username->text()); } else { ui_->login_state->SetLoggedIn(LoginStateWidget::LoggedOut); } @@ -89,9 +90,10 @@ void PodcastSettingsPage::Save() { QSettings s; s.beginGroup(kSettingsGroup); - s.setValue("update_interval_secs", - ui_->check_interval->itemData(ui_->check_interval->currentIndex())); - s.setValue("download_dir", QDir::fromNativeSeparators(ui_->download_dir->text())); + s.setValue("update_interval_secs", ui_->check_interval->itemData( + ui_->check_interval->currentIndex())); + s.setValue("download_dir", + QDir::fromNativeSeparators(ui_->download_dir->text())); s.setValue("auto_download", ui_->auto_download->isChecked()); s.setValue("delete_after", ui_->delete_after->value() * kSecsPerDay); s.setValue("gpodder_device_name", ui_->device_name->text()); @@ -101,18 +103,17 @@ void PodcastSettingsPage::LoginClicked() { ui_->login_state->SetLoggedIn(LoginStateWidget::LoginInProgress); QNetworkReply* reply = dialog()->app()->gpodder_sync()->Login( - ui_->username->text(), ui_->password->text(), ui_->device_name->text()); + ui_->username->text(), ui_->password->text(), ui_->device_name->text()); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(LoginFinished(QNetworkReply*)), - reply); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(LoginFinished(QNetworkReply*)), reply); } void PodcastSettingsPage::LoginFinished(QNetworkReply* reply) { const bool success = reply->error() == QNetworkReply::NoError; - ui_->login_state->SetLoggedIn(success ? LoginStateWidget::LoggedIn - : LoginStateWidget::LoggedOut, - ui_->username->text()); + ui_->login_state->SetLoggedIn( + success ? LoginStateWidget::LoggedIn : LoginStateWidget::LoggedOut, + ui_->username->text()); ui_->login_state->SetAccountTypeVisible(!success); if (!success) { @@ -129,9 +130,8 @@ void PodcastSettingsPage::LogoutClicked() { void PodcastSettingsPage::DownloadDirBrowse() { QString directory = QFileDialog::getExistingDirectory( - this, tr("Choose podcast download directory"), ui_->download_dir->text()); - if (directory.isEmpty()) - return; + this, tr("Choose podcast download directory"), ui_->download_dir->text()); + if (directory.isEmpty()) return; ui_->download_dir->setText(QDir::toNativeSeparators(directory)); } diff --git a/src/podcasts/podcastsettingspage.h b/src/podcasts/podcastsettingspage.h index 46f8cc850..c3a51565f 100644 --- a/src/podcasts/podcastsettingspage.h +++ b/src/podcasts/podcastsettingspage.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -27,7 +27,7 @@ class QNetworkReply; class PodcastSettingsPage : public SettingsPage { Q_OBJECT -public: + public: PodcastSettingsPage(SettingsDialog* dialog); ~PodcastSettingsPage(); @@ -36,15 +36,15 @@ public: void Load(); void Save(); -private slots: + private slots: void LoginClicked(); void LoginFinished(QNetworkReply* reply); void LogoutClicked(); void DownloadDirBrowse(); -private: + private: Ui_PodcastSettingsPage* ui_; }; -#endif // PODCASTSETTINGSPAGE_H +#endif // PODCASTSETTINGSPAGE_H diff --git a/src/podcasts/podcastupdater.cpp b/src/podcasts/podcastupdater.cpp index 411009243..1720714d2 100644 --- a/src/podcasts/podcastupdater.cpp +++ b/src/podcasts/podcastupdater.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -30,13 +30,12 @@ const char* PodcastUpdater::kSettingsGroup = "Podcasts"; PodcastUpdater::PodcastUpdater(Application* app, QObject* parent) - : QObject(parent), - app_(app), - update_interval_secs_(0), - update_timer_(new QTimer(this)), - loader_(new PodcastUrlLoader(this)), - pending_replies_(0) -{ + : QObject(parent), + app_(app), + update_interval_secs_(0), + update_timer_(new QTimer(this)), + loader_(new PodcastUrlLoader(this)), + pending_replies_(0) { connect(app_, SIGNAL(SettingsChanged()), SLOT(ReloadSettings())); connect(update_timer_, SIGNAL(timeout()), SLOT(UpdateAllPodcastsNow())); connect(app_->podcast_backend(), SIGNAL(SubscriptionAdded(Podcast)), @@ -78,14 +77,18 @@ void PodcastUpdater::RestartTimer() { qLog(Info) << "Updating podcasts for the first time"; UpdateAllPodcastsNow(); } else { - const QDateTime next_update = last_full_update_.addSecs(update_interval_secs_); - const int secs_until_next_update = QDateTime::currentDateTime().secsTo(next_update); + const QDateTime next_update = + last_full_update_.addSecs(update_interval_secs_); + const int secs_until_next_update = + QDateTime::currentDateTime().secsTo(next_update); if (secs_until_next_update < 0) { - qLog(Info) << "Updating podcasts" << (-secs_until_next_update) << "seconds late"; + qLog(Info) << "Updating podcasts" << (-secs_until_next_update) + << "seconds late"; UpdateAllPodcastsNow(); } else { - qLog(Info) << "Updating podcasts at" << next_update << "(in" << secs_until_next_update << "seconds)"; + qLog(Info) << "Updating podcasts at" << next_update << "(in" + << secs_until_next_update << "seconds)"; update_timer_->start(secs_until_next_update * kMsecPerSec); } } @@ -103,24 +106,25 @@ void PodcastUpdater::SubscriptionAdded(const Podcast& podcast) { void PodcastUpdater::UpdatePodcastNow(const Podcast& podcast) { PodcastUrlLoaderReply* reply = loader_->Load(podcast.url()); - NewClosure(reply, SIGNAL(Finished(bool)), - this, SLOT(PodcastLoaded(PodcastUrlLoaderReply*,Podcast,bool)), - reply, podcast, false); + NewClosure(reply, SIGNAL(Finished(bool)), this, + SLOT(PodcastLoaded(PodcastUrlLoaderReply*, Podcast, bool)), reply, + podcast, false); } void PodcastUpdater::UpdateAllPodcastsNow() { - foreach (const Podcast& podcast, app_->podcast_backend()->GetAllSubscriptions()) { + foreach(const Podcast & podcast, + app_->podcast_backend()->GetAllSubscriptions()) { PodcastUrlLoaderReply* reply = loader_->Load(podcast.url()); - NewClosure(reply, SIGNAL(Finished(bool)), - this, SLOT(PodcastLoaded(PodcastUrlLoaderReply*,Podcast,bool)), + NewClosure(reply, SIGNAL(Finished(bool)), this, + SLOT(PodcastLoaded(PodcastUrlLoaderReply*, Podcast, bool)), reply, podcast, true); - pending_replies_ ++; + pending_replies_++; } } -void PodcastUpdater::PodcastLoaded(PodcastUrlLoaderReply* reply, const Podcast& podcast, - bool one_of_many) { +void PodcastUpdater::PodcastLoaded(PodcastUrlLoaderReply* reply, + const Podcast& podcast, bool one_of_many) { reply->deleteLater(); if (one_of_many) { @@ -140,21 +144,22 @@ void PodcastUpdater::PodcastLoaded(PodcastUrlLoaderReply* reply, const Podcast& } if (reply->result_type() != PodcastUrlLoaderReply::Type_Podcast) { - qLog(Warning) << "The URL" << podcast.url() << "no longer contains a podcast"; + qLog(Warning) << "The URL" << podcast.url() + << "no longer contains a podcast"; return; } // Get the episode URLs we had for this podcast already. QSet existing_urls; - foreach (const PodcastEpisode& episode, - app_->podcast_backend()->GetEpisodes(podcast.database_id())) { + foreach(const PodcastEpisode & episode, + app_->podcast_backend()->GetEpisodes(podcast.database_id())) { existing_urls.insert(episode.url()); } // Add any new episodes PodcastEpisodeList new_episodes; - foreach (const Podcast& reply_podcast, reply->podcast_results()) { - foreach (const PodcastEpisode& episode, reply_podcast.episodes()) { + foreach(const Podcast & reply_podcast, reply->podcast_results()) { + foreach(const PodcastEpisode & episode, reply_podcast.episodes()) { if (!existing_urls.contains(episode.url())) { PodcastEpisode episode_copy(episode); episode_copy.set_podcast_database_id(podcast.database_id()); @@ -164,5 +169,6 @@ void PodcastUpdater::PodcastLoaded(PodcastUrlLoaderReply* reply, const Podcast& } app_->podcast_backend()->AddEpisodes(&new_episodes); - qLog(Info) << "Added" << new_episodes.count() << "new episodes for" << podcast.url(); + qLog(Info) << "Added" << new_episodes.count() << "new episodes for" + << podcast.url(); } diff --git a/src/podcasts/podcastupdater.h b/src/podcasts/podcastupdater.h index feb5cd670..4340537a0 100644 --- a/src/podcasts/podcastupdater.h +++ b/src/podcasts/podcastupdater.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -33,27 +33,27 @@ class QTimer; class PodcastUpdater : public QObject { Q_OBJECT -public: + public: PodcastUpdater(Application* app, QObject* parent = 0); static const char* kSettingsGroup; -public slots: + public slots: void UpdateAllPodcastsNow(); void UpdatePodcastNow(const Podcast& podcast); -private slots: + private slots: void ReloadSettings(); void SubscriptionAdded(const Podcast& podcast); void PodcastLoaded(PodcastUrlLoaderReply* reply, const Podcast& podcast, bool one_of_many); -private: + private: void RestartTimer(); void SaveSettings(); -private: + private: Application* app_; QDateTime last_full_update_; @@ -64,4 +64,4 @@ private: int pending_replies_; }; -#endif // PODCASTUPDATER_H +#endif // PODCASTUPDATER_H diff --git a/src/podcasts/podcasturlloader.cpp b/src/podcasts/podcasturlloader.cpp index 849fd409c..15247c077 100644 --- a/src/podcasts/podcasturlloader.cpp +++ b/src/podcasts/podcasturlloader.cpp @@ -27,38 +27,36 @@ const int PodcastUrlLoader::kMaxRedirects = 5; - PodcastUrlLoader::PodcastUrlLoader(QObject* parent) - : QObject(parent), - network_(new NetworkAccessManager(this)), - parser_(new PodcastParser), - html_link_re_(""), - html_link_rel_re_("rel\\s*=\\s*['\"]?\\s*alternate"), - html_link_type_re_("type\\s*=\\s*['\"]?([^'\" ]+)"), - html_link_href_re_("href\\s*=\\s*['\"]?([^'\" ]+)") -{ + : QObject(parent), + network_(new NetworkAccessManager(this)), + parser_(new PodcastParser), + html_link_re_(""), + html_link_rel_re_("rel\\s*=\\s*['\"]?\\s*alternate"), + html_link_type_re_("type\\s*=\\s*['\"]?([^'\" ]+)"), + html_link_href_re_("href\\s*=\\s*['\"]?([^'\" ]+)") { html_link_re_.setMinimal(true); html_link_re_.setCaseSensitivity(Qt::CaseInsensitive); } -PodcastUrlLoader::~PodcastUrlLoader() { - delete parser_; -} +PodcastUrlLoader::~PodcastUrlLoader() { delete parser_; } QUrl PodcastUrlLoader::FixPodcastUrl(const QString& url_text) { QString url_text_copy(url_text.trimmed()); // Thanks gpodder! - QuickPrefixList quick_prefixes = QuickPrefixList() + QuickPrefixList quick_prefixes = + QuickPrefixList() << QuickPrefix("fb:", "http://feeds.feedburner.com/%1") << QuickPrefix("yt:", "https://www.youtube.com/rss/user/%1/videos.rss") << QuickPrefix("sc:", "https://soundcloud.com/%1") << QuickPrefix("fm4od:", "http://onapp1.orf.at/webcam/fm4/fod/%1.xspf") - << QuickPrefix("ytpl:", "https://gdata.youtube.com/feeds/api/playlists/%1"); + << QuickPrefix("ytpl:", + "https://gdata.youtube.com/feeds/api/playlists/%1"); // Check if it matches one of the quick prefixes. - for (QuickPrefixList::const_iterator it = quick_prefixes.constBegin() ; - it != quick_prefixes.constEnd() ; ++it) { + for (QuickPrefixList::const_iterator it = quick_prefixes.constBegin(); + it != quick_prefixes.constEnd(); ++it) { if (url_text_copy.startsWith(it->first)) { url_text_copy = it->second.arg(url_text_copy.mid(it->first.length())); } @@ -105,7 +103,8 @@ PodcastUrlLoaderReply* PodcastUrlLoader::Load(const QUrl& url) { return reply; } -void PodcastUrlLoader::SendErrorAndDelete(const QString& error_text, RequestState* state) { +void PodcastUrlLoader::SendErrorAndDelete(const QString& error_text, + RequestState* state) { state->reply_->SetFinished(error_text); delete state; } @@ -120,20 +119,22 @@ void PodcastUrlLoader::NextRequest(const QUrl& url, RequestState* state) { qLog(Debug) << "Loading URL" << url; QNetworkRequest req(url); - req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork); + req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, + QNetworkRequest::AlwaysNetwork); QNetworkReply* network_reply = network_->get(req); - NewClosure(network_reply, SIGNAL(finished()), - this, SLOT(RequestFinished(RequestState*, QNetworkReply*)), - state, network_reply); + NewClosure(network_reply, SIGNAL(finished()), this, + SLOT(RequestFinished(RequestState*, QNetworkReply*)), state, + network_reply); } -void PodcastUrlLoader::RequestFinished(RequestState* state, QNetworkReply* reply) { +void PodcastUrlLoader::RequestFinished(RequestState* state, + QNetworkReply* reply) { reply->deleteLater(); if (reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid()) { const QUrl next_url = reply->url().resolved( - reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl()); + reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl()); NextRequest(next_url, state); return; @@ -148,14 +149,19 @@ void PodcastUrlLoader::RequestFinished(RequestState* state, QNetworkReply* reply const QVariant http_status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if (http_status.isValid() && http_status.toInt() != 200) { - SendErrorAndDelete(QString("HTTP %1: %2").arg( - reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString(), - reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()), state); + SendErrorAndDelete( + QString("HTTP %1: %2") + .arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) + .toString(), + reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute) + .toString()), + state); return; } // Check the mime type. - const QString content_type = reply->header(QNetworkRequest::ContentTypeHeader).toString(); + const QString content_type = + reply->header(QNetworkRequest::ContentTypeHeader).toString(); if (parser_->SupportsContentType(content_type)) { const QVariant ret = parser_->Load(reply, reply->url()); @@ -164,7 +170,8 @@ void PodcastUrlLoader::RequestFinished(RequestState* state, QNetworkReply* reply } else if (ret.canConvert()) { state->reply_->SetFinished(ret.value()); } else { - SendErrorAndDelete(tr("Failed to parse the XML for this RSS feed"), state); + SendErrorAndDelete(tr("Failed to parse the XML for this RSS feed"), + state); return; } @@ -185,7 +192,8 @@ void PodcastUrlLoader::RequestFinished(RequestState* state, QNetworkReply* reply } const QString link_type = html_link_type_re_.cap(1); - const QString href = Utilities::DecodeHtmlEntities(html_link_href_re_.cap(1)); + const QString href = + Utilities::DecodeHtmlEntities(html_link_href_re_.cap(1)); if (parser_->supported_mime_types().contains(link_type)) { NextRequest(QUrl(href), state); @@ -199,13 +207,8 @@ void PodcastUrlLoader::RequestFinished(RequestState* state, QNetworkReply* reply } } - PodcastUrlLoaderReply::PodcastUrlLoaderReply(const QUrl& url, QObject* parent) - : QObject(parent), - url_(url), - finished_(false) -{ -} + : QObject(parent), url_(url), finished_(false) {} void PodcastUrlLoaderReply::SetFinished(const PodcastList& results) { result_type_ = Type_Podcast; diff --git a/src/podcasts/podcasturlloader.h b/src/podcasts/podcasturlloader.h index 9f4e0ee91..aa910cc26 100644 --- a/src/podcasts/podcasturlloader.h +++ b/src/podcasts/podcasturlloader.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -32,13 +32,10 @@ class QNetworkReply; class PodcastUrlLoaderReply : public QObject { Q_OBJECT -public: + public: PodcastUrlLoaderReply(const QUrl& url, QObject* parent); - enum ResultType { - Type_Podcast, - Type_Opml - }; + enum ResultType { Type_Podcast, Type_Opml }; const QUrl& url() const { return url_; } bool is_finished() const { return finished_; } @@ -56,7 +53,7 @@ public: signals: void Finished(bool success); -private: + private: QUrl url_; bool finished_; QString error_text_; @@ -66,11 +63,10 @@ private: OpmlContainer opml_results_; }; - class PodcastUrlLoader : public QObject { Q_OBJECT -public: + public: PodcastUrlLoader(QObject* parent = 0); ~PodcastUrlLoader(); @@ -86,7 +82,7 @@ public: static QUrl FixPodcastUrl(const QString& url_text); static QUrl FixPodcastUrl(const QUrl& url); -private: + private: struct RequestState { int redirects_remaining_; PodcastUrlLoaderReply* reply_; @@ -95,14 +91,14 @@ private: typedef QPair QuickPrefix; typedef QList QuickPrefixList; -private slots: + private slots: void RequestFinished(RequestState* state, QNetworkReply* reply); -private: + private: void SendErrorAndDelete(const QString& error_text, RequestState* state); void NextRequest(const QUrl& url, RequestState* state); -private: + private: QNetworkAccessManager* network_; PodcastParser* parser_; @@ -113,4 +109,4 @@ private: QRegExp html_link_href_re_; }; -#endif // PODCASTURLLOADER_H +#endif // PODCASTURLLOADER_H diff --git a/src/smartplaylists/generator.cpp b/src/smartplaylists/generator.cpp index 58cb864b1..b8a935128 100644 --- a/src/smartplaylists/generator.cpp +++ b/src/smartplaylists/generator.cpp @@ -28,11 +28,7 @@ const int Generator::kDefaultLimit = 20; const int Generator::kDefaultDynamicHistory = 5; const int Generator::kDefaultDynamicFuture = 15; -Generator::Generator() - : QObject(nullptr), - backend_(nullptr) -{ -} +Generator::Generator() : QObject(nullptr), backend_(nullptr) {} GeneratorPtr Generator::Create(const QString& type) { if (type == "Query") @@ -44,5 +40,4 @@ GeneratorPtr Generator::Create(const QString& type) { return GeneratorPtr(); } -} // namespace - +} // namespace diff --git a/src/smartplaylists/generator.h b/src/smartplaylists/generator.h index 561e3b8f5..52df8ac76 100644 --- a/src/smartplaylists/generator.h +++ b/src/smartplaylists/generator.h @@ -26,10 +26,11 @@ class LibraryBackend; namespace smart_playlists { -class Generator : public QObject, public std::enable_shared_from_this { +class Generator : public QObject, + public std::enable_shared_from_this { Q_OBJECT -public: + public: Generator(); static const int kDefaultLimit; @@ -60,27 +61,30 @@ public: // If the generator can be used as a dynamic playlist then GenerateMore // should return the next tracks in the sequence. The subclass should - // remember the last GetDynamicHistory() + GetDynamicFuture() tracks and ensure that + // remember the last GetDynamicHistory() + GetDynamicFuture() tracks and + // ensure that // the tracks returned from this method are not in that set. virtual bool is_dynamic() const { return false; } virtual void set_dynamic(bool dynamic) {} // Called from non-UI thread. - virtual PlaylistItemList GenerateMore(int count) { return PlaylistItemList(); } + virtual PlaylistItemList GenerateMore(int count) { + return PlaylistItemList(); + } - virtual int GetDynamicHistory () { return kDefaultDynamicHistory; } - virtual int GetDynamicFuture () { return kDefaultDynamicFuture; } + virtual int GetDynamicHistory() { return kDefaultDynamicHistory; } + virtual int GetDynamicFuture() { return kDefaultDynamicFuture; } signals: void Error(const QString& message); -protected: + protected: LibraryBackend* backend_; -private: + private: QString name_; }; -} // namespace +} // namespace #include "generator_fwd.h" -#endif // PLAYLISTGENERATOR_H +#endif // PLAYLISTGENERATOR_H diff --git a/src/smartplaylists/generator_fwd.h b/src/smartplaylists/generator_fwd.h index 4f46aa135..732168ccb 100644 --- a/src/smartplaylists/generator_fwd.h +++ b/src/smartplaylists/generator_fwd.h @@ -26,6 +26,6 @@ class Generator; typedef std::shared_ptr GeneratorPtr; -} // namespace +} // namespace -#endif // PLAYLISTGENERATOR_FWD_H +#endif // PLAYLISTGENERATOR_FWD_H diff --git a/src/smartplaylists/generatorinserter.cpp b/src/smartplaylists/generatorinserter.cpp index 4881c4c49..7fe511304 100644 --- a/src/smartplaylists/generatorinserter.cpp +++ b/src/smartplaylists/generatorinserter.cpp @@ -28,15 +28,13 @@ namespace smart_playlists { typedef QFuture Future; typedef QFutureWatcher FutureWatcher; -GeneratorInserter::GeneratorInserter( - TaskManager* task_manager, LibraryBackend* library, QObject* parent) - : QObject(parent), - task_manager_(task_manager), - library_(library), - task_id_(-1), - is_dynamic_(false) -{ -} +GeneratorInserter::GeneratorInserter(TaskManager* task_manager, + LibraryBackend* library, QObject* parent) + : QObject(parent), + task_manager_(task_manager), + library_(library), + task_id_(-1), + is_dynamic_(false) {} static PlaylistItemList Generate(GeneratorPtr generator, int dynamic_count) { if (dynamic_count) { @@ -46,9 +44,9 @@ static PlaylistItemList Generate(GeneratorPtr generator, int dynamic_count) { } } -void GeneratorInserter::Load( - Playlist* destination, int row, bool play_now, bool enqueue, - GeneratorPtr generator, int dynamic_count) { +void GeneratorInserter::Load(Playlist* destination, int row, bool play_now, + bool enqueue, GeneratorPtr generator, + int dynamic_count) { task_id_ = task_manager_->StartTask(tr("Loading smart playlist")); destination_ = destination; @@ -85,4 +83,4 @@ void GeneratorInserter::Finished() { deleteLater(); } -} // namespace +} // namespace diff --git a/src/smartplaylists/generatorinserter.h b/src/smartplaylists/generatorinserter.h index bbabc9608..693d35e51 100644 --- a/src/smartplaylists/generatorinserter.h +++ b/src/smartplaylists/generatorinserter.h @@ -33,9 +33,9 @@ namespace smart_playlists { class GeneratorInserter : public QObject { Q_OBJECT -public: - GeneratorInserter(TaskManager* task_manager, - LibraryBackend* library, QObject* parent); + public: + GeneratorInserter(TaskManager* task_manager, LibraryBackend* library, + QObject* parent); void Load(Playlist* destination, int row, bool play_now, bool enqueue, GeneratorPtr generator, int dynamic_count = 0); @@ -44,10 +44,10 @@ signals: void Error(const QString& message); void PlayRequested(const QModelIndex& index); -private slots: + private slots: void Finished(); -private: + private: TaskManager* task_manager_; LibraryBackend* library_; int task_id_; @@ -59,6 +59,6 @@ private: bool is_dynamic_; }; -} // namespace +} // namespace -#endif // PLAYLISTGENERATORINSERTER_H +#endif // PLAYLISTGENERATORINSERTER_H diff --git a/src/smartplaylists/generatormimedata.h b/src/smartplaylists/generatormimedata.h index 5285152de..7232b7b1f 100644 --- a/src/smartplaylists/generatormimedata.h +++ b/src/smartplaylists/generatormimedata.h @@ -28,13 +28,12 @@ namespace smart_playlists { class GeneratorMimeData : public MimeData { Q_OBJECT -public: - GeneratorMimeData(GeneratorPtr generator) - : generator_(generator) {} + public: + GeneratorMimeData(GeneratorPtr generator) : generator_(generator) {} GeneratorPtr generator_; }; -} // namespace +} // namespace -#endif // GENERATORMIMEDATA_H +#endif // GENERATORMIMEDATA_H diff --git a/src/smartplaylists/querygenerator.cpp b/src/smartplaylists/querygenerator.cpp index 4088dbf32..f98a1e573 100644 --- a/src/smartplaylists/querygenerator.cpp +++ b/src/smartplaylists/querygenerator.cpp @@ -22,17 +22,11 @@ namespace smart_playlists { -QueryGenerator::QueryGenerator() - : dynamic_(false), - current_pos_(0) -{ -} +QueryGenerator::QueryGenerator() : dynamic_(false), current_pos_(0) {} -QueryGenerator::QueryGenerator(const QString& name, const Search& search, bool dynamic) - : search_(search), - dynamic_(dynamic), - current_pos_(0) -{ +QueryGenerator::QueryGenerator(const QString& name, const Search& search, + bool dynamic) + : search_(search), dynamic_(dynamic), current_pos_(0) { set_name(name); } @@ -77,9 +71,9 @@ PlaylistItemList QueryGenerator::GenerateMore(int count) { SongList songs = backend_->FindSongs(search_copy); PlaylistItemList items; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { items << PlaylistItemPtr(PlaylistItem::NewFromSongsTable( - backend_->songs_table(), song)); + backend_->songs_table(), song)); previous_ids_ << song.id(); if (previous_ids_.count() > GetDynamicFuture() + GetDynamicHistory()) @@ -88,4 +82,4 @@ PlaylistItemList QueryGenerator::GenerateMore(int count) { return items; } -} // namespace +} // namespace diff --git a/src/smartplaylists/querygenerator.h b/src/smartplaylists/querygenerator.h index 5c9922cf9..0dc633e3f 100644 --- a/src/smartplaylists/querygenerator.h +++ b/src/smartplaylists/querygenerator.h @@ -24,9 +24,10 @@ namespace smart_playlists { class QueryGenerator : public Generator { -public: + public: QueryGenerator(); - QueryGenerator(const QString& name, const Search& search, bool dynamic = false); + QueryGenerator(const QString& name, const Search& search, + bool dynamic = false); QString type() const { return "Query"; } @@ -40,9 +41,9 @@ public: void set_dynamic(bool dynamic) { dynamic_ = dynamic; } Search search() const { return search_; } - int GetDynamicFuture () { return search_.limit_; } + int GetDynamicFuture() { return search_.limit_; } -private: + private: Search search_; bool dynamic_; @@ -50,6 +51,6 @@ private: int current_pos_; }; -} // namespace +} // namespace -#endif // QUERYPLAYLISTGENERATOR_H +#endif // QUERYPLAYLISTGENERATOR_H diff --git a/src/smartplaylists/querywizardplugin.cpp b/src/smartplaylists/querywizardplugin.cpp index a5dd900b1..242245175 100644 --- a/src/smartplaylists/querywizardplugin.cpp +++ b/src/smartplaylists/querywizardplugin.cpp @@ -30,21 +30,18 @@ namespace smart_playlists { class QueryWizardPlugin::SearchPage : public QWizardPage { friend class QueryWizardPlugin; -public: + public: SearchPage(QWidget* parent = 0) - : QWizardPage(parent), - ui_(new Ui_SmartPlaylistQuerySearchPage) - { + : QWizardPage(parent), ui_(new Ui_SmartPlaylistQuerySearchPage) { ui_->setupUi(this); } bool isComplete() const { - if (ui_->type->currentIndex() == 2) // All songs + if (ui_->type->currentIndex() == 2) // All songs return true; - foreach (SearchTermWidget* widget, terms_) { - if (!widget->Term().is_valid()) - return false; + foreach(SearchTermWidget * widget, terms_) { + if (!widget->Term().is_valid()) return false; } return true; } @@ -59,9 +56,9 @@ public: }; class QueryWizardPlugin::SortPage : public QWizardPage { -public: + public: SortPage(QueryWizardPlugin* plugin, QWidget* parent, int next_id) - : QWizardPage(parent), next_id_(next_id), plugin_(plugin) {} + : QWizardPage(parent), next_id_(next_id), plugin_(plugin) {} void showEvent(QShowEvent*) { plugin_->UpdateSortPreview(); } @@ -71,20 +68,15 @@ public: QueryWizardPlugin* plugin_; }; +QueryWizardPlugin::QueryWizardPlugin(Application* app, LibraryBackend* library, + QObject* parent) + : WizardPlugin(app, library, parent), + search_page_(nullptr), + previous_scrollarea_max_(0) {} -QueryWizardPlugin::QueryWizardPlugin(Application* app, LibraryBackend* library, QObject* parent) - : WizardPlugin(app, library, parent), - search_page_(nullptr), - previous_scrollarea_max_(0) -{ -} +QueryWizardPlugin::~QueryWizardPlugin() {} -QueryWizardPlugin::~QueryWizardPlugin() { -} - -QString QueryWizardPlugin::name() const { - return tr("Library search"); -} +QString QueryWizardPlugin::name() const { return tr("Library search"); } QString QueryWizardPlugin::description() const { return tr("Find songs in your library that match the criteria you specify."); @@ -100,7 +92,8 @@ int QueryWizardPlugin::CreatePages(QWizard* wizard, int finish_page_id) { sort_ui_->limit_value->setValue(Generator::kDefaultLimit); - connect(search_page_->ui_->type, SIGNAL(currentIndexChanged(int)), SLOT(SearchTypeChanged())); + connect(search_page_->ui_->type, SIGNAL(currentIndexChanged(int)), + SLOT(SearchTypeChanged())); // Create the new search term widget search_page_->new_term_ = new SearchTermWidget(library_, search_page_); @@ -108,15 +101,19 @@ int QueryWizardPlugin::CreatePages(QWizard* wizard, int finish_page_id) { connect(search_page_->new_term_, SIGNAL(Clicked()), SLOT(AddSearchTerm())); // Add an empty initial term - search_page_->layout_ = static_cast(search_page_->ui_->terms_scroll_area_content->layout()); + search_page_->layout_ = static_cast( + search_page_->ui_->terms_scroll_area_content->layout()); search_page_->layout_->addWidget(search_page_->new_term_); AddSearchTerm(); // Ensure that the terms are scrolled to the bottom when a new one is added - connect(search_page_->ui_->terms_scroll_area->verticalScrollBar(), SIGNAL(rangeChanged(int,int)), this, SLOT(MoveTermListToBottom(int, int))); + connect(search_page_->ui_->terms_scroll_area->verticalScrollBar(), + SIGNAL(rangeChanged(int, int)), this, + SLOT(MoveTermListToBottom(int, int))); // Add the preview widget at the bottom of the search terms page - QVBoxLayout* terms_page_layout = static_cast(search_page_->layout()); + QVBoxLayout* terms_page_layout = + static_cast(search_page_->layout()); terms_page_layout->addStretch(); search_page_->preview_ = new SearchPreview(search_page_); search_page_->preview_->set_application(app_); @@ -124,12 +121,13 @@ int QueryWizardPlugin::CreatePages(QWizard* wizard, int finish_page_id) { terms_page_layout->addWidget(search_page_->preview_); // Add sort field texts - for (int i=0 ; ifield_value->addItem(field_name); } - connect(sort_ui_->field_value, SIGNAL(currentIndexChanged(int)), SLOT(UpdateSortOrder())); + connect(sort_ui_->field_value, SIGNAL(currentIndexChanged(int)), + SLOT(UpdateSortOrder())); UpdateSortOrder(); // Set the sort and limit radio buttons back to their defaults - they would @@ -141,18 +139,26 @@ int QueryWizardPlugin::CreatePages(QWizard* wizard, int finish_page_id) { sort_ui_->preview->set_application(app_); sort_ui_->preview->set_library(library_); connect(sort_ui_->field, SIGNAL(toggled(bool)), SLOT(UpdateSortPreview())); - connect(sort_ui_->field_value, SIGNAL(currentIndexChanged(int)), SLOT(UpdateSortPreview())); - connect(sort_ui_->limit_limit, SIGNAL(toggled(bool)), SLOT(UpdateSortPreview())); - connect(sort_ui_->limit_none, SIGNAL(toggled(bool)), SLOT(UpdateSortPreview())); - connect(sort_ui_->limit_value, SIGNAL(valueChanged(QString)), SLOT(UpdateSortPreview())); - connect(sort_ui_->order, SIGNAL(currentIndexChanged(int)), SLOT(UpdateSortPreview())); + connect(sort_ui_->field_value, SIGNAL(currentIndexChanged(int)), + SLOT(UpdateSortPreview())); + connect(sort_ui_->limit_limit, SIGNAL(toggled(bool)), + SLOT(UpdateSortPreview())); + connect(sort_ui_->limit_none, SIGNAL(toggled(bool)), + SLOT(UpdateSortPreview())); + connect(sort_ui_->limit_value, SIGNAL(valueChanged(QString)), + SLOT(UpdateSortPreview())); + connect(sort_ui_->order, SIGNAL(currentIndexChanged(int)), + SLOT(UpdateSortPreview())); connect(sort_ui_->random, SIGNAL(toggled(bool)), SLOT(UpdateSortPreview())); // Configure the page text search_page_->setTitle(tr("Search terms")); - search_page_->setSubTitle(tr("A song will be included in the playlist if it matches these conditions.")); + search_page_->setSubTitle( + tr("A song will be included in the playlist if it matches these " + "conditions.")); sort_page->setTitle(tr("Search options")); - sort_page->setSubTitle(tr("Choose how the playlist is sorted and how many songs it will contain.")); + sort_page->setSubTitle(tr( + "Choose how the playlist is sorted and how many songs it will contain.")); // Add the pages const int first_page = wizard->addPage(search_page_); @@ -163,8 +169,7 @@ int QueryWizardPlugin::CreatePages(QWizard* wizard, int finish_page_id) { void QueryWizardPlugin::SetGenerator(GeneratorPtr g) { std::shared_ptr gen = std::dynamic_pointer_cast(g); - if (!gen) - return; + if (!gen) return; Search search = gen->search(); // Search type @@ -174,7 +179,7 @@ void QueryWizardPlugin::SetGenerator(GeneratorPtr g) { qDeleteAll(search_page_->terms_); search_page_->terms_.clear(); - foreach (const SearchTerm& term, search.terms_) { + foreach(const SearchTerm & term, search.terms_) { AddSearchTerm(); search_page_->terms_.last()->SetTerm(term); } @@ -184,7 +189,8 @@ void QueryWizardPlugin::SetGenerator(GeneratorPtr g) { sort_ui_->random->setChecked(true); } else { sort_ui_->field->setChecked(true); - sort_ui_->order->setCurrentIndex(search.sort_type_ == Search::Sort_FieldAsc ? 0 : 1); + sort_ui_->order->setCurrentIndex( + search.sort_type_ == Search::Sort_FieldAsc ? 0 : 1); sort_ui_->field_value->setCurrentIndex(search.sort_field_); } @@ -219,8 +225,7 @@ void QueryWizardPlugin::UpdateSortOrder() { } void QueryWizardPlugin::AddSearchTerm() { - SearchTermWidget* widget = - new SearchTermWidget(library_, search_page_); + SearchTermWidget* widget = new SearchTermWidget(library_, search_page_); connect(widget, SIGNAL(RemoveClicked()), SLOT(RemoveSearchTerm())); connect(widget, SIGNAL(Changed()), SLOT(UpdateTermPreview())); @@ -231,14 +236,11 @@ void QueryWizardPlugin::AddSearchTerm() { } void QueryWizardPlugin::RemoveSearchTerm() { - SearchTermWidget* widget = - qobject_cast(sender()); - if (!widget) - return; + SearchTermWidget* widget = qobject_cast(sender()); + if (!widget) return; const int index = search_page_->terms_.indexOf(widget); - if (index == -1) - return; + if (index == -1) return; search_page_->terms_.takeAt(index)->deleteLater(); UpdateTermPreview(); @@ -248,8 +250,7 @@ void QueryWizardPlugin::UpdateTermPreview() { Search search = MakeSearch(); emit search_page_->completeChanged(); // When removing last term, update anyway the search - if (!search.is_valid() && !search_page_->terms_.isEmpty()) - return; + if (!search.is_valid() && !search_page_->terms_.isEmpty()) return; // Don't apply limits in the term page search.limit_ = -1; @@ -259,8 +260,7 @@ void QueryWizardPlugin::UpdateTermPreview() { void QueryWizardPlugin::UpdateSortPreview() { Search search = MakeSearch(); - if (!search.is_valid()) - return; + if (!search.is_valid()) return; sort_ui_->preview->Update(search); } @@ -269,13 +269,13 @@ Search QueryWizardPlugin::MakeSearch() const { Search ret; // Search type - ret.search_type_ = Search::SearchType(search_page_->ui_->type->currentIndex()); + ret.search_type_ = + Search::SearchType(search_page_->ui_->type->currentIndex()); // Search terms - foreach (SearchTermWidget* widget, search_page_->terms_) { + foreach(SearchTermWidget * widget, search_page_->terms_) { SearchTerm term = widget->Term(); - if (term.is_valid()) - ret.terms_ << term; + if (term.is_valid()) ret.terms_ << term; } // Sort order @@ -283,8 +283,7 @@ Search QueryWizardPlugin::MakeSearch() const { ret.sort_type_ = Search::Sort_Random; } else { const bool ascending = sort_ui_->order->currentIndex() == 0; - ret.sort_type_ = ascending ? Search::Sort_FieldAsc : - Search::Sort_FieldDesc; + ret.sort_type_ = ascending ? Search::Sort_FieldAsc : Search::Sort_FieldDesc; ret.sort_field_ = SearchTerm::Field(sort_ui_->field_value->currentIndex()); } @@ -305,13 +304,12 @@ void QueryWizardPlugin::SearchTypeChanged() { } void QueryWizardPlugin::MoveTermListToBottom(int min, int max) { - Q_UNUSED(min); - // Only scroll to the bottom if a new term is added - if (previous_scrollarea_max_ < max) - search_page_->ui_->terms_scroll_area->verticalScrollBar()->setValue(max); + Q_UNUSED(min); + // Only scroll to the bottom if a new term is added + if (previous_scrollarea_max_ < max) + search_page_->ui_->terms_scroll_area->verticalScrollBar()->setValue(max); - previous_scrollarea_max_ = max; + previous_scrollarea_max_ = max; } - -} // namespace smart_playlists +} // namespace smart_playlists diff --git a/src/smartplaylists/querywizardplugin.h b/src/smartplaylists/querywizardplugin.h index 8dded7c32..f1bdb216e 100644 --- a/src/smartplaylists/querywizardplugin.h +++ b/src/smartplaylists/querywizardplugin.h @@ -39,7 +39,7 @@ class SearchTermWidget; class QueryWizardPlugin : public WizardPlugin { Q_OBJECT -public: + public: QueryWizardPlugin(Application* app, LibraryBackend* library, QObject* parent); ~QueryWizardPlugin(); @@ -52,7 +52,7 @@ public: void SetGenerator(GeneratorPtr); GeneratorPtr CreateGenerator() const; -private slots: + private slots: void AddSearchTerm(); void RemoveSearchTerm(); @@ -64,7 +64,7 @@ private slots: void MoveTermListToBottom(int min, int max); -private: + private: class SearchPage; class SortPage; @@ -76,6 +76,6 @@ private: int previous_scrollarea_max_; }; -} // namespace smart_playlists +} // namespace smart_playlists -#endif // QUERYWIZARDPLUGIN_H +#endif // QUERYWIZARDPLUGIN_H diff --git a/src/smartplaylists/search.cpp b/src/smartplaylists/search.cpp index a929ad432..c868c7b32 100644 --- a/src/smartplaylists/search.cpp +++ b/src/smartplaylists/search.cpp @@ -23,21 +23,16 @@ namespace smart_playlists { -Search::Search() { - Reset(); -} +Search::Search() { Reset(); } -Search::Search( - SearchType type, TermList terms, SortType sort_type, - SearchTerm::Field sort_field, int limit) - : search_type_(type), - terms_(terms), - sort_type_(sort_type), - sort_field_(sort_field), - limit_(limit), - first_item_(0) -{ -} +Search::Search(SearchType type, TermList terms, SortType sort_type, + SearchTerm::Field sort_field, int limit) + : search_type_(type), + terms_(terms), + sort_type_(sort_type), + sort_field_(sort_field), + limit_(limit), + first_item_(0) {} void Search::Reset() { search_type_ = Type_And; @@ -54,7 +49,7 @@ QString Search::ToSql(const QString& songs_table) const { // Add search terms QStringList where_clauses; QStringList term_where_clauses; - foreach (const SearchTerm& term, terms_) { + foreach(const SearchTerm & term, terms_) { term_where_clauses << term.ToSql(); } @@ -66,7 +61,7 @@ QString Search::ToSql(const QString& songs_table) const { // Restrict the IDs of songs if we're making a dynamic playlist if (!id_not_in_.isEmpty()) { QString numbers; - foreach (int id, id_not_in_) { + foreach(int id, id_not_in_) { numbers += (numbers.isEmpty() ? "" : ",") + QString::number(id); } where_clauses << "(ROWID NOT IN (" + numbers + "))"; @@ -85,8 +80,8 @@ QString Search::ToSql(const QString& songs_table) const { if (sort_type_ == Sort_Random) { sql += " ORDER BY random()"; } else { - sql += " ORDER BY " + SearchTerm::FieldColumnName(sort_field_) - + (sort_type_ == Sort_FieldAsc ? " ASC" : " DESC"); + sql += " ORDER BY " + SearchTerm::FieldColumnName(sort_field_) + + (sort_type_ == Sort_FieldAsc ? " ASC" : " DESC"); } // Add limit @@ -101,22 +96,19 @@ QString Search::ToSql(const QString& songs_table) const { } bool Search::is_valid() const { - if (search_type_ == Type_All) - return true; + if (search_type_ == Type_All) return true; return !terms_.isEmpty(); } -bool Search::operator ==(const Search& other) const { - return search_type_ == other.search_type_ && - terms_ == other.terms_ && - sort_type_ == other.sort_type_ && - sort_field_ == other.sort_field_ && +bool Search::operator==(const Search& other) const { + return search_type_ == other.search_type_ && terms_ == other.terms_ && + sort_type_ == other.sort_type_ && sort_field_ == other.sort_field_ && limit_ == other.limit_; } -} // namespace +} // namespace -QDataStream& operator <<(QDataStream& s, const smart_playlists::Search& search) { +QDataStream& operator<<(QDataStream& s, const smart_playlists::Search& search) { s << search.terms_; s << quint8(search.sort_type_); s << quint8(search.sort_field_); @@ -125,7 +117,7 @@ QDataStream& operator <<(QDataStream& s, const smart_playlists::Search& search) return s; } -QDataStream& operator >>(QDataStream& s, smart_playlists::Search& search) { +QDataStream& operator>>(QDataStream& s, smart_playlists::Search& search) { quint8 sort_type, sort_field, search_type; qint32 limit; diff --git a/src/smartplaylists/search.h b/src/smartplaylists/search.h index cca1662b5..7c99fb5b6 100644 --- a/src/smartplaylists/search.h +++ b/src/smartplaylists/search.h @@ -24,31 +24,22 @@ namespace smart_playlists { class Search { -public: + public: typedef QList TermList; // These values are persisted, so add to the end of the enum only - enum SearchType { - Type_And = 0, - Type_Or, - Type_All, - }; + enum SearchType { Type_And = 0, Type_Or, Type_All, }; // These values are persisted, so add to the end of the enum only - enum SortType { - Sort_Random = 0, - Sort_FieldAsc, - Sort_FieldDesc, - }; + enum SortType { Sort_Random = 0, Sort_FieldAsc, Sort_FieldDesc, }; Search(); Search(SearchType type, TermList terms, SortType sort_type, - SearchTerm::Field sort_field, - int limit = Generator::kDefaultLimit); + SearchTerm::Field sort_field, int limit = Generator::kDefaultLimit); bool is_valid() const; - bool operator ==(const Search& other) const; - bool operator !=(const Search& other) const { return !(*this == other); } + bool operator==(const Search& other) const; + bool operator!=(const Search& other) const { return !(*this == other); } SearchType search_type_; TermList terms_; @@ -64,9 +55,9 @@ public: QString ToSql(const QString& songs_table) const; }; -} // namespace +} // namespace -QDataStream& operator <<(QDataStream& s, const smart_playlists::Search& search); -QDataStream& operator >>(QDataStream& s, smart_playlists::Search& search); +QDataStream& operator<<(QDataStream& s, const smart_playlists::Search& search); +QDataStream& operator>>(QDataStream& s, smart_playlists::Search& search); -#endif // SMARTPLAYLISTSEARCH_H +#endif // SMARTPLAYLISTSEARCH_H diff --git a/src/smartplaylists/searchpreview.cpp b/src/smartplaylists/searchpreview.cpp index 78e2fc662..c6d195495 100644 --- a/src/smartplaylists/searchpreview.cpp +++ b/src/smartplaylists/searchpreview.cpp @@ -31,14 +31,12 @@ namespace smart_playlists { typedef QFuture Future; typedef QFutureWatcher FutureWatcher; -SearchPreview::SearchPreview(QWidget *parent) - : QWidget(parent), - ui_(new Ui_SmartPlaylistSearchPreview), - model_(nullptr) -{ +SearchPreview::SearchPreview(QWidget* parent) + : QWidget(parent), ui_(new Ui_SmartPlaylistSearchPreview), model_(nullptr) { ui_->setupUi(this); - // Prevent editing songs and saving settings (like header columns and geometry) + // Prevent editing songs and saving settings (like header columns and + // geometry) ui_->tree->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_->tree->SetReadOnlySettings(true); @@ -48,9 +46,7 @@ SearchPreview::SearchPreview(QWidget *parent) ui_->busy_container->hide(); } -SearchPreview::~SearchPreview() { - delete ui_; -} +SearchPreview::~SearchPreview() { delete ui_; } void SearchPreview::set_application(Application* app) { ui_->tree->SetApplication(app); @@ -90,9 +86,7 @@ void SearchPreview::showEvent(QShowEvent* e) { QWidget::showEvent(e); } -PlaylistItemList DoRunSearch(GeneratorPtr gen) { - return gen->Generate(); -} +PlaylistItemList DoRunSearch(GeneratorPtr gen) { return gen->Generate(); } void SearchPreview::RunSearch(const Search& search) { generator_.reset(new QueryGenerator); @@ -112,7 +106,8 @@ void SearchPreview::SearchFinished() { FutureWatcher* watcher = static_cast(sender()); watcher->deleteLater(); - last_search_ = std::dynamic_pointer_cast(generator_)->search(); + last_search_ = + std::dynamic_pointer_cast(generator_)->search(); generator_.reset(); if (pending_search_.is_valid() && pending_search_ != last_search_) { @@ -131,7 +126,8 @@ void SearchPreview::SearchFinished() { if (displayed_items.count() < all_items.count()) { ui_->count_label->setText(tr("%1 songs found (showing %2)") - .arg(all_items.count()).arg(displayed_items.count())); + .arg(all_items.count()) + .arg(displayed_items.count())); } else { ui_->count_label->setText(tr("%1 songs found").arg(all_items.count())); } @@ -140,4 +136,4 @@ void SearchPreview::SearchFinished() { ui_->count_label->show(); } -} // namespace +} // namespace diff --git a/src/smartplaylists/searchpreview.h b/src/smartplaylists/searchpreview.h index 8f58eeecd..6878f16fe 100644 --- a/src/smartplaylists/searchpreview.h +++ b/src/smartplaylists/searchpreview.h @@ -33,8 +33,8 @@ namespace smart_playlists { class SearchPreview : public QWidget { Q_OBJECT -public: - SearchPreview(QWidget *parent = 0); + public: + SearchPreview(QWidget* parent = 0); ~SearchPreview(); void set_application(Application* app); @@ -42,16 +42,16 @@ public: void Update(const Search& search); -protected: + protected: void showEvent(QShowEvent*); -private: + private: void RunSearch(const Search& search); -private slots: + private slots: void SearchFinished(); -private: + private: Ui_SmartPlaylistSearchPreview* ui_; QList fields_; @@ -63,6 +63,6 @@ private: GeneratorPtr generator_; }; -} // namespace +} // namespace -#endif // SMARTPLAYLISTSEARCHPREVIEW_H +#endif // SMARTPLAYLISTSEARCHPREVIEW_H diff --git a/src/smartplaylists/searchterm.cpp b/src/smartplaylists/searchterm.cpp index ddc6b59fa..30a44c2ec 100644 --- a/src/smartplaylists/searchterm.cpp +++ b/src/smartplaylists/searchterm.cpp @@ -20,19 +20,10 @@ namespace smart_playlists { -SearchTerm::SearchTerm() - : field_(Field_Title), - operator_(Op_Equals) -{ -} +SearchTerm::SearchTerm() : field_(Field_Title), operator_(Op_Equals) {} -SearchTerm::SearchTerm( - Field field, Operator op, const QVariant& value) - : field_(field), - operator_(op), - value_(value) -{ -} +SearchTerm::SearchTerm(Field field, Operator op, const QVariant& value) + : field_(field), operator_(op), value_(value) {} QString SearchTerm::ToSql() const { QString col = FieldColumnName(field_); @@ -42,7 +33,8 @@ QString SearchTerm::ToSql() const { QString second_value; - bool special_date_query = (operator_ == SearchTerm::Op_NumericDate || operator_ == SearchTerm::Op_NumericDateNot || + bool special_date_query = (operator_ == SearchTerm::Op_NumericDate || + operator_ == SearchTerm::Op_NumericDateNot || operator_ == SearchTerm::Op_RelativeDate); // Floating point problems... @@ -69,8 +61,8 @@ QString SearchTerm::ToSql() const { if (date == "weeks") { // Sqlite doesn't know weeks, transform them to days date = "days"; - value = QString::number(value_.toInt()*7); - second_value = QString::number(second_value_.toInt()*7); + value = QString::number(value_.toInt() * 7); + second_value = QString::number(second_value_.toInt() * 7); } } } else if (TypeOf(field_) == Type_Time) { @@ -90,34 +82,34 @@ QString SearchTerm::ToSql() const { case Op_Equals: if (TypeOf(field_) == Type_Text) return col + " LIKE '" + value + "'"; - else if (TypeOf(field_) == Type_Rating || - TypeOf(field_) == Type_Date || + else if (TypeOf(field_) == Type_Rating || TypeOf(field_) == Type_Date || TypeOf(field_) == Type_Time) return col + " = " + value; else return col + " = '" + value + "'"; case Op_GreaterThan: - if (TypeOf(field_) == Type_Rating || - TypeOf(field_) == Type_Date || + if (TypeOf(field_) == Type_Rating || TypeOf(field_) == Type_Date || TypeOf(field_) == Type_Time) return col + " > " + value; else return col + " > '" + value + "'"; case Op_LessThan: - if (TypeOf(field_) == Type_Rating || - TypeOf(field_) == Type_Date || + if (TypeOf(field_) == Type_Rating || TypeOf(field_) == Type_Date || TypeOf(field_) == Type_Time) return col + " < " + value; else return col + " < '" + value + "'"; case Op_NumericDate: - return col + " > " + "DATETIME('now', '-" + value + " " + date +"', 'localtime')"; + return col + " > " + "DATETIME('now', '-" + value + " " + date + + "', 'localtime')"; case Op_NumericDateNot: - return col + " < " + "DATETIME('now', '-" + value + " " + date +"', 'localtime')"; + return col + " < " + "DATETIME('now', '-" + value + " " + date + + "', 'localtime')"; case Op_RelativeDate: // Consider the time range before the first date but after the second one - return "(" + col + " < " + "DATETIME('now', '-" + value + " " + date +"', 'localtime') AND " + - col + " > " + "DATETIME('now', '-" + second_value + " " + date +"', 'localtime'))"; + return "(" + col + " < " + "DATETIME('now', '-" + value + " " + date + + "', 'localtime') AND " + col + " > " + "DATETIME('now', '-" + + second_value + " " + date + "', 'localtime'))"; case Op_NotEquals: if (TypeOf(field_) == Type_Text) { return col + " <> '" + value + "'"; @@ -138,21 +130,25 @@ bool SearchTerm::is_valid() const { } switch (TypeOf(field_)) { - case Type_Text: return !value_.toString().isEmpty(); - case Type_Date: return value_.toInt() != 0; - case Type_Number: return value_.toInt() >= 0; - case Type_Rating: return value_.toFloat() >= 0.0; - case Type_Time: return true; - case Type_Invalid: return false; + case Type_Text: + return !value_.toString().isEmpty(); + case Type_Date: + return value_.toInt() != 0; + case Type_Number: + return value_.toInt() >= 0; + case Type_Rating: + return value_.toFloat() >= 0.0; + case Type_Time: + return true; + case Type_Invalid: + return false; } return false; } -bool SearchTerm::operator ==(const SearchTerm& other) const { - return field_ == other.field_ && - operator_ == other.operator_ && - value_ == other.value_ && - date_ == other.date_ && +bool SearchTerm::operator==(const SearchTerm& other) const { + return field_ == other.field_ && operator_ == other.operator_ && + value_ == other.value_ && date_ == other.date_ && second_value_ == other.second_value_; } @@ -192,37 +188,56 @@ OperatorList SearchTerm::OperatorsForType(Type type) { return OperatorList() << Op_Contains << Op_NotContains << Op_Equals << Op_NotEquals << Op_StartsWith << Op_EndsWith; case Type_Date: - return OperatorList() << Op_Equals << Op_NotEquals << Op_GreaterThan << Op_LessThan - << Op_NumericDate << Op_NumericDateNot << Op_RelativeDate; + return OperatorList() << Op_Equals << Op_NotEquals << Op_GreaterThan + << Op_LessThan << Op_NumericDate + << Op_NumericDateNot << Op_RelativeDate; default: - return OperatorList() << Op_Equals << Op_NotEquals << Op_GreaterThan << Op_LessThan; + return OperatorList() << Op_Equals << Op_NotEquals << Op_GreaterThan + << Op_LessThan; } } QString SearchTerm::OperatorText(Type type, Operator op) { if (type == Type_Date) { switch (op) { - case Op_GreaterThan: return QObject::tr("after"); - case Op_LessThan: return QObject::tr("before"); - case Op_Equals: return QObject::tr("on"); - case Op_NotEquals: return QObject::tr("not on"); - case Op_NumericDate: return QObject::tr("in the last"); - case Op_NumericDateNot: return QObject::tr("not in the last"); - case Op_RelativeDate: return QObject::tr("between"); - default: return QString(); + case Op_GreaterThan: + return QObject::tr("after"); + case Op_LessThan: + return QObject::tr("before"); + case Op_Equals: + return QObject::tr("on"); + case Op_NotEquals: + return QObject::tr("not on"); + case Op_NumericDate: + return QObject::tr("in the last"); + case Op_NumericDateNot: + return QObject::tr("not in the last"); + case Op_RelativeDate: + return QObject::tr("between"); + default: + return QString(); } } switch (op) { - case Op_Contains: return QObject::tr("contains"); - case Op_NotContains: return QObject::tr("does not contain"); - case Op_StartsWith: return QObject::tr("starts with"); - case Op_EndsWith: return QObject::tr("ends with"); - case Op_GreaterThan: return QObject::tr("greater than"); - case Op_LessThan: return QObject::tr("less than"); - case Op_Equals: return QObject::tr("equals"); - case Op_NotEquals: return QObject::tr("not equals"); - default: return QString(); + case Op_Contains: + return QObject::tr("contains"); + case Op_NotContains: + return QObject::tr("does not contain"); + case Op_StartsWith: + return QObject::tr("starts with"); + case Op_EndsWith: + return QObject::tr("ends with"); + case Op_GreaterThan: + return QObject::tr("greater than"); + case Op_LessThan: + return QObject::tr("less than"); + case Op_Equals: + return QObject::tr("equals"); + case Op_NotEquals: + return QObject::tr("not equals"); + default: + return QString(); } return QString(); @@ -230,76 +245,136 @@ QString SearchTerm::OperatorText(Type type, Operator op) { QString SearchTerm::FieldColumnName(Field field) { switch (field) { - case Field_Length: return "length"; - case Field_Track: return "track"; - case Field_Disc: return "disc"; - case Field_Year: return "year"; - case Field_BPM: return "bpm"; - case Field_Bitrate: return "bitrate"; - case Field_Samplerate: return "samplerate"; - case Field_Filesize: return "filesize"; - case Field_PlayCount: return "playcount"; - case Field_SkipCount: return "skipcount"; - case Field_LastPlayed: return "lastplayed"; - case Field_DateCreated: return "ctime"; - case Field_DateModified:return "mtime"; - case Field_Rating: return "rating"; - case Field_Score: return "score"; - case Field_Title: return "title"; - case Field_Artist: return "artist"; - case Field_Album: return "album"; - case Field_AlbumArtist: return "albumartist"; - case Field_Composer: return "composer"; - case Field_Performer: return "performer"; - case Field_Grouping: return "grouping"; - case Field_Genre: return "genre"; - case Field_Comment: return "comment"; - case Field_Filepath: return "filename"; - case FieldCount: Q_ASSERT(0); + case Field_Length: + return "length"; + case Field_Track: + return "track"; + case Field_Disc: + return "disc"; + case Field_Year: + return "year"; + case Field_BPM: + return "bpm"; + case Field_Bitrate: + return "bitrate"; + case Field_Samplerate: + return "samplerate"; + case Field_Filesize: + return "filesize"; + case Field_PlayCount: + return "playcount"; + case Field_SkipCount: + return "skipcount"; + case Field_LastPlayed: + return "lastplayed"; + case Field_DateCreated: + return "ctime"; + case Field_DateModified: + return "mtime"; + case Field_Rating: + return "rating"; + case Field_Score: + return "score"; + case Field_Title: + return "title"; + case Field_Artist: + return "artist"; + case Field_Album: + return "album"; + case Field_AlbumArtist: + return "albumartist"; + case Field_Composer: + return "composer"; + case Field_Performer: + return "performer"; + case Field_Grouping: + return "grouping"; + case Field_Genre: + return "genre"; + case Field_Comment: + return "comment"; + case Field_Filepath: + return "filename"; + case FieldCount: + Q_ASSERT(0); } return QString(); } QString SearchTerm::FieldName(Field field) { switch (field) { - case Field_Length: return Playlist::column_name(Playlist::Column_Length); - case Field_Track: return Playlist::column_name(Playlist::Column_Track); - case Field_Disc: return Playlist::column_name(Playlist::Column_Disc); - case Field_Year: return Playlist::column_name(Playlist::Column_Year); - case Field_BPM: return Playlist::column_name(Playlist::Column_BPM); - case Field_Bitrate: return Playlist::column_name(Playlist::Column_Bitrate); - case Field_Samplerate: return Playlist::column_name(Playlist::Column_Samplerate); - case Field_Filesize: return Playlist::column_name(Playlist::Column_Filesize); - case Field_PlayCount: return Playlist::column_name(Playlist::Column_PlayCount); - case Field_SkipCount: return Playlist::column_name(Playlist::Column_SkipCount); - case Field_LastPlayed: return Playlist::column_name(Playlist::Column_LastPlayed); - case Field_DateCreated: return Playlist::column_name(Playlist::Column_DateCreated); - case Field_DateModified:return Playlist::column_name(Playlist::Column_DateModified); - case Field_Rating: return Playlist::column_name(Playlist::Column_Rating); - case Field_Score: return Playlist::column_name(Playlist::Column_Score); - case Field_Title: return Playlist::column_name(Playlist::Column_Title); - case Field_Artist: return Playlist::column_name(Playlist::Column_Artist); - case Field_Album: return Playlist::column_name(Playlist::Column_Album); - case Field_AlbumArtist: return Playlist::column_name(Playlist::Column_AlbumArtist); - case Field_Composer: return Playlist::column_name(Playlist::Column_Composer); - case Field_Performer: return Playlist::column_name(Playlist::Column_Performer); - case Field_Grouping: return Playlist::column_name(Playlist::Column_Grouping); - case Field_Genre: return Playlist::column_name(Playlist::Column_Genre); - case Field_Comment: return QObject::tr("Comment"); - case Field_Filepath: return Playlist::column_name(Playlist::Column_Filename); - case FieldCount: Q_ASSERT(0); + case Field_Length: + return Playlist::column_name(Playlist::Column_Length); + case Field_Track: + return Playlist::column_name(Playlist::Column_Track); + case Field_Disc: + return Playlist::column_name(Playlist::Column_Disc); + case Field_Year: + return Playlist::column_name(Playlist::Column_Year); + case Field_BPM: + return Playlist::column_name(Playlist::Column_BPM); + case Field_Bitrate: + return Playlist::column_name(Playlist::Column_Bitrate); + case Field_Samplerate: + return Playlist::column_name(Playlist::Column_Samplerate); + case Field_Filesize: + return Playlist::column_name(Playlist::Column_Filesize); + case Field_PlayCount: + return Playlist::column_name(Playlist::Column_PlayCount); + case Field_SkipCount: + return Playlist::column_name(Playlist::Column_SkipCount); + case Field_LastPlayed: + return Playlist::column_name(Playlist::Column_LastPlayed); + case Field_DateCreated: + return Playlist::column_name(Playlist::Column_DateCreated); + case Field_DateModified: + return Playlist::column_name(Playlist::Column_DateModified); + case Field_Rating: + return Playlist::column_name(Playlist::Column_Rating); + case Field_Score: + return Playlist::column_name(Playlist::Column_Score); + case Field_Title: + return Playlist::column_name(Playlist::Column_Title); + case Field_Artist: + return Playlist::column_name(Playlist::Column_Artist); + case Field_Album: + return Playlist::column_name(Playlist::Column_Album); + case Field_AlbumArtist: + return Playlist::column_name(Playlist::Column_AlbumArtist); + case Field_Composer: + return Playlist::column_name(Playlist::Column_Composer); + case Field_Performer: + return Playlist::column_name(Playlist::Column_Performer); + case Field_Grouping: + return Playlist::column_name(Playlist::Column_Grouping); + case Field_Genre: + return Playlist::column_name(Playlist::Column_Genre); + case Field_Comment: + return QObject::tr("Comment"); + case Field_Filepath: + return Playlist::column_name(Playlist::Column_Filename); + case FieldCount: + Q_ASSERT(0); } return QString(); } QString SearchTerm::FieldSortOrderText(Type type, bool ascending) { switch (type) { - case Type_Text: return ascending ? QObject::tr("A-Z") : QObject::tr("Z-A"); - case Type_Date: return ascending ? QObject::tr("oldest first") : QObject::tr("newest first"); - case Type_Time: return ascending ? QObject::tr("shortest first") : QObject::tr("longest first"); + case Type_Text: + return ascending ? QObject::tr("A-Z") : QObject::tr("Z-A"); + case Type_Date: + return ascending ? QObject::tr("oldest first") + : QObject::tr("newest first"); + case Type_Time: + return ascending ? QObject::tr("shortest first") + : QObject::tr("longest first"); case Type_Number: - case Type_Rating: return ascending ? QObject::tr("smallest first") : QObject::tr("biggest first"); - case Type_Invalid: return QString(); + case Type_Rating: + return ascending ? QObject::tr("smallest first") + : QObject::tr("biggest first"); + case Type_Invalid: + return QString(); } return QString(); } @@ -307,18 +382,24 @@ QString SearchTerm::FieldSortOrderText(Type type, bool ascending) { QString SearchTerm::DateName(DateType date, bool forQuery) { // If forQuery is true, untranslated keywords are returned switch (date) { - case Date_Hour: return (forQuery ? "hours" : QObject::tr("Hours")); - case Date_Day: return (forQuery ? "days" : QObject::tr("Days")); - case Date_Week: return (forQuery ? "weeks" : QObject::tr("Weeks")); - case Date_Month: return (forQuery ? "months" : QObject::tr("Months")); - case Date_Year: return (forQuery ? "years" : QObject::tr("Years")); + case Date_Hour: + return (forQuery ? "hours" : QObject::tr("Hours")); + case Date_Day: + return (forQuery ? "days" : QObject::tr("Days")); + case Date_Week: + return (forQuery ? "weeks" : QObject::tr("Weeks")); + case Date_Month: + return (forQuery ? "months" : QObject::tr("Months")); + case Date_Year: + return (forQuery ? "years" : QObject::tr("Years")); } return QString(); } -} // namespace +} // namespace -QDataStream& operator <<(QDataStream& s, const smart_playlists::SearchTerm& term) { +QDataStream& operator<<(QDataStream& s, + const smart_playlists::SearchTerm& term) { s << quint8(term.field_); s << quint8(term.operator_); s << term.value_; @@ -327,7 +408,7 @@ QDataStream& operator <<(QDataStream& s, const smart_playlists::SearchTerm& term return s; } -QDataStream& operator >>(QDataStream& s, smart_playlists::SearchTerm& term) { +QDataStream& operator>>(QDataStream& s, smart_playlists::SearchTerm& term) { quint8 field, op, date; s >> field >> op >> term.value_ >> term.second_value_ >> date; term.field_ = smart_playlists::SearchTerm::Field(field); diff --git a/src/smartplaylists/searchterm.h b/src/smartplaylists/searchterm.h index f1ba69e4c..aaf8ef2a0 100644 --- a/src/smartplaylists/searchterm.h +++ b/src/smartplaylists/searchterm.h @@ -24,7 +24,7 @@ namespace smart_playlists { class SearchTerm { -public: + public: // These values are persisted, so add to the end of the enum only enum Field { Field_Title = 0, @@ -52,7 +52,6 @@ public: Field_Filepath, Field_Performer, Field_Grouping, - FieldCount }; @@ -89,18 +88,11 @@ public: Type_Time, Type_Number, Type_Rating, - Type_Invalid }; // These values are persisted, so add to the end of the enum only - enum DateType { - Date_Hour = 0, - Date_Day, - Date_Week, - Date_Month, - Date_Year, - }; + enum DateType { Date_Hour = 0, Date_Day, Date_Week, Date_Month, Date_Year, }; SearchTerm(); SearchTerm(Field field, Operator op, const QVariant& value); @@ -109,13 +101,14 @@ public: Operator operator_; QVariant value_; DateType date_; - // For relative dates, we need a second parameter, might be useful somewhere else + // For relative dates, we need a second parameter, might be useful somewhere + // else QVariant second_value_; QString ToSql() const; bool is_valid() const; - bool operator ==(const SearchTerm& other) const; - bool operator !=(const SearchTerm& other) const { return !(*this == other); } + bool operator==(const SearchTerm& other) const; + bool operator!=(const SearchTerm& other) const { return !(*this == other); } static Type TypeOf(Field field); static QList OperatorsForType(Type type); @@ -128,9 +121,10 @@ public: typedef QList OperatorList; -} // namespace +} // namespace -QDataStream& operator <<(QDataStream& s, const smart_playlists::SearchTerm& term); -QDataStream& operator >>(QDataStream& s, smart_playlists::SearchTerm& term); +QDataStream& operator<<(QDataStream& s, + const smart_playlists::SearchTerm& term); +QDataStream& operator>>(QDataStream& s, smart_playlists::SearchTerm& term); -#endif // SMARTPLAYLISTSEARCHTERM_H +#endif // SMARTPLAYLISTSEARCHTERM_H diff --git a/src/smartplaylists/searchtermwidget.cpp b/src/smartplaylists/searchtermwidget.cpp index e17a8bbf4..23949b00c 100644 --- a/src/smartplaylists/searchtermwidget.cpp +++ b/src/smartplaylists/searchtermwidget.cpp @@ -31,12 +31,13 @@ #include // Exported by QtGui -void qt_blurImage(QPainter *p, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0); +void qt_blurImage(QPainter* p, QImage& blurImage, qreal radius, bool quality, + bool alphaOnly, int transposed = 0); namespace smart_playlists { class SearchTermWidget::Overlay : public QWidget { -public: + public: Overlay(SearchTermWidget* parent); void Grab(); void SetOpacity(float opacity); @@ -45,11 +46,11 @@ public: static const int kSpacing; static const int kIconSize; -protected: + protected: void paintEvent(QPaintEvent*); void mouseReleaseEvent(QMouseEvent*); -private: + private: SearchTermWidget* parent_; float opacity_; @@ -61,19 +62,18 @@ private: const int SearchTermWidget::Overlay::kSpacing = 6; const int SearchTermWidget::Overlay::kIconSize = 22; - SearchTermWidget::SearchTermWidget(LibraryBackend* library, QWidget* parent) - : QWidget(parent), - ui_(new Ui_SmartPlaylistSearchTermWidget), - library_(library), - overlay_(nullptr), - animation_(new QPropertyAnimation(this, "overlay_opacity", this)), - active_(true), - initialized_(false), - current_field_type_(SearchTerm::Type_Invalid) -{ + : QWidget(parent), + ui_(new Ui_SmartPlaylistSearchTermWidget), + library_(library), + overlay_(nullptr), + animation_(new QPropertyAnimation(this, "overlay_opacity", this)), + active_(true), + initialized_(false), + current_field_type_(SearchTerm::Type_Invalid) { ui_->setupUi(this); - connect(ui_->field, SIGNAL(currentIndexChanged(int)), SLOT(FieldChanged(int))); + connect(ui_->field, SIGNAL(currentIndexChanged(int)), + SLOT(FieldChanged(int))); connect(ui_->op, SIGNAL(currentIndexChanged(int)), SLOT(OpChanged(int))); connect(ui_->remove, SIGNAL(clicked()), SIGNAL(RemoveClicked())); @@ -82,27 +82,33 @@ SearchTermWidget::SearchTermWidget(LibraryBackend* library, QWidget* parent) connect(ui_->value_rating, SIGNAL(RatingChanged(float)), SIGNAL(Changed())); connect(ui_->value_text, SIGNAL(textChanged(QString)), SIGNAL(Changed())); connect(ui_->value_time, SIGNAL(timeChanged(QTime)), SIGNAL(Changed())); - connect(ui_->value_date_numeric, SIGNAL(valueChanged(int)), SIGNAL(Changed())); - connect(ui_->value_date_numeric1, SIGNAL(valueChanged(int)), SLOT(RelativeValueChanged())); - connect(ui_->value_date_numeric2, SIGNAL(valueChanged(int)), SLOT(RelativeValueChanged())); + connect(ui_->value_date_numeric, SIGNAL(valueChanged(int)), + SIGNAL(Changed())); + connect(ui_->value_date_numeric1, SIGNAL(valueChanged(int)), + SLOT(RelativeValueChanged())); + connect(ui_->value_date_numeric2, SIGNAL(valueChanged(int)), + SLOT(RelativeValueChanged())); connect(ui_->date_type, SIGNAL(currentIndexChanged(int)), SIGNAL(Changed())); - connect(ui_->date_type_relative, SIGNAL(currentIndexChanged(int)), SIGNAL(Changed())); + connect(ui_->date_type_relative, SIGNAL(currentIndexChanged(int)), + SIGNAL(Changed())); ui_->value_date->setDate(QDate::currentDate()); // Populate the combo boxes - for (int i=0; ifield->addItem(SearchTerm::FieldName(SearchTerm::Field(i))); ui_->field->setItemData(i, i); } ui_->field->model()->sort(0); // Populate the date type combo box - for (int i=0; i<5; ++i) { - ui_->date_type->addItem(SearchTerm::DateName(SearchTerm::DateType(i), false)); + for (int i = 0; i < 5; ++i) { + ui_->date_type->addItem( + SearchTerm::DateName(SearchTerm::DateType(i), false)); ui_->date_type->setItemData(i, i); - ui_->date_type_relative->addItem(SearchTerm::DateName(SearchTerm::DateType(i), false)); + ui_->date_type_relative->addItem( + SearchTerm::DateName(SearchTerm::DateType(i), false)); ui_->date_type_relative->setItemData(i, i); } @@ -115,25 +121,23 @@ SearchTermWidget::SearchTermWidget(LibraryBackend* library, QWidget* parent) QString stylesheet = QString::fromAscii(stylesheet_file.readAll()); const QColor base(222, 97, 97, 128); stylesheet.replace("%light2", Utilities::ColorToRgba(base.lighter(140))); - stylesheet.replace("%light", Utilities::ColorToRgba(base.lighter(120))); - stylesheet.replace("%dark", Utilities::ColorToRgba(base.darker(120))); - stylesheet.replace("%base", Utilities::ColorToRgba(base)); + stylesheet.replace("%light", Utilities::ColorToRgba(base.lighter(120))); + stylesheet.replace("%dark", Utilities::ColorToRgba(base.darker(120))); + stylesheet.replace("%base", Utilities::ColorToRgba(base)); setStyleSheet(stylesheet); } -SearchTermWidget::~SearchTermWidget() { - delete ui_; -} +SearchTermWidget::~SearchTermWidget() { delete ui_; } void SearchTermWidget::FieldChanged(int index) { - SearchTerm::Field field = SearchTerm::Field( - ui_->field->itemData(index).toInt()); + SearchTerm::Field field = + SearchTerm::Field(ui_->field->itemData(index).toInt()); SearchTerm::Type type = SearchTerm::TypeOf(field); // Populate the operator combo box if (type != current_field_type_) { ui_->op->clear(); - foreach (SearchTerm::Operator op, SearchTerm::OperatorsForType(type)) { + foreach(SearchTerm::Operator op, SearchTerm::OperatorsForType(type)) { const int i = ui_->op->count(); ui_->op->addItem(SearchTerm::OperatorText(type, op)); ui_->op->setItemData(i, op); @@ -144,27 +148,39 @@ void SearchTermWidget::FieldChanged(int index) { // Show the correct value editor QWidget* page = nullptr; switch (type) { - case SearchTerm::Type_Time: page = ui_->page_time; break; - case SearchTerm::Type_Number: page = ui_->page_number; break; - case SearchTerm::Type_Date: page = ui_->page_date; break; - case SearchTerm::Type_Rating: page = ui_->page_rating; break; - case SearchTerm::Type_Text: page = ui_->page_text; break; - case SearchTerm::Type_Invalid: page = nullptr; break; + case SearchTerm::Type_Time: + page = ui_->page_time; + break; + case SearchTerm::Type_Number: + page = ui_->page_number; + break; + case SearchTerm::Type_Date: + page = ui_->page_date; + break; + case SearchTerm::Type_Rating: + page = ui_->page_rating; + break; + case SearchTerm::Type_Text: + page = ui_->page_text; + break; + case SearchTerm::Type_Invalid: + page = nullptr; + break; } ui_->value_stack->setCurrentWidget(page); // Maybe set a tag completer switch (field) { - case SearchTerm::Field_Artist: - new TagCompleter(library_, Playlist::Column_Artist, ui_->value_text); - break; + case SearchTerm::Field_Artist: + new TagCompleter(library_, Playlist::Column_Artist, ui_->value_text); + break; - case SearchTerm::Field_Album: - new TagCompleter(library_, Playlist::Column_Album, ui_->value_text); - break; + case SearchTerm::Field_Album: + new TagCompleter(library_, Playlist::Column_Album, ui_->value_text); + break; - default: - ui_->value_text->setCompleter(nullptr); + default: + ui_->value_text->setCompleter(nullptr); } emit Changed(); @@ -172,17 +188,18 @@ void SearchTermWidget::FieldChanged(int index) { void SearchTermWidget::OpChanged(int index) { // We need to change the page only in the following case - if ((ui_->value_stack->currentWidget() == ui_->page_date) || (ui_->value_stack->currentWidget() == ui_->page_date_numeric) || + if ((ui_->value_stack->currentWidget() == ui_->page_date) || + (ui_->value_stack->currentWidget() == ui_->page_date_numeric) || (ui_->value_stack->currentWidget() == ui_->page_date_relative)) { - QWidget* page = nullptr; - if (index == 4 || index == 5) { - page = ui_->page_date_numeric; - } else if (index == 6) { - page = ui_->page_date_relative; - } else { - page = ui_->page_date; - } - ui_->value_stack->setCurrentWidget(page); + QWidget* page = nullptr; + if (index == 4 || index == 5) { + page = ui_->page_date_numeric; + } else if (index == 6) { + page = ui_->page_date_relative; + } else { + page = ui_->page_date; + } + ui_->value_stack->setCurrentWidget(page); } emit Changed(); } @@ -198,8 +215,7 @@ void SearchTermWidget::SetActive(bool active) { } void SearchTermWidget::enterEvent(QEvent*) { - if (!overlay_ || !isEnabled()) - return; + if (!overlay_ || !isEnabled()) return; animation_->stop(); animation_->setEndValue(1.0); @@ -208,8 +224,7 @@ void SearchTermWidget::enterEvent(QEvent*) { } void SearchTermWidget::leaveEvent(QEvent*) { - if (!overlay_) - return; + if (!overlay_) return; animation_->stop(); animation_->setEndValue(0.0); @@ -231,13 +246,10 @@ void SearchTermWidget::showEvent(QShowEvent* e) { } } -void SearchTermWidget::Grab() { - overlay_->Grab(); -} +void SearchTermWidget::Grab() { overlay_->Grab(); } void SearchTermWidget::set_overlay_opacity(float opacity) { - if (overlay_) - overlay_->SetOpacity(opacity); + if (overlay_) overlay_->SetOpacity(opacity); } float SearchTermWidget::overlay_opacity() const { @@ -250,45 +262,44 @@ void SearchTermWidget::SetTerm(const SearchTerm& term) { // The value depends on the data type switch (SearchTerm::TypeOf(term.field_)) { - case SearchTerm::Type_Text: - ui_->value_text->setText(term.value_.toString()); - break; + case SearchTerm::Type_Text: + ui_->value_text->setText(term.value_.toString()); + break; - case SearchTerm::Type_Number: - ui_->value_number->setValue(term.value_.toInt()); - break; + case SearchTerm::Type_Number: + ui_->value_number->setValue(term.value_.toInt()); + break; - case SearchTerm::Type_Date: - if (ui_->value_stack->currentWidget() == ui_->page_date_numeric) { - ui_->value_date_numeric->setValue(term.value_.toInt()); - ui_->date_type->setCurrentIndex(term.date_); - } - else if (ui_->value_stack->currentWidget() == ui_->page_date_relative) { - ui_->value_date_numeric1->setValue(term.value_.toInt()); - ui_->value_date_numeric2->setValue(term.second_value_.toInt()); - ui_->date_type_relative->setCurrentIndex(term.date_); - } - else if (ui_->value_stack->currentWidget() == ui_->page_date) { - ui_->value_date->setDateTime(QDateTime::fromTime_t(term.value_.toInt())); - } - break; + case SearchTerm::Type_Date: + if (ui_->value_stack->currentWidget() == ui_->page_date_numeric) { + ui_->value_date_numeric->setValue(term.value_.toInt()); + ui_->date_type->setCurrentIndex(term.date_); + } else if (ui_->value_stack->currentWidget() == ui_->page_date_relative) { + ui_->value_date_numeric1->setValue(term.value_.toInt()); + ui_->value_date_numeric2->setValue(term.second_value_.toInt()); + ui_->date_type_relative->setCurrentIndex(term.date_); + } else if (ui_->value_stack->currentWidget() == ui_->page_date) { + ui_->value_date->setDateTime( + QDateTime::fromTime_t(term.value_.toInt())); + } + break; - case SearchTerm::Type_Time: - ui_->value_time->setTime(QTime(0,0).addSecs(term.value_.toInt())); - break; + case SearchTerm::Type_Time: + ui_->value_time->setTime(QTime(0, 0).addSecs(term.value_.toInt())); + break; - case SearchTerm::Type_Rating: - ui_->value_rating->set_rating(term.value_.toFloat()); - break; + case SearchTerm::Type_Rating: + ui_->value_rating->set_rating(term.value_.toFloat()); + break; - case SearchTerm::Type_Invalid: - break; + case SearchTerm::Type_Invalid: + break; } } SearchTerm SearchTermWidget::Term() const { const int field = ui_->field->itemData(ui_->field->currentIndex()).toInt(); - const int op = ui_->op->itemData(ui_->op->currentIndex()).toInt(); + const int op = ui_->op->itemData(ui_->op->currentIndex()).toInt(); SearchTerm ret; ret.field_ = SearchTerm::Field(field); @@ -303,7 +314,7 @@ SearchTerm SearchTermWidget::Term() const { } else if (value_page == ui_->page_date) { ret.value_ = ui_->value_date->dateTime().toTime_t(); } else if (value_page == ui_->page_time) { - ret.value_ = QTime(0,0).secsTo(ui_->value_time->time()); + ret.value_ = QTime(0, 0).secsTo(ui_->value_time->time()); } else if (value_page == ui_->page_rating) { ret.value_ = ui_->value_rating->rating(); } else if (value_page == ui_->page_date_numeric) { @@ -326,21 +337,20 @@ void SearchTermWidget::RelativeValueChanged() { } // Explain the user why he can't proceed if (ui_->value_date_numeric1->value() >= ui_->value_date_numeric2->value()) { - QMessageBox::warning(this, tr("Clementine"), - tr("The second value must be greater than the first one!")); + QMessageBox::warning( + this, tr("Clementine"), + tr("The second value must be greater than the first one!")); } // Emit the signal in any case, so the Next button will be disabled emit Changed(); } - SearchTermWidget::Overlay::Overlay(SearchTermWidget* parent) - : QWidget(parent), - parent_(parent), - opacity_(0.0), - text_(tr("Add search term")), - icon_(IconLoader::Load("list-add").pixmap(kIconSize)) -{ + : QWidget(parent), + parent_(parent), + opacity_(0.0), + text_(tr("Add search term")), + icon_(IconLoader::Load("list-add").pixmap(kIconSize)) { raise(); } @@ -395,8 +405,7 @@ void SearchTermWidget::Overlay::paintEvent(QPaintEvent*) { contents_size); const QRect icon(contents.topLeft(), QSize(kIconSize, kIconSize)); const QRect text(icon.right() + kSpacing, icon.top(), - contents.width() - kSpacing - kIconSize, - contents.height()); + contents.width() - kSpacing - kIconSize, contents.height()); // Icon and text p.setPen(palette().color(QPalette::Text)); @@ -408,4 +417,4 @@ void SearchTermWidget::Overlay::mouseReleaseEvent(QMouseEvent*) { emit parent_->Clicked(); } -} // namespace +} // namespace diff --git a/src/smartplaylists/searchtermwidget.h b/src/smartplaylists/searchtermwidget.h index 35d894201..7363b838f 100644 --- a/src/smartplaylists/searchtermwidget.h +++ b/src/smartplaylists/searchtermwidget.h @@ -32,11 +32,10 @@ namespace smart_playlists { class SearchTermWidget : public QWidget { Q_OBJECT - Q_PROPERTY(float overlay_opacity - READ overlay_opacity - WRITE set_overlay_opacity); + Q_PROPERTY(float overlay_opacity READ overlay_opacity WRITE + set_overlay_opacity); -public: + public: SearchTermWidget(LibraryBackend* library, QWidget* parent); ~SearchTermWidget(); @@ -54,19 +53,19 @@ signals: void Changed(); -protected: + protected: void showEvent(QShowEvent*); void enterEvent(QEvent*); void leaveEvent(QEvent*); void resizeEvent(QResizeEvent*); -private slots: + private slots: void FieldChanged(int index); void OpChanged(int index); void RelativeValueChanged(); void Grab(); -private: + private: class Overlay; friend class Overlay; @@ -81,6 +80,6 @@ private: SearchTerm::Type current_field_type_; }; -} // namespace +} // namespace -#endif // SMARTPLAYLISTSEARCHTERMWIDGET_H +#endif // SMARTPLAYLISTSEARCHTERMWIDGET_H diff --git a/src/smartplaylists/wizard.cpp b/src/smartplaylists/wizard.cpp index 4167d634d..efce81ccc 100644 --- a/src/smartplaylists/wizard.cpp +++ b/src/smartplaylists/wizard.cpp @@ -28,26 +28,22 @@ namespace smart_playlists { class Wizard::TypePage : public QWizardPage { -public: - TypePage(QWidget* parent) - : QWizardPage(parent), next_id_(-1) {} + public: + TypePage(QWidget* parent) : QWizardPage(parent), next_id_(-1) {} int nextId() const { return next_id_; } int next_id_; }; class Wizard::FinishPage : public QWizardPage { -public: + public: FinishPage(QWidget* parent) - : QWizardPage(parent), - ui_(new Ui_SmartPlaylistWizardFinishPage) { + : QWizardPage(parent), ui_(new Ui_SmartPlaylistWizardFinishPage) { ui_->setupUi(this); connect(ui_->name, SIGNAL(textChanged(QString)), SIGNAL(completeChanged())); } - ~FinishPage() { - delete ui_; - } + ~FinishPage() { delete ui_; } int nextId() const { return -1; } bool isComplete() const { return !ui_->name->text().isEmpty(); } @@ -56,14 +52,13 @@ public: }; Wizard::Wizard(Application* app, LibraryBackend* library, QWidget* parent) - : QWizard(parent), - app_(app), - library_(library), - type_page_(new TypePage(this)), - finish_page_(new FinishPage(this)), - type_index_(-1), - type_mapper_(new QSignalMapper(this)) -{ + : QWizard(parent), + app_(app), + library_(library), + type_page_(new TypePage(this)), + finish_page_(new FinishPage(this)), + type_index_(-1), + type_mapper_(new QSignalMapper(this)) { setWindowIcon(QIcon(":/icon.png")); setWindowTitle(tr("Smart playlist")); resize(788, 628); @@ -71,14 +66,17 @@ Wizard::Wizard(Application* app, LibraryBackend* library, QWidget* parent) #ifdef Q_OS_MAC // MacStyle leaves an ugly empty space on the left side of the dialog. setWizardStyle(QWizard::ClassicStyle); -#endif // Q_OS_MAC +#endif // Q_OS_MAC // Type page type_page_->setTitle(tr("Playlist type")); - type_page_->setSubTitle(tr("A smart playlist is a dynamic list of songs that come from your library. There are different types of smart playlist that offer different ways of selecting songs.")); + type_page_->setSubTitle( + tr("A smart playlist is a dynamic list of songs that come from your " + "library. There are different types of smart playlist that offer " + "different ways of selecting songs.")); type_page_->setStyleSheet( - "QRadioButton { font-weight: bold; }" - "QLabel { margin-bottom: 1em; margin-left: 24px; }"); + "QRadioButton { font-weight: bold; }" + "QLabel { margin-bottom: 1em; margin-left: 24px; }"); addPage(type_page_); // Finish page @@ -95,13 +93,11 @@ Wizard::Wizard(Application* app, LibraryBackend* library, QWidget* parent) setStartId(2); } -Wizard::~Wizard() { - qDeleteAll(plugins_); -} +Wizard::~Wizard() { qDeleteAll(plugins_); } void Wizard::SetGenerator(GeneratorPtr gen) { // Find the right type and jump to the start page - for (int i=0 ; itype() == gen->type()) { TypeChanged(i); // TODO: Put this back in when the setStartId is removed from the ctor @@ -145,12 +141,10 @@ void Wizard::TypeChanged(int index) { GeneratorPtr Wizard::CreateGenerator() const { GeneratorPtr ret; - if (type_index_ == -1) - return ret; + if (type_index_ == -1) return ret; ret = plugins_[type_index_]->CreateGenerator(); - if (!ret) - return ret; + if (!ret) return ret; ret->set_name(finish_page_->ui_->name->text()); ret->set_dynamic(finish_page_->ui_->dynamic->isChecked()); @@ -160,9 +154,9 @@ GeneratorPtr Wizard::CreateGenerator() const { void Wizard::initializePage(int id) { if (id == finish_id_) { finish_page_->ui_->dynamic_container->setEnabled( - plugins_[type_index_]->is_dynamic()); + plugins_[type_index_]->is_dynamic()); } QWizard::initializePage(id); } -} // namespace +} // namespace diff --git a/src/smartplaylists/wizard.h b/src/smartplaylists/wizard.h index f8599ce54..0d4f07fff 100644 --- a/src/smartplaylists/wizard.h +++ b/src/smartplaylists/wizard.h @@ -35,26 +35,26 @@ class WizardPlugin; class Wizard : public QWizard { Q_OBJECT -public: + public: Wizard(Application* app, LibraryBackend* library, QWidget* parent); ~Wizard(); void SetGenerator(GeneratorPtr gen); GeneratorPtr CreateGenerator() const; -protected: + protected: void initializePage(int id); -private: + private: class TypePage; class FinishPage; void AddPlugin(WizardPlugin* plugin); -private slots: + private slots: void TypeChanged(int index); -private: + private: Application* app_; LibraryBackend* library_; TypePage* type_page_; @@ -66,6 +66,6 @@ private: QSignalMapper* type_mapper_; }; -} // namespace +} // namespace -#endif // SMARTPLAYLISTWIZARD_H +#endif // SMARTPLAYLISTWIZARD_H diff --git a/src/smartplaylists/wizardplugin.cpp b/src/smartplaylists/wizardplugin.cpp index 6f4eacdb5..8405e626e 100644 --- a/src/smartplaylists/wizardplugin.cpp +++ b/src/smartplaylists/wizardplugin.cpp @@ -19,16 +19,12 @@ namespace smart_playlists { -WizardPlugin::WizardPlugin(Application* app, LibraryBackend* library, QObject* parent) - : QObject(parent), - app_(app), - library_(library), - start_page_(-1) -{ -} +WizardPlugin::WizardPlugin(Application* app, LibraryBackend* library, + QObject* parent) + : QObject(parent), app_(app), library_(library), start_page_(-1) {} void WizardPlugin::Init(QWizard* wizard, int finish_page_id) { start_page_ = CreatePages(wizard, finish_page_id); } -} // namespace smart_playlists +} // namespace smart_playlists diff --git a/src/smartplaylists/wizardplugin.h b/src/smartplaylists/wizardplugin.h index 2d9cea116..55571cbe4 100644 --- a/src/smartplaylists/wizardplugin.h +++ b/src/smartplaylists/wizardplugin.h @@ -32,7 +32,7 @@ namespace smart_playlists { class WizardPlugin : public QObject { Q_OBJECT -public: + public: WizardPlugin(Application* app, LibraryBackend* library, QObject* parent); virtual QString type() const = 0; @@ -46,16 +46,16 @@ public: void Init(QWizard* wizard, int finish_page_id); -protected: + protected: virtual int CreatePages(QWizard* wizard, int finish_page_id) = 0; Application* app_; LibraryBackend* library_; -private: + private: int start_page_; }; -} // namespace smart_playlists +} // namespace smart_playlists -#endif // WIZARDPLUGIN_H +#endif // WIZARDPLUGIN_H diff --git a/src/songinfo/artistinfoview.cpp b/src/songinfo/artistinfoview.cpp index 816c49c5c..131c81142 100644 --- a/src/songinfo/artistinfoview.cpp +++ b/src/songinfo/artistinfoview.cpp @@ -23,13 +23,11 @@ #include "widgets/prettyimageview.h" #ifdef HAVE_LIBLASTFM - #include "echonestsimilarartists.h" - #include "echonesttags.h" +#include "echonestsimilarartists.h" +#include "echonesttags.h" #endif -ArtistInfoView::ArtistInfoView(QWidget *parent) - : SongInfoBase(parent) -{ +ArtistInfoView::ArtistInfoView(QWidget* parent) : SongInfoBase(parent) { fetcher_->AddProvider(new EchoNestBiographies); fetcher_->AddProvider(new EchoNestImages); fetcher_->AddProvider(new SongkickConcerts); @@ -39,37 +37,33 @@ ArtistInfoView::ArtistInfoView(QWidget *parent) #endif } -ArtistInfoView::~ArtistInfoView() { -} +ArtistInfoView::~ArtistInfoView() {} -bool ArtistInfoView::NeedsUpdate(const Song& old_metadata, const Song& new_metadata) const { - if (new_metadata.artist().isEmpty()) - return false; +bool ArtistInfoView::NeedsUpdate(const Song& old_metadata, + const Song& new_metadata) const { + if (new_metadata.artist().isEmpty()) return false; return old_metadata.artist() != new_metadata.artist(); } - -void ArtistInfoView::InfoResultReady (int id, const CollapsibleInfoPane::Data& data) { - if (id != current_request_id_) - return; - - AddSection (new CollapsibleInfoPane(data, this)); + +void ArtistInfoView::InfoResultReady(int id, + const CollapsibleInfoPane::Data& data) { + if (id != current_request_id_) return; + + AddSection(new CollapsibleInfoPane(data, this)); CollapseSections(); } - -void ArtistInfoView::ResultReady(int id, const SongInfoFetcher::Result& result) { - if (id != current_request_id_) - return; + +void ArtistInfoView::ResultReady(int id, + const SongInfoFetcher::Result& result) { + if (id != current_request_id_) return; if (!result.images_.isEmpty()) { // Image view goes at the top PrettyImageView* image_view = new PrettyImageView(network_, this); AddWidget(image_view); - foreach (const QUrl& url, result.images_) { - image_view->AddImage(url); - } + foreach(const QUrl & url, result.images_) { image_view->AddImage(url); } } CollapseSections(); } - diff --git a/src/songinfo/artistinfoview.h b/src/songinfo/artistinfoview.h index 5a597d11f..b25a8788c 100644 --- a/src/songinfo/artistinfoview.h +++ b/src/songinfo/artistinfoview.h @@ -31,17 +31,16 @@ class QVBoxLayout; class ArtistInfoView : public SongInfoBase { Q_OBJECT -public: + public: ArtistInfoView(QWidget* parent = 0); ~ArtistInfoView(); -protected: - virtual void InfoResultReady (int id, const CollapsibleInfoPane::Data& data); + protected: + virtual void InfoResultReady(int id, const CollapsibleInfoPane::Data& data); bool NeedsUpdate(const Song& old_metadata, const Song& new_metadata) const; -protected slots: + protected slots: void ResultReady(int id, const SongInfoFetcher::Result& result); }; -#endif // ARTISTINFOVIEW_H - +#endif // ARTISTINFOVIEW_H diff --git a/src/songinfo/collapsibleinfoheader.cpp b/src/songinfo/collapsibleinfoheader.cpp index 8df53e917..64b182e2f 100644 --- a/src/songinfo/collapsibleinfoheader.cpp +++ b/src/songinfo/collapsibleinfoheader.cpp @@ -27,12 +27,11 @@ const int CollapsibleInfoHeader::kHeight = 20; const int CollapsibleInfoHeader::kIconSize = 16; CollapsibleInfoHeader::CollapsibleInfoHeader(QWidget* parent) - : QWidget(parent), - expanded_(false), - hovering_(false), - animation_(new QPropertyAnimation(this, "opacity", this)), - opacity_(0.0) -{ + : QWidget(parent), + expanded_(false), + hovering_(false), + animation_(new QPropertyAnimation(this, "opacity", this)), + opacity_(0.0) { setMinimumHeight(kHeight); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); setCursor(QCursor(Qt::PointingHandCursor)); @@ -86,21 +85,25 @@ void CollapsibleInfoHeader::set_opacity(float opacity) { void CollapsibleInfoHeader::paintEvent(QPaintEvent* e) { QPainter p(this); - QColor active_text_color(palette().color(QPalette::Active, QPalette::HighlightedText)); + QColor active_text_color( + palette().color(QPalette::Active, QPalette::HighlightedText)); QColor inactive_text_color(palette().color(QPalette::Active, QPalette::Text)); QColor text_color; if (expanded_) { text_color = active_text_color; } else { p.setOpacity(0.4 + opacity_ * 0.6); - text_color = QColor( - active_text_color.red() * opacity_ + inactive_text_color.red() * (1.0 - opacity_), - active_text_color.green() * opacity_ + inactive_text_color.green() * (1.0 - opacity_), - active_text_color.blue() * opacity_ + inactive_text_color.blue() * (1.0 - opacity_)); + text_color = QColor(active_text_color.red() * opacity_ + + inactive_text_color.red() * (1.0 - opacity_), + active_text_color.green() * opacity_ + + inactive_text_color.green() * (1.0 - opacity_), + active_text_color.blue() * opacity_ + + inactive_text_color.blue() * (1.0 - opacity_)); } QRect indicator_rect(0, 0, height(), height()); - QRect icon_rect(height() + 2, (kHeight - kIconSize) / 2, kIconSize, kIconSize); + QRect icon_rect(height() + 2, (kHeight - kIconSize) / 2, kIconSize, + kIconSize); QRect text_rect(rect()); text_rect.setLeft(icon_rect.right() + 4); @@ -127,14 +130,13 @@ void CollapsibleInfoHeader::paintEvent(QPaintEvent* e) { opt.initFrom(this); opt.rect = indicator_rect; opt.state |= QStyle::State_Children; - if (expanded_) - opt.state |= QStyle::State_Open; - if (hovering_) - opt.state |= QStyle::State_Active; + if (expanded_) opt.state |= QStyle::State_Open; + if (hovering_) opt.state |= QStyle::State_Active; // Have to use the application's style here because using the widget's style // will trigger QStyleSheetStyle's recursion guard (I don't know why). - QApplication::style()->drawPrimitive(QStyle::PE_IndicatorBranch, &opt, &p, this); + QApplication::style()->drawPrimitive(QStyle::PE_IndicatorBranch, &opt, &p, + this); // Draw the icon p.drawPixmap(icon_rect, icon_.pixmap(kIconSize)); diff --git a/src/songinfo/collapsibleinfoheader.h b/src/songinfo/collapsibleinfoheader.h index 5696a2e76..388197ad8 100644 --- a/src/songinfo/collapsibleinfoheader.h +++ b/src/songinfo/collapsibleinfoheader.h @@ -27,7 +27,7 @@ class CollapsibleInfoHeader : public QWidget { Q_OBJECT Q_PROPERTY(float opacity READ opacity WRITE set_opacity); -public: + public: CollapsibleInfoHeader(QWidget* parent = 0); static const int kHeight; @@ -41,7 +41,7 @@ public: float opacity() const { return opacity_; } void set_opacity(float opacity); -public slots: + public slots: void SetExpanded(bool expanded); void SetTitle(const QString& title); void SetIcon(const QIcon& icon); @@ -51,13 +51,13 @@ signals: void Collapsed(); void ExpandedToggled(bool expanded); -protected: + protected: void enterEvent(QEvent*); void leaveEvent(QEvent*); void paintEvent(QPaintEvent* e); void mouseReleaseEvent(QMouseEvent*); -private: + private: bool expanded_; bool hovering_; QString title_; @@ -67,4 +67,4 @@ private: float opacity_; }; -#endif // COLLAPSIBLEINFOHEADER_H +#endif // COLLAPSIBLEINFOHEADER_H diff --git a/src/songinfo/collapsibleinfopane.cpp b/src/songinfo/collapsibleinfopane.cpp index 3a43af8e0..c76613b76 100644 --- a/src/songinfo/collapsibleinfopane.cpp +++ b/src/songinfo/collapsibleinfopane.cpp @@ -21,10 +21,7 @@ #include CollapsibleInfoPane::CollapsibleInfoPane(const Data& data, QWidget* parent) - : QWidget(parent), - data_(data), - header_(new CollapsibleInfoHeader(this)) -{ + : QWidget(parent), data_(data), header_(new CollapsibleInfoHeader(this)) { QVBoxLayout* layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(3); @@ -44,20 +41,17 @@ CollapsibleInfoPane::CollapsibleInfoPane(const Data& data, QWidget* parent) connect(header_, SIGNAL(ExpandedToggled(bool)), SIGNAL(Toggled(bool))); } -void CollapsibleInfoPane::Collapse() { - header_->SetExpanded(false); -} +void CollapsibleInfoPane::Collapse() { header_->SetExpanded(false); } -void CollapsibleInfoPane::Expand() { - header_->SetExpanded(true); -} +void CollapsibleInfoPane::Expand() { header_->SetExpanded(true); } void CollapsibleInfoPane::ExpandedToggled(bool expanded) { data_.contents_->setVisible(expanded); } -bool CollapsibleInfoPane::Data::operator <(const CollapsibleInfoPane::Data& other) const { - const int my_score = (TypeCount - type_ ) * 1000 + relevance_; +bool CollapsibleInfoPane::Data::operator<( + const CollapsibleInfoPane::Data& other) const { + const int my_score = (TypeCount - type_) * 1000 + relevance_; const int other_score = (TypeCount - other.type_) * 1000 + other.relevance_; return my_score > other_score; diff --git a/src/songinfo/collapsibleinfopane.h b/src/songinfo/collapsibleinfopane.h index cc884ba9d..36305aafa 100644 --- a/src/songinfo/collapsibleinfopane.h +++ b/src/songinfo/collapsibleinfopane.h @@ -26,11 +26,11 @@ class CollapsibleInfoHeader; class CollapsibleInfoPane : public QWidget { Q_OBJECT -public: + public: struct Data { Data() : type_(Type_Biography), relevance_(0) {} - bool operator <(const Data& other) const; + bool operator<(const Data& other) const; enum Type { Type_PlayCounts, @@ -38,7 +38,6 @@ public: Type_Similar, Type_Biography, Type_Lyrics, - TypeCount }; @@ -56,19 +55,19 @@ public: const Data& data() const { return data_; } -public slots: + public slots: void Expand(); void Collapse(); signals: void Toggled(bool expanded); -private slots: + private slots: void ExpandedToggled(bool expanded); -private: + private: Data data_; CollapsibleInfoHeader* header_; }; -#endif // COLLAPSIBLEINFOPANE_H +#endif // COLLAPSIBLEINFOPANE_H diff --git a/src/songinfo/echonestbiographies.cpp b/src/songinfo/echonestbiographies.cpp index 923fb4bb9..24967e305 100644 --- a/src/songinfo/echonestbiographies.cpp +++ b/src/songinfo/echonestbiographies.cpp @@ -57,26 +57,26 @@ void EchoNestBiographies::FetchInfo(int id, const Song& metadata) { void EchoNestBiographies::RequestFinished() { QNetworkReply* reply = qobject_cast(sender()); - if (!reply || !requests_.contains(reply)) - return; + if (!reply || !requests_.contains(reply)) return; reply->deleteLater(); RequestPtr request = requests_.take(reply); try { request->artist_->parseProfile(reply); - } catch (Echonest::ParseError e) { - qLog(Warning) << "Error parsing echonest reply:" << e.errorType() << e.what(); + } + catch (Echonest::ParseError e) { + qLog(Warning) << "Error parsing echonest reply:" << e.errorType() + << e.what(); } QSet already_seen; for (const Echonest::Biography& bio : request->artist_->biographies()) { QString canonical_site = bio.site().toLower(); - canonical_site.replace(QRegExp("[^a-z]"),""); + canonical_site.replace(QRegExp("[^a-z]"), ""); - if (already_seen.contains(canonical_site)) - continue; + if (already_seen.contains(canonical_site)) continue; already_seen.insert(canonical_site); CollapsibleInfoPane::Data data; @@ -94,18 +94,19 @@ void EchoNestBiographies::RequestFinished() { // Add a link to the bio webpage at the top if we have one if (!bio.url().isEmpty()) { text += "

" + - tr("Open in your browser") + - "

"; + tr("Open in your browser") + "

"; } text += bio.text(); if (bio.site() == "last.fm") { - // Echonest lost formatting and it seems there is currently no plans on Echonest side for changing this. + // Echonest lost formatting and it seems there is currently no plans on + // Echonest side for changing this. // But with last.fm, we can guess newlines: " " corresponds to a newline // (this seems to be because on last.fm' website, extra blank is inserted // before
tag, and this blank is kept). - // This is tricky, but this make the display nicer for last.fm biographies. - text.replace(" ","

"); + // This is tricky, but this make the display nicer for last.fm + // biographies. + text.replace(" ", "

"); } editor->SetHtml(text); data.contents_ = editor; diff --git a/src/songinfo/echonestbiographies.h b/src/songinfo/echonestbiographies.h index 8e8175fd1..2429bce58 100644 --- a/src/songinfo/echonestbiographies.h +++ b/src/songinfo/echonestbiographies.h @@ -27,15 +27,15 @@ class QNetworkReply; class EchoNestBiographies : public SongInfoProvider { Q_OBJECT -public: + public: EchoNestBiographies(); void FetchInfo(int id, const Song& metadata); -private slots: + private slots: void RequestFinished(); -private: + private: QMap site_relevance_; QMap site_icons_; @@ -45,4 +45,4 @@ private: QMap requests_; }; -#endif // ECHONESTBIOGRAPHIES_H +#endif // ECHONESTBIOGRAPHIES_H diff --git a/src/songinfo/echonestimages.cpp b/src/songinfo/echonestimages.cpp index b16e9c20c..4cc7ff62e 100644 --- a/src/songinfo/echonestimages.cpp +++ b/src/songinfo/echonestimages.cpp @@ -41,19 +41,20 @@ void EchoNestImages::FetchInfo(int id, const Song& metadata) { void EchoNestImages::RequestFinished() { QNetworkReply* reply = qobject_cast(sender()); - if (!reply || !requests_.contains(reply)) - return; + if (!reply || !requests_.contains(reply)) return; reply->deleteLater(); RequestPtr request = requests_.take(reply); try { request->artist_->parseProfile(reply); - } catch (Echonest::ParseError e) { - qLog(Warning) << "Error parsing echonest reply:" << e.errorType() << e.what(); + } + catch (Echonest::ParseError e) { + qLog(Warning) << "Error parsing echonest reply:" << e.errorType() + << e.what(); } - foreach (const Echonest::ArtistImage& image, request->artist_->images()) { + foreach(const Echonest::ArtistImage & image, request->artist_->images()) { emit ImageReady(request->id_, image.url()); } diff --git a/src/songinfo/echonestimages.h b/src/songinfo/echonestimages.h index 25585b9bb..d1763a674 100644 --- a/src/songinfo/echonestimages.h +++ b/src/songinfo/echonestimages.h @@ -27,17 +27,17 @@ class QNetworkReply; class EchoNestImages : public SongInfoProvider { Q_OBJECT -public: + public: void FetchInfo(int id, const Song& metadata); -private slots: + private slots: void RequestFinished(); -private: + private: struct Request; typedef std::shared_ptr RequestPtr; QMap requests_; }; -#endif // ECHONESTIMAGES_H +#endif // ECHONESTIMAGES_H diff --git a/src/songinfo/echonestsimilarartists.cpp b/src/songinfo/echonestsimilarartists.cpp index b42c8dd8c..4c394ba21 100644 --- a/src/songinfo/echonestsimilarartists.cpp +++ b/src/songinfo/echonestsimilarartists.cpp @@ -38,8 +38,7 @@ void EchoNestSimilarArtists::FetchInfo(int id, const Song& metadata) { void EchoNestSimilarArtists::RequestFinished() { QNetworkReply* reply = qobject_cast(sender()); - if (!reply || !requests_.contains(reply)) - return; + if (!reply || !requests_.contains(reply)) return; reply->deleteLater(); int id = requests_.take(reply); @@ -47,8 +46,10 @@ void EchoNestSimilarArtists::RequestFinished() { Echonest::Artists artists; try { artists = Echonest::Artist::parseSimilar(reply); - } catch (Echonest::ParseError e) { - qLog(Warning) << "Error parsing echonest reply:" << e.errorType() << e.what(); + } + catch (Echonest::ParseError e) { + qLog(Warning) << "Error parsing echonest reply:" << e.errorType() + << e.what(); } if (!artists.isEmpty()) { @@ -63,10 +64,9 @@ void EchoNestSimilarArtists::RequestFinished() { widget->SetIcon(QIcon(":/icons/22x22/x-clementine-artist.png")); - foreach (const Echonest::Artist& artist, artists) { + foreach(const Echonest::Artist & artist, artists) { widget->AddTag(artist.name()); - if (widget->count() >= 10) - break; + if (widget->count() >= 10) break; } emit InfoReady(id, data); diff --git a/src/songinfo/echonestsimilarartists.h b/src/songinfo/echonestsimilarartists.h index 22065fc18..f78fa544f 100644 --- a/src/songinfo/echonestsimilarartists.h +++ b/src/songinfo/echonestsimilarartists.h @@ -25,14 +25,14 @@ class QNetworkReply; class EchoNestSimilarArtists : public SongInfoProvider { Q_OBJECT -public: + public: void FetchInfo(int id, const Song& metadata); -private slots: + private slots: void RequestFinished(); -private: + private: QMap requests_; }; -#endif // ECHONESTSIMILARARTISTS_H +#endif // ECHONESTSIMILARARTISTS_H diff --git a/src/songinfo/echonesttags.cpp b/src/songinfo/echonesttags.cpp index 6ed53afe2..7911cecf4 100644 --- a/src/songinfo/echonesttags.cpp +++ b/src/songinfo/echonesttags.cpp @@ -42,16 +42,17 @@ void EchoNestTags::FetchInfo(int id, const Song& metadata) { void EchoNestTags::RequestFinished() { QNetworkReply* reply = qobject_cast(sender()); - if (!reply || !requests_.contains(reply)) - return; + if (!reply || !requests_.contains(reply)) return; reply->deleteLater(); RequestPtr request = requests_.take(reply); try { request->artist_->parseProfile(reply); - } catch (Echonest::ParseError e) { - qLog(Warning) << "Error parsing echonest reply:" << e.errorType() << e.what(); + } + catch (Echonest::ParseError e) { + qLog(Warning) << "Error parsing echonest reply:" << e.errorType() + << e.what(); } if (!request->artist_->terms().isEmpty()) { @@ -68,8 +69,7 @@ void EchoNestTags::RequestFinished() { for (const Echonest::Term& term : request->artist_->terms()) { widget->AddTag(term.name()); - if (widget->count() >= 10) - break; + if (widget->count() >= 10) break; } emit InfoReady(request->id_, data); @@ -77,4 +77,3 @@ void EchoNestTags::RequestFinished() { emit Finished(request->id_); } - diff --git a/src/songinfo/echonesttags.h b/src/songinfo/echonesttags.h index 96bddd86d..5776f3e00 100644 --- a/src/songinfo/echonesttags.h +++ b/src/songinfo/echonesttags.h @@ -27,17 +27,17 @@ class QNetworkReply; class EchoNestTags : public SongInfoProvider { Q_OBJECT -public: + public: void FetchInfo(int id, const Song& metadata); -private slots: + private slots: void RequestFinished(); -private: + private: struct Request; typedef std::shared_ptr RequestPtr; QMap requests_; }; -#endif // ECHONESTTAGS_H +#endif // ECHONESTTAGS_H diff --git a/src/songinfo/lastfmtrackinfoprovider.cpp b/src/songinfo/lastfmtrackinfoprovider.cpp index e60ab0ea3..99956a9ae 100644 --- a/src/songinfo/lastfmtrackinfoprovider.cpp +++ b/src/songinfo/lastfmtrackinfoprovider.cpp @@ -38,8 +38,7 @@ void LastfmTrackInfoProvider::FetchInfo(int id, const Song& metadata) { void LastfmTrackInfoProvider::RequestFinished() { QNetworkReply* reply = qobject_cast(sender()); - if (!reply || !requests_.contains(reply)) - return; + if (!reply || !requests_.contains(reply)) return; const int id = requests_.take(reply); @@ -70,8 +69,7 @@ void LastfmTrackInfoProvider::GetPlayCounts(int id, const lastfm::XmlQuery& q) { love = q["track"]["userloved"].text() == "1"; } - if (!listeners && !playcount && myplaycount == -1) - return; // No useful data + if (!listeners && !playcount && myplaycount == -1) return; // No useful data CollapsibleInfoPane::Data data; data.id_ = "lastfm/playcounts"; @@ -85,26 +83,27 @@ void LastfmTrackInfoProvider::GetPlayCounts(int id, const lastfm::XmlQuery& q) { if (myplaycount != -1) { if (love) widget->AddItem(QIcon(":/last.fm/love.png"), tr("You love this track")); - widget->AddItem(QIcon(":/last.fm/icon_user.png"), tr("Your scrobbles: %1").arg(myplaycount)); + widget->AddItem(QIcon(":/last.fm/icon_user.png"), + tr("Your scrobbles: %1").arg(myplaycount)); } if (playcount) - widget->AddItem(IconLoader::Load("media-playback-start"), tr("%L1 total plays").arg(playcount)); + widget->AddItem(IconLoader::Load("media-playback-start"), + tr("%L1 total plays").arg(playcount)); if (listeners) - widget->AddItem(QIcon(":/last.fm/my_neighbours.png"), tr("%L1 other listeners").arg(listeners)); + widget->AddItem(QIcon(":/last.fm/my_neighbours.png"), + tr("%L1 other listeners").arg(listeners)); emit InfoReady(id, data); } void LastfmTrackInfoProvider::GetWiki(int id, const lastfm::XmlQuery& q) { // Parse the response - if (q["track"].children("wiki").isEmpty()) - return; // No wiki element + if (q["track"].children("wiki").isEmpty()) return; // No wiki element const QString content = q["track"]["wiki"]["content"].text(); - if (content.isEmpty()) - return; // No useful data + if (content.isEmpty()) return; // No useful data CollapsibleInfoPane::Data data; data.id_ = "lastfm/songwiki"; @@ -124,7 +123,7 @@ void LastfmTrackInfoProvider::GetTags(int id, const lastfm::XmlQuery& q) { // Parse the response if (q["track"].children("toptags").isEmpty() || q["track"]["toptags"].children("tag").isEmpty()) - return; // No tag elements + return; // No tag elements CollapsibleInfoPane::Data data; data.id_ = "lastfm/songtags"; @@ -137,7 +136,7 @@ void LastfmTrackInfoProvider::GetTags(int id, const lastfm::XmlQuery& q) { widget->SetIcon(data.icon_); - foreach (const lastfm::XmlQuery& e, q["track"]["toptags"].children("tag")) { + foreach(const lastfm::XmlQuery & e, q["track"]["toptags"].children("tag")) { widget->AddTag(e["name"].text()); } diff --git a/src/songinfo/lastfmtrackinfoprovider.h b/src/songinfo/lastfmtrackinfoprovider.h index 51ae416ce..1cd2d6692 100644 --- a/src/songinfo/lastfmtrackinfoprovider.h +++ b/src/songinfo/lastfmtrackinfoprovider.h @@ -21,7 +21,7 @@ #include "songinfoprovider.h" namespace lastfm { - class XmlQuery; +class XmlQuery; } class QNetworkReply; @@ -29,19 +29,19 @@ class QNetworkReply; class LastfmTrackInfoProvider : public SongInfoProvider { Q_OBJECT -public: + public: void FetchInfo(int id, const Song& metadata); -private slots: + private slots: void RequestFinished(); -private: + private: void GetPlayCounts(int id, const lastfm::XmlQuery& q); void GetWiki(int id, const lastfm::XmlQuery& q); void GetTags(int id, const lastfm::XmlQuery& q); -private: + private: QMap requests_; }; -#endif // LASTFMTRACKINFOPROVIDER_H +#endif // LASTFMTRACKINFOPROVIDER_H diff --git a/src/songinfo/songinfobase.cpp b/src/songinfo/songinfobase.cpp index 71a7329f2..8d84618ac 100644 --- a/src/songinfo/songinfobase.cpp +++ b/src/songinfo/songinfobase.cpp @@ -28,16 +28,15 @@ const char* SongInfoBase::kSettingsGroup = "SongInfo"; SongInfoBase::SongInfoBase(QWidget* parent) - : QWidget(parent), - network_(new NetworkAccessManager(this)), - fetcher_(new SongInfoFetcher(this)), - current_request_id_(-1), - scroll_area_(new QScrollArea), - container_(new QVBoxLayout), - section_container_(nullptr), - fader_(new WidgetFadeHelper(this, 1000)), - dirty_(false) -{ + : QWidget(parent), + network_(new NetworkAccessManager(this)), + fetcher_(new SongInfoFetcher(this)), + current_request_id_(-1), + scroll_area_(new QScrollArea), + container_(new QVBoxLayout), + section_container_(nullptr), + fader_(new WidgetFadeHelper(this, 1000)), + dirty_(false) { // Add the top-level scroll area setLayout(new QVBoxLayout); layout()->setContentsMargins(0, 0, 0, 0); @@ -62,10 +61,10 @@ SongInfoBase::SongInfoBase(QWidget* parent) stylesheet.open(QIODevice::ReadOnly); setStyleSheet(QString::fromAscii(stylesheet.readAll())); - connect(fetcher_, SIGNAL(ResultReady(int,SongInfoFetcher::Result)), - SLOT(ResultReady(int,SongInfoFetcher::Result))); - connect(fetcher_, SIGNAL(InfoResultReady(int,CollapsibleInfoPane::Data)), - SLOT(InfoResultReady(int,CollapsibleInfoPane::Data))); + connect(fetcher_, SIGNAL(ResultReady(int, SongInfoFetcher::Result)), + SLOT(ResultReady(int, SongInfoFetcher::Result))); + connect(fetcher_, SIGNAL(InfoResultReady(int, CollapsibleInfoPane::Data)), + SLOT(InfoResultReady(int, CollapsibleInfoPane::Data))); } void SongInfoBase::Clear() { @@ -81,21 +80,22 @@ void SongInfoBase::Clear() { section_container_->setLayout(new QVBoxLayout); section_container_->layout()->setContentsMargins(0, 0, 0, 0); section_container_->layout()->setSpacing(1); - section_container_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); + section_container_->setSizePolicy(QSizePolicy::Expanding, + QSizePolicy::Minimum); container_->insertWidget(0, section_container_); } void SongInfoBase::AddSection(CollapsibleInfoPane* section) { int index = 0; - for ( ; indexdata() < sections_[index]->data()) - break; + for (; index < sections_.count(); ++index) { + if (section->data() < sections_[index]->data()) break; } ConnectWidget(section->data().contents_); sections_.insert(index, section); - qobject_cast(section_container_->layout())->insertWidget(index, section); + qobject_cast(section_container_->layout()) + ->insertWidget(index, section); section->show(); } @@ -116,9 +116,7 @@ void SongInfoBase::SongChanged(const Song& metadata) { } } -void SongInfoBase::SongFinished() { - dirty_ = false; -} +void SongInfoBase::SongFinished() { dirty_ = false; } void SongInfoBase::showEvent(QShowEvent* e) { if (dirty_) { @@ -144,15 +142,15 @@ void SongInfoBase::Update(const Song& metadata) { // Do this after the new pane has been shown otherwise it'll just grab a // black rectangle. - Clear (); + Clear(); QTimer::singleShot(0, fader_, SLOT(StartBlur())); } -void SongInfoBase::InfoResultReady (int id, const CollapsibleInfoPane::Data& data) { -} +void SongInfoBase::InfoResultReady(int id, + const CollapsibleInfoPane::Data& data) {} void SongInfoBase::ResultReady(int id, const SongInfoFetcher::Result& result) { - foreach (const CollapsibleInfoPane::Data& data, result.info_) { + foreach(const CollapsibleInfoPane::Data & data, result.info_) { delete data.contents_; } } @@ -171,7 +169,7 @@ void SongInfoBase::CollapseSections() { QMap types_; QSet has_user_preference_; - foreach (CollapsibleInfoPane* pane, sections_) { + foreach(CollapsibleInfoPane * pane, sections_) { const CollapsibleInfoPane::Data::Type type = pane->data().type_; types_.insertMulti(type, pane); @@ -184,22 +182,21 @@ void SongInfoBase::CollapseSections() { } } - foreach (CollapsibleInfoPane::Data::Type type, types_.keys()) { + foreach(CollapsibleInfoPane::Data::Type type, types_.keys()) { if (!has_user_preference_.contains(type)) { // Expand the first one types_.values(type).last()->Expand(); } } - foreach (CollapsibleInfoPane* pane, sections_) { + foreach(CollapsibleInfoPane * pane, sections_) { connect(pane, SIGNAL(Toggled(bool)), SLOT(SectionToggled(bool))); } } void SongInfoBase::SectionToggled(bool value) { CollapsibleInfoPane* pane = qobject_cast(sender()); - if (!pane || !sections_.contains(pane)) - return; + if (!pane || !sections_.contains(pane)) return; QSettings s; s.beginGroup(kSettingsGroup); @@ -207,10 +204,9 @@ void SongInfoBase::SectionToggled(bool value) { } void SongInfoBase::ReloadSettings() { - foreach (CollapsibleInfoPane* pane, sections_) { + foreach(CollapsibleInfoPane * pane, sections_) { QWidget* contents = pane->data().contents_; - if (!contents) - continue; + if (!contents) continue; QMetaObject::invokeMethod(contents, "ReloadSettings"); } @@ -224,7 +220,7 @@ void SongInfoBase::ConnectWidget(QWidget* widget) { } if (m->indexOfSignal("DoGlobalSearch(QString)") != -1) { - connect(widget, SIGNAL(DoGlobalSearch(QString)), SIGNAL(DoGlobalSearch(QString))); + connect(widget, SIGNAL(DoGlobalSearch(QString)), + SIGNAL(DoGlobalSearch(QString))); } } - diff --git a/src/songinfo/songinfobase.h b/src/songinfo/songinfobase.h index ab8c8448c..0ff87354b 100644 --- a/src/songinfo/songinfobase.h +++ b/src/songinfo/songinfobase.h @@ -37,12 +37,12 @@ class QVBoxLayout; class SongInfoBase : public QWidget { Q_OBJECT -public: + public: SongInfoBase(QWidget* parent = 0); static const char* kSettingsGroup; -public slots: + public slots: void SongChanged(const Song& metadata); void SongFinished(); virtual void ReloadSettings(); @@ -51,34 +51,37 @@ signals: void ShowSettingsDialog(); void DoGlobalSearch(const QString& query); -protected: + protected: void showEvent(QShowEvent* e); virtual void Update(const Song& metadata); - virtual bool NeedsUpdate(const Song& old_metadata, const Song& new_metadata) const { return true; } + virtual bool NeedsUpdate(const Song& old_metadata, + const Song& new_metadata) const { + return true; + } void AddWidget(QWidget* widget); void AddSection(CollapsibleInfoPane* section); void Clear(); void CollapseSections(); -protected slots: - virtual void InfoResultReady (int id, const CollapsibleInfoPane::Data& data); + protected slots: + virtual void InfoResultReady(int id, const CollapsibleInfoPane::Data& data); virtual void ResultReady(int id, const SongInfoFetcher::Result& result); -protected: + protected: QNetworkAccessManager* network_; SongInfoFetcher* fetcher_; int current_request_id_; -private: + private: void MaybeUpdate(const Song& metadata); void ConnectWidget(QWidget* widget); -private slots: + private slots: void SectionToggled(bool value); -private: + private: QScrollArea* scroll_area_; QVBoxLayout* container_; @@ -94,5 +97,4 @@ private: bool dirty_; }; -#endif // SONGINFOBASE_H - +#endif // SONGINFOBASE_H diff --git a/src/songinfo/songinfofetcher.cpp b/src/songinfo/songinfofetcher.cpp index 1497fa994..f581ea11e 100644 --- a/src/songinfo/songinfofetcher.cpp +++ b/src/songinfo/songinfofetcher.cpp @@ -23,23 +23,23 @@ #include SongInfoFetcher::SongInfoFetcher(QObject* parent) - : QObject(parent), - timeout_timer_mapper_(new QSignalMapper(this)), - timeout_duration_(kDefaultTimeoutDuration), - next_id_(1) -{ + : QObject(parent), + timeout_timer_mapper_(new QSignalMapper(this)), + timeout_duration_(kDefaultTimeoutDuration), + next_id_(1) { connect(timeout_timer_mapper_, SIGNAL(mapped(int)), SLOT(Timeout(int))); } void SongInfoFetcher::AddProvider(SongInfoProvider* provider) { providers_ << provider; - connect(provider, SIGNAL(ImageReady(int,QUrl)), SLOT(ImageReady(int,QUrl))); - connect(provider, SIGNAL(InfoReady(int,CollapsibleInfoPane::Data)), SLOT(InfoReady(int,CollapsibleInfoPane::Data))); + connect(provider, SIGNAL(ImageReady(int, QUrl)), SLOT(ImageReady(int, QUrl))); + connect(provider, SIGNAL(InfoReady(int, CollapsibleInfoPane::Data)), + SLOT(InfoReady(int, CollapsibleInfoPane::Data))); connect(provider, SIGNAL(Finished(int)), SLOT(ProviderFinished(int))); } int SongInfoFetcher::FetchInfo(const Song& metadata) { - const int id = next_id_ ++; + const int id = next_id_++; results_[id] = Result(); timeout_timers_[id] = new QTimer(this); timeout_timers_[id]->setSingleShot(true); @@ -47,9 +47,10 @@ int SongInfoFetcher::FetchInfo(const Song& metadata) { timeout_timers_[id]->start(); timeout_timer_mapper_->setMapping(timeout_timers_[id], id); - connect(timeout_timers_[id], SIGNAL(timeout()), timeout_timer_mapper_, SLOT(map())); + connect(timeout_timers_[id], SIGNAL(timeout()), timeout_timer_mapper_, + SLOT(map())); - foreach (SongInfoProvider* provider, providers_) { + foreach(SongInfoProvider * provider, providers_) { if (provider->is_enabled()) { waiting_for_[id].append(provider); provider->FetchInfo(id, metadata); @@ -59,30 +60,24 @@ int SongInfoFetcher::FetchInfo(const Song& metadata) { } void SongInfoFetcher::ImageReady(int id, const QUrl& url) { - if (!results_.contains(id)) - return; + if (!results_.contains(id)) return; results_[id].images_ << url; } void SongInfoFetcher::InfoReady(int id, const CollapsibleInfoPane::Data& data) { - if (!results_.contains(id)) - return; + if (!results_.contains(id)) return; results_[id].info_ << data; - - if (!waiting_for_.contains(id)) - return; - emit InfoResultReady (id, data); + + if (!waiting_for_.contains(id)) return; + emit InfoResultReady(id, data); } void SongInfoFetcher::ProviderFinished(int id) { - if (!results_.contains(id)) - return; - if (!waiting_for_.contains(id)) - return; + if (!results_.contains(id)) return; + if (!waiting_for_.contains(id)) return; SongInfoProvider* provider = qobject_cast(sender()); - if (!waiting_for_[id].contains(provider)) - return; + if (!waiting_for_[id].contains(provider)) return; waiting_for_[id].removeAll(provider); if (waiting_for_[id].isEmpty()) { @@ -93,16 +88,14 @@ void SongInfoFetcher::ProviderFinished(int id) { } void SongInfoFetcher::Timeout(int id) { - if (!results_.contains(id)) - return; - if (!waiting_for_.contains(id)) - return; + if (!results_.contains(id)) return; + if (!waiting_for_.contains(id)) return; // Emit the results that we have already emit ResultReady(id, results_.take(id)); // Cancel any providers that we're still waiting for - foreach (SongInfoProvider* provider, waiting_for_[id]) { + foreach(SongInfoProvider * provider, waiting_for_[id]) { qLog(Info) << "Request timed out from info provider" << provider->name(); provider->Cancel(id); } @@ -111,4 +104,3 @@ void SongInfoFetcher::Timeout(int id) { // Remove the timer delete timeout_timers_.take(id); } - diff --git a/src/songinfo/songinfofetcher.h b/src/songinfo/songinfofetcher.h index e843a5908..9e0decf3d 100644 --- a/src/songinfo/songinfofetcher.h +++ b/src/songinfo/songinfofetcher.h @@ -32,7 +32,7 @@ class QSignalMapper; class SongInfoFetcher : public QObject { Q_OBJECT -public: + public: SongInfoFetcher(QObject* parent = 0); struct Result { @@ -40,7 +40,7 @@ public: QList info_; }; - static const int kDefaultTimeoutDuration = 25000; // msec + static const int kDefaultTimeoutDuration = 25000; // msec void AddProvider(SongInfoProvider* provider); int FetchInfo(const Song& metadata); @@ -48,16 +48,16 @@ public: QList providers() const { return providers_; } signals: - void InfoResultReady (int id, const CollapsibleInfoPane::Data& data); + void InfoResultReady(int id, const CollapsibleInfoPane::Data& data); void ResultReady(int id, const SongInfoFetcher::Result& result); -private slots: + private slots: void ImageReady(int id, const QUrl& url); void InfoReady(int id, const CollapsibleInfoPane::Data& data); void ProviderFinished(int id); void Timeout(int id); -private: + private: QList providers_; QMap results_; @@ -70,5 +70,4 @@ private: int next_id_; }; -#endif // SONGINFOFETCHER_H - +#endif // SONGINFOFETCHER_H diff --git a/src/songinfo/songinfoprovider.cpp b/src/songinfo/songinfoprovider.cpp index 21da0873c..80b830a95 100644 --- a/src/songinfo/songinfoprovider.cpp +++ b/src/songinfo/songinfoprovider.cpp @@ -17,11 +17,6 @@ #include "songinfoprovider.h" -SongInfoProvider::SongInfoProvider() - : enabled_(true) -{ -} +SongInfoProvider::SongInfoProvider() : enabled_(true) {} -QString SongInfoProvider::name() const { - return metaObject()->className(); -} +QString SongInfoProvider::name() const { return metaObject()->className(); } diff --git a/src/songinfo/songinfoprovider.h b/src/songinfo/songinfoprovider.h index 9925d5f67..c241296a0 100644 --- a/src/songinfo/songinfoprovider.h +++ b/src/songinfo/songinfoprovider.h @@ -27,7 +27,7 @@ class SongInfoProvider : public QObject { Q_OBJECT -public: + public: SongInfoProvider(); virtual void FetchInfo(int id, const Song& metadata) = 0; @@ -43,8 +43,8 @@ signals: void InfoReady(int id, const CollapsibleInfoPane::Data& data); void Finished(int id); -private: + private: bool enabled_; }; -#endif // SONGINFOPROVIDER_H +#endif // SONGINFOPROVIDER_H diff --git a/src/songinfo/songinfosettingspage.cpp b/src/songinfo/songinfosettingspage.cpp index 643afa12a..778b34f4d 100644 --- a/src/songinfo/songinfosettingspage.cpp +++ b/src/songinfo/songinfosettingspage.cpp @@ -27,31 +27,29 @@ #include #include - SongInfoSettingsPage::SongInfoSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_SongInfoSettingsPage) -{ + : SettingsPage(dialog), ui_(new Ui_SongInfoSettingsPage) { ui_->setupUi(this); setWindowIcon(IconLoader::Load("view-media-lyrics")); connect(ui_->up, SIGNAL(clicked()), SLOT(MoveUp())); connect(ui_->down, SIGNAL(clicked()), SLOT(MoveDown())); - connect(ui_->providers, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), + connect(ui_->providers, + SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), SLOT(CurrentItemChanged(QListWidgetItem*))); connect(ui_->providers, SIGNAL(itemChanged(QListWidgetItem*)), SLOT(ItemChanged(QListWidgetItem*))); QFile song_info_preview(":/lumberjacksong.txt"); song_info_preview.open(QIODevice::ReadOnly); - ui_->song_info_font_preview->setText(QString::fromUtf8(song_info_preview.readAll())); + ui_->song_info_font_preview->setText( + QString::fromUtf8(song_info_preview.readAll())); - connect(ui_->song_info_font_size, SIGNAL(valueChanged(double)), SLOT(FontSizeChanged(double))); + connect(ui_->song_info_font_size, SIGNAL(valueChanged(double)), + SLOT(FontSizeChanged(double))); } -SongInfoSettingsPage::~SongInfoSettingsPage() { - delete ui_; -} +SongInfoSettingsPage::~SongInfoSettingsPage() { delete ui_; } void SongInfoSettingsPage::Load() { QSettings s; @@ -61,15 +59,18 @@ void SongInfoSettingsPage::Load() { s.value("font_size", SongInfoTextView::kDefaultFontSize).toReal()); s.endGroup(); - QList providers = dialog()->song_info_view()->lyric_providers(); + QList providers = + dialog()->song_info_view()->lyric_providers(); ui_->providers->clear(); - foreach (const UltimateLyricsProvider* provider, providers) { + foreach(const UltimateLyricsProvider * provider, providers) { QListWidgetItem* item = new QListWidgetItem(ui_->providers); item->setText(provider->name()); item->setCheckState(provider->is_enabled() ? Qt::Checked : Qt::Unchecked); - item->setForeground(provider->is_enabled() ? palette().color(QPalette::Active, QPalette::Text) - : palette().color(QPalette::Disabled, QPalette::Text)); + item->setForeground( + provider->is_enabled() + ? palette().color(QPalette::Active, QPalette::Text) + : palette().color(QPalette::Disabled, QPalette::Text)); } } @@ -82,10 +83,9 @@ void SongInfoSettingsPage::Save() { s.beginGroup(SongInfoView::kSettingsGroup); QVariantList search_order; - for (int i=0 ; iproviders->count() ; ++i) { + for (int i = 0; i < ui_->providers->count(); ++i) { const QListWidgetItem* item = ui_->providers->item(i); - if (item->checkState() == Qt::Checked) - search_order << item->text(); + if (item->checkState() == Qt::Checked) search_order << item->text(); } s.setValue("search_order", search_order); s.endGroup(); @@ -102,13 +102,9 @@ void SongInfoSettingsPage::CurrentItemChanged(QListWidgetItem* item) { } } -void SongInfoSettingsPage::MoveUp() { - Move(-1); -} +void SongInfoSettingsPage::MoveUp() { Move(-1); } -void SongInfoSettingsPage::MoveDown() { - Move(+1); -} +void SongInfoSettingsPage::MoveDown() { Move(+1); } void SongInfoSettingsPage::Move(int d) { const int row = ui_->providers->currentRow(); @@ -119,8 +115,9 @@ void SongInfoSettingsPage::Move(int d) { void SongInfoSettingsPage::ItemChanged(QListWidgetItem* item) { const bool checked = item->checkState() == Qt::Checked; - item->setForeground(checked ? palette().color(QPalette::Active, QPalette::Text) - : palette().color(QPalette::Disabled, QPalette::Text)); + item->setForeground( + checked ? palette().color(QPalette::Active, QPalette::Text) + : palette().color(QPalette::Disabled, QPalette::Text)); } void SongInfoSettingsPage::FontSizeChanged(double value) { diff --git a/src/songinfo/songinfosettingspage.h b/src/songinfo/songinfosettingspage.h index e6bbe8fb0..ea6b57d14 100644 --- a/src/songinfo/songinfosettingspage.h +++ b/src/songinfo/songinfosettingspage.h @@ -28,14 +28,14 @@ class QListWidgetItem; class SongInfoSettingsPage : public SettingsPage { Q_OBJECT -public: + public: SongInfoSettingsPage(SettingsDialog* parent); ~SongInfoSettingsPage(); void Load(); void Save(); -private slots: + private slots: void MoveUp(); void MoveDown(); void Move(int d); @@ -45,8 +45,8 @@ private slots: void FontSizeChanged(double value); -private: + private: Ui_SongInfoSettingsPage* ui_; }; -#endif // SONGINFOSETTINGSPAGE_H +#endif // SONGINFOSETTINGSPAGE_H diff --git a/src/songinfo/songinfotextview.cpp b/src/songinfo/songinfotextview.cpp index bd66ef7ea..94b44f31d 100644 --- a/src/songinfo/songinfotextview.cpp +++ b/src/songinfo/songinfotextview.cpp @@ -29,10 +29,7 @@ const qreal SongInfoTextView::kDefaultFontSize = 8.5; const char* SongInfoTextView::kSettingsGroup = "SongInfo"; SongInfoTextView::SongInfoTextView(QWidget* parent) - : QTextBrowser(parent), - last_width_(-1), - recursion_filter_(false) -{ + : QTextBrowser(parent), last_width_(-1), recursion_filter_(false) { setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -52,14 +49,11 @@ QFont SongInfoTextView::Font() { return font; } -void SongInfoTextView::ReloadSettings() { - document()->setDefaultFont(Font()); -} +void SongInfoTextView::ReloadSettings() { document()->setDefaultFont(Font()); } void SongInfoTextView::resizeEvent(QResizeEvent* e) { const int w = qMax(100, width()); - if (w == last_width_) - return; + if (w == last_width_) return; last_width_ = w; document()->setTextWidth(w); @@ -68,19 +62,16 @@ void SongInfoTextView::resizeEvent(QResizeEvent* e) { QTextBrowser::resizeEvent(e); } -QSize SongInfoTextView::sizeHint() const { - return minimumSize(); -} +QSize SongInfoTextView::sizeHint() const { return minimumSize(); } -void SongInfoTextView::wheelEvent(QWheelEvent* e) { - e->ignore(); -} +void SongInfoTextView::wheelEvent(QWheelEvent* e) { e->ignore(); } void SongInfoTextView::contextMenuEvent(QContextMenuEvent* e) { QMenu* menu = createStandardContextMenu(e->pos()); menu->setAttribute(Qt::WA_DeleteOnClose); - menu->addAction(tr("Change font size..."), this, SIGNAL(ShowSettingsDialog())); + menu->addAction(tr("Change font size..."), this, + SIGNAL(ShowSettingsDialog())); menu->popup(e->globalPos()); } @@ -93,7 +84,8 @@ void SongInfoTextView::SetHtml(const QString& html) { copy.replace(QRegExp("([^>])[\\t ]*\\n"), "\\1

"); // Strip any newlines from the end - copy.replace(QRegExp("((<\\s*br\\s*/?\\s*>)|(<\\s*/?\\s*p\\s*/?\\s*>))+$"), ""); + copy.replace(QRegExp("((<\\s*br\\s*/?\\s*>)|(<\\s*/?\\s*p\\s*/?\\s*>))+$"), + ""); setHtml(copy); } diff --git a/src/songinfo/songinfotextview.h b/src/songinfo/songinfotextview.h index e305bb99a..27f5c6683 100644 --- a/src/songinfo/songinfotextview.h +++ b/src/songinfo/songinfotextview.h @@ -23,7 +23,7 @@ class SongInfoTextView : public QTextBrowser { Q_OBJECT -public: + public: SongInfoTextView(QWidget* parent = 0); static const qreal kDefaultFontSize; @@ -34,22 +34,22 @@ public: QSize sizeHint() const; -public slots: + public slots: void ReloadSettings(); void SetHtml(const QString& html); signals: void ShowSettingsDialog(); -protected: + protected: void resizeEvent(QResizeEvent* e); void wheelEvent(QWheelEvent* e); void contextMenuEvent(QContextMenuEvent* e); QVariant loadResource(int type, const QUrl& name); -private: + private: int last_width_; bool recursion_filter_; }; -#endif // SONGINFOTEXTVIEW_H +#endif // SONGINFOTEXTVIEW_H diff --git a/src/songinfo/songinfoview.cpp b/src/songinfo/songinfoview.cpp index 42790b0db..0541b99bb 100644 --- a/src/songinfo/songinfoview.cpp +++ b/src/songinfo/songinfoview.cpp @@ -22,7 +22,7 @@ #include "ultimatelyricsreader.h" #ifdef HAVE_LIBLASTFM - #include "lastfmtrackinfoprovider.h" +#include "lastfmtrackinfoprovider.h" #endif #include @@ -35,14 +35,13 @@ const char* SongInfoView::kSettingsGroup = "SongInfo"; typedef QList ProviderList; SongInfoView::SongInfoView(QWidget* parent) - : SongInfoBase(parent), - ultimate_reader_(new UltimateLyricsReader(this)) -{ + : SongInfoBase(parent), ultimate_reader_(new UltimateLyricsReader(this)) { // Parse the ultimate lyrics xml file in the background - QFuture future = QtConcurrent::run( - ultimate_reader_.get(), &UltimateLyricsReader::Parse, - QString(":lyrics/ultimate_providers.xml")); - QFutureWatcher* watcher = new QFutureWatcher(this); + QFuture future = + QtConcurrent::run(ultimate_reader_.get(), &UltimateLyricsReader::Parse, + QString(":lyrics/ultimate_providers.xml")); + QFutureWatcher* watcher = + new QFutureWatcher(this); watcher->setFuture(future); connect(watcher, SIGNAL(finished()), SLOT(UltimateLyricsParsed())); @@ -51,14 +50,13 @@ SongInfoView::SongInfoView(QWidget* parent) #endif } -SongInfoView::~SongInfoView() { -} +SongInfoView::~SongInfoView() {} void SongInfoView::UltimateLyricsParsed() { QFutureWatcher* watcher = static_cast*>(sender()); - foreach (SongInfoProvider* provider, watcher->result()) { + foreach(SongInfoProvider * provider, watcher->result()) { fetcher_->AddProvider(provider); } @@ -68,7 +66,8 @@ void SongInfoView::UltimateLyricsParsed() { ReloadSettings(); } -bool SongInfoView::NeedsUpdate(const Song& old_metadata, const Song& new_metadata) const { +bool SongInfoView::NeedsUpdate(const Song& old_metadata, + const Song& new_metadata) const { if (new_metadata.title().isEmpty() || new_metadata.artist().isEmpty()) return false; @@ -76,16 +75,15 @@ bool SongInfoView::NeedsUpdate(const Song& old_metadata, const Song& new_metadat old_metadata.artist() != new_metadata.artist(); } -void SongInfoView::InfoResultReady (int id, const CollapsibleInfoPane::Data& data) { - if (id != current_request_id_) - return; - - AddSection (new CollapsibleInfoPane(data, this)); +void SongInfoView::InfoResultReady(int id, + const CollapsibleInfoPane::Data& data) { + if (id != current_request_id_) return; + + AddSection(new CollapsibleInfoPane(data, this)); CollapseSections(); } -void SongInfoView::ResultReady(int id, const SongInfoFetcher::Result& result) { -} +void SongInfoView::ResultReady(int id, const SongInfoFetcher::Result& result) {} void SongInfoView::ReloadSettings() { QSettings s; @@ -115,22 +113,23 @@ void SongInfoView::ReloadSettings() { << "darklyrics.com"; QVariant saved_order = s.value("search_order", default_order); - foreach (const QVariant& name, saved_order.toList()) { + foreach(const QVariant & name, saved_order.toList()) { SongInfoProvider* provider = ProviderByName(name.toString()); - if (provider) - ordered_providers << provider; + if (provider) ordered_providers << provider; } // Enable all the providers in the list and rank them int relevance = 100; - foreach (SongInfoProvider* provider, ordered_providers) { + foreach(SongInfoProvider * provider, ordered_providers) { provider->set_enabled(true); qobject_cast(provider)->set_relevance(relevance--); } - // Any lyric providers we don't have in ordered_providers are considered disabled - foreach (SongInfoProvider* provider, fetcher_->providers()) { - if (qobject_cast(provider) && !ordered_providers.contains(provider)) { + // Any lyric providers we don't have in ordered_providers are considered + // disabled + foreach(SongInfoProvider * provider, fetcher_->providers()) { + if (qobject_cast(provider) && + !ordered_providers.contains(provider)) { provider->set_enabled(false); } } @@ -139,33 +138,32 @@ void SongInfoView::ReloadSettings() { } SongInfoProvider* SongInfoView::ProviderByName(const QString& name) const { - foreach (SongInfoProvider* provider, fetcher_->providers()) { - if (UltimateLyricsProvider* lyrics = qobject_cast(provider)) { - if (lyrics->name() == name) - return provider; + foreach(SongInfoProvider * provider, fetcher_->providers()) { + if (UltimateLyricsProvider* lyrics = + qobject_cast(provider)) { + if (lyrics->name() == name) return provider; } } return nullptr; } namespace { - bool CompareLyricProviders(const UltimateLyricsProvider* a, const UltimateLyricsProvider* b) { - if (a->is_enabled() && !b->is_enabled()) - return true; - if (!a->is_enabled() && b->is_enabled()) - return false; - return a->relevance() > b->relevance(); - } +bool CompareLyricProviders(const UltimateLyricsProvider* a, + const UltimateLyricsProvider* b) { + if (a->is_enabled() && !b->is_enabled()) return true; + if (!a->is_enabled() && b->is_enabled()) return false; + return a->relevance() > b->relevance(); +} } QList SongInfoView::lyric_providers() const { QList ret; - foreach (SongInfoProvider* provider, fetcher_->providers()) { - if (UltimateLyricsProvider* lyrics = qobject_cast(provider)) { + foreach(SongInfoProvider * provider, fetcher_->providers()) { + if (UltimateLyricsProvider* lyrics = + qobject_cast(provider)) { ret << lyrics; } } qSort(ret.begin(), ret.end(), CompareLyricProviders); return ret; } - diff --git a/src/songinfo/songinfoview.h b/src/songinfo/songinfoview.h index 82b869dfc..da42d80ec 100644 --- a/src/songinfo/songinfoview.h +++ b/src/songinfo/songinfoview.h @@ -28,7 +28,7 @@ class UltimateLyricsReader; class SongInfoView : public SongInfoBase { Q_OBJECT -public: + public: SongInfoView(QWidget* parent = 0); ~SongInfoView(); @@ -36,25 +36,24 @@ public: QList lyric_providers() const; -public slots: + public slots: void ReloadSettings(); -protected: + protected: bool NeedsUpdate(const Song& old_metadata, const Song& new_metadata) const; -protected slots: - virtual void InfoResultReady (int id, const CollapsibleInfoPane::Data& data); + protected slots: + virtual void InfoResultReady(int id, const CollapsibleInfoPane::Data& data); virtual void ResultReady(int id, const SongInfoFetcher::Result& result); -private: + private: SongInfoProvider* ProviderByName(const QString& name) const; -private slots: + private slots: void UltimateLyricsParsed(); -private: + private: std::unique_ptr ultimate_reader_; }; -#endif // SONGINFOVIEW_H - +#endif // SONGINFOVIEW_H diff --git a/src/songinfo/songkickconcerts.cpp b/src/songinfo/songkickconcerts.cpp index 186d7a0e4..feb9ec77d 100644 --- a/src/songinfo/songkickconcerts.cpp +++ b/src/songinfo/songkickconcerts.cpp @@ -38,18 +38,23 @@ const char* SongkickConcerts::kSongkickArtistCalendarUrl = SongkickConcerts::SongkickConcerts() { Geolocator* geolocator = new Geolocator; geolocator->Geolocate(); - connect(geolocator, SIGNAL(Finished(Geolocator::LatLng)), SLOT(GeolocateFinished(Geolocator::LatLng))); - NewClosure(geolocator, SIGNAL(Finished(Geolocator::LatLng)), geolocator, SLOT(deleteLater())); + connect(geolocator, SIGNAL(Finished(Geolocator::LatLng)), + SLOT(GeolocateFinished(Geolocator::LatLng))); + NewClosure(geolocator, SIGNAL(Finished(Geolocator::LatLng)), geolocator, + SLOT(deleteLater())); } void SongkickConcerts::FetchInfo(int id, const Song& metadata) { Echonest::Artist::SearchParams params; - params.push_back(qMakePair(Echonest::Artist::Name, QVariant(metadata.artist()))); - params.push_back(qMakePair(Echonest::Artist::IdSpace, QVariant(kSongkickArtistBucket))); + params.push_back( + qMakePair(Echonest::Artist::Name, QVariant(metadata.artist()))); + params.push_back( + qMakePair(Echonest::Artist::IdSpace, QVariant(kSongkickArtistBucket))); qLog(Debug) << "Params:" << params; QNetworkReply* reply = Echonest::Artist::search(params); qLog(Debug) << reply->request().url(); - NewClosure(reply, SIGNAL(finished()), this, SLOT(ArtistSearchFinished(QNetworkReply*, int)), reply, id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(ArtistSearchFinished(QNetworkReply*, int)), reply, id); } void SongkickConcerts::ArtistSearchFinished(QNetworkReply* reply, int id) { @@ -65,7 +70,7 @@ void SongkickConcerts::ArtistSearchFinished(QNetworkReply* reply, int id) { const Echonest::Artist& artist = artists[0]; const Echonest::ForeignIds& foreign_ids = artist.foreignIds(); QString songkick_id; - foreach (const Echonest::ForeignId& id, foreign_ids) { + foreach(const Echonest::ForeignId & id, foreign_ids) { if (id.catalog == "songkick") { songkick_id = id.foreign_id; break; @@ -86,7 +91,8 @@ void SongkickConcerts::ArtistSearchFinished(QNetworkReply* reply, int id) { } FetchSongkickCalendar(split[2], id); - } catch (Echonest::ParseError& e) { + } + catch (Echonest::ParseError& e) { qLog(Error) << "Error parsing echonest reply:" << e.errorType() << e.what(); emit Finished(id); } @@ -96,7 +102,8 @@ void SongkickConcerts::FetchSongkickCalendar(const QString& artist_id, int id) { QUrl url(QString(kSongkickArtistCalendarUrl).arg(artist_id)); qLog(Debug) << url; QNetworkReply* reply = network_.get(QNetworkRequest(url)); - NewClosure(reply, SIGNAL(finished()), this, SLOT(CalendarRequestFinished(QNetworkReply*, int)), reply, id); + NewClosure(reply, SIGNAL(finished()), this, + SLOT(CalendarRequestFinished(QNetworkReply*, int)), reply, id); } void SongkickConcerts::CalendarRequestFinished(QNetworkReply* reply, int id) { @@ -123,7 +130,7 @@ void SongkickConcerts::CalendarRequestFinished(QNetworkReply* reply, int id) { QWidget* container = new QWidget; QVBoxLayout* layout = new QVBoxLayout(container); - foreach (const QVariant& v, events) { + foreach(const QVariant & v, events) { QVariantMap event = v.toMap(); QString display_name = event["displayName"].toString(); QString start_date = event["start"].toMap()["date"].toString(); @@ -132,20 +139,17 @@ void SongkickConcerts::CalendarRequestFinished(QNetworkReply* reply, int id) { // Try to get the lat/lng coordinates of the venue. QVariantMap venue = event["venue"].toMap(); - const bool valid_latlng = - venue["lng"].isValid() && venue["lat"].isValid(); + const bool valid_latlng = venue["lng"].isValid() && venue["lat"].isValid(); if (valid_latlng && latlng_.IsValid()) { static const int kFilterDistanceMetres = 250 * 1e3; // 250km - Geolocator::LatLng latlng( - venue["lat"].toString(), venue["lng"].toString()); + Geolocator::LatLng latlng(venue["lat"].toString(), + venue["lng"].toString()); if (latlng_.IsValid() && latlng.IsValid()) { int distance_metres = latlng_.Distance(latlng); if (distance_metres > kFilterDistanceMetres) { - qLog(Debug) << "Filtered concert:" - << display_name - << "as too far away:" - << distance_metres; + qLog(Debug) << "Filtered concert:" << display_name + << "as too far away:" << distance_metres; continue; } } diff --git a/src/songinfo/songkickconcertwidget.cpp b/src/songinfo/songkickconcertwidget.cpp index c18fe70f3..691f9fb02 100644 --- a/src/songinfo/songkickconcertwidget.cpp +++ b/src/songinfo/songkickconcertwidget.cpp @@ -32,12 +32,10 @@ const int SongKickConcertWidget::kStaticMapWidth = 100; const int SongKickConcertWidget::kStaticMapHeight = 100; - SongKickConcertWidget::SongKickConcertWidget(QWidget* parent) - : QWidget(parent), - ui_(new Ui_SongKickConcertWidget), - network_(new NetworkAccessManager(this)) -{ + : QWidget(parent), + ui_(new Ui_SongKickConcertWidget), + network_(new NetworkAccessManager(this)) { ui_->setupUi(this); // Hide the map by default @@ -48,9 +46,7 @@ SongKickConcertWidget::SongKickConcertWidget(QWidget* parent) ReloadSettings(); } -SongKickConcertWidget::~SongKickConcertWidget() { - delete ui_; -} +SongKickConcertWidget::~SongKickConcertWidget() { delete ui_; } void SongKickConcertWidget::ReloadSettings() { QFont font(SongInfoTextView::Font()); @@ -61,9 +57,8 @@ void SongKickConcertWidget::ReloadSettings() { void SongKickConcertWidget::Init(const QString& title, const QString& url, const QString& date, const QString& location) { - ui_->title->setText(QString("%2").arg( - Qt::escape(url), - Qt::escape(title))); + ui_->title->setText( + QString("%2").arg(Qt::escape(url), Qt::escape(title))); if (!location.isEmpty()) { ui_->location->setText(location); @@ -107,13 +102,11 @@ void SongKickConcertWidget::SetMap(const QString& lat, const QString& lng, } // Request the static map image - const QUrl url(QString(kStaticMapUrl).arg( - QString::number(kStaticMapWidth), - QString::number(kStaticMapHeight), - lat, lng)); + const QUrl url(QString(kStaticMapUrl).arg(QString::number(kStaticMapWidth), + QString::number(kStaticMapHeight), + lat, lng)); QNetworkReply* reply = network_->get(QNetworkRequest(url)); - NewClosure(reply, SIGNAL(finished()), - this, SLOT(MapLoaded(QNetworkReply*)), + NewClosure(reply, SIGNAL(finished()), this, SLOT(MapLoaded(QNetworkReply*)), reply); } diff --git a/src/songinfo/songkickconcertwidget.h b/src/songinfo/songkickconcertwidget.h index faf05b979..fdd2f73ca 100644 --- a/src/songinfo/songkickconcertwidget.h +++ b/src/songinfo/songkickconcertwidget.h @@ -28,33 +28,33 @@ class QNetworkReply; class SongKickConcertWidget : public QWidget { Q_OBJECT - -public: + + public: SongKickConcertWidget(QWidget* parent = 0); ~SongKickConcertWidget(); static const int kStaticMapWidth; static const int kStaticMapHeight; - void Init(const QString& title, const QString& url, - const QString& date, const QString& location); + void Init(const QString& title, const QString& url, const QString& date, + const QString& location); void SetMap(const QString& lat, const QString& lng, const QString& venue_name); // QObject bool eventFilter(QObject* object, QEvent* event); -public slots: + public slots: void ReloadSettings(); -private slots: + private slots: void MapLoaded(QNetworkReply* reply); - -private: + + private: Ui_SongKickConcertWidget* ui_; QNetworkAccessManager* network_; QUrl map_url_; }; -#endif // SONGKICKCONCERTWIDGET_H +#endif // SONGKICKCONCERTWIDGET_H diff --git a/src/songinfo/songplaystats.cpp b/src/songinfo/songplaystats.cpp index 254590354..48a23aff2 100644 --- a/src/songinfo/songplaystats.cpp +++ b/src/songinfo/songplaystats.cpp @@ -25,9 +25,7 @@ const int SongPlayStats::kLineSpacing = 2; const int SongPlayStats::kIconTextSpacing = 6; const int SongPlayStats::kMargin = 4; -SongPlayStats::SongPlayStats(QWidget* parent) - : QWidget(parent) -{ +SongPlayStats::SongPlayStats(QWidget* parent) : QWidget(parent) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); } @@ -38,21 +36,21 @@ void SongPlayStats::AddItem(const QIcon& icon, const QString& text) { } QSize SongPlayStats::sizeHint() const { - return QSize(100, kMargin * 2 + - items_.count() * kIconSize + - (items_.count() - 1) * kLineSpacing); + return QSize(100, kMargin * 2 + items_.count() * kIconSize + + (items_.count() - 1) * kLineSpacing); } void SongPlayStats::paintEvent(QPaintEvent*) { QPainter p(this); int y = kMargin; - foreach (const Item& item, items_) { - const QRect line(kMargin, y, width() - kMargin*2, kIconSize); + foreach(const Item & item, items_) { + const QRect line(kMargin, y, width() - kMargin * 2, kIconSize); const QRect icon_rect(line.topLeft(), QSize(kIconSize, kIconSize)); - const QRect text_rect(icon_rect.topRight() + QPoint(kIconTextSpacing, 0), - QSize(line.width() - icon_rect.width() - kIconTextSpacing, - line.height())); + const QRect text_rect( + icon_rect.topRight() + QPoint(kIconTextSpacing, 0), + QSize(line.width() - icon_rect.width() - kIconTextSpacing, + line.height())); p.drawPixmap(icon_rect, item.icon_.pixmap(kIconSize)); p.drawText(text_rect, item.text_); diff --git a/src/songinfo/songplaystats.h b/src/songinfo/songplaystats.h index 3283f636b..c57fd6ee9 100644 --- a/src/songinfo/songplaystats.h +++ b/src/songinfo/songplaystats.h @@ -24,7 +24,7 @@ class SongPlayStats : public QWidget { Q_OBJECT -public: + public: SongPlayStats(QWidget* parent = 0); static const int kIconSize; @@ -36,10 +36,10 @@ public: QSize sizeHint() const; -protected: + protected: void paintEvent(QPaintEvent*); -private: + private: struct Item { Item(const QIcon& icon, const QString& text) : icon_(icon), text_(text) {} QIcon icon_; @@ -49,4 +49,4 @@ private: QList items_; }; -#endif // SONGPLAYSTATS_H +#endif // SONGPLAYSTATS_H diff --git a/src/songinfo/tagwidget.cpp b/src/songinfo/tagwidget.cpp index b99c3a209..828306291 100644 --- a/src/songinfo/tagwidget.cpp +++ b/src/songinfo/tagwidget.cpp @@ -34,13 +34,13 @@ const int TagWidgetTag::kIconTextSpacing = 8; const int TagWidgetTag::kHPadding = 6; const int TagWidgetTag::kVPadding = 2; -TagWidgetTag::TagWidgetTag(const QIcon& icon, const QString& text, QWidget* parent) - : QWidget(parent), - text_(text), - icon_(icon), - opacity_(0.0), - animation_(new QPropertyAnimation(this, "background_opacity", this)) -{ +TagWidgetTag::TagWidgetTag(const QIcon& icon, const QString& text, + QWidget* parent) + : QWidget(parent), + text_(text), + icon_(icon), + opacity_(0.0), + animation_(new QPropertyAnimation(this, "background_opacity", this)) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } @@ -77,9 +77,10 @@ void TagWidgetTag::paintEvent(QPaintEvent*) { const QRect tag_rect(rect()); const QRect icon_rect(tag_rect.topLeft() + QPoint(kHPadding, kVPadding), QSize(kIconSize, kIconSize)); - const QRect text_rect(icon_rect.topRight() + QPoint(kIconTextSpacing, 0), - QSize(tag_rect.width() - icon_rect.right() - kIconTextSpacing - kHPadding, - icon_rect.height())); + const QRect text_rect( + icon_rect.topRight() + QPoint(kIconTextSpacing, 0), + QSize(tag_rect.width() - icon_rect.right() - kIconTextSpacing - kHPadding, + icon_rect.height())); // Use the tag's opacity p.setOpacity(0.3 + opacity_ * 0.7); @@ -102,25 +103,17 @@ void TagWidgetTag::paintEvent(QPaintEvent*) { p.drawText(text_rect, text_); } -void TagWidgetTag::mouseReleaseEvent(QMouseEvent*) { - emit Clicked(); -} - -void TagWidgetTag::contextMenuEvent(QContextMenuEvent*) { - emit Clicked(); -} +void TagWidgetTag::mouseReleaseEvent(QMouseEvent*) { emit Clicked(); } +void TagWidgetTag::contextMenuEvent(QContextMenuEvent*) { emit Clicked(); } TagWidget::TagWidget(Type type, QWidget* parent) - : QWidget(parent), - type_(type) -{ + : QWidget(parent), type_(type) { setLayout(new FlowLayout(4, 6, 4)); } void TagWidget::AddTag(const QString& tag) { - if (tag.isEmpty()) - return; + if (tag.isEmpty()) return; TagWidgetTag* widget = new TagWidgetTag(icon_, tag, this); connect(widget, SIGNAL(Clicked()), SLOT(TagClicked())); @@ -131,8 +124,7 @@ void TagWidget::AddTag(const QString& tag) { void TagWidget::TagClicked() { TagWidgetTag* tag = qobject_cast(sender()); - if (!tag) - return; + if (!tag) return; emit DoGlobalSearch(tag->text()); } diff --git a/src/songinfo/tagwidget.h b/src/songinfo/tagwidget.h index 63e1ee85d..81cb4b458 100644 --- a/src/songinfo/tagwidget.h +++ b/src/songinfo/tagwidget.h @@ -29,11 +29,10 @@ class QPropertyAnimation; class TagWidgetTag : public QWidget { Q_OBJECT - Q_PROPERTY(float background_opacity - READ background_opacity - WRITE set_background_opacity); + Q_PROPERTY(float background_opacity READ background_opacity WRITE + set_background_opacity); -public: + public: TagWidgetTag(const QIcon& icon, const QString& text, QWidget* parent); static const int kIconSize; @@ -50,14 +49,14 @@ public: signals: void Clicked(); -protected: + protected: void enterEvent(QEvent*); void leaveEvent(QEvent*); void paintEvent(QPaintEvent*); void mouseReleaseEvent(QMouseEvent*); void contextMenuEvent(QContextMenuEvent*); -private: + private: QString text_; QIcon icon_; float opacity_; @@ -68,11 +67,8 @@ private: class TagWidget : public QWidget { Q_OBJECT -public: - enum Type { - Type_Tags, - Type_Artists, - }; + public: + enum Type { Type_Tags, Type_Artists, }; TagWidget(Type type, QWidget* parent = 0); @@ -85,16 +81,16 @@ signals: void AddToPlaylist(QMimeData* data); void DoGlobalSearch(const QString& query); -private slots: + private slots: void TagClicked(); -private: + private: void PlayLastFm(const QString& url_pattern); -private: + private: Type type_; QIcon icon_; QList tags_; }; -#endif // TAGWIDGET_H +#endif // TAGWIDGET_H diff --git a/src/songinfo/ultimatelyricslyric.cpp b/src/songinfo/ultimatelyricslyric.cpp index 6c226032b..8f8575868 100644 --- a/src/songinfo/ultimatelyricslyric.cpp +++ b/src/songinfo/ultimatelyricslyric.cpp @@ -19,9 +19,8 @@ #include -UltimateLyricsLyric::UltimateLyricsLyric(QObject* parent) : - QTextDocument(parent) { -} +UltimateLyricsLyric::UltimateLyricsLyric(QObject* parent) + : QTextDocument(parent) {} void UltimateLyricsLyric::SetHtml(const QString& html) { QString copy(html.trimmed()); @@ -31,7 +30,8 @@ void UltimateLyricsLyric::SetHtml(const QString& html) { copy.replace(QRegExp("([^>])[\\t ]*\\n"), "\\1

"); // Strip any newlines from the end - copy.replace(QRegExp("((<\\s*br\\s*/?\\s*>)|(<\\s*/?\\s*p\\s*/?\\s*>))+$"), ""); + copy.replace(QRegExp("((<\\s*br\\s*/?\\s*>)|(<\\s*/?\\s*p\\s*/?\\s*>))+$"), + ""); setHtml(copy); } diff --git a/src/songinfo/ultimatelyricslyric.h b/src/songinfo/ultimatelyricslyric.h index 7e27ad69c..bca5a9d79 100644 --- a/src/songinfo/ultimatelyricslyric.h +++ b/src/songinfo/ultimatelyricslyric.h @@ -24,10 +24,10 @@ class UltimateLyricsLyric : public QTextDocument { Q_OBJECT -public: + public: UltimateLyricsLyric(QObject* parent = 0); void SetHtml(const QString& html); }; -#endif // ULTIMATELYRICSLYRIC_H +#endif // ULTIMATELYRICSLYRIC_H diff --git a/src/songinfo/ultimatelyricsprovider.cpp b/src/songinfo/ultimatelyricsprovider.cpp index 98f798b99..0238df0f8 100644 --- a/src/songinfo/ultimatelyricsprovider.cpp +++ b/src/songinfo/ultimatelyricsprovider.cpp @@ -28,18 +28,16 @@ const int UltimateLyricsProvider::kRedirectLimit = 5; - UltimateLyricsProvider::UltimateLyricsProvider() - : network_(new NetworkAccessManager(this)), - relevance_(0), - redirect_count_(0), - url_hop_(false) -{ -} + : network_(new NetworkAccessManager(this)), + relevance_(0), + redirect_count_(0), + url_hop_(false) {} void UltimateLyricsProvider::FetchInfo(int id, const Song& metadata) { // Get the text codec - const QTextCodec* codec = QTextCodec::codecForName(charset_.toAscii().constData()); + const QTextCodec* codec = + QTextCodec::codecForName(charset_.toAscii().constData()); if (!codec) { qLog(Warning) << "Invalid codec" << charset_; emit Finished(id); @@ -78,7 +76,8 @@ void UltimateLyricsProvider::LyricsFetched() { } // Handle redirects - QVariant redirect_target = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); + QVariant redirect_target = + reply->attribute(QNetworkRequest::RedirectionTargetAttribute); if (redirect_target.isValid()) { if (redirect_count_ >= kRedirectLimit) { url_hop_ = false; @@ -93,19 +92,20 @@ void UltimateLyricsProvider::LyricsFetched() { target.setPath(path); } - redirect_count_ ++; + redirect_count_++; QNetworkReply* reply = network_->get(QNetworkRequest(target)); requests_[reply] = id; connect(reply, SIGNAL(finished()), SLOT(LyricsFetched())); return; } - const QTextCodec* codec = QTextCodec::codecForName(charset_.toAscii().constData()); + const QTextCodec* codec = + QTextCodec::codecForName(charset_.toAscii().constData()); const QString original_content = codec->toUnicode(reply->readAll()); QString lyrics; // Check for invalid indicators - foreach (const QString& indicator, invalid_indicators_) { + foreach(const QString & indicator, invalid_indicators_) { if (original_content.contains(indicator)) { qLog(Debug) << "Found invalid indicator" << indicator; url_hop_ = false; @@ -116,10 +116,10 @@ void UltimateLyricsProvider::LyricsFetched() { if (!url_hop_) { // Apply extract rules - foreach (const Rule& rule, extract_rules_) { + foreach(const Rule & rule, extract_rules_) { // Modify the rule for this request's metadata Rule rule_copy(rule); - for (Rule::iterator it = rule_copy.begin() ; it != rule_copy.end() ; ++it) { + for (Rule::iterator it = rule_copy.begin(); it != rule_copy.end(); ++it) { ReplaceFields(metadata_, &it->first); } @@ -135,7 +135,7 @@ void UltimateLyricsProvider::LyricsFetched() { } // Apply exclude rules - foreach (const Rule& rule, exclude_rules_) { + foreach(const Rule & rule, exclude_rules_) { ApplyExcludeRule(rule, &content); } @@ -171,14 +171,15 @@ void UltimateLyricsProvider::LyricsFetched() { emit Finished(id); } -bool UltimateLyricsProvider::ApplyExtractRule(const Rule& rule, QString* content) const { - foreach (const RuleItem& item, rule) { +bool UltimateLyricsProvider::ApplyExtractRule(const Rule& rule, + QString* content) const { + foreach(const RuleItem & item, rule) { if (item.second.isNull()) { if (item.first.startsWith("http://") && item.second.isNull()) { *content = ExtractUrl(*content, rule); return true; } else { - *content = ExtractXmlTag(*content, item.first); + *content = ExtractXmlTag(*content, item.first); } } else { *content = Extract(*content, item.first, item.second); @@ -187,15 +188,16 @@ bool UltimateLyricsProvider::ApplyExtractRule(const Rule& rule, QString* content return false; } -QString UltimateLyricsProvider::ExtractUrl(const QString& source, const Rule& rule) { +QString UltimateLyricsProvider::ExtractUrl(const QString& source, + const Rule& rule) { QString url; QString id; - foreach(const RuleItem& item, rule) { + foreach(const RuleItem & item, rule) { if (item.first.startsWith("http://") && item.second.isNull()) url = item.first; else - id = Extract(source, item.first,item.second); + id = Extract(source, item.first, item.second); } url.replace("{id}", id); @@ -203,29 +205,30 @@ QString UltimateLyricsProvider::ExtractUrl(const QString& source, const Rule& ru return url; } -QString UltimateLyricsProvider::ExtractXmlTag(const QString& source, const QString& tag) { - QRegExp re("<(\\w+).*>"); // ಠ_ಠ - if (re.indexIn(tag) == -1) - return QString(); +QString UltimateLyricsProvider::ExtractXmlTag(const QString& source, + const QString& tag) { + QRegExp re("<(\\w+).*>"); // ಠ_ಠ + if (re.indexIn(tag) == -1) return QString(); return Extract(source, tag, ""); } -QString UltimateLyricsProvider::Extract(const QString& source, const QString& begin, const QString& end) { +QString UltimateLyricsProvider::Extract(const QString& source, + const QString& begin, + const QString& end) { int begin_idx = source.indexOf(begin); - if (begin_idx == -1) - return QString(); + if (begin_idx == -1) return QString(); begin_idx += begin.length(); int end_idx = source.indexOf(end, begin_idx); - if (end_idx == -1) - return QString(); + if (end_idx == -1) return QString(); return source.mid(begin_idx, end_idx - begin_idx - 1); } -void UltimateLyricsProvider::ApplyExcludeRule(const Rule& rule, QString* content) const { - foreach (const RuleItem& item, rule) { +void UltimateLyricsProvider::ApplyExcludeRule(const Rule& rule, + QString* content) const { + foreach(const RuleItem & item, rule) { if (item.second.isNull()) { *content = ExcludeXmlTag(*content, item.first); } else { @@ -234,40 +237,39 @@ void UltimateLyricsProvider::ApplyExcludeRule(const Rule& rule, QString* content } } -QString UltimateLyricsProvider::ExcludeXmlTag(const QString& source, const QString& tag) { - QRegExp re("<(\\w+).*>"); // ಠ_ಠ - if (re.indexIn(tag) == -1) - return source; +QString UltimateLyricsProvider::ExcludeXmlTag(const QString& source, + const QString& tag) { + QRegExp re("<(\\w+).*>"); // ಠ_ಠ + if (re.indexIn(tag) == -1) return source; return Exclude(source, tag, ""); } -QString UltimateLyricsProvider::Exclude(const QString& source, const QString& begin, const QString& end) { +QString UltimateLyricsProvider::Exclude(const QString& source, + const QString& begin, + const QString& end) { int begin_idx = source.indexOf(begin); - if (begin_idx == -1) - return source; + if (begin_idx == -1) return source; int end_idx = source.indexOf(end, begin_idx + begin.length()); - if (end_idx == -1) - return source; + if (end_idx == -1) return source; - return source.left(begin_idx) + source.right(source.length() - end_idx - end.length()); + return source.left(begin_idx) + + source.right(source.length() - end_idx - end.length()); } QString UltimateLyricsProvider::FirstChar(const QString& text) { - if (text.isEmpty()) - return QString(); + if (text.isEmpty()) return QString(); return text[0].toLower(); } QString UltimateLyricsProvider::TitleCase(const QString& text) { - if (text.length() == 0) - return QString(); + if (text.length() == 0) return QString(); QString ret = text; bool last_was_space = true; - for (QString::iterator it = ret.begin() ; it != ret.end() ; ++it) { + for (QString::iterator it = ret.begin(); it != ret.end(); ++it) { if (last_was_space) { *it = it->toUpper(); last_was_space = false; @@ -275,18 +277,18 @@ QString UltimateLyricsProvider::TitleCase(const QString& text) { last_was_space = true; } } - + return ret; } -void UltimateLyricsProvider::ReplaceField(const QString& tag, const QString& value, +void UltimateLyricsProvider::ReplaceField(const QString& tag, + const QString& value, QString* text) const { - if (!text->contains(tag)) - return; + if (!text->contains(tag)) return; // Apply URL character replacement QString value_copy(value); - foreach (const UrlFormat& format, url_formats_) { + foreach(const UrlFormat & format, url_formats_) { QRegExp re("[" + QRegExp::escape(format.first) + "]"); value_copy.replace(re, format.second); } @@ -294,20 +296,21 @@ void UltimateLyricsProvider::ReplaceField(const QString& tag, const QString& val text->replace(tag, value_copy, Qt::CaseInsensitive); } -void UltimateLyricsProvider::ReplaceFields(const Song& metadata, QString* text) const { - ReplaceField("{artist}", metadata.artist().toLower(), text); - ReplaceField("{artist2}",NoSpace(metadata.artist().toLower()), text); - ReplaceField("{album}", metadata.album().toLower(), text); - ReplaceField("{album2}", NoSpace(metadata.album().toLower()), text); - ReplaceField("{title}", metadata.title().toLower(), text); - ReplaceField("{Artist}", metadata.artist(), text); - ReplaceField("{Album}", metadata.album(), text); - ReplaceField("{ARTIST}", metadata.artist().toUpper(), text); - ReplaceField("{year}", metadata.PrettyYear(), text); - ReplaceField("{Title}", metadata.title(), text); - ReplaceField("{Title2}", TitleCase(metadata.title()), text); - ReplaceField("{a}", FirstChar(metadata.artist()), text); - ReplaceField("{track}", QString::number(metadata.track()), text); +void UltimateLyricsProvider::ReplaceFields(const Song& metadata, + QString* text) const { + ReplaceField("{artist}", metadata.artist().toLower(), text); + ReplaceField("{artist2}", NoSpace(metadata.artist().toLower()), text); + ReplaceField("{album}", metadata.album().toLower(), text); + ReplaceField("{album2}", NoSpace(metadata.album().toLower()), text); + ReplaceField("{title}", metadata.title().toLower(), text); + ReplaceField("{Artist}", metadata.artist(), text); + ReplaceField("{Album}", metadata.album(), text); + ReplaceField("{ARTIST}", metadata.artist().toUpper(), text); + ReplaceField("{year}", metadata.PrettyYear(), text); + ReplaceField("{Title}", metadata.title(), text); + ReplaceField("{Title2}", TitleCase(metadata.title()), text); + ReplaceField("{a}", FirstChar(metadata.artist()), text); + ReplaceField("{track}", QString::number(metadata.track()), text); } QString UltimateLyricsProvider::NoSpace(const QString& text) { @@ -320,7 +323,7 @@ QString UltimateLyricsProvider::NoSpace(const QString& text) { // TODO: handle special characters (e.g. ® á) bool UltimateLyricsProvider::HTMLHasAlphaNumeric(const QString& html) { bool in_tag = false; - foreach (const QChar& c, html) { + foreach(const QChar & c, html) { if (!in_tag and c.isLetterOrNumber()) return true; else if (c == QChar('<')) diff --git a/src/songinfo/ultimatelyricsprovider.h b/src/songinfo/ultimatelyricsprovider.h index 1e047b8f1..96f2ef4db 100644 --- a/src/songinfo/ultimatelyricsprovider.h +++ b/src/songinfo/ultimatelyricsprovider.h @@ -31,7 +31,7 @@ class QNetworkReply; class UltimateLyricsProvider : public SongInfoProvider { Q_OBJECT -public: + public: UltimateLyricsProvider(); static const int kRedirectLimit; @@ -47,38 +47,44 @@ public: void set_relevance(int relevance) { relevance_ = relevance; } void add_url_format(const QString& replace, const QString& with) { - url_formats_ << UrlFormat(replace, with); } + url_formats_ << UrlFormat(replace, with); + } void add_extract_rule(const Rule& rule) { extract_rules_ << rule; } void add_exclude_rule(const Rule& rule) { exclude_rules_ << rule; } - void add_invalid_indicator(const QString& indicator) { invalid_indicators_ << indicator; } + void add_invalid_indicator(const QString& indicator) { + invalid_indicators_ << indicator; + } QString name() const { return name_; } int relevance() const { return relevance_; } void FetchInfo(int id, const Song& metadata); -private slots: + private slots: void LyricsFetched(); -private: + private: bool ApplyExtractRule(const Rule& rule, QString* content) const; void ApplyExcludeRule(const Rule& rule, QString* content) const; static QString ExtractUrl(const QString& source, const Rule& rule); static QString ExtractXmlTag(const QString& source, const QString& tag); - static QString Extract(const QString& source, const QString& begin, const QString& end); + static QString Extract(const QString& source, const QString& begin, + const QString& end); static QString ExcludeXmlTag(const QString& source, const QString& tag); - static QString Exclude(const QString& source, const QString& begin, const QString& end); + static QString Exclude(const QString& source, const QString& begin, + const QString& end); static QString FirstChar(const QString& text); static QString TitleCase(const QString& text); static QString NoSpace(const QString& text); static bool HTMLHasAlphaNumeric(const QString& html); - void ReplaceField(const QString& tag, const QString& value, QString* text) const; + void ReplaceField(const QString& tag, const QString& value, + QString* text) const; void ReplaceFields(const Song& metadata, QString* text) const; -private: + private: NetworkAccessManager* network_; QMap requests_; @@ -98,4 +104,4 @@ private: bool url_hop_; }; -#endif // ULTIMATELYRICSPROVIDER_H +#endif // ULTIMATELYRICSPROVIDER_H diff --git a/src/songinfo/ultimatelyricsreader.cpp b/src/songinfo/ultimatelyricsreader.cpp index 91850adda..c7ca0612b 100644 --- a/src/songinfo/ultimatelyricsreader.cpp +++ b/src/songinfo/ultimatelyricsreader.cpp @@ -24,16 +24,12 @@ #include UltimateLyricsReader::UltimateLyricsReader(QObject* parent) - : QObject(parent), - thread_(qApp->thread()) -{ -} + : QObject(parent), thread_(qApp->thread()) {} -void UltimateLyricsReader::SetThread(QThread *thread) { - thread_ = thread; -} +void UltimateLyricsReader::SetThread(QThread* thread) { thread_ = thread; } -QList UltimateLyricsReader::Parse(const QString& filename) const { +QList UltimateLyricsReader::Parse(const QString& filename) + const { QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { qLog(Warning) << "Error opening" << filename; @@ -43,7 +39,8 @@ QList UltimateLyricsReader::Parse(const QString& filename) co return ParseDevice(&file); } -QList UltimateLyricsReader::ParseDevice(QIODevice* device) const { +QList UltimateLyricsReader::ParseDevice(QIODevice* device) + const { QList ret; QXmlStreamReader reader(device); @@ -62,7 +59,8 @@ QList UltimateLyricsReader::ParseDevice(QIODevice* device) co return ret; } -SongInfoProvider* UltimateLyricsReader::ParseProvider(QXmlStreamReader* reader) const { +SongInfoProvider* UltimateLyricsReader::ParseProvider(QXmlStreamReader* reader) + const { QXmlStreamAttributes attributes = reader->attributes(); UltimateLyricsProvider* scraper = new UltimateLyricsProvider; @@ -74,8 +72,7 @@ SongInfoProvider* UltimateLyricsReader::ParseProvider(QXmlStreamReader* reader) while (!reader->atEnd()) { reader->readNext(); - if (reader->tokenType() == QXmlStreamReader::EndElement) - break; + if (reader->tokenType() == QXmlStreamReader::EndElement) break; if (reader->tokenType() == QXmlStreamReader::StartElement) { if (reader->name() == "extract") @@ -85,36 +82,39 @@ SongInfoProvider* UltimateLyricsReader::ParseProvider(QXmlStreamReader* reader) else if (reader->name() == "invalidIndicator") scraper->add_invalid_indicator(ParseInvalidIndicator(reader)); else if (reader->name() == "urlFormat") { - scraper->add_url_format(reader->attributes().value("replace").toString(), - reader->attributes().value("with").toString()); + scraper->add_url_format( + reader->attributes().value("replace").toString(), + reader->attributes().value("with").toString()); reader->skipCurrentElement(); - } - else + } else reader->skipCurrentElement(); } } return scraper; } -UltimateLyricsProvider::Rule UltimateLyricsReader::ParseRule(QXmlStreamReader* reader) const { +UltimateLyricsProvider::Rule UltimateLyricsReader::ParseRule( + QXmlStreamReader* reader) const { UltimateLyricsProvider::Rule ret; while (!reader->atEnd()) { reader->readNext(); - if (reader->tokenType() == QXmlStreamReader::EndElement) - break; + if (reader->tokenType() == QXmlStreamReader::EndElement) break; if (reader->tokenType() == QXmlStreamReader::StartElement) { if (reader->name() == "item") { QXmlStreamAttributes attr = reader->attributes(); if (attr.hasAttribute("tag")) - ret << UltimateLyricsProvider::RuleItem(attr.value("tag").toString(), QString()); + ret << UltimateLyricsProvider::RuleItem(attr.value("tag").toString(), + QString()); else if (attr.hasAttribute("url")) - ret << UltimateLyricsProvider::RuleItem(attr.value("url").toString(), QString()); + ret << UltimateLyricsProvider::RuleItem(attr.value("url").toString(), + QString()); else if (attr.hasAttribute("begin")) - ret << UltimateLyricsProvider::RuleItem(attr.value("begin").toString(), - attr.value("end").toString()); + ret << UltimateLyricsProvider::RuleItem( + attr.value("begin").toString(), + attr.value("end").toString()); } reader->skipCurrentElement(); } @@ -122,9 +122,9 @@ UltimateLyricsProvider::Rule UltimateLyricsReader::ParseRule(QXmlStreamReader* r return ret; } -QString UltimateLyricsReader::ParseInvalidIndicator(QXmlStreamReader* reader) const { +QString UltimateLyricsReader::ParseInvalidIndicator(QXmlStreamReader* reader) + const { QString ret = reader->attributes().value("value").toString(); reader->skipCurrentElement(); return ret; } - diff --git a/src/songinfo/ultimatelyricsreader.h b/src/songinfo/ultimatelyricsreader.h index 7cbe99106..2bfb474e7 100644 --- a/src/songinfo/ultimatelyricsreader.h +++ b/src/songinfo/ultimatelyricsreader.h @@ -29,7 +29,7 @@ class QThread; class UltimateLyricsReader : public QObject { Q_OBJECT -public: + public: UltimateLyricsReader(QObject* parent = 0); QList Parse(const QString& filename) const; @@ -37,7 +37,7 @@ public: void SetThread(QThread* thread); -private: + private: SongInfoProvider* ParseProvider(QXmlStreamReader* reader) const; UltimateLyricsProvider::Rule ParseRule(QXmlStreamReader* reader) const; QString ParseInvalidIndicator(QXmlStreamReader* reader) const; @@ -45,4 +45,4 @@ private: QThread* thread_; }; -#endif // ULTIMATELYRICSREADER_H +#endif // ULTIMATELYRICSREADER_H diff --git a/src/transcoder/transcodedialog.cpp b/src/transcoder/transcodedialog.cpp index fc1cb2edd..1836455db 100644 --- a/src/transcoder/transcodedialog.cpp +++ b/src/transcoder/transcodedialog.cpp @@ -31,7 +31,7 @@ // winspool.h defines this :( #ifdef AddJob -# undef AddJob +#undef AddJob #endif const char* TranscodeDialog::kSettingsGroup = "Transcoder"; @@ -43,29 +43,27 @@ static bool ComparePresetsByName(const TranscoderPreset& left, return left.name_ < right.name_; } - -TranscodeDialog::TranscodeDialog(QWidget *parent) - : QDialog(parent), - ui_(new Ui_TranscodeDialog), - log_ui_(new Ui_TranscodeLogDialog), - log_dialog_(new QDialog(this)), - transcoder_(new Transcoder(this)), - queued_(0), - finished_success_(0), - finished_failed_(0) -{ +TranscodeDialog::TranscodeDialog(QWidget* parent) + : QDialog(parent), + ui_(new Ui_TranscodeDialog), + log_ui_(new Ui_TranscodeLogDialog), + log_dialog_(new QDialog(this)), + transcoder_(new Transcoder(this)), + queued_(0), + finished_success_(0), + finished_failed_(0) { ui_->setupUi(this); ui_->files->header()->setResizeMode(QHeaderView::ResizeToContents); log_ui_->setupUi(log_dialog_); QPushButton* clear_button = log_ui_->buttonBox->addButton(tr("Clear"), QDialogButtonBox::ResetRole); - connect(clear_button, SIGNAL(clicked()),log_ui_->log, SLOT(clear())); + connect(clear_button, SIGNAL(clicked()), log_ui_->log, SLOT(clear())); // Get presets QList presets = Transcoder::GetAllPresets(); qSort(presets.begin(), presets.end(), ComparePresetsByName); - foreach (const TranscoderPreset& preset, presets) { + foreach(const TranscoderPreset & preset, presets) { ui_->format->addItem( QString("%1 (.%2)").arg(preset.name_, preset.extension_), QVariant::fromValue(preset)); @@ -77,7 +75,7 @@ TranscodeDialog::TranscodeDialog(QWidget *parent) last_add_dir_ = s.value("last_add_dir", QDir::homePath()).toString(); QString last_output_format = s.value("last_output_format", "ogg").toString(); - for (int i=0 ; iformat->count() ; ++i) { + for (int i = 0; i < ui_->format->count(); ++i) { if (last_output_format == ui_->format->itemData(i).value().extension_) { ui_->format->setCurrentIndex(i); @@ -86,8 +84,8 @@ TranscodeDialog::TranscodeDialog(QWidget *parent) } // Add a start button - start_button_ = ui_->button_box->addButton( - tr("Start transcoding"), QDialogButtonBox::ActionRole); + start_button_ = ui_->button_box->addButton(tr("Start transcoding"), + QDialogButtonBox::ActionRole); cancel_button_ = ui_->button_box->button(QDialogButtonBox::Cancel); close_button_ = ui_->button_box->button(QDialogButtonBox::Close); @@ -107,8 +105,8 @@ TranscodeDialog::TranscodeDialog(QWidget *parent) connect(ui_->options, SIGNAL(clicked()), SLOT(Options())); connect(ui_->select, SIGNAL(clicked()), SLOT(AddDestination())); - - connect(transcoder_, SIGNAL(JobComplete(QString,bool)), SLOT(JobComplete(QString,bool))); + connect(transcoder_, SIGNAL(JobComplete(QString, bool)), + SLOT(JobComplete(QString, bool))); connect(transcoder_, SIGNAL(LogLine(QString)), SLOT(LogLine(QString))); connect(transcoder_, SIGNAL(AllJobsComplete()), SLOT(AllJobsComplete())); } @@ -136,11 +134,11 @@ void TranscodeDialog::Start() { SetWorking(true); QAbstractItemModel* file_model = ui_->files->model(); - TranscoderPreset preset = ui_->format->itemData( - ui_->format->currentIndex()).value(); + TranscoderPreset preset = ui_->format->itemData(ui_->format->currentIndex()) + .value(); // Add jobs to the transcoder - for (int i=0 ; irowCount() ; ++i) { + for (int i = 0; i < file_model->rowCount(); ++i) { QString filename = file_model->index(i, 0).data(Qt::UserRole).toString(); QString outfilename = GetOutputFileName(filename, preset); transcoder_->AddJob(filename, preset, outfilename); @@ -171,8 +169,8 @@ void TranscodeDialog::Cancel() { } void TranscodeDialog::JobComplete(const QString& filename, bool success) { - (*(success ? &finished_success_ : &finished_failed_)) ++; - queued_ --; + (*(success ? &finished_success_ : &finished_failed_))++; + queued_--; UpdateStatusText(); UpdateProgress(); @@ -182,7 +180,7 @@ void TranscodeDialog::UpdateProgress() { int progress = (finished_success_ + finished_failed_) * 100; QMap current_jobs = transcoder_->GetProgress(); - foreach (float value, current_jobs.values()) { + foreach(float value, current_jobs.values()) { progress += qBound(0, int(value * 100), 99); } @@ -193,37 +191,32 @@ void TranscodeDialog::UpdateStatusText() { QStringList sections; if (queued_) { - sections << "" + - tr("%n remaining", "", queued_) + ""; + sections << "" + tr("%n remaining", "", queued_) + + ""; } if (finished_success_) { sections << "" + - tr("%n finished", "", finished_success_) + ""; + tr("%n finished", "", finished_success_) + ""; } if (finished_failed_) { sections << "" + - tr("%n failed", "", finished_failed_) + ""; + tr("%n failed", "", finished_failed_) + ""; } ui_->progress_text->setText(sections.join(", ")); } -void TranscodeDialog::AllJobsComplete() { - SetWorking(false); -} +void TranscodeDialog::AllJobsComplete() { SetWorking(false); } void TranscodeDialog::Add() { QStringList filenames = QFileDialog::getOpenFileNames( this, tr("Add files to transcode"), last_add_dir_, - QString("%1 (%2);;%3").arg( - tr("Music"), - FileView::kFileFilter, - tr(MainWindow::kAllFilesFilterSpec))); + QString("%1 (%2);;%3").arg(tr("Music"), FileView::kFileFilter, + tr(MainWindow::kAllFilesFilterSpec))); - if (filenames.isEmpty()) - return; + if (filenames.isEmpty()) return; SetFilenames(filenames); @@ -233,22 +226,20 @@ void TranscodeDialog::Add() { s.setValue("last_add_dir", last_add_dir_); } -void TranscodeDialog::SetFilenames(const QStringList &filenames) { - foreach (const QString& filename, filenames) { +void TranscodeDialog::SetFilenames(const QStringList& filenames) { + foreach(const QString & filename, filenames) { QString name = filename.section('/', -1, -1); QString path = filename.section('/', 0, -2); - QTreeWidgetItem* item = new QTreeWidgetItem( - ui_->files, QStringList() << name << path); + QTreeWidgetItem* item = + new QTreeWidgetItem(ui_->files, QStringList() << name << path); item->setData(0, Qt::UserRole, filename); } } -void TranscodeDialog::Remove() { - qDeleteAll(ui_->files->selectedItems()); -} +void TranscodeDialog::Remove() { qDeleteAll(ui_->files->selectedItems()); } -void TranscodeDialog::LogLine(const QString &message) { +void TranscodeDialog::LogLine(const QString& message) { QString date(QDateTime::currentDateTime().toString(Qt::TextDate)); log_ui_->log->appendPlainText(QString("%1: %2").arg(date, message)); } @@ -262,8 +253,8 @@ void TranscodeDialog::timerEvent(QTimerEvent* e) { } void TranscodeDialog::Options() { - TranscoderPreset preset = ui_->format->itemData( - ui_->format->currentIndex()).value(); + TranscoderPreset preset = ui_->format->itemData(ui_->format->currentIndex()) + .value(); TranscoderOptionsDialog dialog(preset.type_, this); if (dialog.is_valid()) { @@ -274,16 +265,16 @@ void TranscodeDialog::Options() { // Adds a folder to the destination box. void TranscodeDialog::AddDestination() { int index = ui_->destination->currentIndex(); - QString initial_dir = (!ui_->destination->itemData(index).isNull() ? - ui_->destination->itemData(index).toString() : - QDir::homePath()); - QString dir = QFileDialog::getExistingDirectory( - this, tr("Add folder"), initial_dir); + QString initial_dir = (!ui_->destination->itemData(index).isNull() + ? ui_->destination->itemData(index).toString() + : QDir::homePath()); + QString dir = + QFileDialog::getExistingDirectory(this, tr("Add folder"), initial_dir); if (!dir.isEmpty()) { // Keep only a finite number of items in the box. while (ui_->destination->count() >= kMaxDestinationItems) { - ui_->destination->removeItem(1); // The oldest folder item. + ui_->destination->removeItem(1); // The oldest folder item. } QIcon icon = IconLoader::Load("folder"); @@ -304,10 +295,10 @@ QString TranscodeDialog::TrimPath(const QString& path) const { return path.section('/', -1, -1, QString::SectionSkipEmpty); } -QString TranscodeDialog::GetOutputFileName(const QString& input, - const TranscoderPreset &preset) const { - QString path = ui_->destination->itemData( - ui_->destination->currentIndex()).toString(); +QString TranscodeDialog::GetOutputFileName( + const QString& input, const TranscoderPreset& preset) const { + QString path = + ui_->destination->itemData(ui_->destination->currentIndex()).toString(); if (path.isEmpty()) { // Keep the original path. return input.section('.', 0, -2) + '.' + preset.extension_; diff --git a/src/transcoder/transcodedialog.h b/src/transcoder/transcodedialog.h index 5be060def..de422cc77 100644 --- a/src/transcoder/transcodedialog.h +++ b/src/transcoder/transcodedialog.h @@ -81,4 +81,4 @@ class TranscodeDialog : public QDialog { int finished_failed_; }; -#endif // TRANSCODEDIALOG_H +#endif // TRANSCODEDIALOG_H diff --git a/src/transcoder/transcoder.cpp b/src/transcoder/transcoder.cpp index 3750273b9..3d0be8187 100644 --- a/src/transcoder/transcoder.cpp +++ b/src/transcoder/transcoder.cpp @@ -33,37 +33,30 @@ using std::shared_ptr; int Transcoder::JobFinishedEvent::sEventType = -1; +TranscoderPreset::TranscoderPreset(Song::FileType type, const QString& name, + const QString& extension, + const QString& codec_mimetype, + const QString& muxer_mimetype) + : type_(type), + name_(name), + extension_(extension), + codec_mimetype_(codec_mimetype), + muxer_mimetype_(muxer_mimetype) {} -TranscoderPreset::TranscoderPreset( - Song::FileType type, - const QString& name, - const QString& extension, - const QString& codec_mimetype, - const QString& muxer_mimetype) - : type_(type), - name_(name), - extension_(extension), - codec_mimetype_(codec_mimetype), - muxer_mimetype_(muxer_mimetype) -{ -} - - -GstElement* Transcoder::CreateElement(const QString &factory_name, - GstElement *bin, - const QString &name) { +GstElement* Transcoder::CreateElement(const QString& factory_name, + GstElement* bin, const QString& name) { GstElement* ret = gst_element_factory_make( factory_name.toAscii().constData(), - name.isNull() ? factory_name.toAscii().constData() : name.toAscii().constData()); + name.isNull() ? factory_name.toAscii().constData() + : name.toAscii().constData()); - if (ret && bin) - gst_bin_add(GST_BIN(bin), ret); + if (ret && bin) gst_bin_add(GST_BIN(bin), ret); if (!ret) { emit LogLine( tr("Could not create the GStreamer element \"%1\" -" " make sure you have all the required GStreamer plugins installed") - .arg(factory_name)); + .arg(factory_name)); } else { SetElementProperties(factory_name, G_OBJECT(ret)); } @@ -73,9 +66,11 @@ GstElement* Transcoder::CreateElement(const QString &factory_name, struct SuitableElement { SuitableElement(const QString& name = QString(), int rank = 0) - : name_(name), rank_(rank) {} + : name_(name), rank_(rank) {} - bool operator <(const SuitableElement& other) const { return rank_ < other.rank_; } + bool operator<(const SuitableElement& other) const { + return rank_ < other.rank_; + } QString name_; int rank_; @@ -84,8 +79,7 @@ struct SuitableElement { GstElement* Transcoder::CreateElementForMimeType(const QString& element_type, const QString& mime_type, GstElement* bin) { - if (mime_type.isEmpty()) - return nullptr; + if (mime_type.isEmpty()) return nullptr; // HACK: Force ffmux_mp4 because it doesn't set any useful src caps if (mime_type == "audio/mp4") { @@ -104,18 +98,18 @@ GstElement* Transcoder::CreateElementForMimeType(const QString& element_type, GList* const features = gst_registry_get_feature_list(registry, GST_TYPE_ELEMENT_FACTORY); - for (GList* p = features ; p ; p = g_list_next(p)) { + for (GList* p = features; p; p = g_list_next(p)) { GstElementFactory* factory = GST_ELEMENT_FACTORY(p->data); // Is this the right type of plugin? if (QString(factory->details.klass).contains(element_type)) { const GList* const templates = gst_element_factory_get_static_pad_templates(factory); - for (const GList* p = templates ; p ; p = g_list_next(p)) { + for (const GList* p = templates; p; p = g_list_next(p)) { // Only interested in source pads - GstStaticPadTemplate* pad_template = reinterpret_cast(p->data); - if (pad_template->direction != GST_PAD_SRC) - continue; + GstStaticPadTemplate* pad_template = + reinterpret_cast(p->data); + if (pad_template->direction != GST_PAD_SRC) continue; // Does this pad support the mime type we want? GstCaps* caps = gst_static_pad_template_get_caps(pad_template); @@ -127,7 +121,7 @@ GstElement* Transcoder::CreateElementForMimeType(const QString& element_type, QString name = GST_PLUGIN_FEATURE_NAME(factory); if (name.startsWith("ffmux") || name.startsWith("ffenc")) - rank = -1; // ffmpeg usually sucks + rank = -1; // ffmpeg usually sucks suitable_elements_ << SuitableElement(name, rank); } @@ -140,8 +134,7 @@ GstElement* Transcoder::CreateElementForMimeType(const QString& element_type, gst_plugin_feature_list_free(features); gst_caps_unref(target_caps); - if (suitable_elements_.isEmpty()) - return nullptr; + if (suitable_elements_.isEmpty()) return nullptr; // Sort by rank qSort(suitable_elements_); @@ -151,7 +144,8 @@ GstElement* Transcoder::CreateElementForMimeType(const QString& element_type, if (best.name_ == "lamemp3enc") { // Special case: we need to add xingmux and id3v2mux to the pipeline when - // using lamemp3enc because it doesn't write the VBR or ID3v2 headers itself. + // using lamemp3enc because it doesn't write the VBR or ID3v2 headers + // itself. LogLine("Adding xingmux and id3v2mux to the pipeline"); @@ -160,8 +154,8 @@ GstElement* Transcoder::CreateElementForMimeType(const QString& element_type, gst_bin_add(GST_BIN(bin), mp3bin); // Create the elements - GstElement* lame = CreateElement("lamemp3enc", mp3bin); - GstElement* xing = CreateElement("xingmux", mp3bin); + GstElement* lame = CreateElement("lamemp3enc", mp3bin); + GstElement* xing = CreateElement("xingmux", mp3bin); GstElement* id3v2 = CreateElement("id3v2mux", mp3bin); if (!lame || !xing || !id3v2) { @@ -186,28 +180,21 @@ GstElement* Transcoder::CreateElementForMimeType(const QString& element_type, } } - -Transcoder::JobFinishedEvent::JobFinishedEvent(JobState *state, bool success) - : QEvent(QEvent::Type(sEventType)), - state_(state), - success_(success) -{ -} +Transcoder::JobFinishedEvent::JobFinishedEvent(JobState* state, bool success) + : QEvent(QEvent::Type(sEventType)), state_(state), success_(success) {} void Transcoder::JobState::PostFinished(bool success) { if (success) { - emit parent_->LogLine( - tr("Successfully written %1").arg(QDir::toNativeSeparators(job_.output))); + emit parent_->LogLine(tr("Successfully written %1") + .arg(QDir::toNativeSeparators(job_.output))); } - QCoreApplication::postEvent(parent_, new Transcoder::JobFinishedEvent(this, success)); + QCoreApplication::postEvent(parent_, + new Transcoder::JobFinishedEvent(this, success)); } - Transcoder::Transcoder(QObject* parent) - : QObject(parent), - max_threads_(QThread::idealThreadCount()) -{ + : QObject(parent), max_threads_(QThread::idealThreadCount()) { if (JobFinishedEvent::sEventType == -1) JobFinishedEvent::sEventType = QEvent::registerEventType(); @@ -216,7 +203,7 @@ Transcoder::Transcoder(QObject* parent) s.beginGroup("Transcoder/lamemp3enc"); if (s.value("target").isNull()) { - s.setValue("target", 1); // 1 == bitrate + s.setValue("target", 1); // 1 == bitrate } if (s.value("cbr").isNull()) { s.setValue("cbr", true); @@ -240,23 +227,30 @@ QList Transcoder::GetAllPresets() { TranscoderPreset Transcoder::PresetForFileType(Song::FileType type) { switch (type) { case Song::Type_Flac: - return TranscoderPreset(type, tr("Flac"), "flac", "audio/x-flac"); + return TranscoderPreset(type, tr("Flac"), "flac", "audio/x-flac"); case Song::Type_Mp4: - return TranscoderPreset(type, tr("M4A AAC"), "mp4", "audio/mpeg, mpegversion=(int)4", "audio/mp4"); + return TranscoderPreset(type, tr("M4A AAC"), "mp4", + "audio/mpeg, mpegversion=(int)4", "audio/mp4"); case Song::Type_Mpeg: - return TranscoderPreset(type, tr("MP3"), "mp3", "audio/mpeg, mpegversion=(int)1, layer=(int)3"); + return TranscoderPreset(type, tr("MP3"), "mp3", + "audio/mpeg, mpegversion=(int)1, layer=(int)3"); case Song::Type_OggVorbis: - return TranscoderPreset(type, tr("Ogg Vorbis"), "ogg", "audio/x-vorbis", "application/ogg"); + return TranscoderPreset(type, tr("Ogg Vorbis"), "ogg", "audio/x-vorbis", + "application/ogg"); case Song::Type_OggFlac: - return TranscoderPreset(type, tr("Ogg Flac"), "ogg", "audio/x-flac", "application/ogg"); + return TranscoderPreset(type, tr("Ogg Flac"), "ogg", "audio/x-flac", + "application/ogg"); case Song::Type_OggSpeex: - return TranscoderPreset(type, tr("Ogg Speex"), "spx", "audio/x-speex", "application/ogg"); + return TranscoderPreset(type, tr("Ogg Speex"), "spx", "audio/x-speex", + "application/ogg"); case Song::Type_OggOpus: - return TranscoderPreset(type, tr("Ogg Opus"), "opus", "audio/x-opus", "application/ogg"); + return TranscoderPreset(type, tr("Ogg Opus"), "opus", "audio/x-opus", + "application/ogg"); case Song::Type_Asf: - return TranscoderPreset(type, tr("Windows Media audio"), "wma", "audio/x-wma", "video/x-ms-asf"); + return TranscoderPreset(type, tr("Windows Media audio"), "wma", + "audio/x-wma", "video/x-ms-asf"); case Song::Type_Wav: - return TranscoderPreset(type, tr("Wav"), "wav", QString(), "audio/x-wav"); + return TranscoderPreset(type, tr("Wav"), "wav", QString(), "audio/x-wav"); default: qLog(Warning) << "Unsupported format in PresetForFileType:" << type; return TranscoderPreset(); @@ -264,24 +258,21 @@ TranscoderPreset Transcoder::PresetForFileType(Song::FileType type) { } Song::FileType Transcoder::PickBestFormat(QList supported) { - if (supported.isEmpty()) - return Song::Type_Unknown; + if (supported.isEmpty()) return Song::Type_Unknown; QList best_formats; best_formats << Song::Type_Mpeg; best_formats << Song::Type_OggVorbis; best_formats << Song::Type_Asf; - foreach (Song::FileType type, best_formats) { - if (supported.isEmpty() || supported.contains(type)) - return type; + foreach(Song::FileType type, best_formats) { + if (supported.isEmpty() || supported.contains(type)) return type; } return supported[0]; } -void Transcoder::AddJob(const QString& input, - const TranscoderPreset& preset, +void Transcoder::AddJob(const QString& input, const TranscoderPreset& preset, const QString& output) { Job job; job.input = input; @@ -296,8 +287,10 @@ void Transcoder::AddJob(const QString& input, // Never overwrite existing files if (QFile::exists(job.output)) { - for (int i=0 ; ; ++i) { - QString new_filename = QString("%1.%2.%3").arg(job.output.section('.',0,-2)).arg(i).arg(preset.extension_); + for (int i = 0;; ++i) { + QString new_filename = + QString("%1.%2.%3").arg(job.output.section('.', 0, -2)).arg(i).arg( + preset.extension_); if (!QFile::exists(new_filename)) { job.output = new_filename; break; @@ -310,18 +303,17 @@ void Transcoder::AddJob(const QString& input, void Transcoder::Start() { emit LogLine(tr("Transcoding %1 files using %2 threads") - .arg(queued_jobs_.count()).arg(max_threads())); + .arg(queued_jobs_.count()) + .arg(max_threads())); forever { StartJobStatus status = MaybeStartNextJob(); - if (status == AllThreadsBusy || status == NoMoreJobs) - break; + if (status == AllThreadsBusy || status == NoMoreJobs) break; } } Transcoder::StartJobStatus Transcoder::MaybeStartNextJob() { - if (current_jobs_.count() >= max_threads()) - return AllThreadsBusy; + if (current_jobs_.count() >= max_threads()) return AllThreadsBusy; if (queued_jobs_.isEmpty()) { if (current_jobs_.isEmpty()) { emit AllJobsComplete(); @@ -332,7 +324,7 @@ Transcoder::StartJobStatus Transcoder::MaybeStartNextJob() { Job job = queued_jobs_.takeFirst(); if (StartJob(job)) { - emit(JobOutputName(job.output)); + emit(JobOutputName(job.output)); return StartedSuccessfully; } @@ -340,10 +332,11 @@ Transcoder::StartJobStatus Transcoder::MaybeStartNextJob() { return FailedToStart; } -void Transcoder::NewPadCallback(GstElement*, GstPad* pad, gboolean, gpointer data) { +void Transcoder::NewPadCallback(GstElement*, GstPad* pad, gboolean, + gpointer data) { JobState* state = reinterpret_cast(data); - GstPad* const audiopad = gst_element_get_static_pad( - state->convert_element_, "sink"); + GstPad* const audiopad = + gst_element_get_static_pad(state->convert_element_, "sink"); if (GST_PAD_IS_LINKED(audiopad)) { qLog(Debug) << "audiopad is already linked, unlinking old pad"; @@ -369,7 +362,8 @@ gboolean Transcoder::BusCallback(GstBus*, GstMessage* msg, gpointer data) { return GST_BUS_DROP; } -GstBusSyncReply Transcoder::BusCallbackSync(GstBus*, GstMessage* msg, gpointer data) { +GstBusSyncReply Transcoder::BusCallbackSync(GstBus*, GstMessage* msg, + gpointer data) { JobState* state = reinterpret_cast(data); switch (GST_MESSAGE_TYPE(msg)) { case GST_MESSAGE_EOS: @@ -397,11 +391,11 @@ void Transcoder::JobState::ReportError(GstMessage* msg) { g_error_free(error); free(debugs); - emit parent_->LogLine( - tr("Error processing %1: %2").arg(QDir::toNativeSeparators(job_.input), message)); + emit parent_->LogLine(tr("Error processing %1: %2").arg( + QDir::toNativeSeparators(job_.input), message)); } -bool Transcoder::StartJob(const Job &job) { +bool Transcoder::StartJob(const Job& job) { shared_ptr state(new JobState(job, this)); emit LogLine(tr("Starting %1").arg(QDir::toNativeSeparators(job.input))); @@ -413,26 +407,27 @@ bool Transcoder::StartJob(const Job &job) { if (!state->pipeline_) return false; // Create all the elements - GstElement* src = CreateElement("filesrc", state->pipeline_); - GstElement* decode = CreateElement("decodebin2", state->pipeline_); - GstElement* convert = CreateElement("audioconvert", state->pipeline_); + GstElement* src = CreateElement("filesrc", state->pipeline_); + GstElement* decode = CreateElement("decodebin2", state->pipeline_); + GstElement* convert = CreateElement("audioconvert", state->pipeline_); GstElement* resample = CreateElement("audioresample", state->pipeline_); - GstElement* codec = CreateElementForMimeType("Codec/Encoder/Audio", job.preset.codec_mimetype_, state->pipeline_); - GstElement* muxer = CreateElementForMimeType("Codec/Muxer", job.preset.muxer_mimetype_, state->pipeline_); - GstElement* sink = CreateElement("filesink", state->pipeline_); + GstElement* codec = CreateElementForMimeType( + "Codec/Encoder/Audio", job.preset.codec_mimetype_, state->pipeline_); + GstElement* muxer = CreateElementForMimeType( + "Codec/Muxer", job.preset.muxer_mimetype_, state->pipeline_); + GstElement* sink = CreateElement("filesink", state->pipeline_); - if (!src || !decode || !convert || !sink) - return false; + if (!src || !decode || !convert || !sink) return false; if (!codec && !job.preset.codec_mimetype_.isEmpty()) { - LogLine(tr("Couldn't find an encoder for %1, check you have the correct GStreamer plugins installed" - ).arg(job.preset.codec_mimetype_)); + LogLine(tr("Couldn't find an encoder for %1, check you have the correct " + "GStreamer plugins installed").arg(job.preset.codec_mimetype_)); return false; } if (!muxer && !job.preset.muxer_mimetype_.isEmpty()) { - LogLine(tr("Couldn't find a muxer for %1, check you have the correct GStreamer plugins installed" - ).arg(job.preset.muxer_mimetype_)); + LogLine(tr("Couldn't find a muxer for %1, check you have the correct " + "GStreamer plugins installed").arg(job.preset.muxer_mimetype_)); return false; } @@ -453,8 +448,11 @@ bool Transcoder::StartJob(const Job &job) { state->convert_element_ = convert; CHECKED_GCONNECT(decode, "new-decoded-pad", &NewPadCallback, state.get()); - gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(state->pipeline_)), BusCallbackSync, state.get()); - state->bus_callback_id_ = gst_bus_add_watch(gst_pipeline_get_bus(GST_PIPELINE(state->pipeline_)), BusCallback, state.get()); + gst_bus_set_sync_handler(gst_pipeline_get_bus(GST_PIPELINE(state->pipeline_)), + BusCallbackSync, state.get()); + state->bus_callback_id_ = + gst_bus_add_watch(gst_pipeline_get_bus(GST_PIPELINE(state->pipeline_)), + BusCallback, state.get()); // Start the pipeline gst_element_set_state(state->pipeline_, GST_STATE_PLAYING); @@ -481,8 +479,7 @@ bool Transcoder::event(QEvent* e) { // Find this job in the list JobStateList::iterator it = current_jobs_.begin(); while (it != current_jobs_.end()) { - if (it->get() == finished_event->state_) - break; + if (it->get() == finished_event->state_) break; ++it; } if (it == current_jobs_.end()) { @@ -495,8 +492,9 @@ bool Transcoder::event(QEvent* e) { // 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( - finished_event->state_->pipeline_)), nullptr, nullptr); + gst_bus_set_sync_handler( + gst_pipeline_get_bus(GST_PIPELINE(finished_event->state_->pipeline_)), + nullptr, nullptr); g_source_remove(finished_event->state_->bus_callback_id_); // Remove it from the list - this will also destroy the GStreamer pipeline @@ -525,14 +523,16 @@ void Transcoder::Cancel() { // 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); + gst_bus_set_sync_handler( + gst_pipeline_get_bus(GST_PIPELINE(state->pipeline_)), nullptr, nullptr); g_source_remove(state->bus_callback_id_); // Stop the pipeline - if (gst_element_set_state(state->pipeline_, GST_STATE_NULL) == GST_STATE_CHANGE_ASYNC) { + if (gst_element_set_state(state->pipeline_, GST_STATE_NULL) == + GST_STATE_CHANGE_ASYNC) { // Wait for it to finish stopping... - gst_element_get_state(state->pipeline_, nullptr, nullptr, GST_CLOCK_TIME_NONE); + gst_element_get_state(state->pipeline_, nullptr, nullptr, + GST_CLOCK_TIME_NONE); } // Remove the job, this destroys the GStreamer pipeline too @@ -544,8 +544,7 @@ QMap Transcoder::GetProgress() const { QMap ret; for (const auto& state : current_jobs_) { - if (!state->pipeline_) - continue; + if (!state->pipeline_) continue; gint64 position = 0; gint64 duration = 0; @@ -566,23 +565,31 @@ void Transcoder::SetElementProperties(const QString& name, GObject* object) { guint properties_count = 0; GParamSpec** properties = g_object_class_list_properties( - G_OBJECT_GET_CLASS(object), &properties_count); + G_OBJECT_GET_CLASS(object), &properties_count); - for (int i=0 ; iname); - if (value.isNull()) - continue; + if (value.isNull()) continue; - LogLine(QString("Setting %1 property: %2 = %3").arg(name, property->name, value.toString())); + LogLine(QString("Setting %1 property: %2 = %3") + .arg(name, property->name, value.toString())); switch (property->value_type) { - case G_TYPE_DOUBLE: g_object_set(object, property->name, value.toDouble(), nullptr); break; - case G_TYPE_FLOAT: g_object_set(object, property->name, value.toFloat(), nullptr); break; - case G_TYPE_BOOLEAN: g_object_set(object, property->name, value.toInt(), nullptr); break; + case G_TYPE_DOUBLE: + g_object_set(object, property->name, value.toDouble(), nullptr); + break; + case G_TYPE_FLOAT: + g_object_set(object, property->name, value.toFloat(), nullptr); + break; + case G_TYPE_BOOLEAN: + g_object_set(object, property->name, value.toInt(), nullptr); + break; case G_TYPE_INT: - default: g_object_set(object, property->name, value.toInt(), nullptr); break; + default: + g_object_set(object, property->name, value.toInt(), nullptr); + break; } } diff --git a/src/transcoder/transcoder.h b/src/transcoder/transcoder.h index ab3e3efcf..ad9367833 100644 --- a/src/transcoder/transcoder.h +++ b/src/transcoder/transcoder.h @@ -29,13 +29,10 @@ #include "core/song.h" - struct TranscoderPreset { TranscoderPreset() : type_(Song::Type_Unknown) {} - TranscoderPreset(Song::FileType type, - const QString& name, - const QString& extension, - const QString& codec_mimetype, + TranscoderPreset(Song::FileType type, const QString& name, + const QString& extension, const QString& codec_mimetype, const QString& muxer_mimetype_ = QString()); Song::FileType type_; @@ -46,7 +43,6 @@ struct TranscoderPreset { }; Q_DECLARE_METATYPE(TranscoderPreset); - class Transcoder : public QObject { Q_OBJECT @@ -70,7 +66,7 @@ class Transcoder : public QObject { void Start(); void Cancel(); - signals: +signals: void JobComplete(const QString& filename, bool success); void LogLine(const QString& message); void AllJobsComplete(); @@ -91,8 +87,11 @@ class Transcoder : public QObject { // job's thread. struct JobState { JobState(const Job& job, Transcoder* parent) - : job_(job), parent_(parent), pipeline_(NULL), convert_element_(NULL), - bus_callback_id_(0) {} + : job_(job), + parent_(parent), + pipeline_(NULL), + convert_element_(NULL), + bus_callback_id_(0) {} ~JobState(); void PostFinished(bool success); @@ -135,7 +134,8 @@ class Transcoder : public QObject { static void NewPadCallback(GstElement*, GstPad* pad, gboolean, gpointer data); static gboolean BusCallback(GstBus*, GstMessage* msg, gpointer data); - static GstBusSyncReply BusCallbackSync(GstBus*, GstMessage* msg, gpointer data); + static GstBusSyncReply BusCallbackSync(GstBus*, GstMessage* msg, + gpointer data); private: typedef QList > JobStateList; @@ -145,4 +145,4 @@ class Transcoder : public QObject { JobStateList current_jobs_; }; -#endif // TRANSCODER_H +#endif // TRANSCODER_H diff --git a/src/transcoder/transcoderoptionsaac.cpp b/src/transcoder/transcoderoptionsaac.cpp index 0f5751396..1cec6b263 100644 --- a/src/transcoder/transcoderoptionsaac.cpp +++ b/src/transcoder/transcoderoptionsaac.cpp @@ -23,15 +23,11 @@ const char* TranscoderOptionsAAC::kSettingsGroup = "Transcoder/faac"; TranscoderOptionsAAC::TranscoderOptionsAAC(QWidget* parent) - : TranscoderOptionsInterface(parent), - ui_(new Ui_TranscoderOptionsAAC) -{ + : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsAAC) { ui_->setupUi(this); } -TranscoderOptionsAAC::~TranscoderOptionsAAC() { - delete ui_; -} +TranscoderOptionsAAC::~TranscoderOptionsAAC() { delete ui_; } void TranscoderOptionsAAC::Load() { QSettings s; diff --git a/src/transcoder/transcoderoptionsaac.h b/src/transcoder/transcoderoptionsaac.h index 6710904bd..24b01d8b1 100644 --- a/src/transcoder/transcoderoptionsaac.h +++ b/src/transcoder/transcoderoptionsaac.h @@ -23,17 +23,17 @@ class Ui_TranscoderOptionsAAC; class TranscoderOptionsAAC : public TranscoderOptionsInterface { -public: + public: TranscoderOptionsAAC(QWidget* parent = 0); ~TranscoderOptionsAAC(); void Load(); void Save(); -private: + private: static const char* kSettingsGroup; Ui_TranscoderOptionsAAC* ui_; }; -#endif // TRANSCODEROPTIONSAAC_H +#endif // TRANSCODEROPTIONSAAC_H diff --git a/src/transcoder/transcoderoptionsdialog.cpp b/src/transcoder/transcoderoptionsdialog.cpp index 8f9143a70..1fdb73a54 100644 --- a/src/transcoder/transcoderoptionsdialog.cpp +++ b/src/transcoder/transcoderoptionsdialog.cpp @@ -25,22 +25,34 @@ #include "transcoderoptionswma.h" #include "ui_transcoderoptionsdialog.h" -TranscoderOptionsDialog::TranscoderOptionsDialog(Song::FileType type, QWidget* parent) - : QDialog(parent), - ui_(new Ui_TranscoderOptionsDialog), - options_(nullptr) -{ +TranscoderOptionsDialog::TranscoderOptionsDialog(Song::FileType type, + QWidget* parent) + : QDialog(parent), ui_(new Ui_TranscoderOptionsDialog), options_(nullptr) { ui_->setupUi(this); switch (type) { case Song::Type_Flac: - case Song::Type_OggFlac: options_ = new TranscoderOptionsFlac(this); break; - case Song::Type_Mp4: options_ = new TranscoderOptionsAAC(this); break; - case Song::Type_Mpeg: options_ = new TranscoderOptionsMP3(this); break; - case Song::Type_OggVorbis: options_ = new TranscoderOptionsVorbis(this); break; - case Song::Type_OggOpus: options_ = new TranscoderOptionsOpus(this); break; - case Song::Type_OggSpeex: options_ = new TranscoderOptionsSpeex(this); break; - case Song::Type_Asf: options_ = new TranscoderOptionsWma(this); break; + case Song::Type_OggFlac: + options_ = new TranscoderOptionsFlac(this); + break; + case Song::Type_Mp4: + options_ = new TranscoderOptionsAAC(this); + break; + case Song::Type_Mpeg: + options_ = new TranscoderOptionsMP3(this); + break; + case Song::Type_OggVorbis: + options_ = new TranscoderOptionsVorbis(this); + break; + case Song::Type_OggOpus: + options_ = new TranscoderOptionsOpus(this); + break; + case Song::Type_OggSpeex: + options_ = new TranscoderOptionsSpeex(this); + break; + case Song::Type_Asf: + options_ = new TranscoderOptionsWma(this); + break; default: break; } @@ -53,9 +65,7 @@ TranscoderOptionsDialog::TranscoderOptionsDialog(Song::FileType type, QWidget* p } } -TranscoderOptionsDialog::~TranscoderOptionsDialog() { - delete ui_; -} +TranscoderOptionsDialog::~TranscoderOptionsDialog() { delete ui_; } void TranscoderOptionsDialog::showEvent(QShowEvent* e) { if (options_) { @@ -69,4 +79,3 @@ void TranscoderOptionsDialog::accept() { } QDialog::accept(); } - diff --git a/src/transcoder/transcoderoptionsdialog.h b/src/transcoder/transcoderoptionsdialog.h index 4f033f378..93377d30c 100644 --- a/src/transcoder/transcoderoptionsdialog.h +++ b/src/transcoder/transcoderoptionsdialog.h @@ -28,7 +28,7 @@ class Ui_TranscoderOptionsDialog; class TranscoderOptionsDialog : public QDialog { Q_OBJECT -public: + public: TranscoderOptionsDialog(Song::FileType type, QWidget* parent = 0); ~TranscoderOptionsDialog(); @@ -36,12 +36,12 @@ public: void accept(); -protected: + protected: void showEvent(QShowEvent* e); -private: + private: Ui_TranscoderOptionsDialog* ui_; TranscoderOptionsInterface* options_; }; -#endif // TRANSCODEROPTIONSDIALOG_H +#endif // TRANSCODEROPTIONSDIALOG_H diff --git a/src/transcoder/transcoderoptionsflac.cpp b/src/transcoder/transcoderoptionsflac.cpp index ee73175ed..dc29471a9 100644 --- a/src/transcoder/transcoderoptionsflac.cpp +++ b/src/transcoder/transcoderoptionsflac.cpp @@ -23,15 +23,11 @@ const char* TranscoderOptionsFlac::kSettingsGroup = "Transcoder/flacenc"; TranscoderOptionsFlac::TranscoderOptionsFlac(QWidget* parent) - : TranscoderOptionsInterface(parent), - ui_(new Ui_TranscoderOptionsFlac) -{ + : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsFlac) { ui_->setupUi(this); } -TranscoderOptionsFlac::~TranscoderOptionsFlac() { - delete ui_; -} +TranscoderOptionsFlac::~TranscoderOptionsFlac() { delete ui_; } void TranscoderOptionsFlac::Load() { QSettings s; diff --git a/src/transcoder/transcoderoptionsflac.h b/src/transcoder/transcoderoptionsflac.h index ae410327b..db390a70f 100644 --- a/src/transcoder/transcoderoptionsflac.h +++ b/src/transcoder/transcoderoptionsflac.h @@ -23,17 +23,17 @@ class Ui_TranscoderOptionsFlac; class TranscoderOptionsFlac : public TranscoderOptionsInterface { -public: + public: TranscoderOptionsFlac(QWidget* parent = 0); ~TranscoderOptionsFlac(); void Load(); void Save(); -private: + private: static const char* kSettingsGroup; Ui_TranscoderOptionsFlac* ui_; }; -#endif // TRANSCODEROPTIONSFLAC_H +#endif // TRANSCODEROPTIONSFLAC_H diff --git a/src/transcoder/transcoderoptionsinterface.h b/src/transcoder/transcoderoptionsinterface.h index 11d6740fc..db528e750 100644 --- a/src/transcoder/transcoderoptionsinterface.h +++ b/src/transcoder/transcoderoptionsinterface.h @@ -21,7 +21,7 @@ #include class TranscoderOptionsInterface : public QWidget { -public: + public: TranscoderOptionsInterface(QWidget* parent) : QWidget(parent) {} virtual ~TranscoderOptionsInterface() {} @@ -29,4 +29,4 @@ public: virtual void Save() = 0; }; -#endif // TRANSCODEROPTIONSINTERFACE_H +#endif // TRANSCODEROPTIONSINTERFACE_H diff --git a/src/transcoder/transcoderoptionsmp3.cpp b/src/transcoder/transcoderoptionsmp3.cpp index 827405598..07a44202b 100644 --- a/src/transcoder/transcoderoptionsmp3.cpp +++ b/src/transcoder/transcoderoptionsmp3.cpp @@ -23,22 +23,21 @@ const char* TranscoderOptionsMP3::kSettingsGroup = "Transcoder/lamemp3enc"; TranscoderOptionsMP3::TranscoderOptionsMP3(QWidget* parent) - : TranscoderOptionsInterface(parent), - ui_(new Ui_TranscoderOptionsMP3) -{ + : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsMP3) { ui_->setupUi(this); - connect(ui_->quality_slider, SIGNAL(valueChanged(int)), SLOT(QualitySliderChanged(int))); - connect(ui_->quality_spinbox, SIGNAL(valueChanged(double)), SLOT(QualitySpinboxChanged(double))); + connect(ui_->quality_slider, SIGNAL(valueChanged(int)), + SLOT(QualitySliderChanged(int))); + connect(ui_->quality_spinbox, SIGNAL(valueChanged(double)), + SLOT(QualitySpinboxChanged(double))); } -TranscoderOptionsMP3::~TranscoderOptionsMP3() { - delete ui_; -} +TranscoderOptionsMP3::~TranscoderOptionsMP3() { delete ui_; } void TranscoderOptionsMP3::Load() { QSettings s; - s.beginGroup(kSettingsGroup);; + s.beginGroup(kSettingsGroup); + ; if (s.value("target", 1).toInt() == 0) { ui_->target_quality->setChecked(true); @@ -49,7 +48,8 @@ void TranscoderOptionsMP3::Load() { ui_->quality_spinbox->setValue(s.value("quality", 4.0).toFloat()); ui_->bitrate_slider->setValue(s.value("bitrate", 128).toInt()); ui_->cbr->setChecked(s.value("cbr", true).toBool()); - ui_->encoding_engine_quality->setCurrentIndex(s.value("encoding-engine-quality", 1).toInt()); + ui_->encoding_engine_quality->setCurrentIndex( + s.value("encoding-engine-quality", 1).toInt()); ui_->mono->setChecked(s.value("mono", false).toBool()); } @@ -61,7 +61,8 @@ void TranscoderOptionsMP3::Save() { s.setValue("quality", ui_->quality_spinbox->value()); s.setValue("bitrate", ui_->bitrate_slider->value()); s.setValue("cbr", ui_->cbr->isChecked()); - s.setValue("encoding-engine-quality", ui_->encoding_engine_quality->currentIndex()); + s.setValue("encoding-engine-quality", + ui_->encoding_engine_quality->currentIndex()); s.setValue("mono", ui_->mono->isChecked()); } diff --git a/src/transcoder/transcoderoptionsmp3.h b/src/transcoder/transcoderoptionsmp3.h index 161643e48..776cc7b21 100644 --- a/src/transcoder/transcoderoptionsmp3.h +++ b/src/transcoder/transcoderoptionsmp3.h @@ -25,21 +25,21 @@ class Ui_TranscoderOptionsMP3; class TranscoderOptionsMP3 : public TranscoderOptionsInterface { Q_OBJECT -public: + public: TranscoderOptionsMP3(QWidget* parent = 0); ~TranscoderOptionsMP3(); void Load(); void Save(); -private slots: + private slots: void QualitySliderChanged(int value); void QualitySpinboxChanged(double value); -private: + private: static const char* kSettingsGroup; Ui_TranscoderOptionsMP3* ui_; }; -#endif // TRANSCODEROPTIONSMP3_H +#endif // TRANSCODEROPTIONSMP3_H diff --git a/src/transcoder/transcoderoptionsopus.cpp b/src/transcoder/transcoderoptionsopus.cpp index d055eabe5..013cae7fc 100644 --- a/src/transcoder/transcoderoptionsopus.cpp +++ b/src/transcoder/transcoderoptionsopus.cpp @@ -21,20 +21,16 @@ #include // TODO: Add more options than only bitrate as soon as gst doesn't crash -// anymore while using the cbr parmameter (like cbr=false) +// anymore while using the cbr parmameter (like cbr=false) const char* TranscoderOptionsOpus::kSettingsGroup = "Transcoder/opusenc"; TranscoderOptionsOpus::TranscoderOptionsOpus(QWidget* parent) - : TranscoderOptionsInterface(parent), - ui_(new Ui_TranscoderOptionsOpus) -{ + : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsOpus) { ui_->setupUi(this); } -TranscoderOptionsOpus::~TranscoderOptionsOpus() { - delete ui_; -} +TranscoderOptionsOpus::~TranscoderOptionsOpus() { delete ui_; } void TranscoderOptionsOpus::Load() { QSettings s; diff --git a/src/transcoder/transcoderoptionsopus.h b/src/transcoder/transcoderoptionsopus.h index ee2dd0507..a4e1d557f 100644 --- a/src/transcoder/transcoderoptionsopus.h +++ b/src/transcoder/transcoderoptionsopus.h @@ -23,17 +23,17 @@ class Ui_TranscoderOptionsOpus; class TranscoderOptionsOpus : public TranscoderOptionsInterface { -public: + public: TranscoderOptionsOpus(QWidget* parent = 0); ~TranscoderOptionsOpus(); void Load(); void Save(); -private: + private: static const char* kSettingsGroup; Ui_TranscoderOptionsOpus* ui_; }; -#endif // TRANSCODEROPTIONSOPUS_H +#endif // TRANSCODEROPTIONSOPUS_H diff --git a/src/transcoder/transcoderoptionsspeex.cpp b/src/transcoder/transcoderoptionsspeex.cpp index 02dd0ab49..dd39af280 100644 --- a/src/transcoder/transcoderoptionsspeex.cpp +++ b/src/transcoder/transcoderoptionsspeex.cpp @@ -23,15 +23,11 @@ const char* TranscoderOptionsSpeex::kSettingsGroup = "Transcoder/speexenc"; TranscoderOptionsSpeex::TranscoderOptionsSpeex(QWidget* parent) - : TranscoderOptionsInterface(parent), - ui_(new Ui_TranscoderOptionsSpeex) -{ + : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsSpeex) { ui_->setupUi(this); } -TranscoderOptionsSpeex::~TranscoderOptionsSpeex() { - delete ui_; -} +TranscoderOptionsSpeex::~TranscoderOptionsSpeex() { delete ui_; } void TranscoderOptionsSpeex::Load() { QSettings s; diff --git a/src/transcoder/transcoderoptionsspeex.h b/src/transcoder/transcoderoptionsspeex.h index 40662cbe4..2fe512e6d 100644 --- a/src/transcoder/transcoderoptionsspeex.h +++ b/src/transcoder/transcoderoptionsspeex.h @@ -23,17 +23,17 @@ class Ui_TranscoderOptionsSpeex; class TranscoderOptionsSpeex : public TranscoderOptionsInterface { -public: + public: TranscoderOptionsSpeex(QWidget* parent = 0); ~TranscoderOptionsSpeex(); void Load(); void Save(); -private: + private: static const char* kSettingsGroup; Ui_TranscoderOptionsSpeex* ui_; }; -#endif // TRANSCODEROPTIONSSPEEX_H +#endif // TRANSCODEROPTIONSSPEEX_H diff --git a/src/transcoder/transcoderoptionsvorbis.cpp b/src/transcoder/transcoderoptionsvorbis.cpp index 3914ea711..450bbfd2d 100644 --- a/src/transcoder/transcoderoptionsvorbis.cpp +++ b/src/transcoder/transcoderoptionsvorbis.cpp @@ -23,21 +23,17 @@ const char* TranscoderOptionsVorbis::kSettingsGroup = "Transcoder/vorbisenc"; TranscoderOptionsVorbis::TranscoderOptionsVorbis(QWidget* parent) - : TranscoderOptionsInterface(parent), - ui_(new Ui_TranscoderOptionsVorbis) -{ + : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsVorbis) { ui_->setupUi(this); } -TranscoderOptionsVorbis::~TranscoderOptionsVorbis() { - delete ui_; -} +TranscoderOptionsVorbis::~TranscoderOptionsVorbis() { delete ui_; } void TranscoderOptionsVorbis::Load() { QSettings s; s.beginGroup(kSettingsGroup); -#define GET_BITRATE(variable, property) \ +#define GET_BITRATE(variable, property) \ int variable = s.value(property, -1).toInt(); \ variable = variable == -1 ? 0 : variable / 1000 @@ -58,7 +54,7 @@ void TranscoderOptionsVorbis::Save() { s.beginGroup(kSettingsGroup); #define GET_BITRATE(variable, ui_slider) \ - int variable = ui_slider->value(); \ + int variable = ui_slider->value(); \ variable = variable == 0 ? -1 : variable * 1000 GET_BITRATE(bitrate, ui_->bitrate_slider); diff --git a/src/transcoder/transcoderoptionsvorbis.h b/src/transcoder/transcoderoptionsvorbis.h index 62c14d288..05de8f1c5 100644 --- a/src/transcoder/transcoderoptionsvorbis.h +++ b/src/transcoder/transcoderoptionsvorbis.h @@ -23,17 +23,17 @@ class Ui_TranscoderOptionsVorbis; class TranscoderOptionsVorbis : public TranscoderOptionsInterface { -public: + public: TranscoderOptionsVorbis(QWidget* parent = 0); ~TranscoderOptionsVorbis(); void Load(); void Save(); -private: + private: static const char* kSettingsGroup; Ui_TranscoderOptionsVorbis* ui_; }; -#endif // TRANSCODEROPTIONSVORBIS_H +#endif // TRANSCODEROPTIONSVORBIS_H diff --git a/src/transcoder/transcoderoptionswma.cpp b/src/transcoder/transcoderoptionswma.cpp index 3b24c51a6..db9944953 100644 --- a/src/transcoder/transcoderoptionswma.cpp +++ b/src/transcoder/transcoderoptionswma.cpp @@ -23,15 +23,11 @@ const char* TranscoderOptionsWma::kSettingsGroup = "Transcoder/ffenc_wmav2"; TranscoderOptionsWma::TranscoderOptionsWma(QWidget* parent) - : TranscoderOptionsInterface(parent), - ui_(new Ui_TranscoderOptionsWma) -{ + : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsWma) { ui_->setupUi(this); } -TranscoderOptionsWma::~TranscoderOptionsWma() { - delete ui_; -} +TranscoderOptionsWma::~TranscoderOptionsWma() { delete ui_; } void TranscoderOptionsWma::Load() { QSettings s; diff --git a/src/transcoder/transcoderoptionswma.h b/src/transcoder/transcoderoptionswma.h index 8ae4c19fb..b1d4cfbec 100644 --- a/src/transcoder/transcoderoptionswma.h +++ b/src/transcoder/transcoderoptionswma.h @@ -23,17 +23,17 @@ class Ui_TranscoderOptionsWma; class TranscoderOptionsWma : public TranscoderOptionsInterface { -public: + public: TranscoderOptionsWma(QWidget* parent = 0); ~TranscoderOptionsWma(); void Load(); void Save(); -private: + private: static const char* kSettingsGroup; Ui_TranscoderOptionsWma* ui_; }; -#endif // TRANSCODEROPTIONSWMA_H +#endif // TRANSCODEROPTIONSWMA_H diff --git a/src/transcoder/transcodersettingspage.cpp b/src/transcoder/transcodersettingspage.cpp index 3dd5b597d..5460e60f8 100644 --- a/src/transcoder/transcodersettingspage.cpp +++ b/src/transcoder/transcodersettingspage.cpp @@ -20,16 +20,12 @@ #include "ui/iconloader.h" TranscoderSettingsPage::TranscoderSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_TranscoderSettingsPage) -{ + : SettingsPage(dialog), ui_(new Ui_TranscoderSettingsPage) { ui_->setupUi(this); setWindowIcon(IconLoader::Load("tools-wizard")); } -TranscoderSettingsPage::~TranscoderSettingsPage() { - delete ui_; -} +TranscoderSettingsPage::~TranscoderSettingsPage() { delete ui_; } void TranscoderSettingsPage::Load() { ui_->transcoding_aac->Load(); diff --git a/src/transcoder/transcodersettingspage.h b/src/transcoder/transcodersettingspage.h index 10d0bfb29..fc2b8b068 100644 --- a/src/transcoder/transcodersettingspage.h +++ b/src/transcoder/transcodersettingspage.h @@ -25,15 +25,15 @@ class Ui_TranscoderSettingsPage; class TranscoderSettingsPage : public SettingsPage { Q_OBJECT -public: + public: TranscoderSettingsPage(SettingsDialog* dialog); ~TranscoderSettingsPage(); void Load(); void Save(); -private: + private: Ui_TranscoderSettingsPage* ui_; }; -#endif // TRANSCODERSETTINGSPAGE_H +#endif // TRANSCODERSETTINGSPAGE_H diff --git a/src/ui/about.cpp b/src/ui/about.cpp index 53e42bd89..4ae16b376 100644 --- a/src/ui/about.cpp +++ b/src/ui/about.cpp @@ -24,14 +24,13 @@ const char* About::kUrl = "http://www.clementine-player.org/"; -About::About(QWidget *parent) - : QDialog(parent) -{ +About::About(QWidget* parent) : QDialog(parent) { ui_.setupUi(this); setWindowTitle(tr("About %1").arg(QCoreApplication::applicationName())); ui_.title->setText(QCoreApplication::applicationName()); - ui_.version->setText(tr("Version %1").arg(QCoreApplication::applicationVersion())); + ui_.version->setText( + tr("Version %1").arg(QCoreApplication::applicationVersion())); QFont title_font; title_font.setBold(true); @@ -44,7 +43,8 @@ About::About(QWidget *parent) << Person("Arnaud Bienner", "arnaud.bienner@gmail.com"); thanks_to_ << Person("Mark Kretschmann", "kretschmann@kde.org") << Person("Max Howell", "max.howell@methylblue.com") - << Person(QString::fromUtf8("BartÅ‚omiej Burdukiewicz"), "dev.strikeu@gmail.com") + << Person(QString::fromUtf8("BartÅ‚omiej Burdukiewicz"), + "dev.strikeu@gmail.com") << Person("Jakub Stachowski", "qbast@go2.pl") << Person("Paul Cifarelli", "paul@cifarelli.net") << Person("Felipe Rivera", "liebremx@users.sourceforge.net") @@ -57,32 +57,41 @@ About::About(QWidget *parent) ui_.content->setHtml(MakeHtml()); - ui_.buttonBox->button(QDialogButtonBox::Close)->setShortcut(QKeySequence::Close); + ui_.buttonBox->button(QDialogButtonBox::Close) + ->setShortcut(QKeySequence::Close); } QString About::MakeHtml() const { - QString ret = QString("

%2

" - "

%3:").arg(kUrl, kUrl, tr("Authors")); + QString ret = QString( + "

%2

" + "

%3:").arg(kUrl, kUrl, tr("Authors")); - foreach (const Person& person, authors_) - ret += "
" + MakeHtml(person); + foreach(const Person & person, authors_) + ret += "
" + MakeHtml(person); ret += QString("

%3:").arg(tr("Thanks to")); - foreach (const Person& person, thanks_to_) - ret += "
" + MakeHtml(person); - ret += QString("
" + tr("All the translators") + " <" - "https://www.transifex.net/projects/p/clementine>"); + foreach(const Person & person, thanks_to_) + ret += "
" + MakeHtml(person); + ret += QString( + "
" + tr("All the translators") + + " <" + "https://www.transifex.net/projects/p/clementine>"); ret += QString("
%1

").arg(tr("...and all the Amarok contributors")); ret += QString("

%1").arg(tr("And:")); ret += QString("
Rainy Mood"); - ret += QString("
Scott Smitelli"); - ret += QString("
Allie Brosh

"); + ret += QString( + "
Scott " + "Smitelli"); + ret += QString( + "
Allie " + "Brosh

"); - ret += "

This product uses Music by Spotify but is not endorsed, certified " - "or otherwise approved in any way by Spotify. Spotify is the registered " - "trade mark of the Spotify Group.

"; + ret += + "

This product uses Music by Spotify but is not endorsed, certified " + "or otherwise approved in any way by Spotify. Spotify is the registered " + "trade mark of the Spotify Group.

"; return ret; } diff --git a/src/ui/about.h b/src/ui/about.h index 285f2c509..1a9730815 100644 --- a/src/ui/about.h +++ b/src/ui/about.h @@ -30,9 +30,10 @@ class About : public QDialog { static const char* kUrl; struct Person { - Person(const QString& n, const QString& e = QString()) : name(n), email(e) {} + Person(const QString& n, const QString& e = QString()) + : name(n), email(e) {} - bool operator <(const Person& other) const { return name < other.name; } + bool operator<(const Person& other) const { return name < other.name; } QString name; QString email; @@ -49,4 +50,4 @@ class About : public QDialog { QList thanks_to_; }; -#endif // ABOUT_H +#endif // ABOUT_H diff --git a/src/ui/addstreamdialog.cpp b/src/ui/addstreamdialog.cpp index 17abca7d5..cdf90cbc5 100644 --- a/src/ui/addstreamdialog.cpp +++ b/src/ui/addstreamdialog.cpp @@ -27,11 +27,8 @@ const char* AddStreamDialog::kSettingsGroup = "AddStreamDialog"; -AddStreamDialog::AddStreamDialog(QWidget *parent) - : QDialog(parent), - ui_(new Ui_AddStreamDialog), - saved_radio_(nullptr) -{ +AddStreamDialog::AddStreamDialog(QWidget* parent) + : QDialog(parent), ui_(new Ui_AddStreamDialog), saved_radio_(nullptr) { ui_->setupUi(this); connect(ui_->url, SIGNAL(textChanged(QString)), SLOT(TextChanged(QString))); @@ -45,30 +42,23 @@ AddStreamDialog::AddStreamDialog(QWidget *parent) ui_->name->setText(s.value("name").toString()); } -AddStreamDialog::~AddStreamDialog() { - delete ui_; -} +AddStreamDialog::~AddStreamDialog() { delete ui_; } -QUrl AddStreamDialog::url() const { - return QUrl(ui_->url->text()); -} +QUrl AddStreamDialog::url() const { return QUrl(ui_->url->text()); } -QString AddStreamDialog::name() const { - return ui_->name->text(); -} +QString AddStreamDialog::name() const { return ui_->name->text(); } -void AddStreamDialog::set_name(const QString &name) { +void AddStreamDialog::set_name(const QString& name) { ui_->name->setText(name); } -void AddStreamDialog::set_url(const QUrl &url) { +void AddStreamDialog::set_url(const QUrl& url) { ui_->url->setText(url.toString()); } void AddStreamDialog::set_save_visible(bool visible) { ui_->save->setVisible(visible); - if (!visible) - ui_->name_container->setEnabled(true); + if (!visible) ui_->name_container->setEnabled(true); } void AddStreamDialog::accept() { @@ -86,18 +76,17 @@ void AddStreamDialog::accept() { QDialog::accept(); } -void AddStreamDialog::TextChanged(const QString &text) { +void AddStreamDialog::TextChanged(const QString& text) { // Decide whether the URL is valid QUrl url(text); - bool valid = url.isValid() && - !url.scheme().isEmpty() && - !url.toString().isEmpty(); + bool valid = + url.isValid() && !url.scheme().isEmpty() && !url.toString().isEmpty(); ui_->button_box->button(QDialogButtonBox::Ok)->setEnabled(valid); } -void AddStreamDialog::showEvent(QShowEvent *) { +void AddStreamDialog::showEvent(QShowEvent*) { ui_->url->setFocus(); ui_->url->selectAll(); } diff --git a/src/ui/addstreamdialog.h b/src/ui/addstreamdialog.h index 82a21637e..b0c1220f4 100644 --- a/src/ui/addstreamdialog.h +++ b/src/ui/addstreamdialog.h @@ -28,13 +28,15 @@ class AddStreamDialog : public QDialog { Q_OBJECT public: - AddStreamDialog(QWidget *parent = 0); + AddStreamDialog(QWidget* parent = 0); ~AddStreamDialog(); void set_url(const QUrl& url); void set_name(const QString& name); void set_save_visible(bool visible); - void set_add_on_accept(SavedRadio* saved_radio) { saved_radio_ = saved_radio; } + void set_add_on_accept(SavedRadio* saved_radio) { + saved_radio_ = saved_radio; + } QUrl url() const; QString name() const; @@ -42,7 +44,7 @@ class AddStreamDialog : public QDialog { void accept(); protected: - void showEvent(QShowEvent *); + void showEvent(QShowEvent*); private slots: void TextChanged(const QString& text); @@ -55,4 +57,4 @@ class AddStreamDialog : public QDialog { SavedRadio* saved_radio_; }; -#endif // ADDSTREAMDIALOG_H +#endif // ADDSTREAMDIALOG_H diff --git a/src/ui/albumcoverchoicecontroller.cpp b/src/ui/albumcoverchoicecontroller.cpp index a4a66270b..eddfb07dd 100644 --- a/src/ui/albumcoverchoicecontroller.cpp +++ b/src/ui/albumcoverchoicecontroller.cpp @@ -39,31 +39,37 @@ #include #include -const char* AlbumCoverChoiceController::kLoadImageFileFilter = - QT_TR_NOOP("Images (*.png *.jpg *.jpeg *.bmp *.gif *.xpm *.pbm *.pgm *.ppm *.xbm)"); +const char* AlbumCoverChoiceController::kLoadImageFileFilter = QT_TR_NOOP( + "Images (*.png *.jpg *.jpeg *.bmp *.gif *.xpm *.pbm *.pgm *.ppm *.xbm)"); const char* AlbumCoverChoiceController::kSaveImageFileFilter = - QT_TR_NOOP("Images (*.png *.jpg *.jpeg *.bmp *.xpm *.pbm *.ppm *.xbm)"); + QT_TR_NOOP("Images (*.png *.jpg *.jpeg *.bmp *.xpm *.pbm *.ppm *.xbm)"); const char* AlbumCoverChoiceController::kAllFilesFilter = - QT_TR_NOOP("All files (*)"); + QT_TR_NOOP("All files (*)"); QSet* AlbumCoverChoiceController::sImageExtensions = nullptr; AlbumCoverChoiceController::AlbumCoverChoiceController(QWidget* parent) - : QWidget(parent), - app_(nullptr), - cover_searcher_(nullptr), - cover_fetcher_(nullptr), - save_file_dialog_(nullptr), - cover_from_url_dialog_(nullptr) -{ - cover_from_file_ = new QAction(IconLoader::Load("document-open"), tr("Load cover from disk..."), this); - cover_to_file_ = new QAction(IconLoader::Load("document-save"), tr("Save cover to disk..."), this); - cover_from_url_ = new QAction(IconLoader::Load("download"), tr("Load cover from URL..."), this); - search_for_cover_ = new QAction(IconLoader::Load("find"), tr("Search for album covers..."), this); - unset_cover_ = new QAction(IconLoader::Load("list-remove"), tr("Unset cover"), this); - show_cover_ = new QAction(IconLoader::Load("zoom-in"), tr("Show fullsize..."), this); + : QWidget(parent), + app_(nullptr), + cover_searcher_(nullptr), + cover_fetcher_(nullptr), + save_file_dialog_(nullptr), + cover_from_url_dialog_(nullptr) { + cover_from_file_ = new QAction(IconLoader::Load("document-open"), + tr("Load cover from disk..."), this); + cover_to_file_ = new QAction(IconLoader::Load("document-save"), + tr("Save cover to disk..."), this); + cover_from_url_ = new QAction(IconLoader::Load("download"), + tr("Load cover from URL..."), this); + search_for_cover_ = new QAction(IconLoader::Load("find"), + tr("Search for album covers..."), this); + unset_cover_ = + new QAction(IconLoader::Load("list-remove"), tr("Unset cover"), this); + show_cover_ = + new QAction(IconLoader::Load("zoom-in"), tr("Show fullsize..."), this); - search_cover_auto_ = new QAction(IconLoader::Load("find"), tr("Search automatically"), this); + search_cover_auto_ = + new QAction(IconLoader::Load("find"), tr("Search automatically"), this); search_cover_auto_->setCheckable(true); search_cover_auto_->setChecked(false); @@ -71,9 +77,7 @@ AlbumCoverChoiceController::AlbumCoverChoiceController(QWidget* parent) separator_->setSeparator(true); } -AlbumCoverChoiceController::~AlbumCoverChoiceController() -{ -} +AlbumCoverChoiceController::~AlbumCoverChoiceController() {} void AlbumCoverChoiceController::SetApplication(Application* app) { app_ = app; @@ -82,29 +86,30 @@ void AlbumCoverChoiceController::SetApplication(Application* app) { cover_searcher_ = new AlbumCoverSearcher(QIcon(":/nocover.png"), app, this); cover_searcher_->Init(cover_fetcher_); - connect(cover_fetcher_, SIGNAL(AlbumCoverFetched(quint64,QImage,CoverSearchStatistics)), - this, SLOT(AlbumCoverFetched(quint64,QImage,CoverSearchStatistics))); + connect(cover_fetcher_, + SIGNAL(AlbumCoverFetched(quint64, QImage, CoverSearchStatistics)), + this, + SLOT(AlbumCoverFetched(quint64, QImage, CoverSearchStatistics))); } QList AlbumCoverChoiceController::GetAllActions() { - return QList() << cover_from_file_ << cover_to_file_ - << separator_ + return QList() << cover_from_file_ << cover_to_file_ << separator_ << cover_from_url_ << search_for_cover_ << unset_cover_ << show_cover_; } QString AlbumCoverChoiceController::LoadCoverFromFile(Song* song) { QString cover = QFileDialog::getOpenFileName( - this, tr("Load cover from disk"), GetInitialPathForFileDialog(*song, QString()), + this, tr("Load cover from disk"), + GetInitialPathForFileDialog(*song, QString()), tr(kLoadImageFileFilter) + ";;" + tr(kAllFilesFilter)); - if (cover.isNull()) - return QString(); + if (cover.isNull()) return QString(); // Can we load the image? QImage image(cover); - if(!image.isNull()) { + if (!image.isNull()) { SaveCover(song, cover); return cover; } else { @@ -112,53 +117,54 @@ QString AlbumCoverChoiceController::LoadCoverFromFile(Song* song) { } } -void AlbumCoverChoiceController::SaveCoverToFile(const Song& song, const QImage& image) { - QString initial_file_name = "/" + (song.album().isEmpty() - ? tr("Unknown") - : song.album()) + ".jpg"; +void AlbumCoverChoiceController::SaveCoverToFile(const Song& song, + const QImage& image) { + QString initial_file_name = + "/" + (song.album().isEmpty() ? tr("Unknown") : song.album()) + ".jpg"; QString save_filename = QFileDialog::getSaveFileName( - this, tr("Save album cover"), GetInitialPathForFileDialog(song, initial_file_name), + this, tr("Save album cover"), + GetInitialPathForFileDialog(song, initial_file_name), tr(kSaveImageFileFilter) + ";;" + tr(kAllFilesFilter)); - if(save_filename.isNull()) - return; + if (save_filename.isNull()) return; QString extension = save_filename.right(4); if (!extension.startsWith('.') || - !QImageWriter::supportedImageFormats().contains(extension.right(3).toUtf8())) { + !QImageWriter::supportedImageFormats().contains( + extension.right(3).toUtf8())) { save_filename.append(".jpg"); } image.save(save_filename); } -QString AlbumCoverChoiceController::GetInitialPathForFileDialog(const Song& song, - const QString& filename) { +QString AlbumCoverChoiceController::GetInitialPathForFileDialog( + const Song& song, const QString& filename) { // art automatic is first to show user which cover the album may be // using now; the song is using it if there's no manual path but we // cannot use manual path here because it can contain cached paths if (!song.art_automatic().isEmpty() && !song.has_embedded_cover()) { return song.art_automatic(); - // if no automatic art, start in the song's folder + // if no automatic art, start in the song's folder } else if (!song.url().isEmpty() && song.url().toLocalFile().contains('/')) { return song.url().toLocalFile().section('/', 0, -2) + filename; - // fallback - start in home + // fallback - start in home } else { return QDir::home().absolutePath() + filename; } } QString AlbumCoverChoiceController::LoadCoverFromURL(Song* song) { - if(!cover_from_url_dialog_) { + if (!cover_from_url_dialog_) { cover_from_url_dialog_ = new CoverFromURLDialog(this); } QImage image = cover_from_url_dialog_->Exec(); - if(!image.isNull()) { + if (!image.isNull()) { QString cover = SaveCoverInCache(song->artist(), song->album(), image); SaveCover(song, cover); @@ -172,7 +178,7 @@ QString AlbumCoverChoiceController::SearchForCover(Song* song) { // Get something sensible to stick in the search box QImage image = cover_searcher_->Exec(song->artist(), song->album()); - if(!image.isNull()) { + if (!image.isNull()) { QString cover = SaveCoverInCache(song->artist(), song->album(), image); SaveCover(song, cover); @@ -195,11 +201,9 @@ void AlbumCoverChoiceController::ShowCover(const Song& song) { // Use Artist - Album as the window title QString title_text(song.albumartist()); - if (title_text.isEmpty()) - title_text = song.artist(); + if (title_text.isEmpty()) title_text = song.artist(); - if (!song.album().isEmpty()) - title_text += " - " + song.album(); + if (!song.album().isEmpty()) title_text += " - " + song.album(); dialog->setWindowTitle(title_text); @@ -216,9 +220,8 @@ void AlbumCoverChoiceController::SearchCoverAutomatically(const Song& song) { cover_fetching_tasks_[id] = song; } -void AlbumCoverChoiceController::AlbumCoverFetched(quint64 id, - const QImage& image, - const CoverSearchStatistics& statistics) { +void AlbumCoverChoiceController::AlbumCoverFetched( + quint64 id, const QImage& image, const CoverSearchStatistics& statistics) { Song song; if (cover_fetching_tasks_.contains(id)) { song = cover_fetching_tasks_.take(id); @@ -232,10 +235,11 @@ void AlbumCoverChoiceController::AlbumCoverFetched(quint64 id, emit AutomaticCoverSearchDone(); } -void AlbumCoverChoiceController::SaveCover(Song* song, const QString &cover) { - if(song->is_valid() && song->id() != -1) { +void AlbumCoverChoiceController::SaveCover(Song* song, const QString& cover) { + if (song->is_valid() && song->id() != -1) { song->set_art_manual(cover); - app_->library_backend()->UpdateManualAlbumArtAsync(song->artist(), song->album(), cover); + app_->library_backend()->UpdateManualAlbumArtAsync(song->artist(), + song->album(), cover); if (song->url() == app_->current_art_loader()->last_song().url()) { app_->current_art_loader()->LoadArt(*song); @@ -243,8 +247,9 @@ void AlbumCoverChoiceController::SaveCover(Song* song, const QString &cover) { } } -QString AlbumCoverChoiceController::SaveCoverInCache( - const QString& artist, const QString& album, const QImage& image) { +QString AlbumCoverChoiceController::SaveCoverInCache(const QString& artist, + const QString& album, + const QImage& image) { // Hash the artist and album into a filename for the image QString filename(Utilities::Sha1CoverHash(artist, album).toHex() + ".jpg"); @@ -263,18 +268,25 @@ QString AlbumCoverChoiceController::SaveCoverInCache( bool AlbumCoverChoiceController::IsKnownImageExtension(const QString& suffix) { if (!sImageExtensions) { sImageExtensions = new QSet(); - (*sImageExtensions) << "png" << "jpg" << "jpeg" << "bmp" << "gif" << "xpm" - << "pbm" << "pgm" << "ppm" << "xbm"; + (*sImageExtensions) << "png" + << "jpg" + << "jpeg" + << "bmp" + << "gif" + << "xpm" + << "pbm" + << "pgm" + << "ppm" + << "xbm"; } return sImageExtensions->contains(suffix); } bool AlbumCoverChoiceController::CanAcceptDrag(const QDragEnterEvent* e) { - foreach (const QUrl& url, e->mimeData()->urls()) { + foreach(const QUrl & url, e->mimeData()->urls()) { const QString suffix = QFileInfo(url.toLocalFile()).suffix().toLower(); - if (IsKnownImageExtension(suffix)) - return true; + if (IsKnownImageExtension(suffix)) return true; } if (e->mimeData()->hasImage()) { return true; @@ -283,7 +295,7 @@ bool AlbumCoverChoiceController::CanAcceptDrag(const QDragEnterEvent* e) { } QString AlbumCoverChoiceController::SaveCover(Song* song, const QDropEvent* e) { - foreach (const QUrl& url, e->mimeData()->urls()) { + foreach(const QUrl & url, e->mimeData()->urls()) { const QString filename = url.toLocalFile(); const QString suffix = QFileInfo(filename).suffix().toLower(); @@ -296,7 +308,8 @@ QString AlbumCoverChoiceController::SaveCover(Song* song, const QDropEvent* e) { if (e->mimeData()->hasImage()) { QImage image = qvariant_cast(e->mimeData()->imageData()); if (!image.isNull()) { - QString cover_path = SaveCoverInCache(song->artist(), song->album(), image); + QString cover_path = + SaveCoverInCache(song->artist(), song->album(), image); SaveCover(song, cover_path); return cover_path; } diff --git a/src/ui/albumcoverchoicecontroller.h b/src/ui/albumcoverchoicecontroller.h index b7e574fe7..e1561b48f 100644 --- a/src/ui/albumcoverchoicecontroller.h +++ b/src/ui/albumcoverchoicecontroller.h @@ -67,11 +67,13 @@ class AlbumCoverChoiceController : public QWidget { // All of the methods below require a currently selected song as an // input parameter. Also - LoadCoverFromFile, LoadCoverFromURL, - // SearchForCover, UnsetCover and SaveCover all update manual path + // SearchForCover, UnsetCover and SaveCover all update manual path // of the given song in library to the new cover. - // Lets the user choose a cover from disk. If no cover will be chosen or the chosen - // cover will not be a proper image, this returns an empty string. Otherwise, the + // Lets the user choose a cover from disk. If no cover will be chosen or the + // chosen + // cover will not be a proper image, this returns an empty string. Otherwise, + // the // path to the chosen cover will be returned. QString LoadCoverFromFile(Song* song); @@ -79,7 +81,8 @@ class AlbumCoverChoiceController : public QWidget { // is supposed to be the cover of the given song's album. void SaveCoverToFile(const Song& song, const QImage& image); - // Downloads the cover from an URL given by user. This returns the downloaded image + // Downloads the cover from an URL given by user. This returns the downloaded + // image // or null image if something went wrong for example when user cancelled the // dialog. QString LoadCoverFromURL(Song* song); @@ -103,20 +106,21 @@ class AlbumCoverChoiceController : public QWidget { // Saves the cover that the user picked through a drag and drop operation. QString SaveCover(Song* song, const QDropEvent* e); - // Saves the given image in cache as a cover for 'artist' - 'album'. + // Saves the given image in cache as a cover for 'artist' - 'album'. // The method returns path of the cached image. - QString SaveCoverInCache(const QString& artist, const QString& album, const QImage& image); + QString SaveCoverInCache(const QString& artist, const QString& album, + const QImage& image); static bool CanAcceptDrag(const QDragEnterEvent* e); signals: void AutomaticCoverSearchDone(); -private slots: + private slots: void AlbumCoverFetched(quint64 id, const QImage& image, const CoverSearchStatistics& statistics); -private: + private: QString GetInitialPathForFileDialog(const Song& song, const QString& filename); @@ -142,4 +146,4 @@ private: QMap cover_fetching_tasks_; }; -#endif // ALBUMCOVERCHOICECONTROLLER_H +#endif // ALBUMCOVERCHOICECONTROLLER_H diff --git a/src/ui/albumcoverexport.cpp b/src/ui/albumcoverexport.cpp index 08f286283..bd73e3219 100644 --- a/src/ui/albumcoverexport.cpp +++ b/src/ui/albumcoverexport.cpp @@ -23,17 +23,14 @@ const char* AlbumCoverExport::kSettingsGroup = "AlbumCoverExport"; AlbumCoverExport::AlbumCoverExport(QWidget* parent) - : QDialog(parent), - ui_(new Ui_AlbumCoverExport) -{ + : QDialog(parent), ui_(new Ui_AlbumCoverExport) { ui_->setupUi(this); - connect(ui_->forceSize, SIGNAL(stateChanged(int)), SLOT(ForceSizeToggled(int))); + connect(ui_->forceSize, SIGNAL(stateChanged(int)), + SLOT(ForceSizeToggled(int))); } -AlbumCoverExport::~AlbumCoverExport() { - delete ui_; -} +AlbumCoverExport::~AlbumCoverExport() { delete ui_; } AlbumCoverExport::DialogResult AlbumCoverExport::Exec() { QSettings s; @@ -41,13 +38,17 @@ AlbumCoverExport::DialogResult AlbumCoverExport::Exec() { // restore last accepted settings ui_->fileName->setText(s.value("fileName", "cover").toString()); - ui_->doNotOverwrite->setChecked(s.value("overwrite", OverwriteMode_None).toInt() == OverwriteMode_None); - ui_->overwriteAll->setChecked(s.value("overwrite", OverwriteMode_All).toInt() == OverwriteMode_All); - ui_->overwriteSmaller->setChecked(s.value("overwrite", OverwriteMode_Smaller).toInt() == OverwriteMode_Smaller); + ui_->doNotOverwrite->setChecked( + s.value("overwrite", OverwriteMode_None).toInt() == OverwriteMode_None); + ui_->overwriteAll->setChecked( + s.value("overwrite", OverwriteMode_All).toInt() == OverwriteMode_All); + ui_->overwriteSmaller->setChecked(s.value("overwrite", OverwriteMode_Smaller) + .toInt() == OverwriteMode_Smaller); ui_->forceSize->setChecked(s.value("forceSize", false).toBool()); ui_->width->setText(s.value("width", "").toString()); ui_->height->setText(s.value("height", "").toString()); - ui_->export_downloaded->setChecked(s.value("export_downloaded", true).toBool()); + ui_->export_downloaded->setChecked( + s.value("export_downloaded", true).toBool()); ui_->export_embedded->setChecked(s.value("export_embedded", false).toBool()); ForceSizeToggled(ui_->forceSize->checkState()); @@ -55,16 +56,16 @@ AlbumCoverExport::DialogResult AlbumCoverExport::Exec() { DialogResult result = DialogResult(); result.cancelled_ = (exec() == QDialog::Rejected); - if(!result.cancelled_) { + if (!result.cancelled_) { QString fileName = ui_->fileName->text(); if (fileName.isEmpty()) { fileName = "cover"; } - OverwriteMode overwrite = ui_->doNotOverwrite->isChecked() - ? OverwriteMode_None - : (ui_->overwriteAll->isChecked() - ? OverwriteMode_All - : OverwriteMode_Smaller); + OverwriteMode overwrite = + ui_->doNotOverwrite->isChecked() + ? OverwriteMode_None + : (ui_->overwriteAll->isChecked() ? OverwriteMode_All + : OverwriteMode_Smaller); bool forceSize = ui_->forceSize->isChecked(); QString width = ui_->width->text(); QString height = ui_->height->text(); diff --git a/src/ui/albumcoverexport.h b/src/ui/albumcoverexport.h index fc099e075..d5531a7bb 100644 --- a/src/ui/albumcoverexport.h +++ b/src/ui/albumcoverexport.h @@ -68,4 +68,4 @@ class AlbumCoverExport : public QDialog { static const char* kSettingsGroup; }; -#endif // ALBUMCOVEREXPORT_H +#endif // ALBUMCOVEREXPORT_H diff --git a/src/ui/albumcovermanager.cpp b/src/ui/albumcovermanager.cpp index 0e56e2341..ddef4cfb0 100644 --- a/src/ui/albumcovermanager.cpp +++ b/src/ui/albumcovermanager.cpp @@ -57,22 +57,22 @@ AlbumCoverManager::AlbumCoverManager(Application* app, LibraryBackend* library_backend, QWidget* parent, QNetworkAccessManager* network) - : QMainWindow(parent), - ui_(new Ui_CoverManager), - app_(app), - album_cover_choice_controller_(new AlbumCoverChoiceController(this)), - cover_fetcher_(new AlbumCoverFetcher(app_->cover_providers(), this, network)), - cover_searcher_(nullptr), - cover_export_(nullptr), - cover_exporter_(new AlbumCoverExporter(this)), - artist_icon_(IconLoader::Load("x-clementine-artist")), - all_artists_icon_(IconLoader::Load("x-clementine-album")), - context_menu_(new QMenu(this)), - progress_bar_(new QProgressBar(this)), - abort_progress_(new QPushButton(this)), - jobs_(0), - library_backend_(library_backend) -{ + : QMainWindow(parent), + ui_(new Ui_CoverManager), + app_(app), + album_cover_choice_controller_(new AlbumCoverChoiceController(this)), + cover_fetcher_( + new AlbumCoverFetcher(app_->cover_providers(), this, network)), + cover_searcher_(nullptr), + cover_export_(nullptr), + cover_exporter_(new AlbumCoverExporter(this)), + artist_icon_(IconLoader::Load("x-clementine-artist")), + all_artists_icon_(IconLoader::Load("x-clementine-album")), + context_menu_(new QMenu(this)), + progress_bar_(new QProgressBar(this)), + abort_progress_(new QPushButton(this)), + jobs_(0), + library_backend_(library_backend) { ui_->setupUi(this); ui_->albums->set_cover_manager(this); @@ -81,19 +81,22 @@ AlbumCoverManager::AlbumCoverManager(Application* app, ui_->export_covers->setIcon(IconLoader::Load("document-save")); ui_->view->setIcon(IconLoader::Load("view-choose")); ui_->fetch->setIcon(IconLoader::Load("download")); - ui_->action_add_to_playlist->setIcon(IconLoader::Load("media-playback-start")); + ui_->action_add_to_playlist->setIcon( + IconLoader::Load("media-playback-start")); ui_->action_load->setIcon(IconLoader::Load("media-playback-start")); album_cover_choice_controller_->SetApplication(app_); // Get a square version of nocover.png QImage nocover(":/nocover.png"); - nocover = nocover.scaled(120, 120, Qt::KeepAspectRatio, Qt::SmoothTransformation); + nocover = + nocover.scaled(120, 120, Qt::KeepAspectRatio, Qt::SmoothTransformation); QImage square_nocover(120, 120, QImage::Format_ARGB32); square_nocover.fill(0); QPainter p(&square_nocover); p.setOpacity(0.4); - p.drawImage((120 - nocover.width()) / 2, (120 - nocover.height()) / 2, nocover); + p.drawImage((120 - nocover.width()) / 2, (120 - nocover.height()) / 2, + nocover); p.end(); no_cover_icon_ = QPixmap::fromImage(square_nocover); @@ -123,9 +126,7 @@ AlbumCoverManager::~AlbumCoverManager() { delete ui_; } -LibraryBackend* AlbumCoverManager::backend() const { - return library_backend_; -} +LibraryBackend* AlbumCoverManager::backend() const { return library_backend_; } void AlbumCoverManager::Init() { // View menu @@ -172,19 +173,24 @@ void AlbumCoverManager::Init() { ui_->albums->installEventFilter(this); // Connections - connect(ui_->artists, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), + connect(ui_->artists, + SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), SLOT(ArtistChanged(QListWidgetItem*))); connect(ui_->filter, SIGNAL(textChanged(QString)), SLOT(UpdateFilter())); connect(filter_group, SIGNAL(triggered(QAction*)), SLOT(UpdateFilter())); connect(ui_->view, SIGNAL(clicked()), ui_->view, SLOT(showMenu())); connect(ui_->fetch, SIGNAL(clicked()), SLOT(FetchAlbumCovers())); connect(ui_->export_covers, SIGNAL(clicked()), SLOT(ExportCovers())); - connect(cover_fetcher_, SIGNAL(AlbumCoverFetched(quint64,QImage,CoverSearchStatistics)), - SLOT(AlbumCoverFetched(quint64,QImage,CoverSearchStatistics))); + connect(cover_fetcher_, + SIGNAL(AlbumCoverFetched(quint64, QImage, CoverSearchStatistics)), + SLOT(AlbumCoverFetched(quint64, QImage, CoverSearchStatistics))); connect(ui_->action_fetch, SIGNAL(triggered()), SLOT(FetchSingleCover())); - connect(ui_->albums, SIGNAL(doubleClicked(QModelIndex)), SLOT(AlbumDoubleClicked(QModelIndex))); - connect(ui_->action_add_to_playlist, SIGNAL(triggered()), SLOT(AddSelectedToPlaylist())); - connect(ui_->action_load, SIGNAL(triggered()), SLOT(LoadSelectedToPlaylist())); + connect(ui_->albums, SIGNAL(doubleClicked(QModelIndex)), + SLOT(AlbumDoubleClicked(QModelIndex))); + connect(ui_->action_add_to_playlist, SIGNAL(triggered()), + SLOT(AddSelectedToPlaylist())); + connect(ui_->action_load, SIGNAL(triggered()), + SLOT(LoadSelectedToPlaylist())); // Restore settings QSettings s; @@ -196,18 +202,15 @@ void AlbumCoverManager::Init() { ui_->splitter->setSizes(QList() << 200 << width() - 200); } - connect(app_->album_cover_loader(), - SIGNAL(ImageLoaded(quint64,QImage)), - SLOT(CoverImageLoaded(quint64,QImage))); + connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)), + SLOT(CoverImageLoaded(quint64, QImage))); cover_searcher_->Init(cover_fetcher_); new ForceScrollPerPixel(ui_->albums, this); } -void AlbumCoverManager::showEvent(QShowEvent *) { - Reset(); -} +void AlbumCoverManager::showEvent(QShowEvent*) { Reset(); } void AlbumCoverManager::closeEvent(QCloseEvent* e) { if (!cover_fetching_tasks_.isEmpty()) { @@ -236,7 +239,7 @@ void AlbumCoverManager::closeEvent(QCloseEvent* e) { void AlbumCoverManager::CancelRequests() { app_->album_cover_loader()->CancelTasks( - QSet::fromList(cover_loading_tasks_.keys())); + QSet::fromList(cover_loading_tasks_.keys())); cover_loading_tasks_.clear(); cover_exporter_->Cancel(); @@ -262,15 +265,16 @@ void AlbumCoverManager::Reset() { EnableCoversButtons(); ui_->artists->clear(); - new QListWidgetItem(all_artists_icon_, tr("All artists"), ui_->artists, All_Artists); - new QListWidgetItem(artist_icon_, tr("Various artists"), ui_->artists, Various_Artists); + new QListWidgetItem(all_artists_icon_, tr("All artists"), ui_->artists, + All_Artists); + new QListWidgetItem(artist_icon_, tr("Various artists"), ui_->artists, + Various_Artists); QStringList artists(library_backend_->GetAllArtistsWithAlbums()); qStableSort(artists.begin(), artists.end(), CompareNocase); - foreach (const QString& artist, artists) { - if (artist.isEmpty()) - continue; + foreach(const QString & artist, artists) { + if (artist.isEmpty()) continue; new QListWidgetItem(artist_icon_, artist, ui_->artists, Specific_Artist); } @@ -287,12 +291,10 @@ void AlbumCoverManager::DisableCoversButtons() { } void AlbumCoverManager::ArtistChanged(QListWidgetItem* current) { - if (!current) - return; + if (!current) return; QString artist; - if (current->type() == Specific_Artist) - artist = current->text(); + if (current->type() == Specific_Artist) artist = current->text(); ui_->albums->clear(); context_menu_items_.clear(); @@ -302,33 +304,41 @@ void AlbumCoverManager::ArtistChanged(QListWidgetItem* current) { // selected in the artist list. LibraryBackend::AlbumList albums; switch (current->type()) { - case Various_Artists: albums = library_backend_->GetCompilationAlbums(); break; - case Specific_Artist: albums = library_backend_->GetAlbumsByArtist(current->text()); break; + case Various_Artists: + albums = library_backend_->GetCompilationAlbums(); + break; + case Specific_Artist: + albums = library_backend_->GetAlbumsByArtist(current->text()); + break; case All_Artists: - default: albums = library_backend_->GetAllAlbums(); break; + default: + albums = library_backend_->GetAllAlbums(); + break; } // Sort by album name. The list is already sorted by sqlite but it was done // case sensitively. qStableSort(albums.begin(), albums.end(), CompareAlbumNameNocase); - foreach (const LibraryBackend::Album& info, albums) { + foreach(const LibraryBackend::Album & info, albums) { // Don't show songs without an album, obviously - if (info.album_name.isEmpty()) - continue; + if (info.album_name.isEmpty()) continue; - QListWidgetItem* item = new QListWidgetItem(no_cover_icon_, info.album_name, ui_->albums); + QListWidgetItem* item = + new QListWidgetItem(no_cover_icon_, info.album_name, ui_->albums); item->setData(Role_ArtistName, info.artist); item->setData(Role_AlbumName, info.album_name); item->setData(Role_FirstUrl, info.first_url); - item->setData(Qt::TextAlignmentRole, QVariant(Qt::AlignTop | Qt::AlignHCenter)); - item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled); + item->setData(Qt::TextAlignmentRole, + QVariant(Qt::AlignTop | Qt::AlignHCenter)); + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | + Qt::ItemIsDragEnabled); item->setToolTip(info.artist + " - " + info.album_name); if (!info.art_automatic.isEmpty() || !info.art_manual.isEmpty()) { quint64 id = app_->album_cover_loader()->LoadImageAsync( - cover_loader_options_, - info.art_automatic, info.art_manual, info.first_url.toLocalFile()); + cover_loader_options_, info.art_automatic, info.art_manual, + info.first_url.toLocalFile()); item->setData(Role_PathAutomatic, info.art_automatic); item->setData(Role_PathManual, info.art_manual); cover_loading_tasks_[id] = item; @@ -338,14 +348,12 @@ void AlbumCoverManager::ArtistChanged(QListWidgetItem* current) { UpdateFilter(); } -void AlbumCoverManager::CoverImageLoaded(quint64 id, const QImage &image) { - if (!cover_loading_tasks_.contains(id)) - return; +void AlbumCoverManager::CoverImageLoaded(quint64 id, const QImage& image) { + if (!cover_loading_tasks_.contains(id)) return; QListWidgetItem* item = cover_loading_tasks_.take(id); - if (image.isNull()) - return; + if (image.isNull()) return; item->setIcon(QPixmap::fromImage(image)); UpdateFilter(); @@ -383,8 +391,9 @@ void AlbumCoverManager::UpdateFilter() { ui_->without_cover->setText(QString::number(without_cover)); } -bool AlbumCoverManager::ShouldHide( - const QListWidgetItem& item, const QString& filter, HideCovers hide) const { +bool AlbumCoverManager::ShouldHide(const QListWidgetItem& item, + const QString& filter, + HideCovers hide) const { bool has_cover = item.icon().cacheKey() != no_cover_icon_.cacheKey(); if (hide == Hide_WithCovers && has_cover) { return true; @@ -397,9 +406,10 @@ bool AlbumCoverManager::ShouldHide( } QStringList query = filter.split(' '); - foreach (const QString& s, query) { - if (!item.text().contains(s, Qt::CaseInsensitive) - && !item.data(Role_ArtistName).toString().contains(s, Qt::CaseInsensitive)) { + foreach(const QString & s, query) { + if (!item.text().contains(s, Qt::CaseInsensitive) && + !item.data(Role_ArtistName).toString().contains(s, + Qt::CaseInsensitive)) { return true; } } @@ -408,21 +418,19 @@ bool AlbumCoverManager::ShouldHide( } void AlbumCoverManager::FetchAlbumCovers() { - for (int i=0 ; ialbums->count() ; ++i) { + for (int i = 0; i < ui_->albums->count(); ++i) { QListWidgetItem* item = ui_->albums->item(i); - if (item->isHidden()) - continue; - if (item->icon().cacheKey() != no_cover_icon_.cacheKey()) - continue; + if (item->isHidden()) continue; + if (item->icon().cacheKey() != no_cover_icon_.cacheKey()) continue; - quint64 id = cover_fetcher_->FetchAlbumCover( - item->data(Role_ArtistName).toString(), item->data(Role_AlbumName).toString()); + quint64 id = + cover_fetcher_->FetchAlbumCover(item->data(Role_ArtistName).toString(), + item->data(Role_AlbumName).toString()); cover_fetching_tasks_[id] = item; - jobs_ ++; + jobs_++; } - if (!cover_fetching_tasks_.isEmpty()) - ui_->fetch->setEnabled(false); + if (!cover_fetching_tasks_.isEmpty()) ui_->fetch->setEnabled(false); progress_bar_->setMaximum(jobs_); progress_bar_->show(); @@ -431,10 +439,9 @@ void AlbumCoverManager::FetchAlbumCovers() { UpdateStatusText(); } -void AlbumCoverManager::AlbumCoverFetched(quint64 id, const QImage& image, - const CoverSearchStatistics& statistics) { - if (!cover_fetching_tasks_.contains(id)) - return; +void AlbumCoverManager::AlbumCoverFetched( + quint64 id, const QImage& image, const CoverSearchStatistics& statistics) { + if (!cover_fetching_tasks_.contains(id)) return; QListWidgetItem* item = cover_fetching_tasks_.take(id); if (!image.isNull()) { @@ -451,13 +458,13 @@ void AlbumCoverManager::AlbumCoverFetched(quint64 id, const QImage& image, void AlbumCoverManager::UpdateStatusText() { QString message = tr("Got %1 covers out of %2 (%3 failed)") - .arg(fetch_statistics_.chosen_images_) - .arg(jobs_) - .arg(fetch_statistics_.missing_images_); + .arg(fetch_statistics_.chosen_images_) + .arg(jobs_) + .arg(fetch_statistics_.missing_images_); if (fetch_statistics_.bytes_transferred_) { - message += ", " + tr("%1 transferred") - .arg(Utilities::PrettySize(fetch_statistics_.bytes_transferred_)); + message += ", " + tr("%1 transferred").arg(Utilities::PrettySize( + fetch_statistics_.bytes_transferred_)); } statusBar()->showMessage(message); @@ -477,24 +484,28 @@ void AlbumCoverManager::UpdateStatusText() { } } -bool AlbumCoverManager::eventFilter(QObject *obj, QEvent *event) { +bool AlbumCoverManager::eventFilter(QObject* obj, QEvent* event) { if (obj == ui_->albums && event->type() == QEvent::ContextMenu) { context_menu_items_ = ui_->albums->selectedItems(); - if (context_menu_items_.isEmpty()) - return false; + if (context_menu_items_.isEmpty()) return false; bool some_with_covers = false; - foreach (QListWidgetItem* item, context_menu_items_) { + foreach(QListWidgetItem * item, context_menu_items_) { if (item->icon().cacheKey() != no_cover_icon_.cacheKey()) some_with_covers = true; } - album_cover_choice_controller_->cover_from_file_action()->setEnabled(context_menu_items_.size() == 1); - album_cover_choice_controller_->cover_from_url_action()->setEnabled(context_menu_items_.size() == 1); - album_cover_choice_controller_->show_cover_action()->setEnabled(some_with_covers && context_menu_items_.size() == 1); - album_cover_choice_controller_->unset_cover_action()->setEnabled(some_with_covers); - album_cover_choice_controller_->search_for_cover_action()->setEnabled(app_->cover_providers()->HasAnyProviders()); + album_cover_choice_controller_->cover_from_file_action()->setEnabled( + context_menu_items_.size() == 1); + album_cover_choice_controller_->cover_from_url_action()->setEnabled( + context_menu_items_.size() == 1); + album_cover_choice_controller_->show_cover_action()->setEnabled( + some_with_covers && context_menu_items_.size() == 1); + album_cover_choice_controller_->unset_cover_action()->setEnabled( + some_with_covers); + album_cover_choice_controller_->search_for_cover_action()->setEnabled( + app_->cover_providers()->HasAnyProviders()); QContextMenuEvent* e = static_cast(event); context_menu_->popup(e->globalPos()); @@ -504,15 +515,13 @@ bool AlbumCoverManager::eventFilter(QObject *obj, QEvent *event) { } Song AlbumCoverManager::GetSingleSelectionAsSong() { - return context_menu_items_.size() != 1 - ? Song() - : ItemAsSong(context_menu_items_[0]); + return context_menu_items_.size() != 1 ? Song() + : ItemAsSong(context_menu_items_[0]); } Song AlbumCoverManager::GetFirstSelectedAsSong() { - return context_menu_items_.isEmpty() - ? Song() - : ItemAsSong(context_menu_items_[0]); + return context_menu_items_.isEmpty() ? Song() + : ItemAsSong(context_menu_items_[0]); } Song AlbumCoverManager::ItemAsSong(QListWidgetItem* item) { @@ -541,18 +550,18 @@ Song AlbumCoverManager::ItemAsSong(QListWidgetItem* item) { void AlbumCoverManager::ShowCover() { Song song = GetSingleSelectionAsSong(); - if(!song.is_valid()) - return; + if (!song.is_valid()) return; album_cover_choice_controller_->ShowCover(song); } void AlbumCoverManager::FetchSingleCover() { - foreach (QListWidgetItem* item, context_menu_items_) { - quint64 id = cover_fetcher_->FetchAlbumCover( - item->data(Role_ArtistName).toString(), item->data(Role_AlbumName).toString()); + foreach(QListWidgetItem * item, context_menu_items_) { + quint64 id = + cover_fetcher_->FetchAlbumCover(item->data(Role_ArtistName).toString(), + item->data(Role_AlbumName).toString()); cover_fetching_tasks_[id] = item; - jobs_ ++; + jobs_++; } progress_bar_->setMaximum(jobs_); @@ -561,18 +570,17 @@ void AlbumCoverManager::FetchSingleCover() { UpdateStatusText(); } - -void AlbumCoverManager::UpdateCoverInList(QListWidgetItem* item, const QString& cover) { - quint64 id = app_->album_cover_loader()->LoadImageAsync( - cover_loader_options_, QString(), cover); +void AlbumCoverManager::UpdateCoverInList(QListWidgetItem* item, + const QString& cover) { + quint64 id = app_->album_cover_loader()->LoadImageAsync(cover_loader_options_, + QString(), cover); item->setData(Role_PathManual, cover); cover_loading_tasks_[id] = item; } void AlbumCoverManager::LoadCoverFromFile() { Song song = GetSingleSelectionAsSong(); - if(!song.is_valid()) - return; + if (!song.is_valid()) return; QListWidgetItem* item = context_menu_items_[0]; @@ -585,18 +593,18 @@ void AlbumCoverManager::LoadCoverFromFile() { void AlbumCoverManager::SaveCoverToFile() { Song song = GetSingleSelectionAsSong(); - if(!song.is_valid()) - return; + if (!song.is_valid()) return; QImage image; // load the image from disk - if(song.has_manually_unset_cover()) { + if (song.has_manually_unset_cover()) { image = QImage(":/nocover.png"); } else { - if(!song.art_manual().isEmpty() && QFile::exists(song.art_manual())) { + if (!song.art_manual().isEmpty() && QFile::exists(song.art_manual())) { image = QImage(song.art_manual()); - } else if(!song.art_automatic().isEmpty() && QFile::exists(song.art_automatic())) { + } else if (!song.art_automatic().isEmpty() && + QFile::exists(song.art_automatic())) { image = QImage(song.art_automatic()); } else { image = QImage(":/nocover.png"); @@ -608,8 +616,7 @@ void AlbumCoverManager::SaveCoverToFile() { void AlbumCoverManager::LoadCoverFromURL() { Song song = GetSingleSelectionAsSong(); - if(!song.is_valid()) - return; + if (!song.is_valid()) return; QListWidgetItem* item = context_menu_items_[0]; @@ -622,19 +629,17 @@ void AlbumCoverManager::LoadCoverFromURL() { void AlbumCoverManager::SearchForCover() { Song song = GetFirstSelectedAsSong(); - if(!song.is_valid()) - return; + if (!song.is_valid()) return; QListWidgetItem* item = context_menu_items_[0]; QString cover = album_cover_choice_controller_->SearchForCover(&song); - if (cover.isEmpty()) - return; + if (cover.isEmpty()) return; // force the found cover on all of the selected items - foreach (QListWidgetItem* current, context_menu_items_) { + foreach(QListWidgetItem * current, context_menu_items_) { // don't save the first one twice - if(current != item) { + if (current != item) { Song current_song = ItemAsSong(current); album_cover_choice_controller_->SaveCover(¤t_song, cover); } @@ -645,20 +650,19 @@ void AlbumCoverManager::SearchForCover() { void AlbumCoverManager::UnsetCover() { Song song = GetFirstSelectedAsSong(); - if(!song.is_valid()) - return; + if (!song.is_valid()) return; QListWidgetItem* item = context_menu_items_[0]; QString cover = album_cover_choice_controller_->UnsetCover(&song); // force the 'none' cover on all of the selected items - foreach (QListWidgetItem* current, context_menu_items_) { + foreach(QListWidgetItem * current, context_menu_items_) { current->setIcon(no_cover_icon_); current->setData(Role_PathManual, cover); // don't save the first one twice - if(current != item) { + if (current != item) { Song current_song = ItemAsSong(current); album_cover_choice_controller_->SaveCover(¤t_song, cover); } @@ -675,11 +679,9 @@ SongList AlbumCoverManager::GetSongsInAlbum(const QModelIndex& index) const { QString artist = index.data(Role_ArtistName).toString(); q.AddCompilationRequirement(artist.isEmpty()); - if (!artist.isEmpty()) - q.AddWhere("artist", artist); + if (!artist.isEmpty()) q.AddWhere("artist", artist); - if (!library_backend_->ExecQuery(&q)) - return ret; + if (!library_backend_->ExecQuery(&q)) return ret; while (q.Next()) { Song song; @@ -689,18 +691,17 @@ SongList AlbumCoverManager::GetSongsInAlbum(const QModelIndex& index) const { return ret; } -SongList AlbumCoverManager::GetSongsInAlbums(const QModelIndexList& indexes) const { +SongList AlbumCoverManager::GetSongsInAlbums(const QModelIndexList& indexes) + const { SongList ret; - foreach (const QModelIndex& index, indexes) { - ret << GetSongsInAlbum(index); - } + foreach(const QModelIndex & index, indexes) { ret << GetSongsInAlbum(index); } return ret; } -SongMimeData* AlbumCoverManager::GetMimeDataForAlbums(const QModelIndexList& indexes) const { +SongMimeData* AlbumCoverManager::GetMimeDataForAlbums( + const QModelIndexList& indexes) const { SongList songs = GetSongsInAlbums(indexes); - if (songs.isEmpty()) - return nullptr; + if (songs.isEmpty()) return nullptr; SongMimeData* data = new SongMimeData; data->backend = library_backend_; @@ -708,7 +709,7 @@ SongMimeData* AlbumCoverManager::GetMimeDataForAlbums(const QModelIndexList& ind return data; } -void AlbumCoverManager::AlbumDoubleClicked(const QModelIndex &index) { +void AlbumCoverManager::AlbumDoubleClicked(const QModelIndex& index) { SongMimeData* data = GetMimeDataForAlbums(QModelIndexList() << index); if (data) { data->from_doubleclick_ = true; @@ -717,29 +718,33 @@ void AlbumCoverManager::AlbumDoubleClicked(const QModelIndex &index) { } void AlbumCoverManager::AddSelectedToPlaylist() { - emit AddToPlaylist(GetMimeDataForAlbums(ui_->albums->selectionModel()->selectedIndexes())); + emit AddToPlaylist( + GetMimeDataForAlbums(ui_->albums->selectionModel()->selectedIndexes())); } void AlbumCoverManager::LoadSelectedToPlaylist() { - SongMimeData* data = GetMimeDataForAlbums(ui_->albums->selectionModel()->selectedIndexes()); + SongMimeData* data = + GetMimeDataForAlbums(ui_->albums->selectionModel()->selectedIndexes()); if (data) { data->clear_first_ = true; emit AddToPlaylist(data); } } -void AlbumCoverManager::SaveAndSetCover(QListWidgetItem *item, const QImage &image) { +void AlbumCoverManager::SaveAndSetCover(QListWidgetItem* item, + const QImage& image) { const QString artist = item->data(Role_ArtistName).toString(); const QString album = item->data(Role_AlbumName).toString(); - QString path = album_cover_choice_controller_->SaveCoverInCache(artist, album, image); + QString path = + album_cover_choice_controller_->SaveCoverInCache(artist, album, image); // Save the image in the database library_backend_->UpdateManualAlbumArtAsync(artist, album, path); // Update the icon in our list - quint64 id = app_->album_cover_loader()->LoadImageAsync( - cover_loader_options_, QString(), path); + quint64 id = app_->album_cover_loader()->LoadImageAsync(cover_loader_options_, + QString(), path); item->setData(Role_PathManual, path); cover_loading_tasks_[id] = item; } @@ -747,7 +752,7 @@ void AlbumCoverManager::SaveAndSetCover(QListWidgetItem *item, const QImage &ima void AlbumCoverManager::ExportCovers() { AlbumCoverExport::DialogResult result = cover_export_->Exec(); - if(result.cancelled_) { + if (result.cancelled_) { return; } @@ -755,11 +760,12 @@ void AlbumCoverManager::ExportCovers() { cover_exporter_->SetDialogResult(result); - for (int i=0 ; ialbums->count() ; ++i) { + for (int i = 0; i < ui_->albums->count(); ++i) { QListWidgetItem* item = ui_->albums->item(i); // skip hidden and coverless albums - if (item->isHidden() || item->icon().cacheKey() == no_cover_icon_.cacheKey()) { + if (item->isHidden() || + item->icon().cacheKey() == no_cover_icon_.cacheKey()) { continue; } @@ -784,13 +790,13 @@ void AlbumCoverManager::UpdateExportStatus(int exported, int skipped, int max) { progress_bar_->setValue(exported); QString message = tr("Exported %1 covers out of %2 (%3 skipped)") - .arg(exported) - .arg(max) - .arg(skipped); + .arg(exported) + .arg(max) + .arg(skipped); statusBar()->showMessage(message); // end of the current process - if(exported + skipped >= max) { + if (exported + skipped >= max) { QTimer::singleShot(2000, statusBar(), SLOT(clearMessage())); progress_bar_->hide(); diff --git a/src/ui/albumcovermanager.h b/src/ui/albumcovermanager.h index 30d1287dc..5efa126f6 100644 --- a/src/ui/albumcovermanager.h +++ b/src/ui/albumcovermanager.h @@ -47,10 +47,8 @@ class QProgressBar; class AlbumCoverManager : public QMainWindow { Q_OBJECT public: - AlbumCoverManager(Application* app, - LibraryBackend* library_backend, - QWidget* parent = 0, - QNetworkAccessManager* network = 0); + AlbumCoverManager(Application* app, LibraryBackend* library_backend, + QWidget* parent = 0, QNetworkAccessManager* network = 0); ~AlbumCoverManager(); static const char* kSettingsGroup; @@ -68,15 +66,15 @@ class AlbumCoverManager : public QMainWindow { SongList GetSongsInAlbums(const QModelIndexList& indexes) const; SongMimeData* GetMimeDataForAlbums(const QModelIndexList& indexes) const; - signals: +signals: void AddToPlaylist(QMimeData* data); protected: - void showEvent(QShowEvent *); - void closeEvent(QCloseEvent *); + void showEvent(QShowEvent*); + void closeEvent(QCloseEvent*); // For the album view context menu events - bool eventFilter(QObject *obj, QEvent *event); + bool eventFilter(QObject* obj, QEvent* event); private slots: void ArtistChanged(QListWidgetItem* current); @@ -107,11 +105,7 @@ class AlbumCoverManager : public QMainWindow { void UpdateExportStatus(int exported, int bad, int count); private: - enum ArtistItemType { - All_Artists, - Various_Artists, - Specific_Artist, - }; + enum ArtistItemType { All_Artists, Various_Artists, Specific_Artist, }; enum Role { Role_ArtistName = Qt::UserRole + 1, @@ -121,15 +115,12 @@ class AlbumCoverManager : public QMainWindow { Role_FirstUrl, }; - enum HideCovers { - Hide_None, - Hide_WithCovers, - Hide_WithoutCovers, - }; + enum HideCovers { Hide_None, Hide_WithCovers, Hide_WithoutCovers, }; - QString InitialPathForOpenCoverDialog(const QString& path_automatic, const QString& first_file_name) const; + QString InitialPathForOpenCoverDialog(const QString& path_automatic, + const QString& first_file_name) const; - // Returns the selected element in form of a Song ready to be used + // Returns the selected element in form of a Song ready to be used // by AlbumCoverChoiceController or invalid song if there's nothing // or multiple elements selected. Song GetSingleSelectionAsSong(); @@ -141,7 +132,8 @@ class AlbumCoverManager : public QMainWindow { Song ItemAsSong(QListWidgetItem* item); void UpdateStatusText(); - bool ShouldHide(const QListWidgetItem& item, const QString& filter, HideCovers hide) const; + bool ShouldHide(const QListWidgetItem& item, const QString& filter, + HideCovers hide) const; void SaveAndSetCover(QListWidgetItem* item, const QImage& image); private: @@ -184,4 +176,4 @@ class AlbumCoverManager : public QMainWindow { FRIEND_TEST(AlbumCoverManagerTest, HidesItemsWithFilter); }; -#endif // ALBUMCOVERMANAGER_H +#endif // ALBUMCOVERMANAGER_H diff --git a/src/ui/albumcovermanagerlist.cpp b/src/ui/albumcovermanagerlist.cpp index bc3b9120f..7a7f83b86 100644 --- a/src/ui/albumcovermanagerlist.cpp +++ b/src/ui/albumcovermanagerlist.cpp @@ -26,27 +26,22 @@ #include "library/librarybackend.h" #include "playlist/songmimedata.h" -AlbumCoverManagerList::AlbumCoverManagerList(QWidget *parent) - : QListWidget(parent), - manager_(nullptr) -{ -} +AlbumCoverManagerList::AlbumCoverManagerList(QWidget* parent) + : QListWidget(parent), manager_(nullptr) {} -QMimeData* AlbumCoverManagerList::mimeData(const QList items) const { +QMimeData* AlbumCoverManagerList::mimeData(const QList items) + const { // Get songs SongList songs; - foreach (QListWidgetItem* item, items) { + foreach(QListWidgetItem * item, items) { songs << manager_->GetSongsInAlbum(indexFromItem(item)); } - if (songs.isEmpty()) - return nullptr; + if (songs.isEmpty()) return nullptr; // Get URLs from the songs QList urls; - foreach (const Song& song, songs) { - urls << song.url(); - } + foreach(const Song & song, songs) { urls << song.url(); } // Get the QAbstractItemModel data so the picture works std::unique_ptr orig_data(QListWidget::mimeData(items)); @@ -55,7 +50,8 @@ QMimeData* AlbumCoverManagerList::mimeData(const QList items) mime_data->backend = manager_->backend(); mime_data->songs = songs; mime_data->setUrls(urls); - mime_data->setData(orig_data->formats()[0], orig_data->data(orig_data->formats()[0])); + mime_data->setData(orig_data->formats()[0], + orig_data->data(orig_data->formats()[0])); return mime_data; } diff --git a/src/ui/albumcovermanagerlist.h b/src/ui/albumcovermanagerlist.h index 174af171b..41078e129 100644 --- a/src/ui/albumcovermanagerlist.h +++ b/src/ui/albumcovermanagerlist.h @@ -24,17 +24,17 @@ class AlbumCoverManager; class AlbumCoverManagerList : public QListWidget { Q_OBJECT -public: - AlbumCoverManagerList(QWidget *parent = 0); + public: + AlbumCoverManagerList(QWidget* parent = 0); void set_cover_manager(AlbumCoverManager* manager) { manager_ = manager; } -protected: + protected: QMimeData* mimeData(const QList items) const; - void dropEvent(QDropEvent *event); + void dropEvent(QDropEvent* event); -private: + private: AlbumCoverManager* manager_; }; -#endif // ALBUMCOVERMANAGERLIST_H +#endif // ALBUMCOVERMANAGERLIST_H diff --git a/src/ui/albumcoversearcher.cpp b/src/ui/albumcoversearcher.cpp index ef6204a3b..8421af66d 100644 --- a/src/ui/albumcoversearcher.cpp +++ b/src/ui/albumcoversearcher.cpp @@ -38,11 +38,8 @@ const qreal SizeOverlayDelegate::kFontPointSize = 7.5; const int SizeOverlayDelegate::kBorderAlpha = 200; const int SizeOverlayDelegate::kBackgroundAlpha = 175; - SizeOverlayDelegate::SizeOverlayDelegate(QObject* parent) - : QStyledItemDelegate(parent) -{ -} + : QStyledItemDelegate(parent) {} void SizeOverlayDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, @@ -64,17 +61,16 @@ void SizeOverlayDelegate::paint(QPainter* painter, const int text_width = metrics.width(text); - const QRect icon_rect( - option.rect.left(), option.rect.top(), - option.rect.width(), option.rect.width()); + const QRect icon_rect(option.rect.left(), option.rect.top(), + option.rect.width(), option.rect.width()); const QRect background_rect( - icon_rect.right() - kMargin - text_width - kPaddingX*2, - icon_rect.bottom() - kMargin - metrics.height() - kPaddingY*2, - text_width + kPaddingX*2, metrics.height() + kPaddingY*2); - const QRect text_rect( - background_rect.left() + kPaddingX, background_rect.top() + kPaddingY, - text_width, metrics.height()); + icon_rect.right() - kMargin - text_width - kPaddingX * 2, + icon_rect.bottom() - kMargin - metrics.height() - kPaddingY * 2, + text_width + kPaddingX * 2, metrics.height() + kPaddingY * 2); + const QRect text_rect(background_rect.left() + kPaddingX, + background_rect.top() + kPaddingY, text_width, + metrics.height()); painter->save(); painter->setRenderHint(QPainter::Antialiasing); @@ -88,17 +84,15 @@ void SizeOverlayDelegate::paint(QPainter* painter, painter->restore(); } - AlbumCoverSearcher::AlbumCoverSearcher(const QIcon& no_cover_icon, Application* app, QWidget* parent) - : QDialog(parent), - ui_(new Ui_AlbumCoverSearcher), - app_(app), - model_(new QStandardItemModel(this)), - no_cover_icon_(no_cover_icon), - fetcher_(nullptr), - id_(0) -{ + : QDialog(parent), + ui_(new Ui_AlbumCoverSearcher), + app_(app), + model_(new QStandardItemModel(this)), + no_cover_icon_(no_cover_icon), + fetcher_(nullptr), + id_(0) { setWindowModality(Qt::WindowModal); ui_->setupUi(this); ui_->busy->hide(); @@ -111,27 +105,27 @@ AlbumCoverSearcher::AlbumCoverSearcher(const QIcon& no_cover_icon, options_.scale_output_image_ = false; options_.pad_output_image_ = false; - connect(app_->album_cover_loader(), - SIGNAL(ImageLoaded(quint64,QImage)), - SLOT(ImageLoaded(quint64,QImage))); + connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)), + SLOT(ImageLoaded(quint64, QImage))); connect(ui_->search, SIGNAL(clicked()), SLOT(Search())); - connect(ui_->covers, SIGNAL(doubleClicked(QModelIndex)), SLOT(CoverDoubleClicked(QModelIndex))); + connect(ui_->covers, SIGNAL(doubleClicked(QModelIndex)), + SLOT(CoverDoubleClicked(QModelIndex))); new ForceScrollPerPixel(ui_->covers, this); - ui_->buttonBox->button(QDialogButtonBox::Cancel)->setShortcut(QKeySequence::Close); + ui_->buttonBox->button(QDialogButtonBox::Cancel) + ->setShortcut(QKeySequence::Close); } -AlbumCoverSearcher::~AlbumCoverSearcher() { - delete ui_; -} +AlbumCoverSearcher::~AlbumCoverSearcher() { delete ui_; } void AlbumCoverSearcher::Init(AlbumCoverFetcher* fetcher) { fetcher_ = fetcher; - connect(fetcher_, SIGNAL(SearchFinished(quint64,CoverSearchResults,CoverSearchStatistics)), - SLOT(SearchFinished(quint64,CoverSearchResults))); + connect(fetcher_, SIGNAL(SearchFinished(quint64, CoverSearchResults, + CoverSearchStatistics)), + SLOT(SearchFinished(quint64, CoverSearchResults))); } QImage AlbumCoverSearcher::Exec(const QString& artist, const QString& album) { @@ -139,20 +133,18 @@ QImage AlbumCoverSearcher::Exec(const QString& artist, const QString& album) { ui_->album->setText(album); ui_->artist->setFocus(); - if(!artist.isEmpty() || !album.isEmpty()) { + if (!artist.isEmpty() || !album.isEmpty()) { Search(); } - if (exec() == QDialog::Rejected) - return QImage(); + if (exec() == QDialog::Rejected) return QImage(); QModelIndex selected = ui_->covers->currentIndex(); if (!selected.isValid() || !selected.data(Role_ImageFetchFinished).toBool()) return QImage(); QIcon icon = selected.data(Qt::DecorationRole).value(); - if (icon.cacheKey() == no_cover_icon_.cacheKey()) - return QImage(); + if (icon.cacheKey() == no_cover_icon_.cacheKey()) return QImage(); return icon.pixmap(icon.availableSizes()[0]).toImage(); } @@ -179,9 +171,9 @@ void AlbumCoverSearcher::Search() { } } -void AlbumCoverSearcher::SearchFinished(quint64 id, const CoverSearchResults& results) { - if (id != id_) - return; +void AlbumCoverSearcher::SearchFinished(quint64 id, + const CoverSearchResults& results) { + if (id != id_) return; ui_->search->setEnabled(true); ui_->artist->setEnabled(true); @@ -190,12 +182,11 @@ void AlbumCoverSearcher::SearchFinished(quint64 id, const CoverSearchResults& re ui_->search->setText(tr("Search")); id_ = 0; - foreach (const CoverSearchResult& result, results) { - if (result.image_url.isEmpty()) - continue; + foreach(const CoverSearchResult & result, results) { + if (result.image_url.isEmpty()) continue; quint64 id = app_->album_cover_loader()->LoadImageAsync( - options_, result.image_url.toString(), QString()); + options_, result.image_url.toString(), QString()); QStandardItem* item = new QStandardItem; item->setIcon(no_cover_icon_); @@ -203,7 +194,8 @@ void AlbumCoverSearcher::SearchFinished(quint64 id, const CoverSearchResults& re item->setData(result.image_url, Role_ImageURL); item->setData(id, Role_ImageRequestId); item->setData(false, Role_ImageFetchFinished); - item->setData(QVariant(Qt::AlignTop | Qt::AlignHCenter), Qt::TextAlignmentRole); + item->setData(QVariant(Qt::AlignTop | Qt::AlignHCenter), + Qt::TextAlignmentRole); item->setData(result.provider, GroupedIconView::Role_Group); model_->appendRow(item); @@ -211,17 +203,14 @@ void AlbumCoverSearcher::SearchFinished(quint64 id, const CoverSearchResults& re cover_loading_tasks_[id] = item; } - if (cover_loading_tasks_.isEmpty()) - ui_->busy->hide(); + if (cover_loading_tasks_.isEmpty()) ui_->busy->hide(); } void AlbumCoverSearcher::ImageLoaded(quint64 id, const QImage& image) { - if (!cover_loading_tasks_.contains(id)) - return; + if (!cover_loading_tasks_.contains(id)) return; QStandardItem* item = cover_loading_tasks_.take(id); - if (cover_loading_tasks_.isEmpty()) - ui_->busy->hide(); + if (cover_loading_tasks_.isEmpty()) ui_->busy->hide(); if (image.isNull()) { model_->removeRow(item->row()); @@ -231,11 +220,11 @@ void AlbumCoverSearcher::ImageLoaded(quint64 id, const QImage& image) { QIcon icon(QPixmap::fromImage(image)); // Create a pixmap that's padded and exactly the right size for the icon. - QImage scaled_image(image.scaled(ui_->covers->iconSize(), - Qt::KeepAspectRatio, + QImage scaled_image(image.scaled(ui_->covers->iconSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - QImage padded_image(ui_->covers->iconSize(), QImage::Format_ARGB32_Premultiplied); + QImage padded_image(ui_->covers->iconSize(), + QImage::Format_ARGB32_Premultiplied); padded_image.fill(0); QPainter p(&padded_image); @@ -253,8 +242,7 @@ void AlbumCoverSearcher::ImageLoaded(quint64 id, const QImage& image) { } void AlbumCoverSearcher::keyPressEvent(QKeyEvent* e) { - if (e->key() == Qt::Key_Enter || - e->key() == Qt::Key_Return) { + if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) { e->ignore(); return; } @@ -262,7 +250,6 @@ void AlbumCoverSearcher::keyPressEvent(QKeyEvent* e) { QDialog::keyPressEvent(e); } -void AlbumCoverSearcher::CoverDoubleClicked(const QModelIndex &index) { - if (index.isValid()) - accept(); +void AlbumCoverSearcher::CoverDoubleClicked(const QModelIndex& index) { + if (index.isValid()) accept(); } diff --git a/src/ui/albumcoversearcher.h b/src/ui/albumcoversearcher.h index f028cce40..b460639f4 100644 --- a/src/ui/albumcoversearcher.h +++ b/src/ui/albumcoversearcher.h @@ -34,7 +34,7 @@ class QStandardItem; class QStandardItemModel; class SizeOverlayDelegate : public QStyledItemDelegate { -public: + public: static const int kMargin; static const int kPaddingX; static const int kPaddingY; @@ -49,20 +49,20 @@ public: const QModelIndex& index) const; }; - // This is a dialog that lets the user search for album covers class AlbumCoverSearcher : public QDialog { Q_OBJECT -public: - AlbumCoverSearcher(const QIcon& no_cover_icon, Application* app, QWidget* parent); + public: + AlbumCoverSearcher(const QIcon& no_cover_icon, Application* app, + QWidget* parent); ~AlbumCoverSearcher(); enum Role { Role_ImageURL = Qt::UserRole + 1, Role_ImageRequestId, Role_ImageFetchFinished, - Role_ImageDimensions, // width * height + Role_ImageDimensions, // width * height Role_ImageSize, }; @@ -70,17 +70,17 @@ public: QImage Exec(const QString& artist, const QString& album); -protected: - void keyPressEvent(QKeyEvent *); + protected: + void keyPressEvent(QKeyEvent*); -private slots: + private slots: void Search(); void SearchFinished(quint64 id, const CoverSearchResults& results); void ImageLoaded(quint64 id, const QImage& image); void CoverDoubleClicked(const QModelIndex& index); -private: + private: Ui_AlbumCoverSearcher* ui_; Application* app_; @@ -94,4 +94,4 @@ private: QMap cover_loading_tasks_; }; -#endif // ALBUMCOVERSEARCHER_H +#endif // ALBUMCOVERSEARCHER_H diff --git a/src/ui/appearancesettingspage.cpp b/src/ui/appearancesettingspage.cpp index 866a843e8..77c79a380 100644 --- a/src/ui/appearancesettingspage.cpp +++ b/src/ui/appearancesettingspage.cpp @@ -35,51 +35,54 @@ #include "ui/albumcoverchoicecontroller.h" #ifdef HAVE_MOODBAR -# include "moodbar/moodbarrenderer.h" +#include "moodbar/moodbarrenderer.h" #endif const int AppearanceSettingsPage::kMoodbarPreviewWidth = 150; const int AppearanceSettingsPage::kMoodbarPreviewHeight = 18; AppearanceSettingsPage::AppearanceSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_AppearanceSettingsPage), - original_use_a_custom_color_set_(false), - playlist_view_background_image_type_(PlaylistView::Default), - initialised_moodbar_previews_(false) -{ + : SettingsPage(dialog), + ui_(new Ui_AppearanceSettingsPage), + original_use_a_custom_color_set_(false), + playlist_view_background_image_type_(PlaylistView::Default), + initialised_moodbar_previews_(false) { ui_->setupUi(this); setWindowIcon(IconLoader::Load("view-media-visualization")); - connect(ui_->blur_slider, SIGNAL(valueChanged(int)), SLOT(BlurLevelChanged(int))); - connect(ui_->opacity_slider, SIGNAL(valueChanged(int)), SLOT(OpacityLevelChanged(int))); + connect(ui_->blur_slider, SIGNAL(valueChanged(int)), + SLOT(BlurLevelChanged(int))); + connect(ui_->opacity_slider, SIGNAL(valueChanged(int)), + SLOT(OpacityLevelChanged(int))); Load(); - connect(ui_->select_foreground_color, SIGNAL(pressed()), SLOT(SelectForegroundColor())); - connect(ui_->select_background_color, SIGNAL(pressed()), SLOT(SelectBackgroundColor())); - connect(ui_->use_a_custom_color_set, SIGNAL(toggled(bool)), SLOT(UseCustomColorSetOptionChanged(bool))); + connect(ui_->select_foreground_color, SIGNAL(pressed()), + SLOT(SelectForegroundColor())); + connect(ui_->select_background_color, SIGNAL(pressed()), + SLOT(SelectBackgroundColor())); + connect(ui_->use_a_custom_color_set, SIGNAL(toggled(bool)), + SLOT(UseCustomColorSetOptionChanged(bool))); - connect(ui_->select_background_image_filename_button, SIGNAL(pressed()), SLOT(SelectBackgroundImage())); + connect(ui_->select_background_image_filename_button, SIGNAL(pressed()), + SLOT(SelectBackgroundImage())); connect(ui_->use_custom_background_image, SIGNAL(toggled(bool)), - ui_->background_image_filename, SLOT(setEnabled(bool))); + ui_->background_image_filename, SLOT(setEnabled(bool))); connect(ui_->use_custom_background_image, SIGNAL(toggled(bool)), - ui_->select_background_image_filename_button, SLOT(setEnabled(bool))); + ui_->select_background_image_filename_button, SLOT(setEnabled(bool))); connect(ui_->use_custom_background_image, SIGNAL(toggled(bool)), - ui_->blur_slider, SLOT(setEnabled(bool))); + ui_->blur_slider, SLOT(setEnabled(bool))); connect(ui_->use_album_cover_background, SIGNAL(toggled(bool)), - ui_->blur_slider, SLOT(setEnabled(bool))); + ui_->blur_slider, SLOT(setEnabled(bool))); connect(ui_->use_default_background, SIGNAL(toggled(bool)), - SLOT(DisableBlurAndOpacitySliders(bool))); + SLOT(DisableBlurAndOpacitySliders(bool))); connect(ui_->use_no_background, SIGNAL(toggled(bool)), - SLOT(DisableBlurAndOpacitySliders(bool))); + SLOT(DisableBlurAndOpacitySliders(bool))); } -AppearanceSettingsPage::~AppearanceSettingsPage() { - delete ui_; -} +AppearanceSettingsPage::~AppearanceSettingsPage() { delete ui_; } void AppearanceSettingsPage::Load() { QSettings s; @@ -89,14 +92,17 @@ void AppearanceSettingsPage::Load() { // Keep in mind originals colors, in case the user clicks on Cancel, to be // able to restore colors - original_use_a_custom_color_set_ = s.value(Appearance::kUseCustomColorSet, false).toBool(); + original_use_a_custom_color_set_ = + s.value(Appearance::kUseCustomColorSet, false).toBool(); - original_foreground_color_ = s.value(Appearance::kForegroundColor, - p.color(QPalette::WindowText)).value(); - current_foreground_color_ = original_foreground_color_; - original_background_color_ = s.value(Appearance::kBackgroundColor, - p.color(QPalette::Window)).value(); - current_background_color_ = original_background_color_; + original_foreground_color_ = + s.value(Appearance::kForegroundColor, p.color(QPalette::WindowText)) + .value(); + current_foreground_color_ = original_foreground_color_; + original_background_color_ = + s.value(Appearance::kBackgroundColor, p.color(QPalette::Window)) + .value(); + current_background_color_ = original_background_color_; InitColorSelectorsColors(); s.endGroup(); @@ -106,7 +112,7 @@ void AppearanceSettingsPage::Load() { playlist_view_background_image_type_ = static_cast( s.value(PlaylistView::kSettingBackgroundImageType).toInt()); - playlist_view_background_image_filename_ = + playlist_view_background_image_filename_ = s.value(PlaylistView::kSettingBackgroundImageFilename).toString(); ui_->use_system_color_set->setChecked(!original_use_a_custom_color_set_); @@ -128,7 +134,8 @@ void AppearanceSettingsPage::Load() { ui_->use_default_background->setChecked(true); DisableBlurAndOpacitySliders(true); } - ui_->background_image_filename->setText(playlist_view_background_image_filename_); + ui_->background_image_filename->setText( + playlist_view_background_image_filename_); ui_->blur_slider->setValue( s.value("blur_radius", PlaylistView::kDefaultBlurRadius).toInt()); ui_->opacity_slider->setValue( @@ -141,7 +148,8 @@ void AppearanceSettingsPage::Load() { ui_->moodbar_show->setChecked(s.value("show", true).toBool()); ui_->moodbar_style->setCurrentIndex(s.value("style", 0).toInt()); ui_->moodbar_calculate->setChecked(!s.value("calculate", true).toBool()); - ui_->moodbar_save->setChecked(s.value("save_alongside_originals", false).toBool()); + ui_->moodbar_save->setChecked( + s.value("save_alongside_originals", false).toBool()); s.endGroup(); InitMoodbarPreviews(); @@ -162,7 +170,8 @@ void AppearanceSettingsPage::Save() { // Playlist settings s.beginGroup(Playlist::kSettingsGroup); - playlist_view_background_image_filename_ = ui_->background_image_filename->text(); + playlist_view_background_image_filename_ = + ui_->background_image_filename->text(); if (ui_->use_no_background->isChecked()) { playlist_view_background_image_type_ = PlaylistView::None; } else if (ui_->use_album_cover_background->isChecked()) { @@ -172,7 +181,7 @@ void AppearanceSettingsPage::Save() { } else if (ui_->use_custom_background_image->isChecked()) { playlist_view_background_image_type_ = PlaylistView::Custom; s.setValue(PlaylistView::kSettingBackgroundImageFilename, - playlist_view_background_image_filename_); + playlist_view_background_image_filename_); } s.setValue(PlaylistView::kSettingBackgroundImageType, playlist_view_background_image_type_); @@ -200,8 +209,7 @@ void AppearanceSettingsPage::Cancel() { void AppearanceSettingsPage::SelectForegroundColor() { QColor color_selected = QColorDialog::getColor(current_foreground_color_); - if (!color_selected.isValid()) - return; + if (!color_selected.isValid()) return; current_foreground_color_ = color_selected; dialog()->appearance()->ChangeForegroundColor(color_selected); @@ -211,8 +219,7 @@ void AppearanceSettingsPage::SelectForegroundColor() { void AppearanceSettingsPage::SelectBackgroundColor() { QColor color_selected = QColorDialog::getColor(current_background_color_); - if (!color_selected.isValid()) - return; + if (!color_selected.isValid()) return; current_background_color_ = color_selected; dialog()->appearance()->ChangeBackgroundColor(color_selected); @@ -230,28 +237,32 @@ void AppearanceSettingsPage::UseCustomColorSetOptionChanged(bool checked) { } void AppearanceSettingsPage::InitColorSelectorsColors() { - UpdateColorSelectorColor(ui_->select_foreground_color, current_foreground_color_); - UpdateColorSelectorColor(ui_->select_background_color, current_background_color_); + UpdateColorSelectorColor(ui_->select_foreground_color, + current_foreground_color_); + UpdateColorSelectorColor(ui_->select_background_color, + current_background_color_); } -void AppearanceSettingsPage::UpdateColorSelectorColor(QWidget* color_selector, const QColor& color) { - QString css = QString("background-color: rgb(%1, %2, %3); color: rgb(255, 255, 255)") - .arg(color.red()) - .arg(color.green()) - .arg(color.blue()); +void AppearanceSettingsPage::UpdateColorSelectorColor(QWidget* color_selector, + const QColor& color) { + QString css = + QString("background-color: rgb(%1, %2, %3); color: rgb(255, 255, 255)") + .arg(color.red()) + .arg(color.green()) + .arg(color.blue()); color_selector->setStyleSheet(css); } void AppearanceSettingsPage::SelectBackgroundImage() { - QString selected_filename = - QFileDialog::getOpenFileName(this, tr("Select background image"), + QString selected_filename = QFileDialog::getOpenFileName( + this, tr("Select background image"), playlist_view_background_image_filename_, tr(AlbumCoverChoiceController::kLoadImageFileFilter) + ";;" + - tr(AlbumCoverChoiceController::kAllFilesFilter)); - if (selected_filename.isEmpty()) - return; + tr(AlbumCoverChoiceController::kAllFilesFilter)); + if (selected_filename.isEmpty()) return; playlist_view_background_image_filename_ = selected_filename; - ui_->background_image_filename->setText(playlist_view_background_image_filename_); + ui_->background_image_filename->setText( + playlist_view_background_image_filename_); } void AppearanceSettingsPage::BlurLevelChanged(int value) { @@ -264,8 +275,7 @@ void AppearanceSettingsPage::OpacityLevelChanged(int percent) { void AppearanceSettingsPage::InitMoodbarPreviews() { #ifdef HAVE_MOODBAR - if (initialised_moodbar_previews_) - return; + if (initialised_moodbar_previews_) return; initialised_moodbar_previews_ = true; const QSize preview_size(kMoodbarPreviewWidth, kMoodbarPreviewHeight); @@ -280,7 +290,7 @@ void AppearanceSettingsPage::InitMoodbarPreviews() { QByteArray data(file.readAll()); // Render and set each preview - for (int i=0 ; i #include -BackgroundStreamsSettingsPage::BackgroundStreamsSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_BackgroundStreamsSettingsPage) -{ +BackgroundStreamsSettingsPage::BackgroundStreamsSettingsPage( + SettingsDialog* dialog) + : SettingsPage(dialog), ui_(new Ui_BackgroundStreamsSettingsPage) { ui_->setupUi(this); setWindowIcon(QIcon(":/icons/32x32/weather-showers-scattered.png")); - foreach (const QString& name, dialog->background_streams()->streams()) { + foreach(const QString & name, dialog->background_streams()->streams()) { AddStream(name); } } -BackgroundStreamsSettingsPage::~BackgroundStreamsSettingsPage() { - delete ui_; -} +BackgroundStreamsSettingsPage::~BackgroundStreamsSettingsPage() { delete ui_; } -void BackgroundStreamsSettingsPage::Load() { -} +void BackgroundStreamsSettingsPage::Load() {} void BackgroundStreamsSettingsPage::Save() { dialog()->background_streams()->SaveStreams(); diff --git a/src/ui/backgroundstreamssettingspage.h b/src/ui/backgroundstreamssettingspage.h index a21970170..239d1273f 100644 --- a/src/ui/backgroundstreamssettingspage.h +++ b/src/ui/backgroundstreamssettingspage.h @@ -25,22 +25,22 @@ class Ui_BackgroundStreamsSettingsPage; class BackgroundStreamsSettingsPage : public SettingsPage { Q_OBJECT -public: + public: BackgroundStreamsSettingsPage(SettingsDialog* dialog); ~BackgroundStreamsSettingsPage(); void Load(); void Save(); -private slots: + private slots: void EnableStream(bool enabled); void StreamVolumeChanged(int value); -private: + private: void AddStream(const QString& name); -private: + private: Ui_BackgroundStreamsSettingsPage* ui_; }; -#endif // BACKGROUNDSTREAMSSETTINGSPAGE_H +#endif // BACKGROUNDSTREAMSSETTINGSPAGE_H diff --git a/src/ui/behavioursettingspage.cpp b/src/ui/behavioursettingspage.cpp index adcc89801..d19be32b8 100644 --- a/src/ui/behavioursettingspage.cpp +++ b/src/ui/behavioursettingspage.cpp @@ -30,12 +30,11 @@ bool LocaleAwareCompare(const QString& a, const QString& b) { } // namespace BehaviourSettingsPage::BehaviourSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_BehaviourSettingsPage) -{ + : SettingsPage(dialog), ui_(new Ui_BehaviourSettingsPage) { ui_->setupUi(this); - connect(ui_->b_show_tray_icon_, SIGNAL(toggled(bool)), SLOT(ShowTrayIconToggled(bool))); + connect(ui_->b_show_tray_icon_, SIGNAL(toggled(bool)), + SLOT(ShowTrayIconToggled(bool))); ui_->doubleclick_addmode->setItemData(0, MainWindow::AddBehaviour_Append); ui_->doubleclick_addmode->setItemData(1, MainWindow::AddBehaviour_Load); @@ -43,7 +42,8 @@ BehaviourSettingsPage::BehaviourSettingsPage(SettingsDialog* dialog) ui_->doubleclick_addmode->setItemData(3, MainWindow::AddBehaviour_Enqueue); ui_->doubleclick_playmode->setItemData(0, MainWindow::PlayBehaviour_Never); - ui_->doubleclick_playmode->setItemData(1, MainWindow::PlayBehaviour_IfStopped); + ui_->doubleclick_playmode->setItemData(1, + MainWindow::PlayBehaviour_IfStopped); ui_->doubleclick_playmode->setItemData(2, MainWindow::PlayBehaviour_Always); ui_->menu_playmode->setItemData(0, MainWindow::PlayBehaviour_Never); @@ -55,10 +55,9 @@ BehaviourSettingsPage::BehaviourSettingsPage(SettingsDialog* dialog) QDir dir(":/translations/"); QStringList codes(dir.entryList(QStringList() << "*.qm")); QRegExp lang_re("^clementine_(.*).qm$"); - foreach (const QString& filename, codes) { + foreach(const QString & filename, codes) { // The regex captures the "ru" from "clementine_ru.qm" - if (!lang_re.exactMatch(filename)) - continue; + if (!lang_re.exactMatch(filename)) continue; QString code = lang_re.cap(1); QString language_name = QLocale::languageToString(QLocale(code).language()); @@ -86,32 +85,39 @@ BehaviourSettingsPage::BehaviourSettingsPage(SettingsDialog* dialog) #endif } -BehaviourSettingsPage::~BehaviourSettingsPage() { - delete ui_; -} +BehaviourSettingsPage::~BehaviourSettingsPage() { delete ui_; } void BehaviourSettingsPage::Load() { QSettings s; s.beginGroup(MainWindow::kSettingsGroup); ui_->b_show_tray_icon_->setChecked(s.value("showtray", true).toBool()); - ui_->b_keep_running_->setChecked(s.value("keeprunning", - ui_->b_show_tray_icon_->isChecked()).toBool()); + ui_->b_keep_running_->setChecked( + s.value("keeprunning", ui_->b_show_tray_icon_->isChecked()).toBool()); ui_->doubleclick_addmode->setCurrentIndex(ui_->doubleclick_addmode->findData( s.value("doubleclick_addmode", MainWindow::AddBehaviour_Append).toInt())); - ui_->doubleclick_playmode->setCurrentIndex(ui_->doubleclick_playmode->findData( - s.value("doubleclick_playmode", MainWindow::PlayBehaviour_IfStopped).toInt())); + ui_->doubleclick_playmode->setCurrentIndex( + ui_->doubleclick_playmode->findData( + s.value("doubleclick_playmode", MainWindow::PlayBehaviour_IfStopped) + .toInt())); ui_->menu_playmode->setCurrentIndex(ui_->menu_playmode->findData( s.value("menu_playmode", MainWindow::PlayBehaviour_IfStopped).toInt())); MainWindow::StartupBehaviour behaviour = MainWindow::StartupBehaviour( s.value("startupbehaviour", MainWindow::Startup_Remember).toInt()); switch (behaviour) { - case MainWindow::Startup_AlwaysHide: ui_->b_always_hide_->setChecked(true); break; - case MainWindow::Startup_AlwaysShow: ui_->b_always_show_->setChecked(true); break; - case MainWindow::Startup_Remember: ui_->b_remember_->setChecked(true); break; + case MainWindow::Startup_AlwaysHide: + ui_->b_always_hide_->setChecked(true); + break; + case MainWindow::Startup_AlwaysShow: + ui_->b_always_show_->setChecked(true); + break; + case MainWindow::Startup_Remember: + ui_->b_remember_->setChecked(true); + break; } - ui_->resume_after_start_->setChecked(s.value("resume_playback_after_start", false).toBool()); + ui_->resume_after_start_->setChecked( + s.value("resume_playback_after_start", false).toBool()); s.endGroup(); s.beginGroup("General"); @@ -123,11 +129,13 @@ void BehaviourSettingsPage::Load() { s.endGroup(); s.beginGroup(Playlist::kSettingsGroup); - ui_->b_grey_out_deleted_->setChecked(s.value("greyoutdeleted", false).toBool()); + ui_->b_grey_out_deleted_->setChecked( + s.value("greyoutdeleted", false).toBool()); s.endGroup(); s.beginGroup(PlaylistTabBar::kSettingsGroup); - ui_->b_warn_close_playlist_->setChecked(s.value("warn_close_playlist", true).toBool()); + ui_->b_warn_close_playlist_->setChecked( + s.value("warn_close_playlist", true).toBool()); s.endGroup(); } @@ -135,16 +143,22 @@ void BehaviourSettingsPage::Save() { QSettings s; MainWindow::StartupBehaviour behaviour = MainWindow::Startup_Remember; - if (ui_->b_always_hide_->isChecked()) behaviour = MainWindow::Startup_AlwaysHide; - if (ui_->b_always_show_->isChecked()) behaviour = MainWindow::Startup_AlwaysShow; - if (ui_->b_remember_->isChecked()) behaviour = MainWindow::Startup_Remember; + if (ui_->b_always_hide_->isChecked()) + behaviour = MainWindow::Startup_AlwaysHide; + if (ui_->b_always_show_->isChecked()) + behaviour = MainWindow::Startup_AlwaysShow; + if (ui_->b_remember_->isChecked()) behaviour = MainWindow::Startup_Remember; MainWindow::AddBehaviour doubleclick_addmode = MainWindow::AddBehaviour( - ui_->doubleclick_addmode->itemData(ui_->doubleclick_addmode->currentIndex()).toInt()); + ui_->doubleclick_addmode->itemData( + ui_->doubleclick_addmode->currentIndex()) + .toInt()); MainWindow::PlayBehaviour doubleclick_playmode = MainWindow::PlayBehaviour( - ui_->doubleclick_playmode->itemData(ui_->doubleclick_playmode->currentIndex()).toInt()); + ui_->doubleclick_playmode->itemData( + ui_->doubleclick_playmode->currentIndex()) + .toInt()); MainWindow::PlayBehaviour menu_playmode = MainWindow::PlayBehaviour( - ui_->menu_playmode->itemData(ui_->menu_playmode->currentIndex()).toInt()); + ui_->menu_playmode->itemData(ui_->menu_playmode->currentIndex()).toInt()); s.beginGroup(MainWindow::kSettingsGroup); s.setValue("showtray", ui_->b_show_tray_icon_->isChecked()); @@ -153,12 +167,14 @@ void BehaviourSettingsPage::Save() { s.setValue("doubleclick_addmode", doubleclick_addmode); s.setValue("doubleclick_playmode", doubleclick_playmode); s.setValue("menu_playmode", menu_playmode); - s.setValue("resume_playback_after_start", ui_->resume_after_start_->isChecked()); + s.setValue("resume_playback_after_start", + ui_->resume_after_start_->isChecked()); s.endGroup(); s.beginGroup("General"); - s.setValue("language", language_map_.contains(ui_->language->currentText()) ? - language_map_[ui_->language->currentText()] : QString()); + s.setValue("language", language_map_.contains(ui_->language->currentText()) + ? language_map_[ui_->language->currentText()] + : QString()); s.endGroup(); s.beginGroup(Playlist::kSettingsGroup); diff --git a/src/ui/behavioursettingspage.h b/src/ui/behavioursettingspage.h index fc546f246..9f73c0f77 100644 --- a/src/ui/behavioursettingspage.h +++ b/src/ui/behavioursettingspage.h @@ -27,20 +27,20 @@ class Ui_BehaviourSettingsPage; class BehaviourSettingsPage : public SettingsPage { Q_OBJECT -public: + public: BehaviourSettingsPage(SettingsDialog* dialog); ~BehaviourSettingsPage(); void Load(); void Save(); -private slots: + private slots: void ShowTrayIconToggled(bool on); -private: + private: Ui_BehaviourSettingsPage* ui_; QMap language_map_; }; -#endif // BEHAVIOURSETTINGSPAGE_H +#endif // BEHAVIOURSETTINGSPAGE_H diff --git a/src/ui/console.cpp b/src/ui/console.cpp index fa1f5edb3..681279809 100644 --- a/src/ui/console.cpp +++ b/src/ui/console.cpp @@ -10,8 +10,7 @@ #include "core/database.h" Console::Console(Application* app, QWidget* parent) - : QDialog(parent), - app_(app) { + : QDialog(parent), app_(app) { ui_.setupUi(this); connect(ui_.run, SIGNAL(clicked()), SLOT(RunQuery())); diff --git a/src/ui/coverfromurldialog.cpp b/src/ui/coverfromurldialog.cpp index a96508121..8813a0efe 100644 --- a/src/ui/coverfromurldialog.cpp +++ b/src/ui/coverfromurldialog.cpp @@ -28,21 +28,19 @@ #include CoverFromURLDialog::CoverFromURLDialog(QWidget* parent) - : QDialog(parent), - ui_(new Ui_CoverFromURLDialog), - network_(new NetworkAccessManager(this)) -{ + : QDialog(parent), + ui_(new Ui_CoverFromURLDialog), + network_(new NetworkAccessManager(this)) { ui_->setupUi(this); ui_->busy->hide(); } -CoverFromURLDialog::~CoverFromURLDialog() { - delete ui_; -} +CoverFromURLDialog::~CoverFromURLDialog() { delete ui_; } QImage CoverFromURLDialog::Exec() { // reset state - ui_->url->setText("");; + ui_->url->setText(""); + ; last_image_ = QImage(); QClipboard* clipboard = QApplication::clipboard(); @@ -55,7 +53,8 @@ QImage CoverFromURLDialog::Exec() { void CoverFromURLDialog::accept() { ui_->busy->show(); - QNetworkRequest network_request = QNetworkRequest(QUrl::fromUserInput(ui_->url->text())); + QNetworkRequest network_request = + QNetworkRequest(QUrl::fromUserInput(ui_->url->text())); QNetworkReply* reply = network_->get(network_request); connect(reply, SIGNAL(finished()), SLOT(LoadCoverFromURLFinished())); @@ -68,17 +67,19 @@ void CoverFromURLDialog::LoadCoverFromURLFinished() { reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::information(this, tr("Fetching cover error"), tr("The site you requested does not exist!")); + QMessageBox::information(this, tr("Fetching cover error"), + tr("The site you requested does not exist!")); return; } QImage image; image.loadFromData(reply->readAll()); - if(!image.isNull()) { + if (!image.isNull()) { last_image_ = image; QDialog::accept(); } else { - QMessageBox::information(this, tr("Fetching cover error"), tr("The site you requested is not an image!")); + QMessageBox::information(this, tr("Fetching cover error"), + tr("The site you requested is not an image!")); } } diff --git a/src/ui/coverfromurldialog.h b/src/ui/coverfromurldialog.h index b725eaba1..c3eb065bd 100644 --- a/src/ui/coverfromurldialog.h +++ b/src/ui/coverfromurldialog.h @@ -48,4 +48,4 @@ class CoverFromURLDialog : public QDialog { QImage last_image_; }; -#endif // COVERFROMURLDIALOG_H +#endif // COVERFROMURLDIALOG_H diff --git a/src/ui/dbusscreensaver.cpp b/src/ui/dbusscreensaver.cpp index 021dc1e0d..21fa3a9de 100644 --- a/src/ui/dbusscreensaver.cpp +++ b/src/ui/dbusscreensaver.cpp @@ -23,22 +23,21 @@ DBusScreensaver::DBusScreensaver(const QString& service, const QString& path, const QString& interface) - : service_(service), - path_(path), - interface_(interface) -{ -} + : service_(service), path_(path), interface_(interface) {} void DBusScreensaver::Inhibit() { - QDBusInterface gnome_screensaver("org.gnome.ScreenSaver", "/", "org.gnome.ScreenSaver"); + QDBusInterface gnome_screensaver("org.gnome.ScreenSaver", "/", + "org.gnome.ScreenSaver"); QDBusReply reply = - gnome_screensaver.call("Inhibit", QCoreApplication::applicationName(), QObject::tr("Visualizations")); + gnome_screensaver.call("Inhibit", QCoreApplication::applicationName(), + QObject::tr("Visualizations")); if (reply.isValid()) { cookie_ = reply.value(); } } void DBusScreensaver::Uninhibit() { - QDBusInterface gnome_screensaver("org.gnome.ScreenSaver", "/", "org.gnome.ScreenSaver"); + QDBusInterface gnome_screensaver("org.gnome.ScreenSaver", "/", + "org.gnome.ScreenSaver"); gnome_screensaver.call("UnInhibit", cookie_); } diff --git a/src/ui/dbusscreensaver.h b/src/ui/dbusscreensaver.h index 4d939cf42..4cae2a16c 100644 --- a/src/ui/dbusscreensaver.h +++ b/src/ui/dbusscreensaver.h @@ -30,7 +30,7 @@ class DBusScreensaver : public Screensaver { void Inhibit(); void Uninhibit(); -private: + private: QString service_; QString path_; QString interface_; diff --git a/src/ui/edittagdialog.cpp b/src/ui/edittagdialog.cpp index f44fa7cc9..acbfb5c6b 100644 --- a/src/ui/edittagdialog.cpp +++ b/src/ui/edittagdialog.cpp @@ -45,32 +45,33 @@ #include -const char* EditTagDialog::kHintText = QT_TR_NOOP("(different across multiple songs)"); +const char* EditTagDialog::kHintText = + QT_TR_NOOP("(different across multiple songs)"); const char* EditTagDialog::kSettingsGroup = "EditTagDialog"; EditTagDialog::EditTagDialog(Application* app, QWidget* parent) - : QDialog(parent), - ui_(new Ui_EditTagDialog), - app_(app), - album_cover_choice_controller_(new AlbumCoverChoiceController(this)), - loading_(false), - ignore_edits_(false), - tag_fetcher_(new TagFetcher(this)), - cover_art_id_(0), - cover_art_is_set_(false), - results_dialog_(new TrackSelectionDialog(this)) -{ + : QDialog(parent), + ui_(new Ui_EditTagDialog), + app_(app), + album_cover_choice_controller_(new AlbumCoverChoiceController(this)), + loading_(false), + ignore_edits_(false), + tag_fetcher_(new TagFetcher(this)), + cover_art_id_(0), + cover_art_is_set_(false), + results_dialog_(new TrackSelectionDialog(this)) { cover_options_.default_output_image_ = AlbumCoverLoader::ScaleAndPad(cover_options_, QImage(":nocover.png")); - connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64,QImage,QImage)), - SLOT(ArtLoaded(quint64,QImage,QImage))); + connect(app_->album_cover_loader(), + SIGNAL(ImageLoaded(quint64, QImage, QImage)), + SLOT(ArtLoaded(quint64, QImage, QImage))); connect(tag_fetcher_, SIGNAL(ResultAvailable(Song, SongList)), results_dialog_, SLOT(FetchTagFinished(Song, SongList)), Qt::QueuedConnection); - connect(tag_fetcher_, SIGNAL(Progress(Song,QString)), - results_dialog_, SLOT(FetchTagProgress(Song,QString))); + connect(tag_fetcher_, SIGNAL(Progress(Song, QString)), results_dialog_, + SLOT(FetchTagProgress(Song, QString))); connect(results_dialog_, SIGNAL(SongChosen(Song, Song)), SLOT(FetchTagSongChosen(Song, Song))); connect(results_dialog_, SIGNAL(finished(int)), tag_fetcher_, SLOT(Cancel())); @@ -83,7 +84,7 @@ EditTagDialog::EditTagDialog(Application* app, QWidget* parent) // An editable field is one that has a label as a buddy. The label is // important because it gets turned bold when the field is changed. - foreach (QLabel* label, findChildren()) { + foreach(QLabel * label, findChildren()) { QWidget* widget = label->buddy(); if (widget) { // Store information about the field @@ -109,25 +110,25 @@ EditTagDialog::EditTagDialog(Application* app, QWidget* parent) const bool light = palette().color(QPalette::Base).value() > 128; const QColor color = palette().color(QPalette::Dark); QPalette summary_label_palette(palette()); - summary_label_palette.setColor(QPalette::WindowText, - light ? color.darker(150) : color.lighter(125)); + summary_label_palette.setColor( + QPalette::WindowText, light ? color.darker(150) : color.lighter(125)); - foreach (QLabel* label, ui_->summary_tab->findChildren()) { + foreach(QLabel * label, ui_->summary_tab->findChildren()) { if (label->property("field_label").toBool()) { label->setPalette(summary_label_palette); } } // Pretend the summary text is just a label - ui_->summary->setMaximumHeight(ui_->art->height() - ui_->summary_art_button->height() - 4); + ui_->summary->setMaximumHeight(ui_->art->height() - + ui_->summary_art_button->height() - 4); connect(ui_->song_list->selectionModel(), - SIGNAL(selectionChanged(QItemSelection,QItemSelection)), + SIGNAL(selectionChanged(QItemSelection, QItemSelection)), SLOT(SelectionChanged())); connect(ui_->button_box, SIGNAL(clicked(QAbstractButton*)), - SLOT(ButtonClicked(QAbstractButton*))); - connect(ui_->rating, SIGNAL(RatingChanged(float)), - SLOT(SongRated(float))); + SLOT(ButtonClicked(QAbstractButton*))); + connect(ui_->rating, SIGNAL(RatingChanged(float)), SLOT(SongRated(float))); connect(ui_->playcount_reset, SIGNAL(clicked()), SLOT(ResetPlayCounts())); connect(ui_->fetch_tag, SIGNAL(clicked()), SLOT(FetchTag())); @@ -157,7 +158,8 @@ EditTagDialog::EditTagDialog(Application* app, QWidget* parent) ui_->art->setAcceptDrops(true); // Add the next/previous buttons - previous_button_ = new QPushButton(IconLoader::Load("go-previous"), tr("Previous"), this); + previous_button_ = + new QPushButton(IconLoader::Load("go-previous"), tr("Previous"), this); next_button_ = new QPushButton(IconLoader::Load("go-next"), tr("Next"), this); ui_->button_box->addButton(previous_button_, QDialogButtonBox::ResetRole); ui_->button_box->addButton(next_button_, QDialogButtonBox::ResetRole); @@ -168,36 +170,41 @@ EditTagDialog::EditTagDialog(Application* app, QWidget* parent) // Set some shortcuts for the buttons new QShortcut(QKeySequence::Back, previous_button_, SLOT(click())); new QShortcut(QKeySequence::Forward, next_button_, SLOT(click())); - new QShortcut(QKeySequence::MoveToPreviousPage, previous_button_, SLOT(click())); + new QShortcut(QKeySequence::MoveToPreviousPage, previous_button_, + SLOT(click())); new QShortcut(QKeySequence::MoveToNextPage, next_button_, SLOT(click())); // Show the shortcuts as tooltips previous_button_->setToolTip(QString("%1 (%2 / %3)").arg( previous_button_->text(), QKeySequence(QKeySequence::Back).toString(QKeySequence::NativeText), - QKeySequence(QKeySequence::MoveToPreviousPage).toString(QKeySequence::NativeText))); + QKeySequence(QKeySequence::MoveToPreviousPage) + .toString(QKeySequence::NativeText))); next_button_->setToolTip(QString("%1 (%2 / %3)").arg( next_button_->text(), QKeySequence(QKeySequence::Forward).toString(QKeySequence::NativeText), - QKeySequence(QKeySequence::MoveToNextPage).toString(QKeySequence::NativeText))); + QKeySequence(QKeySequence::MoveToNextPage) + .toString(QKeySequence::NativeText))); - new TagCompleter(app_->library_backend(), Playlist::Column_Artist, ui_->artist); + new TagCompleter(app_->library_backend(), Playlist::Column_Artist, + ui_->artist); new TagCompleter(app_->library_backend(), Playlist::Column_Album, ui_->album); - new TagCompleter(app_->library_backend(), Playlist::Column_AlbumArtist, ui_->albumartist); + new TagCompleter(app_->library_backend(), Playlist::Column_AlbumArtist, + ui_->albumartist); new TagCompleter(app_->library_backend(), Playlist::Column_Genre, ui_->genre); - new TagCompleter(app_->library_backend(), Playlist::Column_Composer, ui_->composer); - new TagCompleter(app_->library_backend(), Playlist::Column_Performer, ui_->performer); - new TagCompleter(app_->library_backend(), Playlist::Column_Grouping, ui_->grouping); + new TagCompleter(app_->library_backend(), Playlist::Column_Composer, + ui_->composer); + new TagCompleter(app_->library_backend(), Playlist::Column_Performer, + ui_->performer); + new TagCompleter(app_->library_backend(), Playlist::Column_Grouping, + ui_->grouping); } -EditTagDialog::~EditTagDialog() { - delete ui_; -} +EditTagDialog::~EditTagDialog() { delete ui_; } bool EditTagDialog::SetLoading(const QString& message) { const bool loading = !message.isEmpty(); - if (loading == loading_) - return false; + if (loading == loading_) return false; loading_ = loading; ui_->button_box->setEnabled(!loading); @@ -209,14 +216,16 @@ bool EditTagDialog::SetLoading(const QString& message) { return true; } -QList EditTagDialog::LoadData(const SongList& songs) const { +QList EditTagDialog::LoadData(const SongList& songs) + const { QList ret; - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { if (song.IsEditable()) { // Try reloading the tags from file Song copy(song); - TagReaderClient::Instance()->ReadFileBlocking(copy.url().toLocalFile(), ©); + TagReaderClient::Instance()->ReadFileBlocking(copy.url().toLocalFile(), + ©); if (copy.is_valid()) { copy.MergeUserSetData(song); @@ -230,28 +239,28 @@ QList EditTagDialog::LoadData(const SongList& songs) const void EditTagDialog::SetSongs(const SongList& s, const PlaylistItemList& items) { // Show the loading indicator - if (!SetLoading(tr("Loading tracks") + "...")) - return; + if (!SetLoading(tr("Loading tracks") + "...")) return; data_.clear(); playlist_items_ = items; ui_->song_list->clear(); // Reload tags in the background - QFuture > future = QtConcurrent::run(this, &EditTagDialog::LoadData, s); - QFutureWatcher >* watcher = new QFutureWatcher >(this); + QFuture > future = + QtConcurrent::run(this, &EditTagDialog::LoadData, s); + QFutureWatcher >* watcher = + new QFutureWatcher >(this); watcher->setFuture(future); connect(watcher, SIGNAL(finished()), SLOT(SetSongsFinished())); } void EditTagDialog::SetSongsFinished() { - QFutureWatcher >* watcher = dynamic_cast >*>(sender()); - if (!watcher) - return; + QFutureWatcher >* watcher = + dynamic_cast >*>(sender()); + if (!watcher) return; watcher->deleteLater(); - if (!SetLoading(QString())) - return; + if (!SetLoading(QString())) return; data_ = watcher->result(); if (data_.count() == 0) { @@ -268,7 +277,7 @@ void EditTagDialog::SetSongsFinished() { } // Add the filenames to the list - foreach (const Data& data, data_) { + foreach(const Data & data, data_) { ui_->song_list->addItem(data.current_.basefilename()); } @@ -287,55 +296,57 @@ void EditTagDialog::SetSongListVisibility(bool visible) { } QVariant EditTagDialog::Data::value(const Song& song, const QString& id) { - if (id == "title") return song.title(); - if (id == "artist") return song.artist(); - if (id == "album") return song.album(); + if (id == "title") return song.title(); + if (id == "artist") return song.artist(); + if (id == "album") return song.album(); if (id == "albumartist") return song.albumartist(); - if (id == "composer") return song.composer(); - if (id == "performer") return song.performer(); - if (id == "grouping") return song.grouping(); - if (id == "genre") return song.genre(); - if (id == "comment") return song.comment(); - if (id == "track") return song.track(); - if (id == "disc") return song.disc(); - if (id == "year") return song.year(); + if (id == "composer") return song.composer(); + if (id == "performer") return song.performer(); + if (id == "grouping") return song.grouping(); + if (id == "genre") return song.genre(); + if (id == "comment") return song.comment(); + if (id == "track") return song.track(); + if (id == "disc") return song.disc(); + if (id == "year") return song.year(); qLog(Warning) << "Unknown ID" << id; return QVariant(); } void EditTagDialog::Data::set_value(const QString& id, const QVariant& value) { - if (id == "title") current_.set_title(value.toString()); - if (id == "artist") current_.set_artist(value.toString()); - if (id == "album") current_.set_album(value.toString()); + if (id == "title") current_.set_title(value.toString()); + if (id == "artist") current_.set_artist(value.toString()); + if (id == "album") current_.set_album(value.toString()); if (id == "albumartist") current_.set_albumartist(value.toString()); - if (id == "composer") current_.set_composer(value.toString()); - if (id == "performer") current_.set_performer(value.toString()); - if (id == "grouping") current_.set_grouping(value.toString()); - if (id == "genre") current_.set_genre(value.toString()); - if (id == "comment") current_.set_comment(value.toString()); - if (id == "track") current_.set_track(value.toInt()); - if (id == "disc") current_.set_disc(value.toInt()); - if (id == "year") current_.set_year(value.toInt()); + if (id == "composer") current_.set_composer(value.toString()); + if (id == "performer") current_.set_performer(value.toString()); + if (id == "grouping") current_.set_grouping(value.toString()); + if (id == "genre") current_.set_genre(value.toString()); + if (id == "comment") current_.set_comment(value.toString()); + if (id == "track") current_.set_track(value.toInt()); + if (id == "disc") current_.set_disc(value.toInt()); + if (id == "year") current_.set_year(value.toInt()); } -bool EditTagDialog::DoesValueVary(const QModelIndexList& sel, const QString& id) const { +bool EditTagDialog::DoesValueVary(const QModelIndexList& sel, + const QString& id) const { QVariant value = data_[sel.first().row()].current_value(id); - for (int i=1 ; isetFont(new_font); } -void EditTagDialog::UpdateFieldValue(const FieldData& field, const QModelIndexList& sel) { +void EditTagDialog::UpdateFieldValue(const FieldData& field, + const QModelIndexList& sel) { // Get the value from the field QVariant value; if (ExtendedEditor* editor = dynamic_cast(field.editor_)) { @@ -368,7 +380,7 @@ void EditTagDialog::UpdateFieldValue(const FieldData& field, const QModelIndexLi } // Set it in each selected song - foreach (const QModelIndex& i, sel) { + foreach(const QModelIndex & i, sel) { data_[i.row()].set_value(field.id_, value); } @@ -381,9 +393,10 @@ void EditTagDialog::UpdateFieldValue(const FieldData& field, const QModelIndexLi field.editor_->setFont(new_font); } -void EditTagDialog::ResetFieldValue(const FieldData& field, const QModelIndexList& sel) { +void EditTagDialog::ResetFieldValue(const FieldData& field, + const QModelIndexList& sel) { // Reset each selected song - foreach (const QModelIndex& i, sel) { + foreach(const QModelIndex & i, sel) { Data& data = data_[i.row()]; data.set_value(field.id_, data.original_value(field.id_)); } @@ -393,20 +406,19 @@ void EditTagDialog::ResetFieldValue(const FieldData& field, const QModelIndexLis } void EditTagDialog::SelectionChanged() { - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); - if (sel.isEmpty()) - return; + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); + if (sel.isEmpty()) return; // Set the editable fields ignore_edits_ = true; - foreach (const FieldData& field, fields_) { - InitFieldValue(field, sel); - } + foreach(const FieldData & field, fields_) { InitFieldValue(field, sel); } ignore_edits_ = false; // If we're editing multiple songs then we have to disable certain tabs const bool multiple = sel.count() > 1; - ui_->tab_widget->setTabEnabled(ui_->tab_widget->indexOf(ui_->summary_tab), !multiple); + ui_->tab_widget->setTabEnabled(ui_->tab_widget->indexOf(ui_->summary_tab), + !multiple); if (!multiple) { const Song& song = data_[sel.first().row()].original_; @@ -415,12 +427,13 @@ void EditTagDialog::SelectionChanged() { } } -static void SetText(QLabel* label, int value, const QString& suffix, const QString& def = QString()) { +static void SetText(QLabel* label, int value, const QString& suffix, + const QString& def = QString()) { label->setText(value <= 0 ? def : (QString::number(value) + " " + suffix)); } static void SetDate(QLabel* label, uint time) { - if (time == std::numeric_limits::max()) { // -1 + if (time == std::numeric_limits::max()) { // -1 label->setText(QObject::tr("Unknown")); } else { label->setText(QDateTime::fromTime_t(time).toString( @@ -429,9 +442,11 @@ static void SetDate(QLabel* label, uint time) { } void EditTagDialog::UpdateSummaryTab(const Song& song) { - cover_art_id_ = app_->album_cover_loader()->LoadImageAsync(cover_options_, song); + cover_art_id_ = + app_->album_cover_loader()->LoadImageAsync(cover_options_, song); - QString summary = "" + Qt::escape(song.PrettyTitleWithArtist()) + "
"; + QString summary = + "" + Qt::escape(song.PrettyTitleWithArtist()) + "
"; bool art_is_set = true; if (song.has_manually_unset_cover()) { @@ -442,7 +457,8 @@ void EditTagDialog::UpdateSummaryTab(const Song& song) { } else if (song.has_embedded_cover()) { summary += Qt::escape(tr("Cover art from embedded image")); } else if (!song.art_automatic().isEmpty()) { - summary += Qt::escape(tr("Cover art loaded automatically from %1").arg(song.art_automatic())); + summary += Qt::escape( + tr("Cover art loaded automatically from %1").arg(song.art_automatic())); } else { summary += Qt::escape(tr("Cover art not set")); art_is_set = false; @@ -475,7 +491,7 @@ void EditTagDialog::UpdateSummaryTab(const Song& song) { ui_->filename->setText(song.url().toString()); album_cover_choice_controller_->search_for_cover_action()->setEnabled( - app_->cover_providers()->HasAnyProviders()); + app_->cover_providers()->HasAnyProviders()); } void EditTagDialog::UpdateStatisticsTab(const Song& song) { @@ -484,12 +500,15 @@ void EditTagDialog::UpdateStatisticsTab(const Song& song) { ui_->score->setText(QString::number(qMax(0, song.score()))); ui_->rating->set_rating(song.rating()); - ui_->lastplayed->setText(song.lastplayed() <= 0 ? tr("Never") : - QDateTime::fromTime_t(song.lastplayed()).toString( - QLocale::system().dateTimeFormat(QLocale::LongFormat))); + ui_->lastplayed->setText( + song.lastplayed() <= 0 + ? tr("Never") + : QDateTime::fromTime_t(song.lastplayed()).toString( + QLocale::system().dateTimeFormat(QLocale::LongFormat))); } -void EditTagDialog::ArtLoaded(quint64 id, const QImage& scaled, const QImage& original) { +void EditTagDialog::ArtLoaded(quint64 id, const QImage& scaled, + const QImage& original) { if (id == cover_art_id_) { ui_->art->setPixmap(QPixmap::fromImage(scaled)); original_ = original; @@ -497,17 +516,16 @@ void EditTagDialog::ArtLoaded(quint64 id, const QImage& scaled, const QImage& or } void EditTagDialog::FieldValueEdited() { - if (ignore_edits_) - return; + if (ignore_edits_) return; - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); - if (sel.isEmpty()) - return; + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); + if (sel.isEmpty()) return; QWidget* w = qobject_cast(sender()); // Find the field - foreach (const FieldData& field, fields_) { + foreach(const FieldData & field, fields_) { if (field.editor_ == w) { UpdateFieldValue(field, sel); return; @@ -516,14 +534,14 @@ void EditTagDialog::FieldValueEdited() { } void EditTagDialog::ResetField() { - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); - if (sel.isEmpty()) - return; + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); + if (sel.isEmpty()) return; QWidget* w = qobject_cast(sender()); // Find the field - foreach (const FieldData& field, fields_) { + foreach(const FieldData & field, fields_) { if (field.editor_ == w) { ignore_edits_ = true; ResetFieldValue(field, sel); @@ -534,65 +552,61 @@ void EditTagDialog::ResetField() { } Song* EditTagDialog::GetFirstSelected() { - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); - if (sel.isEmpty()) - return nullptr; + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); + if (sel.isEmpty()) return nullptr; return &data_[sel.first().row()].original_; } void EditTagDialog::LoadCoverFromFile() { Song* song = GetFirstSelected(); - if(!song) - return; + if (!song) return; - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); QString cover = album_cover_choice_controller_->LoadCoverFromFile(song); - if(!cover.isEmpty()) - UpdateCoverOf(*song, sel, cover); + if (!cover.isEmpty()) UpdateCoverOf(*song, sel, cover); } void EditTagDialog::SaveCoverToFile() { Song* song = GetFirstSelected(); - if(!song) - return; + if (!song) return; album_cover_choice_controller_->SaveCoverToFile(*song, original_); } void EditTagDialog::LoadCoverFromURL() { Song* song = GetFirstSelected(); - if(!song) - return; + if (!song) return; - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); QString cover = album_cover_choice_controller_->LoadCoverFromURL(song); - if(!cover.isEmpty()) - UpdateCoverOf(*song, sel, cover); + if (!cover.isEmpty()) UpdateCoverOf(*song, sel, cover); } void EditTagDialog::SearchForCover() { Song* song = GetFirstSelected(); - if(!song) - return; + if (!song) return; - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); QString cover = album_cover_choice_controller_->SearchForCover(song); - if(!cover.isEmpty()) - UpdateCoverOf(*song, sel, cover); + if (!cover.isEmpty()) UpdateCoverOf(*song, sel, cover); } void EditTagDialog::UnsetCover() { Song* song = GetFirstSelected(); - if(!song) - return; + if (!song) return; - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); QString cover = album_cover_choice_controller_->UnsetCover(song); UpdateCoverOf(*song, sel, cover); @@ -600,29 +614,29 @@ void EditTagDialog::UnsetCover() { void EditTagDialog::ShowCover() { Song* song = GetFirstSelected(); - if(!song) { + if (!song) { return; } album_cover_choice_controller_->ShowCover(*song); } -void EditTagDialog::UpdateCoverOf(const Song& selected, const QModelIndexList& sel, +void EditTagDialog::UpdateCoverOf(const Song& selected, + const QModelIndexList& sel, const QString& cover) { - if (!selected.is_valid() || selected.id() == -1) - return; + if (!selected.is_valid() || selected.id() == -1) return; UpdateSummaryTab(selected); // Now check if we have any other songs cached that share that artist and // album (and would therefore be changed as well) - for (int i=0 ; iartist() && - selected.album() == other_song->album()) { + selected.album() == other_song->album()) { other_song->set_art_manual(cover); } } @@ -642,7 +656,8 @@ void EditTagDialog::PreviousSong() { return; } - int row = (ui_->song_list->currentRow() - 1 + ui_->song_list->count()) % ui_->song_list->count(); + int row = (ui_->song_list->currentRow() - 1 + ui_->song_list->count()) % + ui_->song_list->count(); ui_->song_list->setCurrentRow(row); } @@ -653,25 +668,25 @@ void EditTagDialog::ButtonClicked(QAbstractButton* button) { } void EditTagDialog::SaveData(const QList& data) { - for (int i=0 ; iSaveFileBlocking( - ref.current_.url().toLocalFile(), ref.current_)) { - emit Error(tr("An error occurred writing metadata to '%1'").arg(ref.current_.url().toLocalFile())); + ref.current_.url().toLocalFile(), ref.current_)) { + emit Error(tr("An error occurred writing metadata to '%1'") + .arg(ref.current_.url().toLocalFile())); } } } void EditTagDialog::accept() { // Show the loading indicator - if (!SetLoading(tr("Saving tracks") + "...")) - return; + if (!SetLoading(tr("Saving tracks") + "...")) return; // Save tags in the background - QFuture future = QtConcurrent::run(this, &EditTagDialog::SaveData, data_); + QFuture future = + QtConcurrent::run(this, &EditTagDialog::SaveData, data_); QFutureWatcher* watcher = new QFutureWatcher(this); watcher->setFuture(future); connect(watcher, SIGNAL(finished()), SLOT(AcceptFinished())); @@ -679,12 +694,10 @@ void EditTagDialog::accept() { void EditTagDialog::AcceptFinished() { QFutureWatcher* watcher = dynamic_cast*>(sender()); - if (!watcher) - return; + if (!watcher) return; watcher->deleteLater(); - if (!SetLoading(QString())) - return; + if (!SetLoading(QString())) return; QDialog::accept(); } @@ -706,10 +719,12 @@ bool EditTagDialog::eventFilter(QObject* o, QEvent* e) { case QEvent::Drop: { const QDropEvent* event = static_cast(e); - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); Song* song = GetFirstSelected(); - const QString cover = album_cover_choice_controller_->SaveCover(song, event); + const QString cover = + album_cover_choice_controller_->SaveCover(song, event); if (!cover.isEmpty()) { UpdateCoverOf(*song, sel, cover); } @@ -746,28 +761,27 @@ void EditTagDialog::hideEvent(QHideEvent* e) { } void EditTagDialog::SongRated(float rating) { - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); - if (sel.isEmpty()) - return; + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); + if (sel.isEmpty()) return; Song* song = &data_[sel.first().row()].original_; - if (!song->is_valid() || song->id() == -1) - return; + if (!song->is_valid() || song->id() == -1) return; song->set_rating(rating); app_->library_backend()->UpdateSongRatingAsync(song->id(), rating); } void EditTagDialog::ResetPlayCounts() { - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); - if (sel.isEmpty()) - return; + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); + if (sel.isEmpty()) return; Song* song = &data_[sel.first().row()].original_; - if (!song->is_valid() || song->id() == -1) - return; + if (!song->is_valid() || song->id() == -1) return; - if (QMessageBox::question(this, tr("Reset play counts"), - tr("Are you sure you want to reset this song's statistics?"), - QMessageBox::Reset, QMessageBox::Cancel) != QMessageBox::Reset) { + if (QMessageBox::question( + this, tr("Reset play counts"), + tr("Are you sure you want to reset this song's statistics?"), + QMessageBox::Reset, QMessageBox::Cancel) != QMessageBox::Reset) { return; } @@ -780,11 +794,12 @@ void EditTagDialog::ResetPlayCounts() { } void EditTagDialog::FetchTag() { - const QModelIndexList sel = ui_->song_list->selectionModel()->selectedIndexes(); + const QModelIndexList sel = + ui_->song_list->selectionModel()->selectedIndexes(); SongList songs; - foreach (const QModelIndex& index, sel) { + foreach(const QModelIndex & index, sel) { Song song = data_[index.row()].original_; if (!song.is_valid()) { continue; @@ -793,8 +808,7 @@ void EditTagDialog::FetchTag() { songs << song; } - if (songs.isEmpty()) - return; + if (songs.isEmpty()) return; results_dialog_->Init(songs); tag_fetcher_->StartFetch(songs); @@ -802,14 +816,14 @@ void EditTagDialog::FetchTag() { results_dialog_->show(); } -void EditTagDialog::FetchTagSongChosen(const Song& original_song, const Song& new_metadata) { +void EditTagDialog::FetchTagSongChosen(const Song& original_song, + const Song& new_metadata) { const QString filename = original_song.url().toLocalFile(); // Find the song with this filename - for (int i=0 ; ioriginal_.url().toLocalFile() != filename) - continue; + if (data->original_.url().toLocalFile() != filename) continue; // Is it currently being displayed in the UI? if (ui_->song_list->currentRow() == i) { @@ -830,4 +844,3 @@ void EditTagDialog::FetchTagSongChosen(const Song& original_song, const Song& ne break; } } - diff --git a/src/ui/edittagdialog.h b/src/ui/edittagdialog.h index 885f3bfb8..8c18e6f5d 100644 --- a/src/ui/edittagdialog.h +++ b/src/ui/edittagdialog.h @@ -42,14 +42,15 @@ class QPushButton; class EditTagDialog : public QDialog { Q_OBJECT -public: + public: EditTagDialog(Application* app, QWidget* parent = 0); ~EditTagDialog(); static const char* kHintText; static const char* kSettingsGroup; - void SetSongs(const SongList& songs, const PlaylistItemList& items = PlaylistItemList()); + void SetSongs(const SongList& songs, + const PlaylistItemList& items = PlaylistItemList()); PlaylistItemList playlist_items() const { return playlist_items_; } @@ -58,12 +59,12 @@ public: signals: void Error(const QString& message); -protected: + protected: bool eventFilter(QObject* o, QEvent* e); void showEvent(QShowEvent*); void hideEvent(QHideEvent*); -private slots: + private slots: void SetSongsFinished(); void AcceptFinished(); @@ -88,13 +89,17 @@ private slots: void PreviousSong(); void NextSong(); -private: + private: struct Data { Data(const Song& song = Song()) : original_(song), current_(song) {} static QVariant value(const Song& song, const QString& id); - QVariant original_value(const QString& id) const { return value(original_, id); } - QVariant current_value(const QString& id) const { return value(current_, id); } + QVariant original_value(const QString& id) const { + return value(original_, id); + } + QVariant current_value(const QString& id) const { + return value(current_, id); + } void set_value(const QString& id, const QVariant& value); @@ -105,7 +110,7 @@ private: struct FieldData { FieldData(QLabel* label = NULL, QWidget* editor = NULL, const QString& id = QString()) - : label_(label), editor_(editor), id_(id) {} + : label_(label), editor_(editor), id_(id) {} QLabel* label_; QWidget* editor_; @@ -133,7 +138,7 @@ private: QList LoadData(const SongList& songs) const; void SaveData(const QList& data); -private: + private: Ui_EditTagDialog* ui_; Application* app_; @@ -164,4 +169,4 @@ private: TrackSelectionDialog* results_dialog_; }; -#endif // EDITTAGDIALOG_H +#endif // EDITTAGDIALOG_H diff --git a/src/ui/equalizer.cpp b/src/ui/equalizer.cpp index 16b8680d3..511630ff2 100644 --- a/src/ui/equalizer.cpp +++ b/src/ui/equalizer.cpp @@ -28,16 +28,13 @@ #include "widgets/equalizerslider.h" // We probably don't need to translate these, right? -const char* Equalizer::kGainText[] = { - "60", "170", "310", "600", "1k", "3k", "6k", "12k", "14k", "16k"}; +const char* Equalizer::kGainText[] = {"60", "170", "310", "600", "1k", + "3k", "6k", "12k", "14k", "16k"}; const char* Equalizer::kSettingsGroup = "Equalizer"; -Equalizer::Equalizer(QWidget *parent) - : QDialog(parent), - ui_(new Ui_Equalizer), - loading_(false) -{ +Equalizer::Equalizer(QWidget* parent) + : QDialog(parent), ui_(new Ui_Equalizer), loading_(false) { ui_->setupUi(this); // Icons @@ -51,27 +48,27 @@ Equalizer::Equalizer(QWidget *parent) line->setFrameShadow(QFrame::Sunken); ui_->slider_container->layout()->addWidget(line); - for (int i=0 ; ienable, SIGNAL(toggled(bool)), SIGNAL(EnabledChanged(bool))); - connect(ui_->enable, SIGNAL(toggled(bool)), ui_->slider_container, SLOT(setEnabled(bool))); + connect(ui_->enable, SIGNAL(toggled(bool)), ui_->slider_container, + SLOT(setEnabled(bool))); connect(ui_->enable, SIGNAL(toggled(bool)), SLOT(Save())); - connect(ui_->preset, SIGNAL(currentIndexChanged(int)), SLOT(PresetChanged(int))); + connect(ui_->preset, SIGNAL(currentIndexChanged(int)), + SLOT(PresetChanged(int))); connect(ui_->preset_save, SIGNAL(clicked()), SLOT(SavePreset())); connect(ui_->preset_del, SIGNAL(clicked()), SLOT(DelPreset())); - connect(ui_->balance_slider, SIGNAL(valueChanged(int)), SLOT(StereoSliderChanged(int))); + connect(ui_->balance_slider, SIGNAL(valueChanged(int)), + SLOT(StereoSliderChanged(int))); QShortcut* close = new QShortcut(QKeySequence::Close, this); connect(close, SIGNAL(activated()), SLOT(close())); } -Equalizer::~Equalizer() { - delete ui_; -} +Equalizer::~Equalizer() { delete ui_; } void Equalizer::ReloadSettings() { QSettings s; @@ -82,22 +79,21 @@ void Equalizer::ReloadSettings() { // Load presets int count = s.beginReadArray("presets"); - for (int i=0 ; i()); } s.endArray(); - if (count == 0) - LoadDefaultPresets(); + if (count == 0) LoadDefaultPresets(); // Selected preset QString selected_preset = s.value("selected_preset", "Custom").toString(); - QString selected_preset_display_name = QString(tr(qPrintable(selected_preset))); + QString selected_preset_display_name = + QString(tr(qPrintable(selected_preset))); int selected_index = ui_->preset->findText(selected_preset_display_name); - if (selected_index != -1) - ui_->preset->setCurrentIndex(selected_index); + if (selected_index != -1) ui_->preset->setCurrentIndex(selected_index); // Enabled? ui_->enable->setChecked(s.value("enabled", false).toBool()); @@ -111,38 +107,59 @@ void Equalizer::ReloadSettings() { } void Equalizer::LoadDefaultPresets() { - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Custom"), Params(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Classical"), Params(0, 0, 0, 0, 0, 0, -40, -40, -40, -50)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Club"), Params(0, 0, 20, 30, 30, 30, 20, 0, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Dance"), Params(50, 35, 10, 0, 0, -30, -40, -40, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Custom"), + Params(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Classical"), + Params(0, 0, 0, 0, 0, 0, -40, -40, -40, -50)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Club"), + Params(0, 0, 20, 30, 30, 30, 20, 0, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Dance"), + Params(50, 35, 10, 0, 0, -30, -40, -40, 0, 0)); // Dubstep equalizer created by Devyn Collier Johnson - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Dubstep"), Params(0, 36, 85, 58, 30, 0, 36, 60, 96, 62, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Full Bass"), Params(70, 70, 70, 40, 20, -45, -50, -55, -55, -55)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Full Treble"), Params(-50, -50, -50, -25, 15, 55, 80, 80, 80, 85)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Full Bass + Treble"), Params(35, 30, 0, -40, -25, 10, 45, 55, 60, 60)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Laptop/Headphones"), Params(25, 50, 25, -20, 0, -30, -40, -40, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Large Hall"), Params(50, 50, 30, 30, 0, -25, -25, -25, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Live"), Params(-25, 0, 20, 25, 30, 30, 20, 15, 15, 10)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Party"), Params(35, 35, 0, 0, 0, 0, 0, 0, 35, 35)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Pop"), Params(-10, 25, 35, 40, 25, -5, -15, -15, -10, -10)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Dubstep"), + Params(0, 36, 85, 58, 30, 0, 36, 60, 96, 62, 0)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Full Bass"), + Params(70, 70, 70, 40, 20, -45, -50, -55, -55, -55)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Full Treble"), + Params(-50, -50, -50, -25, 15, 55, 80, 80, 80, 85)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Full Bass + Treble"), + Params(35, 30, 0, -40, -25, 10, 45, 55, 60, 60)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Laptop/Headphones"), + Params(25, 50, 25, -20, 0, -30, -40, -40, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Large Hall"), + Params(50, 50, 30, 30, 0, -25, -25, -25, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Live"), + Params(-25, 0, 20, 25, 30, 30, 20, 15, 15, 10)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Party"), + Params(35, 35, 0, 0, 0, 0, 0, 0, 35, 35)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Pop"), + Params(-10, 25, 35, 40, 25, -5, -15, -15, -10, -10)); // Psychedelic equalizer created by Devyn Collier Johnson - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Psychedelic"), Params(100, 100, 0, 40, 0, 67, 79, 0, 30, -100, 37)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Reggae"), Params(0, 0, -5, -30, 0, -35, -35, 0, 0, 0)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Rock"), Params(40, 25, -30, -40, -20, 20, 45, 55, 55, 55)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Soft"), Params(25, 10, -5, -15, -5, 20, 45, 50, 55, 60)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Ska"), Params(-15, -25, -25, -5, 20, 30, 45, 50, 55, 50)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Soft Rock"), Params(20, 20, 10, -5, -25, -30, -20, -5, 15, 45)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Techno"), Params(40, 30, 0, -30, -25, 0, 40, 50, 50, 45)); - AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Zero"), Params(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Psychedelic"), + Params(100, 100, 0, 40, 0, 67, 79, 0, 30, -100, 37)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Reggae"), + Params(0, 0, -5, -30, 0, -35, -35, 0, 0, 0)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Rock"), + Params(40, 25, -30, -40, -20, 20, 45, 55, 55, 55)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Soft"), + Params(25, 10, -5, -15, -5, 20, 45, 50, 55, 60)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Ska"), + Params(-15, -25, -25, -5, 20, 30, 45, 50, 55, 50)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Soft Rock"), + Params(20, 20, 10, -5, -25, -30, -20, -5, 15, 45)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Techno"), + Params(40, 30, 0, -30, -25, 0, 40, 50, 50, 45)); + AddPreset(QT_TRANSLATE_NOOP("Equalizer", "Zero"), + Params(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); } void Equalizer::AddPreset(const QString& name, const Params& params) { QString name_displayed = tr(qPrintable(name)); presets_[name] = params; if (ui_->preset->findText(name_displayed) == -1) { - ui_->preset->addItem(name_displayed, // name to display (translated) - QVariant(name) // original name - ); + ui_->preset->addItem(name_displayed, // name to display (translated) + QVariant(name) // original name + ); } } @@ -162,8 +179,7 @@ void Equalizer::PresetChanged(const QString& name) { loading_ = true; preamp_->set_value(p.preamp); - for (int i=0 ; iset_value(p.gain[i]); + for (int i = 0; i < kBands; ++i) gain_[i]->set_value(p.gain[i]); loading_ = false; ParametersChanged(); @@ -179,11 +195,11 @@ void Equalizer::SavePreset() { } QString Equalizer::SaveCurrentPreset() { - QString name = QInputDialog::getText(this, tr("Save preset"), tr("Name"), - QLineEdit::Normal, - tr(qPrintable(last_preset_)));; - if (name.isEmpty()) - return QString(); + QString name = + QInputDialog::getText(this, tr("Save preset"), tr("Name"), + QLineEdit::Normal, tr(qPrintable(last_preset_))); + ; + if (name.isEmpty()) return QString(); AddPreset(name, current_params()); Save(); @@ -193,23 +209,22 @@ QString Equalizer::SaveCurrentPreset() { void Equalizer::DelPreset() { QString name = ui_->preset->itemData(ui_->preset->currentIndex()).toString(); QString name_displayed = ui_->preset->currentText(); - if (!presets_.contains(name) || name.isEmpty()) - return; + if (!presets_.contains(name) || name.isEmpty()) return; int ret = QMessageBox::question( this, tr("Delete preset"), - tr("Are you sure you want to delete the \"%1\" preset?").arg(name_displayed), + tr("Are you sure you want to delete the \"%1\" preset?") + .arg(name_displayed), QMessageBox::Yes, QMessageBox::No); - if (ret == QMessageBox::No) - return; + if (ret == QMessageBox::No) return; presets_.remove(name); ui_->preset->removeItem(ui_->preset->currentIndex()); Save(); } -EqualizerSlider* Equalizer::AddSlider(const QString &label) { +EqualizerSlider* Equalizer::AddSlider(const QString& label) { EqualizerSlider* ret = new EqualizerSlider(label, ui_->slider_container); ui_->slider_container->layout()->addWidget(ret); connect(ret, SIGNAL(ValueChanged(int)), SLOT(ParametersChanged())); @@ -217,17 +232,13 @@ EqualizerSlider* Equalizer::AddSlider(const QString &label) { return ret; } -bool Equalizer::is_enabled() const { - return ui_->enable->isChecked(); -} +bool Equalizer::is_enabled() const { return ui_->enable->isChecked(); } -int Equalizer::preamp_value() const { - return preamp_->value(); -} +int Equalizer::preamp_value() const { return preamp_->value(); } QList Equalizer::gain_values() const { QList ret; - for (int i=0 ; ivalue(); } return ret; @@ -243,13 +254,11 @@ Equalizer::Params Equalizer::current_params() const { } float Equalizer::stereo_balance() const { - return qBound( - -1.0f, ui_->balance_slider->value() / 100.0f, 1.0f); + return qBound(-1.0f, ui_->balance_slider->value() / 100.0f, 1.0f); } void Equalizer::ParametersChanged() { - if (loading_) - return; + if (loading_) return; emit ParametersChanged(preamp_value(), gain_values()); } @@ -260,8 +269,8 @@ void Equalizer::Save() { // Presets s.beginWriteArray("presets", presets_.count()); - int i=0; - foreach (const QString& name, presets_.keys()) { + int i = 0; + foreach(const QString & name, presets_.keys()) { s.setArrayIndex(i++); s.setValue("name", name); s.setValue("params", QVariant::fromValue(presets_[name])); @@ -270,7 +279,7 @@ void Equalizer::Save() { // Selected preset s.setValue("selected_preset", - ui_->preset->itemData(ui_->preset->currentIndex()).toString()); + ui_->preset->itemData(ui_->preset->currentIndex()).toString()); // Enabled? s.setValue("enabled", ui_->enable->isChecked()); @@ -280,41 +289,42 @@ void Equalizer::Save() { void Equalizer::closeEvent(QCloseEvent* e) { QString name = ui_->preset->currentText(); - if (!presets_.contains(name)) - return; + if (!presets_.contains(name)) return; - if (presets_[name] == current_params()) - return; + if (presets_[name] == current_params()) return; SavePreset(); } - -Equalizer::Params::Params() - : preamp(0) -{ - for (int i=0 ; i>(QDataStream& s, Equalizer::Params& p) { +QDataStream& operator>>(QDataStream& s, Equalizer::Params& p) { s >> p.preamp; - for (int i=0 ; i> p.gain[i]; + for (int i = 0; i < Equalizer::kBands; ++i) s >> p.gain[i]; return s; } diff --git a/src/ui/equalizer.h b/src/ui/equalizer.h index 6e3eb0d9e..30b20f280 100644 --- a/src/ui/equalizer.h +++ b/src/ui/equalizer.h @@ -29,7 +29,7 @@ class Equalizer : public QDialog { Q_OBJECT public: - Equalizer(QWidget *parent = 0); + Equalizer(QWidget* parent = 0); ~Equalizer(); static const int kBands = 10; @@ -41,8 +41,8 @@ class Equalizer : public QDialog { Params(int g0, int g1, int g2, int g3, int g4, int g5, int g6, int g7, int g8, int g9, int pre = 0); - bool operator ==(const Params& other) const; - bool operator !=(const Params& other) const; + bool operator==(const Params& other) const; + bool operator!=(const Params& other) const; int preamp; int gain[kBands]; @@ -54,13 +54,13 @@ class Equalizer : public QDialog { Params current_params() const; float stereo_balance() const; - signals: +signals: void EnabledChanged(bool enabled); void ParametersChanged(int preamp, const QList& band_gains); void StereoBalanceChanged(float balance); protected: - void closeEvent(QCloseEvent *); + void closeEvent(QCloseEvent*); private slots: void ParametersChanged(); @@ -91,7 +91,7 @@ class Equalizer : public QDialog { }; Q_DECLARE_METATYPE(Equalizer::Params); -QDataStream &operator<<(QDataStream& s, const Equalizer::Params& p); -QDataStream &operator>>(QDataStream& s, Equalizer::Params& p); +QDataStream& operator<<(QDataStream& s, const Equalizer::Params& p); +QDataStream& operator>>(QDataStream& s, Equalizer::Params& p); -#endif // EQUALIZER_H +#endif // EQUALIZER_H diff --git a/src/ui/flowlayout.cpp b/src/ui/flowlayout.cpp index dc4bb0cc9..d75d9fdcb 100644 --- a/src/ui/flowlayout.cpp +++ b/src/ui/flowlayout.cpp @@ -42,172 +42,143 @@ #include "flowlayout.h" //! [1] -FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing) - : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) -{ - setContentsMargins(margin, margin, margin, margin); +FlowLayout::FlowLayout(QWidget* parent, int margin, int hSpacing, int vSpacing) + : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) { + setContentsMargins(margin, margin, margin, margin); } FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) - : m_hSpace(hSpacing), m_vSpace(vSpacing) -{ - setContentsMargins(margin, margin, margin, margin); + : m_hSpace(hSpacing), m_vSpace(vSpacing) { + setContentsMargins(margin, margin, margin, margin); } //! [1] //! [2] -FlowLayout::~FlowLayout() -{ - QLayoutItem *item; - while ((item = takeAt(0))) - delete item; +FlowLayout::~FlowLayout() { + QLayoutItem* item; + while ((item = takeAt(0))) delete item; } //! [2] //! [3] -void FlowLayout::addItem(QLayoutItem *item) -{ - itemList.append(item); -} +void FlowLayout::addItem(QLayoutItem* item) { itemList.append(item); } //! [3] //! [4] -int FlowLayout::horizontalSpacing() const -{ - if (m_hSpace >= 0) { - return m_hSpace; - } else { - return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); - } +int FlowLayout::horizontalSpacing() const { + if (m_hSpace >= 0) { + return m_hSpace; + } else { + return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); + } } -int FlowLayout::verticalSpacing() const -{ - if (m_vSpace >= 0) { - return m_vSpace; - } else { - return smartSpacing(QStyle::PM_LayoutVerticalSpacing); - } +int FlowLayout::verticalSpacing() const { + if (m_vSpace >= 0) { + return m_vSpace; + } else { + return smartSpacing(QStyle::PM_LayoutVerticalSpacing); + } } //! [4] //! [5] -int FlowLayout::count() const -{ - return itemList.size(); +int FlowLayout::count() const { return itemList.size(); } + +QLayoutItem* FlowLayout::itemAt(int index) const { + return itemList.value(index); } -QLayoutItem *FlowLayout::itemAt(int index) const -{ - return itemList.value(index); -} - -QLayoutItem *FlowLayout::takeAt(int index) -{ - if (index >= 0 && index < itemList.size()) - return itemList.takeAt(index); - else - return 0; +QLayoutItem* FlowLayout::takeAt(int index) { + if (index >= 0 && index < itemList.size()) + return itemList.takeAt(index); + else + return 0; } //! [5] //! [6] -Qt::Orientations FlowLayout::expandingDirections() const -{ - return 0; -} +Qt::Orientations FlowLayout::expandingDirections() const { return 0; } //! [6] //! [7] -bool FlowLayout::hasHeightForWidth() const -{ - return true; -} +bool FlowLayout::hasHeightForWidth() const { return true; } -int FlowLayout::heightForWidth(int width) const -{ - int height = doLayout(QRect(0, 0, width, 0), true); - return height; +int FlowLayout::heightForWidth(int width) const { + int height = doLayout(QRect(0, 0, width, 0), true); + return height; } //! [7] //! [8] -void FlowLayout::setGeometry(const QRect &rect) -{ - QLayout::setGeometry(rect); - doLayout(rect, false); +void FlowLayout::setGeometry(const QRect& rect) { + QLayout::setGeometry(rect); + doLayout(rect, false); } -QSize FlowLayout::sizeHint() const -{ - return minimumSize(); -} +QSize FlowLayout::sizeHint() const { return minimumSize(); } -QSize FlowLayout::minimumSize() const -{ - QSize size; - QLayoutItem *item; - foreach (item, itemList) - size = size.expandedTo(item->minimumSize()); +QSize FlowLayout::minimumSize() const { + QSize size; + QLayoutItem* item; + foreach(item, itemList) + size = size.expandedTo(item->minimumSize()); - size += QSize(2*margin(), 2*margin()); - return size; + size += QSize(2 * margin(), 2 * margin()); + return size; } //! [8] //! [9] -int FlowLayout::doLayout(const QRect &rect, bool testOnly) const -{ - int left, top, right, bottom; - getContentsMargins(&left, &top, &right, &bottom); - QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); - int x = effectiveRect.x(); - int y = effectiveRect.y(); - int lineHeight = 0; -//! [9] +int FlowLayout::doLayout(const QRect& rect, bool testOnly) const { + int left, top, right, bottom; + getContentsMargins(&left, &top, &right, &bottom); + QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); + int x = effectiveRect.x(); + int y = effectiveRect.y(); + int lineHeight = 0; + //! [9] -//! [10] - QLayoutItem *item; - foreach (item, itemList) { - QWidget *wid = item->widget(); - int spaceX = horizontalSpacing(); - if (spaceX == -1) - spaceX = wid->style()->layoutSpacing( - QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal); - int spaceY = verticalSpacing(); - if (spaceY == -1) - spaceY = wid->style()->layoutSpacing( - QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical); -//! [10] -//! [11] - int nextX = x + item->sizeHint().width() + spaceX; - if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { - x = effectiveRect.x(); - y = y + lineHeight + spaceY; - nextX = x + item->sizeHint().width() + spaceX; - lineHeight = 0; - } - - if (!testOnly) - item->setGeometry(QRect(QPoint(x, y), item->sizeHint())); - - x = nextX; - lineHeight = qMax(lineHeight, item->sizeHint().height()); + //! [10] + QLayoutItem* item; + foreach(item, itemList) { + QWidget* wid = item->widget(); + int spaceX = horizontalSpacing(); + if (spaceX == -1) + spaceX = wid->style()->layoutSpacing( + QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal); + int spaceY = verticalSpacing(); + if (spaceY == -1) + spaceY = wid->style()->layoutSpacing( + QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical); + //! [10] + //! [11] + int nextX = x + item->sizeHint().width() + spaceX; + if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { + x = effectiveRect.x(); + y = y + lineHeight + spaceY; + nextX = x + item->sizeHint().width() + spaceX; + lineHeight = 0; } - return y + lineHeight - rect.y() + bottom; + + if (!testOnly) item->setGeometry(QRect(QPoint(x, y), item->sizeHint())); + + x = nextX; + lineHeight = qMax(lineHeight, item->sizeHint().height()); + } + return y + lineHeight - rect.y() + bottom; } //! [11] //! [12] -int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const -{ - QObject *parent = this->parent(); - if (!parent) { - return -1; - } else if (parent->isWidgetType()) { - QWidget *pw = static_cast(parent); - return pw->style()->pixelMetric(pm, 0, pw); - } else { - return static_cast(parent)->spacing(); - } +int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const { + QObject* parent = this->parent(); + if (!parent) { + return -1; + } else if (parent->isWidgetType()) { + QWidget* pw = static_cast(parent); + return pw->style()->pixelMetric(pm, 0, pw); + } else { + return static_cast(parent)->spacing(); + } } //! [12] diff --git a/src/ui/flowlayout.h b/src/ui/flowlayout.h index b7a5848b2..a7ac39925 100644 --- a/src/ui/flowlayout.h +++ b/src/ui/flowlayout.h @@ -46,33 +46,33 @@ #include #include //! [0] -class FlowLayout : public QLayout -{ -public: - FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1); - FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1); - ~FlowLayout(); +class FlowLayout : public QLayout { + public: + FlowLayout(QWidget* parent, int margin = -1, int hSpacing = -1, + int vSpacing = -1); + FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1); + ~FlowLayout(); - void addItem(QLayoutItem *item); - int horizontalSpacing() const; - int verticalSpacing() const; - Qt::Orientations expandingDirections() const; - bool hasHeightForWidth() const; - int heightForWidth(int) const; - int count() const; - QLayoutItem *itemAt(int index) const; - QSize minimumSize() const; - void setGeometry(const QRect &rect); - QSize sizeHint() const; - QLayoutItem *takeAt(int index); + void addItem(QLayoutItem* item); + int horizontalSpacing() const; + int verticalSpacing() const; + Qt::Orientations expandingDirections() const; + bool hasHeightForWidth() const; + int heightForWidth(int) const; + int count() const; + QLayoutItem* itemAt(int index) const; + QSize minimumSize() const; + void setGeometry(const QRect& rect); + QSize sizeHint() const; + QLayoutItem* takeAt(int index); -private: - int doLayout(const QRect &rect, bool testOnly) const; - int smartSpacing(QStyle::PixelMetric pm) const; + private: + int doLayout(const QRect& rect, bool testOnly) const; + int smartSpacing(QStyle::PixelMetric pm) const; - QList itemList; - int m_hSpace; - int m_vSpace; + QList itemList; + int m_hSpace; + int m_vSpace; }; //! [0] diff --git a/src/ui/globalshortcutgrabber.cpp b/src/ui/globalshortcutgrabber.cpp index 8cba96390..b7dbe5ecf 100644 --- a/src/ui/globalshortcutgrabber.cpp +++ b/src/ui/globalshortcutgrabber.cpp @@ -21,28 +21,23 @@ #include #include -GlobalShortcutGrabber::GlobalShortcutGrabber(QWidget *parent) - : QDialog(parent), - ui_(new Ui::GlobalShortcutGrabber) -{ +GlobalShortcutGrabber::GlobalShortcutGrabber(QWidget* parent) + : QDialog(parent), ui_(new Ui::GlobalShortcutGrabber) { ui_->setupUi(this); modifier_keys_ << Qt::Key_Shift << Qt::Key_Control << Qt::Key_Meta << Qt::Key_Alt << Qt::Key_AltGr; } -GlobalShortcutGrabber::~GlobalShortcutGrabber() { - delete ui_; -} +GlobalShortcutGrabber::~GlobalShortcutGrabber() { delete ui_; } -QKeySequence GlobalShortcutGrabber::GetKey(const QString &name) { +QKeySequence GlobalShortcutGrabber::GetKey(const QString& name) { ui_->label->setText(tr("Press a key combination to use for %1...").arg(name)); ui_->combo->clear(); ret_ = QKeySequence(); - if (exec() == QDialog::Rejected) - return QKeySequence(); + if (exec() == QDialog::Rejected) return QKeySequence(); return ret_; } @@ -81,8 +76,7 @@ bool GlobalShortcutGrabber::event(QEvent* e) { UpdateText(); - if (!modifier_keys_.contains(ke->key())) - accept(); + if (!modifier_keys_.contains(ke->key())) accept(); return true; } return QDialog::event(e); @@ -91,5 +85,3 @@ bool GlobalShortcutGrabber::event(QEvent* e) { void GlobalShortcutGrabber::UpdateText() { ui_->combo->setText("" + ret_.toString(QKeySequence::NativeText) + ""); } - - diff --git a/src/ui/globalshortcutgrabber.h b/src/ui/globalshortcutgrabber.h index 6f088860c..74319b7f5 100644 --- a/src/ui/globalshortcutgrabber.h +++ b/src/ui/globalshortcutgrabber.h @@ -39,9 +39,9 @@ class GlobalShortcutGrabber : public QDialog { QKeySequence GetKey(const QString& name); protected: - bool event(QEvent *); - void showEvent(QShowEvent *); - void hideEvent(QHideEvent *); + bool event(QEvent*); + void showEvent(QShowEvent*); + void hideEvent(QHideEvent*); void grabKeyboard(); void releaseKeyboard(); @@ -59,4 +59,4 @@ class GlobalShortcutGrabber : public QDialog { MacMonitorWrapper* wrapper_; }; -#endif // GLOBALSHORTCUTGRABBER_H +#endif // GLOBALSHORTCUTGRABBER_H diff --git a/src/ui/globalshortcutssettingspage.cpp b/src/ui/globalshortcutssettingspage.cpp index 45e63ed57..e422f1e2c 100644 --- a/src/ui/globalshortcutssettingspage.cpp +++ b/src/ui/globalshortcutssettingspage.cpp @@ -33,11 +33,10 @@ #include GlobalShortcutsSettingsPage::GlobalShortcutsSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_GlobalShortcutsSettingsPage), - initialised_(false), - grabber_(new GlobalShortcutGrabber) -{ + : SettingsPage(dialog), + ui_(new Ui_GlobalShortcutsSettingsPage), + initialised_(false), + grabber_(new GlobalShortcutGrabber) { ui_->setupUi(this); ui_->shortcut_options->setEnabled(false); ui_->list->header()->setResizeMode(QHeaderView::ResizeToContents); @@ -45,17 +44,18 @@ GlobalShortcutsSettingsPage::GlobalShortcutsSettingsPage(SettingsDialog* dialog) settings_.beginGroup(GlobalShortcuts::kSettingsGroup); - connect(ui_->list, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), SLOT(ItemClicked(QTreeWidgetItem*))); + connect(ui_->list, + SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), + SLOT(ItemClicked(QTreeWidgetItem*))); connect(ui_->radio_none, SIGNAL(clicked()), SLOT(NoneClicked())); connect(ui_->radio_default, SIGNAL(clicked()), SLOT(DefaultClicked())); connect(ui_->radio_custom, SIGNAL(clicked()), SLOT(ChangeClicked())); connect(ui_->change, SIGNAL(clicked()), SLOT(ChangeClicked())); - connect(ui_->gnome_open, SIGNAL(clicked()), SLOT(OpenGnomeKeybindingProperties())); + connect(ui_->gnome_open, SIGNAL(clicked()), + SLOT(OpenGnomeKeybindingProperties())); } -GlobalShortcutsSettingsPage::~GlobalShortcutsSettingsPage() { - delete ui_; -} +GlobalShortcutsSettingsPage::~GlobalShortcutsSettingsPage() { delete ui_; } bool GlobalShortcutsSettingsPage::IsEnabled() const { #ifdef Q_OS_MAC @@ -74,19 +74,22 @@ void GlobalShortcutsSettingsPage::Load() { if (!initialised_) { initialised_ = true; - connect(ui_->mac_open, SIGNAL(clicked()), manager, SLOT(ShowMacAccessibilityDialog())); + connect(ui_->mac_open, SIGNAL(clicked()), manager, + SLOT(ShowMacAccessibilityDialog())); if (!manager->IsGsdAvailable()) { ui_->gnome_container->hide(); } - foreach (const GlobalShortcuts::Shortcut& s, manager->shortcuts().values()) { + foreach(const GlobalShortcuts::Shortcut & s, + manager->shortcuts().values()) { Shortcut shortcut; shortcut.s = s; shortcut.key = s.action->shortcut(); - shortcut.item = new QTreeWidgetItem(ui_->list, - QStringList() << s.action->text() - << s.action->shortcut().toString(QKeySequence::NativeText)); + shortcut.item = new QTreeWidgetItem( + ui_->list, QStringList() << s.action->text() + << s.action->shortcut().toString( + QKeySequence::NativeText)); shortcut.item->setData(0, Qt::UserRole, s.id); shortcuts_[s.id] = shortcut; } @@ -95,7 +98,7 @@ void GlobalShortcutsSettingsPage::Load() { ItemClicked(ui_->list->topLevelItem(0)); } - foreach (const Shortcut& s, shortcuts_.values()) { + foreach(const Shortcut & s, shortcuts_.values()) { SetShortcut(s.s.id, s.s.action->shortcut()); } @@ -107,7 +110,8 @@ void GlobalShortcutsSettingsPage::Load() { ui_->mac_container->setVisible(!manager->IsMacAccessibilityEnabled()); } -void GlobalShortcutsSettingsPage::SetShortcut(const QString& id, const QKeySequence& key) { +void GlobalShortcutsSettingsPage::SetShortcut(const QString& id, + const QKeySequence& key) { Shortcut& shortcut = shortcuts_[id]; shortcut.key = key; @@ -115,7 +119,7 @@ void GlobalShortcutsSettingsPage::SetShortcut(const QString& id, const QKeySeque } void GlobalShortcutsSettingsPage::Save() { - foreach (const Shortcut& s, shortcuts_.values()) { + foreach(const Shortcut & s, shortcuts_.values()) { s.s.action->setShortcut(s.key); s.s.shortcut->setKey(s.key); settings_.setValue(s.s.id, s.key.toString()); @@ -132,7 +136,8 @@ void GlobalShortcutsSettingsPage::ItemClicked(QTreeWidgetItem* item) { // Enable options ui_->shortcut_options->setEnabled(true); - ui_->shortcut_options->setTitle(tr("Shortcut for %1").arg(shortcut.s.action->text())); + ui_->shortcut_options->setTitle( + tr("Shortcut for %1").arg(shortcut.s.action->text())); if (shortcut.key == shortcut.s.default_key) ui_->radio_default->setChecked(true); @@ -156,13 +161,11 @@ void GlobalShortcutsSettingsPage::ChangeClicked() { QKeySequence key = grabber_->GetKey(shortcuts_[current_id_].s.action->text()); manager->Register(); - if (key.isEmpty()) - return; + if (key.isEmpty()) return; // Check if this key sequence is used by any other actions - foreach (const QString& id, shortcuts_.keys()) { - if (shortcuts_[id].key == key) - SetShortcut(id, QKeySequence()); + foreach(const QString & id, shortcuts_.keys()) { + if (shortcuts_[id].key == key) SetShortcut(id, QKeySequence()); } ui_->radio_custom->setChecked(true); @@ -171,11 +174,11 @@ void GlobalShortcutsSettingsPage::ChangeClicked() { void GlobalShortcutsSettingsPage::OpenGnomeKeybindingProperties() { if (!QProcess::startDetached("gnome-keybinding-properties")) { - if (!QProcess::startDetached("gnome-control-center", - QStringList() << "keyboard")) { + if (!QProcess::startDetached("gnome-control-center", QStringList() + << "keyboard")) { QMessageBox::warning(this, "Error", - tr("The \"%1\" command could not be started.") - .arg("gnome-keybinding-properties")); + tr("The \"%1\" command could not be started.") + .arg("gnome-keybinding-properties")); } } } diff --git a/src/ui/globalshortcutssettingspage.h b/src/ui/globalshortcutssettingspage.h index 593b14a5c..1a23c5d30 100644 --- a/src/ui/globalshortcutssettingspage.h +++ b/src/ui/globalshortcutssettingspage.h @@ -32,9 +32,9 @@ class Ui_GlobalShortcutsSettingsPage; class GlobalShortcutGrabber; class GlobalShortcutsSettingsPage : public SettingsPage { - Q_OBJECT + Q_OBJECT -public: + public: GlobalShortcutsSettingsPage(SettingsDialog* dialog); ~GlobalShortcutsSettingsPage(); @@ -43,7 +43,7 @@ public: void Load(); void Save(); -private slots: + private slots: void ItemClicked(QTreeWidgetItem*); void NoneClicked(); void DefaultClicked(); @@ -51,7 +51,7 @@ private slots: void OpenGnomeKeybindingProperties(); -private: + private: struct Shortcut { GlobalShortcuts::Shortcut s; QKeySequence key; @@ -60,7 +60,7 @@ private: void SetShortcut(const QString& id, const QKeySequence& key); -private: + private: Ui_GlobalShortcutsSettingsPage* ui_; bool initialised_; @@ -72,4 +72,4 @@ private: QString current_id_; }; -#endif // GLOBALSHORTCUTSSETTINGSPAGE_H +#endif // GLOBALSHORTCUTSSETTINGSPAGE_H diff --git a/src/ui/iconloader.cpp b/src/ui/iconloader.cpp index a114af07a..cf05ca22a 100644 --- a/src/ui/iconloader.cpp +++ b/src/ui/iconloader.cpp @@ -28,29 +28,25 @@ void IconLoader::Init() { sizes_ << 22 << 32 << 48; } -QIcon IconLoader::Load(const QString &name) { +QIcon IconLoader::Load(const QString& name) { QIcon ret; - if (name.isEmpty()) - return ret; + if (name.isEmpty()) return ret; #if QT_VERSION >= 0x040600 // Try to load it from the theme initially ret = QIcon::fromTheme(name); - if (!ret.isNull()) - return ret; + if (!ret.isNull()) return ret; #endif // Otherwise use our fallback theme const QString path(":/icons/%1x%2/%3.png"); - foreach (int size, sizes_) { + foreach(int size, sizes_) { QString filename(path.arg(size).arg(size).arg(name)); - if (QFile::exists(filename)) - ret.addFile(filename, QSize(size, size)); + if (QFile::exists(filename)) ret.addFile(filename, QSize(size, size)); } - if (ret.isNull()) - qLog(Warning) << "Couldn't load icon" << name; + if (ret.isNull()) qLog(Warning) << "Couldn't load icon" << name; return ret; } diff --git a/src/ui/iconloader.h b/src/ui/iconloader.h index f81f7a483..01b499a59 100644 --- a/src/ui/iconloader.h +++ b/src/ui/iconloader.h @@ -21,14 +21,14 @@ #include class IconLoader { -public: + public: static void Init(); static QIcon Load(const QString& name); -private: + private: IconLoader() {} static QList sizes_; }; -#endif // ICONLOADER_H +#endif // ICONLOADER_H diff --git a/src/ui/macscreensaver.cpp b/src/ui/macscreensaver.cpp index 41337df77..67b8fd7f6 100644 --- a/src/ui/macscreensaver.cpp +++ b/src/ui/macscreensaver.cpp @@ -24,22 +24,16 @@ // kIOPMAssertionTypePreventUserIdleDisplaySleep from Lion. #define kLionDisplayAssertion CFSTR("PreventUserIdleDisplaySleep") -MacScreensaver::MacScreensaver() - : assertion_id_(0) { -} +MacScreensaver::MacScreensaver() : assertion_id_(0) {} void MacScreensaver::Inhibit() { CFStringRef assertion_type = (Utilities::GetMacVersion() >= 7) - ? kLionDisplayAssertion - : kIOPMAssertionTypeNoDisplaySleep; + ? kLionDisplayAssertion + : kIOPMAssertionTypeNoDisplaySleep; IOPMAssertionCreateWithName( - assertion_type, - kIOPMAssertionLevelOn, - CFSTR("Showing full-screen Clementine visualisations"), - &assertion_id_); + assertion_type, kIOPMAssertionLevelOn, + CFSTR("Showing full-screen Clementine visualisations"), &assertion_id_); } -void MacScreensaver::Uninhibit() { - IOPMAssertionRelease(assertion_id_); -} +void MacScreensaver::Uninhibit() { IOPMAssertionRelease(assertion_id_); } diff --git a/src/ui/macsystemtrayicon.h b/src/ui/macsystemtrayicon.h index 1cfa5f6ab..3b9741c31 100644 --- a/src/ui/macsystemtrayicon.h +++ b/src/ui/macsystemtrayicon.h @@ -27,7 +27,7 @@ class MacSystemTrayIconPrivate; class MacSystemTrayIcon : public SystemTrayIcon { Q_OBJECT -public: + public: MacSystemTrayIcon(QObject* parent = 0); ~MacSystemTrayIcon(); @@ -38,21 +38,21 @@ public: void SetNowPlaying(const Song& song, const QString& image_path); void ClearNowPlaying(); -private: + private: void SetupMenuItem(QAction* action); -private slots: + private slots: void ActionChanged(); -protected: + protected: // SystemTrayIcon void UpdateIcon(); -private: + private: QPixmap orange_icon_; QPixmap grey_icon_; std::unique_ptr p_; Q_DISABLE_COPY(MacSystemTrayIcon); }; -#endif // MACSYSTEMTRAYICON_H +#endif // MACSYSTEMTRAYICON_H diff --git a/src/ui/mainwindow.cpp b/src/ui/mainwindow.cpp index 7445db88e..a244133be 100644 --- a/src/ui/mainwindow.cpp +++ b/src/ui/mainwindow.cpp @@ -38,12 +38,11 @@ #include #ifdef Q_OS_WIN32 -# include +#include #endif #include - #include "core/appearance.h" #include "core/application.h" #include "core/backgroundstreams.h" @@ -129,24 +128,24 @@ #include "widgets/trackslider.h" #ifdef Q_OS_DARWIN -# include "ui/macsystemtrayicon.h" +#include "ui/macsystemtrayicon.h" #endif #ifdef HAVE_LIBLASTFM -# include "internet/lastfmservice.h" +#include "internet/lastfmservice.h" #endif #ifdef HAVE_WIIMOTEDEV -# include "wiimotedev/shortcuts.h" +#include "wiimotedev/shortcuts.h" #endif #ifdef ENABLE_VISUALISATIONS -# include "visualisations/visualisationcontainer.h" +#include "visualisations/visualisationcontainer.h" #endif #ifdef HAVE_MOODBAR -# include "moodbar/moodbarcontroller.h" -# include "moodbar/moodbarproxystyle.h" +#include "moodbar/moodbarcontroller.h" +#include "moodbar/moodbarproxystyle.h" #endif #ifdef Q_OS_DARWIN @@ -155,44 +154,40 @@ void qt_mac_set_dock_menu(QMenu*); #endif const char* MainWindow::kSettingsGroup = "MainWindow"; -const char* MainWindow::kAllFilesFilterSpec = - QT_TR_NOOP("All Files (*)"); +const char* MainWindow::kAllFilesFilterSpec = QT_TR_NOOP("All Files (*)"); -MainWindow::MainWindow(Application* app, - SystemTrayIcon* tray_icon, - OSD* osd, +MainWindow::MainWindow(Application* app, SystemTrayIcon* tray_icon, OSD* osd, QWidget* parent) - : QMainWindow(parent), - ui_(new Ui_MainWindow), - thumbbar_(new Windows7ThumbBar(this)), - app_(app), - tray_icon_(tray_icon), - osd_(osd), - global_shortcuts_(new GlobalShortcuts(this)), - remote_(nullptr), - global_search_view_(new GlobalSearchView(app_, this)), - library_view_(new LibraryViewContainer(this)), - file_view_(new FileView(this)), - playlist_list_(new PlaylistListContainer(this)), - internet_view_(new InternetViewContainer(this)), - device_view_container_(new DeviceViewContainer(this)), - device_view_(device_view_container_->view()), - song_info_view_(new SongInfoView(this)), - artist_info_view_(new ArtistInfoView(this)), - equalizer_(new Equalizer), - organise_dialog_(new OrganiseDialog(app_->task_manager())), - playlist_menu_(new QMenu(this)), - playlist_add_to_another_(nullptr), - playlistitem_actions_separator_(nullptr), - library_sort_model_(new QSortFilterProxyModel(this)), - track_position_timer_(new QTimer(this)), - was_maximized_(false), - saved_playback_position_(0), - saved_playback_state_(Engine::Empty), - doubleclick_addmode_(AddBehaviour_Append), - doubleclick_playmode_(PlayBehaviour_IfStopped), - menu_playmode_(PlayBehaviour_IfStopped) -{ + : QMainWindow(parent), + ui_(new Ui_MainWindow), + thumbbar_(new Windows7ThumbBar(this)), + app_(app), + tray_icon_(tray_icon), + osd_(osd), + global_shortcuts_(new GlobalShortcuts(this)), + remote_(nullptr), + global_search_view_(new GlobalSearchView(app_, this)), + library_view_(new LibraryViewContainer(this)), + file_view_(new FileView(this)), + playlist_list_(new PlaylistListContainer(this)), + internet_view_(new InternetViewContainer(this)), + device_view_container_(new DeviceViewContainer(this)), + device_view_(device_view_container_->view()), + song_info_view_(new SongInfoView(this)), + artist_info_view_(new ArtistInfoView(this)), + equalizer_(new Equalizer), + organise_dialog_(new OrganiseDialog(app_->task_manager())), + playlist_menu_(new QMenu(this)), + playlist_add_to_another_(nullptr), + playlistitem_actions_separator_(nullptr), + library_sort_model_(new QSortFilterProxyModel(this)), + track_position_timer_(new QTimer(this)), + was_maximized_(false), + saved_playback_position_(0), + saved_playback_state_(Engine::Empty), + doubleclick_addmode_(AddBehaviour_Append), + doubleclick_playmode_(PlayBehaviour_IfStopped), + menu_playmode_(PlayBehaviour_IfStopped) { qLog(Debug) << "Starting"; connect(app, SIGNAL(ErrorAdded(QString)), SLOT(ShowErrorDialog(QString))); @@ -223,18 +218,27 @@ MainWindow::MainWindow(Application* app, app_->global_search()->ReloadSettings(); global_search_view_->ReloadSettings(); - connect(global_search_view_, SIGNAL(AddToPlaylist(QMimeData*)), SLOT(AddToPlaylist(QMimeData*))); + connect(global_search_view_, SIGNAL(AddToPlaylist(QMimeData*)), + SLOT(AddToPlaylist(QMimeData*))); // Add tabs to the fancy tab widget - ui_->tabs->AddTab(global_search_view_, IconLoader::Load("search"), tr("Search")); - ui_->tabs->AddTab(library_view_, IconLoader::Load("folder-sound"), tr("Library")); + ui_->tabs->AddTab(global_search_view_, IconLoader::Load("search"), + tr("Search")); + ui_->tabs->AddTab(library_view_, IconLoader::Load("folder-sound"), + tr("Library")); ui_->tabs->AddTab(file_view_, IconLoader::Load("document-open"), tr("Files")); - ui_->tabs->AddTab(playlist_list_, IconLoader::Load("view-media-playlist"), tr("Playlists")); - ui_->tabs->AddTab(internet_view_, IconLoader::Load("applications-internet"), tr("Internet")); - ui_->tabs->AddTab(device_view_container_, IconLoader::Load("multimedia-player-ipod-mini-blue"), tr("Devices")); + ui_->tabs->AddTab(playlist_list_, IconLoader::Load("view-media-playlist"), + tr("Playlists")); + ui_->tabs->AddTab(internet_view_, IconLoader::Load("applications-internet"), + tr("Internet")); + ui_->tabs->AddTab(device_view_container_, + IconLoader::Load("multimedia-player-ipod-mini-blue"), + tr("Devices")); ui_->tabs->AddSpacer(); - ui_->tabs->AddTab(song_info_view_, IconLoader::Load("view-media-lyrics"), tr("Song info")); - ui_->tabs->AddTab(artist_info_view_, IconLoader::Load("x-clementine-artist"), tr("Artist info")); + ui_->tabs->AddTab(song_info_view_, IconLoader::Load("view-media-lyrics"), + tr("Song info")); + ui_->tabs->AddTab(artist_info_view_, IconLoader::Load("x-clementine-artist"), + tr("Artist info")); // Add the now playing widget to the fancy tab widget ui_->tabs->AddBottomWidget(ui_->now_playing); @@ -242,7 +246,8 @@ MainWindow::MainWindow(Application* app, ui_->tabs->SetBackgroundPixmap(QPixmap(":/sidebar_background.png")); track_position_timer_->setInterval(1000); - connect(track_position_timer_, SIGNAL(timeout()), SLOT(UpdateTrackPosition())); + connect(track_position_timer_, SIGNAL(timeout()), + SLOT(UpdateTrackPosition())); // Start initialising the player qLog(Debug) << "Initialising player"; @@ -258,7 +263,8 @@ MainWindow::MainWindow(Application* app, library_sort_model_->setSortLocaleAware(true); library_sort_model_->sort(0); - connect(ui_->playlist, SIGNAL(ViewSelectionModelChanged()), SLOT(PlaylistViewSelectionModelChanged())); + connect(ui_->playlist, SIGNAL(ViewSelectionModelChanged()), + SLOT(PlaylistViewSelectionModelChanged())); ui_->playlist->SetManager(app_->playlist_manager()); ui_->playlist->view()->SetApplication(app_); @@ -268,12 +274,14 @@ MainWindow::MainWindow(Application* app, device_view_->SetApplication(app_); playlist_list_->SetApplication(app_); - organise_dialog_->SetDestinationModel(app_->library()->model()->directory_model()); + organise_dialog_->SetDestinationModel( + app_->library()->model()->directory_model()); // Icons qLog(Debug) << "Creating UI"; ui_->action_about->setIcon(IconLoader::Load("help-about")); - ui_->action_about_qt->setIcon(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png")); + ui_->action_about_qt->setIcon( + QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png")); ui_->action_add_file->setIcon(IconLoader::Load("document-open")); ui_->action_add_folder->setIcon(IconLoader::Load("document-open-folder")); ui_->action_add_stream->setIcon(IconLoader::Load("document-open-remote")); @@ -294,7 +302,8 @@ MainWindow::MainWindow(Application* app, ui_->action_shuffle->setIcon(IconLoader::Load("x-clementine-shuffle")); ui_->action_shuffle_mode->setIcon(IconLoader::Load("media-playlist-shuffle")); ui_->action_stop->setIcon(IconLoader::Load("media-playback-stop")); - ui_->action_stop_after_this_track->setIcon(IconLoader::Load("media-playback-stop")); + ui_->action_stop_after_this_track->setIcon( + IconLoader::Load("media-playback-stop")); ui_->action_new_playlist->setIcon(IconLoader::Load("document-new")); ui_->action_load_playlist->setIcon(IconLoader::Load("document-open")); ui_->action_save_playlist->setIcon(IconLoader::Load("document-save")); @@ -302,71 +311,100 @@ MainWindow::MainWindow(Application* app, ui_->action_rain->setIcon(IconLoader::Load("weather-showers-scattered")); // File view connections - connect(file_view_, SIGNAL(AddToPlaylist(QMimeData*)), SLOT(AddToPlaylist(QMimeData*))); - connect(file_view_, SIGNAL(PathChanged(QString)), SLOT(FilePathChanged(QString))); - connect(file_view_, SIGNAL(CopyToLibrary(QList)), SLOT(CopyFilesToLibrary(QList))); - connect(file_view_, SIGNAL(MoveToLibrary(QList)), SLOT(MoveFilesToLibrary(QList))); - connect(file_view_, SIGNAL(EditTags(QList)), SLOT(EditFileTags(QList))); - connect(file_view_, SIGNAL(CopyToDevice(QList)), SLOT(CopyFilesToDevice(QList))); + connect(file_view_, SIGNAL(AddToPlaylist(QMimeData*)), + SLOT(AddToPlaylist(QMimeData*))); + connect(file_view_, SIGNAL(PathChanged(QString)), + SLOT(FilePathChanged(QString))); + connect(file_view_, SIGNAL(CopyToLibrary(QList)), + SLOT(CopyFilesToLibrary(QList))); + connect(file_view_, SIGNAL(MoveToLibrary(QList)), + SLOT(MoveFilesToLibrary(QList))); + connect(file_view_, SIGNAL(EditTags(QList)), + SLOT(EditFileTags(QList))); + connect(file_view_, SIGNAL(CopyToDevice(QList)), + SLOT(CopyFilesToDevice(QList))); file_view_->SetTaskManager(app_->task_manager()); // Action connections - connect(ui_->action_next_track, SIGNAL(triggered()), app_->player(), SLOT(Next())); - connect(ui_->action_previous_track, SIGNAL(triggered()), app_->player(), SLOT(Previous())); - connect(ui_->action_play_pause, SIGNAL(triggered()), app_->player(), SLOT(PlayPause())); + connect(ui_->action_next_track, SIGNAL(triggered()), app_->player(), + SLOT(Next())); + connect(ui_->action_previous_track, SIGNAL(triggered()), app_->player(), + SLOT(Previous())); + connect(ui_->action_play_pause, SIGNAL(triggered()), app_->player(), + SLOT(PlayPause())); connect(ui_->action_stop, SIGNAL(triggered()), app_->player(), SLOT(Stop())); connect(ui_->action_quit, SIGNAL(triggered()), SLOT(Exit())); - connect(ui_->action_stop_after_this_track, SIGNAL(triggered()), SLOT(StopAfterCurrent())); + connect(ui_->action_stop_after_this_track, SIGNAL(triggered()), + SLOT(StopAfterCurrent())); connect(ui_->action_mute, SIGNAL(triggered()), app_->player(), SLOT(Mute())); #ifdef HAVE_LIBLASTFM - connect(ui_->action_ban, SIGNAL(triggered()), InternetModel::Service(), SLOT(Ban())); + connect(ui_->action_ban, SIGNAL(triggered()), + InternetModel::Service(), SLOT(Ban())); connect(ui_->action_love, SIGNAL(triggered()), SLOT(Love())); - connect(ui_->action_toggle_scrobbling, SIGNAL(triggered()), InternetModel::Service(), SLOT(ToggleScrobbling())); + connect(ui_->action_toggle_scrobbling, SIGNAL(triggered()), + InternetModel::Service(), SLOT(ToggleScrobbling())); #endif - connect(ui_->action_clear_playlist, SIGNAL(triggered()), app_->playlist_manager(), SLOT(ClearCurrent())); - connect(ui_->action_remove_duplicates, SIGNAL(triggered()), app_->playlist_manager(), SLOT(RemoveDuplicatesCurrent())); - connect(ui_->action_remove_from_playlist, SIGNAL(triggered()), SLOT(PlaylistRemoveCurrent())); + connect(ui_->action_clear_playlist, SIGNAL(triggered()), + app_->playlist_manager(), SLOT(ClearCurrent())); + connect(ui_->action_remove_duplicates, SIGNAL(triggered()), + app_->playlist_manager(), SLOT(RemoveDuplicatesCurrent())); + connect(ui_->action_remove_from_playlist, SIGNAL(triggered()), + SLOT(PlaylistRemoveCurrent())); connect(ui_->action_edit_track, SIGNAL(triggered()), SLOT(EditTracks())); - connect(ui_->action_renumber_tracks, SIGNAL(triggered()), SLOT(RenumberTracks())); - connect(ui_->action_selection_set_value, SIGNAL(triggered()), SLOT(SelectionSetValue())); + connect(ui_->action_renumber_tracks, SIGNAL(triggered()), + SLOT(RenumberTracks())); + connect(ui_->action_selection_set_value, SIGNAL(triggered()), + SLOT(SelectionSetValue())); connect(ui_->action_edit_value, SIGNAL(triggered()), SLOT(EditValue())); - connect(ui_->action_auto_complete_tags, SIGNAL(triggered()), SLOT(AutoCompleteTags())); - connect(ui_->action_configure, SIGNAL(triggered()), SLOT(OpenSettingsDialog())); + connect(ui_->action_auto_complete_tags, SIGNAL(triggered()), + SLOT(AutoCompleteTags())); + connect(ui_->action_configure, SIGNAL(triggered()), + SLOT(OpenSettingsDialog())); connect(ui_->action_about, SIGNAL(triggered()), SLOT(ShowAboutDialog())); connect(ui_->action_about_qt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); - connect(ui_->action_shuffle, SIGNAL(triggered()), app_->playlist_manager(), SLOT(ShuffleCurrent())); + connect(ui_->action_shuffle, SIGNAL(triggered()), app_->playlist_manager(), + SLOT(ShuffleCurrent())); connect(ui_->action_open_media, SIGNAL(triggered()), SLOT(AddFile())); connect(ui_->action_open_cd, SIGNAL(triggered()), SLOT(AddCDTracks())); - #ifdef HAVE_AUDIOCD - connect(ui_->action_rip_audio_cd, SIGNAL(triggered()), SLOT(OpenRipCD())); - #else - ui_->action_rip_audio_cd->setVisible(false); - #endif +#ifdef HAVE_AUDIOCD + connect(ui_->action_rip_audio_cd, SIGNAL(triggered()), SLOT(OpenRipCD())); +#else + ui_->action_rip_audio_cd->setVisible(false); +#endif connect(ui_->action_add_file, SIGNAL(triggered()), SLOT(AddFile())); connect(ui_->action_add_folder, SIGNAL(triggered()), SLOT(AddFolder())); connect(ui_->action_add_stream, SIGNAL(triggered()), SLOT(AddStream())); connect(ui_->action_add_podcast, SIGNAL(triggered()), SLOT(AddPodcast())); - connect(ui_->action_cover_manager, SIGNAL(triggered()), SLOT(ShowCoverManager())); - connect(ui_->action_equalizer, SIGNAL(triggered()), equalizer_.get(), SLOT(show())); - connect(ui_->action_transcode, SIGNAL(triggered()), SLOT(ShowTranscodeDialog())); - connect(ui_->action_jump, SIGNAL(triggered()), ui_->playlist->view(), SLOT(JumpToCurrentlyPlayingTrack())); - connect(ui_->action_update_library, SIGNAL(triggered()), app_->library(), SLOT(IncrementalScan())); - connect(ui_->action_full_library_scan, SIGNAL(triggered()), app_->library(), SLOT(FullScan())); - connect(ui_->action_queue_manager, SIGNAL(triggered()), SLOT(ShowQueueManager())); - connect(ui_->action_add_files_to_transcoder, SIGNAL(triggered()), SLOT(AddFilesToTranscoder())); + connect(ui_->action_cover_manager, SIGNAL(triggered()), + SLOT(ShowCoverManager())); + connect(ui_->action_equalizer, SIGNAL(triggered()), equalizer_.get(), + SLOT(show())); + connect(ui_->action_transcode, SIGNAL(triggered()), + SLOT(ShowTranscodeDialog())); + connect(ui_->action_jump, SIGNAL(triggered()), ui_->playlist->view(), + SLOT(JumpToCurrentlyPlayingTrack())); + connect(ui_->action_update_library, SIGNAL(triggered()), app_->library(), + SLOT(IncrementalScan())); + connect(ui_->action_full_library_scan, SIGNAL(triggered()), app_->library(), + SLOT(FullScan())); + connect(ui_->action_queue_manager, SIGNAL(triggered()), + SLOT(ShowQueueManager())); + connect(ui_->action_add_files_to_transcoder, SIGNAL(triggered()), + SLOT(AddFilesToTranscoder())); background_streams_->AddAction("Rain", ui_->action_rain); background_streams_->AddAction("Hypnotoad", ui_->action_hypnotoad); background_streams_->AddAction("Make it so!", ui_->action_enterprise); // Playlist view actions - ui_->action_next_playlist->setShortcuts(QList() - << QKeySequence::fromString("Ctrl+Tab") - << QKeySequence::fromString("Ctrl+PgDown")); - ui_->action_previous_playlist->setShortcuts(QList() - << QKeySequence::fromString("Ctrl+Shift+Tab") - << QKeySequence::fromString("Ctrl+PgUp")); - // Actions for switching tabs will be global to the entire window, so adding them here + ui_->action_next_playlist->setShortcuts( + QList() << QKeySequence::fromString("Ctrl+Tab") + << QKeySequence::fromString("Ctrl+PgDown")); + ui_->action_previous_playlist->setShortcuts( + QList() << QKeySequence::fromString("Ctrl+Shift+Tab") + << QKeySequence::fromString("Ctrl+PgUp")); + // Actions for switching tabs will be global to the entire window, so adding + // them here addAction(ui_->action_next_playlist); addAction(ui_->action_previous_playlist); @@ -379,15 +417,15 @@ MainWindow::MainWindow(Application* app, ui_->ban_button->setDefaultAction(ui_->action_ban); ui_->scrobbling_button->setDefaultAction(ui_->action_toggle_scrobbling); ui_->clear_playlist_button->setDefaultAction(ui_->action_clear_playlist); - ui_->playlist->SetActions(ui_->action_new_playlist, - ui_->action_load_playlist, - ui_->action_save_playlist, - ui_->action_next_playlist, /* These two actions aren't associated */ - ui_->action_previous_playlist /* to a button but to the main window */ ); - + ui_->playlist->SetActions( + ui_->action_new_playlist, ui_->action_load_playlist, + ui_->action_save_playlist, + ui_->action_next_playlist, /* These two actions aren't associated */ + ui_->action_previous_playlist /* to a button but to the main window */); #ifdef ENABLE_VISUALISATIONS - connect(ui_->action_visualisations, SIGNAL(triggered()), SLOT(ShowVisualisations())); + connect(ui_->action_visualisations, SIGNAL(triggered()), + SLOT(ShowVisualisations())); #else ui_->action_visualisations->setEnabled(false); #endif @@ -403,74 +441,111 @@ MainWindow::MainWindow(Application* app, ui_->stop_button->setMenu(stop_menu); // Player connections - connect(ui_->volume, SIGNAL(valueChanged(int)), app_->player(), SLOT(SetVolume(int))); + connect(ui_->volume, SIGNAL(valueChanged(int)), app_->player(), + SLOT(SetVolume(int))); - connect(app_->player(), SIGNAL(Error(QString)), SLOT(ShowErrorDialog(QString))); - connect(app_->player(), SIGNAL(SongChangeRequestProcessed(QUrl,bool)), app_->playlist_manager(), SLOT(SongChangeRequestProcessed(QUrl,bool))); + connect(app_->player(), SIGNAL(Error(QString)), + SLOT(ShowErrorDialog(QString))); + connect(app_->player(), SIGNAL(SongChangeRequestProcessed(QUrl, bool)), + app_->playlist_manager(), + SLOT(SongChangeRequestProcessed(QUrl, bool))); connect(app_->player(), SIGNAL(Paused()), SLOT(MediaPaused())); connect(app_->player(), SIGNAL(Playing()), SLOT(MediaPlaying())); connect(app_->player(), SIGNAL(Stopped()), SLOT(MediaStopped())); connect(app_->player(), SIGNAL(Seeked(qlonglong)), SLOT(Seeked(qlonglong))); - connect(app_->player(), SIGNAL(TrackSkipped(PlaylistItemPtr)), SLOT(TrackSkipped(PlaylistItemPtr))); + connect(app_->player(), SIGNAL(TrackSkipped(PlaylistItemPtr)), + SLOT(TrackSkipped(PlaylistItemPtr))); connect(app_->player(), SIGNAL(VolumeChanged(int)), SLOT(VolumeChanged(int))); - connect(app_->player(), SIGNAL(Paused()), ui_->playlist, SLOT(ActivePaused())); - connect(app_->player(), SIGNAL(Playing()), ui_->playlist, SLOT(ActivePlaying())); - connect(app_->player(), SIGNAL(Stopped()), ui_->playlist, SLOT(ActiveStopped())); + connect(app_->player(), SIGNAL(Paused()), ui_->playlist, + SLOT(ActivePaused())); + connect(app_->player(), SIGNAL(Playing()), ui_->playlist, + SLOT(ActivePlaying())); + connect(app_->player(), SIGNAL(Stopped()), ui_->playlist, + SLOT(ActiveStopped())); connect(app_->player(), SIGNAL(Paused()), osd_, SLOT(Paused())); connect(app_->player(), SIGNAL(Stopped()), osd_, SLOT(Stopped())); - connect(app_->player(), SIGNAL(PlaylistFinished()), osd_, SLOT(PlaylistFinished())); - connect(app_->player(), SIGNAL(VolumeChanged(int)), osd_, SLOT(VolumeChanged(int))); - connect(app_->player(), SIGNAL(VolumeChanged(int)), ui_->volume, SLOT(setValue(int))); - connect(app_->player(), SIGNAL(ForceShowOSD(Song, bool)), SLOT(ForceShowOSD(Song, bool))); - connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), SLOT(SongChanged(Song))); - connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), app_->player(), SLOT(CurrentMetadataChanged(Song))); - connect(app_->playlist_manager(), SIGNAL(EditingFinished(QModelIndex)), SLOT(PlaylistEditFinished(QModelIndex))); - connect(app_->playlist_manager(), SIGNAL(Error(QString)), SLOT(ShowErrorDialog(QString))); - connect(app_->playlist_manager(), SIGNAL(SummaryTextChanged(QString)), ui_->playlist_summary, SLOT(setText(QString))); - connect(app_->playlist_manager(), SIGNAL(PlayRequested(QModelIndex)), SLOT(PlayIndex(QModelIndex))); + connect(app_->player(), SIGNAL(PlaylistFinished()), osd_, + SLOT(PlaylistFinished())); + connect(app_->player(), SIGNAL(VolumeChanged(int)), osd_, + SLOT(VolumeChanged(int))); + connect(app_->player(), SIGNAL(VolumeChanged(int)), ui_->volume, + SLOT(setValue(int))); + connect(app_->player(), SIGNAL(ForceShowOSD(Song, bool)), + SLOT(ForceShowOSD(Song, bool))); + connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), + SLOT(SongChanged(Song))); + connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), + app_->player(), SLOT(CurrentMetadataChanged(Song))); + connect(app_->playlist_manager(), SIGNAL(EditingFinished(QModelIndex)), + SLOT(PlaylistEditFinished(QModelIndex))); + connect(app_->playlist_manager(), SIGNAL(Error(QString)), + SLOT(ShowErrorDialog(QString))); + connect(app_->playlist_manager(), SIGNAL(SummaryTextChanged(QString)), + ui_->playlist_summary, SLOT(setText(QString))); + connect(app_->playlist_manager(), SIGNAL(PlayRequested(QModelIndex)), + SLOT(PlayIndex(QModelIndex))); - connect(ui_->playlist->view(), SIGNAL(doubleClicked(QModelIndex)), SLOT(PlayIndex(QModelIndex))); - connect(ui_->playlist->view(), SIGNAL(PlayItem(QModelIndex)), SLOT(PlayIndex(QModelIndex))); - connect(ui_->playlist->view(), SIGNAL(PlayPause()), app_->player(), SLOT(PlayPause())); - connect(ui_->playlist->view(), SIGNAL(RightClicked(QPoint,QModelIndex)), SLOT(PlaylistRightClick(QPoint,QModelIndex))); - connect(ui_->playlist->view(), SIGNAL(SeekTrack(int)), ui_->track_slider, SLOT(Seek(int))); - connect(ui_->playlist->view(), SIGNAL(BackgroundPropertyChanged()), SLOT(RefreshStyleSheet())); + connect(ui_->playlist->view(), SIGNAL(doubleClicked(QModelIndex)), + SLOT(PlayIndex(QModelIndex))); + connect(ui_->playlist->view(), SIGNAL(PlayItem(QModelIndex)), + SLOT(PlayIndex(QModelIndex))); + connect(ui_->playlist->view(), SIGNAL(PlayPause()), app_->player(), + SLOT(PlayPause())); + connect(ui_->playlist->view(), SIGNAL(RightClicked(QPoint, QModelIndex)), + SLOT(PlaylistRightClick(QPoint, QModelIndex))); + connect(ui_->playlist->view(), SIGNAL(SeekTrack(int)), ui_->track_slider, + SLOT(Seek(int))); + connect(ui_->playlist->view(), SIGNAL(BackgroundPropertyChanged()), + SLOT(RefreshStyleSheet())); - connect(ui_->track_slider, SIGNAL(ValueChanged(int)), app_->player(), SLOT(SeekTo(int))); + connect(ui_->track_slider, SIGNAL(ValueChanged(int)), app_->player(), + SLOT(SeekTo(int))); // Library connections - connect(library_view_->view(), SIGNAL(AddToPlaylistSignal(QMimeData*)), SLOT(AddToPlaylist(QMimeData*))); - connect(library_view_->view(), SIGNAL(ShowConfigDialog()), SLOT(ShowLibraryConfig())); - connect(app_->library_model(), SIGNAL(TotalSongCountUpdated(int)), library_view_->view(), SLOT(TotalSongCountUpdated(int))); - connect(app_->library_model(), SIGNAL(modelAboutToBeReset()), library_view_->view(), SLOT(SaveFocus())); - connect(app_->library_model(), SIGNAL(modelReset()), library_view_->view(), SLOT(RestoreFocus())); + connect(library_view_->view(), SIGNAL(AddToPlaylistSignal(QMimeData*)), + SLOT(AddToPlaylist(QMimeData*))); + connect(library_view_->view(), SIGNAL(ShowConfigDialog()), + SLOT(ShowLibraryConfig())); + connect(app_->library_model(), SIGNAL(TotalSongCountUpdated(int)), + library_view_->view(), SLOT(TotalSongCountUpdated(int))); + connect(app_->library_model(), SIGNAL(modelAboutToBeReset()), + library_view_->view(), SLOT(SaveFocus())); + connect(app_->library_model(), SIGNAL(modelReset()), library_view_->view(), + SLOT(RestoreFocus())); - connect(app_->task_manager(), SIGNAL(PauseLibraryWatchers()), app_->library(), SLOT(PauseWatcher())); - connect(app_->task_manager(), SIGNAL(ResumeLibraryWatchers()), app_->library(), SLOT(ResumeWatcher())); + connect(app_->task_manager(), SIGNAL(PauseLibraryWatchers()), app_->library(), + SLOT(PauseWatcher())); + connect(app_->task_manager(), SIGNAL(ResumeLibraryWatchers()), + app_->library(), SLOT(ResumeWatcher())); // Devices connections - connect(device_view_, SIGNAL(AddToPlaylistSignal(QMimeData*)), SLOT(AddToPlaylist(QMimeData*))); + connect(device_view_, SIGNAL(AddToPlaylistSignal(QMimeData*)), + SLOT(AddToPlaylist(QMimeData*))); // Library filter widget QActionGroup* library_view_group = new QActionGroup(this); library_show_all_ = library_view_group->addAction(tr("Show all songs")); - library_show_duplicates_ = library_view_group->addAction(tr("Show only duplicates")); - library_show_untagged_ = library_view_group->addAction(tr("Show only untagged")); + library_show_duplicates_ = + library_view_group->addAction(tr("Show only duplicates")); + library_show_untagged_ = + library_view_group->addAction(tr("Show only untagged")); library_show_all_->setCheckable(true); library_show_duplicates_->setCheckable(true); library_show_untagged_->setCheckable(true); library_show_all_->setChecked(true); - connect(library_view_group, SIGNAL(triggered(QAction*)), SLOT(ChangeLibraryQueryMode(QAction*))); + connect(library_view_group, SIGNAL(triggered(QAction*)), + SLOT(ChangeLibraryQueryMode(QAction*))); QAction* library_config_action = new QAction( IconLoader::Load("configure"), tr("Configure library..."), this); - connect(library_config_action, SIGNAL(triggered()), SLOT(ShowLibraryConfig())); + connect(library_config_action, SIGNAL(triggered()), + SLOT(ShowLibraryConfig())); library_view_->filter()->SetSettingsGroup(kSettingsGroup); library_view_->filter()->SetLibraryModel(app_->library()->model()); @@ -484,9 +559,12 @@ MainWindow::MainWindow(Application* app, library_view_->filter()->AddMenuAction(library_config_action); // Playlist menu - playlist_play_pause_ = playlist_menu_->addAction(tr("Play"), this, SLOT(PlaylistPlay())); + playlist_play_pause_ = + playlist_menu_->addAction(tr("Play"), this, SLOT(PlaylistPlay())); playlist_menu_->addAction(ui_->action_stop); - playlist_stop_after_ = playlist_menu_->addAction(IconLoader::Load("media-playback-stop"), tr("Stop after this track"), this, SLOT(PlaylistStopAfter())); + playlist_stop_after_ = playlist_menu_->addAction( + IconLoader::Load("media-playback-stop"), tr("Stop after this track"), + this, SLOT(PlaylistStopAfter())); playlist_queue_ = playlist_menu_->addAction("", this, SLOT(PlaylistQueue())); playlist_queue_->setShortcut(QKeySequence("Ctrl+D")); ui_->playlist->addAction(playlist_queue_); @@ -500,13 +578,27 @@ MainWindow::MainWindow(Application* app, playlist_menu_->addAction(ui_->action_auto_complete_tags); playlist_menu_->addAction(ui_->action_add_files_to_transcoder); playlist_menu_->addSeparator(); - playlist_copy_to_library_ = playlist_menu_->addAction(IconLoader::Load("edit-copy"), tr("Copy to library..."), this, SLOT(PlaylistCopyToLibrary())); - playlist_move_to_library_ = playlist_menu_->addAction(IconLoader::Load("go-jump"), tr("Move to library..."), this, SLOT(PlaylistMoveToLibrary())); - playlist_organise_ = playlist_menu_->addAction(IconLoader::Load("edit-copy"), tr("Organise files..."), this, SLOT(PlaylistMoveToLibrary())); - playlist_copy_to_device_ = playlist_menu_->addAction(IconLoader::Load("multimedia-player-ipod-mini-blue"), tr("Copy to device..."), this, SLOT(PlaylistCopyToDevice())); - playlist_delete_ = playlist_menu_->addAction(IconLoader::Load("edit-delete"), tr("Delete from disk..."), this, SLOT(PlaylistDelete())); - playlist_open_in_browser_ = playlist_menu_->addAction(IconLoader::Load("document-open-folder"), tr("Show in file browser..."), this, SLOT(PlaylistOpenInBrowser())); - playlist_show_in_library_ = playlist_menu_->addAction(IconLoader::Load("edit-find"), tr("Show in library..."), this, SLOT(ShowInLibrary())); + playlist_copy_to_library_ = playlist_menu_->addAction( + IconLoader::Load("edit-copy"), tr("Copy to library..."), this, + SLOT(PlaylistCopyToLibrary())); + playlist_move_to_library_ = playlist_menu_->addAction( + IconLoader::Load("go-jump"), tr("Move to library..."), this, + SLOT(PlaylistMoveToLibrary())); + playlist_organise_ = playlist_menu_->addAction(IconLoader::Load("edit-copy"), + tr("Organise files..."), this, + SLOT(PlaylistMoveToLibrary())); + playlist_copy_to_device_ = playlist_menu_->addAction( + IconLoader::Load("multimedia-player-ipod-mini-blue"), + tr("Copy to device..."), this, SLOT(PlaylistCopyToDevice())); + playlist_delete_ = playlist_menu_->addAction(IconLoader::Load("edit-delete"), + tr("Delete from disk..."), this, + SLOT(PlaylistDelete())); + playlist_open_in_browser_ = playlist_menu_->addAction( + IconLoader::Load("document-open-folder"), tr("Show in file browser..."), + this, SLOT(PlaylistOpenInBrowser())); + playlist_show_in_library_ = playlist_menu_->addAction( + IconLoader::Load("edit-find"), tr("Show in library..."), this, + SLOT(ShowInLibrary())); playlist_menu_->addSeparator(); playlistitem_actions_separator_ = playlist_menu_->addSeparator(); playlist_menu_->addAction(ui_->action_clear_playlist); @@ -521,12 +613,14 @@ MainWindow::MainWindow(Application* app, // their shortcut keys don't work addActions(playlist_menu_->actions()); - connect(ui_->playlist, SIGNAL(UndoRedoActionsChanged(QAction*,QAction*)), - SLOT(PlaylistUndoRedoChanged(QAction*,QAction*))); + connect(ui_->playlist, SIGNAL(UndoRedoActionsChanged(QAction*, QAction*)), + SLOT(PlaylistUndoRedoChanged(QAction*, QAction*))); - playlist_copy_to_device_->setDisabled(app_->device_manager()->connected_devices_model()->rowCount() == 0); - connect(app_->device_manager()->connected_devices_model(), SIGNAL(IsEmptyChanged(bool)), - playlist_copy_to_device_, SLOT(setDisabled(bool))); + playlist_copy_to_device_->setDisabled( + app_->device_manager()->connected_devices_model()->rowCount() == 0); + connect(app_->device_manager()->connected_devices_model(), + SIGNAL(IsEmptyChanged(bool)), playlist_copy_to_device_, + SLOT(setDisabled(bool))); // Global search shortcut QAction* global_search_action = new QAction(this); @@ -538,57 +632,65 @@ MainWindow::MainWindow(Application* app, SLOT(FocusGlobalSearchField())); // Internet connections - connect(app_->internet_model(), SIGNAL(StreamError(QString)), SLOT(ShowErrorDialog(QString))); - connect(app_->internet_model(), SIGNAL(StreamMetadataFound(QUrl,Song)), app_->playlist_manager(), SLOT(SetActiveStreamMetadata(QUrl,Song))); - connect(app_->internet_model(), SIGNAL(AddToPlaylist(QMimeData*)), SLOT(AddToPlaylist(QMimeData*))); - connect(app_->internet_model(), SIGNAL(ScrollToIndex(QModelIndex)), SLOT(ScrollToInternetIndex(QModelIndex))); + connect(app_->internet_model(), SIGNAL(StreamError(QString)), + SLOT(ShowErrorDialog(QString))); + connect(app_->internet_model(), SIGNAL(StreamMetadataFound(QUrl, Song)), + app_->playlist_manager(), SLOT(SetActiveStreamMetadata(QUrl, Song))); + connect(app_->internet_model(), SIGNAL(AddToPlaylist(QMimeData*)), + SLOT(AddToPlaylist(QMimeData*))); + connect(app_->internet_model(), SIGNAL(ScrollToIndex(QModelIndex)), + SLOT(ScrollToInternetIndex(QModelIndex))); #ifdef HAVE_LIBLASTFM LastFMService* lastfm_service = InternetModel::Service(); - connect(lastfm_service, SIGNAL(ButtonVisibilityChanged(bool)), SLOT(LastFMButtonVisibilityChanged(bool))); - connect(lastfm_service, SIGNAL(ScrobbleButtonVisibilityChanged(bool)), SLOT(ScrobbleButtonVisibilityChanged(bool))); - connect(lastfm_service, SIGNAL(ScrobblingEnabledChanged(bool)), SLOT(ScrobblingEnabledChanged(bool))); - connect(lastfm_service, SIGNAL(ScrobbledRadioStream()), SLOT(ScrobbledRadioStream())); + connect(lastfm_service, SIGNAL(ButtonVisibilityChanged(bool)), + SLOT(LastFMButtonVisibilityChanged(bool))); + connect(lastfm_service, SIGNAL(ScrobbleButtonVisibilityChanged(bool)), + SLOT(ScrobbleButtonVisibilityChanged(bool))); + connect(lastfm_service, SIGNAL(ScrobblingEnabledChanged(bool)), + SLOT(ScrobblingEnabledChanged(bool))); + connect(lastfm_service, SIGNAL(ScrobbledRadioStream()), + SLOT(ScrobbledRadioStream())); #endif - connect(app_->internet_model()->Service(), SIGNAL(DownloadFinished(QStringList)), osd_, SLOT(MagnatuneDownloadFinished(QStringList))); - connect(internet_view_->tree(), SIGNAL(AddToPlaylistSignal(QMimeData*)), SLOT(AddToPlaylist(QMimeData*))); + connect(app_->internet_model()->Service(), + SIGNAL(DownloadFinished(QStringList)), osd_, + SLOT(MagnatuneDownloadFinished(QStringList))); + connect(internet_view_->tree(), SIGNAL(AddToPlaylistSignal(QMimeData*)), + SLOT(AddToPlaylist(QMimeData*))); // Connections to the saved streams service - connect(InternetModel::Service(), SIGNAL(ShowAddStreamDialog()), SLOT(AddStream())); + connect(InternetModel::Service(), SIGNAL(ShowAddStreamDialog()), + SLOT(AddStream())); #ifdef Q_OS_DARWIN 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_ban, - ui_->action_quit); + 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_ban, ui_->action_quit); connect(tray_icon_, SIGNAL(PlayPause()), app_->player(), SLOT(PlayPause())); - connect(tray_icon_, SIGNAL(SeekForward()), app_->player(), SLOT(SeekForward())); - connect(tray_icon_, SIGNAL(SeekBackward()), app_->player(), SLOT(SeekBackward())); + connect(tray_icon_, SIGNAL(SeekForward()), app_->player(), + SLOT(SeekForward())); + connect(tray_icon_, SIGNAL(SeekBackward()), app_->player(), + SLOT(SeekBackward())); connect(tray_icon_, SIGNAL(NextTrack()), app_->player(), SLOT(Next())); - connect(tray_icon_, SIGNAL(PreviousTrack()), app_->player(), SLOT(Previous())); + connect(tray_icon_, SIGNAL(PreviousTrack()), app_->player(), + SLOT(Previous())); connect(tray_icon_, SIGNAL(ShowHide()), SLOT(ToggleShowHide())); connect(tray_icon_, SIGNAL(ChangeVolume(int)), SLOT(VolumeWheelEvent(int))); // Windows 7 thumbbar buttons thumbbar_->SetActions(QList() - << ui_->action_previous_track - << ui_->action_play_pause - << ui_->action_stop - << ui_->action_next_track - << nullptr // spacer - << ui_->action_love - << ui_->action_ban); + << ui_->action_previous_track << ui_->action_play_pause + << ui_->action_stop << ui_->action_next_track + << nullptr // spacer + << ui_->action_love << ui_->action_ban); #if (defined(Q_OS_DARWIN) && defined(HAVE_SPARKLE)) || defined(Q_OS_WIN32) // Add check for updates item to application menu. - QAction* check_updates = ui_->menu_tools->addAction(tr("Check for updates...")); + QAction* check_updates = + ui_->menu_tools->addAction(tr("Check for updates...")); check_updates->setMenuRole(QAction::ApplicationSpecificRole); connect(check_updates, SIGNAL(triggered(bool)), SLOT(CheckForUpdates())); #endif @@ -605,27 +707,41 @@ MainWindow::MainWindow(Application* app, // Global shortcuts connect(global_shortcuts_, SIGNAL(Play()), app_->player(), SLOT(Play())); connect(global_shortcuts_, SIGNAL(Pause()), app_->player(), SLOT(Pause())); - connect(global_shortcuts_, SIGNAL(PlayPause()), ui_->action_play_pause, SLOT(trigger())); + connect(global_shortcuts_, SIGNAL(PlayPause()), ui_->action_play_pause, + SLOT(trigger())); connect(global_shortcuts_, SIGNAL(Stop()), ui_->action_stop, SLOT(trigger())); - connect(global_shortcuts_, SIGNAL(StopAfter()), ui_->action_stop_after_this_track, SLOT(trigger())); - connect(global_shortcuts_, SIGNAL(Next()), ui_->action_next_track, SLOT(trigger())); - connect(global_shortcuts_, SIGNAL(Previous()), ui_->action_previous_track, SLOT(trigger())); - connect(global_shortcuts_, SIGNAL(IncVolume()), app_->player(), SLOT(VolumeUp())); - connect(global_shortcuts_, SIGNAL(DecVolume()), app_->player(), SLOT(VolumeDown())); + connect(global_shortcuts_, SIGNAL(StopAfter()), + ui_->action_stop_after_this_track, SLOT(trigger())); + connect(global_shortcuts_, SIGNAL(Next()), ui_->action_next_track, + SLOT(trigger())); + connect(global_shortcuts_, SIGNAL(Previous()), ui_->action_previous_track, + SLOT(trigger())); + connect(global_shortcuts_, SIGNAL(IncVolume()), app_->player(), + SLOT(VolumeUp())); + connect(global_shortcuts_, SIGNAL(DecVolume()), app_->player(), + SLOT(VolumeDown())); connect(global_shortcuts_, SIGNAL(Mute()), app_->player(), SLOT(Mute())); - connect(global_shortcuts_, SIGNAL(SeekForward()), app_->player(), SLOT(SeekForward())); - connect(global_shortcuts_, SIGNAL(SeekBackward()), app_->player(), SLOT(SeekBackward())); + connect(global_shortcuts_, SIGNAL(SeekForward()), app_->player(), + SLOT(SeekForward())); + connect(global_shortcuts_, SIGNAL(SeekBackward()), app_->player(), + SLOT(SeekBackward())); connect(global_shortcuts_, SIGNAL(ShowHide()), SLOT(ToggleShowHide())); - connect(global_shortcuts_, SIGNAL(ShowOSD()), app_->player(), SLOT(ShowOSD())); - connect(global_shortcuts_, SIGNAL(TogglePrettyOSD()), app_->player(), SLOT(TogglePrettyOSD())); + connect(global_shortcuts_, SIGNAL(ShowOSD()), app_->player(), + SLOT(ShowOSD())); + connect(global_shortcuts_, SIGNAL(TogglePrettyOSD()), app_->player(), + SLOT(TogglePrettyOSD())); #ifdef HAVE_LIBLASTFM - connect(global_shortcuts_, SIGNAL(ToggleScrobbling()), app_->internet_model()->InternetModel::Service(), SLOT(ToggleScrobbling())); + connect(global_shortcuts_, SIGNAL(ToggleScrobbling()), + app_->internet_model()->InternetModel::Service(), + SLOT(ToggleScrobbling())); #endif - connect(global_shortcuts_, SIGNAL(RateCurrentSong(int)), app_->playlist_manager(), SLOT(RateCurrentSong(int))); + connect(global_shortcuts_, SIGNAL(RateCurrentSong(int)), + app_->playlist_manager(), SLOT(RateCurrentSong(int))); // Fancy tabs - connect(ui_->tabs, SIGNAL(ModeChanged(FancyTabWidget::Mode)), SLOT(SaveGeometry())); + connect(ui_->tabs, SIGNAL(ModeChanged(FancyTabWidget::Mode)), + SLOT(SaveGeometry())); connect(ui_->tabs, SIGNAL(CurrentChanged(int)), SLOT(SaveGeometry())); // Lyrics @@ -639,26 +755,30 @@ MainWindow::MainWindow(Application* app, // Equalizer qLog(Debug) << "Creating equalizer"; - connect(equalizer_.get(), SIGNAL(ParametersChanged(int,QList)), - app_->player()->engine(), SLOT(SetEqualizerParameters(int,QList))); + connect(equalizer_.get(), SIGNAL(ParametersChanged(int, QList)), + app_->player()->engine(), + SLOT(SetEqualizerParameters(int, QList))); connect(equalizer_.get(), SIGNAL(EnabledChanged(bool)), app_->player()->engine(), SLOT(SetEqualizerEnabled(bool))); connect(equalizer_.get(), SIGNAL(StereoBalanceChanged(float)), app_->player()->engine(), SLOT(SetStereoBalance(float))); app_->player()->engine()->SetEqualizerEnabled(equalizer_->is_enabled()); - app_->player()->engine()->SetEqualizerParameters( - equalizer_->preamp_value(), equalizer_->gain_values()); + app_->player()->engine()->SetEqualizerParameters(equalizer_->preamp_value(), + equalizer_->gain_values()); app_->player()->engine()->SetStereoBalance(equalizer_->stereo_balance()); // Statusbar widgets - ui_->playlist_summary->setMinimumWidth(QFontMetrics(font()).width("WW selected of WW tracks - [ WW:WW ]")); + ui_->playlist_summary->setMinimumWidth( + QFontMetrics(font()).width("WW selected of WW tracks - [ WW:WW ]")); ui_->status_bar_stack->setCurrentWidget(ui_->playlist_summary_page); - connect(ui_->multi_loading_indicator, SIGNAL(TaskCountChange(int)), SLOT(TaskCountChanged(int))); + connect(ui_->multi_loading_indicator, SIGNAL(TaskCountChange(int)), + SLOT(TaskCountChanged(int))); ui_->track_slider->SetApplication(app); #ifdef HAVE_MOODBAR // Moodbar connections - connect(app_->moodbar_controller(), SIGNAL(CurrentMoodbarDataChanged(QByteArray)), + connect(app_->moodbar_controller(), + SIGNAL(CurrentMoodbarDataChanged(QByteArray)), ui_->track_slider->moodbar_style(), SLOT(SetMoodbarData(QByteArray))); #endif @@ -669,42 +789,62 @@ MainWindow::MainWindow(Application* app, connect(app_->player(), SIGNAL(Stopped()), ui_->now_playing, SLOT(Stopped())); connect(ui_->now_playing, SIGNAL(ShowAboveStatusBarChanged(bool)), SLOT(NowPlayingWidgetPositionChanged(bool))); - connect(ui_->action_hypnotoad, SIGNAL(toggled(bool)), ui_->now_playing, SLOT(AllHail(bool))); - connect(ui_->action_kittens, SIGNAL(toggled(bool)), ui_->now_playing, SLOT(EnableKittens(bool))); - connect(ui_->action_kittens, SIGNAL(toggled(bool)), app_->network_remote(), SLOT(EnableKittens(bool))); + connect(ui_->action_hypnotoad, SIGNAL(toggled(bool)), ui_->now_playing, + SLOT(AllHail(bool))); + connect(ui_->action_kittens, SIGNAL(toggled(bool)), ui_->now_playing, + SLOT(EnableKittens(bool))); + connect(ui_->action_kittens, SIGNAL(toggled(bool)), app_->network_remote(), + SLOT(EnableKittens(bool))); // Hide the console - //connect(ui_->action_console, SIGNAL(triggered()), SLOT(ShowConsole())); + // connect(ui_->action_console, SIGNAL(triggered()), SLOT(ShowConsole())); NowPlayingWidgetPositionChanged(ui_->now_playing->show_above_status_bar()); // Load theme // This is tricky: we need to save the default/system palette now, before - // loading user preferred theme (which will overide it), to be able to restore it later + // loading user preferred theme (which will overide it), to be able to restore + // it later const_cast(Appearance::kDefaultPalette) = QApplication::palette(); app_->appearance()->LoadUserTheme(); StyleSheetLoader* css_loader = new StyleSheetLoader(this); css_loader->SetStyleSheet(this, ":mainwindow.css"); // Load playlists - app_->playlist_manager()->Init(app_->library_backend(), app_->playlist_backend(), + app_->playlist_manager()->Init(app_->library_backend(), + app_->playlist_backend(), ui_->playlist_sequence, ui_->playlist); // This connection must be done after the playlists have been initialized. - connect(this, SIGNAL(StopAfterToggled(bool)), - osd_, SLOT(StopAfterToggle(bool))); + connect(this, SIGNAL(StopAfterToggled(bool)), osd_, + SLOT(StopAfterToggle(bool))); - // We need to connect these global shortcuts here after the playlist have been initialized - connect(global_shortcuts_, SIGNAL(CycleShuffleMode()), app_->playlist_manager()->sequence(), SLOT(CycleShuffleMode())); - connect(global_shortcuts_, SIGNAL(CycleRepeatMode()), app_->playlist_manager()->sequence(), SLOT(CycleRepeatMode())); - connect(app_->playlist_manager()->sequence(), SIGNAL(RepeatModeChanged(PlaylistSequence::RepeatMode)), osd_, SLOT(RepeatModeChanged(PlaylistSequence::RepeatMode))); - connect(app_->playlist_manager()->sequence(), SIGNAL(ShuffleModeChanged(PlaylistSequence::ShuffleMode)), osd_, SLOT(ShuffleModeChanged(PlaylistSequence::ShuffleMode))); + // We need to connect these global shortcuts here after the playlist have been + // initialized + connect(global_shortcuts_, SIGNAL(CycleShuffleMode()), + app_->playlist_manager()->sequence(), SLOT(CycleShuffleMode())); + connect(global_shortcuts_, SIGNAL(CycleRepeatMode()), + app_->playlist_manager()->sequence(), SLOT(CycleRepeatMode())); + connect(app_->playlist_manager()->sequence(), + SIGNAL(RepeatModeChanged(PlaylistSequence::RepeatMode)), osd_, + SLOT(RepeatModeChanged(PlaylistSequence::RepeatMode))); + connect(app_->playlist_manager()->sequence(), + SIGNAL(ShuffleModeChanged(PlaylistSequence::ShuffleMode)), osd_, + SLOT(ShuffleModeChanged(PlaylistSequence::ShuffleMode))); #ifdef HAVE_LIBLASTFM - connect(InternetModel::Service(), SIGNAL(ScrobbleSubmitted()), SLOT(ScrobbleSubmitted())); - connect(InternetModel::Service(), SIGNAL(ScrobbleError(int)), SLOT(ScrobbleError(int))); + connect(InternetModel::Service(), SIGNAL(ScrobbleSubmitted()), + SLOT(ScrobbleSubmitted())); + connect(InternetModel::Service(), SIGNAL(ScrobbleError(int)), + SLOT(ScrobbleError(int))); - LastFMButtonVisibilityChanged(app_->internet_model()->InternetModel::Service()->AreButtonsVisible()); - ScrobbleButtonVisibilityChanged(app_->internet_model()->InternetModel::Service()->IsScrobbleButtonVisible()); - ScrobblingEnabledChanged(app_->internet_model()->InternetModel::Service()->IsScrobblingEnabled()); + LastFMButtonVisibilityChanged(app_->internet_model() + ->InternetModel::Service() + ->AreButtonsVisible()); + ScrobbleButtonVisibilityChanged(app_->internet_model() + ->InternetModel::Service() + ->IsScrobbleButtonVisible()); + ScrobblingEnabledChanged(app_->internet_model() + ->InternetModel::Service() + ->IsScrobblingEnabled()); #else LastFMButtonVisibilityChanged(false); ScrobbleButtonVisibilityChanged(false); @@ -715,14 +855,17 @@ MainWindow::MainWindow(Application* app, settings_.beginGroup(kSettingsGroup); restoreGeometry(settings_.value("geometry").toByteArray()); - if (!ui_->splitter->restoreState(settings_.value("splitter_state").toByteArray())) { + if (!ui_->splitter->restoreState( + settings_.value("splitter_state").toByteArray())) { ui_->splitter->setSizes(QList() << 300 << width() - 300); } - ui_->tabs->SetCurrentIndex(settings_.value("current_tab", 1 /* Library tab */ ).toInt()); + ui_->tabs->SetCurrentIndex( + settings_.value("current_tab", 1 /* Library tab */).toInt()); FancyTabWidget::Mode default_mode = FancyTabWidget::Mode_LargeSidebar; - ui_->tabs->SetMode(FancyTabWidget::Mode(settings_.value( - "tab_mode", default_mode).toInt())); - file_view_->SetPath(settings_.value("file_path", QDir::homePath()).toString()); + ui_->tabs->SetMode( + FancyTabWidget::Mode(settings_.value("tab_mode", default_mode).toInt())); + file_view_->SetPath( + settings_.value("file_path", QDir::homePath()).toString()); ReloadSettings(); @@ -733,17 +876,24 @@ MainWindow::MainWindow(Application* app, ui_->playlist->view()->ReloadSettings(); #ifndef Q_OS_DARWIN - StartupBehaviour behaviour = - StartupBehaviour(settings_.value("startupbehaviour", Startup_Remember).toInt()); + StartupBehaviour behaviour = StartupBehaviour( + settings_.value("startupbehaviour", Startup_Remember).toInt()); bool hidden = settings_.value("hidden", false).toBool(); switch (behaviour) { - case Startup_AlwaysHide: hide(); break; - case Startup_AlwaysShow: show(); break; - case Startup_Remember: setVisible(!hidden); break; + case Startup_AlwaysHide: + hide(); + break; + case Startup_AlwaysShow: + show(); + break; + case Startup_Remember: + setVisible(!hidden); + break; } - // Force the window to show in case somehow the config has tray and window set to hide + // Force the window to show in case somehow the config has tray and window set + // to hide if (hidden && !tray_icon_->IsVisible()) { settings_.setValue("hidden", false); show(); @@ -758,10 +908,11 @@ MainWindow::MainWindow(Application* app, connect(close_window_shortcut, SIGNAL(activated()), SLOT(SetHiddenInTray())); #ifdef HAVE_WIIMOTEDEV -// http://code.google.com/p/clementine-player/issues/detail?id=670 -// Switched position, mayby something is not ready ? + // http://code.google.com/p/clementine-player/issues/detail?id=670 + // Switched position, mayby something is not ready ? - wiimotedev_shortcuts_.reset(new WiimotedevShortcuts(osd_, this, app_->player())); + wiimotedev_shortcuts_.reset( + new WiimotedevShortcuts(osd_, this, app_->player())); #endif CheckFullRescanRevisions(); @@ -781,20 +932,18 @@ void MainWindow::ReloadSettings() { bool show_tray = settings_.value("showtray", true).toBool(); tray_icon_->SetVisible(show_tray); - if (!show_tray && !isVisible()) - show(); + if (!show_tray && !isVisible()) show(); #endif QSettings s; s.beginGroup(kSettingsGroup); - doubleclick_addmode_ = AddBehaviour( - s.value("doubleclick_addmode", AddBehaviour_Append).toInt()); + doubleclick_addmode_ = + AddBehaviour(s.value("doubleclick_addmode", AddBehaviour_Append).toInt()); doubleclick_playmode_ = PlayBehaviour( s.value("doubleclick_playmode", PlayBehaviour_IfStopped).toInt()); - menu_playmode_ = PlayBehaviour( - s.value("menu_playmode", PlayBehaviour_IfStopped).toInt()); - + menu_playmode_ = + PlayBehaviour(s.value("menu_playmode", PlayBehaviour_IfStopped).toInt()); } void MainWindow::ReloadAllSettings() { @@ -816,9 +965,7 @@ void MainWindow::ReloadAllSettings() { #endif } -void MainWindow::RefreshStyleSheet() { - setStyleSheet(styleSheet()); -} +void MainWindow::RefreshStyleSheet() { setStyleSheet(styleSheet()); } void MainWindow::MediaStopped() { setWindowTitle(QCoreApplication::applicationName()); @@ -859,14 +1006,17 @@ void MainWindow::MediaPlaying() { ui_->action_play_pause->setIcon(IconLoader::Load("media-playback-pause")); ui_->action_play_pause->setText(tr("Pause")); - bool enable_play_pause = !(app_->player()->GetCurrentItem()->options() & PlaylistItem::PauseDisabled); + bool enable_play_pause = !(app_->player()->GetCurrentItem()->options() & + PlaylistItem::PauseDisabled); ui_->action_play_pause->setEnabled(enable_play_pause); - bool can_seek = !(app_->player()->GetCurrentItem()->options() & PlaylistItem::SeekDisabled); + bool can_seek = !(app_->player()->GetCurrentItem()->options() & + PlaylistItem::SeekDisabled); ui_->track_slider->SetCanSeek(can_seek); #ifdef HAVE_LIBLASTFM - bool is_lastfm = (app_->player()->GetCurrentItem()->options() & PlaylistItem::LastFMControls); + bool is_lastfm = (app_->player()->GetCurrentItem()->options() & + PlaylistItem::LastFMControls); LastFMService* lastfm = InternetModel::Service(); bool enable_ban = lastfm->IsScrobblingEnabled() && is_lastfm; bool enable_love = lastfm->IsScrobblingEnabled(); @@ -896,7 +1046,8 @@ void MainWindow::SongChanged(const Song& song) { #ifdef HAVE_LIBLASTFM if (ui_->action_toggle_scrobbling->isVisible()) - SetToggleScrobblingIcon(InternetModel::Service()->IsScrobblingEnabled()); + SetToggleScrobblingIcon( + InternetModel::Service()->IsScrobblingEnabled()); #endif } @@ -904,8 +1055,10 @@ void MainWindow::TrackSkipped(PlaylistItemPtr item) { // If it was a library item then we have to increment its skipped count in // the database. if (item && item->IsLocalLibraryItem() && item->Metadata().id() != -1 && - app_->playlist_manager()->active()->get_lastfm_status() != Playlist::LastFM_Scrobbled && - app_->playlist_manager()->active()->get_lastfm_status() != Playlist::LastFM_Queued) { + app_->playlist_manager()->active()->get_lastfm_status() != + Playlist::LastFM_Scrobbled && + app_->playlist_manager()->active()->get_lastfm_status() != + Playlist::LastFM_Queued) { Song song = item->Metadata(); const qint64 position = app_->player()->engine()->position_nanosec(); const qint64 length = app_->player()->engine()->length_nanosec(); @@ -914,8 +1067,9 @@ void MainWindow::TrackSkipped(PlaylistItemPtr item) { const qint64 seconds_left = (length - position) / kNsecPerSec; const qint64 seconds_total = length / kNsecPerSec; - if (((0.05 * seconds_total > 60 && percentage < 0.98) || percentage < 0.95) && - seconds_left > 5) { // Never count the skip if under 5 seconds left + if (((0.05 * seconds_total > 60 && percentage < 0.98) || + percentage < 0.95) && + seconds_left > 5) { // Never count the skip if under 5 seconds left app_->library_backend()->IncrementSkipCountAsync(song.id(), percentage); } } @@ -928,14 +1082,16 @@ void MainWindow::ScrobblingEnabledChanged(bool value) { if (!app_->player()->GetState() == Engine::Idle) { return; - } - else { - //invalidate current song, we will scrobble the next one - if (app_->playlist_manager()->active()->get_lastfm_status() == Playlist::LastFM_New) - app_->playlist_manager()->active()->set_lastfm_status(Playlist::LastFM_Seeked); + } else { + // invalidate current song, we will scrobble the next one + if (app_->playlist_manager()->active()->get_lastfm_status() == + Playlist::LastFM_New) + app_->playlist_manager()->active()->set_lastfm_status( + Playlist::LastFM_Seeked); } - bool is_lastfm = (app_->player()->GetCurrentItem()->options() & PlaylistItem::LastFMControls); + bool is_lastfm = (app_->player()->GetCurrentItem()->options() & + PlaylistItem::LastFMControls); ui_->action_ban->setEnabled(value && is_lastfm); tray_icon_->LastFMButtonBanStateChanged(value && is_lastfm); ui_->action_love->setEnabled(value); @@ -954,22 +1110,23 @@ void MainWindow::ScrobbleButtonVisibilityChanged(bool value) { ui_->action_toggle_scrobbling->setVisible(value); ui_->scrobbling_button->setVisible(value); - //when you reshow the buttons + // when you reshow the buttons if (value) { - //check if the song was scrobbled - if (app_->playlist_manager()->active()->get_lastfm_status() == Playlist::LastFM_Scrobbled) { + // check if the song was scrobbled + if (app_->playlist_manager()->active()->get_lastfm_status() == + Playlist::LastFM_Scrobbled) { ui_->action_toggle_scrobbling->setIcon(QIcon(":/last.fm/as.png")); } else { #ifdef HAVE_LIBLASTFM - SetToggleScrobblingIcon(app_->internet_model()->InternetModel::Service()->IsScrobblingEnabled()); + SetToggleScrobblingIcon(app_->internet_model() + ->InternetModel::Service() + ->IsScrobblingEnabled()); #endif } } } -void MainWindow::resizeEvent(QResizeEvent*) { - SaveGeometry(); -} +void MainWindow::resizeEvent(QResizeEvent*) { SaveGeometry(); } void MainWindow::SaveGeometry() { settings_.setValue("geometry", saveGeometry()); @@ -983,8 +1140,10 @@ void MainWindow::SavePlaybackStatus() { settings.beginGroup(MainWindow::kSettingsGroup); settings.setValue("playback_state", app_->player()->GetState()); if (app_->player()->GetState() == Engine::Playing || - app_->player()->GetState() == Engine::Paused) { - settings.setValue("playback_position", app_->player()->engine()->position_nanosec() / kNsecPerSec); + app_->player()->GetState() == Engine::Paused) { + settings.setValue( + "playback_position", + app_->player()->engine()->position_nanosec() / kNsecPerSec); } else { settings.setValue("playback_position", 0); } @@ -993,13 +1152,13 @@ void MainWindow::SavePlaybackStatus() { void MainWindow::LoadPlaybackStatus() { QSettings settings; settings.beginGroup(MainWindow::kSettingsGroup); - bool resume_playback = settings.value("resume_playback_after_start", false).toBool(); - saved_playback_state_ = static_cast - (settings.value("playback_state", Engine::Empty).toInt()); + bool resume_playback = + settings.value("resume_playback_after_start", false).toBool(); + saved_playback_state_ = static_cast( + settings.value("playback_state", Engine::Empty).toInt()); saved_playback_position_ = settings.value("playback_position", 0).toDouble(); - if (!resume_playback || - saved_playback_state_ == Engine::Empty || - saved_playback_state_ == Engine::Idle) { + if (!resume_playback || saved_playback_state_ == Engine::Empty || + saved_playback_state_ == Engine::Idle) { return; } @@ -1018,14 +1177,14 @@ void MainWindow::ResumePlayback() { } void MainWindow::PlayIndex(const QModelIndex& index) { - if (!index.isValid()) - return; + if (!index.isValid()) return; int row = index.row(); if (index.model() == app_->playlist_manager()->current()->proxy()) { // The index was in the proxy model (might've been filtered), so we need // to get the actual row in the source model. - row = app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); + row = + app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); } app_->playlist_manager()->SetActiveToCurrent(); @@ -1048,8 +1207,7 @@ void MainWindow::ToggleShowHide() { hide(); setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); SetHiddenInTray(false); - } else if (!isVisible()) - { + } else if (!isVisible()) { show(); activateWindow(); } else { @@ -1060,8 +1218,10 @@ void MainWindow::ToggleShowHide() { } void MainWindow::StopAfterCurrent() { - app_->playlist_manager()->active()->StopAfter(app_->playlist_manager()->active()->current_row()); - emit StopAfterToggled(app_->playlist_manager()->active()->stop_after_current()); + app_->playlist_manager()->active()->StopAfter( + app_->playlist_manager()->active()->current_row()); + emit StopAfterToggled( + app_->playlist_manager()->active()->stop_after_current()); } void MainWindow::closeEvent(QCloseEvent* event) { @@ -1100,12 +1260,13 @@ void MainWindow::FilePathChanged(const QString& path) { void MainWindow::Seeked(qlonglong microseconds) { const int position = microseconds / kUsecPerSec; - const int length = app_->player()->GetCurrentItem()->Metadata().length_nanosec() / kNsecPerSec; + const int length = + app_->player()->GetCurrentItem()->Metadata().length_nanosec() / + kNsecPerSec; tray_icon_->SetProgress(double(position) / length * 100); - //if we seeked, scrobbling is canceled, update the icon - if (ui_->action_toggle_scrobbling->isVisible()) - SetToggleScrobblingIcon(true); + // if we seeked, scrobbling is canceled, update the icon + if (ui_->action_toggle_scrobbling->isVisible()) SetToggleScrobblingIcon(true); } void MainWindow::UpdateTrackPosition() { @@ -1134,17 +1295,18 @@ void MainWindow::UpdateTrackPosition() { // Time to scrobble? if (position >= scrobble_point) { if (playlist->get_lastfm_status() == Playlist::LastFM_New) { - #ifdef HAVE_LIBLASTFM - if (lastfm_service->IsScrobblingEnabled() && lastfm_service->IsAuthenticated()) { - qLog(Info) << "Scrobbling at" << scrobble_point; - lastfm_service->Scrobble(); - } - #endif +#ifdef HAVE_LIBLASTFM + if (lastfm_service->IsScrobblingEnabled() && + lastfm_service->IsAuthenticated()) { + qLog(Info) << "Scrobbling at" << scrobble_point; + lastfm_service->Scrobble(); + } +#endif } // Update the play count for the song if it's from the library - if (!playlist->have_incremented_playcount() && - item->IsLocalLibraryItem() && item->Metadata().id() != -1 && + if (!playlist->have_incremented_playcount() && item->IsLocalLibraryItem() && + item->Metadata().id() != -1 && playlist->get_lastfm_status() != Playlist::LastFM_Seeked) { app_->library_backend()->IncrementPlayCountAsync(item->Metadata().id()); playlist->set_have_incremented_playcount(); @@ -1157,15 +1319,16 @@ void MainWindow::UpdateTrackPosition() { // Update the tray icon every 10 seconds if (position % 10 == 0) { qLog(Debug) << "position" << position << "scrobble point" << scrobble_point - << "status" << playlist->get_lastfm_status(); + << "status" << playlist->get_lastfm_status(); tray_icon_->SetProgress(double(position) / length * 100); - //if we're waiting for the scrobble point, update the icon +// if we're waiting for the scrobble point, update the icon #ifdef HAVE_LIBLASTFM if (position < scrobble_point && playlist->get_lastfm_status() == Playlist::LastFM_New && last_fm_enabled) { - ui_->action_toggle_scrobbling->setIcon(CreateOverlayedIcon(position, scrobble_point)); + ui_->action_toggle_scrobbling->setIcon( + CreateOverlayedIcon(position, scrobble_point)); } #endif } @@ -1184,48 +1347,49 @@ void MainWindow::Love() { } #endif -void MainWindow::ApplyAddBehaviour(MainWindow::AddBehaviour b, MimeData* data) const { +void MainWindow::ApplyAddBehaviour(MainWindow::AddBehaviour b, + MimeData* data) const { switch (b) { - case AddBehaviour_Append: - data->clear_first_ = false; - data->enqueue_now_ = false; - break; + case AddBehaviour_Append: + data->clear_first_ = false; + data->enqueue_now_ = false; + break; - case AddBehaviour_Enqueue: - data->clear_first_ = false; - data->enqueue_now_ = true; - break; + case AddBehaviour_Enqueue: + data->clear_first_ = false; + data->enqueue_now_ = true; + break; - case AddBehaviour_Load: - data->clear_first_ = true; - data->enqueue_now_ = false; - break; + case AddBehaviour_Load: + data->clear_first_ = true; + data->enqueue_now_ = false; + break; - case AddBehaviour_OpenInNew: - data->open_in_new_playlist_ = true; - break; + case AddBehaviour_OpenInNew: + data->open_in_new_playlist_ = true; + break; } } -void MainWindow::ApplyPlayBehaviour(MainWindow::PlayBehaviour b, MimeData* data) const { +void MainWindow::ApplyPlayBehaviour(MainWindow::PlayBehaviour b, + MimeData* data) const { switch (b) { - case PlayBehaviour_Always: - data->play_now_ = true; - break; + case PlayBehaviour_Always: + data->play_now_ = true; + break; - case PlayBehaviour_Never: - data->play_now_ = false; - break; + case PlayBehaviour_Never: + data->play_now_ = false; + break; - case PlayBehaviour_IfStopped: - data->play_now_ = !(app_->player()->GetState() == Engine::Playing); - break; + case PlayBehaviour_IfStopped: + data->play_now_ = !(app_->player()->GetState() == Engine::Playing); + break; } } void MainWindow::AddToPlaylist(QMimeData* data) { - if (!data) - return; + if (!data) return; if (MimeData* mime_data = qobject_cast(data)) { // Should we replace the flags with the user's preference? @@ -1239,12 +1403,13 @@ void MainWindow::AddToPlaylist(QMimeData* data) { } // Should we create a new playlist for the songs? - if(mime_data->open_in_new_playlist_) { + if (mime_data->open_in_new_playlist_) { app_->playlist_manager()->New(mime_data->get_name_for_new_playlist()); } } - app_->playlist_manager()->current()->dropMimeData(data, Qt::CopyAction, -1, 0, QModelIndex()); + app_->playlist_manager()->current()->dropMimeData(data, Qt::CopyAction, -1, 0, + QModelIndex()); delete data; } @@ -1252,44 +1417,48 @@ void MainWindow::AddToPlaylist(QAction* action) { int destination = action->data().toInt(); PlaylistItemList items; - //get the selected playlist items - foreach (const QModelIndex& index, ui_->playlist->view()->selectionModel()->selection().indexes()) { - if (index.column() != 0) - continue; - int row = app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); + // get the selected playlist items + foreach(const QModelIndex & index, + ui_->playlist->view()->selectionModel()->selection().indexes()) { + if (index.column() != 0) continue; + int row = + app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); items << app_->playlist_manager()->current()->item_at(row); } SongList songs; - foreach(PlaylistItemPtr item, items) { - songs << item->Metadata(); - } + foreach(PlaylistItemPtr item, items) { songs << item->Metadata(); } - //we're creating a new playlist + // we're creating a new playlist if (destination == -1) { - //save the current playlist to reactivate it + // save the current playlist to reactivate it int current_id = app_->playlist_manager()->current_id(); - //get the name from selection - app_->playlist_manager()->New(app_->playlist_manager()->GetNameForNewPlaylist(songs)); + // get the name from selection + app_->playlist_manager()->New( + app_->playlist_manager()->GetNameForNewPlaylist(songs)); if (app_->playlist_manager()->current()->id() != current_id) { - //I'm sure the new playlist was created and is selected, so I can just insert items + // I'm sure the new playlist was created and is selected, so I can just + // insert items app_->playlist_manager()->current()->InsertItems(items); - //set back the current playlist + // set back the current playlist app_->playlist_manager()->SetCurrentPlaylist(current_id); } - } - else { - //we're inserting in a existing playlist + } else { + // we're inserting in a existing playlist app_->playlist_manager()->playlist(destination)->InsertItems(items); } } -void MainWindow::PlaylistRightClick(const QPoint& global_pos, const QModelIndex& index) { - QModelIndex source_index = app_->playlist_manager()->current()->proxy()->mapToSource(index); +void MainWindow::PlaylistRightClick(const QPoint& global_pos, + const QModelIndex& index) { + QModelIndex source_index = + app_->playlist_manager()->current()->proxy()->mapToSource(index); playlist_menu_index_ = source_index; // Is this song currently playing? - if (app_->playlist_manager()->current()->current_row() == source_index.row() && app_->player()->GetState() == Engine::Playing) { + if (app_->playlist_manager()->current()->current_row() == + source_index.row() && + app_->player()->GetState() == Engine::Playing) { playlist_play_pause_->setText(tr("Pause")); playlist_play_pause_->setIcon(IconLoader::Load("media-playback-pause")); } else { @@ -1300,8 +1469,13 @@ void MainWindow::PlaylistRightClick(const QPoint& global_pos, const QModelIndex& // Are we allowed to pause? if (index.isValid()) { playlist_play_pause_->setEnabled( - app_->playlist_manager()->current()->current_row() != source_index.row() || - ! (app_->playlist_manager()->current()->item_at(source_index.row())->options() & PlaylistItem::PauseDisabled)); + app_->playlist_manager()->current()->current_row() != + source_index.row() || + !(app_->playlist_manager() + ->current() + ->item_at(source_index.row()) + ->options() & + PlaylistItem::PauseDisabled)); } else { playlist_play_pause_->setEnabled(false); } @@ -1309,31 +1483,32 @@ void MainWindow::PlaylistRightClick(const QPoint& global_pos, const QModelIndex& playlist_stop_after_->setEnabled(index.isValid()); // Are any of the selected songs editable or queued? - QModelIndexList selection = ui_->playlist->view()->selectionModel()->selection().indexes(); + QModelIndexList selection = + ui_->playlist->view()->selectionModel()->selection().indexes(); bool cue_selected = false; int editable = 0; int streams = 0; int in_queue = 0; int not_in_queue = 0; - foreach (const QModelIndex& index, selection) { - if (index.column() != 0) - continue; + foreach(const QModelIndex & index, selection) { + if (index.column() != 0) continue; - PlaylistItemPtr item = app_->playlist_manager()->current()->item_at(index.row()); - if(item->Metadata().has_cue()) { + PlaylistItemPtr item = + app_->playlist_manager()->current()->item_at(index.row()); + if (item->Metadata().has_cue()) { cue_selected = true; } else if (item->Metadata().IsEditable()) { editable++; } - if(item->Metadata().is_stream()) { + if (item->Metadata().is_stream()) { streams++; } if (index.data(Playlist::Role_QueuePosition).toInt() == -1) - not_in_queue ++; + not_in_queue++; else - in_queue ++; + in_queue++; } int all = not_in_queue + in_queue; @@ -1346,8 +1521,7 @@ void MainWindow::PlaylistRightClick(const QPoint& global_pos, const QModelIndex& ui_->action_auto_complete_tags->setVisible(editable); // the rest of the read / write actions work only when there are no CUEs // involved - if(cue_selected) - editable = 0; + if (cue_selected) editable = 0; // no 'show in browser' action if only streams are selected playlist_open_in_browser_->setVisible(streams != all); @@ -1386,25 +1560,26 @@ void MainWindow::PlaylistRightClick(const QPoint& global_pos, const QModelIndex& ui_->action_edit_value->setVisible(false); } else { Playlist::Column column = (Playlist::Column)index.column(); - bool column_is_editable = Playlist::column_is_editable(column) - && editable; + bool column_is_editable = Playlist::column_is_editable(column) && editable; ui_->action_selection_set_value->setVisible( ui_->action_selection_set_value->isVisible() && column_is_editable); - ui_->action_edit_value->setVisible( - ui_->action_edit_value->isVisible() && column_is_editable); + ui_->action_edit_value->setVisible(ui_->action_edit_value->isVisible() && + column_is_editable); QString column_name = Playlist::column_name(column); - QString column_value = app_->playlist_manager()->current()->data(source_index).toString(); + QString column_value = + app_->playlist_manager()->current()->data(source_index).toString(); if (column_value.length() > 25) column_value = column_value.left(25) + "..."; - ui_->action_selection_set_value->setText(tr("Set %1 to \"%2\"...") - .arg(column_name.toLower()).arg(column_value)); + ui_->action_selection_set_value->setText( + tr("Set %1 to \"%2\"...").arg(column_name.toLower()).arg(column_value)); ui_->action_edit_value->setText(tr("Edit tag \"%1\"...").arg(column_name)); // Is it a library item? - PlaylistItemPtr item = app_->playlist_manager()->current()->item_at(source_index.row()); + PlaylistItemPtr item = + app_->playlist_manager()->current()->item_at(source_index.row()); if (item->IsLocalLibraryItem() && item->Metadata().id() != -1) { playlist_organise_->setVisible(editable); playlist_show_in_library_->setVisible(editable); @@ -1417,29 +1592,32 @@ void MainWindow::PlaylistRightClick(const QPoint& global_pos, const QModelIndex& playlist_copy_to_device_->setVisible(editable); // Remove old item actions, if any. - foreach(QAction* action, playlistitem_actions_) { + foreach(QAction * action, playlistitem_actions_) { playlist_menu_->removeAction(action); } // Get the new item actions, and add them playlistitem_actions_ = item->actions(); - playlistitem_actions_separator_->setVisible(!playlistitem_actions_.isEmpty()); - playlist_menu_->insertActions(playlistitem_actions_separator_, playlistitem_actions_); + playlistitem_actions_separator_->setVisible( + !playlistitem_actions_.isEmpty()); + playlist_menu_->insertActions(playlistitem_actions_separator_, + playlistitem_actions_); } - //if it isn't the first time we right click, we need to remove the menu previously created + // if it isn't the first time we right click, we need to remove the menu + // previously created if (playlist_add_to_another_ != nullptr) { playlist_menu_->removeAction(playlist_add_to_another_); delete playlist_add_to_another_; } - //create the playlist submenu + // create the playlist submenu QMenu* add_to_another_menu = new QMenu(tr("Add to another playlist"), this); add_to_another_menu->setIcon(IconLoader::Load("list-add")); PlaylistBackend::Playlist playlist; - foreach (playlist, app_->playlist_backend()->GetAllOpenPlaylists()) { - //don't add the current playlist + foreach(playlist, app_->playlist_backend()->GetAllOpenPlaylists()) { + // don't add the current playlist if (playlist.id != app_->playlist_manager()->current()->id()) { QAction* existing_playlist = new QAction(this); existing_playlist->setText(playlist.name); @@ -1449,21 +1627,23 @@ void MainWindow::PlaylistRightClick(const QPoint& global_pos, const QModelIndex& } add_to_another_menu->addSeparator(); - //add to a new playlist + // add to a new playlist QAction* new_playlist = new QAction(this); new_playlist->setText(tr("New playlist")); - new_playlist->setData(-1); //fake id + new_playlist->setData(-1); // fake id add_to_another_menu->addAction(new_playlist); - playlist_add_to_another_ = playlist_menu_->insertMenu(ui_->action_remove_from_playlist, - add_to_another_menu); + playlist_add_to_another_ = playlist_menu_->insertMenu( + ui_->action_remove_from_playlist, add_to_another_menu); - connect(add_to_another_menu, SIGNAL(triggered(QAction*)), SLOT(AddToPlaylist(QAction*))); + connect(add_to_another_menu, SIGNAL(triggered(QAction*)), + SLOT(AddToPlaylist(QAction*))); playlist_menu_->popup(global_pos); } void MainWindow::PlaylistPlay() { - if (app_->playlist_manager()->current()->current_row() == playlist_menu_index_.row()) { + if (app_->playlist_manager()->current()->current_row() == + playlist_menu_index_.row()) { app_->player()->PlayPause(); } else { PlayIndex(playlist_menu_index_); @@ -1478,11 +1658,11 @@ void MainWindow::EditTracks() { SongList songs; PlaylistItemList items; - foreach (const QModelIndex& index, - ui_->playlist->view()->selectionModel()->selection().indexes()) { - if (index.column() != 0) - continue; - int row = app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); + foreach(const QModelIndex & index, + ui_->playlist->view()->selectionModel()->selection().indexes()) { + if (index.column() != 0) continue; + int row = + app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); PlaylistItemPtr item(app_->playlist_manager()->current()->item_at(row)); Song song = item->Metadata(); @@ -1498,7 +1678,7 @@ void MainWindow::EditTracks() { } void MainWindow::EditTagDialogAccepted() { - foreach (PlaylistItemPtr item, edit_tag_dialog_->playlist_items()) { + foreach(PlaylistItemPtr item, edit_tag_dialog_->playlist_items()) { item->Reload(); } @@ -1518,17 +1698,19 @@ void MainWindow::RenumberTracks() { // if first selected song has a track number set, start from that offset if (!indexes.isEmpty()) { - const Song first_song = app_->playlist_manager()->current()->item_at(indexes[0].row())->Metadata(); + const Song first_song = app_->playlist_manager() + ->current() + ->item_at(indexes[0].row()) + ->Metadata(); - if (first_song.track() > 0) - track = first_song.track(); + if (first_song.track() > 0) track = first_song.track(); } - foreach (const QModelIndex& index, indexes) { - if (index.column() != 0) - continue; + foreach(const QModelIndex & index, indexes) { + if (index.column() != 0) continue; - const QModelIndex source_index = app_->playlist_manager()->current()->proxy()->mapToSource(index); + const QModelIndex source_index = + app_->playlist_manager()->current()->proxy()->mapToSource(index); int row = source_index.row(); Song song = app_->playlist_manager()->current()->item_at(row)->Metadata(); @@ -1538,8 +1720,8 @@ void MainWindow::RenumberTracks() { TagReaderReply* reply = TagReaderClient::Instance()->SaveFile(song.url().toLocalFile(), song); - NewClosure(reply, SIGNAL(Finished(bool)), - this, SLOT(SongSaveComplete(TagReaderReply*,QPersistentModelIndex)), + NewClosure(reply, SIGNAL(Finished(bool)), this, + SLOT(SongSaveComplete(TagReaderReply*, QPersistentModelIndex)), reply, QPersistentModelIndex(source_index)); } track++; @@ -1549,22 +1731,24 @@ void MainWindow::RenumberTracks() { void MainWindow::SongSaveComplete(TagReaderReply* reply, const QPersistentModelIndex& index) { if (reply->is_successful() && index.isValid()) { - app_->playlist_manager()->current()->ReloadItems(QList() << index.row()); + app_->playlist_manager()->current()->ReloadItems(QList() + << index.row()); } reply->deleteLater(); } void MainWindow::SelectionSetValue() { Playlist::Column column = (Playlist::Column)playlist_menu_index_.column(); - QVariant column_value = app_->playlist_manager()->current()->data(playlist_menu_index_); + QVariant column_value = + app_->playlist_manager()->current()->data(playlist_menu_index_); QModelIndexList indexes = ui_->playlist->view()->selectionModel()->selection().indexes(); - foreach (const QModelIndex& index, indexes) { - if (index.column() != 0) - continue; + foreach(const QModelIndex & index, indexes) { + if (index.column() != 0) continue; - const QModelIndex source_index = app_->playlist_manager()->current()->proxy()->mapToSource(index); + const QModelIndex source_index = + app_->playlist_manager()->current()->proxy()->mapToSource(index); int row = source_index.row(); Song song = app_->playlist_manager()->current()->item_at(row)->Metadata(); @@ -1572,8 +1756,8 @@ void MainWindow::SelectionSetValue() { TagReaderReply* reply = TagReaderClient::Instance()->SaveFile(song.url().toLocalFile(), song); - NewClosure(reply, SIGNAL(Finished(bool)), - this, SLOT(SongSaveComplete(TagReaderReply*,QPersistentModelIndex)), + NewClosure(reply, SIGNAL(Finished(bool)), this, + SLOT(SongSaveComplete(TagReaderReply*, QPersistentModelIndex)), reply, QPersistentModelIndex(source_index)); } } @@ -1581,18 +1765,15 @@ void MainWindow::SelectionSetValue() { void MainWindow::EditValue() { QModelIndex current = ui_->playlist->view()->currentIndex(); - if (!current.isValid()) - return; + if (!current.isValid()) return; // Edit the last column that was right-clicked on. If nothing's ever been // right clicked then look for the first editable column. int column = playlist_menu_index_.column(); if (column == -1) { - for (int i=0 ; iplaylist->view()->model()->columnCount() ; ++i) { - if (ui_->playlist->view()->isColumnHidden(i)) - continue; - if (!Playlist::column_is_editable(Playlist::Column(i))) - continue; + for (int i = 0; i < ui_->playlist->view()->model()->columnCount(); ++i) { + if (ui_->playlist->view()->isColumnHidden(i)) continue; + if (!Playlist::column_is_editable(Playlist::Column(i))) continue; column = i; break; } @@ -1603,27 +1784,25 @@ void MainWindow::EditValue() { void MainWindow::AddFile() { // Last used directory - QString directory = settings_.value("add_media_path", QDir::currentPath()).toString(); + QString directory = + settings_.value("add_media_path", QDir::currentPath()).toString(); PlaylistParser parser(app_->library_backend()); // Show dialog QStringList file_names = QFileDialog::getOpenFileNames( this, tr("Add file"), directory, - QString("%1 (%2);;%3;;%4").arg( - tr("Music"), - FileView::kFileFilter, - parser.filters(), - tr(kAllFilesFilterSpec))); - if (file_names.isEmpty()) - return; + QString("%1 (%2);;%3;;%4").arg(tr("Music"), FileView::kFileFilter, + parser.filters(), + tr(kAllFilesFilterSpec))); + if (file_names.isEmpty()) return; // Save last used directory settings_.setValue("add_media_path", file_names[0]); // Convert to URLs QList urls; - foreach (const QString& path, file_names) { + foreach(const QString & path, file_names) { urls << QUrl::fromLocalFile(QFileInfo(path).canonicalFilePath()); } @@ -1634,26 +1813,29 @@ void MainWindow::AddFile() { void MainWindow::AddFolder() { // Last used directory - QString directory = settings_.value("add_folder_path", QDir::currentPath()).toString(); + QString directory = + settings_.value("add_folder_path", QDir::currentPath()).toString(); // Show dialog - directory = QFileDialog::getExistingDirectory(this, tr("Add folder"), directory); - if (directory.isEmpty()) - return; + directory = + QFileDialog::getExistingDirectory(this, tr("Add folder"), directory); + if (directory.isEmpty()) return; // Save last used directory settings_.setValue("add_folder_path", directory); // Add media MimeData* data = new MimeData; - data->setUrls(QList() << QUrl::fromLocalFile(QFileInfo(directory).canonicalFilePath())); + data->setUrls(QList() << QUrl::fromLocalFile( + QFileInfo(directory).canonicalFilePath())); AddToPlaylist(data); } void MainWindow::AddStream() { if (!add_stream_dialog_) { add_stream_dialog_.reset(new AddStreamDialog); - connect(add_stream_dialog_.get(), SIGNAL(accepted()), SLOT(AddStreamAccepted())); + connect(add_stream_dialog_.get(), SIGNAL(accepted()), + SLOT(AddStreamAccepted())); add_stream_dialog_->set_add_on_accept(InternetModel::Service()); } @@ -1667,22 +1849,21 @@ void MainWindow::AddStreamAccepted() { AddToPlaylist(data); } - void MainWindow::OpenRipCD() { - #ifdef HAVE_AUDIOCD - if (!rip_cd_) { - rip_cd_.reset(new RipCD); - } - if(rip_cd_->CDIOIsValid()) { - rip_cd_->show(); - } else { - QMessageBox cdio_fail(QMessageBox::Critical, tr("Error"), tr("Failed reading CD drive")); - cdio_fail.exec(); - } - #endif +#ifdef HAVE_AUDIOCD + if (!rip_cd_) { + rip_cd_.reset(new RipCD); + } + if (rip_cd_->CDIOIsValid()) { + rip_cd_->show(); + } else { + QMessageBox cdio_fail(QMessageBox::Critical, tr("Error"), + tr("Failed reading CD drive")); + cdio_fail.exec(); + } +#endif } - void MainWindow::AddCDTracks() { MimeData* data = new MimeData; // We are putting empty data, but we specify cdda mimetype to indicate that @@ -1694,19 +1875,28 @@ void MainWindow::AddCDTracks() { void MainWindow::ShowInLibrary() { // Show the first valid selected track artist/album in LibraryView - QModelIndexList proxy_indexes = ui_->playlist->view()->selectionModel()->selectedRows(); + QModelIndexList proxy_indexes = + ui_->playlist->view()->selectionModel()->selectedRows(); SongList songs; - foreach (const QModelIndex& proxy_index, proxy_indexes) { - QModelIndex index = app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); - if (app_->playlist_manager()->current()->item_at(index.row())->IsLocalLibraryItem()) { - songs << app_->playlist_manager()->current()->item_at(index.row())->Metadata(); + foreach(const QModelIndex & proxy_index, proxy_indexes) { + QModelIndex index = + app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); + if (app_->playlist_manager() + ->current() + ->item_at(index.row()) + ->IsLocalLibraryItem()) { + songs << app_->playlist_manager() + ->current() + ->item_at(index.row()) + ->Metadata(); break; } } QString search; if (!songs.isEmpty()) { - search = "artist:" + songs.first().artist() + " album:" + songs.first().album(); + search = + "artist:" + songs.first().artist() + " album:" + songs.first().album(); } library_view_->filter()->ShowInLibrary(search); } @@ -1716,11 +1906,11 @@ void MainWindow::PlaylistRemoveCurrent() { } void MainWindow::PlaylistEditFinished(const QModelIndex& index) { - if (index == playlist_menu_index_) - SelectionSetValue(); + if (index == playlist_menu_index_) SelectionSetValue(); } -void MainWindow::CommandlineOptionsReceived(const QByteArray& serialized_options) { +void MainWindow::CommandlineOptionsReceived( + const QByteArray& serialized_options) { if (serialized_options == "wake up!") { // Old versions of Clementine sent this - just ignore it return; @@ -1732,12 +1922,11 @@ void MainWindow::CommandlineOptionsReceived(const QByteArray& serialized_options if (options.is_empty()) { show(); activateWindow(); - } - else + } else CommandlineOptionsReceived(options); } -void MainWindow::CommandlineOptionsReceived(const CommandlineOptions &options) { +void MainWindow::CommandlineOptionsReceived(const CommandlineOptions& options) { switch (options.player_action()) { case CommandlineOptions::Player_Play: app_->player()->Play(); @@ -1769,7 +1958,7 @@ void MainWindow::CommandlineOptionsReceived(const CommandlineOptions &options) { case CommandlineOptions::UrlList_Load: app_->playlist_manager()->ClearCurrent(); - // fallthrough + // fallthrough case CommandlineOptions::UrlList_Append: { MimeData* data = new MimeData; data->setUrls(options.urls()); @@ -1782,21 +1971,22 @@ void MainWindow::CommandlineOptionsReceived(const CommandlineOptions &options) { app_->player()->SetVolume(options.set_volume()); if (options.volume_modifier() != 0) - app_->player()->SetVolume(app_->player()->GetVolume() + options.volume_modifier()); + app_->player()->SetVolume(app_->player()->GetVolume() + + options.volume_modifier()); if (options.seek_to() != -1) app_->player()->SeekTo(options.seek_to()); else if (options.seek_by() != 0) - app_->player()->SeekTo(app_->player()->engine()->position_nanosec() / kNsecPerSec + options.seek_by()); + app_->player()->SeekTo(app_->player()->engine()->position_nanosec() / + kNsecPerSec + + options.seek_by()); if (options.play_track_at() != -1) app_->player()->PlayAt(options.play_track_at(), Engine::Manual, true); - if (options.show_osd()) - app_->player()->ShowOSD(); + if (options.show_osd()) app_->player()->ShowOSD(); - if (options.toggle_pretty_osd()) - app_->player()->TogglePrettyOSD(); + if (options.toggle_pretty_osd()) app_->player()->TogglePrettyOSD(); } void MainWindow::ForceShowOSD(const Song& song, const bool toggle) { @@ -1806,13 +1996,10 @@ void MainWindow::ForceShowOSD(const Song& song, const bool toggle) { osd_->ReshowCurrentSong(); } -void MainWindow::Activate() { - show(); -} +void MainWindow::Activate() { show(); } bool MainWindow::LoadUrl(const QString& url) { - if (!QFile::exists(url)) - return false; + if (!QFile::exists(url)) return false; MimeData* data = new MimeData; data->setUrls(QList() << QUrl::fromLocalFile(url)); @@ -1827,7 +2014,7 @@ void MainWindow::CheckForUpdates() { #endif } -void MainWindow::PlaylistUndoRedoChanged(QAction *undo, QAction *redo) { +void MainWindow::PlaylistUndoRedoChanged(QAction* undo, QAction* redo) { playlist_menu_->insertAction(playlist_undoredo_, undo); playlist_menu_->insertAction(playlist_undoredo_, redo); } @@ -1839,11 +2026,11 @@ void MainWindow::AddFilesToTranscoder() { QStringList filenames; - foreach (const QModelIndex& index, - ui_->playlist->view()->selectionModel()->selection().indexes()) { - if (index.column() != 0) - continue; - int row = app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); + foreach(const QModelIndex & index, + ui_->playlist->view()->selectionModel()->selection().indexes()) { + if (index.column() != 0) continue; + int row = + app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); PlaylistItemPtr item(app_->playlist_manager()->current()->item_at(row)); Song song = item->Metadata(); filenames << song.url().toLocalFile(); @@ -1879,26 +2066,30 @@ void MainWindow::NowPlayingWidgetPositionChanged(bool above_status_bar) { } void MainWindow::CopyFilesToLibrary(const QList& urls) { - organise_dialog_->SetDestinationModel(app_->library_model()->directory_model()); + organise_dialog_->SetDestinationModel( + app_->library_model()->directory_model()); organise_dialog_->SetUrls(urls); organise_dialog_->SetCopy(true); organise_dialog_->show(); } void MainWindow::MoveFilesToLibrary(const QList& urls) { - organise_dialog_->SetDestinationModel(app_->library_model()->directory_model()); + organise_dialog_->SetDestinationModel( + app_->library_model()->directory_model()); organise_dialog_->SetUrls(urls); organise_dialog_->SetCopy(false); organise_dialog_->show(); } void MainWindow::CopyFilesToDevice(const QList& urls) { - organise_dialog_->SetDestinationModel(app_->device_manager()->connected_devices_model(), true); + organise_dialog_->SetDestinationModel( + app_->device_manager()->connected_devices_model(), true); organise_dialog_->SetCopy(true); if (organise_dialog_->SetUrls(urls)) organise_dialog_->show(); else { - QMessageBox::warning(this, tr("Error"), + QMessageBox::warning( + this, tr("Error"), tr("None of the selected songs were suitable for copying to a device")); } } @@ -1907,7 +2098,7 @@ void MainWindow::EditFileTags(const QList& urls) { EnsureEditTagDialogCreated(); SongList songs; - foreach (const QUrl& url, urls) { + foreach(const QUrl & url, urls) { Song song; song.set_url(url); song.set_valid(true); @@ -1919,25 +2110,27 @@ void MainWindow::EditFileTags(const QList& urls) { edit_tag_dialog_->show(); } -void MainWindow::PlaylistCopyToLibrary() { - PlaylistOrganiseSelected(true); -} +void MainWindow::PlaylistCopyToLibrary() { PlaylistOrganiseSelected(true); } -void MainWindow::PlaylistMoveToLibrary() { - PlaylistOrganiseSelected(false); -} +void MainWindow::PlaylistMoveToLibrary() { PlaylistOrganiseSelected(false); } void MainWindow::PlaylistOrganiseSelected(bool copy) { - QModelIndexList proxy_indexes = ui_->playlist->view()->selectionModel()->selectedRows(); + QModelIndexList proxy_indexes = + ui_->playlist->view()->selectionModel()->selectedRows(); SongList songs; - foreach (const QModelIndex& proxy_index, proxy_indexes) { - QModelIndex index = app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); + foreach(const QModelIndex & proxy_index, proxy_indexes) { + QModelIndex index = + app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); - songs << app_->playlist_manager()->current()->item_at(index.row())->Metadata(); + songs << app_->playlist_manager() + ->current() + ->item_at(index.row()) + ->Metadata(); } - organise_dialog_->SetDestinationModel(app_->library_model()->directory_model()); + organise_dialog_->SetDestinationModel( + app_->library_model()->directory_model()); organise_dialog_->SetSongs(songs); organise_dialog_->SetCopy(copy); organise_dialog_->show(); @@ -1947,42 +2140,53 @@ void MainWindow::PlaylistDelete() { // Note: copied from LibraryView::Delete if (QMessageBox::warning(this, tr("Delete files"), - tr("These files will be permanently deleted from disk, are you sure you want to continue?"), - QMessageBox::Yes, QMessageBox::Cancel) != QMessageBox::Yes) + tr("These files will be permanently deleted from " + "disk, are you sure you want to continue?"), + QMessageBox::Yes, + QMessageBox::Cancel) != QMessageBox::Yes) return; std::shared_ptr storage(new FilesystemMusicStorage("/")); // Get selected songs SongList selected_songs; - QModelIndexList proxy_indexes = ui_->playlist->view()->selectionModel()->selectedRows(); - foreach (const QModelIndex& proxy_index, proxy_indexes) { - QModelIndex index = app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); - selected_songs << app_->playlist_manager()->current()->item_at(index.row())->Metadata(); + QModelIndexList proxy_indexes = + ui_->playlist->view()->selectionModel()->selectedRows(); + foreach(const QModelIndex & proxy_index, proxy_indexes) { + QModelIndex index = + app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); + selected_songs << app_->playlist_manager() + ->current() + ->item_at(index.row()) + ->Metadata(); } ui_->playlist->view()->RemoveSelected(); DeleteFiles* delete_files = new DeleteFiles(app_->task_manager(), storage); - connect(delete_files, SIGNAL(Finished(SongList)), SLOT(DeleteFinished(SongList))); + connect(delete_files, SIGNAL(Finished(SongList)), + SLOT(DeleteFinished(SongList))); delete_files->Start(selected_songs); } void MainWindow::PlaylistOpenInBrowser() { QList urls; - QModelIndexList proxy_indexes = ui_->playlist->view()->selectionModel()->selectedRows(); + QModelIndexList proxy_indexes = + ui_->playlist->view()->selectionModel()->selectedRows(); - foreach (const QModelIndex& proxy_index, proxy_indexes) { - const QModelIndex index = app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); - urls << QUrl(index.sibling(index.row(), Playlist::Column_Filename).data().toString()); + foreach(const QModelIndex & proxy_index, proxy_indexes) { + const QModelIndex index = + app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); + urls << QUrl(index.sibling(index.row(), Playlist::Column_Filename) + .data() + .toString()); } Utilities::OpenInFileBrowser(urls); } void MainWindow::DeleteFinished(const SongList& songs_with_errors) { - if (songs_with_errors.isEmpty()) - return; + if (songs_with_errors.isEmpty()) return; OrganiseErrorDialog* dialog = new OrganiseErrorDialog(this); dialog->Show(OrganiseErrorDialog::Type_Delete, songs_with_errors); @@ -1991,36 +2195,44 @@ void MainWindow::DeleteFinished(const SongList& songs_with_errors) { void MainWindow::PlaylistQueue() { QModelIndexList indexes; - foreach (const QModelIndex& proxy_index, - ui_->playlist->view()->selectionModel()->selectedRows()) { - indexes << app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); + foreach(const QModelIndex & proxy_index, + ui_->playlist->view()->selectionModel()->selectedRows()) { + indexes << app_->playlist_manager()->current()->proxy()->mapToSource( + proxy_index); } app_->playlist_manager()->current()->queue()->ToggleTracks(indexes); } void MainWindow::PlaylistCopyToDevice() { - QModelIndexList proxy_indexes = ui_->playlist->view()->selectionModel()->selectedRows(); + QModelIndexList proxy_indexes = + ui_->playlist->view()->selectionModel()->selectedRows(); SongList songs; - foreach (const QModelIndex& proxy_index, proxy_indexes) { - QModelIndex index = app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); + foreach(const QModelIndex & proxy_index, proxy_indexes) { + QModelIndex index = + app_->playlist_manager()->current()->proxy()->mapToSource(proxy_index); - songs << app_->playlist_manager()->current()->item_at(index.row())->Metadata(); + songs << app_->playlist_manager() + ->current() + ->item_at(index.row()) + ->Metadata(); } - organise_dialog_->SetDestinationModel(app_->device_manager()->connected_devices_model(), true); + organise_dialog_->SetDestinationModel( + app_->device_manager()->connected_devices_model(), true); organise_dialog_->SetCopy(true); if (organise_dialog_->SetSongs(songs)) organise_dialog_->show(); else { - QMessageBox::warning(this, tr("Error"), + QMessageBox::warning( + this, tr("Error"), tr("None of the selected songs were suitable for copying to a device")); } } void MainWindow::ChangeLibraryQueryMode(QAction* action) { - if(action == library_show_duplicates_) { + if (action == library_show_duplicates_) { library_view_->filter()->SetQueryMode(QueryOptions::QueryMode_Duplicates); } else if (action == library_show_untagged_) { library_view_->filter()->SetQueryMode(QueryOptions::QueryMode_Untagged); @@ -2035,30 +2247,34 @@ void MainWindow::ShowCoverManager() { cover_manager_->Init(); // Cover manager connections - connect(cover_manager_.get(), SIGNAL(AddToPlaylist(QMimeData*)), SLOT(AddToPlaylist(QMimeData*))); + connect(cover_manager_.get(), SIGNAL(AddToPlaylist(QMimeData*)), + SLOT(AddToPlaylist(QMimeData*))); } cover_manager_->show(); } void MainWindow::EnsureSettingsDialogCreated() { - if (settings_dialog_) - return; + if (settings_dialog_) return; settings_dialog_.reset(new SettingsDialog(app_, background_streams_)); settings_dialog_->SetGlobalShortcutManager(global_shortcuts_); settings_dialog_->SetSongInfoView(song_info_view_); // Settings - connect(settings_dialog_.get(), SIGNAL(accepted()), SLOT(ReloadAllSettings())); + connect(settings_dialog_.get(), SIGNAL(accepted()), + SLOT(ReloadAllSettings())); #ifdef HAVE_WIIMOTEDEV - connect(settings_dialog_.get(), SIGNAL(SetWiimotedevInterfaceActived(bool)), wiimotedev_shortcuts_.get(), SLOT(SetWiimotedevInterfaceActived(bool))); + connect(settings_dialog_.get(), SIGNAL(SetWiimotedevInterfaceActived(bool)), + wiimotedev_shortcuts_.get(), + SLOT(SetWiimotedevInterfaceActived(bool))); #endif // Allows custom notification preview - connect(settings_dialog_.get(), SIGNAL(NotificationPreview(OSD::Behaviour,QString,QString)), - SLOT(HandleNotificationPreview(OSD::Behaviour,QString,QString))); + connect(settings_dialog_.get(), + SIGNAL(NotificationPreview(OSD::Behaviour, QString, QString)), + SLOT(HandleNotificationPreview(OSD::Behaviour, QString, QString))); } void MainWindow::OpenSettingsDialog() { @@ -2072,12 +2288,13 @@ void MainWindow::OpenSettingsDialogAtPage(SettingsDialog::Page page) { } void MainWindow::EnsureEditTagDialogCreated() { - if (edit_tag_dialog_) - return; + if (edit_tag_dialog_) return; edit_tag_dialog_.reset(new EditTagDialog(app_)); - connect(edit_tag_dialog_.get(), SIGNAL(accepted()), SLOT(EditTagDialogAccepted())); - connect(edit_tag_dialog_.get(), SIGNAL(Error(QString)), SLOT(ShowErrorDialog(QString))); + connect(edit_tag_dialog_.get(), SIGNAL(accepted()), + SLOT(EditTagDialogAccepted())); + connect(edit_tag_dialog_.get(), SIGNAL(Error(QString)), + SLOT(ShowErrorDialog(QString))); } void MainWindow::ShowAboutDialog() { @@ -2108,31 +2325,34 @@ void MainWindow::CheckFullRescanRevisions() { // if we're restoring DB from scratch or nothing has // changed, do nothing - if(from == 0 || from == to) { + if (from == 0 || from == to) { return; } // collect all reasons QSet reasons; - for(int i = from; i <= to; i++) { + for (int i = from; i <= to; i++) { QString reason = app_->library()->full_rescan_reason(i); - if(!reason.isEmpty()) { + if (!reason.isEmpty()) { reasons.insert(reason); } } // if we have any... - if(!reasons.isEmpty()) { - QString message = tr("The version of Clementine you've just updated to requires a full library rescan " - "because of the new features listed below:") + "
    "; - foreach(const QString& reason, reasons) { + if (!reasons.isEmpty()) { + QString message = tr("The version of Clementine you've just updated to " + "requires a full library rescan " + "because of the new features listed below:") + + "
      "; + foreach(const QString & reason, reasons) { message += ("
    • " + reason + "
    • "); } message += "
    " + tr("Would you like to run a full rescan right now?"); - if(QMessageBox::question(this, tr("Library rescan notice"), - message, QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { + if (QMessageBox::question(this, tr("Library rescan notice"), message, + QMessageBox::Yes, + QMessageBox::No) == QMessageBox::Yes) { app_->library()->FullScan(); } } @@ -2151,32 +2371,37 @@ void MainWindow::ShowVisualisations() { if (!visualisation_) { visualisation_.reset(new VisualisationContainer); - visualisation_->SetActions(ui_->action_previous_track, ui_->action_play_pause, - ui_->action_stop, ui_->action_next_track); - connect(app_->player(), SIGNAL(Stopped()), visualisation_.get(), SLOT(Stopped())); - connect(app_->player(), SIGNAL(ForceShowOSD(Song, bool)), visualisation_.get(), SLOT(SongMetadataChanged(Song))); - connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), visualisation_.get(), SLOT(SongMetadataChanged(Song))); + visualisation_->SetActions(ui_->action_previous_track, + ui_->action_play_pause, ui_->action_stop, + ui_->action_next_track); + connect(app_->player(), SIGNAL(Stopped()), visualisation_.get(), + SLOT(Stopped())); + connect(app_->player(), SIGNAL(ForceShowOSD(Song, bool)), + visualisation_.get(), SLOT(SongMetadataChanged(Song))); + connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), + visualisation_.get(), SLOT(SongMetadataChanged(Song))); - visualisation_->SetEngine(qobject_cast(app_->player()->engine())); + visualisation_->SetEngine( + qobject_cast(app_->player()->engine())); } visualisation_->show(); -#endif // ENABLE_VISUALISATIONS +#endif // ENABLE_VISUALISATIONS } void MainWindow::ConnectInfoView(SongInfoBase* view) { - connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), view, SLOT(SongChanged(Song))); - connect(app_->player(), SIGNAL(PlaylistFinished()), view, SLOT(SongFinished())); + connect(app_->playlist_manager(), SIGNAL(CurrentSongChanged(Song)), view, + SLOT(SongChanged(Song))); + connect(app_->player(), SIGNAL(PlaylistFinished()), view, + SLOT(SongFinished())); connect(app_->player(), SIGNAL(Stopped()), view, SLOT(SongFinished())); connect(view, SIGNAL(ShowSettingsDialog()), SLOT(ShowSongInfoConfig())); - connect(view, SIGNAL(DoGlobalSearch(QString)), - SLOT(DoGlobalSearch(QString))); + connect(view, SIGNAL(DoGlobalSearch(QString)), SLOT(DoGlobalSearch(QString))); } void MainWindow::AddSongInfoGenerator(smart_playlists::GeneratorPtr gen) { - if (!gen) - return; + if (!gen) return; gen->set_library(app_->library_backend()); AddToPlaylist(new smart_playlists::GeneratorMimeData(gen)); @@ -2188,7 +2413,7 @@ void MainWindow::ShowSongInfoConfig() { void MainWindow::PlaylistViewSelectionModelChanged() { connect(ui_->playlist->view()->selectionModel(), - SIGNAL(currentChanged(QModelIndex,QModelIndex)), + SIGNAL(currentChanged(QModelIndex, QModelIndex)), SLOT(PlaylistCurrentChanged(QModelIndex))); } @@ -2212,18 +2437,20 @@ bool MainWindow::winEvent(MSG* msg, long*) { thumbbar_->HandleWinEvent(msg); return false; } -#endif // Q_OS_WIN32 +#endif // Q_OS_WIN32 void MainWindow::Exit() { SavePlaybackStatus(); - if(app_->player()->engine()->is_fadeout_enabled()) { + if (app_->player()->engine()->is_fadeout_enabled()) { // To shut down the application when fadeout will be finished - connect(app_->player()->engine(), SIGNAL(FadeoutFinishedSignal()), qApp, SLOT(quit())); - if(app_->player()->GetState() == Engine::Playing) { + connect(app_->player()->engine(), SIGNAL(FadeoutFinishedSignal()), qApp, + SLOT(quit())); + if (app_->player()->GetState() == Engine::Playing) { app_->player()->Stop(); hide(); tray_icon_->SetVisible(false); - return; // Don't quit the application now: wait for the fadeout finished signal + return; // Don't quit the application now: wait for the fadeout finished + // signal } } qApp->quit(); @@ -2237,10 +2464,11 @@ void MainWindow::AutoCompleteTags() { track_selection_dialog_->set_save_on_close(true); connect(tag_fetcher_.get(), SIGNAL(ResultAvailable(Song, SongList)), - track_selection_dialog_.get(), SLOT(FetchTagFinished(Song, SongList)), - Qt::QueuedConnection); - connect(tag_fetcher_.get(), SIGNAL(Progress(Song,QString)), - track_selection_dialog_.get(), SLOT(FetchTagProgress(Song,QString))); + track_selection_dialog_.get(), + SLOT(FetchTagFinished(Song, SongList)), Qt::QueuedConnection); + connect(tag_fetcher_.get(), SIGNAL(Progress(Song, QString)), + track_selection_dialog_.get(), + SLOT(FetchTagProgress(Song, QString))); connect(track_selection_dialog_.get(), SIGNAL(accepted()), SLOT(AutoCompleteTagsAccepted())); connect(track_selection_dialog_.get(), SIGNAL(finished(int)), @@ -2250,11 +2478,11 @@ void MainWindow::AutoCompleteTags() { // Get the selected songs and start fetching tags for them SongList songs; autocomplete_tag_items_.clear(); - foreach (const QModelIndex& index, - ui_->playlist->view()->selectionModel()->selection().indexes()) { - if (index.column() != 0) - continue; - int row = app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); + foreach(const QModelIndex & index, + ui_->playlist->view()->selectionModel()->selection().indexes()) { + if (index.column() != 0) continue; + int row = + app_->playlist_manager()->current()->proxy()->mapToSource(index).row(); PlaylistItemPtr item(app_->playlist_manager()->current()->item_at(row)); Song song = item->Metadata(); @@ -2271,9 +2499,7 @@ void MainWindow::AutoCompleteTags() { } void MainWindow::AutoCompleteTagsAccepted() { - foreach (PlaylistItemPtr item, autocomplete_tag_items_) { - item->Reload(); - } + foreach(PlaylistItemPtr item, autocomplete_tag_items_) { item->Reload(); } // This is really lame but we don't know what rows have changed ui_->playlist->view()->update(); @@ -2284,14 +2510,14 @@ QPixmap MainWindow::CreateOverlayedIcon(int position, int scrobble_point) { QPixmap light_icon = QIcon(":/last.fm/as.png").pixmap(16); QRect rect(normal_icon.rect()); - //calculates the progress - double perc = 1.0 - ((double) position / (double) scrobble_point); + // calculates the progress + double perc = 1.0 - ((double)position / (double)scrobble_point); QPolygon mask; mask << rect.topRight(); mask << rect.topLeft(); - mask << QPoint(rect.left(), rect.height()*perc); - mask << QPoint(rect.right(), (rect.height())*perc); + mask << QPoint(rect.left(), rect.height() * perc); + mask << QPoint(rect.right(), (rect.height()) * perc); QPixmap ret(light_icon); QPainter p(&ret); @@ -2321,7 +2547,8 @@ void MainWindow::ScrobbleSubmitted() { lastfm_service->IsScrobblingEnabled() && lastfm_service->IsAuthenticated(); - app_->playlist_manager()->active()->set_lastfm_status(Playlist::LastFM_Scrobbled); + app_->playlist_manager()->active()->set_lastfm_status( + Playlist::LastFM_Scrobbled); // update the button icon if (last_fm_enabled) @@ -2332,19 +2559,23 @@ void MainWindow::ScrobbleError(int value) { switch (value) { case -1: // custom error value got from initial validity check - app_->playlist_manager()->active()->set_lastfm_status(Playlist::LastFM_Invalid); + app_->playlist_manager()->active()->set_lastfm_status( + Playlist::LastFM_Invalid); break; case 30: // Hack: when offline, liblastfm doesn't inform us, so set the status - // as queued; in this way we won't try to scrobble again, it will be done automatically - app_->playlist_manager()->active()->set_lastfm_status(Playlist::LastFM_Queued); + // as queued; in this way we won't try to scrobble again, it will be done + // automatically + app_->playlist_manager()->active()->set_lastfm_status( + Playlist::LastFM_Queued); break; default: if (value > 3) { // we're for sure in an error state - app_->playlist_manager()->active()->set_lastfm_status(Playlist::LastFM_Error); + app_->playlist_manager()->active()->set_lastfm_status( + Playlist::LastFM_Error); qLog(Warning) << "Last.fm scrobbling error: " << value; } break; @@ -2352,10 +2583,13 @@ void MainWindow::ScrobbleError(int value) { } #endif -void MainWindow::HandleNotificationPreview(OSD::Behaviour type, QString line1, QString line2) { +void MainWindow::HandleNotificationPreview(OSD::Behaviour type, QString line1, + QString line2) { if (!app_->playlist_manager()->current()->GetAllSongs().isEmpty()) { // Show a preview notification for the first song in the current playlist - osd_->ShowPreview(type, line1, line2, app_->playlist_manager()->current()->GetAllSongs().first()); + osd_->ShowPreview( + type, line1, line2, + app_->playlist_manager()->current()->GetAllSongs().first()); } else { qLog(Debug) << "The current playlist is empty, showing a fake song"; // Create a fake song @@ -2397,13 +2631,13 @@ void MainWindow::ShowConsole() { } void MainWindow::keyPressEvent(QKeyEvent* event) { - if(event->key() == Qt::Key_Space) { + if (event->key() == Qt::Key_Space) { app_->player()->PlayPause(); event->accept(); - } else if(event->key() == Qt::Key_Left) { + } else if (event->key() == Qt::Key_Left) { ui_->track_slider->Seek(-1); event->accept(); - } else if(event->key() == Qt::Key_Right) { + } else if (event->key() == Qt::Key_Right) { ui_->track_slider->Seek(1); event->accept(); } else { diff --git a/src/ui/mainwindow.h b/src/ui/mainwindow.h index 4ab78948f..0aead56fd 100644 --- a/src/ui/mainwindow.h +++ b/src/ui/mainwindow.h @@ -82,17 +82,14 @@ class WiimotedevShortcuts; class Windows7ThumbBar; class Ui_MainWindow; - class QSortFilterProxyModel; class MainWindow : public QMainWindow, public PlatformInterface { Q_OBJECT public: - MainWindow(Application* app, - SystemTrayIcon* tray_icon, - OSD* osd, - QWidget *parent = 0); + MainWindow(Application* app, SystemTrayIcon* tray_icon, OSD* osd, + QWidget* parent = 0); ~MainWindow(); static const char* kSettingsGroup; @@ -136,13 +133,13 @@ class MainWindow : public QMainWindow, public PlatformInterface { void Activate(); bool LoadUrl(const QString& url); - signals: +signals: // Signals that stop playing after track was toggled. void StopAfterToggled(bool stop); private slots: void FilePathChanged(const QString& path); - + void MediaStopped(); void MediaPaused(); void MediaPlaying(); @@ -197,7 +194,7 @@ class MainWindow : public QMainWindow, public PlatformInterface { void Seeked(qlonglong microseconds); void UpdateTrackPosition(); - //Handle visibility of LastFM icons + // Handle visibility of LastFM icons void LastFMButtonVisibilityChanged(bool value); void ScrobbleButtonVisibilityChanged(bool value); void SetToggleScrobblingIcon(bool value); @@ -261,7 +258,8 @@ class MainWindow : public QMainWindow, public PlatformInterface { void Exit(); - void HandleNotificationPreview(OSD::Behaviour type, QString line1, QString line2); + void HandleNotificationPreview(OSD::Behaviour type, QString line1, + QString line2); void ScrollToInternetIndex(const QModelIndex& index); void FocusGlobalSearchField(); @@ -277,7 +275,7 @@ class MainWindow : public QMainWindow, public PlatformInterface { void CheckFullRescanRevisions(); - //creates the icon by painting the full one depending on the current position + // creates the icon by painting the full one depending on the current position QPixmap CreateOverlayedIcon(int position, int scrobble_point); private: @@ -296,9 +294,9 @@ class MainWindow : public QMainWindow, public PlatformInterface { GlobalSearchView* global_search_view_; LibraryViewContainer* library_view_; FileView* file_view_; - #ifdef HAVE_AUDIOCD - std::unique_ptr rip_cd_; - #endif +#ifdef HAVE_AUDIOCD + std::unique_ptr rip_cd_; +#endif PlaylistListContainer* playlist_list_; InternetViewContainer* internet_view_; DeviceViewContainer* device_view_container_; @@ -363,4 +361,4 @@ class MainWindow : public QMainWindow, public PlatformInterface { BackgroundStreams* background_streams_; }; -#endif // MAINWINDOW_H +#endif // MAINWINDOW_H diff --git a/src/ui/networkproxysettingspage.cpp b/src/ui/networkproxysettingspage.cpp index 623abfd49..19efb05ae 100644 --- a/src/ui/networkproxysettingspage.cpp +++ b/src/ui/networkproxysettingspage.cpp @@ -22,18 +22,13 @@ #include - NetworkProxySettingsPage::NetworkProxySettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_NetworkProxySettingsPage) -{ + : SettingsPage(dialog), ui_(new Ui_NetworkProxySettingsPage) { ui_->setupUi(this); setWindowIcon(IconLoader::Load("applications-internet")); } -NetworkProxySettingsPage::~NetworkProxySettingsPage() { - delete ui_; -} +NetworkProxySettingsPage::~NetworkProxySettingsPage() { delete ui_; } void NetworkProxySettingsPage::Load() { QSettings s; @@ -42,22 +37,25 @@ void NetworkProxySettingsPage::Load() { NetworkProxyFactory::Mode mode = NetworkProxyFactory::Mode( s.value("mode", NetworkProxyFactory::Mode_System).toInt()); switch (mode) { - case NetworkProxyFactory::Mode_Manual: - ui_->proxy_manual->setChecked(true); - break; + case NetworkProxyFactory::Mode_Manual: + ui_->proxy_manual->setChecked(true); + break; - case NetworkProxyFactory::Mode_Direct: - ui_->proxy_direct->setChecked(true); - break; + case NetworkProxyFactory::Mode_Direct: + ui_->proxy_direct->setChecked(true); + break; - case NetworkProxyFactory::Mode_System: - default: - ui_->proxy_system->setChecked(true); - break; + case NetworkProxyFactory::Mode_System: + default: + ui_->proxy_system->setChecked(true); + break; } - ui_->proxy_type->setCurrentIndex(s.value("type", QNetworkProxy::HttpProxy) - .toInt() == QNetworkProxy::HttpProxy ? 0 : 1); + ui_->proxy_type->setCurrentIndex( + s.value("type", QNetworkProxy::HttpProxy).toInt() == + QNetworkProxy::HttpProxy + ? 0 + : 1); ui_->proxy_hostname->setText(s.value("hostname").toString()); ui_->proxy_port->setValue(s.value("port").toInt()); ui_->proxy_auth->setChecked(s.value("use_authentication", false).toBool()); @@ -70,14 +68,18 @@ void NetworkProxySettingsPage::Save() { QSettings s; NetworkProxyFactory::Mode mode = NetworkProxyFactory::Mode_System; - if (ui_->proxy_direct->isChecked()) mode = NetworkProxyFactory::Mode_Direct; - else if (ui_->proxy_system->isChecked()) mode = NetworkProxyFactory::Mode_System; - else if (ui_->proxy_manual->isChecked()) mode = NetworkProxyFactory::Mode_Manual; + if (ui_->proxy_direct->isChecked()) + mode = NetworkProxyFactory::Mode_Direct; + else if (ui_->proxy_system->isChecked()) + mode = NetworkProxyFactory::Mode_System; + else if (ui_->proxy_manual->isChecked()) + mode = NetworkProxyFactory::Mode_Manual; s.beginGroup(NetworkProxyFactory::kSettingsGroup); s.setValue("mode", mode); - s.setValue("type", ui_->proxy_type->currentIndex() == 0 ? - QNetworkProxy::HttpProxy : QNetworkProxy::Socks5Proxy); + s.setValue("type", ui_->proxy_type->currentIndex() == 0 + ? QNetworkProxy::HttpProxy + : QNetworkProxy::Socks5Proxy); s.setValue("hostname", ui_->proxy_hostname->text()); s.setValue("port", ui_->proxy_port->value()); s.setValue("use_authentication", ui_->proxy_auth->isChecked()); diff --git a/src/ui/networkproxysettingspage.h b/src/ui/networkproxysettingspage.h index 317653913..9cde92ae9 100644 --- a/src/ui/networkproxysettingspage.h +++ b/src/ui/networkproxysettingspage.h @@ -25,15 +25,15 @@ class Ui_NetworkProxySettingsPage; class NetworkProxySettingsPage : public SettingsPage { Q_OBJECT -public: + public: NetworkProxySettingsPage(SettingsDialog* dialog); ~NetworkProxySettingsPage(); void Load(); void Save(); -private: + private: Ui_NetworkProxySettingsPage* ui_; }; -#endif // NETWORKPROXYSETTINGSPAGE_H +#endif // NETWORKPROXYSETTINGSPAGE_H diff --git a/src/ui/networkremotesettingspage.cpp b/src/ui/networkremotesettingspage.cpp index 09221becf..57debe8e4 100644 --- a/src/ui/networkremotesettingspage.cpp +++ b/src/ui/networkremotesettingspage.cpp @@ -30,18 +30,14 @@ const char* NetworkRemoteSettingsPage::kPlayStoreUrl = "https://play.google.com/store/apps/details?id=de.qspool.clementineremote"; NetworkRemoteSettingsPage::NetworkRemoteSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_NetworkRemoteSettingsPage) -{ + : SettingsPage(dialog), ui_(new Ui_NetworkRemoteSettingsPage) { ui_->setupUi(this); setWindowIcon(IconLoader::Load("ipodtouchicon")); ui_->play_store->installEventFilter(this); } -NetworkRemoteSettingsPage::~NetworkRemoteSettingsPage() { - delete ui_; -} +NetworkRemoteSettingsPage::~NetworkRemoteSettingsPage() { delete ui_; } bool NetworkRemoteSettingsPage::eventFilter(QObject* object, QEvent* event) { if (object == ui_->play_store && @@ -75,7 +71,7 @@ void NetworkRemoteSettingsPage::Load() { // Get local ip addresses QString ip_addresses; QList addresses = QNetworkInterface::allAddresses(); - foreach (const QHostAddress& address, addresses) { + foreach(const QHostAddress & address, addresses) { // TODO: Add ipv6 support to tinysvcmdns. if (address.protocol() == QAbstractSocket::IPv4Protocol && !address.isInSubnet(QHostAddress::parseSubnet("127.0.0.1/8"))) { diff --git a/src/ui/networkremotesettingspage.h b/src/ui/networkremotesettingspage.h index 265440773..3a8a06d8d 100644 --- a/src/ui/networkremotesettingspage.h +++ b/src/ui/networkremotesettingspage.h @@ -25,20 +25,20 @@ class Ui_NetworkRemoteSettingsPage; class NetworkRemoteSettingsPage : public SettingsPage { Q_OBJECT -public: + public: NetworkRemoteSettingsPage(SettingsDialog* dialog); ~NetworkRemoteSettingsPage(); void Load(); void Save(); -protected: + protected: bool eventFilter(QObject* object, QEvent* event); -private: + private: static const char* kPlayStoreUrl; Ui_NetworkRemoteSettingsPage* ui_; }; -#endif // NETWORKREMOTESETTINGSPAGE_H +#endif // NETWORKREMOTESETTINGSPAGE_H diff --git a/src/ui/notificationssettingspage.cpp b/src/ui/notificationssettingspage.cpp index ef05f15ac..11b1e4c55 100644 --- a/src/ui/notificationssettingspage.cpp +++ b/src/ui/notificationssettingspage.cpp @@ -27,18 +27,19 @@ #include NotificationsSettingsPage::NotificationsSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_NotificationsSettingsPage), - pretty_popup_(new OSDPretty(OSDPretty::Mode_Draggable)) -{ + : SettingsPage(dialog), + ui_(new Ui_NotificationsSettingsPage), + pretty_popup_(new OSDPretty(OSDPretty::Mode_Draggable)) { ui_->setupUi(this); setWindowIcon(IconLoader::Load("help-hint")); pretty_popup_->SetMessage(tr("OSD Preview"), tr("Drag to reposition"), QImage(":nocover.png")); - ui_->notifications_bg_preset->setItemData(0, QColor(OSDPretty::kPresetBlue), Qt::DecorationRole); - ui_->notifications_bg_preset->setItemData(1, QColor(OSDPretty::kPresetOrange), Qt::DecorationRole); + ui_->notifications_bg_preset->setItemData(0, QColor(OSDPretty::kPresetBlue), + Qt::DecorationRole); + ui_->notifications_bg_preset->setItemData(1, QColor(OSDPretty::kPresetOrange), + Qt::DecorationRole); // Create and populate the helper menus QMenu* menu = new QMenu(this); @@ -68,27 +69,40 @@ NotificationsSettingsPage::NotificationsSettingsPage(SettingsDialog* dialog) // We need this because by default menus don't show tooltips connect(menu, SIGNAL(hovered(QAction*)), SLOT(ShowMenuTooltip(QAction*))); - connect(ui_->notifications_none, SIGNAL(toggled(bool)), SLOT(NotificationTypeChanged())); - connect(ui_->notifications_native, SIGNAL(toggled(bool)), SLOT(NotificationTypeChanged())); - connect(ui_->notifications_tray, SIGNAL(toggled(bool)), SLOT(NotificationTypeChanged())); - connect(ui_->notifications_pretty, SIGNAL(toggled(bool)), SLOT(NotificationTypeChanged())); - connect(ui_->notifications_opacity, SIGNAL(valueChanged(int)), SLOT(PrettyOpacityChanged(int))); - connect(ui_->notifications_bg_preset, SIGNAL(activated(int)), SLOT(PrettyColorPresetChanged(int))); - connect(ui_->notifications_fg_choose, SIGNAL(clicked()), SLOT(ChooseFgColor())); - connect(ui_->notifications_font_choose, SIGNAL(clicked()), SLOT(ChooseFont())); - connect(ui_->notifications_exp_chooser1, SIGNAL(triggered(QAction*)), SLOT(InsertVariableFirstLine(QAction*))); - connect(ui_->notifications_exp_chooser2, SIGNAL(triggered(QAction*)), SLOT(InsertVariableSecondLine(QAction*))); - connect(ui_->notifications_disable_duration, SIGNAL(toggled(bool)), ui_->notifications_duration, SLOT(setDisabled(bool))); + connect(ui_->notifications_none, SIGNAL(toggled(bool)), + SLOT(NotificationTypeChanged())); + connect(ui_->notifications_native, SIGNAL(toggled(bool)), + SLOT(NotificationTypeChanged())); + connect(ui_->notifications_tray, SIGNAL(toggled(bool)), + SLOT(NotificationTypeChanged())); + connect(ui_->notifications_pretty, SIGNAL(toggled(bool)), + SLOT(NotificationTypeChanged())); + connect(ui_->notifications_opacity, SIGNAL(valueChanged(int)), + SLOT(PrettyOpacityChanged(int))); + connect(ui_->notifications_bg_preset, SIGNAL(activated(int)), + SLOT(PrettyColorPresetChanged(int))); + connect(ui_->notifications_fg_choose, SIGNAL(clicked()), + SLOT(ChooseFgColor())); + connect(ui_->notifications_font_choose, SIGNAL(clicked()), + SLOT(ChooseFont())); + connect(ui_->notifications_exp_chooser1, SIGNAL(triggered(QAction*)), + SLOT(InsertVariableFirstLine(QAction*))); + connect(ui_->notifications_exp_chooser2, SIGNAL(triggered(QAction*)), + SLOT(InsertVariableSecondLine(QAction*))); + connect(ui_->notifications_disable_duration, SIGNAL(toggled(bool)), + ui_->notifications_duration, SLOT(setDisabled(bool))); if (!OSD::SupportsNativeNotifications()) ui_->notifications_native->setEnabled(false); - if (!OSD::SupportsTrayPopups()) - ui_->notifications_tray->setEnabled(false); + if (!OSD::SupportsTrayPopups()) ui_->notifications_tray->setEnabled(false); - connect(ui_->notifications_pretty, SIGNAL(toggled(bool)), SLOT(UpdatePopupVisible())); + connect(ui_->notifications_pretty, SIGNAL(toggled(bool)), + SLOT(UpdatePopupVisible())); - connect(ui_->notifications_custom_text_enabled, SIGNAL(toggled(bool)), SLOT(NotificationCustomTextChanged(bool))); - connect(ui_->notifications_preview, SIGNAL(clicked()), SLOT(PrepareNotificationPreview())); + connect(ui_->notifications_custom_text_enabled, SIGNAL(toggled(bool)), + SLOT(NotificationCustomTextChanged(bool))); + connect(ui_->notifications_preview, SIGNAL(clicked()), + SLOT(PrepareNotificationPreview())); // Icons ui_->notifications_exp_chooser1->setIcon(IconLoader::Load("list-add")); @@ -100,26 +114,23 @@ NotificationsSettingsPage::~NotificationsSettingsPage() { delete ui_; } -void NotificationsSettingsPage::showEvent(QShowEvent*) { - UpdatePopupVisible(); -} +void NotificationsSettingsPage::showEvent(QShowEvent*) { UpdatePopupVisible(); } -void NotificationsSettingsPage::hideEvent(QHideEvent*) { - UpdatePopupVisible(); -} +void NotificationsSettingsPage::hideEvent(QHideEvent*) { UpdatePopupVisible(); } void NotificationsSettingsPage::Load() { QSettings s; s.beginGroup(OSD::kSettingsGroup); - OSD::Behaviour osd_behaviour = OSD::Behaviour(s.value("Behaviour", OSD::Native).toInt()); + OSD::Behaviour osd_behaviour = + OSD::Behaviour(s.value("Behaviour", OSD::Native).toInt()); switch (osd_behaviour) { case OSD::Native: if (OSD::SupportsNativeNotifications()) { ui_->notifications_native->setChecked(true); break; } - // Fallthrough + // Fallthrough case OSD::Pretty: ui_->notifications_pretty->setChecked(true); @@ -130,29 +141,35 @@ void NotificationsSettingsPage::Load() { ui_->notifications_tray->setChecked(true); break; } - // Fallthrough + // Fallthrough case OSD::Disabled: default: ui_->notifications_none->setChecked(true); break; } - ui_->notifications_duration->setValue(s.value("Timeout", 5000).toInt() / 1000); - ui_->notifications_volume->setChecked(s.value("ShowOnVolumeChange", false).toBool()); - ui_->notifications_play_mode->setChecked(s.value("ShowOnPlayModeChange", true).toBool()); + ui_->notifications_duration->setValue(s.value("Timeout", 5000).toInt() / + 1000); + ui_->notifications_volume->setChecked( + s.value("ShowOnVolumeChange", false).toBool()); + ui_->notifications_play_mode->setChecked( + s.value("ShowOnPlayModeChange", true).toBool()); ui_->notifications_art->setChecked(s.value("ShowArt", true).toBool()); - ui_->notifications_custom_text_enabled->setChecked(s.value("CustomTextEnabled", false).toBool()); + ui_->notifications_custom_text_enabled->setChecked( + s.value("CustomTextEnabled", false).toBool()); ui_->notifications_custom_text1->setText(s.value("CustomText1").toString()); ui_->notifications_custom_text2->setText(s.value("CustomText2").toString()); s.endGroup(); #ifdef Q_OS_DARWIN - ui_->notifications_options->setEnabled(ui_->notifications_pretty->isChecked()); + ui_->notifications_options->setEnabled( + ui_->notifications_pretty->isChecked()); #endif // Pretty OSD pretty_popup_->ReloadSettings(); - ui_->notifications_opacity->setValue(pretty_popup_->background_opacity() * 100); + ui_->notifications_opacity->setValue(pretty_popup_->background_opacity() * + 100); QRgb color = pretty_popup_->background_color(); if (color == OSDPretty::kPresetBlue) @@ -161,8 +178,10 @@ void NotificationsSettingsPage::Load() { ui_->notifications_bg_preset->setCurrentIndex(1); else ui_->notifications_bg_preset->setCurrentIndex(2); - ui_->notifications_bg_preset->setItemData(2, QColor(color), Qt::DecorationRole); - ui_->notifications_disable_duration->setChecked(pretty_popup_->disable_duration()); + ui_->notifications_bg_preset->setItemData(2, QColor(color), + Qt::DecorationRole); + ui_->notifications_disable_duration->setChecked( + pretty_popup_->disable_duration()); UpdatePopupVisible(); } @@ -170,10 +189,14 @@ void NotificationsSettingsPage::Save() { QSettings s; OSD::Behaviour osd_behaviour = OSD::Disabled; - if (ui_->notifications_none->isChecked()) osd_behaviour = OSD::Disabled; - else if (ui_->notifications_native->isChecked()) osd_behaviour = OSD::Native; - else if (ui_->notifications_tray->isChecked()) osd_behaviour = OSD::TrayPopup; - else if (ui_->notifications_pretty->isChecked()) osd_behaviour = OSD::Pretty; + if (ui_->notifications_none->isChecked()) + osd_behaviour = OSD::Disabled; + else if (ui_->notifications_native->isChecked()) + osd_behaviour = OSD::Native; + else if (ui_->notifications_tray->isChecked()) + osd_behaviour = OSD::TrayPopup; + else if (ui_->notifications_pretty->isChecked()) + osd_behaviour = OSD::Pretty; s.beginGroup(OSD::kSettingsGroup); s.setValue("Behaviour", int(osd_behaviour)); @@ -181,7 +204,8 @@ void NotificationsSettingsPage::Save() { s.setValue("ShowOnVolumeChange", ui_->notifications_volume->isChecked()); s.setValue("ShowOnPlayModeChange", ui_->notifications_play_mode->isChecked()); s.setValue("ShowArt", ui_->notifications_art->isChecked()); - s.setValue("CustomTextEnabled", ui_->notifications_custom_text_enabled->isChecked()); + s.setValue("CustomTextEnabled", + ui_->notifications_custom_text_enabled->isChecked()); s.setValue("CustomText1", ui_->notifications_custom_text1->text()); s.setValue("CustomText2", ui_->notifications_custom_text2->text()); s.endGroup(); @@ -193,7 +217,8 @@ void NotificationsSettingsPage::Save() { s.setValue("popup_display", pretty_popup_->popup_display()); s.setValue("popup_pos", pretty_popup_->popup_pos()); s.setValue("font", pretty_popup_->font().toString()); - s.setValue("disable_duration", ui_->notifications_disable_duration->isChecked()); + s.setValue("disable_duration", + ui_->notifications_disable_duration->isChecked()); s.endGroup(); } @@ -202,44 +227,42 @@ void NotificationsSettingsPage::PrettyOpacityChanged(int value) { } void NotificationsSettingsPage::UpdatePopupVisible() { - pretty_popup_->setVisible( - isVisible() && - ui_->notifications_pretty->isChecked()); + pretty_popup_->setVisible(isVisible() && + ui_->notifications_pretty->isChecked()); } void NotificationsSettingsPage::PrettyColorPresetChanged(int index) { - if (dialog()->is_loading_settings()) - return; + if (dialog()->is_loading_settings()) return; switch (index) { - case 0: - pretty_popup_->set_background_color(OSDPretty::kPresetBlue); - break; + case 0: + pretty_popup_->set_background_color(OSDPretty::kPresetBlue); + break; - case 1: - pretty_popup_->set_background_color(OSDPretty::kPresetOrange); - break; + case 1: + pretty_popup_->set_background_color(OSDPretty::kPresetOrange); + break; - case 2: - default: - ChooseBgColor(); - break; + case 2: + default: + ChooseBgColor(); + break; } } void NotificationsSettingsPage::ChooseBgColor() { - QColor color = QColorDialog::getColor(pretty_popup_->background_color(), this); - if (!color.isValid()) - return; + QColor color = + QColorDialog::getColor(pretty_popup_->background_color(), this); + if (!color.isValid()) return; pretty_popup_->set_background_color(color.rgb()); ui_->notifications_bg_preset->setItemData(2, color, Qt::DecorationRole); } void NotificationsSettingsPage::ChooseFgColor() { - QColor color = QColorDialog::getColor(pretty_popup_->foreground_color(), this); - if (!color.isValid()) - return; + QColor color = + QColorDialog::getColor(pretty_popup_->foreground_color(), this); + if (!color.isValid()) return; pretty_popup_->set_foreground_color(color.rgb()); } @@ -247,8 +270,7 @@ void NotificationsSettingsPage::ChooseFgColor() { void NotificationsSettingsPage::ChooseFont() { bool ok; QFont font = QFontDialog::getFont(&ok, pretty_popup_->font(), this); - if (ok) - pretty_popup_->set_font(font); + if (ok) pretty_popup_->set_font(font); } void NotificationsSettingsPage::NotificationCustomTextChanged(bool enabled) { @@ -271,8 +293,11 @@ void NotificationsSettingsPage::PrepareNotificationPreview() { notificationType = OSD::TrayPopup; } - // If user changes timeout or other options, that won't be reflected in the preview - emit NotificationPreview(notificationType, ui_->notifications_custom_text1->text(), ui_->notifications_custom_text2->text()); + // If user changes timeout or other options, that won't be reflected in the + // preview + emit NotificationPreview(notificationType, + ui_->notifications_custom_text1->text(), + ui_->notifications_custom_text2->text()); } void NotificationsSettingsPage::InsertVariableFirstLine(QAction* action) { @@ -300,6 +325,7 @@ void NotificationsSettingsPage::NotificationTypeChanged() { #ifdef Q_OS_DARWIN ui_->notifications_options->setEnabled(pretty); #endif - ui_->notifications_duration->setEnabled(!pretty || (pretty && !ui_->notifications_disable_duration->isChecked())); + ui_->notifications_duration->setEnabled( + !pretty || (pretty && !ui_->notifications_disable_duration->isChecked())); ui_->notifications_disable_duration->setEnabled(pretty); } diff --git a/src/ui/notificationssettingspage.h b/src/ui/notificationssettingspage.h index 9f32b48cd..a088cf8e1 100644 --- a/src/ui/notificationssettingspage.h +++ b/src/ui/notificationssettingspage.h @@ -25,18 +25,18 @@ class Ui_NotificationsSettingsPage; class NotificationsSettingsPage : public SettingsPage { Q_OBJECT -public: + public: NotificationsSettingsPage(SettingsDialog* dialog); ~NotificationsSettingsPage(); void Load(); void Save(); -protected: + protected: void hideEvent(QHideEvent*); void showEvent(QShowEvent*); -private slots: + private slots: void NotificationTypeChanged(); void NotificationCustomTextChanged(bool enabled); void PrepareNotificationPreview(); @@ -52,9 +52,9 @@ private slots: void UpdatePopupVisible(); -private: + private: Ui_NotificationsSettingsPage* ui_; OSDPretty* pretty_popup_; }; -#endif // NOTIFICATIONSSETTINGSPAGE_H +#endif // NOTIFICATIONSSETTINGSPAGE_H diff --git a/src/ui/organisedialog.cpp b/src/ui/organisedialog.cpp index 51749fa74..2c241f4b8 100644 --- a/src/ui/organisedialog.cpp +++ b/src/ui/organisedialog.cpp @@ -41,15 +41,15 @@ const char* OrganiseDialog::kDefaultFormat = "%artist/%album{ (Disc %disc)}/{%track - }%title.%extension"; const char* OrganiseDialog::kSettingsGroup = "OrganiseDialog"; -OrganiseDialog::OrganiseDialog(TaskManager* task_manager, QWidget *parent) - : QDialog(parent), - ui_(new Ui_OrganiseDialog), - task_manager_(task_manager), - total_size_(0), - resized_by_user_(false) -{ +OrganiseDialog::OrganiseDialog(TaskManager* task_manager, QWidget* parent) + : QDialog(parent), + ui_(new Ui_OrganiseDialog), + task_manager_(task_manager), + total_size_(0), + resized_by_user_(false) { ui_->setupUi(this); - connect(ui_->buttonBox->button(QDialogButtonBox::Reset), SIGNAL(clicked()), SLOT(Reset())); + connect(ui_->buttonBox->button(QDialogButtonBox::Reset), SIGNAL(clicked()), + SLOT(Reset())); ui_->aftercopying->setItemIcon(1, IconLoader::Load("edit-delete")); @@ -77,7 +77,8 @@ OrganiseDialog::OrganiseDialog(TaskManager* task_manager, QWidget *parent) // Naming scheme input field new OrganiseFormat::SyntaxHighlighter(ui_->naming); - connect(ui_->destination, SIGNAL(currentIndexChanged(int)), SLOT(UpdatePreviews())); + connect(ui_->destination, SIGNAL(currentIndexChanged(int)), + SLOT(UpdatePreviews())); connect(ui_->naming, SIGNAL(textChanged()), SLOT(UpdatePreviews())); connect(ui_->replace_ascii, SIGNAL(toggled(bool)), SLOT(UpdatePreviews())); connect(ui_->replace_the, SIGNAL(toggled(bool)), SLOT(UpdatePreviews())); @@ -99,11 +100,10 @@ OrganiseDialog::OrganiseDialog(TaskManager* task_manager, QWidget *parent) ui_->insert->setMenu(tag_menu); } -OrganiseDialog::~OrganiseDialog() { - delete ui_; -} +OrganiseDialog::~OrganiseDialog() { delete ui_; } -void OrganiseDialog::SetDestinationModel(QAbstractItemModel *model, bool devices) { +void OrganiseDialog::SetDestinationModel(QAbstractItemModel* model, + bool devices) { ui_->destination->setModel(model); ui_->eject_after->setVisible(devices); @@ -118,8 +118,7 @@ int OrganiseDialog::SetSongs(const SongList& songs) { continue; } - if (song.filesize() > 0) - total_size_ += song.filesize(); + if (song.filesize() > 0) total_size_ += song.filesize(); songs_ << song; } @@ -130,31 +129,29 @@ int OrganiseDialog::SetSongs(const SongList& songs) { return songs_.count(); } -int OrganiseDialog::SetUrls(const QList &urls, quint64 total_size) { +int OrganiseDialog::SetUrls(const QList& urls, quint64 total_size) { SongList songs; Song song; // Only add file:// URLs for (const QUrl& url : urls) { - if (url.scheme() != "file") - continue; + if (url.scheme() != "file") continue; TagReaderClient::Instance()->ReadFileBlocking(url.toLocalFile(), &song); - if (song.is_valid()) - songs << song; + if (song.is_valid()) songs << song; } return SetSongs(songs); } -int OrganiseDialog::SetFilenames(const QStringList& filenames, quint64 total_size) { +int OrganiseDialog::SetFilenames(const QStringList& filenames, + quint64 total_size) { SongList songs; Song song; // Load some of the songs to show in the preview for (const QString& filename : filenames) { TagReaderClient::Instance()->ReadFileBlocking(filename, &song); - if (song.is_valid()) - songs << song; + if (song.is_valid()) songs << song; } return SetSongs(songs); } @@ -163,7 +160,7 @@ void OrganiseDialog::SetCopy(bool copy) { ui_->aftercopying->setCurrentIndex(copy ? 0 : 1); } -void OrganiseDialog::InsertTag(const QString &tag) { +void OrganiseDialog::InsertTag(const QString& tag) { ui_->naming->insertPlainText("%" + tag); } @@ -180,9 +177,9 @@ Organise::NewSongInfoList OrganiseDialog::ComputeNewSongsFilenames( QString new_filename = format.GetFilenameForSong(song); if (filenames.contains(new_filename)) { QString song_number = QString::number(++filenames[new_filename]); - new_filename = - Utilities::PathWithoutFilenameExtension(new_filename) + - "(" + song_number + ")." + QFileInfo(new_filename).suffix(); + new_filename = Utilities::PathWithoutFilenameExtension(new_filename) + + "(" + song_number + ")." + + QFileInfo(new_filename).suffix(); } filenames.insert(new_filename, 1); new_songs_info << Organise::NewSongInfo(song, new_filename); @@ -191,14 +188,14 @@ Organise::NewSongInfoList OrganiseDialog::ComputeNewSongsFilenames( } void OrganiseDialog::UpdatePreviews() { - const QModelIndex destination = ui_->destination->model()->index( - ui_->destination->currentIndex(), 0); + const QModelIndex destination = + ui_->destination->model()->index(ui_->destination->currentIndex(), 0); std::shared_ptr storage; bool has_local_destination = false; if (destination.isValid()) { storage = destination.data(MusicStorage::Role_Storage) - .value>(); + .value>(); if (storage) { has_local_destination = !storage->LocalPath().isEmpty(); } @@ -226,12 +223,10 @@ void OrganiseDialog::UpdatePreviews() { // Are we gonna enable the ok button? bool ok = format_valid && !songs_.isEmpty(); - if (capacity != 0 && total_size_ > free) - ok = false; + if (capacity != 0 && total_size_ > free) ok = false; ui_->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok); - if (!format_valid) - return; + if (!format_valid) return; new_songs_info_ = ComputeNewSongsFilenames(songs_, format_); @@ -241,8 +236,7 @@ void OrganiseDialog::UpdatePreviews() { ui_->naming_group->setVisible(has_local_destination); if (has_local_destination) { for (const Organise::NewSongInfo& song_info : new_songs_info_) { - QString filename = storage->LocalPath() + "/" + - song_info.new_filename_; + QString filename = storage->LocalPath() + "/" + song_info.new_filename_; ui_->preview->addItem(QDir::toNativeSeparators(filename)); } } @@ -252,9 +246,7 @@ void OrganiseDialog::UpdatePreviews() { } } -QSize OrganiseDialog::sizeHint() const { - return QSize(650, 0); -} +QSize OrganiseDialog::sizeHint() const { return QSize(650, 0); } void OrganiseDialog::Reset() { ui_->naming->setPlainText(kDefaultFormat); @@ -295,29 +287,28 @@ void OrganiseDialog::accept() { s.setValue("destination", ui_->destination->currentText()); s.setValue("eject_after", ui_->eject_after->isChecked()); - const QModelIndex destination = ui_->destination->model()->index( - ui_->destination->currentIndex(), 0); + const QModelIndex destination = + ui_->destination->model()->index(ui_->destination->currentIndex(), 0); std::shared_ptr storage = destination.data(MusicStorage::Role_StorageForceConnect) - .value>(); + .value>(); - if (!storage) - return; + if (!storage) return; // It deletes itself when it's finished. const bool copy = ui_->aftercopying->currentIndex() == 0; Organise* organise = new Organise( task_manager_, storage, format_, copy, ui_->overwrite->isChecked(), new_songs_info_, ui_->eject_after->isChecked()); - connect(organise, SIGNAL(Finished(QStringList)), SLOT(OrganiseFinished(QStringList))); + connect(organise, SIGNAL(Finished(QStringList)), + SLOT(OrganiseFinished(QStringList))); organise->Start(); QDialog::accept(); } void OrganiseDialog::OrganiseFinished(const QStringList& files_with_errors) { - if (files_with_errors.isEmpty()) - return; + if (files_with_errors.isEmpty()) return; error_dialog_.reset(new OrganiseErrorDialog); error_dialog_->Show(OrganiseErrorDialog::Type_Copy, files_with_errors); diff --git a/src/ui/organisedialog.h b/src/ui/organisedialog.h index 4466e0307..9eb764ded 100644 --- a/src/ui/organisedialog.h +++ b/src/ui/organisedialog.h @@ -40,7 +40,7 @@ class QAbstractItemModel; class OrganiseDialog : public QDialog { Q_OBJECT -public: + public: OrganiseDialog(TaskManager* task_manager, QWidget* parent = 0); ~OrganiseDialog(); @@ -56,14 +56,14 @@ public: int SetFilenames(const QStringList& filenames, quint64 total_size = 0); void SetCopy(bool copy); -public slots: + public slots: void accept(); -protected: + protected: void showEvent(QShowEvent*); void resizeEvent(QResizeEvent*); -private slots: + private slots: void Reset(); void InsertTag(const QString& tag); @@ -71,10 +71,9 @@ private slots: void OrganiseFinished(const QStringList& files_with_errors); -private: + private: static Organise::NewSongInfoList ComputeNewSongsFilenames( - const SongList& songs, - const OrganiseFormat& format); + const SongList& songs, const OrganiseFormat& format); Ui_OrganiseDialog* ui_; TaskManager* task_manager_; @@ -92,4 +91,4 @@ private: FRIEND_TEST(OrganiseDialogTest, ComputeNewSongsFilenamesTest); }; -#endif // ORGANISEDIALOG_H +#endif // ORGANISEDIALOG_H diff --git a/src/ui/organiseerrordialog.cpp b/src/ui/organiseerrordialog.cpp index 4d914d43c..24fec04cf 100644 --- a/src/ui/organiseerrordialog.cpp +++ b/src/ui/organiseerrordialog.cpp @@ -20,46 +20,47 @@ #include -OrganiseErrorDialog::OrganiseErrorDialog(QWidget *parent) - : QDialog(parent), - ui_(new Ui_OrganiseErrorDialog) -{ +OrganiseErrorDialog::OrganiseErrorDialog(QWidget* parent) + : QDialog(parent), ui_(new Ui_OrganiseErrorDialog) { ui_->setupUi(this); - const int icon_size = style()->pixelMetric(QStyle::PM_MessageBoxIconSize, 0, this); + const int icon_size = + style()->pixelMetric(QStyle::PM_MessageBoxIconSize, 0, this); QIcon icon = style()->standardIcon(QStyle::SP_MessageBoxCritical, 0, this); ui_->icon->setPixmap(icon.pixmap(icon_size)); } -OrganiseErrorDialog::~OrganiseErrorDialog() { - delete ui_; -} +OrganiseErrorDialog::~OrganiseErrorDialog() { delete ui_; } -void OrganiseErrorDialog::Show( - OperationType type, const SongList& songs_with_errors) { +void OrganiseErrorDialog::Show(OperationType type, + const SongList& songs_with_errors) { QStringList files; - foreach (const Song& song, songs_with_errors) { + foreach(const Song & song, songs_with_errors) { files << song.url().toLocalFile(); } Show(type, files); } -void OrganiseErrorDialog::Show( - OperationType type, const QStringList& files_with_errors) { +void OrganiseErrorDialog::Show(OperationType type, + const QStringList& files_with_errors) { QStringList sorted_files = files_with_errors; qStableSort(sorted_files); switch (type) { - case Type_Copy: - setWindowTitle(tr("Error copying songs")); - ui_->label->setText(tr("There were problems copying some songs. The following files could not be copied:")); - break; + case Type_Copy: + setWindowTitle(tr("Error copying songs")); + ui_->label->setText( + tr("There were problems copying some songs. The following files " + "could not be copied:")); + break; - case Type_Delete: - setWindowTitle(tr("Error deleting songs")); - ui_->label->setText(tr("There were problems deleting some songs. The following files could not be deleted:")); - break; + case Type_Delete: + setWindowTitle(tr("Error deleting songs")); + ui_->label->setText( + tr("There were problems deleting some songs. The following files " + "could not be deleted:")); + break; } ui_->list->addItems(sorted_files); diff --git a/src/ui/organiseerrordialog.h b/src/ui/organiseerrordialog.h index 8cc16aec6..117a47e62 100644 --- a/src/ui/organiseerrordialog.h +++ b/src/ui/organiseerrordialog.h @@ -27,20 +27,17 @@ class Ui_OrganiseErrorDialog; class OrganiseErrorDialog : public QDialog { Q_OBJECT -public: + public: OrganiseErrorDialog(QWidget* parent = 0); ~OrganiseErrorDialog(); - enum OperationType { - Type_Copy, - Type_Delete, - }; + enum OperationType { Type_Copy, Type_Delete, }; void Show(OperationType type, const SongList& songs_with_errors); void Show(OperationType type, const QStringList& files_with_errors); -private: + private: Ui_OrganiseErrorDialog* ui_; }; -#endif // ORGANISEERRORDIALOG_H +#endif // ORGANISEERRORDIALOG_H diff --git a/src/ui/playbacksettingspage.cpp b/src/ui/playbacksettingspage.cpp index abe5b6846..f601beb2e 100644 --- a/src/ui/playbacksettingspage.cpp +++ b/src/ui/playbacksettingspage.cpp @@ -22,28 +22,27 @@ #include "engines/gstengine.h" #include "playlist/playlist.h" - PlaybackSettingsPage::PlaybackSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_PlaybackSettingsPage) -{ + : SettingsPage(dialog), ui_(new Ui_PlaybackSettingsPage) { ui_->setupUi(this); setWindowIcon(IconLoader::Load("media-playback-start")); - connect(ui_->fading_cross, SIGNAL(toggled(bool)), SLOT(FadingOptionsChanged())); + connect(ui_->fading_cross, SIGNAL(toggled(bool)), + SLOT(FadingOptionsChanged())); connect(ui_->fading_out, SIGNAL(toggled(bool)), SLOT(FadingOptionsChanged())); - connect(ui_->fading_auto, SIGNAL(toggled(bool)), SLOT(FadingOptionsChanged())); - connect(ui_->gst_plugin, SIGNAL(currentIndexChanged(int)), SLOT(GstPluginChanged(int))); + connect(ui_->fading_auto, SIGNAL(toggled(bool)), + SLOT(FadingOptionsChanged())); + connect(ui_->gst_plugin, SIGNAL(currentIndexChanged(int)), + SLOT(GstPluginChanged(int))); - connect(ui_->replaygain_preamp, SIGNAL(valueChanged(int)), SLOT(RgPreampChanged(int))); + connect(ui_->replaygain_preamp, SIGNAL(valueChanged(int)), + SLOT(RgPreampChanged(int))); ui_->replaygain_preamp_label->setMinimumWidth( QFontMetrics(ui_->replaygain_preamp_label->font()).width("-WW.W dB")); RgPreampChanged(ui_->replaygain_preamp->value()); } -PlaybackSettingsPage::~PlaybackSettingsPage() { - delete ui_; -} +PlaybackSettingsPage::~PlaybackSettingsPage() { delete ui_; } void PlaybackSettingsPage::Load() { const GstEngine* engine = dialog()->gst_engine(); @@ -52,9 +51,8 @@ void PlaybackSettingsPage::Load() { GstEngine::PluginDetailsList list = engine->GetOutputsList(); ui_->gst_plugin->setItemData(0, GstEngine::kAutoSink); - foreach (const GstEngine::PluginDetails& details, list) { - if (details.name == "autoaudiosink") - continue; + foreach(const GstEngine::PluginDetails & details, list) { + if (details.name == "autoaudiosink") continue; ui_->gst_plugin->addItem(details.long_name, details.name); } @@ -73,15 +71,18 @@ void PlaybackSettingsPage::Load() { ui_->fading_cross->setChecked(s.value("CrossfadeEnabled", true).toBool()); ui_->fading_auto->setChecked(s.value("AutoCrossfadeEnabled", false).toBool()); ui_->fading_duration->setValue(s.value("FadeoutDuration", 2000).toInt()); - ui_->fading_samealbum->setChecked(s.value("NoCrossfadeSameAlbum", true).toBool()); - ui_->fadeout_pause->setChecked(s.value("FadeoutPauseEnabled", false).toBool()); - ui_->fading_pause_duration->setValue(s.value("FadeoutPauseDuration", 250).toInt()); + ui_->fading_samealbum->setChecked( + s.value("NoCrossfadeSameAlbum", true).toBool()); + ui_->fadeout_pause->setChecked( + s.value("FadeoutPauseEnabled", false).toBool()); + ui_->fading_pause_duration->setValue( + s.value("FadeoutPauseDuration", 250).toInt()); s.endGroup(); s.beginGroup(GstEngine::kSettingsGroup); QString sink = s.value("sink", GstEngine::kAutoSink).toString(); ui_->gst_plugin->setCurrentIndex(0); - for (int i=0 ; igst_plugin->count() ; ++i) { + for (int i = 0; i < ui_->gst_plugin->count(); ++i) { if (ui_->gst_plugin->itemData(i).toString() == sink) { ui_->gst_plugin->setCurrentIndex(i); break; @@ -90,8 +91,10 @@ void PlaybackSettingsPage::Load() { ui_->gst_device->setText(s.value("device").toString()); ui_->replaygain->setChecked(s.value("rgenabled", false).toBool()); ui_->replaygain_mode->setCurrentIndex(s.value("rgmode", 0).toInt()); - ui_->replaygain_preamp->setValue(s.value("rgpreamp", 0.0).toDouble() * 10 + 150); - ui_->replaygain_compression->setChecked(s.value("rgcompression", true).toBool()); + ui_->replaygain_preamp->setValue(s.value("rgpreamp", 0.0).toDouble() * 10 + + 150); + ui_->replaygain_compression->setChecked( + s.value("rgcompression", true).toBool()); ui_->buffer_duration->setValue(s.value("bufferduration", 4000).toInt()); ui_->mono_playback->setChecked(s.value("monoplayback", false).toBool()); s.endGroup(); @@ -115,7 +118,8 @@ void PlaybackSettingsPage::Save() { s.endGroup(); s.beginGroup(GstEngine::kSettingsGroup); - s.setValue("sink", ui_->gst_plugin->itemData(ui_->gst_plugin->currentIndex()).toString()); + s.setValue("sink", ui_->gst_plugin->itemData(ui_->gst_plugin->currentIndex()) + .toString()); s.setValue("device", ui_->gst_device->text()); s.setValue("rgenabled", ui_->replaygain->isChecked()); s.setValue("rgmode", ui_->replaygain_mode->currentIndex()); @@ -129,7 +133,8 @@ void PlaybackSettingsPage::Save() { void PlaybackSettingsPage::GstPluginChanged(int index) { QString name = ui_->gst_plugin->itemData(index).toString(); - bool enabled = GstEngine::DoesThisSinkSupportChangingTheOutputDeviceToAUserEditableString(name); + bool enabled = GstEngine:: + DoesThisSinkSupportChangingTheOutputDeviceToAUserEditableString(name); ui_->gst_device->setEnabled(enabled); ui_->gst_device_label->setEnabled(enabled); @@ -143,7 +148,7 @@ void PlaybackSettingsPage::RgPreampChanged(int value) { } void PlaybackSettingsPage::FadingOptionsChanged() { - ui_->fading_options->setEnabled( - ui_->fading_out->isChecked() || ui_->fading_cross->isChecked() || - ui_->fading_auto->isChecked()); + ui_->fading_options->setEnabled(ui_->fading_out->isChecked() || + ui_->fading_cross->isChecked() || + ui_->fading_auto->isChecked()); } diff --git a/src/ui/playbacksettingspage.h b/src/ui/playbacksettingspage.h index 2d06538c6..d5799fa6f 100644 --- a/src/ui/playbacksettingspage.h +++ b/src/ui/playbacksettingspage.h @@ -25,20 +25,20 @@ class Ui_PlaybackSettingsPage; class PlaybackSettingsPage : public SettingsPage { Q_OBJECT -public: + public: PlaybackSettingsPage(SettingsDialog* dialog); ~PlaybackSettingsPage(); void Load(); void Save(); -private slots: + private slots: void GstPluginChanged(int index); void FadingOptionsChanged(); void RgPreampChanged(int value); -private: + private: Ui_PlaybackSettingsPage* ui_; }; -#endif // PLAYBACKSETTINGSPAGE_H +#endif // PLAYBACKSETTINGSPAGE_H diff --git a/src/ui/qt_blurimage.h b/src/ui/qt_blurimage.h index 3f1f15b8f..ec0336f77 100644 --- a/src/ui/qt_blurimage.h +++ b/src/ui/qt_blurimage.h @@ -22,4 +22,4 @@ void qt_blurImage(QPainter* p, QImage& blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0); -#endif // QT_BLURIMAGE_H +#endif // QT_BLURIMAGE_H diff --git a/src/ui/qtsystemtrayicon.cpp b/src/ui/qtsystemtrayicon.cpp index 904376be3..0dceb18a1 100644 --- a/src/ui/qtsystemtrayicon.cpp +++ b/src/ui/qtsystemtrayicon.cpp @@ -29,17 +29,16 @@ #include QtSystemTrayIcon::QtSystemTrayIcon(QObject* parent) - : SystemTrayIcon(parent), - tray_(new QSystemTrayIcon(this)), - menu_(new QMenu), - action_play_pause_(nullptr), - action_stop_(nullptr), - action_stop_after_this_track_(nullptr), - action_mute_(nullptr), - action_love_(nullptr), - action_ban_(nullptr) -{ - QIcon theme_icon = IconLoader::Load("clementine-panel"); + : SystemTrayIcon(parent), + tray_(new QSystemTrayIcon(this)), + menu_(new QMenu), + action_play_pause_(nullptr), + action_stop_(nullptr), + action_stop_after_this_track_(nullptr), + action_mute_(nullptr), + action_love_(nullptr), + action_ban_(nullptr) { + QIcon theme_icon = IconLoader::Load("clementine-panel"); QIcon theme_icon_grey = IconLoader::Load("clementine-panel-grey"); if (theme_icon.isNull() || theme_icon_grey.isNull()) { @@ -65,16 +64,12 @@ QtSystemTrayIcon::QtSystemTrayIcon(QObject* parent) SLOT(Clicked(QSystemTrayIcon::ActivationReason))); } -QtSystemTrayIcon::~QtSystemTrayIcon() { - delete menu_; -} +QtSystemTrayIcon::~QtSystemTrayIcon() { delete menu_; } bool QtSystemTrayIcon::eventFilter(QObject* object, QEvent* event) { - if (QObject::eventFilter(object, event)) - return true; + if (QObject::eventFilter(object, event)) return true; - if (object != tray_) - return false; + if (object != tray_) return false; if (event->type() == QEvent::Wheel) { QWheelEvent* e = static_cast(event); @@ -99,29 +94,37 @@ bool QtSystemTrayIcon::eventFilter(QObject* object, QEvent* event) { return false; } -void QtSystemTrayIcon::SetupMenu( - QAction* previous, QAction* play, QAction* stop, QAction* stop_after, - QAction* next, QAction* mute, QAction* love, QAction* ban, QAction* quit) { +void QtSystemTrayIcon::SetupMenu(QAction* previous, QAction* play, + QAction* stop, QAction* stop_after, + QAction* next, QAction* mute, QAction* love, + QAction* ban, QAction* quit) { // Creating new actions and connecting them to old ones. This allows us to // use old actions without displaying shortcuts that can not be used when // Clementine's window is hidden - menu_->addAction(previous->icon(), previous->text(), previous, SLOT(trigger())); - action_play_pause_ = menu_->addAction(play->icon(), play->text(), play, SLOT(trigger())); - action_stop_ = menu_->addAction(stop->icon(), stop->text(), stop, SLOT(trigger())); - action_stop_after_this_track_ = menu_->addAction(stop_after->icon(), stop_after->text(), stop_after, SLOT(trigger())); + menu_->addAction(previous->icon(), previous->text(), previous, + SLOT(trigger())); + action_play_pause_ = + menu_->addAction(play->icon(), play->text(), play, SLOT(trigger())); + action_stop_ = + menu_->addAction(stop->icon(), stop->text(), stop, SLOT(trigger())); + action_stop_after_this_track_ = menu_->addAction( + stop_after->icon(), stop_after->text(), stop_after, SLOT(trigger())); menu_->addAction(next->icon(), next->text(), next, SLOT(trigger())); menu_->addSeparator(); - action_mute_ = menu_->addAction(mute->icon(), mute->text(), mute, SLOT(trigger())); + action_mute_ = + menu_->addAction(mute->icon(), mute->text(), mute, SLOT(trigger())); action_mute_->setCheckable(true); action_mute_->setChecked(mute->isChecked()); menu_->addSeparator(); #ifdef HAVE_LIBLASTFM - action_love_ = menu_->addAction(love->icon(), love->text(), love, SLOT(trigger())); + action_love_ = + menu_->addAction(love->icon(), love->text(), love, SLOT(trigger())); action_love_->setVisible(love->isVisible()); action_love_->setEnabled(love->isEnabled()); - action_ban_ = menu_->addAction(ban->icon(), ban->text(), ban, SLOT(trigger())); + action_ban_ = + menu_->addAction(ban->icon(), ban->text(), ban, SLOT(trigger())); action_ban_->setVisible(ban->isVisible()); action_ban_->setEnabled(ban->isEnabled()); #endif @@ -148,8 +151,8 @@ void QtSystemTrayIcon::Clicked(QSystemTrayIcon::ActivationReason reason) { } } -void QtSystemTrayIcon::ShowPopup(const QString &summary, - const QString &message, int timeout) { +void QtSystemTrayIcon::ShowPopup(const QString& summary, const QString& message, + int timeout) { tray_->showMessage(summary, message, QSystemTrayIcon::NoIcon, timeout); } @@ -219,19 +222,15 @@ void QtSystemTrayIcon::LastFMButtonBanStateChanged(bool value) { } void QtSystemTrayIcon::MuteButtonStateChanged(bool value) { - if (action_mute_) - action_mute_->setChecked(value); + if (action_mute_) action_mute_->setChecked(value); } -bool QtSystemTrayIcon::IsVisible() const { - return tray_->isVisible(); -} +bool QtSystemTrayIcon::IsVisible() const { return tray_->isVisible(); } -void QtSystemTrayIcon::SetVisible(bool visible) { - tray_->setVisible(visible); -} +void QtSystemTrayIcon::SetVisible(bool visible) { tray_->setVisible(visible); } -void QtSystemTrayIcon::SetNowPlaying(const Song& song, const QString& image_path) { +void QtSystemTrayIcon::SetNowPlaying(const Song& song, + const QString& image_path) { #ifdef Q_WS_WIN // Windows doesn't support HTML in tooltips, so just show something basic tray_->setToolTip(song.PrettyTitleWithArtist()); @@ -242,26 +241,28 @@ void QtSystemTrayIcon::SetNowPlaying(const Song& song, const QString& image_path QString clone = pattern_; - clone.replace("%columns" , QString::number(columns)); - clone.replace("%appName" , QCoreApplication::applicationName()); + clone.replace("%columns", QString::number(columns)); + clone.replace("%appName", QCoreApplication::applicationName()); - clone.replace("%titleKey" , tr("Title") % ":"); - clone.replace("%titleValue" , Qt::escape(song.PrettyTitle())); - clone.replace("%artistKey" , tr("Artist") % ":"); + clone.replace("%titleKey", tr("Title") % ":"); + clone.replace("%titleValue", Qt::escape(song.PrettyTitle())); + clone.replace("%artistKey", tr("Artist") % ":"); clone.replace("%artistValue", Qt::escape(song.artist())); - clone.replace("%albumKey" , tr("Album") % ":"); - clone.replace("%albumValue" , Qt::escape(song.album())); + clone.replace("%albumKey", tr("Album") % ":"); + clone.replace("%albumValue", Qt::escape(song.album())); - clone.replace("%lengthKey" , tr("Length") % ":"); + clone.replace("%lengthKey", tr("Length") % ":"); clone.replace("%lengthValue", Qt::escape(song.PrettyLength())); - if(columns == 2) { - QString final_path = image_path.startsWith("file://") - ? image_path.mid(7) - : image_path; - clone.replace("%image", " " - " " - " "); + if (columns == 2) { + QString final_path = + image_path.startsWith("file://") ? image_path.mid(7) : image_path; + clone.replace("%image", + " " + " " + " "); } else { clone.replace("%image", ""); } diff --git a/src/ui/qtsystemtrayicon.h b/src/ui/qtsystemtrayicon.h index 3a4b64e4e..710a839ce 100644 --- a/src/ui/qtsystemtrayicon.h +++ b/src/ui/qtsystemtrayicon.h @@ -25,7 +25,7 @@ class QtSystemTrayIcon : public SystemTrayIcon { Q_OBJECT -public: + public: QtSystemTrayIcon(QObject* parent = 0); ~QtSystemTrayIcon(); @@ -35,12 +35,12 @@ public: bool IsVisible() const; void SetVisible(bool visible); - void ShowPopup(const QString &summary, const QString &message, int timeout); + void ShowPopup(const QString& summary, const QString& message, int timeout); void SetNowPlaying(const Song& song, const QString& image_path); void ClearNowPlaying(); - -protected: + + protected: // SystemTrayIcon void UpdateIcon(); void SetPaused(); @@ -53,12 +53,12 @@ protected: void MuteButtonStateChanged(bool value); // QObject - bool eventFilter(QObject *, QEvent *); + bool eventFilter(QObject*, QEvent*); -private slots: + private slots: void Clicked(QSystemTrayIcon::ActivationReason); -private: + private: QSystemTrayIcon* tray_; QMenu* menu_; QAction* action_play_pause_; @@ -74,4 +74,4 @@ private: QPixmap grey_icon_; }; -#endif // QTSYSTEMTRAYICON_H +#endif // QTSYSTEMTRAYICON_H diff --git a/src/ui/ripcd.cpp b/src/ui/ripcd.cpp index 34d55aad0..7bfada2d5 100644 --- a/src/ui/ripcd.cpp +++ b/src/ui/ripcd.cpp @@ -44,38 +44,36 @@ // winspool.h defines this :( #ifdef AddJob -# undef AddJob +#undef AddJob #endif namespace { - bool ComparePresetsByName(const TranscoderPreset& left, - const TranscoderPreset& right) { - return left.name_ < right.name_; - } +bool ComparePresetsByName(const TranscoderPreset& left, + const TranscoderPreset& right) { + return left.name_ < right.name_; +} - const char kWavHeaderRiffMarker[] = "RIFF"; - const char kWavFileTypeFormatChunk[] = "WAVEfmt "; - const char kWavDataString[] = "data"; - - const int kCheckboxColumn = 0; - const int kTrackNumberColumn = 1; - const int kTrackTitleColumn = 2; +const char kWavHeaderRiffMarker[] = "RIFF"; +const char kWavFileTypeFormatChunk[] = "WAVEfmt "; +const char kWavDataString[] = "data"; +const int kCheckboxColumn = 0; +const int kTrackNumberColumn = 1; +const int kTrackTitleColumn = 2; } const char* RipCD::kSettingsGroup = "Transcoder"; const int RipCD::kProgressInterval = 500; const int RipCD::kMaxDestinationItems = 10; -RipCD::RipCD(QWidget* parent) : - QDialog(parent), - transcoder_(new Transcoder(this)), - queued_(0), - finished_success_(0), - finished_failed_(0), - ui_(new Ui_RipCD) -{ +RipCD::RipCD(QWidget* parent) + : QDialog(parent), + transcoder_(new Transcoder(this)), + queued_(0), + finished_success_(0), + finished_failed_(0), + ui_(new Ui_RipCD) { - // Init + // Init ui_->setupUi(this); // Set column widths in the QTableWidget. @@ -83,12 +81,12 @@ RipCD::RipCD(QWidget* parent) : kCheckboxColumn, QHeaderView::ResizeToContents); ui_->tableWidget->horizontalHeader()->setResizeMode( kTrackNumberColumn, QHeaderView::ResizeToContents); - ui_->tableWidget->horizontalHeader()->setResizeMode( - kTrackTitleColumn, QHeaderView::Stretch); + ui_->tableWidget->horizontalHeader()->setResizeMode(kTrackTitleColumn, + QHeaderView::Stretch); // Add a rip button - rip_button_ = ui_->button_box->addButton( - tr("Start ripping"), QDialogButtonBox::ActionRole); + rip_button_ = ui_->button_box->addButton(tr("Start ripping"), + QDialogButtonBox::ActionRole); cancel_button_ = ui_->button_box->button(QDialogButtonBox::Cancel); close_button_ = ui_->button_box->button(QDialogButtonBox::Close); @@ -104,10 +102,11 @@ RipCD::RipCD(QWidget* parent) : connect(cancel_button_, SIGNAL(clicked()), SLOT(Cancel())); connect(close_button_, SIGNAL(clicked()), SLOT(hide())); - connect(transcoder_, SIGNAL(JobComplete(QString, bool)), SLOT(JobComplete(QString, bool))); + connect(transcoder_, SIGNAL(JobComplete(QString, bool)), + SLOT(JobComplete(QString, bool))); connect(transcoder_, SIGNAL(AllJobsComplete()), SLOT(AllJobsComplete())); connect(transcoder_, SIGNAL(JobOutputName(QString)), - SLOT(AppendOutput(QString))); + SLOT(AppendOutput(QString))); connect(this, SIGNAL(RippingComplete()), SLOT(ThreadedTranscoding())); connect(this, SIGNAL(SignalUpdateProgress()), SLOT(UpdateProgress())); @@ -118,31 +117,31 @@ RipCD::RipCD(QWidget* parent) : AddDestinationDirectory(QDir::homePath()); cdio_ = cdio_open(nullptr, DRIVER_UNKNOWN); - if(!cdio_) { + if (!cdio_) { qLog(Error) << "Failed to read CD drive"; return; } else { i_tracks_ = cdio_get_num_tracks(cdio_); ui_->tableWidget->setRowCount(i_tracks_); for (int i = 1; i <= i_tracks_; i++) { - QCheckBox *checkbox_i = new QCheckBox(ui_->tableWidget); + QCheckBox* checkbox_i = new QCheckBox(ui_->tableWidget); checkbox_i->setCheckState(Qt::Checked); checkboxes_.append(checkbox_i); ui_->tableWidget->setCellWidget(i - 1, kCheckboxColumn, checkbox_i); ui_->tableWidget->setCellWidget(i - 1, kTrackNumberColumn, - new QLabel(QString::number(i))); + new QLabel(QString::number(i))); QString track_title = QString("Track %1").arg(i); - QLineEdit *line_edit_track_title_i = new QLineEdit(track_title, - ui_->tableWidget); + QLineEdit* line_edit_track_title_i = + new QLineEdit(track_title, ui_->tableWidget); track_names_.append(line_edit_track_title_i); ui_->tableWidget->setCellWidget(i - 1, kTrackTitleColumn, - line_edit_track_title_i); + line_edit_track_title_i); } } // Get presets - QList presets = Transcoder::GetAllPresets(); + QList presets = Transcoder::GetAllPresets(); qSort(presets.begin(), presets.end(), ComparePresetsByName); - for(const TranscoderPreset& preset : presets) { + for (const TranscoderPreset& preset : presets) { ui_->format->addItem( QString("%1 (.%2)").arg(preset.name_, preset.extension_), QVariant::fromValue(preset)); @@ -155,8 +154,8 @@ RipCD::RipCD(QWidget* parent) : QString last_output_format = s.value("last_output_format", "ogg").toString(); for (int i = 0; i < ui_->format->count(); ++i) { - if (last_output_format - == ui_->format->itemData(i).value().extension_) { + if (last_output_format == + ui_->format->itemData(i).value().extension_) { ui_->format->setCurrentIndex(i); break; } @@ -166,10 +165,7 @@ RipCD::RipCD(QWidget* parent) : ui_->progress_bar->setMaximum(100); } -RipCD::~RipCD() { - delete ui_; -} - +RipCD::~RipCD() { delete ui_; } /* * WAV Header documentation @@ -190,28 +186,32 @@ RipCD::~RipCD() { * | are 44100 (CD), 48000 (DAT). * | Sample Rate = Number of Samples per second, or Hertz. * 29-32 | 176400 | (Sample Rate * BitsPerSample * Channels) / 8. - * 33-34 | 4 | (BitsPerSample * Channels) / 8.1 - 8 bit mono2 - 8 bit stereo/16 bit mono4 - 16 bit stereo + * 33-34 | 4 | (BitsPerSample * Channels) / 8.1 - 8 bit mono2 - 8 bit stereo/16 + * bit mono4 - 16 bit stereo * 35-36 | 16 | Bits per sample * 37-40 | "data" | "data" chunk header. * | Marks the beginning of the data section. * 41-44 | File size (data) | Size of the data section. */ -void RipCD::WriteWAVHeader(QFile *stream, int32_t i_bytecount) { +void RipCD::WriteWAVHeader(QFile* stream, int32_t i_bytecount) { QDataStream data_stream(stream); data_stream.setByteOrder(QDataStream::LittleEndian); // sizeof() - 1 to avoid including "\0" in the file too - data_stream.writeRawData(kWavHeaderRiffMarker,sizeof(kWavHeaderRiffMarker)-1); /* 0-3 */ - data_stream << qint32(i_bytecount + 44 - 8); /* 4-7 */ - data_stream.writeRawData(kWavFileTypeFormatChunk,sizeof(kWavFileTypeFormatChunk)-1); /* 8-15 */ - data_stream << (qint32)16; /* 16-19 */ - data_stream << (qint16)1; /* 20-21 */ - data_stream << (qint16)2; /* 22-23 */ - data_stream << (qint32)44100; /* 24-27 */ - data_stream << (qint32)(44100 * 2 * 2); /* 28-31 */ - data_stream << (qint16)4; /* 32-33 */ - data_stream << (qint16)16; /* 34-35 */ - data_stream.writeRawData(kWavDataString,sizeof(kWavDataString)-1); /* 36-39 */ - data_stream << (qint32)i_bytecount; /* 40-43 */ + data_stream.writeRawData(kWavHeaderRiffMarker, + sizeof(kWavHeaderRiffMarker) - 1); /* 0-3 */ + data_stream << qint32(i_bytecount + 44 - 8); /* 4-7 */ + data_stream.writeRawData(kWavFileTypeFormatChunk, + sizeof(kWavFileTypeFormatChunk) - 1); /* 8-15 */ + data_stream << (qint32)16; /* 16-19 */ + data_stream << (qint16)1; /* 20-21 */ + data_stream << (qint16)2; /* 22-23 */ + data_stream << (qint32)44100; /* 24-27 */ + data_stream << (qint32)(44100 * 2 * 2); /* 28-31 */ + data_stream << (qint16)4; /* 32-33 */ + data_stream << (qint16)16; /* 34-35 */ + data_stream.writeRawData(kWavDataString, + sizeof(kWavDataString) - 1); /* 36-39 */ + data_stream << (qint32)i_bytecount; /* 40-43 */ } int RipCD::NumTracksToRip() { @@ -235,27 +235,29 @@ void RipCD::ThreadClickedRipButton() { // Set up progress bar emit(SignalUpdateProgress()); - for (int i = 1; i <= i_tracks_; i++) { if (!checkboxes_.value(i - 1)->isChecked()) { continue; } tracks_to_rip_.append(i); - QString filename = temporary_directory_ - + ParseFileFormatString(ui_->format_filename->text(), i) + ".wav"; - QFile *destination_file = new QFile(filename); + QString filename = temporary_directory_ + + ParseFileFormatString(ui_->format_filename->text(), i) + + ".wav"; + QFile* destination_file = new QFile(filename); destination_file->open(QIODevice::WriteOnly); lsn_t i_first_lsn = cdio_get_track_lsn(cdio_, i); lsn_t i_last_lsn = cdio_get_track_last_lsn(cdio_, i); WriteWAVHeader(destination_file, - (i_last_lsn - i_first_lsn + 1) * CDIO_CD_FRAMESIZE_RAW); + (i_last_lsn - i_first_lsn + 1) * CDIO_CD_FRAMESIZE_RAW); - QByteArray buffered_input_bytes(CDIO_CD_FRAMESIZE_RAW,'\0'); + QByteArray buffered_input_bytes(CDIO_CD_FRAMESIZE_RAW, '\0'); for (lsn_t i_cursor = i_first_lsn; i_cursor <= i_last_lsn; i_cursor++) { - if(cdio_read_audio_sector(cdio_, buffered_input_bytes.data(), i_cursor) == DRIVER_OP_SUCCESS) { - destination_file->write(buffered_input_bytes.data(), buffered_input_bytes.size()); + if (cdio_read_audio_sector(cdio_, buffered_input_bytes.data(), + i_cursor) == DRIVER_OP_SUCCESS) { + destination_file->write(buffered_input_bytes.data(), + buffered_input_bytes.size()); } else { qLog(Error) << "CD read error"; break; @@ -263,9 +265,8 @@ void RipCD::ThreadClickedRipButton() { } finished_success_++; emit(SignalUpdateProgress()); - TranscoderPreset preset = - ui_->format->itemData(ui_->format->currentIndex()) - .value(); + TranscoderPreset preset = ui_->format->itemData(ui_->format->currentIndex()) + .value(); QString outfilename = GetOutputFileName(filename, preset); transcoder_->AddJob(filename.toUtf8().constData(), preset, outfilename); @@ -279,7 +280,7 @@ QString RipCD::TrimPath(const QString& path) const { } QString RipCD::GetOutputFileName(const QString& input, - const TranscoderPreset &preset) const { + const TranscoderPreset& preset) const { QString path = ui_->destination->itemData(ui_->destination->currentIndex()).toString(); if (path.isEmpty()) { @@ -293,7 +294,7 @@ QString RipCD::GetOutputFileName(const QString& input, } QString RipCD::ParseFileFormatString(const QString& file_format, - int track_no) const { + int track_no) const { QString to_return = file_format; to_return.replace(QString("%artist%"), ui_->artistLineEdit->text()); to_return.replace(QString("%album%"), ui_->albumLineEdit->text()); @@ -301,7 +302,7 @@ QString RipCD::ParseFileFormatString(const QString& file_format, to_return.replace(QString("%year%"), ui_->yearLineEdit->text()); to_return.replace(QString("%tracknum%"), QString::number(track_no)); to_return.replace(QString("%track%"), - track_names_.value(track_no - 1)->text()); + track_names_.value(track_no - 1)->text()); return to_return; } @@ -317,9 +318,8 @@ void RipCD::UpdateProgress() { void RipCD::ThreadedTranscoding() { transcoder_->Start(); - TranscoderPreset preset = - ui_->format->itemData(ui_->format->currentIndex()) - .value(); + TranscoderPreset preset = ui_->format->itemData(ui_->format->currentIndex()) + .value(); // Save the last output format QSettings s; s.beginGroup(kSettingsGroup); @@ -345,9 +345,10 @@ void RipCD::AllJobsComplete() { for (int i = 0; i < generated_files_.length(); i++) { TagLib::FileRef f(generated_files_.value(i).toUtf8().constData()); - f.tag()->setTitle( - track_names_.value(tracks_to_rip_.value(i) - 1) - ->text().toUtf8().constData()); + f.tag()->setTitle(track_names_.value(tracks_to_rip_.value(i) - 1) + ->text() + .toUtf8() + .constData()); f.tag()->setAlbum(ui_->albumLineEdit->text().toUtf8().constData()); f.tag()->setArtist(ui_->artistLineEdit->text().toUtf8().constData()); f.tag()->setGenre(ui_->genreLineEdit->text().toUtf8().constData()); @@ -369,10 +370,8 @@ void RipCD::AppendOutput(const QString& filename) { } void RipCD::Options() { - TranscoderPreset preset = - ui_->format->itemData( - ui_->format->currentIndex()) - .value(); + TranscoderPreset preset = ui_->format->itemData(ui_->format->currentIndex()) + .value(); TranscoderOptionsDialog dialog(preset.type_, this); if (dialog.is_valid()) { @@ -383,11 +382,11 @@ void RipCD::Options() { // Adds a folder to the destination box. void RipCD::AddDestination() { int index = ui_->destination->currentIndex(); - QString initial_dir = ( - !ui_->destination->itemData(index).isNull() ? - ui_->destination->itemData(index).toString() : QDir::homePath()); - QString dir = QFileDialog::getExistingDirectory(this, tr("Add folder"), - initial_dir); + QString initial_dir = (!ui_->destination->itemData(index).isNull() + ? ui_->destination->itemData(index).toString() + : QDir::homePath()); + QString dir = + QFileDialog::getExistingDirectory(this, tr("Add folder"), initial_dir); if (!dir.isEmpty()) { // Keep only a finite number of items in the box. @@ -418,9 +417,7 @@ void RipCD::Cancel() { SetWorking(false); } -bool RipCD::CDIOIsValid() const { - return (cdio_); -} +bool RipCD::CDIOIsValid() const { return (cdio_); } void RipCD::SetWorking(bool working) { rip_button_->setVisible(!working); @@ -432,23 +429,23 @@ void RipCD::SetWorking(bool working) { } void RipCD::SelectAll() { - foreach (QCheckBox* checkbox, checkboxes_) { + foreach(QCheckBox * checkbox, checkboxes_) { checkbox->setCheckState(Qt::Checked); } } void RipCD::SelectNone() { - foreach (QCheckBox* checkbox, checkboxes_) { + foreach(QCheckBox * checkbox, checkboxes_) { checkbox->setCheckState(Qt::Unchecked); } } void RipCD::InvertSelection() { - foreach (QCheckBox* checkbox, checkboxes_) { + foreach(QCheckBox * checkbox, checkboxes_) { if (checkbox->isChecked()) { - checkbox->setCheckState(Qt::Unchecked); + checkbox->setCheckState(Qt::Unchecked); } else { - checkbox->setCheckState(Qt::Checked); + checkbox->setCheckState(Qt::Checked); } } } diff --git a/src/ui/ripcd.h b/src/ui/ripcd.h index 6f134639f..779889c53 100644 --- a/src/ui/ripcd.h +++ b/src/ui/ripcd.h @@ -30,7 +30,7 @@ class Transcoder; struct TranscoderPreset; -class RipCD: public QDialog { +class RipCD : public QDialog { Q_OBJECT public: @@ -48,7 +48,7 @@ class RipCD: public QDialog { int finished_failed_; track_t i_tracks_; Ui_RipCD* ui_; - CdIo_t *cdio_; + CdIo_t* cdio_; QList checkboxes_; QList generated_files_; QList tracks_to_rip_; @@ -59,18 +59,18 @@ class RipCD: public QDialog { QPushButton* rip_button_; QString temporary_directory_; - void WriteWAVHeader(QFile *stream, int32_t i_bytecount); + void WriteWAVHeader(QFile* stream, int32_t i_bytecount); int NumTracksToRip(); void ThreadClickedRipButton(); QString TrimPath(const QString& path) const; QString GetOutputFileName(const QString& input, - const TranscoderPreset& preset) const; + const TranscoderPreset& preset) const; QString ParseFileFormatString(const QString& file_format, int track_no) const; void SetWorking(bool working); void AddDestinationDirectory(QString dir); void RemoveTemporaryDirectory(); - signals: +signals: void RippingComplete(); void SignalUpdateProgress(); private slots: diff --git a/src/ui/screensaver.cpp b/src/ui/screensaver.cpp index 58aeaa728..f919845cd 100644 --- a/src/ui/screensaver.cpp +++ b/src/ui/screensaver.cpp @@ -21,37 +21,40 @@ #include #ifdef HAVE_DBUS - #include "dbusscreensaver.h" - #include - #include +#include "dbusscreensaver.h" +#include +#include #endif #ifdef Q_OS_DARWIN - #include "macscreensaver.h" +#include "macscreensaver.h" #endif #include -const char* Screensaver::kGnomeService = "org.gnome.ScreenSaver"; -const char* Screensaver::kGnomePath = "/"; +const char* Screensaver::kGnomeService = "org.gnome.ScreenSaver"; +const char* Screensaver::kGnomePath = "/"; const char* Screensaver::kGnomeInterface = "org.gnome.ScreenSaver"; -const char* Screensaver::kKdeService = "org.kde.ScreenSaver"; -const char* Screensaver::kKdePath = "/ScreenSaver/"; -const char* Screensaver::kKdeInterface = "org.freedesktop.ScreenSaver"; +const char* Screensaver::kKdeService = "org.kde.ScreenSaver"; +const char* Screensaver::kKdePath = "/ScreenSaver/"; +const char* Screensaver::kKdeInterface = "org.freedesktop.ScreenSaver"; Screensaver* Screensaver::screensaver_ = 0; Screensaver* Screensaver::GetScreensaver() { if (!screensaver_) { - #if defined(HAVE_DBUS) - if (QDBusConnection::sessionBus().interface()->isServiceRegistered(kGnomeService)) { - screensaver_ = new DBusScreensaver(kGnomeService, kGnomePath, kGnomeInterface); - } else if (QDBusConnection::sessionBus().interface()->isServiceRegistered(kKdeService)) { - screensaver_ = new DBusScreensaver(kKdeService, kKdePath, kKdeInterface); - } - #elif defined(Q_OS_DARWIN) - screensaver_ = new MacScreensaver(); - #endif +#if defined(HAVE_DBUS) + if (QDBusConnection::sessionBus().interface()->isServiceRegistered( + kGnomeService)) { + screensaver_ = + new DBusScreensaver(kGnomeService, kGnomePath, kGnomeInterface); + } else if (QDBusConnection::sessionBus().interface()->isServiceRegistered( + kKdeService)) { + screensaver_ = new DBusScreensaver(kKdeService, kKdePath, kKdeInterface); + } +#elif defined(Q_OS_DARWIN) + screensaver_ = new MacScreensaver(); +#endif } return screensaver_; } diff --git a/src/ui/settingsdialog.cpp b/src/ui/settingsdialog.cpp index fca7c5074..2dc3016cd 100644 --- a/src/ui/settingsdialog.cpp +++ b/src/ui/settingsdialog.cpp @@ -52,28 +52,27 @@ #include "ui_settingsdialog.h" #ifdef HAVE_LIBLASTFM -# include "internet/lastfmsettingspage.h" +#include "internet/lastfmsettingspage.h" #endif #ifdef HAVE_WIIMOTEDEV -# include "wiimotedev/wiimotesettingspage.h" +#include "wiimotedev/wiimotesettingspage.h" #endif - #ifdef HAVE_GOOGLE_DRIVE -# include "internet/googledrivesettingspage.h" +#include "internet/googledrivesettingspage.h" #endif #ifdef HAVE_UBUNTU_ONE -# include "internet/ubuntuonesettingspage.h" +#include "internet/ubuntuonesettingspage.h" #endif #ifdef HAVE_DROPBOX -# include "internet/dropboxsettingspage.h" +#include "internet/dropboxsettingspage.h" #endif #ifdef HAVE_BOX -# include "internet/boxsettingspage.h" +#include "internet/boxsettingspage.h" #endif #include @@ -82,15 +81,13 @@ #include #include - SettingsItemDelegate::SettingsItemDelegate(QObject* parent) - : QStyledItemDelegate(parent) -{ -} + : QStyledItemDelegate(parent) {} QSize SettingsItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { - const bool is_separator = index.data(SettingsDialog::Role_IsSeparator).toBool(); + const bool is_separator = + index.data(SettingsDialog::Role_IsSeparator).toBool(); QSize ret = QStyledItemDelegate::sizeHint(option, index); if (is_separator) { @@ -100,9 +97,11 @@ QSize SettingsItemDelegate::sizeHint(const QStyleOptionViewItem& option, return ret; } -void SettingsItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, +void SettingsItemDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, const QModelIndex& index) const { - const bool is_separator = index.data(SettingsDialog::Role_IsSeparator).toBool(); + const bool is_separator = + index.data(SettingsDialog::Role_IsSeparator).toBool(); if (is_separator) { GroupedIconView::DrawHeader(painter, option.rect, option.font, @@ -112,19 +111,18 @@ void SettingsItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& } } - -SettingsDialog::SettingsDialog(Application* app, BackgroundStreams* streams, QWidget* parent) - : QDialog(parent), - app_(app), - model_(app_->library_model()->directory_model()), - gst_engine_(qobject_cast(app_->player()->engine())), - song_info_view_(nullptr), - streams_(streams), - global_search_(app_->global_search()), - appearance_(app_->appearance()), - ui_(new Ui_SettingsDialog), - loading_settings_(false) -{ +SettingsDialog::SettingsDialog(Application* app, BackgroundStreams* streams, + QWidget* parent) + : QDialog(parent), + app_(app), + model_(app_->library_model()->directory_model()), + gst_engine_(qobject_cast(app_->player()->engine())), + song_info_view_(nullptr), + streams_(streams), + global_search_(app_->global_search()), + appearance_(app_->appearance()), + ui_(new Ui_SettingsDialog), + loading_settings_(false) { ui_->setupUi(this); ui_->list->setItemDelegate(new SettingsItemDelegate(this)); @@ -176,25 +174,28 @@ SettingsDialog::SettingsDialog(Application* app, BackgroundStreams* streams, QWi AddPage(Page_Spotify, new SpotifySettingsPage(this), providers); AddPage(Page_Magnatune, new MagnatuneSettingsPage(this), providers); - AddPage(Page_DigitallyImported, new DigitallyImportedSettingsPage(this), providers); - AddPage(Page_BackgroundStreams, new BackgroundStreamsSettingsPage(this), providers); + AddPage(Page_DigitallyImported, new DigitallyImportedSettingsPage(this), + providers); + AddPage(Page_BackgroundStreams, new BackgroundStreamsSettingsPage(this), + providers); AddPage(Page_Subsonic, new SubsonicSettingsPage(this), providers); AddPage(Page_Podcasts, new PodcastSettingsPage(this), providers); // List box - connect(ui_->list, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), + connect(ui_->list, + SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), SLOT(CurrentItemChanged(QTreeWidgetItem*))); ui_->list->setCurrentItem(pages_[Page_Playback].item_); // Make sure the list is big enough to show all the items - ui_->list->setMinimumWidth(static_cast(ui_->list)->sizeHintForColumn(0)); + ui_->list->setMinimumWidth( + static_cast(ui_->list)->sizeHintForColumn(0)); - ui_->buttonBox->button(QDialogButtonBox::Cancel)->setShortcut(QKeySequence::Close); + ui_->buttonBox->button(QDialogButtonBox::Cancel) + ->setShortcut(QKeySequence::Close); } -SettingsDialog::~SettingsDialog() { - delete ui_; -} +SettingsDialog::~SettingsDialog() { delete ui_; } QTreeWidgetItem* SettingsDialog::AddCategory(const QString& name) { QTreeWidgetItem* item = new QTreeWidgetItem; @@ -208,15 +209,15 @@ QTreeWidgetItem* SettingsDialog::AddCategory(const QString& name) { return item; } -void SettingsDialog::AddPage(Page id, SettingsPage* page, QTreeWidgetItem* parent) { - if (!parent) - parent = ui_->list->invisibleRootItem(); +void SettingsDialog::AddPage(Page id, SettingsPage* page, + QTreeWidgetItem* parent) { + if (!parent) parent = ui_->list->invisibleRootItem(); // Connect page's signals to the settings dialog's signals - connect(page, SIGNAL(NotificationPreview(OSD::Behaviour,QString,QString)), - SIGNAL(NotificationPreview(OSD::Behaviour,QString,QString))); + connect(page, SIGNAL(NotificationPreview(OSD::Behaviour, QString, QString)), + SIGNAL(NotificationPreview(OSD::Behaviour, QString, QString))); connect(page, SIGNAL(SetWiimotedevInterfaceActived(bool)), - SIGNAL(SetWiimotedevInterfaceActived(bool))); + SIGNAL(SetWiimotedevInterfaceActived(bool))); // Create the list item QTreeWidgetItem* item = new QTreeWidgetItem; @@ -250,9 +251,7 @@ void SettingsDialog::AddPage(Page id, SettingsPage* page, QTreeWidgetItem* paren } void SettingsDialog::Save() { - foreach (const PageData& data, pages_.values()) { - data.page_->Save(); - } + foreach(const PageData & data, pages_.values()) { data.page_->Save(); } } void SettingsDialog::accept() { @@ -262,9 +261,7 @@ void SettingsDialog::accept() { void SettingsDialog::reject() { // Notify each page that user clicks on Cancel - foreach (const PageData& data, pages_.values()) { - data.page_->Cancel(); - } + foreach(const PageData & data, pages_.values()) { data.page_->Cancel(); } QDialog::reject(); } @@ -279,13 +276,12 @@ void SettingsDialog::DialogButtonClicked(QAbstractButton* button) { void SettingsDialog::showEvent(QShowEvent* e) { // Load settings loading_settings_ = true; - foreach (const PageData& data, pages_.values()) { - data.page_->Load(); - } + foreach(const PageData & data, pages_.values()) { data.page_->Load(); } loading_settings_ = false; // Resize the dialog if it's too big - const QSize available = QApplication::desktop()->availableGeometry(this).size(); + const QSize available = + QApplication::desktop()->availableGeometry(this).size(); if (available.height() < height()) { resize(width(), sizeHint().height()); } @@ -303,7 +299,7 @@ void SettingsDialog::OpenAtPage(Page page) { } void SettingsDialog::CurrentItemChanged(QTreeWidgetItem* item) { - if (! (item->flags() & Qt::ItemIsSelectable)) { + if (!(item->flags() & Qt::ItemIsSelectable)) { return; } @@ -311,7 +307,7 @@ void SettingsDialog::CurrentItemChanged(QTreeWidgetItem* item) { ui_->title->setText("" + item->text(0) + ""); // Display the right page - foreach (const PageData& data, pages_.values()) { + foreach(const PageData & data, pages_.values()) { if (data.item_ == item) { ui_->stacked_widget->setCurrentWidget(data.scroll_area_); break; diff --git a/src/ui/settingsdialog.h b/src/ui/settingsdialog.h index e9e709a99..583fc47c5 100644 --- a/src/ui/settingsdialog.h +++ b/src/ui/settingsdialog.h @@ -39,22 +39,22 @@ class Ui_SettingsDialog; class GstEngine; - class SettingsItemDelegate : public QStyledItemDelegate { -public: + public: SettingsItemDelegate(QObject* parent); - QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; + QSize sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const; void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; }; - class SettingsDialog : public QDialog { Q_OBJECT -public: - SettingsDialog(Application* app, BackgroundStreams* streams, QWidget* parent = 0); + public: + SettingsDialog(Application* app, BackgroundStreams* streams, + QWidget* parent = 0); ~SettingsDialog(); enum Page { @@ -86,11 +86,11 @@ public: Page_Box, }; - enum Role { - Role_IsSeparator = Qt::UserRole - }; + enum Role { Role_IsSeparator = Qt::UserRole }; - void SetGlobalShortcutManager(GlobalShortcuts* manager) { manager_ = manager; } + void SetGlobalShortcutManager(GlobalShortcuts* manager) { + manager_ = manager; + } void SetSongInfoView(SongInfoView* view) { song_info_view_ = view; } bool is_loading_settings() const { return loading_settings_; } @@ -117,11 +117,11 @@ signals: void NotificationPreview(OSD::Behaviour, QString, QString); void SetWiimotedevInterfaceActived(bool); -private slots: + private slots: void CurrentItemChanged(QTreeWidgetItem* item); void DialogButtonClicked(QAbstractButton* button); -private: + private: struct PageData { QTreeWidgetItem* item_; QScrollArea* scroll_area_; @@ -133,7 +133,7 @@ private: void Save(); -private: + private: Application* app_; LibraryDirectoryModel* model_; GlobalShortcuts* manager_; @@ -149,4 +149,4 @@ private: QMap pages_; }; -#endif // SETTINGSDIALOG_H +#endif // SETTINGSDIALOG_H diff --git a/src/ui/settingspage.cpp b/src/ui/settingspage.cpp index 696d4598a..b66912e81 100644 --- a/src/ui/settingspage.cpp +++ b/src/ui/settingspage.cpp @@ -19,7 +19,4 @@ #include "settingspage.h" SettingsPage::SettingsPage(SettingsDialog* dialog) - : QWidget(dialog), - dialog_(dialog) -{ -} + : QWidget(dialog), dialog_(dialog) {} diff --git a/src/ui/settingspage.h b/src/ui/settingspage.h index c9499ff02..99e33014d 100644 --- a/src/ui/settingspage.h +++ b/src/ui/settingspage.h @@ -27,7 +27,7 @@ class SettingsDialog; class SettingsPage : public QWidget { Q_OBJECT -public: + public: SettingsPage(SettingsDialog* dialog); // Return false to grey out the page's item in the list. @@ -46,8 +46,8 @@ signals: void NotificationPreview(OSD::Behaviour, QString, QString); void SetWiimotedevInterfaceActived(bool); -private: + private: SettingsDialog* dialog_; }; -#endif // SETTINGSPAGE_H +#endif // SETTINGSPAGE_H diff --git a/src/ui/standarditemiconloader.cpp b/src/ui/standarditemiconloader.cpp index bc592fbbc..2a671f34d 100644 --- a/src/ui/standarditemiconloader.cpp +++ b/src/ui/standarditemiconloader.cpp @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -24,56 +24,53 @@ StandardItemIconLoader::StandardItemIconLoader(AlbumCoverLoader* cover_loader, QObject* parent) - : QObject(parent), - cover_loader_(cover_loader), - model_(nullptr) -{ + : QObject(parent), cover_loader_(cover_loader), model_(nullptr) { cover_options_.desired_height_ = 16; - connect(cover_loader_, SIGNAL(ImageLoaded(quint64,QImage)), - SLOT(ImageLoaded(quint64,QImage))); + connect(cover_loader_, SIGNAL(ImageLoaded(quint64, QImage)), + SLOT(ImageLoaded(quint64, QImage))); } void StandardItemIconLoader::SetModel(QAbstractItemModel* model) { if (model_) { - disconnect(model_, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), - this, SLOT(RowsAboutToBeRemoved(QModelIndex,int,int))); + disconnect(model_, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int)), + this, SLOT(RowsAboutToBeRemoved(QModelIndex, int, int))); } model_ = model; - connect(model_, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), - SLOT(RowsAboutToBeRemoved(QModelIndex,int,int))); - connect(model_, SIGNAL(modelAboutToBeReset()), - SLOT(ModelReset())); + connect(model_, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int)), + SLOT(RowsAboutToBeRemoved(QModelIndex, int, int))); + connect(model_, SIGNAL(modelAboutToBeReset()), SLOT(ModelReset())); } void StandardItemIconLoader::LoadIcon(const QString& art_automatic, const QString& art_manual, QStandardItem* for_item) { - const quint64 id = cover_loader_->LoadImageAsync(cover_options_, art_automatic, art_manual); + const quint64 id = + cover_loader_->LoadImageAsync(cover_options_, art_automatic, art_manual); pending_covers_[id] = for_item; } -void StandardItemIconLoader::LoadIcon(const Song& song, QStandardItem* for_item) { +void StandardItemIconLoader::LoadIcon(const Song& song, + QStandardItem* for_item) { const quint64 id = cover_loader_->LoadImageAsync(cover_options_, song); pending_covers_[id] = for_item; } -void StandardItemIconLoader::RowsAboutToBeRemoved(const QModelIndex& parent, int begin, int end) { - for (QMap::iterator it = pending_covers_.begin() ; - it != pending_covers_.end() ; ) { +void StandardItemIconLoader::RowsAboutToBeRemoved(const QModelIndex& parent, + int begin, int end) { + for (QMap::iterator it = pending_covers_.begin(); + it != pending_covers_.end();) { const QStandardItem* item = it.value(); const QStandardItem* item_parent = item->parent(); - if (item_parent && - item_parent->index() == parent && - item->index().row() >= begin && - item->index().row() <= end) { + if (item_parent && item_parent->index() == parent && + item->index().row() >= begin && item->index().row() <= end) { cover_loader_->CancelTask(it.key()); it = pending_covers_.erase(it); } else { - ++ it; + ++it; } } } @@ -85,8 +82,7 @@ void StandardItemIconLoader::ModelReset() { void StandardItemIconLoader::ImageLoaded(quint64 id, const QImage& image) { QStandardItem* item = pending_covers_.take(id); - if (!item) - return; + if (!item) return; if (!image.isNull()) { item->setIcon(QIcon(QPixmap::fromImage(image))); diff --git a/src/ui/standarditemiconloader.h b/src/ui/standarditemiconloader.h index 536c27a88..999dd2b34 100644 --- a/src/ui/standarditemiconloader.h +++ b/src/ui/standarditemiconloader.h @@ -1,16 +1,16 @@ /* This file is part of Clementine. Copyright 2012, David Sansome - + Clementine 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. - + Clementine 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 Clementine. If not, see . */ @@ -35,7 +35,7 @@ class QStandardItem; class StandardItemIconLoader : public QObject { Q_OBJECT -public: + public: StandardItemIconLoader(AlbumCoverLoader* cover_loader, QObject* parent = 0); AlbumCoverLoaderOptions* options() { return &cover_options_; } @@ -45,13 +45,13 @@ public: void LoadIcon(const QString& art_automatic, const QString& art_manual, QStandardItem* for_item); void LoadIcon(const Song& song, QStandardItem* for_item); - -private slots: + + private slots: void ImageLoaded(quint64 id, const QImage& image); void RowsAboutToBeRemoved(const QModelIndex& parent, int begin, int end); void ModelReset(); -private: + private: AlbumCoverLoader* cover_loader_; AlbumCoverLoaderOptions cover_options_; @@ -60,4 +60,4 @@ private: QMap pending_covers_; }; -#endif // STANDARDITEMICONLOADER_H +#endif // STANDARDITEMICONLOADER_H diff --git a/src/ui/systemtrayicon.cpp b/src/ui/systemtrayicon.cpp index 060436645..a293a5d66 100644 --- a/src/ui/systemtrayicon.cpp +++ b/src/ui/systemtrayicon.cpp @@ -29,14 +29,13 @@ #include SystemTrayIcon::SystemTrayIcon(QObject* parent) - : QObject(parent), - percentage_(0), - playing_icon_(":/tiny-start.png"), - paused_icon_(":/tiny-pause.png") -{ -} + : QObject(parent), + percentage_(0), + playing_icon_(":/tiny-start.png"), + paused_icon_(":/tiny-pause.png") {} -QPixmap SystemTrayIcon::CreateIcon(const QPixmap& icon, const QPixmap& grey_icon) { +QPixmap SystemTrayIcon::CreateIcon(const QPixmap& icon, + const QPixmap& grey_icon) { QRect rect(icon.rect()); // The angle of the line that's used to cover the icon. @@ -46,12 +45,9 @@ QPixmap SystemTrayIcon::CreateIcon(const QPixmap& icon, const QPixmap& grey_icon QPolygon mask; mask << rect.topRight(); - mask << rect.topRight() + QPoint( - length * sin(angle), - - length * cos(angle)); + mask << rect.topRight() + QPoint(length * sin(angle), -length * cos(angle)); - if (song_progress() > 50) - mask << rect.bottomLeft(); + if (song_progress() > 50) mask << rect.bottomLeft(); mask << rect.topLeft(); mask << rect.topRight(); @@ -67,9 +63,11 @@ QPixmap SystemTrayIcon::CreateIcon(const QPixmap& icon, const QPixmap& grey_icon // Draw the playing or paused icon in the top-right if (!current_state_icon().isNull()) { int height = rect.height() / 2; - QPixmap scaled(current_state_icon().scaledToHeight(height, Qt::SmoothTransformation)); + QPixmap scaled( + current_state_icon().scaledToHeight(height, Qt::SmoothTransformation)); - QRect state_rect(rect.width() - scaled.width(), 0, scaled.width(), scaled.height()); + QRect state_rect(rect.width() - scaled.width(), 0, scaled.width(), + scaled.height()); p.drawPixmap(state_rect, scaled); } diff --git a/src/ui/systemtrayicon.h b/src/ui/systemtrayicon.h index defe5d533..4c68b6420 100644 --- a/src/ui/systemtrayicon.h +++ b/src/ui/systemtrayicon.h @@ -61,7 +61,7 @@ class SystemTrayIcon : public QObject { virtual void LastFMButtonBanStateChanged(bool value) {} virtual void MuteButtonStateChanged(bool value) {} - signals: +signals: void ChangeVolume(int delta); void SeekForward(); void SeekBackward(); @@ -84,4 +84,4 @@ class SystemTrayIcon : public QObject { QPixmap current_state_icon_; }; -#endif // SYSTEMTRAYICON_H +#endif // SYSTEMTRAYICON_H diff --git a/src/ui/trackselectiondialog.cpp b/src/ui/trackselectiondialog.cpp index 0fcde0502..3423ca0c6 100644 --- a/src/ui/trackselectiondialog.cpp +++ b/src/ui/trackselectiondialog.cpp @@ -29,23 +29,22 @@ #include #include -TrackSelectionDialog::TrackSelectionDialog(QWidget *parent) - : QDialog(parent), - ui_(new Ui_TrackSelectionDialog), - save_on_close_(false) -{ +TrackSelectionDialog::TrackSelectionDialog(QWidget* parent) + : QDialog(parent), ui_(new Ui_TrackSelectionDialog), save_on_close_(false) { // Setup dialog window ui_->setupUi(this); connect(ui_->song_list, SIGNAL(currentRowChanged(int)), SLOT(UpdateStack())); - connect(ui_->results, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), + connect(ui_->results, + SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), SLOT(ResultSelected())); ui_->splitter->setSizes(QList() << 200 << width() - 200); SetLoading(QString()); // Add the next/previous buttons - previous_button_ = new QPushButton(IconLoader::Load("go-previous"), tr("Previous"), this); + previous_button_ = + new QPushButton(IconLoader::Load("go-previous"), tr("Previous"), this); next_button_ = new QPushButton(IconLoader::Load("go-next"), tr("Next"), this); ui_->button_box->addButton(previous_button_, QDialogButtonBox::ResetRole); ui_->button_box->addButton(next_button_, QDialogButtonBox::ResetRole); @@ -56,27 +55,26 @@ TrackSelectionDialog::TrackSelectionDialog(QWidget *parent) // Set some shortcuts for the buttons new QShortcut(QKeySequence::Back, previous_button_, SLOT(click())); new QShortcut(QKeySequence::Forward, next_button_, SLOT(click())); - new QShortcut(QKeySequence::MoveToPreviousPage, previous_button_, SLOT(click())); + new QShortcut(QKeySequence::MoveToPreviousPage, previous_button_, + SLOT(click())); new QShortcut(QKeySequence::MoveToNextPage, next_button_, SLOT(click())); // Resize columns - ui_->results->setColumnWidth(0, 50); // Track column - ui_->results->setColumnWidth(1, 50); // Year column - ui_->results->setColumnWidth(2, 160); // Title column - ui_->results->setColumnWidth(3, 160); // Artist column - ui_->results->setColumnWidth(4, 160); // Album column + ui_->results->setColumnWidth(0, 50); // Track column + ui_->results->setColumnWidth(1, 50); // Year column + ui_->results->setColumnWidth(2, 160); // Title column + ui_->results->setColumnWidth(3, 160); // Artist column + ui_->results->setColumnWidth(4, 160); // Album column } -TrackSelectionDialog::~TrackSelectionDialog() { - delete ui_; -} +TrackSelectionDialog::~TrackSelectionDialog() { delete ui_; } void TrackSelectionDialog::Init(const SongList& songs) { ui_->song_list->clear(); ui_->stack->setCurrentWidget(ui_->loading_page); data_.clear(); - foreach (const Song& song, songs) { + foreach(const Song & song, songs) { Data data; data.original_song_ = song; data_ << data; @@ -98,15 +96,14 @@ void TrackSelectionDialog::FetchTagProgress(const Song& original_song, const QString& progress) { // Find the item with this filename int row = -1; - for (int i=0 ; isong_list->item(row)->setForeground(palette().text()); @@ -145,8 +141,7 @@ void TrackSelectionDialog::FetchTagFinished(const Song& original_song, void TrackSelectionDialog::UpdateStack() { const int row = ui_->song_list->currentRow(); - if (row < 0 || row >= data_.count()) - return; + if (row < 0 || row >= data_.count()) return; const Data& data = data_[row]; @@ -171,12 +166,12 @@ void TrackSelectionDialog::UpdateStack() { AddDivider(tr("Suggested tags"), ui_->results); int song_index = 0; - foreach (const Song& song, data.results_) { + foreach(const Song & song, data.results_) { AddSong(song, song_index++, ui_->results); } // Find the item that was selected last time - for (int i=0 ; iresults->model()->rowCount() ; ++i) { + for (int i = 0; i < ui_->results->model()->rowCount(); ++i) { const QModelIndex index = ui_->results->model()->index(i, 0); const QVariant id = index.data(Qt::UserRole); if (!id.isNull() && id.toInt() == data.selected_result_) { @@ -186,7 +181,8 @@ void TrackSelectionDialog::UpdateStack() { } } -void TrackSelectionDialog::AddDivider(const QString& text, QTreeWidget* parent) const { +void TrackSelectionDialog::AddDivider(const QString& text, + QTreeWidget* parent) const { QTreeWidgetItem* item = new QTreeWidgetItem(parent); item->setFirstColumnSpanned(true); item->setText(0, text); @@ -198,7 +194,8 @@ void TrackSelectionDialog::AddDivider(const QString& text, QTreeWidget* parent) item->setFont(0, bold_font); } -void TrackSelectionDialog::AddSong(const Song& song, int result_index, QTreeWidget* parent) const { +void TrackSelectionDialog::AddSong(const Song& song, int result_index, + QTreeWidget* parent) const { QStringList values; values << ((song.track() > 0) ? QString::number(song.track()) : QString()) << ((song.year() > 0) ? QString::number(song.year()) : QString()) @@ -210,14 +207,13 @@ void TrackSelectionDialog::AddSong(const Song& song, int result_index, QTreeWidg } void TrackSelectionDialog::ResultSelected() { - if (!ui_->results->currentItem()) - return; + if (!ui_->results->currentItem()) return; const int song_row = ui_->song_list->currentRow(); - if (song_row == -1) - return; + if (song_row == -1) return; - const int result_index = ui_->results->currentItem()->data(0, Qt::UserRole).toInt(); + const int result_index = + ui_->results->currentItem()->data(0, Qt::UserRole).toInt(); data_[song_row].selected_result_ = result_index; } @@ -231,7 +227,7 @@ void TrackSelectionDialog::SetLoading(const QString& message) { } void TrackSelectionDialog::SaveData(const QList& data) { - for (int i=0 ; i& data) { copy.set_track(new_metadata.track()); copy.set_year(new_metadata.year()); - if (!TagReaderClient::Instance()->SaveFileBlocking(copy.url().toLocalFile(), copy)) { - qLog(Warning) << "Failed to write new auto-tags to" << copy.url().toLocalFile(); + if (!TagReaderClient::Instance()->SaveFileBlocking(copy.url().toLocalFile(), + copy)) { + qLog(Warning) << "Failed to write new auto-tags to" + << copy.url().toLocalFile(); } } } @@ -256,7 +254,8 @@ void TrackSelectionDialog::accept() { SetLoading(tr("Saving tracks") + "..."); // Save tags in the background - QFuture future = QtConcurrent::run(&TrackSelectionDialog::SaveData, data_); + QFuture future = + QtConcurrent::run(&TrackSelectionDialog::SaveData, data_); QFutureWatcher* watcher = new QFutureWatcher(this); watcher->setFuture(future); connect(watcher, SIGNAL(finished()), SLOT(AcceptFinished())); @@ -266,7 +265,7 @@ void TrackSelectionDialog::accept() { QDialog::accept(); - foreach (const Data& data, data_) { + foreach(const Data & data, data_) { if (data.pending_ || data.results_.isEmpty() || data.selected_result_ == -1) continue; @@ -278,8 +277,7 @@ void TrackSelectionDialog::accept() { void TrackSelectionDialog::AcceptFinished() { QFutureWatcher* watcher = dynamic_cast*>(sender()); - if (!watcher) - return; + if (!watcher) return; watcher->deleteLater(); SetLoading(QString()); @@ -292,7 +290,7 @@ void TrackSelectionDialog::NextSong() { } void TrackSelectionDialog::PreviousSong() { - int row = (ui_->song_list->currentRow() - 1 + ui_->song_list->count()) % ui_->song_list->count(); + int row = (ui_->song_list->currentRow() - 1 + ui_->song_list->count()) % + ui_->song_list->count(); ui_->song_list->setCurrentRow(row); } - diff --git a/src/ui/trackselectiondialog.h b/src/ui/trackselectiondialog.h index 03ae1f8b1..f95b57852 100644 --- a/src/ui/trackselectiondialog.h +++ b/src/ui/trackselectiondialog.h @@ -30,17 +30,18 @@ class QTreeWidget; class TrackSelectionDialog : public QDialog { Q_OBJECT -public: - TrackSelectionDialog(QWidget *parent = 0); + public: + TrackSelectionDialog(QWidget* parent = 0); ~TrackSelectionDialog(); void set_save_on_close(bool save_on_close) { save_on_close_ = save_on_close; } void Init(const SongList& songs); -public slots: + public slots: void FetchTagProgress(const Song& original_song, const QString& progress); - void FetchTagFinished(const Song& original_song, const SongList& songs_guessed); + void FetchTagFinished(const Song& original_song, + const SongList& songs_guessed); // QDialog void accept(); @@ -48,7 +49,7 @@ public slots: signals: void SongChosen(const Song& original_song, const Song& new_metadata); -private slots: + private slots: void UpdateStack(); void NextSong(); @@ -57,7 +58,7 @@ private slots: void ResultSelected(); void AcceptFinished(); -private: + private: Ui_TrackSelectionDialog* ui_; struct Data { @@ -76,7 +77,7 @@ private: void SetLoading(const QString& message); static void SaveData(const QList& data); -private: + private: QList data_; QPushButton* previous_button_; @@ -85,6 +86,4 @@ private: bool save_on_close_; }; -#endif // TRACKSELECTIONDIALOG_H - - +#endif // TRACKSELECTIONDIALOG_H diff --git a/src/ui/windows7thumbbar.cpp b/src/ui/windows7thumbbar.cpp index 4cc11c8c3..0dc01ea78 100644 --- a/src/ui/windows7thumbbar.cpp +++ b/src/ui/windows7thumbbar.cpp @@ -22,24 +22,20 @@ #include #ifdef Q_OS_WIN32 -# define _WIN32_WINNT 0x0600 -# include -# include -# include -#endif // Q_OS_WIN32 - +#define _WIN32_WINNT 0x0600 +#include +#include +#include +#endif // Q_OS_WIN32 const int Windows7ThumbBar::kIconSize = 16; const int Windows7ThumbBar::kMaxButtonCount = 7; - Windows7ThumbBar::Windows7ThumbBar(QWidget* widget) - : QObject(widget), - widget_(widget), - button_created_message_id_(0), - taskbar_list_(nullptr) -{ -} + : QObject(widget), + widget_(widget), + button_created_message_id_(0), + taskbar_list_(nullptr) {} void Windows7ThumbBar::SetActions(const QList& actions) { #ifdef Q_OS_WIN32 @@ -47,19 +43,20 @@ void Windows7ThumbBar::SetActions(const QList& actions) { Q_ASSERT(actions.count() <= kMaxButtonCount); actions_ = actions; - foreach (QAction* action, actions) { + foreach(QAction * action, actions) { if (action) { connect(action, SIGNAL(changed()), SLOT(ActionChanged())); } } qLog(Debug) << "Done"; -#endif // Q_OS_WIN32 +#endif // Q_OS_WIN32 } #ifdef Q_OS_WIN32 static void SetupButton(const QAction* action, THUMBBUTTON* button) { if (action) { - button->hIcon = action->icon().pixmap(Windows7ThumbBar::kIconSize).toWinHICON(); + button->hIcon = + action->icon().pixmap(Windows7ThumbBar::kIconSize).toWinHICON(); button->dwFlags = action->isEnabled() ? THBF_ENABLED : THBF_DISABLED; // This is unsafe - doesn't obey 260-char restriction action->text().toWCharArray(button->szTip); @@ -76,14 +73,15 @@ static void SetupButton(const QAction* action, THUMBBUTTON* button) { button->dwMask = THUMBBUTTONMASK(THB_FLAGS); } } -#endif // Q_OS_WIN32 +#endif // Q_OS_WIN32 void Windows7ThumbBar::HandleWinEvent(MSG* msg) { #ifdef Q_OS_WIN32 if (button_created_message_id_ == 0) { // Compute the value for the TaskbarButtonCreated message button_created_message_id_ = RegisterWindowMessage("TaskbarButtonCreated"); - qLog(Debug) << "TaskbarButtonCreated message ID registered" << button_created_message_id_; + qLog(Debug) << "TaskbarButtonCreated message ID registered" + << button_created_message_id_; } if (msg->message == button_created_message_id_) { @@ -97,19 +95,25 @@ void Windows7ThumbBar::HandleWinEvent(MSG* msg) { } // Copied from win7 SDK shobjidl.h - static const GUID CLSID_ITaskbarList ={ 0x56FDF344,0xFD6D,0x11d0,{0x95,0x8A,0x00,0x60,0x97,0xC9,0xA0,0x90}}; + static const GUID CLSID_ITaskbarList = { + 0x56FDF344, + 0xFD6D, + 0x11d0, + {0x95, 0x8A, 0x00, 0x60, 0x97, 0xC9, 0xA0, 0x90}}; // Create the taskbar list hr = CoCreateInstance(CLSID_ITaskbarList, nullptr, CLSCTX_ALL, - IID_ITaskbarList3, (void**) &taskbar_list_); + IID_ITaskbarList3, (void**)&taskbar_list_); if (hr != S_OK) { - qLog(Warning) << "Error creating the ITaskbarList3 interface" << hex << DWORD (hr); + qLog(Warning) << "Error creating the ITaskbarList3 interface" << hex + << DWORD(hr); return; } - ITaskbarList3* taskbar_list = reinterpret_cast(taskbar_list_); + ITaskbarList3* taskbar_list = + reinterpret_cast(taskbar_list_); hr = taskbar_list->HrInit(); if (hr != S_OK) { - qLog(Warning) << "Error initialising taskbar list" << hex << DWORD (hr); + qLog(Warning) << "Error initialising taskbar list" << hex << DWORD(hr); taskbar_list->Release(); taskbar_list_ = nullptr; return; @@ -118,7 +122,7 @@ void Windows7ThumbBar::HandleWinEvent(MSG* msg) { // Add the buttons qLog(Debug) << "Initialising" << actions_.count() << "buttons"; THUMBBUTTON buttons[kMaxButtonCount]; - for (int i=0 ; iiId = i; @@ -126,12 +130,11 @@ void Windows7ThumbBar::HandleWinEvent(MSG* msg) { } qLog(Debug) << "Adding buttons"; - hr = taskbar_list->ThumbBarAddButtons(widget_->winId(), actions_.count(), buttons); - if (hr != S_OK) - qLog(Debug) << "Failed to add buttons" << hex << DWORD (hr); + hr = taskbar_list->ThumbBarAddButtons(widget_->winId(), actions_.count(), + buttons); + if (hr != S_OK) qLog(Debug) << "Failed to add buttons" << hex << DWORD(hr); for (int i = 0; i < actions_.count(); i++) { - if (buttons[i].hIcon > 0) - DestroyIcon (buttons[i].hIcon); + if (buttons[i].hIcon > 0) DestroyIcon(buttons[i].hIcon); } } else if (msg->message == WM_COMMAND) { const int button_id = LOWORD(msg->wParam); @@ -143,26 +146,25 @@ void Windows7ThumbBar::HandleWinEvent(MSG* msg) { } } } -#endif // Q_OS_WIN32 +#endif // Q_OS_WIN32 } void Windows7ThumbBar::ActionChanged() { #ifdef Q_OS_WIN32 - if (!taskbar_list_) - return; + if (!taskbar_list_) return; ITaskbarList3* taskbar_list = reinterpret_cast(taskbar_list_); THUMBBUTTON buttons[kMaxButtonCount]; - for (int i=0 ; iiId = i; SetupButton(action, button); - if (buttons->hIcon > 0) - DestroyIcon(buttons->hIcon); + if (buttons->hIcon > 0) DestroyIcon(buttons->hIcon); } - taskbar_list->ThumbBarUpdateButtons(widget_->winId(), actions_.count(), buttons); -#endif // Q_OS_WIN32 + taskbar_list->ThumbBarUpdateButtons(widget_->winId(), actions_.count(), + buttons); +#endif // Q_OS_WIN32 } diff --git a/src/ui/windows7thumbbar.h b/src/ui/windows7thumbbar.h index 70b7f03bc..731a87c67 100644 --- a/src/ui/windows7thumbbar.h +++ b/src/ui/windows7thumbbar.h @@ -22,13 +22,13 @@ #include #ifndef Q_OS_WIN32 - typedef void MSG; -#endif // Q_OS_WIN32 +typedef void MSG; +#endif // Q_OS_WIN32 class Windows7ThumbBar : public QObject { Q_OBJECT -public: + public: // Creates a list of buttons in the taskbar icon for this window. Does // nothing and is safe to use on other operating systems too. Windows7ThumbBar(QWidget* widget = 0); @@ -43,10 +43,10 @@ public: // Call this from the parent's winEvent() function. void HandleWinEvent(MSG* msg); -private slots: + private slots: void ActionChanged(); -private: + private: QWidget* widget_; QList actions_; @@ -56,4 +56,4 @@ private: void* taskbar_list_; }; -#endif // WINDOWS7THUMBBAR_H +#endif // WINDOWS7THUMBBAR_H diff --git a/src/visualisations/projectmpresetmodel.cpp b/src/visualisations/projectmpresetmodel.cpp index 77c684394..7065c43d0 100644 --- a/src/visualisations/projectmpresetmodel.cpp +++ b/src/visualisations/projectmpresetmodel.cpp @@ -20,75 +20,74 @@ #include "projectmvisualisation.h" #ifdef USE_SYSTEM_PROJECTM -# include +#include #else -# include "projectM.hpp" +#include "projectM.hpp" #endif #include #include -ProjectMPresetModel::ProjectMPresetModel(ProjectMVisualisation* vis, QObject *parent) - : QAbstractItemModel(parent), - vis_(vis) -{ +ProjectMPresetModel::ProjectMPresetModel(ProjectMVisualisation* vis, + QObject* parent) + : QAbstractItemModel(parent), vis_(vis) { // Find presets QDir preset_dir(vis_->preset_url()); - QStringList presets(preset_dir.entryList( - QStringList() << "*.milk" << "*.prjm", - QDir::Files | QDir::NoDotAndDotDot | QDir::Readable, - QDir::Name | QDir::IgnoreCase)); + QStringList presets( + preset_dir.entryList(QStringList() << "*.milk" + << "*.prjm", + QDir::Files | QDir::NoDotAndDotDot | QDir::Readable, + QDir::Name | QDir::IgnoreCase)); - foreach (const QString& filename, presets) { - all_presets_ << Preset(preset_dir.absoluteFilePath(filename), filename, false); + foreach(const QString & filename, presets) { + all_presets_ << Preset(preset_dir.absoluteFilePath(filename), filename, + false); } } int ProjectMPresetModel::rowCount(const QModelIndex&) const { - if (!vis_) - return 0; + if (!vis_) return 0; return all_presets_.count(); } -int ProjectMPresetModel::columnCount(const QModelIndex&) const { - return 1; -} +int ProjectMPresetModel::columnCount(const QModelIndex&) const { return 1; } -QModelIndex ProjectMPresetModel::index(int row, int column, const QModelIndex&) const { +QModelIndex ProjectMPresetModel::index(int row, int column, + const QModelIndex&) const { return createIndex(row, column); } -QModelIndex ProjectMPresetModel::parent(const QModelIndex &child) const { +QModelIndex ProjectMPresetModel::parent(const QModelIndex& child) const { return QModelIndex(); } -QVariant ProjectMPresetModel::data(const QModelIndex &index, int role) const { +QVariant ProjectMPresetModel::data(const QModelIndex& index, int role) const { switch (role) { - case Qt::DisplayRole: - return all_presets_[index.row()].name_; - case Qt::CheckStateRole: { - bool selected = all_presets_[index.row()].selected_; - return selected ? Qt::Checked : Qt::Unchecked; - } - case Role_Url: - return all_presets_[index.row()].path_; - default: - return QVariant(); + case Qt::DisplayRole: + return all_presets_[index.row()].name_; + case Qt::CheckStateRole: { + bool selected = all_presets_[index.row()].selected_; + return selected ? Qt::Checked : Qt::Unchecked; + } + case Role_Url: + return all_presets_[index.row()].path_; + default: + return QVariant(); } } -Qt::ItemFlags ProjectMPresetModel::flags(const QModelIndex &index) const { - if (!index.isValid()) - return QAbstractItemModel::flags(index); +Qt::ItemFlags ProjectMPresetModel::flags(const QModelIndex& index) const { + if (!index.isValid()) return QAbstractItemModel::flags(index); return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled; } -bool ProjectMPresetModel::setData(const QModelIndex &index, - const QVariant &value, int role) { +bool ProjectMPresetModel::setData(const QModelIndex& index, + const QVariant& value, int role) { if (role == Qt::CheckStateRole) { all_presets_[index.row()].selected_ = value.toBool(); - vis_->SetSelected(QStringList() << all_presets_[index.row()].path_, value.toBool()); + vis_->SetSelected(QStringList() << all_presets_[index.row()].path_, + value.toBool()); return true; } return false; @@ -100,30 +99,29 @@ void ProjectMPresetModel::SetImmediatePreset(const QModelIndex& index) { void ProjectMPresetModel::SelectAll() { QStringList paths; - for (int i=0 ; iSetSelected(paths, true); - emit dataChanged(index(0, 0), index(rowCount()-1, 0)); + emit dataChanged(index(0, 0), index(rowCount() - 1, 0)); } void ProjectMPresetModel::SelectNone() { vis_->ClearSelected(); - for (int i=0 ; i all_presets_; }; -#endif // PROJECTMPRESETMODEL_H +#endif // PROJECTMPRESETMODEL_H diff --git a/src/visualisations/projectmvisualisation.cpp b/src/visualisations/projectmvisualisation.cpp index 798b19179..3ef229d40 100644 --- a/src/visualisations/projectmvisualisation.cpp +++ b/src/visualisations/projectmvisualisation.cpp @@ -34,44 +34,45 @@ #include #ifdef USE_SYSTEM_PROJECTM -# include +#include #else -# include "projectM.hpp" +#include "projectM.hpp" #endif #ifdef Q_OS_MAC -# include "core/mac_startup.h" -# include +#include "core/mac_startup.h" +#include #else -# include +#include #endif -ProjectMVisualisation::ProjectMVisualisation(QObject *parent) - : QGraphicsScene(parent), - preset_model_(nullptr), - mode_(Random), - duration_(15), - texture_size_(512) { - connect(this, SIGNAL(sceneRectChanged(QRectF)), SLOT(SceneRectChanged(QRectF))); +ProjectMVisualisation::ProjectMVisualisation(QObject* parent) + : QGraphicsScene(parent), + preset_model_(nullptr), + mode_(Random), + duration_(15), + texture_size_(512) { + connect(this, SIGNAL(sceneRectChanged(QRectF)), + SLOT(SceneRectChanged(QRectF))); for (int i = 0; i < TOTAL_RATING_TYPES; ++i) default_rating_list_.push_back(3); } -ProjectMVisualisation::~ProjectMVisualisation() { -} +ProjectMVisualisation::~ProjectMVisualisation() {} void ProjectMVisualisation::InitProjectM() { // Find the projectM presets QStringList paths = QStringList() #ifdef USE_INSTALL_PREFIX - << CMAKE_INSTALL_PREFIX "/share/clementine/projectm-presets" - << CMAKE_INSTALL_PREFIX "/share/projectM/presets" + << CMAKE_INSTALL_PREFIX + "/share/clementine/projectm-presets" + << CMAKE_INSTALL_PREFIX "/share/projectM/presets" #endif - << "/usr/share/clementine/projectm-presets" - << "/usr/local/share/clementine/projectm-presets" - << "/usr/share/projectM/presets" - << "/usr/local/share/projectM/presets"; + << "/usr/share/clementine/projectm-presets" + << "/usr/local/share/clementine/projectm-presets" + << "/usr/share/projectM/presets" + << "/usr/local/share/projectM/presets"; #if defined(Q_OS_WIN32) paths.prepend(QCoreApplication::applicationDirPath() + "/projectm-presets"); @@ -80,9 +81,8 @@ void ProjectMVisualisation::InitProjectM() { #endif QString preset_path; - foreach (const QString& path, paths) { - if (!QFile::exists(path)) - continue; + foreach(const QString & path, paths) { + if (!QFile::exists(path)) continue; // Don't use empty directories if (QDir(path).entryList(QDir::Files | QDir::NoDotAndDotDot).isEmpty()) @@ -110,7 +110,7 @@ void ProjectMVisualisation::InitProjectM() { s.presetDuration = duration_; s.presetURL = preset_path.toStdString(); s.shuffleEnabled = true; - s.easterEgg = 0; // ?? + s.easterEgg = 0; // ?? s.softCutRatingsEnabled = false; s.menuFontURL = font_path.toStdString(); s.titleFontURL = font_path.toStdString(); @@ -127,8 +127,10 @@ void ProjectMVisualisation::InitProjectM() { if (font_path.isNull()) { qWarning("ProjectM presets could not be found, search path was:\n %s", paths.join("\n ").toLocal8Bit().constData()); - QMessageBox::warning(nullptr, tr("Missing projectM presets"), - tr("Clementine could not load any projectM visualisations. Check that you have installed Clementine properly.")); + QMessageBox::warning( + nullptr, tr("Missing projectM presets"), + tr("Clementine could not load any projectM visualisations. Check that " + "you have installed Clementine properly.")); } } @@ -145,23 +147,20 @@ void ProjectMVisualisation::drawBackground(QPainter* p, const QRectF&) { p->endNativePainting(); } -void ProjectMVisualisation::SceneRectChanged(const QRectF &rect) { - if (projectm_) - projectm_->projectM_resetGL(rect.width(), rect.height()); +void ProjectMVisualisation::SceneRectChanged(const QRectF& rect) { + if (projectm_) projectm_->projectM_resetGL(rect.width(), rect.height()); } void ProjectMVisualisation::SetTextureSize(int size) { texture_size_ = size; - if (projectm_) - projectm_->changeTextureSize(texture_size_); + if (projectm_) projectm_->changeTextureSize(texture_size_); } void ProjectMVisualisation::SetDuration(int seconds) { duration_ = seconds; - if (projectm_) - projectm_->changePresetDuration(duration_); + if (projectm_) projectm_->changePresetDuration(duration_); Save(); } @@ -170,16 +169,17 @@ void ProjectMVisualisation::ConsumeBuffer(GstBuffer* buffer, int) { const int samples_per_channel = GST_BUFFER_SIZE(buffer) / sizeof(short) / 2; const short* data = reinterpret_cast(GST_BUFFER_DATA(buffer)); - if (projectm_) - projectm_->pcm()->addPCM16Data(data, samples_per_channel); + if (projectm_) projectm_->pcm()->addPCM16Data(data, samples_per_channel); gst_buffer_unref(buffer); } -void ProjectMVisualisation::SetSelected(const QStringList& paths, bool selected) { - foreach (const QString& path, paths) { +void ProjectMVisualisation::SetSelected(const QStringList& paths, + bool selected) { + foreach(const QString & path, paths) { int index = IndexOfPreset(path); if (selected && index == -1) { - projectm_->addPresetURL(path.toStdString(), std::string(), default_rating_list_); + projectm_->addPresetURL(path.toStdString(), std::string(), + default_rating_list_); } else if (!selected && index != -1) { projectm_->removePreset(index); } @@ -193,10 +193,9 @@ void ProjectMVisualisation::ClearSelected() { Save(); } -int ProjectMVisualisation::IndexOfPreset(const QString &path) const { - for (uint i=0 ; igetPlaylistSize() ; ++i) { - if (QString::fromStdString(projectm_->getPresetURL(i)) == path) - return i; +int ProjectMVisualisation::IndexOfPreset(const QString& path) const { + for (uint i = 0; i < projectm_->getPlaylistSize(); ++i) { + if (QString::fromStdString(projectm_->getPresetURL(i)) == path) return i; } return -1; } @@ -211,17 +210,19 @@ void ProjectMVisualisation::Load() { projectm_->clearPlaylist(); switch (mode_) { case Random: - for (int i=0 ; iall_presets_.count() ; ++i) { - projectm_->addPresetURL(preset_model_->all_presets_[i].path_.toStdString(), - std::string(), default_rating_list_); + for (int i = 0; i < preset_model_->all_presets_.count(); ++i) { + projectm_->addPresetURL( + preset_model_->all_presets_[i].path_.toStdString(), std::string(), + default_rating_list_); preset_model_->all_presets_[i].selected_ = true; } break; case FromList: { QStringList paths(s.value("preset_paths").toStringList()); - foreach (const QString& path, paths) { - projectm_->addPresetURL(path.toStdString(), std::string(), default_rating_list_); + foreach(const QString & path, paths) { + projectm_->addPresetURL(path.toStdString(), std::string(), + default_rating_list_); preset_model_->MarkSelected(path, true); } } @@ -231,9 +232,9 @@ void ProjectMVisualisation::Load() { void ProjectMVisualisation::Save() { QStringList paths; - foreach (const ProjectMPresetModel::Preset& preset, preset_model_->all_presets_) { - if (preset.selected_) - paths << preset.path_; + foreach(const ProjectMPresetModel::Preset & preset, + preset_model_->all_presets_) { + if (preset.selected_) paths << preset.path_; } QSettings s; @@ -255,7 +256,8 @@ QString ProjectMVisualisation::preset_url() const { void ProjectMVisualisation::SetImmediatePreset(const QString& path) { int index = IndexOfPreset(path); if (index == -1) { - index = projectm_->addPresetURL(path.toStdString(), std::string(), default_rating_list_); + index = projectm_->addPresetURL(path.toStdString(), std::string(), + default_rating_list_); } projectm_->selectPreset(index, true); @@ -264,7 +266,5 @@ void ProjectMVisualisation::SetImmediatePreset(const QString& path) { void ProjectMVisualisation::Lock(bool lock) { projectm_->setPresetLock(lock); - if (!lock) - Load(); + if (!lock) Load(); } - diff --git a/src/visualisations/projectmvisualisation.h b/src/visualisations/projectmvisualisation.h index c8bd5be39..ec1266f54 100644 --- a/src/visualisations/projectmvisualisation.h +++ b/src/visualisations/projectmvisualisation.h @@ -34,14 +34,11 @@ class QTemporaryFile; class ProjectMVisualisation : public QGraphicsScene, public BufferConsumer { Q_OBJECT -public: - ProjectMVisualisation(QObject *parent = 0); + public: + ProjectMVisualisation(QObject* parent = 0); ~ProjectMVisualisation(); - enum Mode { - Random = 0, - FromList = 1, - }; + enum Mode { Random = 0, FromList = 1, }; QString preset_url() const; ProjectMPresetModel* preset_model() const { return preset_model_; } @@ -50,9 +47,9 @@ public: int duration() const { return duration_; } // BufferConsumer - void ConsumeBuffer(GstBuffer *buffer, int); + void ConsumeBuffer(GstBuffer* buffer, int); -public slots: + public slots: void SetTextureSize(int size); void SetDuration(int seconds); @@ -63,21 +60,21 @@ public slots: void Lock(bool lock); -protected: + protected: // QGraphicsScene - void drawBackground(QPainter *painter, const QRectF &rect); + void drawBackground(QPainter* painter, const QRectF& rect); -private slots: + private slots: void SceneRectChanged(const QRectF& rect); -private: + private: void InitProjectM(); void Load(); void Save(); int IndexOfPreset(const QString& path) const; -private: + private: std::unique_ptr projectm_; ProjectMPresetModel* preset_model_; Mode mode_; @@ -90,4 +87,4 @@ private: int texture_size_; }; -#endif // PROJECTMVISUALISATION_H +#endif // PROJECTMVISUALISATION_H diff --git a/src/visualisations/visualisationcontainer.cpp b/src/visualisations/visualisationcontainer.cpp index 14711c445..b371c625e 100644 --- a/src/visualisations/visualisationcontainer.cpp +++ b/src/visualisations/visualisationcontainer.cpp @@ -47,18 +47,17 @@ const int VisualisationContainer::kDefaultHeight = 512; const int VisualisationContainer::kDefaultFps = kHighFramerate; const int VisualisationContainer::kDefaultTextureSize = 512; -VisualisationContainer::VisualisationContainer(QWidget *parent) - : QGraphicsView(parent), - initialised_(false), - engine_(nullptr), - vis_(new ProjectMVisualisation(this)), - overlay_(new VisualisationOverlay), - selector_(new VisualisationSelector(this)), - overlay_proxy_(nullptr), - menu_(new QMenu(this)), - fps_(kDefaultFps), - size_(kDefaultTextureSize) -{ +VisualisationContainer::VisualisationContainer(QWidget* parent) + : QGraphicsView(parent), + initialised_(false), + engine_(nullptr), + vis_(new ProjectMVisualisation(this)), + overlay_(new VisualisationOverlay), + selector_(new VisualisationSelector(this)), + overlay_proxy_(nullptr), + menu_(new QMenu(this)), + fps_(kDefaultFps), + size_(kDefaultTextureSize) { QSettings s; s.beginGroup(kSettingsGroup); if (!restoreGeometry(s.value("geometry").toByteArray())) { @@ -87,7 +86,8 @@ void VisualisationContainer::Init() { // Add the overlay overlay_proxy_ = scene()->addWidget(overlay_); - connect(overlay_, SIGNAL(OpacityChanged(qreal)), SLOT(ChangeOverlayOpacity(qreal))); + connect(overlay_, SIGNAL(OpacityChanged(qreal)), + SLOT(ChangeOverlayOpacity(qreal))); connect(overlay_, SIGNAL(ShowPopupMenu(QPoint)), SLOT(ShowPopupMenu(QPoint))); ChangeOverlayOpacity(0.0); @@ -104,10 +104,14 @@ void VisualisationContainer::Init() { QMenu* fps_menu = menu_->addMenu(tr("Framerate")); QSignalMapper* fps_mapper = new QSignalMapper(this); QActionGroup* fps_group = new QActionGroup(this); - AddMenuItem(tr("Low (%1 fps)").arg(kLowFramerate), kLowFramerate, fps_, fps_group, fps_mapper); - AddMenuItem(tr("Medium (%1 fps)").arg(kMediumFramerate), kMediumFramerate, fps_, fps_group, fps_mapper); - AddMenuItem(tr("High (%1 fps)").arg(kHighFramerate), kHighFramerate, fps_, fps_group, fps_mapper); - AddMenuItem(tr("Super high (%1 fps)").arg(kSuperHighFramerate), kSuperHighFramerate, fps_, fps_group, fps_mapper); + AddMenuItem(tr("Low (%1 fps)").arg(kLowFramerate), kLowFramerate, fps_, + fps_group, fps_mapper); + AddMenuItem(tr("Medium (%1 fps)").arg(kMediumFramerate), kMediumFramerate, + fps_, fps_group, fps_mapper); + AddMenuItem(tr("High (%1 fps)").arg(kHighFramerate), kHighFramerate, fps_, + fps_group, fps_mapper); + AddMenuItem(tr("Super high (%1 fps)").arg(kSuperHighFramerate), + kSuperHighFramerate, fps_, fps_group, fps_mapper); fps_menu->addActions(fps_group->actions()); connect(fps_mapper, SIGNAL(mapped(int)), SLOT(SetFps(int))); @@ -115,21 +119,25 @@ void VisualisationContainer::Init() { QSignalMapper* quality_mapper = new QSignalMapper(this); QActionGroup* quality_group = new QActionGroup(this); AddMenuItem(tr("Low (256x256)"), 256, size_, quality_group, quality_mapper); - AddMenuItem(tr("Medium (512x512)"), 512, size_, quality_group, quality_mapper); - AddMenuItem(tr("High (1024x1024)"), 1024, size_, quality_group, quality_mapper); - AddMenuItem(tr("Super high (2048x2048)"), 2048, size_, quality_group, quality_mapper); + AddMenuItem(tr("Medium (512x512)"), 512, size_, quality_group, + quality_mapper); + AddMenuItem(tr("High (1024x1024)"), 1024, size_, quality_group, + quality_mapper); + AddMenuItem(tr("Super high (2048x2048)"), 2048, size_, quality_group, + quality_mapper); quality_menu->addActions(quality_group->actions()); connect(quality_mapper, SIGNAL(mapped(int)), SLOT(SetQuality(int))); menu_->addAction(tr("Select visualizations..."), selector_, SLOT(show())); menu_->addSeparator(); - menu_->addAction(IconLoader::Load("application-exit"), tr("Close visualization"), - this, SLOT(hide())); + menu_->addAction(IconLoader::Load("application-exit"), + tr("Close visualization"), this, SLOT(hide())); } -void VisualisationContainer::AddMenuItem(const QString &name, int value, int def, - QActionGroup* group, QSignalMapper *mapper) { +void VisualisationContainer::AddMenuItem(const QString& name, int value, + int def, QActionGroup* group, + QSignalMapper* mapper) { QAction* action = group->addAction(name); action->setCheckable(true); action->setChecked(value == def); @@ -140,8 +148,7 @@ void VisualisationContainer::AddMenuItem(const QString &name, int value, int def void VisualisationContainer::SetEngine(GstEngine* engine) { engine_ = engine; - if (isVisible()) - engine_->AddBufferConsumer(vis_); + if (isVisible()) engine_->AddBufferConsumer(vis_); } void VisualisationContainer::showEvent(QShowEvent* e) { @@ -149,8 +156,9 @@ void VisualisationContainer::showEvent(QShowEvent* e) { if (!QGLFormat::hasOpenGL()) { hide(); QMessageBox::warning(this, tr("Clementine Visualization"), - tr("Your system is missing OpenGL support, visualizations are unavailable."), - QMessageBox::Close); + tr("Your system is missing OpenGL support, " + "visualizations are unavailable."), + QMessageBox::Close); return; } Init(); @@ -160,16 +168,14 @@ void VisualisationContainer::showEvent(QShowEvent* e) { QGraphicsView::showEvent(e); update_timer_.start(1000 / fps_, this); - if (engine_) - engine_->AddBufferConsumer(vis_); + if (engine_) engine_->AddBufferConsumer(vis_); } void VisualisationContainer::hideEvent(QHideEvent* e) { QGraphicsView::hideEvent(e); update_timer_.stop(); - if (engine_) - engine_->RemoveBufferConsumer(vis_); + if (engine_) engine_->RemoveBufferConsumer(vis_); } void VisualisationContainer::resizeEvent(QResizeEvent* e) { @@ -184,27 +190,25 @@ void VisualisationContainer::SizeChanged() { s.setValue("geometry", saveGeometry()); // Resize the scene - if (scene()) - scene()->setSceneRect(QRect(QPoint(0, 0), size())); + if (scene()) scene()->setSceneRect(QRect(QPoint(0, 0), size())); // Resize the overlay - if (overlay_) - overlay_->resize(size()); + if (overlay_) overlay_->resize(size()); } void VisualisationContainer::timerEvent(QTimerEvent* e) { QGraphicsView::timerEvent(e); - if (e->timerId() == update_timer_.timerId()) - scene()->update(); + if (e->timerId() == update_timer_.timerId()) scene()->update(); } -void VisualisationContainer::SetActions(QAction *previous, QAction *play_pause, - QAction *stop, QAction *next) { +void VisualisationContainer::SetActions(QAction* previous, QAction* play_pause, + QAction* stop, QAction* next) { overlay_->SetActions(previous, play_pause, stop, next); } -void VisualisationContainer::SongMetadataChanged(const Song &metadata) { - overlay_->SetSongTitle(QString("%1 - %2").arg(metadata.artist(), metadata.title())); +void VisualisationContainer::SongMetadataChanged(const Song& metadata) { + overlay_->SetSongTitle( + QString("%1 - %2").arg(metadata.artist(), metadata.title())); } void VisualisationContainer::Stopped() { @@ -241,14 +245,13 @@ void VisualisationContainer::mouseDoubleClickEvent(QMouseEvent* e) { ToggleFullscreen(); } -void VisualisationContainer::contextMenuEvent(QContextMenuEvent *event) { +void VisualisationContainer::contextMenuEvent(QContextMenuEvent* event) { QGraphicsView::contextMenuEvent(event); ShowPopupMenu(event->pos()); } -void VisualisationContainer::keyReleaseEvent(QKeyEvent *event) { - if (event->matches(QKeySequence::Close) || - event->key() == Qt::Key_Escape) { +void VisualisationContainer::keyReleaseEvent(QKeyEvent* event) { + if (event->matches(QKeySequence::Close) || event->key() == Qt::Key_Escape) { if (isFullScreen()) ToggleFullscreen(); else @@ -279,7 +282,7 @@ void VisualisationContainer::SetFps(int fps) { update_timer_.start(1000 / fps_, this); } -void VisualisationContainer::ShowPopupMenu(const QPoint &pos) { +void VisualisationContainer::ShowPopupMenu(const QPoint& pos) { menu_->popup(mapToGlobal(pos)); } diff --git a/src/visualisations/visualisationcontainer.h b/src/visualisations/visualisationcontainer.h index 345e23c55..6154d4251 100644 --- a/src/visualisations/visualisationcontainer.h +++ b/src/visualisations/visualisationcontainer.h @@ -35,7 +35,7 @@ class QActionGroup; class VisualisationContainer : public QGraphicsView { Q_OBJECT -public: + public: VisualisationContainer(QWidget* parent = 0); static const int kLowFramerate; @@ -50,14 +50,14 @@ public: static const int kDefaultTextureSize; void SetEngine(GstEngine* engine); - void SetActions(QAction* previous, QAction* play_pause, - QAction* stop, QAction* next); + void SetActions(QAction* previous, QAction* play_pause, QAction* stop, + QAction* next); -public slots: + public slots: void SongMetadataChanged(const Song& metadata); void Stopped(); -protected: + protected: // QWidget void showEvent(QShowEvent* e); void hideEvent(QHideEvent* e); @@ -67,24 +67,24 @@ protected: void enterEvent(QEvent* e); void leaveEvent(QEvent* e); void mouseDoubleClickEvent(QMouseEvent* e); - void contextMenuEvent(QContextMenuEvent *event); - void keyReleaseEvent(QKeyEvent *event); + void contextMenuEvent(QContextMenuEvent* event); + void keyReleaseEvent(QKeyEvent* event); -private: + private: void Init(); void SizeChanged(); - void AddMenuItem(const QString& name, int value, int def, - QActionGroup* group, QSignalMapper* mapper); + void AddMenuItem(const QString& name, int value, int def, QActionGroup* group, + QSignalMapper* mapper); -private slots: + private slots: void ChangeOverlayOpacity(qreal value); void ShowPopupMenu(const QPoint& pos); void ToggleFullscreen(); void SetFps(int fps); void SetQuality(int size); -private: + private: bool initialised_; GstEngine* engine_; @@ -102,4 +102,4 @@ private: int size_; }; -#endif // VISUALISATIONCONTAINER_H +#endif // VISUALISATIONCONTAINER_H diff --git a/src/visualisations/visualisationoverlay.cpp b/src/visualisations/visualisationoverlay.cpp index 89c9bda32..6df8d31c8 100644 --- a/src/visualisations/visualisationoverlay.cpp +++ b/src/visualisations/visualisationoverlay.cpp @@ -28,12 +28,11 @@ const int VisualisationOverlay::kFadeDuration = 500; const int VisualisationOverlay::kFadeTimeout = 5000; -VisualisationOverlay::VisualisationOverlay(QWidget *parent) - : QWidget(parent), - ui_(new Ui_VisualisationOverlay), - fade_timeline_(new QTimeLine(kFadeDuration, this)), - visible_(false) -{ +VisualisationOverlay::VisualisationOverlay(QWidget* parent) + : QWidget(parent), + ui_(new Ui_VisualisationOverlay), + fade_timeline_(new QTimeLine(kFadeDuration, this)), + visible_(false) { ui_->setupUi(this); setAttribute(Qt::WA_TranslucentBackground); @@ -42,14 +41,14 @@ VisualisationOverlay::VisualisationOverlay(QWidget *parent) ui_->settings->setIcon(IconLoader::Load("configure")); connect(ui_->settings, SIGNAL(clicked()), SLOT(ShowSettingsMenu())); - connect(fade_timeline_, SIGNAL(valueChanged(qreal)), SIGNAL(OpacityChanged(qreal))); + connect(fade_timeline_, SIGNAL(valueChanged(qreal)), + SIGNAL(OpacityChanged(qreal))); } -VisualisationOverlay::~VisualisationOverlay() { - delete ui_; -} +VisualisationOverlay::~VisualisationOverlay() { delete ui_; } -QGraphicsProxyWidget* VisualisationOverlay::title(QGraphicsProxyWidget* proxy) const { +QGraphicsProxyWidget* VisualisationOverlay::title(QGraphicsProxyWidget* proxy) + const { return proxy->createProxyForChildWidget(ui_->song_title); } @@ -62,7 +61,8 @@ void VisualisationOverlay::SetActions(QAction* previous, QAction* play_pause, } void VisualisationOverlay::ShowSettingsMenu() { - emit ShowPopupMenu(ui_->settings->mapToGlobal(ui_->settings->rect().bottomLeft())); + emit ShowPopupMenu( + ui_->settings->mapToGlobal(ui_->settings->rect().bottomLeft())); } void VisualisationOverlay::timerEvent(QTimerEvent* e) { @@ -76,12 +76,10 @@ void VisualisationOverlay::timerEvent(QTimerEvent* e) { void VisualisationOverlay::SetVisible(bool visible) { // If we're showing the overlay, then fade out again in a little while fade_out_timeout_.stop(); - if (visible) - fade_out_timeout_.start(kFadeTimeout, this); + if (visible) fade_out_timeout_.start(kFadeTimeout, this); // Don't change to the state we're in already - if (visible == visible_) - return; + if (visible == visible_) return; visible_ = visible; // If there's already another fader running then start from the same time @@ -91,12 +89,13 @@ void VisualisationOverlay::SetVisible(bool visible) { start_time = fade_timeline_->currentTime(); fade_timeline_->stop(); - fade_timeline_->setDirection(visible ? QTimeLine::Forward : QTimeLine::Backward); + fade_timeline_->setDirection(visible ? QTimeLine::Forward + : QTimeLine::Backward); fade_timeline_->setCurrentTime(start_time); fade_timeline_->resume(); } -void VisualisationOverlay::SetSongTitle(const QString &title) { +void VisualisationOverlay::SetSongTitle(const QString& title) { ui_->song_title->setText(title); SetVisible(true); } diff --git a/src/visualisations/visualisationoverlay.h b/src/visualisations/visualisationoverlay.h index cc60d8d67..aa13f4257 100644 --- a/src/visualisations/visualisationoverlay.h +++ b/src/visualisations/visualisationoverlay.h @@ -28,7 +28,7 @@ class QTimeLine; class VisualisationOverlay : public QWidget { Q_OBJECT -public: + public: VisualisationOverlay(QWidget* parent = 0); ~VisualisationOverlay(); @@ -37,25 +37,25 @@ public: QGraphicsProxyWidget* title(QGraphicsProxyWidget* proxy) const; - void SetActions(QAction* previous, QAction* play_pause, - QAction* stop, QAction* next); + void SetActions(QAction* previous, QAction* play_pause, QAction* stop, + QAction* next); void SetSongTitle(const QString& title); -public slots: + public slots: void SetVisible(bool visible); signals: void OpacityChanged(qreal value); void ShowPopupMenu(const QPoint& pos); -protected: + protected: // QWidget - void timerEvent(QTimerEvent *); + void timerEvent(QTimerEvent*); -private slots: + private slots: void ShowSettingsMenu(); -private: + private: Ui_VisualisationOverlay* ui_; QTimeLine* fade_timeline_; @@ -63,4 +63,4 @@ private: bool visible_; }; -#endif // VISUALISATIONOVERLAY_H +#endif // VISUALISATIONOVERLAY_H diff --git a/src/visualisations/visualisationselector.cpp b/src/visualisations/visualisationselector.cpp index b352e9b62..beaeb9323 100644 --- a/src/visualisations/visualisationselector.cpp +++ b/src/visualisations/visualisationselector.cpp @@ -24,22 +24,19 @@ #include #ifdef USE_SYSTEM_PROJECTM -# include +#include #else -# include "projectM.hpp" +#include "projectM.hpp" #endif -VisualisationSelector::VisualisationSelector(QWidget *parent) - : QDialog(parent), - ui_(new Ui_VisualisationSelector), - vis_(nullptr) -{ +VisualisationSelector::VisualisationSelector(QWidget* parent) + : QDialog(parent), ui_(new Ui_VisualisationSelector), vis_(nullptr) { ui_->setupUi(this); select_all_ = ui_->buttonBox->addButton(tr("Select All"), QDialogButtonBox::ActionRole); - select_none_ = - ui_->buttonBox->addButton(tr("Select None"), QDialogButtonBox::ActionRole); + select_none_ = ui_->buttonBox->addButton(tr("Select None"), + QDialogButtonBox::ActionRole); connect(select_all_, SIGNAL(clicked()), SLOT(SelectAll())); connect(select_none_, SIGNAL(clicked()), SLOT(SelectNone())); select_all_->setEnabled(false); @@ -48,17 +45,17 @@ VisualisationSelector::VisualisationSelector(QWidget *parent) connect(ui_->mode, SIGNAL(currentIndexChanged(int)), SLOT(ModeChanged(int))); } -VisualisationSelector::~VisualisationSelector() { - delete ui_; -} +VisualisationSelector::~VisualisationSelector() { delete ui_; } -void VisualisationSelector::showEvent(QShowEvent *) { +void VisualisationSelector::showEvent(QShowEvent*) { if (!ui_->list->model()) { ui_->delay->setValue(vis_->duration()); ui_->list->setModel(vis_->preset_model()); - connect(ui_->list->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), + connect(ui_->list->selectionModel(), + SIGNAL(currentChanged(QModelIndex, QModelIndex)), vis_->preset_model(), SLOT(SetImmediatePreset(QModelIndex))); - connect(ui_->delay, SIGNAL(valueChanged(int)), vis_, SLOT(SetDuration(int))); + connect(ui_->delay, SIGNAL(valueChanged(int)), vis_, + SLOT(SetDuration(int))); ui_->mode->setCurrentIndex(vis_->mode()); } @@ -66,9 +63,7 @@ void VisualisationSelector::showEvent(QShowEvent *) { vis_->Lock(true); } -void VisualisationSelector::hideEvent(QHideEvent *) { - vis_->Lock(false); -} +void VisualisationSelector::hideEvent(QHideEvent*) { vis_->Lock(false); } void VisualisationSelector::ModeChanged(int mode) { bool enabled = mode == 1; @@ -79,10 +74,6 @@ void VisualisationSelector::ModeChanged(int mode) { vis_->SetMode(ProjectMVisualisation::Mode(mode)); } -void VisualisationSelector::SelectAll() { - vis_->preset_model()->SelectAll(); -} +void VisualisationSelector::SelectAll() { vis_->preset_model()->SelectAll(); } -void VisualisationSelector::SelectNone() { - vis_->preset_model()->SelectNone(); -} +void VisualisationSelector::SelectNone() { vis_->preset_model()->SelectNone(); } diff --git a/src/visualisations/visualisationselector.h b/src/visualisations/visualisationselector.h index c7262f737..a6732c24b 100644 --- a/src/visualisations/visualisationselector.h +++ b/src/visualisations/visualisationselector.h @@ -25,22 +25,22 @@ class Ui_VisualisationSelector; class VisualisationSelector : public QDialog { Q_OBJECT -public: + public: VisualisationSelector(QWidget* parent = 0); ~VisualisationSelector(); void SetVisualisation(ProjectMVisualisation* vis) { vis_ = vis; } -protected: - void showEvent(QShowEvent *); - void hideEvent(QHideEvent *); + protected: + void showEvent(QShowEvent*); + void hideEvent(QHideEvent*); -private slots: + private slots: void ModeChanged(int mode); void SelectAll(); void SelectNone(); -private: + private: Ui_VisualisationSelector* ui_; QPushButton* select_all_; QPushButton* select_none_; @@ -48,4 +48,4 @@ private: ProjectMVisualisation* vis_; }; -#endif // VISUALISATIONSELECTOR_H +#endif // VISUALISATIONSELECTOR_H diff --git a/src/widgets/autoexpandingtreeview.cpp b/src/widgets/autoexpandingtreeview.cpp index 7b2359248..d5cf2152e 100644 --- a/src/widgets/autoexpandingtreeview.cpp +++ b/src/widgets/autoexpandingtreeview.cpp @@ -23,18 +23,18 @@ const int AutoExpandingTreeView::kRowsToShow = 50; -AutoExpandingTreeView::AutoExpandingTreeView(QWidget *parent) - : QTreeView(parent), - auto_open_(true), - expand_on_reset_(true), - add_on_double_click_(true), - ignore_next_click_(false) -{ +AutoExpandingTreeView::AutoExpandingTreeView(QWidget* parent) + : QTreeView(parent), + auto_open_(true), + expand_on_reset_(true), + add_on_double_click_(true), + ignore_next_click_(false) { setExpandsOnDoubleClick(false); connect(this, SIGNAL(expanded(QModelIndex)), SLOT(ItemExpanded(QModelIndex))); connect(this, SIGNAL(clicked(QModelIndex)), SLOT(ItemClicked(QModelIndex))); - connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(ItemDoubleClicked(QModelIndex))); + connect(this, SIGNAL(doubleClicked(QModelIndex)), + SLOT(ItemDoubleClicked(QModelIndex))); } void AutoExpandingTreeView::reset() { @@ -46,28 +46,25 @@ void AutoExpandingTreeView::reset() { } } -void AutoExpandingTreeView::RecursivelyExpand(const QModelIndex &index) { +void AutoExpandingTreeView::RecursivelyExpand(const QModelIndex& index) { int rows = model()->rowCount(index); RecursivelyExpand(index, &rows); } -bool AutoExpandingTreeView::RecursivelyExpand(const QModelIndex& index, int* count) { - if (!CanRecursivelyExpand(index)) - return true; +bool AutoExpandingTreeView::RecursivelyExpand(const QModelIndex& index, + int* count) { + if (!CanRecursivelyExpand(index)) return true; - if (model()->canFetchMore(index)) - model()->fetchMore(index); + if (model()->canFetchMore(index)) model()->fetchMore(index); int children = model()->rowCount(index); - if (*count + children > kRowsToShow) - return false; + if (*count + children > kRowsToShow) return false; expand(index); *count += children; - for (int i=0 ; iindex(i, 0, index), count)) - return false; + for (int i = 0; i < children; ++i) { + if (!RecursivelyExpand(model()->index(i, 0, index), count)) return false; } return true; @@ -106,7 +103,7 @@ void AutoExpandingTreeView::mousePressEvent(QMouseEvent* event) { QTreeView::mousePressEvent(event); - //enqueue to playlist with middleClick + // enqueue to playlist with middleClick if (event->button() == Qt::MidButton) { QMimeData* data = model()->mimeData(selectedIndexes()); if (MimeData* mime_data = qobject_cast(data)) { @@ -120,8 +117,7 @@ void AutoExpandingTreeView::keyPressEvent(QKeyEvent* e) { switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: - if (currentIndex().isValid()) - emit doubleClicked(currentIndex()); + if (currentIndex().isValid()) emit doubleClicked(currentIndex()); e->accept(); break; diff --git a/src/widgets/autoexpandingtreeview.h b/src/widgets/autoexpandingtreeview.h index 1007dd439..a113a174c 100644 --- a/src/widgets/autoexpandingtreeview.h +++ b/src/widgets/autoexpandingtreeview.h @@ -23,7 +23,7 @@ class AutoExpandingTreeView : public QTreeView { Q_OBJECT -public: + public: AutoExpandingTreeView(QWidget* parent = 0); static const int kRowsToShow; @@ -32,8 +32,8 @@ public: void SetExpandOnReset(bool v) { expand_on_reset_ = v; } void SetAddOnDoubleClick(bool v) { add_on_double_click_ = v; } -public slots: - void RecursivelyExpand(const QModelIndex &index); + public slots: + void RecursivelyExpand(const QModelIndex& index); void UpAndFocus(); void DownAndFocus(); @@ -41,7 +41,7 @@ signals: void AddToPlaylistSignal(QMimeData* data); void FocusOnFilterSignal(QKeyEvent* event); -protected: + protected: // QAbstractItemView void reset(); @@ -49,17 +49,19 @@ protected: void mousePressEvent(QMouseEvent* event); void keyPressEvent(QKeyEvent* event); - virtual bool CanRecursivelyExpand(const QModelIndex& index) const { return true; } + virtual bool CanRecursivelyExpand(const QModelIndex& index) const { + return true; + } -private slots: + private slots: void ItemExpanded(const QModelIndex& index); void ItemClicked(const QModelIndex& index); void ItemDoubleClicked(const QModelIndex& index); -private: + private: bool RecursivelyExpand(const QModelIndex& index, int* count); -private: + private: bool auto_open_; bool expand_on_reset_; bool add_on_double_click_; @@ -67,4 +69,4 @@ private: bool ignore_next_click_; }; -#endif // AUTOEXPANDINGTREEVIEW_H +#endif // AUTOEXPANDINGTREEVIEW_H diff --git a/src/widgets/busyindicator.cpp b/src/widgets/busyindicator.cpp index 8b4c35c01..cc627a130 100644 --- a/src/widgets/busyindicator.cpp +++ b/src/widgets/busyindicator.cpp @@ -21,18 +21,16 @@ #include BusyIndicator::BusyIndicator(const QString& text, QWidget* parent) - : QWidget(parent) { + : QWidget(parent) { Init(text); } -BusyIndicator::BusyIndicator(QWidget* parent) - : QWidget(parent) { +BusyIndicator::BusyIndicator(QWidget* parent) : QWidget(parent) { Init(QString::null); } void BusyIndicator::Init(const QString& text) { - movie_ = new QMovie(":spinner.gif"), - label_ = new QLabel; + movie_ = new QMovie(":spinner.gif"), label_ = new QLabel; QLabel* icon = new QLabel; icon->setMovie(movie_); @@ -50,24 +48,15 @@ void BusyIndicator::Init(const QString& text) { set_text(text); } -BusyIndicator::~BusyIndicator() { - delete movie_; -} +BusyIndicator::~BusyIndicator() { delete movie_; } -void BusyIndicator::showEvent(QShowEvent*) { - movie_->start(); -} +void BusyIndicator::showEvent(QShowEvent*) { movie_->start(); } -void BusyIndicator::hideEvent(QHideEvent*) { - movie_->stop(); -} +void BusyIndicator::hideEvent(QHideEvent*) { movie_->stop(); } void BusyIndicator::set_text(const QString& text) { label_->setText(text); label_->setVisible(!text.isEmpty()); } -QString BusyIndicator::text() const { - return label_->text(); -} - +QString BusyIndicator::text() const { return label_->text(); } diff --git a/src/widgets/busyindicator.h b/src/widgets/busyindicator.h index 783a2a187..d4d62fc70 100644 --- a/src/widgets/busyindicator.h +++ b/src/widgets/busyindicator.h @@ -46,4 +46,4 @@ class BusyIndicator : public QWidget { QLabel* label_; }; -#endif // BUSYINDICATOR_H +#endif // BUSYINDICATOR_H diff --git a/src/widgets/clickablelabel.cpp b/src/widgets/clickablelabel.cpp index be9517733..e8d65753c 100644 --- a/src/widgets/clickablelabel.cpp +++ b/src/widgets/clickablelabel.cpp @@ -17,10 +17,7 @@ #include "clickablelabel.h" -ClickableLabel::ClickableLabel(QWidget* parent) - : QLabel(parent) -{ -} +ClickableLabel::ClickableLabel(QWidget* parent) : QLabel(parent) {} void ClickableLabel::mousePressEvent(QMouseEvent* event) { emit Clicked(); diff --git a/src/widgets/clickablelabel.h b/src/widgets/clickablelabel.h index 6de1d62cb..9d8515055 100644 --- a/src/widgets/clickablelabel.h +++ b/src/widgets/clickablelabel.h @@ -23,14 +23,14 @@ class ClickableLabel : public QLabel { Q_OBJECT -public: + public: ClickableLabel(QWidget* parent = 0); signals: void Clicked(); -protected: + protected: void mousePressEvent(QMouseEvent* event); }; -#endif // CLICKABLELABEL_H +#endif // CLICKABLELABEL_H diff --git a/src/widgets/didyoumean.cpp b/src/widgets/didyoumean.cpp index d3f0f2b5a..f54738db9 100644 --- a/src/widgets/didyoumean.cpp +++ b/src/widgets/didyoumean.cpp @@ -27,12 +27,12 @@ const int DidYouMean::kPadding = 3; DidYouMean::DidYouMean(QWidget* buddy, QWidget* parent) - : QWidget(parent, Qt::ToolTip), - buddy_(buddy), - close_(new QToolButton(this)), - normal_font_(font()), - correction_font_(font()), - press_enter_font_(font()) { + : QWidget(parent, Qt::ToolTip), + buddy_(buddy), + close_(new QToolButton(this)), + normal_font_(font()), + correction_font_(font()), + press_enter_font_(font()) { // Close icon close_->setToolTip(tr("Close")); close_->setIcon(QIcon(":/trolltech/styles/macstyle/images/closedock-16.png")); @@ -82,7 +82,7 @@ bool DidYouMean::eventFilter(QObject* object, QEvent* event) { case Qt::Key_Return: case Qt::Key_Enter: emit Accepted(correction_); - // fallthrough + // fallthrough case Qt::Key_Escape: hide(); return true; @@ -105,9 +105,7 @@ bool DidYouMean::eventFilter(QObject* object, QEvent* event) { return QObject::eventFilter(object, event); } -void DidYouMean::showEvent(QShowEvent*) { - UpdateGeometry(); -} +void DidYouMean::showEvent(QShowEvent*) { UpdateGeometry(); } void DidYouMean::UpdateGeometry() { const int text_height = fontMetrics().height(); @@ -118,10 +116,8 @@ void DidYouMean::UpdateGeometry() { // size(close button), so the "Did you mean" widget is always fully displayed resize(QSize(did_you_mean_size_ + - QFontMetrics(correction_font_).width(correction_ + " ") + - press_enter_size_ + - kPadding * 6 + - close_->width(), + QFontMetrics(correction_font_).width(correction_ + " ") + + press_enter_size_ + kPadding * 6 + close_->width(), height)); close_->move(kPadding, kPadding); @@ -133,17 +129,15 @@ void DidYouMean::paintEvent(QPaintEvent*) { // Draw the background QColor bg(palette().color(QPalette::Inactive, QPalette::ToolTipBase)); - p.fillRect(0, 0, width()-1, height()-1, bg); + p.fillRect(0, 0, width() - 1, height() - 1, bg); // Border p.setPen(Qt::black); - p.drawRect(0, 0, width()-1, height()-1); + p.drawRect(0, 0, width() - 1, height() - 1); // Text rectangle - QRect text_rect(kPadding + close_->width() + kPadding, - kPadding, - rect().width() - kPadding, - rect().height() - kPadding); + QRect text_rect(kPadding + close_->width() + kPadding, kPadding, + rect().width() - kPadding, rect().height() - kPadding); // Text p.setFont(normal_font_); @@ -152,7 +146,8 @@ void DidYouMean::paintEvent(QPaintEvent*) { p.setFont(correction_font_); p.drawText(text_rect, Qt::AlignLeft | Qt::AlignVCenter, correction_); - text_rect.setLeft(text_rect.left() + p.fontMetrics().width(correction_ + " ")); + text_rect.setLeft(text_rect.left() + + p.fontMetrics().width(correction_ + " ")); p.setPen(palette().color(QPalette::Disabled, QPalette::Text)); p.setFont(press_enter_font_); diff --git a/src/widgets/didyoumean.h b/src/widgets/didyoumean.h index 30fd98cae..b73ec420c 100644 --- a/src/widgets/didyoumean.h +++ b/src/widgets/didyoumean.h @@ -25,28 +25,28 @@ class QToolButton; class DidYouMean : public QWidget { Q_OBJECT -public: + public: DidYouMean(QWidget* buddy, QWidget* parent); static const int kPadding; -public slots: + public slots: void SetCorrection(const QString& correction); void Show(const QString& correction); signals: void Accepted(const QString& correction); -protected: + protected: void paintEvent(QPaintEvent*); void showEvent(QShowEvent*); void mouseReleaseEvent(QMouseEvent* e); bool eventFilter(QObject* object, QEvent* event); -private: + private: void UpdateGeometry(); -private: + private: QWidget* buddy_; QString correction_; @@ -65,4 +65,4 @@ private: int press_enter_size_; }; -#endif // DIDYOUMEAN_H +#endif // DIDYOUMEAN_H diff --git a/src/widgets/elidedlabel.cpp b/src/widgets/elidedlabel.cpp index c2b9f6f04..6f4d071df 100644 --- a/src/widgets/elidedlabel.cpp +++ b/src/widgets/elidedlabel.cpp @@ -17,19 +17,14 @@ #include "elidedlabel.h" -ElidedLabel::ElidedLabel(QWidget* parent) - : QLabel(parent) -{ -} +ElidedLabel::ElidedLabel(QWidget* parent) : QLabel(parent) {} void ElidedLabel::SetText(const QString& text) { text_ = text; UpdateText(); } -void ElidedLabel::resizeEvent(QResizeEvent*) { - UpdateText(); -} +void ElidedLabel::resizeEvent(QResizeEvent*) { UpdateText(); } void ElidedLabel::UpdateText() { setText(fontMetrics().elidedText(text_, Qt::ElideRight, width() - 5)); diff --git a/src/widgets/elidedlabel.h b/src/widgets/elidedlabel.h index d0e99939c..9d3bbf17e 100644 --- a/src/widgets/elidedlabel.h +++ b/src/widgets/elidedlabel.h @@ -23,20 +23,20 @@ class ElidedLabel : public QLabel { Q_OBJECT -public: + public: ElidedLabel(QWidget* parent = 0); -public slots: + public slots: void SetText(const QString& text); -protected: + protected: void resizeEvent(QResizeEvent* e); -private: + private: void UpdateText(); -private: + private: QString text_; }; -#endif // ELIDEDLABEL_H +#endif // ELIDEDLABEL_H diff --git a/src/widgets/equalizerslider.cpp b/src/widgets/equalizerslider.cpp index da6046e40..8a7bcc817 100644 --- a/src/widgets/equalizerslider.cpp +++ b/src/widgets/equalizerslider.cpp @@ -18,24 +18,16 @@ #include "equalizerslider.h" #include "ui_equalizerslider.h" -EqualizerSlider::EqualizerSlider(const QString& label, QWidget *parent) - : QWidget(parent), - ui_(new Ui_EqualizerSlider) -{ +EqualizerSlider::EqualizerSlider(const QString& label, QWidget* parent) + : QWidget(parent), ui_(new Ui_EqualizerSlider) { ui_->setupUi(this); ui_->label->setText(label); connect(ui_->slider, SIGNAL(valueChanged(int)), SIGNAL(ValueChanged(int))); } -EqualizerSlider::~EqualizerSlider() { - delete ui_; -} +EqualizerSlider::~EqualizerSlider() { delete ui_; } -int EqualizerSlider::value() const { - return ui_->slider->value(); -} +int EqualizerSlider::value() const { return ui_->slider->value(); } -void EqualizerSlider::set_value(int value) { - ui_->slider->setValue(value); -} +void EqualizerSlider::set_value(int value) { ui_->slider->setValue(value); } diff --git a/src/widgets/equalizerslider.h b/src/widgets/equalizerslider.h index b4d4b12fb..255d1e7ed 100644 --- a/src/widgets/equalizerslider.h +++ b/src/widgets/equalizerslider.h @@ -27,17 +27,17 @@ class EqualizerSlider : public QWidget { Q_OBJECT public: - EqualizerSlider(const QString& label, QWidget *parent = 0); + EqualizerSlider(const QString& label, QWidget* parent = 0); ~EqualizerSlider(); int value() const; void set_value(int value); - signals: +signals: void ValueChanged(int value); private: Ui_EqualizerSlider* ui_; }; -#endif // EQUALISERSLIDER_H +#endif // EQUALISERSLIDER_H diff --git a/src/widgets/errordialog.cpp b/src/widgets/errordialog.cpp index 60a863718..6b34aabba 100644 --- a/src/widgets/errordialog.cpp +++ b/src/widgets/errordialog.cpp @@ -18,27 +18,24 @@ #include "errordialog.h" #include "ui_errordialog.h" -ErrorDialog::ErrorDialog(QWidget *parent) - : QDialog(parent), - ui_(new Ui_ErrorDialog) -{ +ErrorDialog::ErrorDialog(QWidget* parent) + : QDialog(parent), ui_(new Ui_ErrorDialog) { ui_->setupUi(this); QIcon warning_icon(style()->standardIcon(QStyle::SP_MessageBoxWarning)); QPixmap warning_pixmap(warning_icon.pixmap(48)); QPalette messages_palette(ui_->messages->palette()); - messages_palette.setColor(QPalette::Base, messages_palette.color(QPalette::Background)); + messages_palette.setColor(QPalette::Base, + messages_palette.color(QPalette::Background)); ui_->messages->setPalette(messages_palette); ui_->icon->setPixmap(warning_pixmap); } -ErrorDialog::~ErrorDialog() { - delete ui_; -} +ErrorDialog::~ErrorDialog() { delete ui_; } -void ErrorDialog::ShowMessage(const QString &message) { +void ErrorDialog::ShowMessage(const QString& message) { current_messages_ << message; UpdateContent(); @@ -47,16 +44,15 @@ void ErrorDialog::ShowMessage(const QString &message) { activateWindow(); } -void ErrorDialog::hideEvent(QHideEvent *) { +void ErrorDialog::hideEvent(QHideEvent*) { current_messages_.clear(); UpdateContent(); } void ErrorDialog::UpdateContent() { QString html; - foreach (const QString& message, current_messages_) { - if (!html.isEmpty()) - html += "
    "; + foreach(const QString & message, current_messages_) { + if (!html.isEmpty()) html += "
    "; html += Qt::escape(message); } ui_->messages->setHtml(html); diff --git a/src/widgets/errordialog.h b/src/widgets/errordialog.h index 4ea5bbf65..bfa59f711 100644 --- a/src/widgets/errordialog.h +++ b/src/widgets/errordialog.h @@ -25,17 +25,17 @@ class Ui_ErrorDialog; class ErrorDialog : public QDialog { Q_OBJECT -public: + public: ErrorDialog(QWidget* parent = 0); ~ErrorDialog(); -public slots: + public slots: void ShowMessage(const QString& message); -protected: - void hideEvent(QHideEvent *); + protected: + void hideEvent(QHideEvent*); -private: + private: void UpdateContent(); Ui_ErrorDialog* ui_; @@ -43,4 +43,4 @@ private: QStringList current_messages_; }; -#endif // ERRORDIALOG_H +#endif // ERRORDIALOG_H diff --git a/src/widgets/fancytabwidget.cpp b/src/widgets/fancytabwidget.cpp index f89c5aa60..d28483db9 100644 --- a/src/widgets/fancytabwidget.cpp +++ b/src/widgets/fancytabwidget.cpp @@ -55,11 +55,12 @@ using namespace Internal; const int FancyTabBar::m_rounding = 22; const int FancyTabBar::m_textPadding = 4; -void FancyTabProxyStyle::drawControl( - ControlElement element, const QStyleOption* option, - QPainter* p, const QWidget* widget) const { +void FancyTabProxyStyle::drawControl(ControlElement element, + const QStyleOption* option, QPainter* p, + const QWidget* widget) const { - const QStyleOptionTabV3* v_opt = qstyleoption_cast(option); + const QStyleOptionTabV3* v_opt = + qstyleoption_cast(option); if (element != CE_TabBarTab || !v_opt) { QProxyStyle::drawControl(element, option, p, widget); @@ -72,7 +73,7 @@ void FancyTabProxyStyle::drawControl( const QString text = v_opt->text; if (selected) { - //background + // background p->save(); QLinearGradient grad(rect.topLeft(), rect.topRight()); grad.setColorAt(0, QColor(255, 255, 255, 140)); @@ -80,21 +81,24 @@ void FancyTabProxyStyle::drawControl( p->fillRect(rect.adjusted(0, 0, 0, -1), grad); p->restore(); - //shadows + // shadows p->setPen(QColor(0, 0, 0, 110)); - p->drawLine(rect.topLeft() + QPoint(1,-1), rect.topRight() - QPoint(0,1)); + p->drawLine(rect.topLeft() + QPoint(1, -1), rect.topRight() - QPoint(0, 1)); p->drawLine(rect.bottomLeft(), rect.bottomRight()); p->setPen(QColor(0, 0, 0, 40)); p->drawLine(rect.topLeft(), rect.bottomLeft()); - //highlights + // highlights p->setPen(QColor(255, 255, 255, 50)); - p->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0,2)); - p->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0,1)); + p->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0, 2)); + p->drawLine(rect.bottomLeft() + QPoint(0, 1), + rect.bottomRight() + QPoint(0, 1)); p->setPen(QColor(255, 255, 255, 40)); p->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight()); - p->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1)); - p->drawLine(rect.bottomLeft() + QPoint(0,-1), rect.bottomRight()-QPoint(0,1)); + p->drawLine(rect.topRight() + QPoint(0, 1), + rect.bottomRight() - QPoint(0, 1)); + p->drawLine(rect.bottomLeft() + QPoint(0, -1), + rect.bottomRight() - QPoint(0, 1)); } QTransform m; @@ -122,7 +126,8 @@ void FancyTabProxyStyle::drawControl( p->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110)); int textFlags = Qt::AlignHCenter | Qt::AlignVCenter; p->drawText(text_rect, textFlags, text); - p->setPen(selected ? QColor(60, 60, 60) : Utils::StyleHelper::panelTextColor()); + p->setPen(selected ? QColor(60, 60, 60) + : Utils::StyleHelper::panelTextColor()); #ifndef Q_WS_MAC if (widget) { const QString fader_key = "tab_" + text + "_fader"; @@ -130,15 +135,20 @@ void FancyTabProxyStyle::drawControl( const QString tab_hover = widget->property("tab_hover").toString(); int fader = widget->property(fader_key.toUtf8().constData()).toInt(); - QPropertyAnimation* animation = widget->property(animation_key.toUtf8().constData()).value(); + QPropertyAnimation* animation = + widget->property(animation_key.toUtf8().constData()) + .value(); if (!animation) { QWidget* mut_widget = const_cast(widget); fader = 0; mut_widget->setProperty(fader_key.toUtf8().constData(), fader); - animation = new QPropertyAnimation(mut_widget, fader_key.toUtf8(), mut_widget); - connect(animation, SIGNAL(valueChanged(QVariant)), mut_widget, SLOT(update())); - mut_widget->setProperty(animation_key.toUtf8().constData(), QVariant::fromValue(animation)); + animation = + new QPropertyAnimation(mut_widget, fader_key.toUtf8(), mut_widget); + connect(animation, SIGNAL(valueChanged(QVariant)), mut_widget, + SLOT(update())); + mut_widget->setProperty(animation_key.toUtf8().constData(), + QVariant::fromValue(animation)); } if (text == tab_hover) { @@ -159,20 +169,26 @@ void FancyTabProxyStyle::drawControl( if (!selected) { p->save(); - QLinearGradient grad(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() : draw_rect.topRight()); + QLinearGradient grad(draw_rect.topLeft(), vertical_tabs + ? draw_rect.bottomLeft() + : draw_rect.topRight()); grad.setColorAt(0, Qt::transparent); grad.setColorAt(0.5, QColor(255, 255, 255, fader)); grad.setColorAt(1, Qt::transparent); p->fillRect(draw_rect, grad); p->setPen(QPen(grad, 1.0)); - p->drawLine(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() : draw_rect.topRight()); - p->drawLine(draw_rect.bottomRight(), vertical_tabs ? draw_rect.topRight() : draw_rect.bottomLeft()); + p->drawLine(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() + : draw_rect.topRight()); + p->drawLine(draw_rect.bottomRight(), vertical_tabs + ? draw_rect.topRight() + : draw_rect.bottomLeft()); p->restore(); } } #endif - Utils::StyleHelper::drawIconWithShadow(v_opt->icon, icon_rect, p, QIcon::Normal); + Utils::StyleHelper::drawIconWithShadow(v_opt->icon, icon_rect, p, + QIcon::Normal); p->drawText(text_rect.translated(0, -1), textFlags, text); @@ -187,9 +203,7 @@ void FancyTabProxyStyle::polish(QWidget* widget) { QProxyStyle::polish(widget); } -void FancyTabProxyStyle::polish(QApplication* app) { - QProxyStyle::polish(app); -} +void FancyTabProxyStyle::polish(QApplication* app) { QProxyStyle::polish(app); } void FancyTabProxyStyle::polish(QPalette& palette) { QProxyStyle::polish(palette); @@ -200,71 +214,64 @@ bool FancyTabProxyStyle::eventFilter(QObject* o, QEvent* e) { if (bar && (e->type() == QEvent::MouseMove || e->type() == QEvent::Leave)) { QMouseEvent* event = static_cast(e); const QString old_hovered_tab = bar->property("tab_hover").toString(); - const QString hovered_tab = e->type() == QEvent::Leave ? QString() : bar->tabText(bar->tabAt(event->pos())); + const QString hovered_tab = e->type() == QEvent::Leave + ? QString() + : bar->tabText(bar->tabAt(event->pos())); bar->setProperty("tab_hover", hovered_tab); - if (old_hovered_tab != hovered_tab) - bar->update(); + if (old_hovered_tab != hovered_tab) bar->update(); } return false; } FancyTab::FancyTab(QWidget* tabbar) - : QWidget(tabbar), tabbar(tabbar), m_fader(0) -{ + : QWidget(tabbar), tabbar(tabbar), m_fader(0) { animator.setPropertyName("fader"); animator.setTargetObject(this); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); } -void FancyTab::fadeIn() -{ - animator.stop(); - animator.setDuration(80); - animator.setEndValue(40); - animator.start(); +void FancyTab::fadeIn() { + animator.stop(); + animator.setDuration(80); + animator.setEndValue(40); + animator.start(); } -void FancyTab::fadeOut() -{ - animator.stop(); - animator.setDuration(160); - animator.setEndValue(0); - animator.start(); +void FancyTab::fadeOut() { + animator.stop(); + animator.setDuration(160); + animator.setEndValue(0); + animator.start(); } -void FancyTab::setFader(float value) -{ - m_fader = value; - tabbar->update(); +void FancyTab::setFader(float value) { + m_fader = value; + tabbar->update(); } -FancyTabBar::FancyTabBar(QWidget *parent) - : QWidget(parent) -{ - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); - setStyle(new QWindowsStyle); - setMinimumWidth(qMax(2 * m_rounding, 40)); - setAttribute(Qt::WA_Hover, true); - setFocusPolicy(Qt::NoFocus); - setMouseTracking(true); // Needed for hover events - m_triggerTimer.setSingleShot(true); +FancyTabBar::FancyTabBar(QWidget* parent) : QWidget(parent) { + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); + setStyle(new QWindowsStyle); + setMinimumWidth(qMax(2 * m_rounding, 40)); + setAttribute(Qt::WA_Hover, true); + setFocusPolicy(Qt::NoFocus); + setMouseTracking(true); // Needed for hover events + m_triggerTimer.setSingleShot(true); - QVBoxLayout* layout = new QVBoxLayout; - layout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding)); - layout->setSpacing(0); - layout->setContentsMargins(0, 0, 0, 0); - setLayout(layout); + QVBoxLayout* layout = new QVBoxLayout; + layout->addSpacerItem( + new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding)); + layout->setSpacing(0); + layout->setContentsMargins(0, 0, 0, 0); + setLayout(layout); - // We use a zerotimer to keep the sidebar responsive - connect(&m_triggerTimer, SIGNAL(timeout()), this, SLOT(emitCurrentIndex())); + // We use a zerotimer to keep the sidebar responsive + connect(&m_triggerTimer, SIGNAL(timeout()), this, SLOT(emitCurrentIndex())); } -FancyTabBar::~FancyTabBar() -{ - delete style(); -} +FancyTabBar::~FancyTabBar() { delete style(); } QSize FancyTab::sizeHint() const { QFont boldFont(font()); @@ -278,8 +285,7 @@ QSize FancyTab::sizeHint() const { return ret; } -QSize FancyTabBar::tabSizeHint(bool minimum) const -{ +QSize FancyTabBar::tabSizeHint(bool minimum) const { QFont boldFont(font()); boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize()); boldFont.setBold(true); @@ -290,24 +296,20 @@ QSize FancyTabBar::tabSizeHint(bool minimum) const return QSize(width, iconHeight + spacing + fm.height()); } -void FancyTabBar::paintEvent(QPaintEvent *event) -{ - Q_UNUSED(event) - QPainter p(this); +void FancyTabBar::paintEvent(QPaintEvent* event) { + Q_UNUSED(event) + QPainter p(this); - for (int i = 0; i < count(); ++i) - if (i != currentIndex()) - paintTab(&p, i); + for (int i = 0; i < count(); ++i) + if (i != currentIndex()) paintTab(&p, i); - // paint active tab last, since it overlaps the neighbors - if (currentIndex() != -1) - paintTab(&p, currentIndex()); + // paint active tab last, since it overlaps the neighbors + if (currentIndex() != -1) paintTab(&p, currentIndex()); } -bool FancyTab::event(QEvent* event) -{ +bool FancyTab::event(QEvent* event) { if (event->type() == QEvent::ToolTip) { - QFontMetrics metrics (font()); + QFontMetrics metrics(font()); int text_width = metrics.width(text); if (text_width > sizeHint().width()) { @@ -322,31 +324,22 @@ bool FancyTab::event(QEvent* event) return QWidget::event(event); } -void FancyTab::enterEvent(QEvent*) -{ - fadeIn(); +void FancyTab::enterEvent(QEvent*) { fadeIn(); } + +void FancyTab::leaveEvent(QEvent*) { fadeOut(); } + +QSize FancyTabBar::sizeHint() const { + QSize sh = tabSizeHint(); + return QSize(sh.width(), sh.height() * m_tabs.count()); } -void FancyTab::leaveEvent(QEvent*) -{ - fadeOut(); +QSize FancyTabBar::minimumSizeHint() const { + QSize sh = tabSizeHint(true); + return QSize(sh.width(), sh.height() * m_tabs.count()); } -QSize FancyTabBar::sizeHint() const -{ - QSize sh = tabSizeHint(); - return QSize(sh.width(), sh.height() * m_tabs.count()); -} - -QSize FancyTabBar::minimumSizeHint() const -{ - QSize sh = tabSizeHint(true); - return QSize(sh.width(), sh.height() * m_tabs.count()); -} - -QRect FancyTabBar::tabRect(int index) const -{ - return m_tabs[index]->geometry(); +QRect FancyTabBar::tabRect(int index) const { + return m_tabs[index]->geometry(); } QString FancyTabBar::tabToolTip(int index) const { @@ -360,140 +353,142 @@ void FancyTabBar::setTabToolTip(int index, const QString& toolTip) { // This keeps the sidebar responsive since // we get a repaint before loading the // mode itself -void FancyTabBar::emitCurrentIndex() -{ - emit currentChanged(m_currentIndex); -} +void FancyTabBar::emitCurrentIndex() { emit currentChanged(m_currentIndex); } -void FancyTabBar::mousePressEvent(QMouseEvent *e) -{ - e->accept(); - for (int index = 0; index < m_tabs.count(); ++index) { - if (tabRect(index).contains(e->pos())) { - m_currentIndex = index; - update(); - m_triggerTimer.start(0); - break; - } +void FancyTabBar::mousePressEvent(QMouseEvent* e) { + e->accept(); + for (int index = 0; index < m_tabs.count(); ++index) { + if (tabRect(index).contains(e->pos())) { + m_currentIndex = index; + update(); + m_triggerTimer.start(0); + break; } + } } void FancyTabBar::addTab(const QIcon& icon, const QString& label) { - FancyTab *tab = new FancyTab(this); + FancyTab* tab = new FancyTab(this); tab->icon = icon; tab->text = label; tab->setToolTip(label); m_tabs.append(tab); - qobject_cast(layout())->insertWidget(layout()->count()-1, tab); + qobject_cast(layout()) + ->insertWidget(layout()->count() - 1, tab); } void FancyTabBar::addSpacer(int size) { - qobject_cast(layout())->insertSpacerItem(layout()->count()-1, + qobject_cast(layout())->insertSpacerItem( + layout()->count() - 1, new QSpacerItem(0, size, QSizePolicy::Fixed, QSizePolicy::Maximum)); } -void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const -{ - if (!validIndex(tabIndex)) { - qWarning("invalid index"); - return; - } +void FancyTabBar::paintTab(QPainter* painter, int tabIndex) const { + if (!validIndex(tabIndex)) { + qWarning("invalid index"); + return; + } + painter->save(); + + QRect rect = tabRect(tabIndex); + bool selected = (tabIndex == m_currentIndex); + + if (selected) { + // background painter->save(); + QLinearGradient grad(rect.topLeft(), rect.topRight()); + grad.setColorAt(0, QColor(255, 255, 255, 140)); + grad.setColorAt(1, QColor(255, 255, 255, 210)); + painter->fillRect(rect.adjusted(0, 0, 0, -1), grad); + painter->restore(); - QRect rect = tabRect(tabIndex); - bool selected = (tabIndex == m_currentIndex); + // shadows + painter->setPen(QColor(0, 0, 0, 110)); + painter->drawLine(rect.topLeft() + QPoint(1, -1), + rect.topRight() - QPoint(0, 1)); + painter->drawLine(rect.bottomLeft(), rect.bottomRight()); + painter->setPen(QColor(0, 0, 0, 40)); + painter->drawLine(rect.topLeft(), rect.bottomLeft()); - if (selected) { - //background - painter->save(); - QLinearGradient grad(rect.topLeft(), rect.topRight()); - grad.setColorAt(0, QColor(255, 255, 255, 140)); - grad.setColorAt(1, QColor(255, 255, 255, 210)); - painter->fillRect(rect.adjusted(0, 0, 0, -1), grad); - painter->restore(); + // highlights + painter->setPen(QColor(255, 255, 255, 50)); + painter->drawLine(rect.topLeft() + QPoint(0, -2), + rect.topRight() - QPoint(0, 2)); + painter->drawLine(rect.bottomLeft() + QPoint(0, 1), + rect.bottomRight() + QPoint(0, 1)); + painter->setPen(QColor(255, 255, 255, 40)); + painter->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight()); + painter->drawLine(rect.topRight() + QPoint(0, 1), + rect.bottomRight() - QPoint(0, 1)); + painter->drawLine(rect.bottomLeft() + QPoint(0, -1), + rect.bottomRight() - QPoint(0, 1)); + } - //shadows - painter->setPen(QColor(0, 0, 0, 110)); - painter->drawLine(rect.topLeft() + QPoint(1,-1), rect.topRight() - QPoint(0,1)); - painter->drawLine(rect.bottomLeft(), rect.bottomRight()); - painter->setPen(QColor(0, 0, 0, 40)); - painter->drawLine(rect.topLeft(), rect.bottomLeft()); - - //highlights - painter->setPen(QColor(255, 255, 255, 50)); - painter->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0,2)); - painter->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0,1)); - painter->setPen(QColor(255, 255, 255, 40)); - painter->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight()); - painter->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1)); - painter->drawLine(rect.bottomLeft() + QPoint(0,-1), rect.bottomRight()-QPoint(0,1)); - } - - QString tabText(painter->fontMetrics().elidedText(this->tabText(tabIndex), Qt::ElideRight, width())); - QRect tabTextRect(tabRect(tabIndex)); - QRect tabIconRect(tabTextRect); - tabIconRect.adjust(+4, +4, -4, -4); - tabTextRect.translate(0, -2); - QFont boldFont(painter->font()); - boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize()); - boldFont.setBold(true); - painter->setFont(boldFont); - painter->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110)); - int textFlags = Qt::AlignCenter | Qt::AlignBottom; - painter->drawText(tabTextRect, textFlags, tabText); - painter->setPen(selected ? QColor(60, 60, 60) : Utils::StyleHelper::panelTextColor()); + QString tabText(painter->fontMetrics().elidedText(this->tabText(tabIndex), + Qt::ElideRight, width())); + QRect tabTextRect(tabRect(tabIndex)); + QRect tabIconRect(tabTextRect); + tabIconRect.adjust(+4, +4, -4, -4); + tabTextRect.translate(0, -2); + QFont boldFont(painter->font()); + boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize()); + boldFont.setBold(true); + painter->setFont(boldFont); + painter->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110)); + int textFlags = Qt::AlignCenter | Qt::AlignBottom; + painter->drawText(tabTextRect, textFlags, tabText); + painter->setPen(selected ? QColor(60, 60, 60) + : Utils::StyleHelper::panelTextColor()); #ifndef Q_WS_MAC - if (!selected) { - painter->save(); - int fader = int(m_tabs[tabIndex]->fader()); - QLinearGradient grad(rect.topLeft(), rect.topRight()); - grad.setColorAt(0, Qt::transparent); - grad.setColorAt(0.5, QColor(255, 255, 255, fader)); - grad.setColorAt(1, Qt::transparent); - painter->fillRect(rect, grad); - painter->setPen(QPen(grad, 1.0)); - painter->drawLine(rect.topLeft(), rect.topRight()); - painter->drawLine(rect.bottomLeft(), rect.bottomRight()); - painter->restore(); - } + if (!selected) { + painter->save(); + int fader = int(m_tabs[tabIndex]->fader()); + QLinearGradient grad(rect.topLeft(), rect.topRight()); + grad.setColorAt(0, Qt::transparent); + grad.setColorAt(0.5, QColor(255, 255, 255, fader)); + grad.setColorAt(1, Qt::transparent); + painter->fillRect(rect, grad); + painter->setPen(QPen(grad, 1.0)); + painter->drawLine(rect.topLeft(), rect.topRight()); + painter->drawLine(rect.bottomLeft(), rect.bottomRight()); + painter->restore(); + } #endif - const int textHeight = painter->fontMetrics().height(); - tabIconRect.adjust(0, 4, 0, -textHeight); - Utils::StyleHelper::drawIconWithShadow(tabIcon(tabIndex), tabIconRect, painter, QIcon::Normal); + const int textHeight = painter->fontMetrics().height(); + tabIconRect.adjust(0, 4, 0, -textHeight); + Utils::StyleHelper::drawIconWithShadow(tabIcon(tabIndex), tabIconRect, + painter, QIcon::Normal); - painter->translate(0, -1); - painter->drawText(tabTextRect, textFlags, tabText); - painter->restore(); + painter->translate(0, -1); + painter->drawText(tabTextRect, textFlags, tabText); + painter->restore(); } void FancyTabBar::setCurrentIndex(int index) { - m_currentIndex = index; - update(); - emit currentChanged(m_currentIndex); + m_currentIndex = index; + update(); + emit currentChanged(m_currentIndex); } - ////// // FancyColorButton ////// -class FancyColorButton : public QWidget -{ -public: - FancyColorButton(QWidget *parent) - : m_parent(parent) - { - setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); - } +class FancyColorButton : public QWidget { + public: + FancyColorButton(QWidget* parent) : m_parent(parent) { + setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); + } - void mousePressEvent(QMouseEvent *ev) - { - if (ev->modifiers() & Qt::ShiftModifier) - Utils::StyleHelper::setBaseColor(QColorDialog::getColor(Utils::StyleHelper::requestedBaseColor(), m_parent)); - } -private: - QWidget *m_parent; + void mousePressEvent(QMouseEvent* ev) { + if (ev->modifiers() & Qt::ShiftModifier) + Utils::StyleHelper::setBaseColor(QColorDialog::getColor( + Utils::StyleHelper::requestedBaseColor(), m_parent)); + } + + private: + QWidget* m_parent; }; ////// @@ -501,20 +496,20 @@ private: ////// FancyTabWidget::FancyTabWidget(QWidget* parent) - : QWidget(parent), - mode_(Mode_None), - tab_bar_(nullptr), - stack_(new QStackedLayout), - side_widget_(new QWidget), - side_layout_(new QVBoxLayout), - top_layout_(new QVBoxLayout), - use_background_(false), - menu_(nullptr), - proxy_style_(new FancyTabProxyStyle) -{ + : QWidget(parent), + mode_(Mode_None), + tab_bar_(nullptr), + stack_(new QStackedLayout), + side_widget_(new QWidget), + side_layout_(new QVBoxLayout), + top_layout_(new QVBoxLayout), + use_background_(false), + menu_(nullptr), + proxy_style_(new FancyTabProxyStyle) { side_layout_->setSpacing(0); side_layout_->setMargin(0); - side_layout_->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding)); + side_layout_->addSpacerItem( + new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding)); side_widget_->setLayout(side_layout_); side_widget_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); @@ -531,14 +526,13 @@ FancyTabWidget::FancyTabWidget(QWidget* parent) setLayout(main_layout); } -void FancyTabWidget::AddTab(QWidget* tab, const QIcon& icon, const QString& label) { +void FancyTabWidget::AddTab(QWidget* tab, const QIcon& icon, + const QString& label) { stack_->addWidget(tab); items_ << Item(icon, label); } -void FancyTabWidget::AddSpacer(int size) { - items_ << Item(size); -} +void FancyTabWidget::AddSpacer(int size) { items_ << Item(size); } void FancyTabWidget::SetBackgroundPixmap(const QPixmap& pixmap) { background_pixmap_ = pixmap; @@ -546,8 +540,7 @@ void FancyTabWidget::SetBackgroundPixmap(const QPixmap& pixmap) { } void FancyTabWidget::paintEvent(QPaintEvent*) { - if (!use_background_) - return; + if (!use_background_) return; QPainter painter(this); @@ -562,7 +555,8 @@ void FancyTabWidget::paintEvent(QPaintEvent*) { while (pixmap_rect.top() < rect.bottom()) { QRect source_rect(pixmap_rect.intersected(rect)); source_rect.moveTo(0, 0); - painter.drawPixmap(pixmap_rect.topLeft(), background_pixmap_, source_rect); + painter.drawPixmap(pixmap_rect.topLeft(), background_pixmap_, + source_rect); pixmap_rect.moveTop(pixmap_rect.bottom() - 10); } } @@ -575,9 +569,7 @@ void FancyTabWidget::paintEvent(QPaintEvent*) { painter.drawLine(rect.bottomLeft(), rect.bottomRight()); } -int FancyTabWidget::current_index() const { - return stack_->currentIndex(); -} +int FancyTabWidget::current_index() const { return stack_->currentIndex(); } void FancyTabWidget::SetCurrentIndex(int index) { if (FancyTabBar* bar = qobject_cast(tab_bar_)) { @@ -614,14 +606,14 @@ void FancyTabWidget::SetMode(Mode mode) { case Mode_None: default: qLog(Warning) << "Unknown fancy tab mode" << mode; - // fallthrough + // fallthrough case Mode_LargeSidebar: { FancyTabBar* bar = new FancyTabBar(this); side_layout_->insertWidget(0, bar); tab_bar_ = bar; - foreach (const Item& item, items_) { + foreach(const Item & item, items_) { if (item.type_ == Item::Type_Spacer) bar->addSpacer(item.spacer_size_); else @@ -687,8 +679,7 @@ void FancyTabWidget::AddMenuItem(QSignalMapper* mapper, QActionGroup* group, mapper->setMapping(action, mode); connect(action, SIGNAL(triggered()), mapper, SLOT(map())); - if (mode == mode_) - action->setChecked(true); + if (mode == mode_) action->setChecked(true); } void FancyTabWidget::MakeTabBar(QTabBar::Shape shape, bool text, bool icons, @@ -712,9 +703,8 @@ void FancyTabWidget::MakeTabBar(QTabBar::Shape shape, bool text, bool icons, else side_layout_->insertWidget(0, bar); - foreach (const Item& item, items_) { - if (item.type_ != Item::Type_Tab) - continue; + foreach(const Item & item, items_) { + if (item.type_ != Item::Type_Tab) continue; QString label = item.tab_label_; if (shape == QTabBar::RoundedWest) { diff --git a/src/widgets/fancytabwidget.h b/src/widgets/fancytabwidget.h index 5d9d412fa..375a292a0 100644 --- a/src/widgets/fancytabwidget.h +++ b/src/widgets/fancytabwidget.h @@ -53,104 +53,103 @@ namespace Internal { class FancyTabProxyStyle : public QProxyStyle { Q_OBJECT -public: + public: void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const; void polish(QWidget* widget); void polish(QApplication* app); void polish(QPalette& palette); -protected: + protected: bool eventFilter(QObject* o, QEvent* e); }; class FancyTab : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(float fader READ fader WRITE setFader) -public: - FancyTab(QWidget *tabbar); - float fader() { return m_fader; } - void setFader(float value); + Q_PROPERTY(float fader READ fader WRITE setFader) + public: + FancyTab(QWidget* tabbar); + float fader() { return m_fader; } + void setFader(float value); - QSize sizeHint() const; + QSize sizeHint() const; - void fadeIn(); - void fadeOut(); + void fadeIn(); + void fadeOut(); - QIcon icon; - QString text; + QIcon icon; + QString text; -protected: - bool event(QEvent *); - void enterEvent(QEvent *); - void leaveEvent(QEvent *); + protected: + bool event(QEvent*); + void enterEvent(QEvent*); + void leaveEvent(QEvent*); -private: - QPropertyAnimation animator; - QWidget *tabbar; - float m_fader; + private: + QPropertyAnimation animator; + QWidget* tabbar; + float m_fader; }; -class FancyTabBar : public QWidget -{ - Q_OBJECT +class FancyTabBar : public QWidget { + Q_OBJECT -public: - FancyTabBar(QWidget *parent = 0); - ~FancyTabBar(); + public: + FancyTabBar(QWidget* parent = 0); + ~FancyTabBar(); - void paintEvent(QPaintEvent *event); - void paintTab(QPainter *painter, int tabIndex) const; - void mousePressEvent(QMouseEvent *); - bool validIndex(int index) const { return index >= 0 && index < m_tabs.count(); } + void paintEvent(QPaintEvent* event); + void paintTab(QPainter* painter, int tabIndex) const; + void mousePressEvent(QMouseEvent*); + bool validIndex(int index) const { + return index >= 0 && index < m_tabs.count(); + } - QSize sizeHint() const; - QSize minimumSizeHint() const; + QSize sizeHint() const; + QSize minimumSizeHint() const; - void addTab(const QIcon &icon, const QString &label); - void addSpacer(int size = 40); - void removeTab(int index) { - FancyTab *tab = m_tabs.takeAt(index); - delete tab; - } - void setCurrentIndex(int index); - int currentIndex() const { return m_currentIndex; } + void addTab(const QIcon& icon, const QString& label); + void addSpacer(int size = 40); + void removeTab(int index) { + FancyTab* tab = m_tabs.takeAt(index); + delete tab; + } + void setCurrentIndex(int index); + int currentIndex() const { return m_currentIndex; } - void setTabToolTip(int index, const QString& toolTip); - QString tabToolTip(int index) const; + void setTabToolTip(int index, const QString& toolTip); + QString tabToolTip(int index) const; - QIcon tabIcon(int index) const {return m_tabs.at(index)->icon; } - QString tabText(int index) const { return m_tabs.at(index)->text; } - int count() const {return m_tabs.count(); } - QRect tabRect(int index) const; + QIcon tabIcon(int index) const { return m_tabs.at(index)->icon; } + QString tabText(int index) const { return m_tabs.at(index)->text; } + int count() const { return m_tabs.count(); } + QRect tabRect(int index) const; signals: - void currentChanged(int); + void currentChanged(int); -public slots: - void emitCurrentIndex(); - -private: - static const int m_rounding; - static const int m_textPadding; - int m_currentIndex; - QList m_tabs; - QTimer m_triggerTimer; - QSize tabSizeHint(bool minimum = false) const; + public slots: + void emitCurrentIndex(); + private: + static const int m_rounding; + static const int m_textPadding; + int m_currentIndex; + QList m_tabs; + QTimer m_triggerTimer; + QSize tabSizeHint(bool minimum = false) const; }; class FancyTabWidget : public QWidget { Q_OBJECT -public: + public: FancyTabWidget(QWidget* parent = 0); // Values are persisted - only add to the end enum Mode { Mode_None = 0, - Mode_LargeSidebar = 1, Mode_SmallSidebar = 2, Mode_Tabs = 3, @@ -160,13 +159,13 @@ public: struct Item { Item(const QIcon& icon, const QString& label) - : type_(Type_Tab), tab_label_(label), tab_icon_(icon), spacer_size_(0) {} + : type_(Type_Tab), + tab_label_(label), + tab_icon_(icon), + spacer_size_(0) {} Item(int size) : type_(Type_Spacer), spacer_size_(size) {} - enum Type { - Type_Tab, - Type_Spacer, - }; + enum Type { Type_Tab, Type_Spacer, }; Type type_; QString tab_label_; @@ -174,7 +173,7 @@ public: int spacer_size_; }; - void AddTab(QWidget *tab, const QIcon &icon, const QString &label); + void AddTab(QWidget* tab, const QIcon& icon, const QString& label); void AddSpacer(int size = 40); void SetBackgroundPixmap(const QPixmap& pixmap); @@ -183,7 +182,7 @@ public: int current_index() const; Mode mode() const { return mode_; } -public slots: + public slots: void SetCurrentIndex(int index); void SetCurrentWidget(QWidget* widget); void SetMode(Mode mode); @@ -193,14 +192,14 @@ signals: void CurrentChanged(int index); void ModeChanged(FancyTabWidget::Mode mode); -protected: - void paintEvent(QPaintEvent *event); + protected: + void paintEvent(QPaintEvent* event); void contextMenuEvent(QContextMenuEvent* e); -private slots: + private slots: void ShowWidget(int index); -private: + private: void MakeTabBar(QTabBar::Shape shape, bool text, bool icons, bool fancy); void AddMenuItem(QSignalMapper* mapper, QActionGroup* group, const QString& text, Mode mode); @@ -222,8 +221,8 @@ private: std::unique_ptr proxy_style_; }; -} // namespace Internal -} // namespace Core +} // namespace Internal +} // namespace Core Q_DECLARE_METATYPE(QPropertyAnimation*); @@ -231,4 +230,4 @@ using Core::Internal::FancyTab; using Core::Internal::FancyTabBar; using Core::Internal::FancyTabWidget; -#endif // FANCYTABWIDGET_H +#endif // FANCYTABWIDGET_H diff --git a/src/widgets/favoritewidget.cpp b/src/widgets/favoritewidget.cpp index c3dc66557..72a751daf 100644 --- a/src/widgets/favoritewidget.cpp +++ b/src/widgets/favoritewidget.cpp @@ -28,14 +28,12 @@ const int FavoriteWidget::kStarSize = 15; FavoriteWidget::FavoriteWidget(int tab_index, bool favorite, QWidget* parent) - : QWidget(parent), - tab_index_(tab_index), - favorite_(favorite), - on_(":/star-on.png"), - off_(":/star-off.png"), - rect_(0, 0, kStarSize, kStarSize) -{ -} + : QWidget(parent), + tab_index_(tab_index), + favorite_(favorite), + on_(":/star-on.png"), + off_(":/star-off.png"), + rect_(0, 0, kStarSize, kStarSize) {} void FavoriteWidget::SetFavorite(bool favorite) { if (favorite_ != favorite) { @@ -46,8 +44,9 @@ void FavoriteWidget::SetFavorite(bool favorite) { } QSize FavoriteWidget::sizeHint() const { - const int frame_width = 1 + style()->pixelMetric(QStyle::PM_DefaultFrameWidth); - return QSize(kStarSize + frame_width*2, kStarSize + frame_width*2); + const int frame_width = + 1 + style()->pixelMetric(QStyle::PM_DefaultFrameWidth); + return QSize(kStarSize + frame_width * 2, kStarSize + frame_width * 2); } void FavoriteWidget::paintEvent(QPaintEvent* e) { diff --git a/src/widgets/favoritewidget.h b/src/widgets/favoritewidget.h index c200cc565..d4ea15c93 100644 --- a/src/widgets/favoritewidget.h +++ b/src/widgets/favoritewidget.h @@ -24,7 +24,7 @@ class FavoriteWidget : public QWidget { Q_OBJECT public: - FavoriteWidget(int tab_id, bool favorite = false, QWidget *parent = 0); + FavoriteWidget(int tab_id, bool favorite = false, QWidget* parent = 0); // Change the value if different from the current one and then update display // and emit FavoriteStateChanged signal @@ -32,7 +32,7 @@ class FavoriteWidget : public QWidget { QSize sizeHint() const; - signals: +signals: void FavoriteStateChanged(int, bool); protected: diff --git a/src/widgets/fileview.cpp b/src/widgets/fileview.cpp index 121eed017..5ec1fa6d8 100644 --- a/src/widgets/fileview.cpp +++ b/src/widgets/fileview.cpp @@ -21,7 +21,7 @@ #include "core/filesystemmusicstorage.h" #include "core/mimedata.h" #include "ui/iconloader.h" -#include "ui/mainwindow.h" // for filter information +#include "ui/mainwindow.h" // for filter information #include "ui/organiseerrordialog.h" #include @@ -29,10 +29,11 @@ #include #include -const char* FileView::kFileFilter = "*.mp3 *.ogg *.flac *.mpc *.m4a *.aac *.wma " - "*.mp4 *.spx *.wav *.m3u *.m3u8 *.pls *.xspf " - "*.asx *.asxini *.cue *.ape *.wv *.mka *.opus " - "*.oga *.mka *.mp2"; +const char* FileView::kFileFilter = + "*.mp3 *.ogg *.flac *.mpc *.m4a *.aac *.wma " + "*.mp4 *.spx *.wav *.m3u *.m3u8 *.pls *.xspf " + "*.asx *.asxini *.cue *.ape *.wv *.mka *.opus " + "*.oga *.mka *.mp2"; FileView::FileView(QWidget* parent) : QWidget(parent), @@ -40,8 +41,7 @@ FileView::FileView(QWidget* parent) model_(nullptr), undo_stack_(new QUndoStack(this)), task_manager_(nullptr), - storage_(new FilesystemMusicStorage("/")) -{ + storage_(new FilesystemMusicStorage("/")) { ui_->setupUi(this); // Icons @@ -54,27 +54,35 @@ FileView::FileView(QWidget* parent) connect(ui_->forward, SIGNAL(clicked()), undo_stack_, SLOT(redo())); connect(ui_->home, SIGNAL(clicked()), SLOT(FileHome())); connect(ui_->up, SIGNAL(clicked()), SLOT(FileUp())); - connect(ui_->path, SIGNAL(textChanged(QString)), SLOT(ChangeFilePath(QString))); + connect(ui_->path, SIGNAL(textChanged(QString)), + SLOT(ChangeFilePath(QString))); - connect(undo_stack_, SIGNAL(canUndoChanged(bool)), ui_->back, SLOT(setEnabled(bool))); - connect(undo_stack_, SIGNAL(canRedoChanged(bool)), ui_->forward, SLOT(setEnabled(bool))); + connect(undo_stack_, SIGNAL(canUndoChanged(bool)), ui_->back, + SLOT(setEnabled(bool))); + connect(undo_stack_, SIGNAL(canRedoChanged(bool)), ui_->forward, + SLOT(setEnabled(bool))); - connect(ui_->list, SIGNAL(activated(QModelIndex)), SLOT(ItemActivated(QModelIndex))); - connect(ui_->list, SIGNAL(doubleClicked(QModelIndex)), SLOT(ItemDoubleClick(QModelIndex))); - connect(ui_->list, SIGNAL(AddToPlaylist(QMimeData*)), SIGNAL(AddToPlaylist(QMimeData*))); - connect(ui_->list, SIGNAL(CopyToLibrary(QList)), SIGNAL(CopyToLibrary(QList))); - connect(ui_->list, SIGNAL(MoveToLibrary(QList)), SIGNAL(MoveToLibrary(QList))); - connect(ui_->list, SIGNAL(CopyToDevice(QList)), SIGNAL(CopyToDevice(QList))); + connect(ui_->list, SIGNAL(activated(QModelIndex)), + SLOT(ItemActivated(QModelIndex))); + connect(ui_->list, SIGNAL(doubleClicked(QModelIndex)), + SLOT(ItemDoubleClick(QModelIndex))); + connect(ui_->list, SIGNAL(AddToPlaylist(QMimeData*)), + SIGNAL(AddToPlaylist(QMimeData*))); + connect(ui_->list, SIGNAL(CopyToLibrary(QList)), + SIGNAL(CopyToLibrary(QList))); + connect(ui_->list, SIGNAL(MoveToLibrary(QList)), + SIGNAL(MoveToLibrary(QList))); + connect(ui_->list, SIGNAL(CopyToDevice(QList)), + SIGNAL(CopyToDevice(QList))); connect(ui_->list, SIGNAL(Delete(QStringList)), SLOT(Delete(QStringList))); - connect(ui_->list, SIGNAL(EditTags(QList)), SIGNAL(EditTags(QList))); + connect(ui_->list, SIGNAL(EditTags(QList)), + SIGNAL(EditTags(QList))); QString filter(FileView::kFileFilter); filter_list_ << filter.split(" "); } -FileView::~FileView() { - delete ui_; -} +FileView::~FileView() { delete ui_; } void FileView::SetPath(const QString& path) { if (!model_) @@ -95,7 +103,7 @@ void FileView::FileUp() { // view scroll position. if (undo_stack_->canUndo()) { const UndoCommand* last_dir = static_cast( - undo_stack_->command(undo_stack_->index()-1)); + undo_stack_->command(undo_stack_->index() - 1)); if (last_dir->undo_path() == dir.path()) { undo_stack_->undo(); return; @@ -105,20 +113,16 @@ void FileView::FileUp() { ChangeFilePath(dir.path()); } -void FileView::FileHome() { - ChangeFilePath(QDir::homePath()); -} +void FileView::FileHome() { ChangeFilePath(QDir::homePath()); } void FileView::ChangeFilePath(const QString& new_path_native) { QString new_path = QDir::fromNativeSeparators(new_path_native); QFileInfo info(new_path); - if (!info.exists() || !info.isDir()) - return; + if (!info.exists() || !info.isDir()) return; QString old_path(model_->rootPath()); - if (old_path == new_path) - return; + if (old_path == new_path) return; undo_stack_->push(new UndoCommand(this, new_path)); } @@ -134,13 +138,11 @@ void FileView::ChangeFilePathWithoutUndo(const QString& new_path) { } void FileView::ItemActivated(const QModelIndex& index) { - if (model_->isDir(index)) - ChangeFilePath(model_->filePath(index)); + if (model_->isDir(index)) ChangeFilePath(model_->filePath(index)); } void FileView::ItemDoubleClick(const QModelIndex& index) { - if (model_->isDir(index)) - return; + if (model_->isDir(index)) return; QString file_path = model_->filePath(index); @@ -152,10 +154,8 @@ void FileView::ItemDoubleClick(const QModelIndex& index) { emit AddToPlaylist(data); } - FileView::UndoCommand::UndoCommand(FileView* view, const QString& new_path) - : view_(view) -{ + : view_(view) { old_state_.path = view->model_->rootPath(); old_state_.scroll_pos = view_->ui_->list->verticalScrollBar()->value(); old_state_.index = view_->ui_->list->currentIndex(); @@ -181,22 +181,23 @@ void FileView::UndoCommand::undo() { } void FileView::Delete(const QStringList& filenames) { - if (filenames.isEmpty()) - return; + if (filenames.isEmpty()) return; if (QMessageBox::warning(this, tr("Delete files"), - tr("These files will be permanently deleted from disk, are you sure you want to continue?"), - QMessageBox::Yes, QMessageBox::Cancel) != QMessageBox::Yes) + tr("These files will be permanently deleted from " + "disk, are you sure you want to continue?"), + QMessageBox::Yes, + QMessageBox::Cancel) != QMessageBox::Yes) return; DeleteFiles* delete_files = new DeleteFiles(task_manager_, storage_); - connect(delete_files, SIGNAL(Finished(SongList)), SLOT(DeleteFinished(SongList))); + connect(delete_files, SIGNAL(Finished(SongList)), + SLOT(DeleteFinished(SongList))); delete_files->Start(filenames); } void FileView::DeleteFinished(const SongList& songs_with_errors) { - if (songs_with_errors.isEmpty()) - return; + if (songs_with_errors.isEmpty()) return; OrganiseErrorDialog* dialog = new OrganiseErrorDialog(this); dialog->Show(OrganiseErrorDialog::Type_Delete, songs_with_errors); @@ -206,11 +207,10 @@ void FileView::DeleteFinished(const SongList& songs_with_errors) { void FileView::showEvent(QShowEvent* e) { QWidget::showEvent(e); - if (model_) - return; + if (model_) return; model_ = new QFileSystemModel(this); - + model_->setNameFilters(filter_list_); // if an item fails the filter, hide it model_->setNameFilterDisables(false); @@ -218,8 +218,7 @@ void FileView::showEvent(QShowEvent* e) { ui_->list->setModel(model_); ChangeFilePathWithoutUndo(QDir::homePath()); - if (!lazy_set_path_.isEmpty()) - ChangeFilePathWithoutUndo(lazy_set_path_); + if (!lazy_set_path_.isEmpty()) ChangeFilePathWithoutUndo(lazy_set_path_); } void FileView::keyPressEvent(QKeyEvent* e) { diff --git a/src/widgets/fileview.h b/src/widgets/fileview.h index db740bcb7..5f0178c90 100644 --- a/src/widgets/fileview.h +++ b/src/widgets/fileview.h @@ -50,7 +50,7 @@ class FileView : public QWidget { void showEvent(QShowEvent*); void keyPressEvent(QKeyEvent* e); - signals: +signals: void PathChanged(const QString& path); void AddToPlaylist(QMimeData* data); @@ -109,4 +109,4 @@ class FileView : public QWidget { QStringList filter_list_; }; -#endif // FILEVIEW_H +#endif // FILEVIEW_H diff --git a/src/widgets/fileviewlist.cpp b/src/widgets/fileviewlist.cpp index 3084c9124..841113b84 100644 --- a/src/widgets/fileviewlist.cpp +++ b/src/widgets/fileviewlist.cpp @@ -26,20 +26,19 @@ #include FileViewList::FileViewList(QWidget* parent) - : QListView(parent), - menu_(new QMenu(this)) -{ - menu_->addAction(IconLoader::Load("media-playback-start"), tr("Append to current playlist"), - this, SLOT(AddToPlaylistSlot())); - menu_->addAction(IconLoader::Load("media-playback-start"), tr("Replace current playlist"), - this, SLOT(LoadSlot())); + : QListView(parent), menu_(new QMenu(this)) { + menu_->addAction(IconLoader::Load("media-playback-start"), + tr("Append to current playlist"), this, + SLOT(AddToPlaylistSlot())); + menu_->addAction(IconLoader::Load("media-playback-start"), + tr("Replace current playlist"), this, SLOT(LoadSlot())); menu_->addAction(IconLoader::Load("document-new"), tr("Open in new playlist"), this, SLOT(OpenInNewPlaylistSlot())); menu_->addSeparator(); menu_->addAction(IconLoader::Load("edit-copy"), tr("Copy to library..."), this, SLOT(CopyToLibrarySlot())); - menu_->addAction(IconLoader::Load("go-jump"), tr("Move to library..."), - this, SLOT(MoveToLibrarySlot())); + menu_->addAction(IconLoader::Load("go-jump"), tr("Move to library..."), this, + SLOT(MoveToLibrarySlot())); menu_->addAction(IconLoader::Load("multimedia-player-ipod-mini-blue"), tr("Copy to device..."), this, SLOT(CopyToDeviceSlot())); menu_->addAction(IconLoader::Load("edit-delete"), tr("Delete from disk..."), @@ -47,9 +46,9 @@ FileViewList::FileViewList(QWidget* parent) menu_->addSeparator(); menu_->addAction(IconLoader::Load("edit-rename"), - tr("Edit track information..."), this, SLOT(EditTagsSlot())); + tr("Edit track information..."), this, SLOT(EditTagsSlot())); menu_->addAction(IconLoader::Load("document-open-folder"), - tr("Show in file browser..."), this, SLOT(ShowInBrowser())); + tr("Show in file browser..."), this, SLOT(ShowInBrowser())); setAttribute(Qt::WA_MacShowFocusRect, false); } @@ -63,10 +62,11 @@ void FileViewList::contextMenuEvent(QContextMenuEvent* e) { QList FileViewList::UrlListFromSelection() const { QList urls; - foreach (const QModelIndex& index, menu_selection_.indexes()) { + foreach(const QModelIndex & index, menu_selection_.indexes()) { if (index.column() == 0) - urls << QUrl::fromLocalFile( - static_cast(model())->fileInfo(index).canonicalFilePath()); + urls << QUrl::fromLocalFile(static_cast(model()) + ->fileInfo(index) + .canonicalFilePath()); } return urls; } @@ -77,11 +77,12 @@ MimeData* FileViewList::MimeDataFromSelection() const { QList filenames = FilenamesFromSelection(); // if just one folder selected - use it's path as the new playlist's name - if(filenames.size() == 1 && QFileInfo(filenames.first()).isDir()) { + if (filenames.size() == 1 && QFileInfo(filenames.first()).isDir()) { data->name_for_new_playlist_ = filenames.first(); - // otherwise, use the current root path + // otherwise, use the current root path } else { - data->name_for_new_playlist_ = static_cast(model())->rootPath(); + data->name_for_new_playlist_ = + static_cast(model())->rootPath(); } return data; @@ -89,7 +90,7 @@ MimeData* FileViewList::MimeDataFromSelection() const { QStringList FileViewList::FilenamesFromSelection() const { QStringList filenames; - foreach (const QModelIndex& index, menu_selection_.indexes()) { + foreach(const QModelIndex & index, menu_selection_.indexes()) { if (index.column() == 0) filenames << static_cast(model())->filePath(index); } @@ -124,20 +125,16 @@ void FileViewList::CopyToDeviceSlot() { emit CopyToDevice(UrlListFromSelection()); } -void FileViewList::DeleteSlot() { - emit Delete(FilenamesFromSelection()); -} +void FileViewList::DeleteSlot() { emit Delete(FilenamesFromSelection()); } -void FileViewList::EditTagsSlot() { - emit EditTags(UrlListFromSelection()); -} +void FileViewList::EditTagsSlot() { emit EditTags(UrlListFromSelection()); } void FileViewList::mousePressEvent(QMouseEvent* e) { QListView::mousePressEvent(e); - //enqueue to playlist with middleClick + // enqueue to playlist with middleClick if (e->button() == Qt::MidButton) { - //we need to update the menu selection + // we need to update the menu selection menu_selection_ = selectionModel()->selection(); MimeData* data = new MimeData; diff --git a/src/widgets/fileviewlist.h b/src/widgets/fileviewlist.h index 6935e9483..0a8fe503d 100644 --- a/src/widgets/fileviewlist.h +++ b/src/widgets/fileviewlist.h @@ -31,7 +31,7 @@ class FileViewList : public QListView { void mousePressEvent(QMouseEvent* e); - signals: +signals: void AddToPlaylist(QMimeData* data); void CopyToLibrary(const QList& urls); void MoveToLibrary(const QList& urls); @@ -62,4 +62,4 @@ class FileViewList : public QListView { QItemSelection menu_selection_; }; -#endif // FILEVIEWLIST_H +#endif // FILEVIEWLIST_H diff --git a/src/widgets/forcescrollperpixel.cpp b/src/widgets/forcescrollperpixel.cpp index f54fab067..065c1e47b 100644 --- a/src/widgets/forcescrollperpixel.cpp +++ b/src/widgets/forcescrollperpixel.cpp @@ -21,17 +21,14 @@ #include #include - -ForceScrollPerPixel::ForceScrollPerPixel(QAbstractItemView* item_view, QObject* parent) - : QObject(parent), - item_view_(item_view) -{ +ForceScrollPerPixel::ForceScrollPerPixel(QAbstractItemView* item_view, + QObject* parent) + : QObject(parent), item_view_(item_view) { item_view_->installEventFilter(this); } bool ForceScrollPerPixel::eventFilter(QObject* object, QEvent* event) { - if (object == item_view_ && - event->type() != QEvent::Destroy && + if (object == item_view_ && event->type() != QEvent::Destroy && event->type() != QEvent::WinIdChange && event->type() != QEvent::AccessibilityPrepare) { item_view_->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); diff --git a/src/widgets/forcescrollperpixel.h b/src/widgets/forcescrollperpixel.h index 0b498d12c..5ff8d4e8c 100644 --- a/src/widgets/forcescrollperpixel.h +++ b/src/widgets/forcescrollperpixel.h @@ -25,14 +25,14 @@ class QAbstractItemView; // Some KDE styles override the ScrollMode property of QAbstractItemViews. // This helper class forces the mode back to ScrollPerPixel. class ForceScrollPerPixel : public QObject { -public: + public: ForceScrollPerPixel(QAbstractItemView* item_view, QObject* parent = 0); -protected: + protected: bool eventFilter(QObject* object, QEvent* event); -private: + private: QAbstractItemView* item_view_; }; -#endif // FORCESCROLLPERPIXEL_H +#endif // FORCESCROLLPERPIXEL_H diff --git a/src/widgets/freespacebar.cpp b/src/widgets/freespacebar.cpp index 02fc44acd..1f25c04d5 100644 --- a/src/widgets/freespacebar.cpp +++ b/src/widgets/freespacebar.cpp @@ -36,16 +36,14 @@ const QRgb FreeSpaceBar::kColorBar1 = qRgb(250, 148, 76); const QRgb FreeSpaceBar::kColorBar2 = qRgb(214, 102, 24); const QRgb FreeSpaceBar::kColorBorder = qRgb(174, 168, 162); - -FreeSpaceBar::FreeSpaceBar(QWidget *parent) - : QWidget(parent), - free_(100), - additional_(0), - total_(100), - free_text_(tr("Available")), - additional_text_(tr("New songs")), - used_text_(tr("Used")) -{ +FreeSpaceBar::FreeSpaceBar(QWidget* parent) + : QWidget(parent), + free_(100), + additional_(0), + total_(100), + free_text_(tr("Available")), + additional_text_(tr("New songs")), + used_text_(tr("Used")) { setMinimumHeight(sizeHint().height()); } @@ -66,7 +64,8 @@ void FreeSpaceBar::paintEvent(QPaintEvent*) { // Draw the reflection // Create the reflected pixmap - QImage reflection(reflection_rect.size(), QImage::Format_ARGB32_Premultiplied); + QImage reflection(reflection_rect.size(), + QImage::Format_ARGB32_Premultiplied); reflection.fill(palette().color(QPalette::Background).rgba()); QPainter p(&reflection); @@ -80,7 +79,8 @@ void FreeSpaceBar::paintEvent(QPaintEvent*) { DrawBar(&p, QRect(QPoint(0, 0), reflection.size())); // Make it fade out towards the bottom - QLinearGradient fade_gradient(reflection.rect().topLeft(), reflection.rect().bottomLeft()); + QLinearGradient fade_gradient(reflection.rect().topLeft(), + reflection.rect().bottomLeft()); fade_gradient.setColorAt(0.0, QColor(0, 0, 0, 0)); fade_gradient.setColorAt(1.0, QColor(0, 0, 0, 128)); @@ -125,10 +125,11 @@ void FreeSpaceBar::DrawBar(QPainter* p, const QRect& r) { if (additional_) { QRect additional_rect(bar_rect); additional_rect.setLeft(bar_rect.right()); - additional_rect.setWidth(float(r.width()) * ( - float(qMin(free_, additional_)) / total_) + 1); + additional_rect.setWidth( + float(r.width()) * (float(qMin(free_, additional_)) / total_) + 1); - QLinearGradient additional_gradient(additional_rect.topLeft(), additional_rect.bottomLeft()); + QLinearGradient additional_gradient(additional_rect.topLeft(), + additional_rect.bottomLeft()); additional_gradient.setColorAt(0, kColorAdd1); additional_gradient.setColorAt(1, kColorAdd2); @@ -148,7 +149,7 @@ void FreeSpaceBar::DrawBar(QPainter* p, const QRect& r) { p->setOpacity(0.35); p->setRenderHint(QPainter::Antialiasing, false); p->setPen(QPen(palette().color(QPalette::Light), 1.0)); - for (int x = r.left() + kMarkerSpacing ; x < r.right() ; x += kMarkerSpacing) { + for (int x = r.left() + kMarkerSpacing; x < r.right(); x += kMarkerSpacing) { p->drawLine(x, r.top() + 2, x, r.bottom() - 2); } @@ -170,26 +171,30 @@ void FreeSpaceBar::DrawText(QPainter* p, const QRect& r) { labels << Label(TextForSize(free_text_, free_ - additional_), kColorBg2); int text_width = 0; - foreach (const Label& label, labels) - text_width += kLabelBoxSize + kLabelBoxPadding + kLabelSpacing + small_metrics.width(label.text); + foreach(const Label & label, labels) + text_width += kLabelBoxSize + kLabelBoxPadding + kLabelSpacing + + small_metrics.width(label.text); // Draw the text int x = (r.width() - text_width) / 2; p->setRenderHint(QPainter::Antialiasing, false); - foreach (const Label& label, labels) { + foreach(const Label & label, labels) { const bool light = palette().color(QPalette::Base).value() > 128; - QRect box(x, r.top() + (r.height() - kLabelBoxSize)/2, kLabelBoxSize, kLabelBoxSize); + QRect box(x, r.top() + (r.height() - kLabelBoxSize) / 2, kLabelBoxSize, + kLabelBoxSize); p->setPen(label.color.darker()); p->setBrush(label.color); p->drawRect(box); - QRect text(x + kLabelBoxSize + kLabelBoxPadding, r.top(), small_metrics.width(label.text), r.height()); + QRect text(x + kLabelBoxSize + kLabelBoxPadding, r.top(), + small_metrics.width(label.text), r.height()); p->setPen(light ? label.color.darker() : label.color); p->drawText(text, Qt::AlignCenter, label.text); - x += kLabelBoxSize + kLabelBoxPadding + kLabelSpacing + small_metrics.width(label.text); + x += kLabelBoxSize + kLabelBoxPadding + kLabelSpacing + + small_metrics.width(label.text); } } @@ -202,7 +207,6 @@ QString FreeSpaceBar::TextForSize(const QString& prefix, qint64 size) const { else ret = "0 MB"; - if (!prefix.isEmpty()) - ret.prepend(prefix + " "); + if (!prefix.isEmpty()) ret.prepend(prefix + " "); return ret; } diff --git a/src/widgets/freespacebar.h b/src/widgets/freespacebar.h index d1369b5b2..0630724c5 100644 --- a/src/widgets/freespacebar.h +++ b/src/widgets/freespacebar.h @@ -23,7 +23,7 @@ class FreeSpaceBar : public QWidget { Q_OBJECT -public: + public: FreeSpaceBar(QWidget* parent = 0); static const int kBarHeight; @@ -41,20 +41,38 @@ public: static const QRgb kColorBar2; static const QRgb kColorBorder; - void set_free_bytes(qint64 bytes) { free_ = bytes; update(); } - void set_additional_bytes(qint64 bytes) { additional_ = bytes; update(); } - void set_total_bytes(qint64 bytes) { total_ = bytes; update(); } + void set_free_bytes(qint64 bytes) { + free_ = bytes; + update(); + } + void set_additional_bytes(qint64 bytes) { + additional_ = bytes; + update(); + } + void set_total_bytes(qint64 bytes) { + total_ = bytes; + update(); + } - void set_free_text(const QString& text) { free_text_ = text; update(); } - void set_additional_text(const QString& text) { additional_text_ = text; update(); } - void set_used_text(const QString& text) { used_text_ = text; update(); } + void set_free_text(const QString& text) { + free_text_ = text; + update(); + } + void set_additional_text(const QString& text) { + additional_text_ = text; + update(); + } + void set_used_text(const QString& text) { + used_text_ = text; + update(); + } QSize sizeHint() const; -protected: + protected: void paintEvent(QPaintEvent*); -private: + private: struct Label { Label(const QString& t, const QColor& c) : text(t), color(c) {} @@ -67,7 +85,7 @@ private: void DrawBar(QPainter* p, const QRect& r); void DrawText(QPainter* p, const QRect& r); -private: + private: qint64 free_; qint64 additional_; qint64 total_; @@ -77,4 +95,4 @@ private: QString used_text_; }; -#endif // FREESPACEBAR_H +#endif // FREESPACEBAR_H diff --git a/src/widgets/fullscreenhypnotoad.cpp b/src/widgets/fullscreenhypnotoad.cpp index 371e2a561..7a7138b55 100644 --- a/src/widgets/fullscreenhypnotoad.cpp +++ b/src/widgets/fullscreenhypnotoad.cpp @@ -20,8 +20,7 @@ #include FullscreenHypnotoad::FullscreenHypnotoad() - : movie_(new QMovie(":/hypnotoad.gif")) -{ + : movie_(new QMovie(":/hypnotoad.gif")) { setMovie(movie_); setScaledContents(true); @@ -31,18 +30,10 @@ FullscreenHypnotoad::FullscreenHypnotoad() setPalette(p); } -void FullscreenHypnotoad::mouseReleaseEvent(QMouseEvent* e) { - hide(); -} +void FullscreenHypnotoad::mouseReleaseEvent(QMouseEvent* e) { hide(); } -void FullscreenHypnotoad::keyReleaseEvent(QKeyEvent* e) { - hide(); -} +void FullscreenHypnotoad::keyReleaseEvent(QKeyEvent* e) { hide(); } -void FullscreenHypnotoad::showEvent(QShowEvent*) { - movie_->start(); -} +void FullscreenHypnotoad::showEvent(QShowEvent*) { movie_->start(); } -void FullscreenHypnotoad::hideEvent(QHideEvent*) { - movie_->stop(); -} +void FullscreenHypnotoad::hideEvent(QHideEvent*) { movie_->stop(); } diff --git a/src/widgets/fullscreenhypnotoad.h b/src/widgets/fullscreenhypnotoad.h index 54f9c7756..a95bb1568 100644 --- a/src/widgets/fullscreenhypnotoad.h +++ b/src/widgets/fullscreenhypnotoad.h @@ -21,17 +21,17 @@ #include class FullscreenHypnotoad : public QLabel { -public: + public: FullscreenHypnotoad(); -protected: + protected: void keyReleaseEvent(QKeyEvent* e); void mouseReleaseEvent(QMouseEvent* e); void showEvent(QShowEvent* e); void hideEvent(QHideEvent* e); -private: + private: QMovie* movie_; }; -#endif // FULLSCREENHYPNOTOAD_H +#endif // FULLSCREENHYPNOTOAD_H diff --git a/src/widgets/groupediconview.cpp b/src/widgets/groupediconview.cpp index ab686a0b8..32f41c4ef 100644 --- a/src/widgets/groupediconview.cpp +++ b/src/widgets/groupediconview.cpp @@ -27,17 +27,15 @@ const int GroupedIconView::kBarThickness = 2; const int GroupedIconView::kBarMarginTop = 3; - GroupedIconView::GroupedIconView(QWidget* parent) - : QListView(parent), - proxy_model_(new MultiSortFilterProxy(this)), - default_header_height_(fontMetrics().height() + - kBarMarginTop + kBarThickness), - header_spacing_(10), - header_indent_(5), - item_indent_(10), - header_text_("%1") -{ + : QListView(parent), + proxy_model_(new MultiSortFilterProxy(this)), + default_header_height_(fontMetrics().height() + kBarMarginTop + + kBarThickness), + header_spacing_(10), + header_indent_(5), + item_indent_(10), + header_text_("%1") { setFlow(LeftToRight); setViewMode(IconMode); setResizeMode(Adjust); @@ -62,9 +60,7 @@ void GroupedIconView::setModel(QAbstractItemModel* model) { LayoutItems(); } -int GroupedIconView::header_height() const { - return default_header_height_; -} +int GroupedIconView::header_height() const { return default_header_height_; } void GroupedIconView::DrawHeader(QPainter* painter, const QRect& rect, const QFont& font, const QPalette& palette, @@ -78,8 +74,9 @@ void GroupedIconView::DrawHeader(QPainter* painter, const QRect& rect, QRect text_rect(rect); text_rect.setHeight(metrics.height()); - text_rect.moveTop(rect.top() + (rect.height() - text_rect.height() - - kBarThickness - kBarMarginTop) / 2); + text_rect.moveTop( + rect.top() + + (rect.height() - text_rect.height() - kBarThickness - kBarMarginTop) / 2); text_rect.setLeft(text_rect.left() + 3); // Draw text @@ -104,19 +101,20 @@ void GroupedIconView::resizeEvent(QResizeEvent* e) { LayoutItems(); } -void GroupedIconView::rowsInserted(const QModelIndex& parent, int start, int end) { +void GroupedIconView::rowsInserted(const QModelIndex& parent, int start, + int end) { QListView::rowsInserted(parent, start, end); LayoutItems(); } -void GroupedIconView::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) { +void GroupedIconView::dataChanged(const QModelIndex& topLeft, + const QModelIndex& bottomRight) { QListView::dataChanged(topLeft, bottomRight); LayoutItems(); } void GroupedIconView::LayoutItems() { - if (!model()) - return; + if (!model()) return; const int count = model()->rowCount(); @@ -128,7 +126,7 @@ void GroupedIconView::LayoutItems() { visual_rects_.reserve(count); headers_.clear(); - for (int i=0 ; iindex(i, 0)); const QString group = index.data(Role_Group).toString(); const QSize size(rectForIndex(index).size()); @@ -152,7 +150,8 @@ void GroupedIconView::LayoutItems() { // Move the next item immediately below the header. next_position.setX(0); - next_position.setY(header.y + header_height() + header_indent_ + header_spacing_); + next_position.setY(header.y + header_height() + header_indent_ + + header_spacing_); max_row_height = 0; } @@ -165,7 +164,8 @@ void GroupedIconView::LayoutItems() { } // Should this item wrap? - if (next_position.x() != 0 && this_position.x() + size.width() >= viewport()->width()) { + if (next_position.x() != 0 && + this_position.x() + size.width() >= viewport()->width()) { next_position.setX(0); next_position.setY(next_position.y() + max_row_height); this_position = next_position; @@ -182,21 +182,22 @@ void GroupedIconView::LayoutItems() { max_row_height = qMax(max_row_height, size.height()); } - verticalScrollBar()->setRange(0, next_position.y() + max_row_height - viewport()->height()); + verticalScrollBar()->setRange( + 0, next_position.y() + max_row_height - viewport()->height()); update(); } QRect GroupedIconView::visualRect(const QModelIndex& index) const { - if (index.row() < 0 || index.row() >= visual_rects_.count()) - return QRect(); - return visual_rects_[index.row()].translated(-horizontalOffset(), -verticalOffset()); + if (index.row() < 0 || index.row() >= visual_rects_.count()) return QRect(); + return visual_rects_[index.row()].translated(-horizontalOffset(), + -verticalOffset()); } QModelIndex GroupedIconView::indexAt(const QPoint& p) const { const QPoint viewport_p = p + QPoint(horizontalOffset(), verticalOffset()); const int count = visual_rects_.count(); - for (int i=0 ; iindex(i, 0); } @@ -209,31 +210,33 @@ void GroupedIconView::paintEvent(QPaintEvent* e) { // visualRect() of items, and to draw headers. QStyleOptionViewItemV4 option(viewOptions()); - if (isWrapping()) - option.features = QStyleOptionViewItemV2::WrapText; + if (isWrapping()) option.features = QStyleOptionViewItemV2::WrapText; option.locale = locale(); option.locale.setNumberOptions(QLocale::OmitGroupSeparator); option.widget = this; QPainter painter(viewport()); - const QRect viewport_rect(e->rect().translated(horizontalOffset(), verticalOffset())); + const QRect viewport_rect( + e->rect().translated(horizontalOffset(), verticalOffset())); QVector toBeRendered = IntersectingItems(viewport_rect); const QModelIndex current = currentIndex(); - const QAbstractItemModel *itemModel = model(); - const QItemSelectionModel *selections = selectionModel(); - const bool focus = (hasFocus() || viewport()->hasFocus()) && current.isValid(); + const QAbstractItemModel* itemModel = model(); + const QItemSelectionModel* selections = selectionModel(); + const bool focus = + (hasFocus() || viewport()->hasFocus()) && current.isValid(); const QStyle::State state = option.state; const QAbstractItemView::State viewState = this->state(); const bool enabled = (state & QStyle::State_Enabled) != 0; int maxSize = (flow() == TopToBottom) - ? viewport()->size().width() - 2 * spacing() - : viewport()->size().height() - 2 * spacing(); + ? viewport()->size().width() - 2 * spacing() + : viewport()->size().height() - 2 * spacing(); QVector::const_iterator end = toBeRendered.constEnd(); - for (QVector::const_iterator it = toBeRendered.constBegin(); it != end; ++it) { + for (QVector::const_iterator it = toBeRendered.constBegin(); + it != end; ++it) { if (!it->isValid()) { continue; } @@ -260,18 +263,17 @@ void GroupedIconView::paintEvent(QPaintEvent* e) { } if (focus && current == *it) { option.state |= QStyle::State_HasFocus; - if (viewState == EditingState) - option.state |= QStyle::State_Editing; + if (viewState == EditingState) option.state |= QStyle::State_Editing; } itemDelegate()->paint(&painter, option, *it); } // Draw headers - foreach (const Header& header, headers_) { - const QRect header_rect = QRect( - header_indent_, header.y, - viewport()->width() - header_indent_ * 2, header_height()); + foreach(const Header & header, headers_) { + const QRect header_rect = + QRect(header_indent_, header.y, + viewport()->width() - header_indent_ * 2, header_height()); // Is this header contained in the area we're drawing? if (!header_rect.intersects(viewport_rect)) { @@ -281,28 +283,30 @@ void GroupedIconView::paintEvent(QPaintEvent* e) { // Draw the header DrawHeader(&painter, header_rect.translated(-horizontalOffset(), -verticalOffset()), - font(), - palette(), + font(), palette(), model()->index(header.first_row, 0).data(Role_Group).toString()); } } -void GroupedIconView::setSelection(const QRect& rect, QItemSelectionModel::SelectionFlags command) { - QVector indexes(IntersectingItems(rect.translated(horizontalOffset(), verticalOffset()))); +void GroupedIconView::setSelection( + const QRect& rect, QItemSelectionModel::SelectionFlags command) { + QVector indexes( + IntersectingItems(rect.translated(horizontalOffset(), verticalOffset()))); QItemSelection selection; - foreach (const QModelIndex& index, indexes) { + foreach(const QModelIndex & index, indexes) { selection << QItemSelectionRange(index); } selectionModel()->select(selection, command); } -QVector GroupedIconView::IntersectingItems(const QRect& rect) const { +QVector GroupedIconView::IntersectingItems(const QRect& rect) + const { QVector ret; const int count = visual_rects_.count(); - for (int i=0 ; iindex(i, 0)); } @@ -311,15 +315,17 @@ QVector GroupedIconView::IntersectingItems(const QRect& rect) const return ret; } -QRegion GroupedIconView::visualRegionForSelection(const QItemSelection& selection) const { +QRegion GroupedIconView::visualRegionForSelection( + const QItemSelection& selection) const { QRegion ret; - foreach (const QModelIndex& index, selection.indexes()) { + foreach(const QModelIndex & index, selection.indexes()) { ret += visual_rects_[index.row()]; } return ret; } -QModelIndex GroupedIconView::moveCursor(CursorAction action, Qt::KeyboardModifiers) { +QModelIndex GroupedIconView::moveCursor(CursorAction action, + Qt::KeyboardModifiers) { if (model()->rowCount() == 0) { return QModelIndex(); } @@ -330,16 +336,28 @@ QModelIndex GroupedIconView::moveCursor(CursorAction action, Qt::KeyboardModifie } switch (action) { - case MoveUp: ret = IndexAboveOrBelow(ret, -1); break; + case MoveUp: + ret = IndexAboveOrBelow(ret, -1); + break; case MovePrevious: - case MoveLeft: ret --; break; - case MoveDown: ret = IndexAboveOrBelow(ret, +1); break; + case MoveLeft: + ret--; + break; + case MoveDown: + ret = IndexAboveOrBelow(ret, +1); + break; case MoveNext: - case MoveRight: ret ++; break; + case MoveRight: + ret++; + break; case MovePageUp: - case MoveHome: ret = 0; break; + case MoveHome: + ret = 0; + break; case MovePageDown: - case MoveEnd: ret = model()->rowCount() - 1; break; + case MoveEnd: + ret = model()->rowCount() - 1; + break; } return model()->index(qBound(0, ret, model()->rowCount()), 0); @@ -353,8 +371,7 @@ int GroupedIconView::IndexAboveOrBelow(int index, int d) const { const QPoint center(rect.center()); if ((center.y() <= orig_rect.top() || center.y() >= orig_rect.bottom()) && - center.x() >= orig_rect.left() && - center.x() <= orig_rect.right()) { + center.x() >= orig_rect.left() && center.x() <= orig_rect.right()) { return index; } diff --git a/src/widgets/groupediconview.h b/src/widgets/groupediconview.h index 4af40430f..fefe9ca4e 100644 --- a/src/widgets/groupediconview.h +++ b/src/widgets/groupediconview.h @@ -22,35 +22,34 @@ class MultiSortFilterProxy; - class GroupedIconView : public QListView { Q_OBJECT // Vertical space separating a header from the items above and below it. Q_PROPERTY(int header_spacing READ header_spacing WRITE set_header_spacing) - // Horizontal space separating a header from the left and right edges of the widget. + // Horizontal space separating a header from the left and right edges of the + // widget. Q_PROPERTY(int header_indent READ header_indent WRITE set_header_indent) - // Horizontal space separating an item from the left and right edges of the widget. + // Horizontal space separating an item from the left and right edges of the + // widget. Q_PROPERTY(int item_indent READ item_indent WRITE set_item_indent) // The text of each group's header. Must contain "%1". Q_PROPERTY(QString header_text READ header_text WRITE set_header_text); -public: + public: GroupedIconView(QWidget* parent = 0); - enum Role { - Role_Group = 1158300, - }; + enum Role { Role_Group = 1158300, }; void AddSortSpec(int role, Qt::SortOrder order = Qt::AscendingOrder); int header_spacing() const { return header_spacing_; } int header_indent() const { return header_indent_; } int item_indent() const { return item_indent_; } - const QString& header_text() const { return header_text_;} + const QString& header_text() const { return header_text_; } void set_header_spacing(int value) { header_spacing_ = value; } void set_header_indent(int value) { header_indent_ = value; } @@ -65,7 +64,7 @@ public: const QFont& font, const QPalette& palette, const QString& text); -protected: + protected: virtual int header_height() const; // QWidget @@ -76,14 +75,15 @@ protected: void dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight); QModelIndex indexAt(const QPoint& p) const; void rowsInserted(const QModelIndex& parent, int start, int end); - void setSelection(const QRect& rect, QItemSelectionModel::SelectionFlags command); + void setSelection(const QRect& rect, + QItemSelectionModel::SelectionFlags command); QRect visualRect(const QModelIndex& index) const; QRegion visualRegionForSelection(const QItemSelection& selection) const; -private slots: + private slots: void LayoutItems(); -private: + private: static const int kBarThickness; static const int kBarMarginTop; @@ -110,4 +110,4 @@ private: QString header_text_; }; -#endif // GROUPEDICONVIEW_H +#endif // GROUPEDICONVIEW_H diff --git a/src/widgets/lineedit.cpp b/src/widgets/lineedit.cpp index 5d524a675..0ded8b3bd 100644 --- a/src/widgets/lineedit.cpp +++ b/src/widgets/lineedit.cpp @@ -26,15 +26,14 @@ ExtendedEditor::ExtendedEditor(QWidget* widget, int extra_right_padding, bool draw_hint) - : LineEditInterface(widget), - has_clear_button_(true), - clear_button_(new QToolButton(widget)), - reset_button_(new QToolButton(widget)), - extra_right_padding_(extra_right_padding), - draw_hint_(draw_hint), - font_point_size_(widget->font().pointSizeF() - 1), - is_rtl_(false) -{ + : LineEditInterface(widget), + has_clear_button_(true), + clear_button_(new QToolButton(widget)), + reset_button_(new QToolButton(widget)), + extra_right_padding_(extra_right_padding), + draw_hint_(draw_hint), + font_point_size_(widget->font().pointSizeF() - 1), + is_rtl_(false) { clear_button_->setIcon(IconLoader::Load("edit-clear-locationbar-ltr")); clear_button_->setIconSize(QSize(16, 16)); clear_button_->setCursor(Qt::ArrowCursor); @@ -45,7 +44,8 @@ ExtendedEditor::ExtendedEditor(QWidget* widget, int extra_right_padding, QStyleOption opt; opt.initFrom(widget); - reset_button_->setIcon(widget->style()->standardIcon(QStyle::SP_DialogResetButton, &opt, widget)); + reset_button_->setIcon(widget->style()->standardIcon( + QStyle::SP_DialogResetButton, &opt, widget)); reset_button_->setIconSize(QSize(16, 16)); reset_button_->setCursor(Qt::ArrowCursor); reset_button_->setStyleSheet("QToolButton { border: none; padding: 0px; }"); @@ -80,19 +80,25 @@ void ExtendedEditor::set_reset_button(bool visible) { } void ExtendedEditor::UpdateButtonGeometry() { - const int frame_width = widget_->style()->pixelMetric(QStyle::PM_DefaultFrameWidth); - const int left = frame_width + 1 + ( - has_clear_button() ? clear_button_->sizeHint().width() : 0); - const int right = frame_width + 1 + ( - has_reset_button() ? reset_button_->sizeHint().width() : 0); + const int frame_width = + widget_->style()->pixelMetric(QStyle::PM_DefaultFrameWidth); + const int left = frame_width + 1 + + (has_clear_button() ? clear_button_->sizeHint().width() : 0); + const int right = + frame_width + 1 + + (has_reset_button() ? reset_button_->sizeHint().width() : 0); widget_->setStyleSheet( QString("QLineEdit { padding-left: %1px; padding-right: %2px; }") - .arg(left).arg(right)); + .arg(left) + .arg(right)); QSize msz = widget_->minimumSizeHint(); - widget_->setMinimumSize(msz.width() + (clear_button_->sizeHint().width() + frame_width + 1) * 2 + extra_right_padding_, - qMax(msz.height(), clear_button_->sizeHint().height() + frame_width * 2 + 2)); + widget_->setMinimumSize( + msz.width() + (clear_button_->sizeHint().width() + frame_width + 1) * 2 + + extra_right_padding_, + qMax(msz.height(), + clear_button_->sizeHint().height() + frame_width * 2 + 2)); } void ExtendedEditor::Paint(QPaintDevice* device) { @@ -113,7 +119,7 @@ void ExtendedEditor::Paint(QPaintDevice* device) { p.setPen(widget_->palette().color(QPalette::Disabled, QPalette::Text)); p.setFont(font); - QRect r(5, kBorder, device->width() - 10, device->height() - kBorder*2); + QRect r(5, kBorder, device->width() - 10, device->height() - kBorder * 2); p.drawText(r, Qt::AlignLeft | Qt::AlignVCenter, m.elidedText(hint_, Qt::ElideRight, r.width())); } @@ -124,23 +130,22 @@ void ExtendedEditor::Paint(QPaintDevice* device) { void ExtendedEditor::Resize() { const QSize sz = clear_button_->sizeHint(); - const int frame_width = widget_->style()->pixelMetric(QStyle::PM_DefaultFrameWidth); + const int frame_width = + widget_->style()->pixelMetric(QStyle::PM_DefaultFrameWidth); const int y = (widget_->rect().height() - sz.height()) / 2; clear_button_->move(frame_width, y); if (!is_rtl_) { - reset_button_->move(widget_->width() - frame_width - sz.width() - extra_right_padding_, y); + reset_button_->move( + widget_->width() - frame_width - sz.width() - extra_right_padding_, y); } else { - reset_button_->move((has_clear_button() ? sz.width() + 4 : 0) + frame_width, y); + reset_button_->move((has_clear_button() ? sz.width() + 4 : 0) + frame_width, + y); } } - -LineEdit::LineEdit(QWidget* parent) - : QLineEdit(parent), - ExtendedEditor(this) -{ +LineEdit::LineEdit(QWidget* parent) : QLineEdit(parent), ExtendedEditor(this) { connect(reset_button_, SIGNAL(clicked()), SIGNAL(Reset())); connect(this, SIGNAL(textChanged(QString)), SLOT(text_changed(QString))); } @@ -150,7 +155,8 @@ void LineEdit::text_changed(const QString& text) { // Consider empty string as LTR set_rtl(false); } else { - // For some reason Qt will detect any text with LTR at the end as LTR, so instead + // For some reason Qt will detect any text with LTR at the end as LTR, so + // instead // compare only the first character set_rtl(QString(text.at(0)).isRightToLeft()); } @@ -167,13 +173,11 @@ void LineEdit::resizeEvent(QResizeEvent* e) { Resize(); } - TextEdit::TextEdit(QWidget* parent) - : QPlainTextEdit(parent), - ExtendedEditor(this) -{ + : QPlainTextEdit(parent), ExtendedEditor(this) { connect(reset_button_, SIGNAL(clicked()), SIGNAL(Reset())); - connect(this, SIGNAL(textChanged()), viewport(), SLOT(update())); // To clear the hint + connect(this, SIGNAL(textChanged()), viewport(), + SLOT(update())); // To clear the hint } void TextEdit::paintEvent(QPaintEvent* e) { @@ -186,11 +190,8 @@ void TextEdit::resizeEvent(QResizeEvent* e) { Resize(); } - SpinBox::SpinBox(QWidget* parent) - : QSpinBox(parent), - ExtendedEditor(this, 14, false) -{ + : QSpinBox(parent), ExtendedEditor(this, 14, false) { connect(reset_button_, SIGNAL(clicked()), SIGNAL(Reset())); } @@ -205,7 +206,6 @@ void SpinBox::resizeEvent(QResizeEvent* e) { } QString SpinBox::textFromValue(int val) const { - if (val <= 0 && !hint_.isEmpty()) - return "-"; + if (val <= 0 && !hint_.isEmpty()) return "-"; return QSpinBox::textFromValue(val); } diff --git a/src/widgets/lineedit.h b/src/widgets/lineedit.h index e730ae29d..8a192a699 100644 --- a/src/widgets/lineedit.h +++ b/src/widgets/lineedit.h @@ -27,7 +27,7 @@ class QToolButton; class LineEditInterface { -public: + public: LineEditInterface(QWidget* widget) : widget_(widget) {} QWidget* widget() const { return widget_; } @@ -45,13 +45,14 @@ public: virtual void set_enabled(bool enabled) = 0; -protected: + protected: QWidget* widget_; }; class ExtendedEditor : public LineEditInterface { -public: - ExtendedEditor(QWidget* widget, int extra_right_padding = 0, bool draw_hint = true); + public: + ExtendedEditor(QWidget* widget, int extra_right_padding = 0, + bool draw_hint = true); virtual ~ExtendedEditor() {} virtual bool is_empty() const { return text().isEmpty(); } @@ -69,14 +70,14 @@ public: qreal font_point_size() const { return font_point_size_; } void set_font_point_size(qreal size) { font_point_size_ = size; } -protected: + protected: void Paint(QPaintDevice* device); void Resize(); -private: + private: void UpdateButtonGeometry(); -protected: + protected: QString hint_; bool has_clear_button_; @@ -89,15 +90,17 @@ protected: bool is_rtl_; }; -class LineEdit : public QLineEdit, - public ExtendedEditor { +class LineEdit : public QLineEdit, public ExtendedEditor { Q_OBJECT Q_PROPERTY(QString hint READ hint WRITE set_hint); - Q_PROPERTY(qreal font_point_size READ font_point_size WRITE set_font_point_size); - Q_PROPERTY(bool has_clear_button READ has_clear_button WRITE set_clear_button); - Q_PROPERTY(bool has_reset_button READ has_reset_button WRITE set_reset_button); + Q_PROPERTY(qreal font_point_size READ font_point_size WRITE + set_font_point_size); + Q_PROPERTY(bool has_clear_button READ has_clear_button WRITE + set_clear_button); + Q_PROPERTY(bool has_reset_button READ has_reset_button WRITE + set_reset_button); -public: + public: LineEdit(QWidget* parent = 0); // ExtendedEditor @@ -106,29 +109,30 @@ public: void set_text(const QString& text) { QLineEdit::setText(text); } void set_enabled(bool enabled) { QLineEdit::setEnabled(enabled); } -protected: + protected: void paintEvent(QPaintEvent*); void resizeEvent(QResizeEvent*); -private: + private: bool is_rtl() const { return is_rtl_; } void set_rtl(bool rtl) { is_rtl_ = rtl; } -private slots: + private slots: void text_changed(const QString& text); signals: void Reset(); }; -class TextEdit : public QPlainTextEdit, - public ExtendedEditor { +class TextEdit : public QPlainTextEdit, public ExtendedEditor { Q_OBJECT Q_PROPERTY(QString hint READ hint WRITE set_hint); - Q_PROPERTY(bool has_clear_button READ has_clear_button WRITE set_clear_button); - Q_PROPERTY(bool has_reset_button READ has_reset_button WRITE set_reset_button); + Q_PROPERTY(bool has_clear_button READ has_clear_button WRITE + set_clear_button); + Q_PROPERTY(bool has_reset_button READ has_reset_button WRITE + set_reset_button); -public: + public: TextEdit(QWidget* parent = 0); // ExtendedEditor @@ -137,7 +141,7 @@ public: void set_text(const QString& text) { QPlainTextEdit::setPlainText(text); } void set_enabled(bool enabled) { QPlainTextEdit::setEnabled(enabled); } -protected: + protected: void paintEvent(QPaintEvent*); void resizeEvent(QResizeEvent*); @@ -145,14 +149,15 @@ signals: void Reset(); }; -class SpinBox : public QSpinBox, - public ExtendedEditor { +class SpinBox : public QSpinBox, public ExtendedEditor { Q_OBJECT Q_PROPERTY(QString hint READ hint WRITE set_hint); - Q_PROPERTY(bool has_clear_button READ has_clear_button WRITE set_clear_button); - Q_PROPERTY(bool has_reset_button READ has_reset_button WRITE set_reset_button); + Q_PROPERTY(bool has_clear_button READ has_clear_button WRITE + set_clear_button); + Q_PROPERTY(bool has_reset_button READ has_reset_button WRITE + set_reset_button); -public: + public: SpinBox(QWidget* parent = 0); // QSpinBox @@ -165,7 +170,7 @@ public: void set_text(const QString& text) { QSpinBox::setValue(text.toInt()); } void set_enabled(bool enabled) { QSpinBox::setEnabled(enabled); } -protected: + protected: void paintEvent(QPaintEvent*); void resizeEvent(QResizeEvent*); @@ -173,4 +178,4 @@ signals: void Reset(); }; -#endif // LINEEDIT_H +#endif // LINEEDIT_H diff --git a/src/widgets/linetextedit.cpp b/src/widgets/linetextedit.cpp index 119161e57..c974ae17e 100644 --- a/src/widgets/linetextedit.cpp +++ b/src/widgets/linetextedit.cpp @@ -19,9 +19,7 @@ #include -LineTextEdit::LineTextEdit(QWidget *parent) - : QTextEdit(parent) -{ +LineTextEdit::LineTextEdit(QWidget* parent) : QTextEdit(parent) { setWordWrapMode(QTextOption::NoWrap); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -39,13 +37,10 @@ QSize LineTextEdit::sizeHint() const { return QSize(w, h); } -QSize LineTextEdit::minimumSizeHint() const { - return sizeHint(); -} +QSize LineTextEdit::minimumSizeHint() const { return sizeHint(); } void LineTextEdit::keyPressEvent(QKeyEvent* e) { - if (e->key() == Qt::Key_Enter || - e->key() == Qt::Key_Return) { + if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) { e->ignore(); } else { QTextEdit::keyPressEvent(e); diff --git a/src/widgets/linetextedit.h b/src/widgets/linetextedit.h index 004912375..f66c981af 100644 --- a/src/widgets/linetextedit.h +++ b/src/widgets/linetextedit.h @@ -23,14 +23,14 @@ class LineTextEdit : public QTextEdit { Q_OBJECT -public: + public: LineTextEdit(QWidget* parent = 0); QSize sizeHint() const; QSize minimumSizeHint() const; -protected: + protected: void keyPressEvent(QKeyEvent* e); }; -#endif // LINETEXTEDIT_H +#endif // LINETEXTEDIT_H diff --git a/src/widgets/loginstatewidget.cpp b/src/widgets/loginstatewidget.cpp index d302549af..8abbbc87c 100644 --- a/src/widgets/loginstatewidget.cpp +++ b/src/widgets/loginstatewidget.cpp @@ -25,10 +25,7 @@ #include LoginStateWidget::LoginStateWidget(QWidget* parent) - : QWidget(parent), - ui_(new Ui_LoginStateWidget), - state_(LoggedOut) -{ + : QWidget(parent), ui_(new Ui_LoginStateWidget), state_(LoggedOut) { ui_->setupUi(this); ui_->signed_in->hide(); ui_->expires->hide(); @@ -44,9 +41,7 @@ LoginStateWidget::LoginStateWidget(QWidget* parent) connect(ui_->sign_out, SIGNAL(clicked()), SLOT(Logout())); } -LoginStateWidget::~LoginStateWidget() { - delete ui_; -} +LoginStateWidget::~LoginStateWidget() { delete ui_; } void LoginStateWidget::Logout() { SetLoggedIn(LoggedOut); @@ -72,9 +67,10 @@ void LoginStateWidget::SetLoggedIn(State state, const QString& account_name) { if (account_name.isEmpty()) ui_->signed_in_label->setText("" + tr("You are signed in.") + ""); else - ui_->signed_in_label->setText(tr("You are signed in as %1.").arg("" + account_name + "")); + ui_->signed_in_label->setText( + tr("You are signed in as %1.").arg("" + account_name + "")); - foreach (QWidget* widget, credential_groups_) { + foreach(QWidget * widget, credential_groups_) { widget->setVisible(state != LoggedIn); widget->setEnabled(state != LoginInProgress); } @@ -139,7 +135,7 @@ void LoginStateWidget::SetExpires(const QDate& expires) { if (expires.isValid()) { const QString expires_text = expires.toString(Qt::SystemLocaleLongDate); - ui_->expires_label->setText(tr("Expires on %1").arg("" + expires_text + "")); + ui_->expires_label->setText( + tr("Expires on %1").arg("" + expires_text + "")); } } - diff --git a/src/widgets/loginstatewidget.h b/src/widgets/loginstatewidget.h index 71dc0912f..a4d3ed562 100644 --- a/src/widgets/loginstatewidget.h +++ b/src/widgets/loginstatewidget.h @@ -26,15 +26,11 @@ class Ui_LoginStateWidget; class LoginStateWidget : public QWidget { Q_OBJECT -public: + public: LoginStateWidget(QWidget* parent = 0); ~LoginStateWidget(); - enum State { - LoggedIn, - LoginInProgress, - LoggedOut - }; + enum State { LoggedIn, LoginInProgress, LoggedOut }; // Installs an event handler on the field so that pressing enter will emit // LoginClicked() instead of doing the default action (closing the dialog). @@ -47,7 +43,7 @@ public: // QObject bool eventFilter(QObject* object, QEvent* event); -public slots: + public slots: // Changes the "You are logged in/out" label, shows/hides any QGroupBoxes // added with AddCredentialGroup. void SetLoggedIn(State state, const QString& account_name = QString::null); @@ -64,11 +60,11 @@ signals: void LogoutClicked(); void LoginClicked(); -private slots: + private slots: void Logout(); void FocusLastCredentialField(); -private: + private: Ui_LoginStateWidget* ui_; State state_; @@ -77,4 +73,4 @@ private: QList credential_groups_; }; -#endif // LOGINSTATEWIDGET_H +#endif // LOGINSTATEWIDGET_H diff --git a/src/widgets/multiloadingindicator.cpp b/src/widgets/multiloadingindicator.cpp index cf91b92b2..cf048ce5f 100644 --- a/src/widgets/multiloadingindicator.cpp +++ b/src/widgets/multiloadingindicator.cpp @@ -26,17 +26,17 @@ const int MultiLoadingIndicator::kVerticalPadding = 4; const int MultiLoadingIndicator::kHorizontalPadding = 6; const int MultiLoadingIndicator::kSpacing = 6; -MultiLoadingIndicator::MultiLoadingIndicator(QWidget *parent) - : QWidget(parent), - spinner_(new BusyIndicator(this)) -{ +MultiLoadingIndicator::MultiLoadingIndicator(QWidget* parent) + : QWidget(parent), spinner_(new BusyIndicator(this)) { spinner_->move(kHorizontalPadding, kVerticalPadding); setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); } QSize MultiLoadingIndicator::sizeHint() const { - const int width = kHorizontalPadding*2 + spinner_->sizeHint().width() + kSpacing + fontMetrics().width(text_); - const int height = kVerticalPadding*2 + qMax(spinner_->sizeHint().height(), fontMetrics().height()); + const int width = kHorizontalPadding * 2 + spinner_->sizeHint().width() + + kSpacing + fontMetrics().width(text_); + const int height = kVerticalPadding * 2 + qMax(spinner_->sizeHint().height(), + fontMetrics().height()); return QSize(width, height); } @@ -50,7 +50,7 @@ void MultiLoadingIndicator::UpdateText() { QList tasks = task_manager_->GetTasks(); QStringList strings; - foreach (const TaskManager::Task& task, tasks) { + foreach(const TaskManager::Task & task, tasks) { QString task_text(task.name); task_text[0] = task_text[0].toLower(); @@ -77,10 +77,11 @@ void MultiLoadingIndicator::paintEvent(QPaintEvent*) { QPainter p(this); const QRect text_rect( - kHorizontalPadding + spinner_->sizeHint().width() + kSpacing, - kVerticalPadding, - width() - kHorizontalPadding*2 - spinner_->sizeHint().width() - kSpacing, - height() - kVerticalPadding*2); - p.drawText(text_rect, Qt::TextSingleLine | Qt::AlignLeft, - fontMetrics().elidedText(text_, Qt::ElideRight, text_rect.width())); + kHorizontalPadding + spinner_->sizeHint().width() + kSpacing, + kVerticalPadding, width() - kHorizontalPadding * 2 - + spinner_->sizeHint().width() - kSpacing, + height() - kVerticalPadding * 2); + p.drawText( + text_rect, Qt::TextSingleLine | Qt::AlignLeft, + fontMetrics().elidedText(text_, Qt::ElideRight, text_rect.width())); } diff --git a/src/widgets/multiloadingindicator.h b/src/widgets/multiloadingindicator.h index 9dc918bf4..4f7fa0c00 100644 --- a/src/widgets/multiloadingindicator.h +++ b/src/widgets/multiloadingindicator.h @@ -26,7 +26,7 @@ class TaskManager; class MultiLoadingIndicator : public QWidget { Q_OBJECT -public: + public: MultiLoadingIndicator(QWidget* parent = 0); static const int kVerticalPadding; @@ -40,17 +40,17 @@ public: signals: void TaskCountChange(int tasks); -protected: + protected: void paintEvent(QPaintEvent*); -private slots: + private slots: void UpdateText(); -private: + private: TaskManager* task_manager_; BusyIndicator* spinner_; QString text_; }; -#endif // MULTILOADINGINDICATOR_H +#endif // MULTILOADINGINDICATOR_H diff --git a/src/widgets/nowplayingwidget.cpp b/src/widgets/nowplayingwidget.cpp index 7b3ebc4a5..796d1d061 100644 --- a/src/widgets/nowplayingwidget.cpp +++ b/src/widgets/nowplayingwidget.cpp @@ -57,31 +57,30 @@ const int NowPlayingWidget::kBottomOffset = 0; // Border for large mode const int NowPlayingWidget::kTopBorder = 4; - NowPlayingWidget::NowPlayingWidget(QWidget* parent) - : QWidget(parent), - app_(nullptr), - album_cover_choice_controller_(new AlbumCoverChoiceController(this)), - mode_(SmallSongDetails), - menu_(new QMenu(this)), - above_statusbar_action_(nullptr), - visible_(false), - small_ideal_height_(0), - show_hide_animation_(new QTimeLine(500, this)), - fade_animation_(new QTimeLine(1000, this)), - details_(new QTextDocument(this)), - previous_track_opacity_(0.0), - bask_in_his_glory_action_(nullptr), - downloading_covers_(false), - aww_(false), - kittens_(nullptr), - pending_kitten_(0) -{ + : QWidget(parent), + app_(nullptr), + album_cover_choice_controller_(new AlbumCoverChoiceController(this)), + mode_(SmallSongDetails), + menu_(new QMenu(this)), + above_statusbar_action_(nullptr), + visible_(false), + small_ideal_height_(0), + show_hide_animation_(new QTimeLine(500, this)), + fade_animation_(new QTimeLine(1000, this)), + details_(new QTextDocument(this)), + previous_track_opacity_(0.0), + bask_in_his_glory_action_(nullptr), + downloading_covers_(false), + aww_(false), + kittens_(nullptr), + pending_kitten_(0) { // Load settings QSettings s; s.beginGroup(kSettingsGroup); mode_ = Mode(s.value("mode", SmallSongDetails).toInt()); - album_cover_choice_controller_->search_cover_auto_action()->setChecked(s.value("search_for_cover_auto", false).toBool()); + album_cover_choice_controller_->search_cover_auto_action()->setChecked( + s.value("search_for_cover_auto", false).toBool()); // Accept drops for setting album art setAcceptDrops(true); @@ -90,8 +89,10 @@ NowPlayingWidget::NowPlayingWidget(QWidget* parent) QActionGroup* mode_group = new QActionGroup(this); QSignalMapper* mode_mapper = new QSignalMapper(this); connect(mode_mapper, SIGNAL(mapped(int)), SLOT(SetMode(int))); - CreateModeAction(SmallSongDetails, tr("Small album cover"), mode_group, mode_mapper); - CreateModeAction(LargeSongDetails, tr("Large album cover"), mode_group, mode_mapper); + CreateModeAction(SmallSongDetails, tr("Small album cover"), mode_group, + mode_mapper); + CreateModeAction(LargeSongDetails, tr("Large album cover"), mode_group, + mode_mapper); menu_->addActions(mode_group->actions()); menu_->addSeparator(); @@ -121,19 +122,24 @@ NowPlayingWidget::NowPlayingWidget(QWidget* parent) above_statusbar_action_ = menu_->addAction(tr("Show above status bar")); above_statusbar_action_->setCheckable(true); - connect(above_statusbar_action_, SIGNAL(toggled(bool)), SLOT(ShowAboveStatusBar(bool))); - above_statusbar_action_->setChecked(s.value("above_status_bar", false).toBool()); + connect(above_statusbar_action_, SIGNAL(toggled(bool)), + SLOT(ShowAboveStatusBar(bool))); + above_statusbar_action_->setChecked( + s.value("above_status_bar", false).toBool()); - bask_in_his_glory_action_ = menu_->addAction(tr("ALL GLORY TO THE HYPNOTOAD")); + bask_in_his_glory_action_ = + menu_->addAction(tr("ALL GLORY TO THE HYPNOTOAD")); bask_in_his_glory_action_->setVisible(false); connect(bask_in_his_glory_action_, SIGNAL(triggered()), SLOT(Bask())); // Animations - connect(show_hide_animation_, SIGNAL(frameChanged(int)), SLOT(SetHeight(int))); + connect(show_hide_animation_, SIGNAL(frameChanged(int)), + SLOT(SetHeight(int))); setMaximumHeight(0); - connect(fade_animation_, SIGNAL(valueChanged(qreal)), SLOT(FadePreviousTrack(qreal))); - fade_animation_->setDirection(QTimeLine::Backward); // 1.0 -> 0.0 + connect(fade_animation_, SIGNAL(valueChanged(qreal)), + SLOT(FadePreviousTrack(qreal))); + fade_animation_->setDirection(QTimeLine::Backward); // 1.0 -> 0.0 UpdateHeight(); @@ -141,25 +147,25 @@ NowPlayingWidget::NowPlayingWidget(QWidget* parent) this, SLOT(AutomaticCoverSearchDone())); } -NowPlayingWidget::~NowPlayingWidget() { -} +NowPlayingWidget::~NowPlayingWidget() {} void NowPlayingWidget::SetApplication(Application* app) { app_ = app; album_cover_choice_controller_->SetApplication(app_); - connect(app_->current_art_loader(), SIGNAL(ArtLoaded(Song,QString,QImage)), - SLOT(AlbumArtLoaded(Song,QString,QImage))); + connect(app_->current_art_loader(), SIGNAL(ArtLoaded(Song, QString, QImage)), + SLOT(AlbumArtLoaded(Song, QString, QImage))); } -void NowPlayingWidget::CreateModeAction(Mode mode, const QString &text, QActionGroup *group, QSignalMapper* mapper) { +void NowPlayingWidget::CreateModeAction(Mode mode, const QString& text, + QActionGroup* group, + QSignalMapper* mapper) { QAction* action = new QAction(text, group); action->setCheckable(true); mapper->setMapping(action, mode); connect(action, SIGNAL(triggered()), mapper, SLOT(map())); - if (mode == mode_) - action->setChecked(true); + if (mode == mode_) action->setChecked(true); } void NowPlayingWidget::set_ideal_height(int height) { @@ -173,15 +179,16 @@ QSize NowPlayingWidget::sizeHint() const { void NowPlayingWidget::UpdateHeight() { switch (mode_) { - case SmallSongDetails: - cover_loader_options_.desired_height_ = small_ideal_height_; - total_height_ = small_ideal_height_; - break; + case SmallSongDetails: + cover_loader_options_.desired_height_ = small_ideal_height_; + total_height_ = small_ideal_height_; + break; - case LargeSongDetails: - cover_loader_options_.desired_height_ = qMin(kMaxCoverSize, width()); - total_height_ = kTopBorder + cover_loader_options_.desired_height_ + kBottomOffset; - break; + case LargeSongDetails: + cover_loader_options_.desired_height_ = qMin(kMaxCoverSize, width()); + total_height_ = + kTopBorder + cover_loader_options_.desired_height_ + kBottomOffset; + break; } // Update the animation settings and resize the widget now if we're visible @@ -198,9 +205,7 @@ void NowPlayingWidget::UpdateHeight() { updateGeometry(); } -void NowPlayingWidget::Stopped() { - SetVisible(false); -} +void NowPlayingWidget::Stopped() { SetVisible(false); } void NowPlayingWidget::UpdateDetailsText() { QString html; @@ -214,7 +219,8 @@ void NowPlayingWidget::UpdateDetailsText() { case LargeSongDetails: details_->setTextWidth(cover_loader_options_.desired_height_); - details_->setDefaultStyleSheet("p {" + details_->setDefaultStyleSheet( + "p {" " font-size: small;" " color: white;" "}"); @@ -233,7 +239,7 @@ void NowPlayingWidget::UpdateDetailsText() { void NowPlayingWidget::ScaleCover() { cover_ = QPixmap::fromImage( - AlbumCoverLoader::ScaleAndPad(cover_loader_options_, original_)); + AlbumCoverLoader::ScaleAndPad(cover_loader_options_, original_)); update(); } @@ -249,7 +255,8 @@ void NowPlayingWidget::AlbumArtLoaded(const Song& metadata, const QString& uri, downloading_covers_ = false; if (aww_) { - pending_kitten_ = kittens_->LoadKitten(app_->current_art_loader()->options()); + pending_kitten_ = + kittens_->LoadKitten(app_->current_art_loader()->options()); return; } @@ -282,20 +289,18 @@ void NowPlayingWidget::SetImage(const QImage& image) { } } -void NowPlayingWidget::SetHeight(int height) { - setMaximumHeight(height); -} +void NowPlayingWidget::SetHeight(int height) { setMaximumHeight(height); } void NowPlayingWidget::SetVisible(bool visible) { - if (visible == visible_) - return; + if (visible == visible_) return; visible_ = visible; - show_hide_animation_->setDirection(visible ? QTimeLine::Forward : QTimeLine::Backward); + show_hide_animation_->setDirection(visible ? QTimeLine::Forward + : QTimeLine::Backward); show_hide_animation_->start(); } -void NowPlayingWidget::paintEvent(QPaintEvent *e) { +void NowPlayingWidget::paintEvent(QPaintEvent* e) { QPainter p(this); DrawContents(&p); @@ -307,60 +312,66 @@ void NowPlayingWidget::paintEvent(QPaintEvent *e) { } } -void NowPlayingWidget::DrawContents(QPainter *p) { +void NowPlayingWidget::DrawContents(QPainter* p) { switch (mode_) { - case SmallSongDetails: - if (hypnotoad_) { - p->drawPixmap(0, 0, small_ideal_height_, small_ideal_height_, hypnotoad_->currentPixmap()); - } else { + case SmallSongDetails: + if (hypnotoad_) { + p->drawPixmap(0, 0, small_ideal_height_, small_ideal_height_, + hypnotoad_->currentPixmap()); + } else { + // Draw the cover + p->drawPixmap(0, 0, small_ideal_height_, small_ideal_height_, cover_); + if (downloading_covers_) { + p->drawPixmap(small_ideal_height_ - 18, 6, 16, 16, + spinner_animation_->currentPixmap()); + } + } + + // Draw the details + p->translate(small_ideal_height_ + kPadding, 0); + details_->drawContents(p); + p->translate(-small_ideal_height_ - kPadding, 0); + break; + + case LargeSongDetails: + const int total_size = qMin(kMaxCoverSize, width()); + const int x_offset = + (width() - cover_loader_options_.desired_height_) / 2; + + // Draw the black background + p->fillRect(QRect(0, kTopBorder, width(), height() - kTopBorder), + Qt::black); + // Draw the cover - p->drawPixmap(0, 0, small_ideal_height_, small_ideal_height_, cover_); - if (downloading_covers_) { - p->drawPixmap(small_ideal_height_ - 18, 6, 16, 16, spinner_animation_->currentPixmap()); + if (hypnotoad_) { + p->drawPixmap(x_offset, kTopBorder, total_size, total_size, + hypnotoad_->currentPixmap()); + } else { + p->drawPixmap(x_offset, kTopBorder, total_size, total_size, cover_); + if (downloading_covers_) { + p->drawPixmap(total_size - 31, 40, 16, 16, + spinner_animation_->currentPixmap()); + } } - } - // Draw the details - p->translate(small_ideal_height_ + kPadding, 0); - details_->drawContents(p); - p->translate(-small_ideal_height_ - kPadding, 0); - break; + // Work out how high the text is going to be + const int text_height = details_->size().height(); + const int gradient_mid = height() - qMax(text_height, kBottomOffset); - case LargeSongDetails: - const int total_size = qMin(kMaxCoverSize, width()); - const int x_offset = (width() - cover_loader_options_.desired_height_) / 2; + // Draw the black fade + QLinearGradient gradient(0, gradient_mid - kGradientHead, 0, + gradient_mid + kGradientTail); + gradient.setColorAt(0, QColor(0, 0, 0, 0)); + gradient.setColorAt(1, QColor(0, 0, 0, 255)); - // Draw the black background - p->fillRect(QRect(0, kTopBorder, width(), height() - kTopBorder), Qt::black); + p->fillRect(0, gradient_mid - kGradientHead, width(), + height() - (gradient_mid - kGradientHead), gradient); - // Draw the cover - if (hypnotoad_) { - p->drawPixmap(x_offset, kTopBorder, total_size, total_size, hypnotoad_->currentPixmap()); - } else { - p->drawPixmap(x_offset, kTopBorder, total_size, total_size, cover_); - if (downloading_covers_) { - p->drawPixmap(total_size - 31, 40, 16, 16, spinner_animation_->currentPixmap()); - } - } - - // Work out how high the text is going to be - const int text_height = details_->size().height(); - const int gradient_mid = height() - qMax(text_height, kBottomOffset); - - // Draw the black fade - QLinearGradient gradient(0, gradient_mid - kGradientHead, - 0, gradient_mid + kGradientTail); - gradient.setColorAt(0, QColor(0, 0, 0, 0)); - gradient.setColorAt(1, QColor(0, 0, 0, 255)); - - p->fillRect(0, gradient_mid - kGradientHead, - width(), height() - (gradient_mid - kGradientHead), gradient); - - // Draw the text on top - p->translate(x_offset, height() - text_height); - details_->drawContents(p); - p->translate(-x_offset, -height() + text_height); - break; + // Draw the text on top + p->translate(x_offset, height() - text_height); + details_->drawContents(p); + p->translate(-x_offset, -height() + text_height); + break; } } @@ -396,17 +407,20 @@ void NowPlayingWidget::contextMenuEvent(QContextMenuEvent* e) { album_cover_choice_controller_->cover_from_file_action()->setEnabled(!aww_); album_cover_choice_controller_->cover_from_url_action()->setEnabled(!aww_); album_cover_choice_controller_->search_for_cover_action()->setEnabled( - !aww_ && app_->cover_providers()->HasAnyProviders()); + !aww_ && app_->cover_providers()->HasAnyProviders()); album_cover_choice_controller_->unset_cover_action()->setEnabled(!aww_); album_cover_choice_controller_->show_cover_action()->setEnabled(!aww_); // some special cases if (!aww_) { - const bool art_is_not_set = metadata_.has_manually_unset_cover() - || (metadata_.art_automatic().isEmpty() && metadata_.art_manual().isEmpty()); + const bool art_is_not_set = metadata_.has_manually_unset_cover() || + (metadata_.art_automatic().isEmpty() && + metadata_.art_manual().isEmpty()); - album_cover_choice_controller_->unset_cover_action()->setEnabled(!art_is_not_set); - album_cover_choice_controller_->show_cover_action()->setEnabled(!art_is_not_set); + album_cover_choice_controller_->unset_cover_action()->setEnabled( + !art_is_not_set); + album_cover_choice_controller_->show_cover_action()->setEnabled( + !art_is_not_set); } bask_in_his_glory_action_->setVisible(static_cast(hypnotoad_)); @@ -443,8 +457,10 @@ void NowPlayingWidget::EnableKittens(bool aww) { if (!kittens_ && aww) { kittens_ = new KittenLoader(this); app_->MoveToNewThread(kittens_); - connect(kittens_, SIGNAL(ImageLoaded(quint64,QImage)), SLOT(KittenLoaded(quint64,QImage))); - connect(kittens_, SIGNAL(ImageLoaded(quint64,QImage)), app_->network_remote(), SLOT(SendKitten(quint64,QImage))); + connect(kittens_, SIGNAL(ImageLoaded(quint64, QImage)), + SLOT(KittenLoaded(quint64, QImage))); + connect(kittens_, SIGNAL(ImageLoaded(quint64, QImage)), + app_->network_remote(), SLOT(SendKitten(quint64, QImage))); } aww_ = aww; @@ -477,7 +493,9 @@ void NowPlayingWidget::ShowCover() { void NowPlayingWidget::SearchCoverAutomatically() { QSettings s; s.beginGroup(kSettingsGroup); - s.setValue("search_for_cover_auto", album_cover_choice_controller_->search_cover_auto_action()->isChecked()); + s.setValue( + "search_for_cover_auto", + album_cover_choice_controller_->search_cover_auto_action()->isChecked()); // Search for cover automatically? GetCoverAutomatically(); @@ -504,10 +522,10 @@ void NowPlayingWidget::dropEvent(QDropEvent* e) { bool NowPlayingWidget::GetCoverAutomatically() { // Search for cover automatically? - bool search = album_cover_choice_controller_->search_cover_auto_action()->isChecked() && + bool search = + album_cover_choice_controller_->search_cover_auto_action()->isChecked() && !metadata_.has_manually_unset_cover() && - metadata_.art_automatic().isEmpty() && - metadata_.art_manual().isEmpty(); + metadata_.art_automatic().isEmpty() && metadata_.art_manual().isEmpty(); if (search) { qLog(Debug) << "GetCoverAutomatically"; @@ -516,7 +534,8 @@ bool NowPlayingWidget::GetCoverAutomatically() { // Show a spinner animation spinner_animation_.reset(new QMovie(":/spinner.gif", QByteArray(), this)); - connect(spinner_animation_.get(), SIGNAL(updated(const QRect&)), SLOT(update())); + connect(spinner_animation_.get(), SIGNAL(updated(const QRect&)), + SLOT(update())); spinner_animation_->start(); update(); } diff --git a/src/widgets/nowplayingwidget.h b/src/widgets/nowplayingwidget.h index fee7f8efe..62f9dd9f4 100644 --- a/src/widgets/nowplayingwidget.h +++ b/src/widgets/nowplayingwidget.h @@ -41,7 +41,7 @@ class QTimeLine; class NowPlayingWidget : public QWidget { Q_OBJECT -public: + public: NowPlayingWidget(QWidget* parent = 0); ~NowPlayingWidget(); @@ -54,10 +54,7 @@ public: static const int kTopBorder; // Values are saved in QSettings - enum Mode { - SmallSongDetails = 0, - LargeSongDetails = 1, - }; + enum Mode { SmallSongDetails = 0, LargeSongDetails = 1, }; void SetApplication(Application* app); @@ -69,23 +66,24 @@ public: signals: void ShowAboveStatusBarChanged(bool above); -public slots: + public slots: void Stopped(); void AllHail(bool hypnotoad); void EnableKittens(bool aww); -protected: + protected: void paintEvent(QPaintEvent* e); void resizeEvent(QResizeEvent*); void contextMenuEvent(QContextMenuEvent* e); void dragEnterEvent(QDragEnterEvent* e); void dropEvent(QDropEvent* e); -private slots: + private slots: void SetMode(int mode); void ShowAboveStatusBar(bool above); - void AlbumArtLoaded(const Song& metadata, const QString& uri, const QImage& image); + void AlbumArtLoaded(const Song& metadata, const QString& uri, + const QImage& image); void KittenLoaded(quint64 id, const QImage& image); void SetVisible(bool visible); @@ -105,7 +103,7 @@ private slots: void AutomaticCoverSearchDone(); -private: + private: void CreateModeAction(Mode mode, const QString& text, QActionGroup* group, QSignalMapper* mapper); void UpdateDetailsText(); @@ -115,7 +113,7 @@ private: void ScaleCover(); bool GetCoverAutomatically(); -private: + private: Application* app_; AlbumCoverChoiceController* album_cover_choice_controller_; @@ -156,4 +154,4 @@ private: quint64 pending_kitten_; }; -#endif // NOWPLAYINGWIDGET_H +#endif // NOWPLAYINGWIDGET_H diff --git a/src/widgets/osd.cpp b/src/widgets/osd.cpp index c2dfe8b81..b64f8e0b4 100644 --- a/src/widgets/osd.cpp +++ b/src/widgets/osd.cpp @@ -24,7 +24,7 @@ #include "ui/systemtrayicon.h" #ifdef HAVE_DBUS -# include "dbus/notification.h" +#include "dbus/notification.h" #endif #include @@ -34,32 +34,30 @@ const char* OSD::kSettingsGroup = "OSD"; OSD::OSD(SystemTrayIcon* tray_icon, Application* app, QObject* parent) - : QObject(parent), - tray_icon_(tray_icon), - app_(app), - timeout_msec_(5000), - behaviour_(Native), - show_on_volume_change_(false), - show_art_(true), - show_on_play_mode_change_(true), - use_custom_text_(false), - custom_text1_(QString()), - custom_text2_(QString()), - preview_mode_(false), - force_show_next_(false), - ignore_next_stopped_(false), - pretty_popup_(new OSDPretty(OSDPretty::Mode_Popup)) -{ - connect(app_->current_art_loader(), SIGNAL(ThumbnailLoaded(Song,QString,QImage)), - SLOT(AlbumArtLoaded(Song,QString,QImage))); + : QObject(parent), + tray_icon_(tray_icon), + app_(app), + timeout_msec_(5000), + behaviour_(Native), + show_on_volume_change_(false), + show_art_(true), + show_on_play_mode_change_(true), + use_custom_text_(false), + custom_text1_(QString()), + custom_text2_(QString()), + preview_mode_(false), + force_show_next_(false), + ignore_next_stopped_(false), + pretty_popup_(new OSDPretty(OSDPretty::Mode_Popup)) { + connect(app_->current_art_loader(), + SIGNAL(ThumbnailLoaded(Song, QString, QImage)), + SLOT(AlbumArtLoaded(Song, QString, QImage))); ReloadSettings(); Init(); } -OSD::~OSD() { - delete pretty_popup_; -} +OSD::~OSD() { delete pretty_popup_; } void OSD::ReloadSettings() { QSettings s; @@ -75,8 +73,7 @@ void OSD::ReloadSettings() { if (!SupportsNativeNotifications() && behaviour_ == Native) behaviour_ = Pretty; - if (!SupportsTrayPopups() && behaviour_ == TrayPopup) - behaviour_ = Disabled; + if (!SupportsTrayPopups() && behaviour_ == TrayPopup) behaviour_ = Disabled; ReloadPrettyOSDSettings(); } @@ -92,7 +89,8 @@ void OSD::ReshowCurrentSong() { AlbumArtLoaded(last_song_, last_image_uri_, last_image_); } -void OSD::AlbumArtLoaded(const Song& song, const QString& uri, const QImage& image) { +void OSD::AlbumArtLoaded(const Song& song, const QString& uri, + const QImage& image) { // Don't change tray icon details if it's a preview if (!preview_mode_) { tray_icon_->SetNowPlaying(song, uri); @@ -108,12 +106,9 @@ void OSD::AlbumArtLoaded(const Song& song, const QString& uri, const QImage& ima summary = song.PrettyTitle(); if (!song.artist().isEmpty()) summary = QString("%1 - %2").arg(song.artist(), summary); - if (!song.album().isEmpty()) - message_parts << song.album(); - if (song.disc() > 0) - message_parts << tr("disc %1").arg(song.disc()); - if (song.track() > 0) - message_parts << tr("track %1").arg(song.track()); + if (!song.album().isEmpty()) message_parts << song.album(); + if (song.disc() > 0) message_parts << tr("disc %1").arg(song.disc()); + if (song.track() > 0) message_parts << tr("track %1").arg(song.track()); } else { QRegExp variable_replacer("[%][a-z]+[%]"); summary = custom_text1_; @@ -140,9 +135,11 @@ void OSD::AlbumArtLoaded(const Song& song, const QString& uri, const QImage& ima } if (show_art_) { - ShowMessage(summary, message_parts.join(", "), "notification-audio-play", image); + ShowMessage(summary, message_parts.join(", "), "notification-audio-play", + image); } else { - ShowMessage(summary, message_parts.join(", "), "notification-audio-play", QImage()); + ShowMessage(summary, message_parts.join(", "), "notification-audio-play", + QImage()); } // Reload the saved settings if they were changed for preview @@ -167,8 +164,9 @@ void OSD::Stopped() { } void OSD::StopAfterToggle(bool stop) { - ShowMessage(QCoreApplication::applicationName(), - tr("Stop playing after track: %1").arg(stop ? tr("On") : tr("Off"))); + ShowMessage( + QCoreApplication::applicationName(), + tr("Stop playing after track: %1").arg(stop ? tr("On") : tr("Off"))); } void OSD::PlaylistFinished() { @@ -179,8 +177,7 @@ void OSD::PlaylistFinished() { } void OSD::VolumeChanged(int value) { - if (!show_on_volume_change_) - return; + if (!show_on_volume_change_) return; ShowMessage(QCoreApplication::applicationName(), tr("Volume %1%").arg(value)); } @@ -196,39 +193,36 @@ void OSD::MagnatuneDownloadFinished(const QStringList& albums) { QImage(":/providers/magnatune.png")); } -void OSD::ShowMessage(const QString& summary, - const QString& message, - const QString& icon, - const QImage& image) { +void OSD::ShowMessage(const QString& summary, const QString& message, + const QString& icon, const QImage& image) { if (pretty_popup_->toggle_mode()) { pretty_popup_->ShowMessage(summary, message, image); } else { switch (behaviour_) { - case Native: - if (image.isNull()) { - ShowMessageNative(summary, message, icon, QImage()); - } else { - ShowMessageNative(summary, message, QString(), image); - } - break; + case Native: + if (image.isNull()) { + ShowMessageNative(summary, message, icon, QImage()); + } else { + ShowMessageNative(summary, message, QString(), image); + } + break; #ifndef Q_OS_DARWIN - case TrayPopup: - tray_icon_->ShowPopup(summary, message, timeout_msec_); - break; + case TrayPopup: + tray_icon_->ShowPopup(summary, message, timeout_msec_); + break; #endif - case Disabled: - if (!force_show_next_) - break; - force_show_next_ = false; + case Disabled: + if (!force_show_next_) break; + force_show_next_ = false; // fallthrough - case Pretty: - pretty_popup_->ShowMessage(summary, message, image); - break; + case Pretty: + pretty_popup_->ShowMessage(summary, message, image); + break; - default: - break; + default: + break; } } } @@ -240,33 +234,41 @@ void OSD::CallFinished(QDBusPendingCallWatcher*) {} #ifdef HAVE_WIIMOTEDEV void OSD::WiiremoteActived(int id) { - ShowMessage(QString(tr("%1: Wiimotedev module")).arg(QCoreApplication::applicationName()), + ShowMessage(QString(tr("%1: Wiimotedev module")) + .arg(QCoreApplication::applicationName()), tr("Wii Remote %1: actived").arg(QString::number(id))); } void OSD::WiiremoteDeactived(int id) { - ShowMessage(QString(tr("%1: Wiimotedev module")).arg(QCoreApplication::applicationName()), + ShowMessage(QString(tr("%1: Wiimotedev module")) + .arg(QCoreApplication::applicationName()), tr("Wii Remote %1: disactived").arg(QString::number(id))); } void OSD::WiiremoteConnected(int id) { - ShowMessage(QString(tr("%1: Wiimotedev module")).arg(QCoreApplication::applicationName()), + ShowMessage(QString(tr("%1: Wiimotedev module")) + .arg(QCoreApplication::applicationName()), tr("Wii Remote %1: connected").arg(QString::number(id))); } void OSD::WiiremoteDisconnected(int id) { - ShowMessage(QString(tr("%1: Wiimotedev module")).arg(QCoreApplication::applicationName()), + ShowMessage(QString(tr("%1: Wiimotedev module")) + .arg(QCoreApplication::applicationName()), tr("Wii Remote %1: disconnected").arg(QString::number(id))); } void OSD::WiiremoteLowBattery(int id, int live) { - ShowMessage(QString(tr("%1: Wiimotedev module")).arg(QCoreApplication::applicationName()), - tr("Wii Remote %1: low battery (%2%)").arg(QString::number(id), QString::number(live))); + ShowMessage(QString(tr("%1: Wiimotedev module")) + .arg(QCoreApplication::applicationName()), + tr("Wii Remote %1: low battery (%2%)") + .arg(QString::number(id), QString::number(live))); } void OSD::WiiremoteCriticalBattery(int id, int live) { - ShowMessage(QString(tr("%1: Wiimotedev module")).arg(QCoreApplication::applicationName()), - tr("Wii Remote %1: critical battery (%2%) ").arg(QString::number(id), QString::number(live))); + ShowMessage(QString(tr("%1: Wiimotedev module")) + .arg(QCoreApplication::applicationName()), + tr("Wii Remote %1: critical battery (%2%) ") + .arg(QString::number(id), QString::number(live))); } #endif @@ -275,10 +277,18 @@ void OSD::ShuffleModeChanged(PlaylistSequence::ShuffleMode mode) { if (show_on_play_mode_change_) { QString current_mode = QString(); switch (mode) { - case PlaylistSequence::Shuffle_Off: current_mode = tr("Don't shuffle"); break; - case PlaylistSequence::Shuffle_All: current_mode = tr("Shuffle all"); break; - case PlaylistSequence::Shuffle_InsideAlbum: current_mode = tr("Shuffle tracks in this album"); break; - case PlaylistSequence::Shuffle_Albums: current_mode = tr("Shuffle albums"); break; + case PlaylistSequence::Shuffle_Off: + current_mode = tr("Don't shuffle"); + break; + case PlaylistSequence::Shuffle_All: + current_mode = tr("Shuffle all"); + break; + case PlaylistSequence::Shuffle_InsideAlbum: + current_mode = tr("Shuffle tracks in this album"); + break; + case PlaylistSequence::Shuffle_Albums: + current_mode = tr("Shuffle albums"); + break; } ShowMessage(QCoreApplication::applicationName(), current_mode); } @@ -288,10 +298,18 @@ void OSD::RepeatModeChanged(PlaylistSequence::RepeatMode mode) { if (show_on_play_mode_change_) { QString current_mode = QString(); switch (mode) { - case PlaylistSequence::Repeat_Off: current_mode = tr("Don't repeat"); break; - case PlaylistSequence::Repeat_Track: current_mode = tr("Repeat track"); break; - case PlaylistSequence::Repeat_Album: current_mode = tr("Repeat album"); break; - case PlaylistSequence::Repeat_Playlist: current_mode = tr("Repeat playlist"); break; + case PlaylistSequence::Repeat_Off: + current_mode = tr("Don't repeat"); + break; + case PlaylistSequence::Repeat_Track: + current_mode = tr("Repeat track"); + break; + case PlaylistSequence::Repeat_Album: + current_mode = tr("Repeat album"); + break; + case PlaylistSequence::Repeat_Playlist: + current_mode = tr("Repeat playlist"); + break; } ShowMessage(QCoreApplication::applicationName(), current_mode); } @@ -345,7 +363,8 @@ QString OSD::ReplaceVariable(const QString& variable, const Song& song) { #endif #ifdef Q_OS_WIN32 // Other OS don't support native notifications - qLog(Debug) << "New line not supported by this notification type under Windows"; + qLog(Debug) + << "New line not supported by this notification type under Windows"; return ""; #endif case TrayPopup: @@ -358,18 +377,19 @@ QString OSD::ReplaceVariable(const QString& variable, const Song& song) { } } - //if the variable is not recognized, just return it + // if the variable is not recognized, just return it return variable; } -void OSD::ShowPreview(const Behaviour type, const QString& line1, const QString& line2, const Song& song) { +void OSD::ShowPreview(const Behaviour type, const QString& line1, + const QString& line2, const Song& song) { behaviour_ = type; custom_text1_ = line1; custom_text2_ = line2; - if (!use_custom_text_) - use_custom_text_ = true; + if (!use_custom_text_) use_custom_text_ = true; - // We want to reload the settings, but we can't do this here because the cover art loading is asynch + // We want to reload the settings, but we can't do this here because the cover + // art loading is asynch preview_mode_ = true; AlbumArtLoaded(song, QString(), QImage()); } diff --git a/src/widgets/osd.h b/src/widgets/osd.h index 158bc0d9b..151f721ab 100644 --- a/src/widgets/osd.h +++ b/src/widgets/osd.h @@ -37,10 +37,10 @@ class SystemTrayIcon; class QDBusPendingCallWatcher; #ifdef HAVE_DBUS -# include +#include - QDBusArgument& operator<< (QDBusArgument& arg, const QImage& image); - const QDBusArgument& operator>> (const QDBusArgument& arg, QImage& image); +QDBusArgument& operator<<(QDBusArgument& arg, const QImage& image); +const QDBusArgument& operator>>(const QDBusArgument& arg, QImage& image); #endif class OSD : public QObject { @@ -52,12 +52,7 @@ class OSD : public QObject { static const char* kSettingsGroup; - enum Behaviour { - Disabled = 0, - Native, - TrayPopup, - Pretty, - }; + enum Behaviour { Disabled = 0, Native, TrayPopup, Pretty, }; // Implemented in the OS-specific files static bool SupportsNativeNotifications(); @@ -90,25 +85,25 @@ class OSD : public QObject { void WiiremoteCriticalBattery(int id, int live); #endif - void ShowPreview(const Behaviour type, const QString& line1, const QString& line2, const Song& song); + void ShowPreview(const Behaviour type, const QString& line1, + const QString& line2, const Song& song); private: - void ShowMessage(const QString& summary, - const QString& message = QString(), + void ShowMessage(const QString& summary, const QString& message = QString(), const QString& icon = QString(), const QImage& image = QImage()); // These are implemented in the OS-specific files void Init(); - void ShowMessageNative(const QString& summary, - const QString& message, + void ShowMessageNative(const QString& summary, const QString& message, const QString& icon = QString(), const QImage& image = QImage()); QString ReplaceVariable(const QString& variable, const Song& song); private slots: void CallFinished(QDBusPendingCallWatcher* watcher); - void AlbumArtLoaded(const Song& song, const QString& uri, const QImage& image); + void AlbumArtLoaded(const Song& song, const QString& uri, + const QImage& image); private: SystemTrayIcon* tray_icon_; @@ -144,4 +139,4 @@ class OSD : public QObject { #endif }; -#endif // OSD_H +#endif // OSD_H diff --git a/src/widgets/osd_win.cpp b/src/widgets/osd_win.cpp index ff7e86ab2..7b2ffe277 100644 --- a/src/widgets/osd_win.cpp +++ b/src/widgets/osd_win.cpp @@ -20,18 +20,13 @@ #include -void OSD::Init() { -} +void OSD::Init() {} -bool OSD::SupportsNativeNotifications() { - return false; -} +bool OSD::SupportsNativeNotifications() { return false; } -bool OSD::SupportsTrayPopups() { - return true; -} +bool OSD::SupportsTrayPopups() { return true; } -void OSD::ShowMessageNative(const QString&, const QString&, - const QString&, const QImage&) { +void OSD::ShowMessageNative(const QString&, const QString&, const QString&, + const QImage&) { qLog(Warning) << "not implemented"; } diff --git a/src/widgets/osd_x11.cpp b/src/widgets/osd_x11.cpp index 831b9761a..a79bc841c 100644 --- a/src/widgets/osd_x11.cpp +++ b/src/widgets/osd_x11.cpp @@ -29,7 +29,7 @@ #include #include -QDBusArgument& operator<< (QDBusArgument& arg, const QImage& image) { +QDBusArgument& operator<<(QDBusArgument& arg, const QImage& image) { if (image.isNull()) { // Sometimes this gets called with a null QImage for no obvious reason. arg.beginStructure(); @@ -47,8 +47,8 @@ QDBusArgument& operator<< (QDBusArgument& arg, const QImage& image) { // ABGR -> GBAR QImage i(scaled.size(), scaled.format()); for (int y = 0; y < i.height(); ++y) { - QRgb* p = (QRgb*) scaled.scanLine(y); - QRgb* q = (QRgb*) i.scanLine(y); + QRgb* p = (QRgb*)scaled.scanLine(y); + QRgb* q = (QRgb*)i.scanLine(y); QRgb* end = p + scaled.width(); while (p < end) { *q = qRgba(qGreen(*p), qBlue(*p), qAlpha(*p), qRed(*p)); @@ -71,12 +71,12 @@ QDBusArgument& operator<< (QDBusArgument& arg, const QImage& image) { return arg; } -const QDBusArgument& operator>> (const QDBusArgument& arg, QImage& image) { +const QDBusArgument& operator>>(const QDBusArgument& arg, QImage& image) { // This is needed to link but shouldn't be called. Q_ASSERT(0); return arg; } -#endif // HAVE_DBUS +#endif // HAVE_DBUS void OSD::Init() { #ifdef HAVE_DBUS @@ -84,12 +84,11 @@ void OSD::Init() { interface_.reset(new OrgFreedesktopNotificationsInterface( OrgFreedesktopNotificationsInterface::staticInterfaceName(), - "/org/freedesktop/Notifications", - QDBusConnection::sessionBus())); + "/org/freedesktop/Notifications", QDBusConnection::sessionBus())); if (!interface_->isValid()) { qLog(Warning) << "Error connecting to notifications service."; } -#endif // HAVE_DBUS +#endif // HAVE_DBUS } bool OSD::SupportsNativeNotifications() { @@ -100,15 +99,12 @@ bool OSD::SupportsNativeNotifications() { #endif } -bool OSD::SupportsTrayPopups() { - return true; -} +bool OSD::SupportsTrayPopups() { return true; } void OSD::ShowMessageNative(const QString& summary, const QString& message, const QString& icon, const QImage& image) { #ifdef HAVE_DBUS - if (!interface_) - return; + if (!interface_) return; QVariantMap hints; if (!image.isNull()) { @@ -116,29 +112,23 @@ void OSD::ShowMessageNative(const QString& summary, const QString& message, } int id = 0; - if (last_notification_time_.secsTo(QDateTime::currentDateTime()) * 1000 - < timeout_msec_) { + if (last_notification_time_.secsTo(QDateTime::currentDateTime()) * 1000 < + timeout_msec_) { // Reuse the existing popup if it's still open. The reason we don't always // reuse the popup is because the notification daemon on KDE4 won't re-show // the bubble if it's already gone to the tray. See issue #118 id = notification_id_; } - QDBusPendingReply reply = interface_->Notify( - QCoreApplication::applicationName(), - id, - icon, - summary, - message, - QStringList(), - hints, - timeout_msec_); + QDBusPendingReply reply = + interface_->Notify(QCoreApplication::applicationName(), id, icon, summary, + message, QStringList(), hints, timeout_msec_); QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(reply, this); connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - SLOT(CallFinished(QDBusPendingCallWatcher*))); -#else // HAVE_DBUS + SLOT(CallFinished(QDBusPendingCallWatcher*))); +#else // HAVE_DBUS qLog(Warning) << "not implemented"; -#endif // HAVE_DBUS +#endif // HAVE_DBUS } #ifdef HAVE_DBUS diff --git a/src/widgets/osdpretty.cpp b/src/widgets/osdpretty.cpp index bd771c3f7..9437bf2b9 100644 --- a/src/widgets/osdpretty.cpp +++ b/src/widgets/osdpretty.cpp @@ -18,7 +18,6 @@ #include "osdpretty.h" #include "ui_osdpretty.h" - #include #include #include @@ -33,12 +32,12 @@ #include #ifdef Q_WS_X11 -# include +#include #endif #ifdef Q_OS_WIN32 -# include "qtwin.h" -# include +#include "qtwin.h" +#include #endif const char* OSDPretty::kSettingsGroup = "OSDPretty"; @@ -52,21 +51,19 @@ const int OSDPretty::kSnapProximity = 20; const QRgb OSDPretty::kPresetBlue = qRgb(102, 150, 227); const QRgb OSDPretty::kPresetOrange = qRgb(254, 156, 67); - -OSDPretty::OSDPretty(Mode mode, QWidget *parent) - : QWidget(parent), - ui_(new Ui_OSDPretty), - mode_(mode), - background_color_(kPresetBlue), - background_opacity_(0.85), - popup_display_(0), - font_(QFont()), - disable_duration_(false), - timeout_(new QTimer(this)), - fading_enabled_(false), - fader_(new QTimeLine(300, this)), - toggle_mode_(false) -{ +OSDPretty::OSDPretty(Mode mode, QWidget* parent) + : QWidget(parent), + ui_(new Ui_OSDPretty), + mode_(mode), + background_color_(kPresetBlue), + background_opacity_(0.85), + popup_display_(0), + font_(QFont()), + disable_duration_(false), + timeout_(new QTimer(this)), + fading_enabled_(false), + fader_(new QTimeLine(300, this)), + toggle_mode_(false) { Qt::WindowFlags flags = Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint; @@ -86,13 +83,13 @@ OSDPretty::OSDPretty(Mode mode, QWidget *parent) // Mode settings switch (mode_) { - case Mode_Popup: - setCursor(QCursor(Qt::ArrowCursor)); - break; + case Mode_Popup: + setCursor(QCursor(Qt::ArrowCursor)); + break; - case Mode_Draggable: - setCursor(QCursor(Qt::OpenHandCursor)); - break; + case Mode_Draggable: + setCursor(QCursor(Qt::OpenHandCursor)); + break; } // Timeout @@ -113,7 +110,7 @@ OSDPretty::OSDPretty(Mode mode, QWidget *parent) // Load the show edges and corners QImage shadow_edge(":osd_shadow_edge.png"); QImage shadow_corner(":osd_shadow_corner.png"); - for (int i=0 ; i<4 ; ++i) { + for (int i = 0; i < 4; ++i) { QTransform rotation = QTransform().rotate(90 * i); shadow_edge_[i] = QPixmap::fromImage(shadow_edge.transformed(rotation)); shadow_corner_[i] = QPixmap::fromImage(shadow_corner.transformed(rotation)); @@ -128,17 +125,16 @@ OSDPretty::OSDPretty(Mode mode, QWidget *parent) // Get current screen resolution QRect screenResolution = QApplication::desktop()->screenGeometry(); // Leave 200 px for icon - ui_->summary->setMaximumWidth(screenResolution.width()-200); - ui_->message->setMaximumWidth(screenResolution.width()-200); + ui_->summary->setMaximumWidth(screenResolution.width() - 200); + ui_->message->setMaximumWidth(screenResolution.width() - 200); // Set maximum size for the OSD, a little margin here too - setMaximumSize(screenResolution.width()-100,screenResolution.height()-100); + setMaximumSize(screenResolution.width() - 100, + screenResolution.height() - 100); // Don't load settings here, they will be reloaded anyway on creation } -OSDPretty::~OSDPretty() { - delete ui_; -} +OSDPretty::~OSDPretty() { delete ui_; } bool OSDPretty::IsTransparencyAvailable() { #ifdef Q_WS_X11 @@ -165,16 +161,15 @@ void OSDPretty::Load() { void OSDPretty::ReloadSettings() { Load(); - if (isVisible()) - update(); + if (isVisible()) update(); } QRect OSDPretty::BoxBorder() const { - return rect().adjusted(kDropShadowSize, kDropShadowSize, - -kDropShadowSize, -kDropShadowSize); + return rect().adjusted(kDropShadowSize, kDropShadowSize, -kDropShadowSize, + -kDropShadowSize); } -void OSDPretty::paintEvent(QPaintEvent *) { +void OSDPretty::paintEvent(QPaintEvent*) { QPainter p(this); p.setRenderHint(QPainter::Antialiasing); p.setRenderHint(QPainter::HighQualityAntialiasing); @@ -185,22 +180,21 @@ void OSDPretty::paintEvent(QPaintEvent *) { const int kShadowCornerSize = kDropShadowSize + kBorderRadius; p.drawPixmap(0, 0, shadow_corner_[0]); p.drawPixmap(width() - kShadowCornerSize, 0, shadow_corner_[1]); - p.drawPixmap(width() - kShadowCornerSize, height() - kShadowCornerSize, shadow_corner_[2]); + p.drawPixmap(width() - kShadowCornerSize, height() - kShadowCornerSize, + shadow_corner_[2]); p.drawPixmap(0, height() - kShadowCornerSize, shadow_corner_[3]); // Shadow edges - p.drawTiledPixmap(kShadowCornerSize, 0, - width() - kShadowCornerSize*2, kDropShadowSize, - shadow_edge_[0]); + p.drawTiledPixmap(kShadowCornerSize, 0, width() - kShadowCornerSize * 2, + kDropShadowSize, shadow_edge_[0]); p.drawTiledPixmap(width() - kDropShadowSize, kShadowCornerSize, - kDropShadowSize, height() - kShadowCornerSize*2, + kDropShadowSize, height() - kShadowCornerSize * 2, shadow_edge_[1]); p.drawTiledPixmap(kShadowCornerSize, height() - kDropShadowSize, - width() - kShadowCornerSize*2, kDropShadowSize, + width() - kShadowCornerSize * 2, kDropShadowSize, shadow_edge_[2]); - p.drawTiledPixmap(0, kShadowCornerSize, - kDropShadowSize, height() - kShadowCornerSize*2, - shadow_edge_[3]); + p.drawTiledPixmap(0, kShadowCornerSize, kDropShadowSize, + height() - kShadowCornerSize * 2, shadow_edge_[3]); // Box background p.setBrush(background_color_); @@ -235,8 +229,8 @@ void OSDPretty::SetMessage(const QString& summary, const QString& message, if (!image.isNull()) { QImage scaled_image = - image.scaled(kMaxIconSize, kMaxIconSize, - Qt::KeepAspectRatio, Qt::SmoothTransformation); + image.scaled(kMaxIconSize, kMaxIconSize, Qt::KeepAspectRatio, + Qt::SmoothTransformation); ui_->icon->setPixmap(QPixmap::fromImage(scaled_image)); ui_->icon->show(); } else { @@ -246,8 +240,7 @@ void OSDPretty::SetMessage(const QString& summary, const QString& message, ui_->summary->setText(summary); ui_->message->setText(message); - if (isVisible()) - Reposition(); + if (isVisible()) Reposition(); } // Set the desired message and then show the OSD @@ -260,16 +253,13 @@ void OSDPretty::ShowMessage(const QString& summary, const QString& message, if (toggle_mode()) { set_toggle_mode(false); // If timeout is disabled, timer hadn't been started - if (!disable_duration()) - timeout_->stop(); + if (!disable_duration()) timeout_->stop(); hide(); } else { - if (!disable_duration()) - timeout_->start(); // Restart the timer + if (!disable_duration()) timeout_->start(); // Restart the timer } } else { - if (toggle_mode()) - set_toggle_mode(false); + if (toggle_mode()) set_toggle_mode(false); // The OSD is not visible, show it show(); } @@ -284,18 +274,17 @@ void OSDPretty::showEvent(QShowEvent* e) { if (fading_enabled_) { fader_->setDirection(QTimeLine::Forward); - fader_->start(); // Timeout will be started in FaderFinished - } - else if (mode_ == Mode_Popup) { - if (!disable_duration()) - timeout_->start(); + fader_->start(); // Timeout will be started in FaderFinished + } else if (mode_ == Mode_Popup) { + if (!disable_duration()) timeout_->start(); // Ensures it is above when showing the preview raise(); } } void OSDPretty::setVisible(bool visible) { - if (!visible && fading_enabled_ && fader_->direction() == QTimeLine::Forward) { + if (!visible && fading_enabled_ && + fader_->direction() == QTimeLine::Forward) { fader_->setDirection(QTimeLine::Backward); fader_->start(); } else { @@ -310,9 +299,7 @@ void OSDPretty::FaderFinished() { timeout_->start(); } -void OSDPretty::FaderValueChanged(qreal value) { - setWindowOpacity(value); -} +void OSDPretty::FaderValueChanged(qreal value) { setWindowOpacity(value); } void OSDPretty::Reposition() { QDesktopWidget* desktop = QApplication::desktop(); @@ -339,7 +326,8 @@ void OSDPretty::Reposition() { QPainter p(&mask); p.setBrush(Qt::color1); - p.drawRoundedRect(BoxBorder().adjusted(-1, -1, 0, 0), kBorderRadius, kBorderRadius); + p.drawRoundedRect(BoxBorder().adjusted(-1, -1, 0, 0), kBorderRadius, + kBorderRadius); p.end(); // If there's no compositing window manager running then we have to set an @@ -356,14 +344,11 @@ void OSDPretty::Reposition() { #endif } -void OSDPretty::enterEvent(QEvent *) { - if (mode_ == Mode_Popup) - setWindowOpacity(0.25); +void OSDPretty::enterEvent(QEvent*) { + if (mode_ == Mode_Popup) setWindowOpacity(0.25); } -void OSDPretty::leaveEvent(QEvent *) { - setWindowOpacity(1.0); -} +void OSDPretty::leaveEvent(QEvent*) { setWindowOpacity(1.0); } void OSDPretty::mousePressEvent(QMouseEvent* e) { if (mode_ == Mode_Popup) @@ -383,12 +368,15 @@ void OSDPretty::mouseMoveEvent(QMouseEvent* e) { QDesktopWidget* desktop = QApplication::desktop(); QRect geometry(desktop->availableGeometry(e->globalPos())); - new_pos.setX(qBound(geometry.left(), new_pos.x(), geometry.right() - width())); - new_pos.setY(qBound(geometry.top(), new_pos.y(), geometry.bottom() - height())); + new_pos.setX( + qBound(geometry.left(), new_pos.x(), geometry.right() - width())); + new_pos.setY( + qBound(geometry.top(), new_pos.y(), geometry.bottom() - height())); // Snap to center int snap_x = geometry.center().x() - width() / 2; - if (new_pos.x() > snap_x - kSnapProximity && new_pos.x() < snap_x + kSnapProximity) { + if (new_pos.x() > snap_x - kSnapProximity && + new_pos.x() < snap_x + kSnapProximity) { new_pos.setX(snap_x); } @@ -403,10 +391,10 @@ QPoint OSDPretty::current_pos() const { QDesktopWidget* desktop = QApplication::desktop(); QRect geometry(desktop->availableGeometry(current_display())); - int x = pos().x() >= geometry.right() - width() - ? -1 : pos().x() - geometry.left(); - int y = pos().y() >= geometry.bottom() - height() - ? -1 : pos().y() - geometry.top(); + int x = pos().x() >= geometry.right() - width() ? -1 + : pos().x() - geometry.left(); + int y = pos().y() >= geometry.bottom() - height() ? -1 : pos().y() - + geometry.top(); return QPoint(x, y); } @@ -418,14 +406,12 @@ int OSDPretty::current_display() const { void OSDPretty::set_background_color(QRgb color) { background_color_ = color; - if (isVisible()) - update(); + if (isVisible()) update(); } void OSDPretty::set_background_opacity(qreal opacity) { background_opacity_ = opacity; - if (isVisible()) - update(); + if (isVisible()) update(); } void OSDPretty::set_foreground_color(QRgb color) { @@ -438,11 +424,9 @@ void OSDPretty::set_foreground_color(QRgb color) { ui_->message->setPalette(p); } -void OSDPretty::set_popup_duration(int msec) { - timeout_->setInterval(msec); -} +void OSDPretty::set_popup_duration(int msec) { timeout_->setInterval(msec); } -void OSDPretty::mouseReleaseEvent(QMouseEvent *) { +void OSDPretty::mouseReleaseEvent(QMouseEvent*) { if (mode_ == Mode_Draggable) { popup_display_ = current_display(); popup_pos_ = current_pos(); diff --git a/src/widgets/osdpretty.h b/src/widgets/osdpretty.h index 0dc49d3da..b077ee1aa 100644 --- a/src/widgets/osdpretty.h +++ b/src/widgets/osdpretty.h @@ -28,12 +28,9 @@ class OSDPretty : public QWidget { Q_OBJECT public: - enum Mode { - Mode_Popup, - Mode_Draggable, - }; + enum Mode { Mode_Popup, Mode_Draggable, }; - OSDPretty(Mode mode, QWidget *parent = 0); + OSDPretty(Mode mode, QWidget* parent = 0); ~OSDPretty(); static const char* kSettingsGroup; @@ -49,11 +46,9 @@ class OSDPretty : public QWidget { static bool IsTransparencyAvailable(); - void SetMessage(const QString& summary, - const QString& message, + void SetMessage(const QString& summary, const QString& message, const QImage& image); - void ShowMessage(const QString& summary, - const QString& message, + void ShowMessage(const QString& summary, const QString& message, const QImage& image); // Controls the fader. This is enabled by default on Windows. @@ -92,13 +87,13 @@ class OSDPretty : public QWidget { void ReloadSettings(); protected: - void paintEvent(QPaintEvent *); - void enterEvent(QEvent *); - void leaveEvent(QEvent *); - void mousePressEvent(QMouseEvent *); - void showEvent(QShowEvent *); - void mouseMoveEvent(QMouseEvent *); - void mouseReleaseEvent(QMouseEvent *); + void paintEvent(QPaintEvent*); + void enterEvent(QEvent*); + void leaveEvent(QEvent*); + void mousePressEvent(QMouseEvent*); + void showEvent(QShowEvent*); + void mouseMoveEvent(QMouseEvent*); + void mouseReleaseEvent(QMouseEvent*); private: void Reposition(); @@ -119,7 +114,7 @@ class OSDPretty : public QWidget { QColor foreground_color_; QColor background_color_; float background_opacity_; - int popup_display_; // -1 for default + int popup_display_; // -1 for default QPoint popup_pos_; QFont font_; // The OSD is kept always on top until you click (no timer) @@ -145,4 +140,4 @@ class OSDPretty : public QWidget { bool toggle_mode_; }; -#endif // OSDPRETTY_H +#endif // OSDPRETTY_H diff --git a/src/widgets/prettyimage.cpp b/src/widgets/prettyimage.cpp index adca4360c..50db99ff5 100644 --- a/src/widgets/prettyimage.cpp +++ b/src/widgets/prettyimage.cpp @@ -36,8 +36,8 @@ const int PrettyImage::kTotalHeight = 200; const int PrettyImage::kReflectionHeight = 40; -const int PrettyImage::kImageHeight = PrettyImage::kTotalHeight - - PrettyImage::kReflectionHeight; +const int PrettyImage::kImageHeight = + PrettyImage::kTotalHeight - PrettyImage::kReflectionHeight; const int PrettyImage::kMaxImageWidth = 300; @@ -45,20 +45,18 @@ const char* PrettyImage::kSettingsGroup = "PrettyImageView"; PrettyImage::PrettyImage(const QUrl& url, QNetworkAccessManager* network, QWidget* parent) - : QWidget(parent), - network_(network), - state_(State_WaitingForLazyLoad), - url_(url), - menu_(nullptr) -{ + : QWidget(parent), + network_(network), + state_(State_WaitingForLazyLoad), + url_(url), + menu_(nullptr) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); LazyLoad(); } void PrettyImage::LazyLoad() { - if (state_ != State_WaitingForLazyLoad) - return; + if (state_ != State_WaitingForLazyLoad) return; // Start fetching the image QNetworkReply* reply = network_->get(QNetworkRequest(url_)); @@ -67,8 +65,7 @@ void PrettyImage::LazyLoad() { } QSize PrettyImage::image_size() const { - if (state_ != State_Finished) - return QSize(kImageHeight * 1.6, kImageHeight); + if (state_ != State_Finished) return QSize(kImageHeight * 1.6, kImageHeight); QSize ret = image_.size(); ret.scale(kMaxImageWidth, kImageHeight, Qt::KeepAspectRatio); @@ -90,8 +87,9 @@ void PrettyImage::ImageFetched() { state_ = State_CreatingThumbnail; image_ = image; - QFuture future = QtConcurrent::run(image_, &QImage::scaled, - image_size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); + QFuture future = + QtConcurrent::run(image_, &QImage::scaled, image_size(), + Qt::KeepAspectRatio, Qt::SmoothTransformation); QFutureWatcher* watcher = new QFutureWatcher(this); watcher->setFuture(future); @@ -100,9 +98,9 @@ void PrettyImage::ImageFetched() { } void PrettyImage::ImageScaled() { - QFutureWatcher* watcher = reinterpret_cast*>(sender()); - if (!watcher) - return; + QFutureWatcher* watcher = + reinterpret_cast*>(sender()); + if (!watcher) return; watcher->deleteLater(); thumbnail_ = QPixmap::fromImage(watcher->result()); @@ -113,7 +111,7 @@ void PrettyImage::ImageScaled() { emit Loaded(); } -void PrettyImage::paintEvent(QPaintEvent* ) { +void PrettyImage::paintEvent(QPaintEvent*) { // Draw at the bottom of our area QRect image_rect(QPoint(0, 0), image_size()); image_rect.moveBottom(kImageHeight); @@ -129,7 +127,8 @@ void PrettyImage::paintEvent(QPaintEvent* ) { reflection_rect.moveTop(image_rect.bottom()); // Create the reflected pixmap - QImage reflection(reflection_rect.size(), QImage::Format_ARGB32_Premultiplied); + QImage reflection(reflection_rect.size(), + QImage::Format_ARGB32_Premultiplied); reflection.fill(palette().color(QPalette::Base).rgba()); QPainter reflection_painter(&reflection); @@ -150,7 +149,8 @@ void PrettyImage::paintEvent(QPaintEvent* ) { fade_gradient.setColorAt(0.0, QColor(0, 0, 0, 0)); fade_gradient.setColorAt(1.0, QColor(0, 0, 0, 128)); - reflection_painter.setCompositionMode(QPainter::CompositionMode_DestinationIn); + reflection_painter.setCompositionMode( + QPainter::CompositionMode_DestinationIn); reflection_painter.fillRect(fade_rect, fade_gradient); reflection_painter.end(); @@ -161,29 +161,28 @@ void PrettyImage::paintEvent(QPaintEvent* ) { void PrettyImage::DrawThumbnail(QPainter* p, const QRect& rect) { switch (state_) { - case State_WaitingForLazyLoad: - case State_Fetching: - case State_CreatingThumbnail: - p->setPen(palette().color(QPalette::Disabled, QPalette::Text)); - p->drawText(rect, Qt::AlignHCenter | Qt::AlignBottom, tr("Loading...")); - break; + case State_WaitingForLazyLoad: + case State_Fetching: + case State_CreatingThumbnail: + p->setPen(palette().color(QPalette::Disabled, QPalette::Text)); + p->drawText(rect, Qt::AlignHCenter | Qt::AlignBottom, tr("Loading...")); + break; - case State_Finished: - p->drawPixmap(rect, thumbnail_); - break; + case State_Finished: + p->drawPixmap(rect, thumbnail_); + break; } } void PrettyImage::contextMenuEvent(QContextMenuEvent* e) { - if (e->pos().y() >= kImageHeight) - return; + if (e->pos().y() >= kImageHeight) return; if (!menu_) { menu_ = new QMenu(this); - menu_->addAction(IconLoader::Load("zoom-in"), tr("Show fullsize..."), - this, SLOT(ShowFullsize())); - menu_->addAction(IconLoader::Load("document-save"), tr("Save image") + "...", - this, SLOT(SaveAs())); + menu_->addAction(IconLoader::Load("zoom-in"), tr("Show fullsize..."), this, + SLOT(ShowFullsize())); + menu_->addAction(IconLoader::Load("document-save"), + tr("Save image") + "...", this, SLOT(SaveAs())); } menu_->popup(e->globalPos()); @@ -214,8 +213,7 @@ void PrettyImage::ShowFullsize() { void PrettyImage::SaveAs() { QString filename = QFileInfo(url_.path()).fileName(); - if (filename.isEmpty()) - filename = "artwork.jpg"; + if (filename.isEmpty()) filename = "artwork.jpg"; QSettings s; s.beginGroup(kSettingsGroup); @@ -230,8 +228,7 @@ void PrettyImage::SaveAs() { } filename = QFileDialog::getSaveFileName(this, tr("Save image"), path); - if (filename.isEmpty()) - return; + if (filename.isEmpty()) return; image_.save(filename); diff --git a/src/widgets/prettyimage.h b/src/widgets/prettyimage.h index 77118f301..f6b062b44 100644 --- a/src/widgets/prettyimage.h +++ b/src/widgets/prettyimage.h @@ -28,7 +28,7 @@ class QNetworkReply; class PrettyImage : public QWidget { Q_OBJECT -public: + public: PrettyImage(const QUrl& url, QNetworkAccessManager* network, QWidget* parent = 0); @@ -46,20 +46,20 @@ public: signals: void Loaded(); -public slots: + public slots: void LazyLoad(); void SaveAs(); void ShowFullsize(); -protected: + protected: void contextMenuEvent(QContextMenuEvent*); void paintEvent(QPaintEvent*); -private slots: + private slots: void ImageFetched(); void ImageScaled(); -private: + private: enum State { State_WaitingForLazyLoad, State_Fetching, @@ -69,7 +69,7 @@ private: void DrawThumbnail(QPainter* p, const QRect& rect); -private: + private: QNetworkAccessManager* network_; State state_; QUrl url_; @@ -81,4 +81,4 @@ private: QString last_save_dir_; }; -#endif // PRETTYIMAGE_H +#endif // PRETTYIMAGE_H diff --git a/src/widgets/prettyimageview.cpp b/src/widgets/prettyimageview.cpp index 52d5c36b8..8f9fe3e57 100644 --- a/src/widgets/prettyimageview.cpp +++ b/src/widgets/prettyimageview.cpp @@ -25,15 +25,16 @@ #include #include -PrettyImageView::PrettyImageView(QNetworkAccessManager* network, QWidget* parent) - : QScrollArea(parent), - network_(network), - container_(new QWidget(this)), - layout_(new QHBoxLayout(container_)), - current_index_(-1), - scroll_animation_(new QPropertyAnimation(horizontalScrollBar(), "value", this)), - recursion_filter_(false) -{ +PrettyImageView::PrettyImageView(QNetworkAccessManager* network, + QWidget* parent) + : QScrollArea(parent), + network_(network), + container_(new QWidget(this)), + layout_(new QHBoxLayout(container_)), + current_index_(-1), + scroll_animation_( + new QPropertyAnimation(horizontalScrollBar(), "value", this)), + recursion_filter_(false) { setWidget(container_); setWidgetResizable(true); setMinimumHeight(PrettyImage::kTotalHeight + 10); @@ -43,8 +44,10 @@ PrettyImageView::PrettyImageView(QNetworkAccessManager* network, QWidget* parent scroll_animation_->setDuration(250); scroll_animation_->setEasingCurve(QEasingCurve::InOutCubic); - connect(horizontalScrollBar(), SIGNAL(sliderReleased()), SLOT(ScrollBarReleased())); - connect(horizontalScrollBar(), SIGNAL(actionTriggered(int)), SLOT(ScrollBarAction(int))); + connect(horizontalScrollBar(), SIGNAL(sliderReleased()), + SLOT(ScrollBarReleased())); + connect(horizontalScrollBar(), SIGNAL(actionTriggered(int)), + SLOT(ScrollBarAction(int))); layout_->setSizeConstraint(QLayout::SetMinAndMaxSize); layout_->setContentsMargins(6, 6, 6, 6); @@ -72,20 +75,17 @@ void PrettyImageView::AddImage(const QUrl& url) { connect(image, SIGNAL(Loaded()), SLOT(ScrollToCurrent())); layout_->insertWidget(layout_->count() - 1, image); - if (current_index_ == -1) - ScrollTo(0); + if (current_index_ == -1) ScrollTo(0); } void PrettyImageView::mouseReleaseEvent(QMouseEvent* e) { // Find the image that was clicked on QWidget* widget = container_->childAt(container_->mapFrom(this, e->pos())); - if (!widget) - return; + if (!widget) return; // Get the index of that image const int index = layout_->indexOf(widget) - 1; - if (index == -1) - return; + if (index == -1) return; if (index == current_index_) { // Show the image fullsize @@ -104,14 +104,12 @@ void PrettyImageView::ScrollTo(int index, bool smooth) { const int layout_index = current_index_ + 1; const QWidget* target_widget = layout_->itemAt(layout_index)->widget(); - if (!target_widget) - return; + if (!target_widget) return; const int current_x = horizontalScrollBar()->value(); const int target_x = target_widget->geometry().center().x() - width() / 2; - if (current_x == target_x) - return; + if (current_x == target_x) return; if (smooth) { scroll_animation_->setStartValue(current_x); @@ -123,15 +121,13 @@ void PrettyImageView::ScrollTo(int index, bool smooth) { } } -void PrettyImageView::ScrollToCurrent() { - ScrollTo(current_index_); -} +void PrettyImageView::ScrollToCurrent() { ScrollTo(current_index_); } void PrettyImageView::ScrollBarReleased() { // Find the nearest widget to where the scroll bar was released const int current_x = horizontalScrollBar()->value() + width() / 2; int layout_index = 1; - for (; layout_indexcount() - 1 ; ++layout_index) { + for (; layout_index < layout_->count() - 1; ++layout_index) { const QWidget* widget = layout_->itemAt(layout_index)->widget(); if (widget && widget->geometry().right() > current_x) { break; @@ -143,15 +139,15 @@ void PrettyImageView::ScrollBarReleased() { void PrettyImageView::ScrollBarAction(int action) { switch (action) { - case QAbstractSlider::SliderSingleStepAdd: - case QAbstractSlider::SliderPageStepAdd: - ScrollTo(current_index_ + 1); - break; + case QAbstractSlider::SliderSingleStepAdd: + case QAbstractSlider::SliderPageStepAdd: + ScrollTo(current_index_ + 1); + break; - case QAbstractSlider::SliderSingleStepSub: - case QAbstractSlider::SliderPageStepSub: - ScrollTo(current_index_ - 1); - break; + case QAbstractSlider::SliderSingleStepSub: + case QAbstractSlider::SliderPageStepSub: + ScrollTo(current_index_ - 1); + break; } } diff --git a/src/widgets/prettyimageview.h b/src/widgets/prettyimageview.h index 4a4f29329..fad801424 100644 --- a/src/widgets/prettyimageview.h +++ b/src/widgets/prettyimageview.h @@ -32,26 +32,26 @@ class QTimeLine; class PrettyImageView : public QScrollArea { Q_OBJECT -public: + public: PrettyImageView(QNetworkAccessManager* network, QWidget* parent = 0); static const char* kSettingsGroup; -public slots: + public slots: void AddImage(const QUrl& url); -protected: + protected: void mouseReleaseEvent(QMouseEvent*); void resizeEvent(QResizeEvent* e); void wheelEvent(QWheelEvent* e); -private slots: + private slots: void ScrollBarReleased(); void ScrollBarAction(int action); void ScrollTo(int index, bool smooth = true); void ScrollToCurrent(); -private: + private: bool eventFilter(QObject*, QEvent*); QNetworkAccessManager* network_; @@ -65,4 +65,4 @@ private: bool recursion_filter_; }; -#endif // PRETTYIMAGEVIEW_H +#endif // PRETTYIMAGEVIEW_H diff --git a/src/widgets/progressitemdelegate.cpp b/src/widgets/progressitemdelegate.cpp index 6e334539d..52d12d860 100644 --- a/src/widgets/progressitemdelegate.cpp +++ b/src/widgets/progressitemdelegate.cpp @@ -19,12 +19,12 @@ #include -ProgressItemDelegate::ProgressItemDelegate(QObject *parent) - : QStyledItemDelegate(parent) -{ -} +ProgressItemDelegate::ProgressItemDelegate(QObject* parent) + : QStyledItemDelegate(parent) {} -void ProgressItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { +void ProgressItemDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { bool ok = false; int progress = index.data().toInt(&ok); diff --git a/src/widgets/progressitemdelegate.h b/src/widgets/progressitemdelegate.h index 91dd4fd8f..95ec4843b 100644 --- a/src/widgets/progressitemdelegate.h +++ b/src/widgets/progressitemdelegate.h @@ -22,10 +22,11 @@ class ProgressItemDelegate : public QStyledItemDelegate { Q_OBJECT -public: + public: ProgressItemDelegate(QObject* parent = 0); - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const; }; -#endif // PROGRESSITEMDELEGATE_H +#endif // PROGRESSITEMDELEGATE_H diff --git a/src/widgets/ratingwidget.cpp b/src/widgets/ratingwidget.cpp index dc30a4276..43973eb97 100644 --- a/src/widgets/ratingwidget.cpp +++ b/src/widgets/ratingwidget.cpp @@ -31,7 +31,7 @@ RatingPainter::RatingPainter() { QPixmap off(":/star-off.png"); // Generate the 10 states, better to do it now than on the fly - for (int i=0 ; idrawPixmap(QRect(pos, size), stars_[star], QRect(QPoint(0,0), size)); + const int star = qBound(0, int(rating * 2.0 + 0.5), kStarCount * 2); + painter->drawPixmap(QRect(pos, size), stars_[star], + QRect(QPoint(0, 0), size)); } - RatingWidget::RatingWidget(QWidget* parent) - : QWidget(parent), - rating_(0.0), - hover_rating_(-1.0) -{ + : QWidget(parent), rating_(0.0), hover_rating_(-1.0) { setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); setMouseTracking(true); } QSize RatingWidget::sizeHint() const { - const int frame_width = 1 + style()->pixelMetric(QStyle::PM_DefaultFrameWidth); - return QSize(RatingPainter::kStarSize * (RatingPainter::kStarCount+2) + frame_width*2, - RatingPainter::kStarSize + frame_width*2); + const int frame_width = + 1 + style()->pixelMetric(QStyle::PM_DefaultFrameWidth); + return QSize(RatingPainter::kStarSize * (RatingPainter::kStarCount + 2) + + frame_width * 2, + RatingPainter::kStarSize + frame_width * 2); } void RatingWidget::set_rating(float rating) { @@ -119,7 +120,8 @@ void RatingWidget::paintEvent(QPaintEvent* e) { opt.initFrom(this); opt.state |= QStyle::State_Sunken; opt.frameShape = QFrame::StyledPanel; - opt.lineWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt, this); + opt.lineWidth = + style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt, this); opt.midLineWidth = 0; p.drawPrimitive(QStyle::PE_PanelLineEdit, opt); diff --git a/src/widgets/ratingwidget.h b/src/widgets/ratingwidget.h index fad3615a1..013da0867 100644 --- a/src/widgets/ratingwidget.h +++ b/src/widgets/ratingwidget.h @@ -22,7 +22,7 @@ #include class RatingPainter { -public: + public: RatingPainter(); static const int kStarCount = 5; @@ -32,15 +32,15 @@ public: void Paint(QPainter* painter, const QRect& rect, float rating) const; -private: - QPixmap stars_[kStarCount*2+1]; + private: + QPixmap stars_[kStarCount * 2 + 1]; }; class RatingWidget : public QWidget { Q_OBJECT Q_PROPERTY(float rating READ rating WRITE set_rating); -public: + public: RatingWidget(QWidget* parent = 0); QSize sizeHint() const; @@ -51,16 +51,16 @@ public: signals: void RatingChanged(float rating); -protected: + protected: void paintEvent(QPaintEvent*); void mousePressEvent(QMouseEvent* e); void mouseMoveEvent(QMouseEvent* e); void leaveEvent(QEvent*); -private: + private: RatingPainter painter_; float rating_; float hover_rating_; }; -#endif // RATINGWIDGET_H +#endif // RATINGWIDGET_H diff --git a/src/widgets/renametablineedit.cpp b/src/widgets/renametablineedit.cpp index 9598e30e2..ecb607455 100644 --- a/src/widgets/renametablineedit.cpp +++ b/src/widgets/renametablineedit.cpp @@ -19,23 +19,19 @@ #include -RenameTabLineEdit::RenameTabLineEdit(QWidget *parent) : - QLineEdit(parent) -{ -} +RenameTabLineEdit::RenameTabLineEdit(QWidget* parent) : QLineEdit(parent) {} -void RenameTabLineEdit::keyPressEvent (QKeyEvent *e) { +void RenameTabLineEdit::keyPressEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Escape) { e->accept(); emit EditingCanceled(); - } - else { + } else { QLineEdit::keyPressEvent(e); } } -void RenameTabLineEdit::focusOutEvent(QFocusEvent *e) { - //if the user hasn't explicitly accepted, discard the value +void RenameTabLineEdit::focusOutEvent(QFocusEvent* e) { + // if the user hasn't explicitly accepted, discard the value emit EditingCanceled(); - //we don't call the default event since it will trigger editingFished() + // we don't call the default event since it will trigger editingFished() } diff --git a/src/widgets/renametablineedit.h b/src/widgets/renametablineedit.h index 370ae8cad..7359f3777 100644 --- a/src/widgets/renametablineedit.h +++ b/src/widgets/renametablineedit.h @@ -23,17 +23,17 @@ class RenameTabLineEdit : public QLineEdit { Q_OBJECT -public: + public: RenameTabLineEdit(QWidget* parent = 0); signals: void EditingCanceled(); -public slots: + public slots: -protected: + protected: void focusOutEvent(QFocusEvent* e); void keyPressEvent(QKeyEvent* e); }; -#endif // RENAMETABLINEEDIT_H +#endif // RENAMETABLINEEDIT_H diff --git a/src/widgets/sliderwidget.cpp b/src/widgets/sliderwidget.cpp index 1ca80ad90..b9d6b432a 100644 --- a/src/widgets/sliderwidget.cpp +++ b/src/widgets/sliderwidget.cpp @@ -32,107 +32,100 @@ #include #include - -Amarok::Slider::Slider( Qt::Orientation orientation, QWidget *parent, uint max ) - : QSlider( orientation, parent ) - , m_sliding( false ) - , m_outside( false ) - , m_prevValue( 0 ) -{ - setRange( 0, max ); +Amarok::Slider::Slider(Qt::Orientation orientation, QWidget* parent, uint max) + : QSlider(orientation, parent), + m_sliding(false), + m_outside(false), + m_prevValue(0) { + setRange(0, max); } -void -Amarok::Slider::wheelEvent( QWheelEvent *e ) -{ - if( orientation() == Qt::Vertical ) { - // Will be handled by the parent widget - e->ignore(); - return; +void Amarok::Slider::wheelEvent(QWheelEvent* e) { + if (orientation() == Qt::Vertical) { + // Will be handled by the parent widget + e->ignore(); + return; + } + + // Position Slider (horizontal) + int step = e->delta() * 1500 / 18; + int nval = QSlider::value() + step; + nval = qMax(nval, minimum()); + nval = qMin(nval, maximum()); + + QSlider::setValue(nval); + + emit sliderReleased(value()); +} + +void Amarok::Slider::mouseMoveEvent(QMouseEvent* e) { + if (m_sliding) { + // feels better, but using set value of 20 is bad of course + QRect rect(-20, -20, width() + 40, height() + 40); + + if (orientation() == Qt::Horizontal && !rect.contains(e->pos())) { + if (!m_outside) QSlider::setValue(m_prevValue); + m_outside = true; + } else { + m_outside = false; + slideEvent(e); + emit sliderMoved(value()); } - - // Position Slider (horizontal) - int step = e->delta() * 1500 / 18; - int nval = QSlider::value() + step; - nval = qMax(nval, minimum()); - nval = qMin(nval, maximum()); - - QSlider::setValue( nval ); - - emit sliderReleased( value() ); + } else + QSlider::mouseMoveEvent(e); } -void -Amarok::Slider::mouseMoveEvent( QMouseEvent *e ) -{ - if ( m_sliding ) - { - //feels better, but using set value of 20 is bad of course - QRect rect( -20, -20, width()+40, height()+40 ); - - if ( orientation() == Qt::Horizontal && !rect.contains( e->pos() ) ) { - if ( !m_outside ) - QSlider::setValue( m_prevValue ); - m_outside = true; - } else { - m_outside = false; - slideEvent( e ); - emit sliderMoved( value() ); - } - } - else QSlider::mouseMoveEvent( e ); -} - -void -Amarok::Slider::slideEvent( QMouseEvent *e ) -{ +void Amarok::Slider::slideEvent(QMouseEvent* e) { QStyleOptionSlider option; initStyleOption(&option); - QRect sliderRect(style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this)); + QRect sliderRect(style()->subControlRect(QStyle::CC_Slider, &option, + QStyle::SC_SliderHandle, this)); - QSlider::setValue( orientation() == Qt::Horizontal - ? ((QApplication::layoutDirection() == Qt::RightToLeft) ? - QStyle::sliderValueFromPosition(minimum(), maximum(), width() - (e->pos().x() - sliderRect.width()/2), width() + sliderRect.width(), true ) - : QStyle::sliderValueFromPosition(minimum(), maximum(), e->pos().x() - sliderRect.width()/2, width() - sliderRect.width() ) ) - : QStyle::sliderValueFromPosition(minimum(), maximum(), e->pos().y() - sliderRect.height()/2, height() - sliderRect.height() ) ); + QSlider::setValue( + orientation() == Qt::Horizontal + ? ((QApplication::layoutDirection() == Qt::RightToLeft) + ? QStyle::sliderValueFromPosition( + minimum(), maximum(), + width() - (e->pos().x() - sliderRect.width() / 2), + width() + sliderRect.width(), true) + : QStyle::sliderValueFromPosition( + minimum(), maximum(), + e->pos().x() - sliderRect.width() / 2, + width() - sliderRect.width())) + : QStyle::sliderValueFromPosition( + minimum(), maximum(), e->pos().y() - sliderRect.height() / 2, + height() - sliderRect.height())); } -void -Amarok::Slider::mousePressEvent( QMouseEvent *e ) -{ +void Amarok::Slider::mousePressEvent(QMouseEvent* e) { QStyleOptionSlider option; initStyleOption(&option); - QRect sliderRect(style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this)); + QRect sliderRect(style()->subControlRect(QStyle::CC_Slider, &option, + QStyle::SC_SliderHandle, this)); - m_sliding = true; - m_prevValue = QSlider::value(); + m_sliding = true; + m_prevValue = QSlider::value(); - if ( !sliderRect.contains( e->pos() ) ) - mouseMoveEvent( e ); + if (!sliderRect.contains(e->pos())) mouseMoveEvent(e); } -void -Amarok::Slider::mouseReleaseEvent( QMouseEvent* ) -{ - if( !m_outside && QSlider::value() != m_prevValue ) - emit sliderReleased( value() ); +void Amarok::Slider::mouseReleaseEvent(QMouseEvent*) { + if (!m_outside && QSlider::value() != m_prevValue) + emit sliderReleased(value()); - m_sliding = false; - m_outside = false; + m_sliding = false; + m_outside = false; } -void -Amarok::Slider::setValue( int newValue ) -{ - //don't adjust the slider while the user is dragging it! +void Amarok::Slider::setValue(int newValue) { + // don't adjust the slider while the user is dragging it! - if ( !m_sliding || m_outside ) - QSlider::setValue( adjustValue( newValue ) ); - else - m_prevValue = newValue; + if (!m_sliding || m_outside) + QSlider::setValue(adjustValue(newValue)); + else + m_prevValue = newValue; } - ////////////////////////////////////////////////////////////////////////////////////////// /// CLASS PrettySlider ////////////////////////////////////////////////////////////////////////////////////////// @@ -140,43 +133,38 @@ Amarok::Slider::setValue( int newValue ) #define THICKNESS 7 #define MARGIN 3 -Amarok::PrettySlider::PrettySlider( Qt::Orientation orientation, SliderMode mode, - QWidget *parent, uint max ) - : Amarok::Slider( orientation, parent, max ) - , m_mode( mode ) -{ - if( m_mode == Pretty) - { - setFocusPolicy( Qt::NoFocus ); - } +Amarok::PrettySlider::PrettySlider(Qt::Orientation orientation, SliderMode mode, + QWidget* parent, uint max) + : Amarok::Slider(orientation, parent, max), m_mode(mode) { + if (m_mode == Pretty) { + setFocusPolicy(Qt::NoFocus); + } } -void -Amarok::PrettySlider::mousePressEvent( QMouseEvent *e ) -{ - Amarok::Slider::mousePressEvent( e ); +void Amarok::PrettySlider::mousePressEvent(QMouseEvent* e) { + Amarok::Slider::mousePressEvent(e); - slideEvent( e ); + slideEvent(e); } -void -Amarok::PrettySlider::slideEvent( QMouseEvent *e ) -{ - if( m_mode == Pretty ) - QSlider::setValue( orientation() == Qt::Horizontal - ? QStyle::sliderValueFromPosition(minimum(), maximum(), e->pos().x(), width()-2 ) - : QStyle::sliderValueFromPosition(minimum(), maximum(), e->pos().y(), height()-2 ) ); - else - Amarok::Slider::slideEvent( e ); +void Amarok::PrettySlider::slideEvent(QMouseEvent* e) { + if (m_mode == Pretty) + QSlider::setValue( + orientation() == Qt::Horizontal + ? QStyle::sliderValueFromPosition(minimum(), maximum(), + e->pos().x(), width() - 2) + : QStyle::sliderValueFromPosition(minimum(), maximum(), + e->pos().y(), height() - 2)); + else + Amarok::Slider::slideEvent(e); } namespace Amarok { - namespace ColorScheme { - extern QColor Background; - extern QColor Foreground; - } +namespace ColorScheme { +extern QColor Background; +extern QColor Foreground; +} } - #if 0 /** these functions aren't required in our fixed size world, @@ -203,167 +191,146 @@ Amarok::PrettySlider::sizeHint() const /// CLASS VolumeSlider ////////////////////////////////////////////////////////////////////////////////////////// -Amarok::VolumeSlider::VolumeSlider( QWidget *parent, uint max ) - : Amarok::Slider( Qt::Horizontal, parent, max ) - , m_animCount( 0 ) - , m_animTimer( new QTimer( this ) ) - , m_pixmapInset( QPixmap( ":volumeslider-inset.png" )) -{ - setFocusPolicy( Qt::NoFocus ); +Amarok::VolumeSlider::VolumeSlider(QWidget* parent, uint max) + : Amarok::Slider(Qt::Horizontal, parent, max), + m_animCount(0), + m_animTimer(new QTimer(this)), + m_pixmapInset(QPixmap(":volumeslider-inset.png")) { + setFocusPolicy(Qt::NoFocus); - // BEGIN Calculate handle animation pixmaps for mouse-over effect - QImage pixmapHandle ( ":volumeslider-handle.png" ); - QImage pixmapHandleGlow( ":volumeslider-handle_glow.png" ); + // BEGIN Calculate handle animation pixmaps for mouse-over effect + QImage pixmapHandle(":volumeslider-handle.png"); + QImage pixmapHandleGlow(":volumeslider-handle_glow.png"); - float opacity = 0.0; - const float step = 1.0 / ANIM_MAX; - QImage dst; - for ( int i = 0; i < ANIM_MAX; ++i ) { - dst = pixmapHandle.copy(); + float opacity = 0.0; + const float step = 1.0 / ANIM_MAX; + QImage dst; + for (int i = 0; i < ANIM_MAX; ++i) { + dst = pixmapHandle.copy(); - QPainter p(&dst); - p.setOpacity(opacity); - p.drawImage(0, 0, pixmapHandleGlow); - p.end(); - - m_handlePixmaps.append( QPixmap::fromImage( dst ) ); - opacity += step; - } - // END - - generateGradient(); - - setMinimumWidth( m_pixmapInset.width() ); - setMinimumHeight( m_pixmapInset.height() ); - - connect( m_animTimer, SIGNAL( timeout() ), this, SLOT( slotAnimTimer() ) ); -} - -void -Amarok::VolumeSlider::generateGradient() -{ - const QImage mask( ":volumeslider-gradient.png" ); - - QImage gradient_image(mask.size(), QImage::Format_ARGB32_Premultiplied); - QPainter p(&gradient_image); - - QLinearGradient gradient(gradient_image.rect().topLeft(), - gradient_image.rect().topRight()); - gradient.setColorAt(0, palette().color(QPalette::Background)); - gradient.setColorAt(1, palette().color(QPalette::Highlight)); - p.fillRect(gradient_image.rect(), QBrush(gradient)); - - p.setCompositionMode(QPainter::CompositionMode_DestinationIn); - p.drawImage(0, 0, mask); + QPainter p(&dst); + p.setOpacity(opacity); + p.drawImage(0, 0, pixmapHandleGlow); p.end(); - m_pixmapGradient = QPixmap::fromImage(gradient_image); + m_handlePixmaps.append(QPixmap::fromImage(dst)); + opacity += step; + } + // END + + generateGradient(); + + setMinimumWidth(m_pixmapInset.width()); + setMinimumHeight(m_pixmapInset.height()); + + connect(m_animTimer, SIGNAL(timeout()), this, SLOT(slotAnimTimer())); } -void -Amarok::VolumeSlider::slotAnimTimer() //SLOT +void Amarok::VolumeSlider::generateGradient() { + const QImage mask(":volumeslider-gradient.png"); + + QImage gradient_image(mask.size(), QImage::Format_ARGB32_Premultiplied); + QPainter p(&gradient_image); + + QLinearGradient gradient(gradient_image.rect().topLeft(), + gradient_image.rect().topRight()); + gradient.setColorAt(0, palette().color(QPalette::Background)); + gradient.setColorAt(1, palette().color(QPalette::Highlight)); + p.fillRect(gradient_image.rect(), QBrush(gradient)); + + p.setCompositionMode(QPainter::CompositionMode_DestinationIn); + p.drawImage(0, 0, mask); + p.end(); + + m_pixmapGradient = QPixmap::fromImage(gradient_image); +} + +void Amarok::VolumeSlider::slotAnimTimer() // SLOT { - if ( m_animEnter ) { - m_animCount++; - update(); - if ( m_animCount == ANIM_MAX - 1 ) - m_animTimer->stop(); - } else { - m_animCount--; - update(); - if ( m_animCount == 0 ) - m_animTimer->stop(); - } + if (m_animEnter) { + m_animCount++; + update(); + if (m_animCount == ANIM_MAX - 1) m_animTimer->stop(); + } else { + m_animCount--; + update(); + if (m_animCount == 0) m_animTimer->stop(); + } } -void -Amarok::VolumeSlider::mousePressEvent( QMouseEvent *e ) -{ - if( e->button() != Qt::RightButton ) { - Amarok::Slider::mousePressEvent( e ); - slideEvent( e ); - } -} - -void -Amarok::VolumeSlider::contextMenuEvent( QContextMenuEvent *e ) -{ - QMap values; - QMenu menu; - menu.setTitle("Volume"); - values[menu.addAction("100%" )] = 100; - values[menu.addAction("80%" )] = 80; - values[menu.addAction("60%" )] = 60; - values[menu.addAction("40%" )] = 40; - values[menu.addAction("20%" )] = 20; - values[menu.addAction("0%" )] = 0; - - QAction* ret = menu.exec( mapToGlobal( e->pos() ) ); - if( ret ) - { - QSlider::setValue( values[ret] ); - emit sliderReleased( values[ret] ); - } +void Amarok::VolumeSlider::mousePressEvent(QMouseEvent* e) { + if (e->button() != Qt::RightButton) { + Amarok::Slider::mousePressEvent(e); + slideEvent(e); + } } -void -Amarok::VolumeSlider::slideEvent( QMouseEvent *e ) -{ - QSlider::setValue( QStyle::sliderValueFromPosition(minimum(), maximum(), e->pos().x(), width()-2 ) ); +void Amarok::VolumeSlider::contextMenuEvent(QContextMenuEvent* e) { + QMap values; + QMenu menu; + menu.setTitle("Volume"); + values[menu.addAction("100%")] = 100; + values[menu.addAction("80%")] = 80; + values[menu.addAction("60%")] = 60; + values[menu.addAction("40%")] = 40; + values[menu.addAction("20%")] = 20; + values[menu.addAction("0%")] = 0; + + QAction* ret = menu.exec(mapToGlobal(e->pos())); + if (ret) { + QSlider::setValue(values[ret]); + emit sliderReleased(values[ret]); + } } -void -Amarok::VolumeSlider::wheelEvent( QWheelEvent *e ) -{ - const uint step = e->delta() / 30; - QSlider::setValue( QSlider::value() + step ); - - emit sliderReleased( value() ); +void Amarok::VolumeSlider::slideEvent(QMouseEvent* e) { + QSlider::setValue(QStyle::sliderValueFromPosition(minimum(), maximum(), + e->pos().x(), width() - 2)); } -void -Amarok::VolumeSlider::paintEvent( QPaintEvent * ) -{ - QPainter p(this); +void Amarok::VolumeSlider::wheelEvent(QWheelEvent* e) { + const uint step = e->delta() / 30; + QSlider::setValue(QSlider::value() + step); - const int padding = 7; - const int offset = int( double( ( width() - 2 * padding ) * value() ) / maximum() ); - - p.drawPixmap(0, 0, m_pixmapGradient, 0, 0, offset + padding, 0); - p.drawPixmap(0, 0, m_pixmapInset); - p.drawPixmap(offset - m_handlePixmaps[0].width() / 2 + padding, 0, m_handlePixmaps[m_animCount]); - - // Draw percentage number - p.setPen( palette().color( QPalette::Disabled, QPalette::Text ).dark() ); - QFont font; - font.setPixelSize( 9 ); - p.setFont( font ); - const QRect rect( 0, 0, 34, 15 ); - p.drawText( rect, Qt::AlignRight | Qt::AlignVCenter, QString::number( value() ) + '%' ); + emit sliderReleased(value()); } -void -Amarok::VolumeSlider::enterEvent( QEvent* ) -{ - m_animEnter = true; - m_animCount = 0; +void Amarok::VolumeSlider::paintEvent(QPaintEvent*) { + QPainter p(this); - m_animTimer->start( ANIM_INTERVAL ); + const int padding = 7; + const int offset = int(double((width() - 2 * padding) * value()) / maximum()); + + p.drawPixmap(0, 0, m_pixmapGradient, 0, 0, offset + padding, 0); + p.drawPixmap(0, 0, m_pixmapInset); + p.drawPixmap(offset - m_handlePixmaps[0].width() / 2 + padding, 0, + m_handlePixmaps[m_animCount]); + + // Draw percentage number + p.setPen(palette().color(QPalette::Disabled, QPalette::Text).dark()); + QFont font; + font.setPixelSize(9); + p.setFont(font); + const QRect rect(0, 0, 34, 15); + p.drawText(rect, Qt::AlignRight | Qt::AlignVCenter, + QString::number(value()) + '%'); } -void -Amarok::VolumeSlider::leaveEvent( QEvent* ) -{ - // This can happen if you enter and leave the widget quickly - if ( m_animCount == 0 ) - m_animCount = 1; +void Amarok::VolumeSlider::enterEvent(QEvent*) { + m_animEnter = true; + m_animCount = 0; - m_animEnter = false; - m_animTimer->start( ANIM_INTERVAL ); + m_animTimer->start(ANIM_INTERVAL); } -void -Amarok::VolumeSlider::paletteChange( const QPalette& ) -{ - generateGradient(); +void Amarok::VolumeSlider::leaveEvent(QEvent*) { + // This can happen if you enter and leave the widget quickly + if (m_animCount == 0) m_animCount = 1; + + m_animEnter = false; + m_animTimer->start(ANIM_INTERVAL); +} + +void Amarok::VolumeSlider::paletteChange(const QPalette&) { + generateGradient(); } diff --git a/src/widgets/sliderwidget.h b/src/widgets/sliderwidget.h index 681026f58..787fa1319 100644 --- a/src/widgets/sliderwidget.h +++ b/src/widgets/sliderwidget.h @@ -20,7 +20,6 @@ #ifndef AMAROKSLIDER_H #define AMAROKSLIDER_H - #include #include #include @@ -28,118 +27,110 @@ class QPalette; class QTimer; -namespace Amarok -{ - class Slider : public QSlider - { - Q_OBJECT +namespace Amarok { +class Slider : public QSlider { + Q_OBJECT - public: - Slider( Qt::Orientation, QWidget*, uint max = 0 ); + public: + Slider(Qt::Orientation, QWidget*, uint max = 0); - virtual void setValue( int ); + virtual void setValue(int); - //WARNING non-virtual - and thus only really intended for internal use - //this is a major flaw in the class presently, however it suits our - //current needs fine - int value() const { return adjustValue( QSlider::value() ); } + // WARNING non-virtual - and thus only really intended for internal use + // this is a major flaw in the class presently, however it suits our + // current needs fine + int value() const { return adjustValue(QSlider::value()); } - signals: - //we emit this when the user has specifically changed the slider - //so connect to it if valueChanged() is too generic - //Qt also emits valueChanged( int ) - void sliderReleased( int ); +signals: + // we emit this when the user has specifically changed the slider + // so connect to it if valueChanged() is too generic + // Qt also emits valueChanged( int ) + void sliderReleased(int); - protected: - virtual void wheelEvent( QWheelEvent* ); - virtual void mouseMoveEvent( QMouseEvent* ); - virtual void mouseReleaseEvent( QMouseEvent* ); - virtual void mousePressEvent( QMouseEvent* ); - virtual void slideEvent( QMouseEvent* ); + protected: + virtual void wheelEvent(QWheelEvent*); + virtual void mouseMoveEvent(QMouseEvent*); + virtual void mouseReleaseEvent(QMouseEvent*); + virtual void mousePressEvent(QMouseEvent*); + virtual void slideEvent(QMouseEvent*); - bool m_sliding; + bool m_sliding; - /// we flip the value for vertical sliders - int adjustValue( int v ) const - { - int mp = (minimum() + maximum()) / 2; - return orientation() == Qt::Vertical ? mp - (v - mp) : v; - } + /// we flip the value for vertical sliders + int adjustValue(int v) const { + int mp = (minimum() + maximum()) / 2; + return orientation() == Qt::Vertical ? mp - (v - mp) : v; + } - private: - bool m_outside; - int m_prevValue; + private: + bool m_outside; + int m_prevValue; - Slider( const Slider& ); //undefined - Slider &operator=( const Slider& ); //undefined - }; + Slider(const Slider&); // undefined + Slider& operator=(const Slider&); // undefined +}; +class PrettySlider : public Slider { + Q_OBJECT - class PrettySlider : public Slider - { - Q_OBJECT + public: + typedef enum { + Normal, // Same behavior as Slider *unless* there's a moodbar + Pretty + } SliderMode; - public: - typedef enum - { - Normal, // Same behavior as Slider *unless* there's a moodbar - Pretty - } SliderMode; + PrettySlider(Qt::Orientation orientation, SliderMode mode, QWidget* parent, + uint max = 0); - PrettySlider( Qt::Orientation orientation, SliderMode mode, - QWidget *parent, uint max = 0 ); + protected: + virtual void slideEvent(QMouseEvent*); + virtual void mousePressEvent(QMouseEvent*); - protected: - virtual void slideEvent( QMouseEvent* ); - virtual void mousePressEvent( QMouseEvent* ); + private: + PrettySlider(const PrettySlider&); // undefined + PrettySlider& operator=(const PrettySlider&); // undefined - private: - PrettySlider( const PrettySlider& ); //undefined - PrettySlider &operator=( const PrettySlider& ); //undefined + SliderMode m_mode; +}; - SliderMode m_mode; - }; +class VolumeSlider : public Slider { + Q_OBJECT - class VolumeSlider: public Slider - { - Q_OBJECT + public: + VolumeSlider(QWidget* parent, uint max = 0); - public: - VolumeSlider( QWidget *parent, uint max = 0 ); + protected: + virtual void paintEvent(QPaintEvent*); + virtual void enterEvent(QEvent*); + virtual void leaveEvent(QEvent*); + virtual void paletteChange(const QPalette&); + virtual void slideEvent(QMouseEvent*); + virtual void mousePressEvent(QMouseEvent*); + virtual void contextMenuEvent(QContextMenuEvent*); + virtual void wheelEvent(QWheelEvent* e); - protected: - virtual void paintEvent( QPaintEvent* ); - virtual void enterEvent( QEvent* ); - virtual void leaveEvent( QEvent* ); - virtual void paletteChange( const QPalette& ); - virtual void slideEvent( QMouseEvent* ); - virtual void mousePressEvent( QMouseEvent* ); - virtual void contextMenuEvent( QContextMenuEvent* ); - virtual void wheelEvent( QWheelEvent *e ); + private slots: + virtual void slotAnimTimer(); - private slots: - virtual void slotAnimTimer(); + private: + void generateGradient(); - private: - void generateGradient(); + VolumeSlider(const VolumeSlider&); // undefined + VolumeSlider& operator=(const VolumeSlider&); // undefined - VolumeSlider( const VolumeSlider& ); //undefined - VolumeSlider &operator=( const VolumeSlider& ); //undefined + //////////////////////////////////////////////////////////////// + static const int ANIM_INTERVAL = 18; + static const int ANIM_MAX = 18; - //////////////////////////////////////////////////////////////// - static const int ANIM_INTERVAL = 18; - static const int ANIM_MAX = 18; + bool m_animEnter; + int m_animCount; + QTimer* m_animTimer; - bool m_animEnter; - int m_animCount; - QTimer* m_animTimer; - - QPixmap m_pixmapInset; - QPixmap m_pixmapGradient; - - QList m_handlePixmaps; - }; + QPixmap m_pixmapInset; + QPixmap m_pixmapGradient; + QList m_handlePixmaps; +}; } #endif diff --git a/src/widgets/stickyslider.cpp b/src/widgets/stickyslider.cpp index f05805e7b..5c7064f14 100644 --- a/src/widgets/stickyslider.cpp +++ b/src/widgets/stickyslider.cpp @@ -17,18 +17,13 @@ #include "stickyslider.h" -StickySlider::StickySlider(QWidget *parent) - : QSlider(parent), - sticky_center_(-1), - sticky_threshold_(10) -{ -} +StickySlider::StickySlider(QWidget* parent) + : QSlider(parent), sticky_center_(-1), sticky_threshold_(10) {} -void StickySlider::mouseMoveEvent(QMouseEvent *e) { +void StickySlider::mouseMoveEvent(QMouseEvent* e) { QSlider::mouseMoveEvent(e); - if (sticky_center_ == -1) - return; + if (sticky_center_ == -1) return; const int v = sliderPosition(); if (v <= sticky_center_ + sticky_threshold_ && diff --git a/src/widgets/stickyslider.h b/src/widgets/stickyslider.h index ba1b5426c..4401b8fb8 100644 --- a/src/widgets/stickyslider.h +++ b/src/widgets/stickyslider.h @@ -23,7 +23,8 @@ class StickySlider : public QSlider { Q_OBJECT Q_PROPERTY(int sticky_center READ sticky_center WRITE set_sticky_center); - Q_PROPERTY(int sticky_threshold READ sticky_threshold WRITE set_sticky_threshold); + Q_PROPERTY(int sticky_threshold READ sticky_threshold WRITE + set_sticky_threshold); public: StickySlider(QWidget* parent = 0); @@ -41,4 +42,4 @@ class StickySlider : public QSlider { int sticky_threshold_; }; -#endif // STICKYSLIDER_H +#endif // STICKYSLIDER_H diff --git a/src/widgets/stretchheaderview.cpp b/src/widgets/stretchheaderview.cpp index b5a344852..77d988873 100644 --- a/src/widgets/stretchheaderview.cpp +++ b/src/widgets/stretchheaderview.cpp @@ -27,12 +27,13 @@ const int StretchHeaderView::kMinimumColumnWidth = 20; const int StretchHeaderView::kMagicNumber = 0x502c950f; -StretchHeaderView::StretchHeaderView(Qt::Orientation orientation, QWidget* parent) - : QHeaderView(orientation, parent), - stretch_enabled_(false), - in_mouse_move_event_(false) -{ - connect(this, SIGNAL(sectionResized(int,int,int)), SLOT(SectionResized(int,int,int))); +StretchHeaderView::StretchHeaderView(Qt::Orientation orientation, + QWidget* parent) + : QHeaderView(orientation, parent), + stretch_enabled_(false), + in_mouse_move_event_(false) { + connect(this, SIGNAL(sectionResized(int, int, int)), + SLOT(SectionResized(int, int, int))); setMinimumSectionSize(kMinimumColumnWidth); } @@ -46,8 +47,7 @@ void StretchHeaderView::setModel(QAbstractItemModel* model) { } void StretchHeaderView::NormaliseWidths(const QList& sections) { - if (!stretch_enabled_) - return; + if (!stretch_enabled_) return; const ColumnWidthType total_sum = std::accumulate(column_widths_.begin(), column_widths_.end(), 0.0); @@ -55,37 +55,33 @@ void StretchHeaderView::NormaliseWidths(const QList& sections) { if (!sections.isEmpty()) { selected_sum = 0.0; - for (int i=0 ; i& sections) { - if (!stretch_enabled_) - return; + if (!stretch_enabled_) return; ColumnWidthType total_w = 0.0; - for (int i=0 ; i 0.5) - pixels ++; + if (pixels != 0 && total_w - int(total_w) > 0.5) pixels++; total_w += w; - if (!sections.isEmpty() && !sections.contains(i)) - continue; + if (!sections.isEmpty() && !sections.contains(i)) continue; if (pixels == 0 && !isSectionHidden(i)) hideSection(i); @@ -93,15 +89,14 @@ void StretchHeaderView::UpdateWidths(const QList& sections) { showSection(i); } - if (pixels != 0) - resizeSection(i, pixels); + if (pixels != 0) resizeSection(i, pixels); } } void StretchHeaderView::HideSection(int logical) { // Would this hide the last section? bool all_hidden = true; - for (int i=0 ; i 0) { all_hidden = false; break; @@ -129,19 +124,17 @@ void StretchHeaderView::ShowSection(int logical) { // How many sections are visible already? int visible_count = 0; - for (int i=0 ; i logical_sections_to_resize; - for (int i=0 ; i visual) logical_sections_to_resize << i; } @@ -199,7 +191,7 @@ void StretchHeaderView::SetStretchEnabled(bool enabled) { if (enabled) { // Initialise the list of widths from the current state of the widget column_widths_.resize(count()); - for (int i=0 ; i other_columns; - for (int i=0 ; i pixel_widths; QList visual_indices; - for (int i=0 ; i& sections = QList()); @@ -78,14 +78,14 @@ private: // in column_widths_. void UpdateWidths(const QList& sections = QList()); -private slots: + private slots: void SectionResized(int logical, int old_size, int new_size); -private: + private: bool stretch_enabled_; QVector column_widths_; bool in_mouse_move_event_; }; -#endif // STRETCHHEADERVIEW_H +#endif // STRETCHHEADERVIEW_H diff --git a/src/widgets/stylehelper.cpp b/src/widgets/stylehelper.cpp index 84035f4cd..cc9b98aec 100644 --- a/src/widgets/stylehelper.cpp +++ b/src/widgets/stylehelper.cpp @@ -39,203 +39,196 @@ #include // Clamps float color values within (0, 255) -static int clamp(float x) -{ - const int val = x > 255 ? 255 : static_cast(x); - return val < 0 ? 0 : val; +static int clamp(float x) { + const int val = x > 255 ? 255 : static_cast(x); + return val < 0 ? 0 : val; } namespace Utils { -qreal StyleHelper::sidebarFontSize() -{ +qreal StyleHelper::sidebarFontSize() { #if defined(Q_WS_MAC) - return 10; + return 10; #else - return 7.5; + return 7.5; #endif } -QColor StyleHelper::panelTextColor(bool lightColored) -{ - if (!lightColored) - return Qt::white; - else - return Qt::black; +QColor StyleHelper::panelTextColor(bool lightColored) { + if (!lightColored) + return Qt::white; + else + return Qt::black; } // Invalid by default, setBaseColor needs to be called at least once QColor StyleHelper::m_baseColor; QColor StyleHelper::m_requestedBaseColor; -QColor StyleHelper::baseColor(bool lightColored) -{ - if (!lightColored) - return m_baseColor; - else - return m_baseColor.lighter(230); +QColor StyleHelper::baseColor(bool lightColored) { + if (!lightColored) + return m_baseColor; + else + return m_baseColor.lighter(230); } -QColor StyleHelper::highlightColor(bool lightColored) -{ - QColor result = baseColor(lightColored); - if (!lightColored) - result.setHsv(result.hue(), - clamp(result.saturation()), +QColor StyleHelper::highlightColor(bool lightColored) { + QColor result = baseColor(lightColored); + if (!lightColored) + result.setHsv(result.hue(), clamp(result.saturation()), clamp(result.value() * 1.16)); - else - result.setHsv(result.hue(), - clamp(result.saturation()), + else + result.setHsv(result.hue(), clamp(result.saturation()), clamp(result.value() * 1.06)); - return result; + return result; } -QColor StyleHelper::shadowColor(bool lightColored) -{ - QColor result = baseColor(lightColored); - result.setHsv(result.hue(), - clamp(result.saturation() * 1.1), - clamp(result.value() * 0.70)); - return result; +QColor StyleHelper::shadowColor(bool lightColored) { + QColor result = baseColor(lightColored); + result.setHsv(result.hue(), clamp(result.saturation() * 1.1), + clamp(result.value() * 0.70)); + return result; } -QColor StyleHelper::borderColor(bool lightColored) -{ - QColor result = baseColor(lightColored); - result.setHsv(result.hue(), - result.saturation(), - result.value() / 2); - return result; +QColor StyleHelper::borderColor(bool lightColored) { + QColor result = baseColor(lightColored); + result.setHsv(result.hue(), result.saturation(), result.value() / 2); + return result; } // We try to ensure that the actual color used are within // reasonalbe bounds while generating the actual baseColor // from the users request. -void StyleHelper::setBaseColor(const QColor &newcolor) -{ - m_requestedBaseColor = newcolor; +void StyleHelper::setBaseColor(const QColor& newcolor) { + m_requestedBaseColor = newcolor; - QColor color; - color.setHsv(newcolor.hue(), - newcolor.saturation() * 0.7, - 64 + newcolor.value() / 3); + QColor color; + color.setHsv(newcolor.hue(), newcolor.saturation() * 0.7, + 64 + newcolor.value() / 3); - if (color.isValid() && color != m_baseColor) { - m_baseColor = color; - foreach (QWidget *w, QApplication::topLevelWidgets()) - w->update(); - } + if (color.isValid() && color != m_baseColor) { + m_baseColor = color; + foreach(QWidget * w, QApplication::topLevelWidgets()) + w->update(); + } } -static void verticalGradientHelper(QPainter *p, const QRect &spanRect, const QRect &rect, bool lightColored) -{ - QColor highlight = StyleHelper::highlightColor(lightColored); - QColor shadow = StyleHelper::shadowColor(lightColored); - QLinearGradient grad(spanRect.topRight(), spanRect.topLeft()); - grad.setColorAt(0, highlight.lighter(117)); - grad.setColorAt(1, shadow.darker(109)); - p->fillRect(rect, grad); +static void verticalGradientHelper(QPainter* p, const QRect& spanRect, + const QRect& rect, bool lightColored) { + QColor highlight = StyleHelper::highlightColor(lightColored); + QColor shadow = StyleHelper::shadowColor(lightColored); + QLinearGradient grad(spanRect.topRight(), spanRect.topLeft()); + grad.setColorAt(0, highlight.lighter(117)); + grad.setColorAt(1, shadow.darker(109)); + p->fillRect(rect, grad); - QColor light(255, 255, 255, 80); - p->setPen(light); - p->drawLine(rect.topRight() - QPoint(1, 0), rect.bottomRight() - QPoint(1, 0)); - QColor dark(0, 0, 0, 90); - p->setPen(dark); - p->drawLine(rect.topLeft(), rect.bottomLeft()); + QColor light(255, 255, 255, 80); + p->setPen(light); + p->drawLine(rect.topRight() - QPoint(1, 0), + rect.bottomRight() - QPoint(1, 0)); + QColor dark(0, 0, 0, 90); + p->setPen(dark); + p->drawLine(rect.topLeft(), rect.bottomLeft()); } -void StyleHelper::verticalGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect, bool lightColored) -{ - if (StyleHelper::usePixmapCache()) { - QString key; - QColor keyColor = baseColor(lightColored); - key.sprintf("mh_vertical %d %d %d %d %d", - spanRect.width(), spanRect.height(), clipRect.width(), - clipRect.height(), keyColor.rgb());; +void StyleHelper::verticalGradient(QPainter* painter, const QRect& spanRect, + const QRect& clipRect, bool lightColored) { + if (StyleHelper::usePixmapCache()) { + QString key; + QColor keyColor = baseColor(lightColored); + key.sprintf("mh_vertical %d %d %d %d %d", spanRect.width(), + spanRect.height(), clipRect.width(), clipRect.height(), + keyColor.rgb()); + ; - QPixmap pixmap; - if (!QPixmapCache::find(key, pixmap)) { - pixmap = QPixmap(clipRect.size()); - QPainter p(&pixmap); - QRect rect(0, 0, clipRect.width(), clipRect.height()); - verticalGradientHelper(&p, spanRect, rect, lightColored); - p.end(); - QPixmapCache::insert(key, pixmap); - } - - painter->drawPixmap(clipRect.topLeft(), pixmap); - } else { - verticalGradientHelper(painter, spanRect, clipRect, lightColored); + QPixmap pixmap; + if (!QPixmapCache::find(key, pixmap)) { + pixmap = QPixmap(clipRect.size()); + QPainter p(&pixmap); + QRect rect(0, 0, clipRect.width(), clipRect.height()); + verticalGradientHelper(&p, spanRect, rect, lightColored); + p.end(); + QPixmapCache::insert(key, pixmap); } + + painter->drawPixmap(clipRect.topLeft(), pixmap); + } else { + verticalGradientHelper(painter, spanRect, clipRect, lightColored); + } } // Draws a cached pixmap with shadow -void StyleHelper::drawIconWithShadow(const QIcon &icon, const QRect &rect, - QPainter *p, QIcon::Mode iconMode, int radius, const QColor &color, const QPoint &offset) -{ - QPixmap cache; - QString pixmapName = QString("icon %0 %1 %2").arg(icon.cacheKey()).arg(iconMode).arg(rect.height()); +void StyleHelper::drawIconWithShadow(const QIcon& icon, const QRect& rect, + QPainter* p, QIcon::Mode iconMode, + int radius, const QColor& color, + const QPoint& offset) { + QPixmap cache; + QString pixmapName = + QString("icon %0 %1 %2").arg(icon.cacheKey()).arg(iconMode).arg( + rect.height()); - if (!QPixmapCache::find(pixmapName, cache)) { - QPixmap px = icon.pixmap(rect.size()); - cache = QPixmap(px.size() + QSize(radius * 2, radius * 2)); - cache.fill(Qt::transparent); + if (!QPixmapCache::find(pixmapName, cache)) { + QPixmap px = icon.pixmap(rect.size()); + cache = QPixmap(px.size() + QSize(radius * 2, radius * 2)); + cache.fill(Qt::transparent); - QPainter cachePainter(&cache); - if (iconMode == QIcon::Disabled) { - QImage im = px.toImage().convertToFormat(QImage::Format_ARGB32); - for (int y=0; ydrawPixmap(targetRect.topLeft() - offset, cache); + // Draw shadow + QImage tmp(px.size() + QSize(radius * 2, radius * 2 + 1), + QImage::Format_ARGB32_Premultiplied); + tmp.fill(Qt::transparent); + + QPainter tmpPainter(&tmp); + tmpPainter.setCompositionMode(QPainter::CompositionMode_Source); + tmpPainter.drawPixmap(QPoint(radius, radius), px); + tmpPainter.end(); + + // blur the alpha channel + QImage blurred(tmp.size(), QImage::Format_ARGB32_Premultiplied); + blurred.fill(Qt::transparent); + QPainter blurPainter(&blurred); + qt_blurImage(&blurPainter, tmp, radius, false, true); + blurPainter.end(); + + tmp = blurred; + + // blacken the image... + tmpPainter.begin(&tmp); + tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn); + tmpPainter.fillRect(tmp.rect(), color); + tmpPainter.end(); + + tmpPainter.begin(&tmp); + tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn); + tmpPainter.fillRect(tmp.rect(), color); + tmpPainter.end(); + + // draw the blurred drop shadow... + cachePainter.drawImage( + QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp); + + // Draw the actual pixmap... + cachePainter.drawPixmap(QPoint(radius, radius) + offset, px); + QPixmapCache::insert(pixmapName, cache); + } + + QRect targetRect = cache.rect(); + targetRect.moveCenter(rect.center()); + p->drawPixmap(targetRect.topLeft() - offset, cache); } -} // namespace Utils +} // namespace Utils diff --git a/src/widgets/stylehelper.h b/src/widgets/stylehelper.h index 81e878104..f73f4b442 100644 --- a/src/widgets/stylehelper.h +++ b/src/widgets/stylehelper.h @@ -44,42 +44,45 @@ QT_END_NAMESPACE // Helper class holding all custom color values namespace Utils { -class StyleHelper -{ -public: - static const unsigned int DEFAULT_BASE_COLOR = 0x666666; +class StyleHelper { + public: + static const unsigned int DEFAULT_BASE_COLOR = 0x666666; - // Height of the project explorer navigation bar - static qreal sidebarFontSize(); + // Height of the project explorer navigation bar + static qreal sidebarFontSize(); - // This is our color table, all colors derive from baseColor - static QColor requestedBaseColor() { return m_requestedBaseColor; } - static QColor baseColor(bool lightColored = false); - static QColor panelTextColor(bool lightColored = false); - static QColor highlightColor(bool lightColored = false); - static QColor shadowColor(bool lightColored = false); - static QColor borderColor(bool lightColored = false); + // This is our color table, all colors derive from baseColor + static QColor requestedBaseColor() { return m_requestedBaseColor; } + static QColor baseColor(bool lightColored = false); + static QColor panelTextColor(bool lightColored = false); + static QColor highlightColor(bool lightColored = false); + static QColor shadowColor(bool lightColored = false); + static QColor borderColor(bool lightColored = false); - static QColor sidebarHighlight() { return QColor(255, 255, 255, 40); } - static QColor sidebarShadow() { return QColor(0, 0, 0, 40); } + static QColor sidebarHighlight() { return QColor(255, 255, 255, 40); } + static QColor sidebarShadow() { return QColor(0, 0, 0, 40); } - // Sets the base color and makes sure all top level widgets are updated - static void setBaseColor(const QColor &color); + // Sets the base color and makes sure all top level widgets are updated + static void setBaseColor(const QColor& color); - // Gradients used for panels - static void verticalGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect, bool lightColored = false); - static bool usePixmapCache() { return true; } + // Gradients used for panels + static void verticalGradient(QPainter* painter, const QRect& spanRect, + const QRect& clipRect, + bool lightColored = false); + static bool usePixmapCache() { return true; } - static void drawIconWithShadow(const QIcon &icon, const QRect &rect, QPainter *p, QIcon::Mode iconMode, - int radius = 3, const QColor &color = QColor(0, 0, 0, 130), - const QPoint &offset = QPoint(1, -2)); + static void drawIconWithShadow(const QIcon& icon, const QRect& rect, + QPainter* p, QIcon::Mode iconMode, + int radius = 3, + const QColor& color = QColor(0, 0, 0, 130), + const QPoint& offset = QPoint(1, -2)); -private: - static QColor m_baseColor; - static QColor m_requestedBaseColor; + private: + static QColor m_baseColor; + static QColor m_requestedBaseColor; }; -} // namespace Utils +} // namespace Utils using Utils::StyleHelper; -#endif // STYLEHELPER_H +#endif // STYLEHELPER_H diff --git a/src/widgets/trackslider.cpp b/src/widgets/trackslider.cpp index eab53cbc2..3a092b444 100644 --- a/src/widgets/trackslider.cpp +++ b/src/widgets/trackslider.cpp @@ -23,19 +23,18 @@ #include #ifdef HAVE_MOODBAR -# include "moodbar/moodbarproxystyle.h" +#include "moodbar/moodbarproxystyle.h" #endif const char* TrackSlider::kSettingsGroup = "MainWindow"; TrackSlider::TrackSlider(QWidget* parent) - : QWidget(parent), - ui_(new Ui_TrackSlider), - moodbar_style_(nullptr), - setting_value_(false), - show_remaining_time_(true), - slider_maximum_value_(0) -{ + : QWidget(parent), + ui_(new Ui_TrackSlider), + moodbar_style_(nullptr), + setting_value_(false), + show_remaining_time_(true), + slider_maximum_value_(0) { ui_->setupUi(this); UpdateLabelWidth(); @@ -50,9 +49,7 @@ TrackSlider::TrackSlider(QWidget* parent) connect(ui_->remaining, SIGNAL(Clicked()), SLOT(ToggleTimeDisplay())); } -TrackSlider::~TrackSlider() { - delete ui_; -} +TrackSlider::~TrackSlider() { delete ui_; } void TrackSlider::SetApplication(Application* app) { #ifdef HAVE_MOODBAR @@ -82,13 +79,15 @@ QSize TrackSlider::sizeHint() const { width += ui_->elapsed->sizeHint().width(); width += ui_->remaining->sizeHint().width(); - int height = qMax(ui_->slider->sizeHint().height(), ui_->elapsed->sizeHint().height()); + int height = + qMax(ui_->slider->sizeHint().height(), ui_->elapsed->sizeHint().height()); return QSize(width, height); } void TrackSlider::SetValue(int elapsed, int total) { - setting_value_ = true; // This is so we don't emit from QAbstractSlider::valueChanged + setting_value_ = + true; // This is so we don't emit from QAbstractSlider::valueChanged ui_->slider->setMaximum(total); ui_->slider->setValue(elapsed); setting_value_ = false; @@ -98,12 +97,12 @@ void TrackSlider::SetValue(int elapsed, int total) { void TrackSlider::UpdateTimes(int elapsed) { ui_->elapsed->setText(Utilities::PrettyTime(elapsed)); - //update normally if showing remaining time + // update normally if showing remaining time if (show_remaining_time_) { - ui_->remaining->setText("-" + Utilities::PrettyTime(ui_->slider->maximum() - elapsed)); - } - else { - //check if slider maximum value is changed before updating + ui_->remaining->setText( + "-" + Utilities::PrettyTime(ui_->slider->maximum() - elapsed)); + } else { + // check if slider maximum value is changed before updating if (slider_maximum_value_ != ui_->slider->maximum()) { slider_maximum_value_ = ui_->slider->maximum(); ui_->remaining->setText(Utilities::PrettyTime(ui_->slider->maximum())); @@ -129,12 +128,11 @@ void TrackSlider::SetCanSeek(bool can_seek) { void TrackSlider::Seek(int gap) { if (ui_->slider->isEnabled()) - ui_->slider->setValue(ui_->slider->value()+gap); + ui_->slider->setValue(ui_->slider->value() + gap); } void TrackSlider::ValueMaybeChanged(int value) { - if (setting_value_) - return; + if (setting_value_) return; UpdateTimes(value); emit ValueChanged(value); @@ -155,12 +153,12 @@ bool TrackSlider::event(QEvent* e) { void TrackSlider::ToggleTimeDisplay() { show_remaining_time_ = !show_remaining_time_; if (!show_remaining_time_) { - //we set the value to -1 because the label must be updated + // we set the value to -1 because the label must be updated slider_maximum_value_ = -1; } UpdateTimes(ui_->slider->value()); - //save this setting + // save this setting QSettings s; s.beginGroup(kSettingsGroup); s.setValue("show_remaining_time", show_remaining_time_); diff --git a/src/widgets/trackslider.h b/src/widgets/trackslider.h index 68173ee6f..e8ff54925 100644 --- a/src/widgets/trackslider.h +++ b/src/widgets/trackslider.h @@ -39,7 +39,7 @@ class TrackSlider : public QWidget { QSize sizeHint() const; // QObject - bool event(QEvent *); + bool event(QEvent*); MoodbarProxyStyle* moodbar_style() const { return moodbar_style_; } @@ -51,7 +51,7 @@ class TrackSlider : public QWidget { void SetCanSeek(bool can_seek); void Seek(int gap); - signals: +signals: void ValueChanged(int value); private slots: @@ -70,7 +70,7 @@ class TrackSlider : public QWidget { bool setting_value_; bool show_remaining_time_; - int slider_maximum_value_; //we cache it to avoid unnecessary updates + int slider_maximum_value_; // we cache it to avoid unnecessary updates }; -#endif // TRACKSLIDER_H +#endif // TRACKSLIDER_H diff --git a/src/widgets/tracksliderpopup.cpp b/src/widgets/tracksliderpopup.cpp index 711b94c99..d6e9fbc06 100644 --- a/src/widgets/tracksliderpopup.cpp +++ b/src/widgets/tracksliderpopup.cpp @@ -32,12 +32,10 @@ const int TrackSliderPopup::kPointWidth = 4; const int TrackSliderPopup::kBorderRadius = 4; const qreal TrackSliderPopup::kBlurRadius = 20.0; - TrackSliderPopup::TrackSliderPopup(QWidget* parent) - : QWidget(parent), - font_metrics_(fontMetrics()), - small_font_metrics_(fontMetrics()) -{ + : QWidget(parent), + font_metrics_(fontMetrics()), + small_font_metrics_(fontMetrics()) { setAttribute(Qt::WA_TransparentForMouseEvents); setMouseTracking(true); @@ -69,8 +67,8 @@ void TrackSliderPopup::paintEvent(QPaintEvent*) { } void TrackSliderPopup::UpdatePixmap() { - const int text_width = qMax(font_metrics_.width(text_), - small_font_metrics_.width(small_text_)); + const int text_width = + qMax(font_metrics_.width(text_), small_font_metrics_.width(small_text_)); const QRect text_rect1(kBlurRadius + kTextMargin, kBlurRadius + kTextMargin, text_width + 2, font_metrics_.height()); const QRect text_rect2(kBlurRadius + kTextMargin, text_rect1.bottom(), @@ -84,14 +82,15 @@ void TrackSliderPopup::UpdatePixmap() { bubble_bottom - kBlurRadius); if (background_cache_.size() != total_rect.size()) { - const QColor highlight(palette().color(QPalette::Active, QPalette::Highlight)); + const QColor highlight( + palette().color(QPalette::Active, QPalette::Highlight)); const QColor bg_color_1(highlight.lighter(110)); const QColor bg_color_2(highlight.darker(120)); QPolygon pointy; - pointy << QPoint(total_rect.width()/2 - kPointWidth, bubble_bottom) - << QPoint(total_rect.width()/2, total_rect.bottom() - kBlurRadius) - << QPoint(total_rect.width()/2 + kPointWidth, bubble_bottom); + pointy << QPoint(total_rect.width() / 2 - kPointWidth, bubble_bottom) + << QPoint(total_rect.width() / 2, total_rect.bottom() - kBlurRadius) + << QPoint(total_rect.width() / 2 + kPointWidth, bubble_bottom); QPolygon inner_pointy; inner_pointy << QPoint(pointy[0].x() + 1, pointy[0].y() - 1) @@ -138,8 +137,8 @@ void TrackSliderPopup::UpdatePixmap() { // Inner bubble p.setBrush(bg_color_1); - p.drawRoundedRect(bubble_rect.adjusted(1, 1, -1, -1), - kBorderRadius, kBorderRadius); + p.drawRoundedRect(bubble_rect.adjusted(1, 1, -1, -1), kBorderRadius, + kBorderRadius); // Inner pointy p.drawPolygon(inner_pointy); diff --git a/src/widgets/tracksliderpopup.h b/src/widgets/tracksliderpopup.h index a4cfc9095..97d7d5f7b 100644 --- a/src/widgets/tracksliderpopup.h +++ b/src/widgets/tracksliderpopup.h @@ -23,18 +23,18 @@ class TrackSliderPopup : public QWidget { Q_OBJECT -public: + public: TrackSliderPopup(QWidget* parent); -public slots: + public slots: void SetText(const QString& text); void SetSmallText(const QString& small_text); void SetPopupPosition(const QPoint& pos); -protected: + protected: void paintEvent(QPaintEvent*); -private: + private: static const int kTextMargin; static const int kPointLength; static const int kPointWidth; @@ -45,7 +45,7 @@ private: void UpdatePosition(); void SendMouseEventToParent(QMouseEvent* e); -private: + private: QString text_; QString small_text_; QPoint pos_; @@ -58,4 +58,4 @@ private: QPixmap background_cache_; }; -#endif // TRACKSLIDERPOPUP_H +#endif // TRACKSLIDERPOPUP_H diff --git a/src/widgets/tracksliderslider.cpp b/src/widgets/tracksliderslider.cpp index 7c6779624..540c208ad 100644 --- a/src/widgets/tracksliderslider.cpp +++ b/src/widgets/tracksliderslider.cpp @@ -25,10 +25,9 @@ #include TrackSliderSlider::TrackSliderSlider(QWidget* parent) - : QSlider(parent), - popup_(new TrackSliderPopup(window())), - mouse_hover_seconds_(0) -{ + : QSlider(parent), + popup_(new TrackSliderPopup(window())), + mouse_hover_seconds_(0) { setMouseTracking(true); connect(this, SIGNAL(valueChanged(int)), SLOT(UpdateDeltaTime())); @@ -50,11 +49,11 @@ void TrackSliderSlider::mousePressEvent(QMouseEvent* e) { new_button = Qt::RightButton; } - QMouseEvent new_event(e->type(), e->pos(), new_button, new_button, e->modifiers()); + QMouseEvent new_event(e->type(), e->pos(), new_button, new_button, + e->modifiers()); QSlider::mousePressEvent(&new_event); - if (new_event.isAccepted()) - e->accept(); + if (new_event.isAccepted()) e->accept(); } void TrackSliderSlider::mouseReleaseEvent(QMouseEvent* e) { @@ -67,21 +66,23 @@ void TrackSliderSlider::mouseMoveEvent(QMouseEvent* e) { // Borrowed from QSliderPrivate::pixelPosToRangeValue QStyleOptionSlider opt; initStyleOption(&opt); - QRect gr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); - QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); + QRect gr = style()->subControlRect(QStyle::CC_Slider, &opt, + QStyle::SC_SliderGroove, this); + QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, + QStyle::SC_SliderHandle, this); int slider_length = sr.width(); int slider_min = gr.x(); int slider_max = gr.right() - slider_length + 1; mouse_hover_seconds_ = QStyle::sliderValueFromPosition( - minimum(), maximum(), e->x() - slider_length/2 - slider_min + 1, + minimum(), maximum(), e->x() - slider_length / 2 - slider_min + 1, slider_max - slider_min); popup_->SetText(Utilities::PrettyTime(mouse_hover_seconds_)); UpdateDeltaTime(); - popup_->SetPopupPosition(mapTo(window(), QPoint( - e->x(), rect().center().y()))); + popup_->SetPopupPosition( + mapTo(window(), QPoint(e->x(), rect().center().y()))); } void TrackSliderSlider::enterEvent(QEvent* e) { diff --git a/src/widgets/tracksliderslider.h b/src/widgets/tracksliderslider.h index decaf1816..57d383268 100644 --- a/src/widgets/tracksliderslider.h +++ b/src/widgets/tracksliderslider.h @@ -26,23 +26,23 @@ class TrackSliderPopup; class TrackSliderSlider : public QSlider { Q_OBJECT -public: + public: TrackSliderSlider(QWidget* parent = 0); -protected: + protected: void mousePressEvent(QMouseEvent* e); void mouseReleaseEvent(QMouseEvent* e); void mouseMoveEvent(QMouseEvent* e); void enterEvent(QEvent*); void leaveEvent(QEvent*); -private slots: + private slots: void UpdateDeltaTime(); -private: + private: TrackSliderPopup* popup_; int mouse_hover_seconds_; }; -#endif // TRACKSLIDERSLIDER_H +#endif // TRACKSLIDERSLIDER_H diff --git a/src/widgets/widgetfadehelper.cpp b/src/widgets/widgetfadehelper.cpp index b7bb02881..adb1fcb67 100644 --- a/src/widgets/widgetfadehelper.cpp +++ b/src/widgets/widgetfadehelper.cpp @@ -27,11 +27,10 @@ const int WidgetFadeHelper::kLoadingPadding = 9; const int WidgetFadeHelper::kLoadingBorderRadius = 10; WidgetFadeHelper::WidgetFadeHelper(QWidget* parent, int msec) - : QWidget(parent), - parent_(parent), - blur_timeline_(new QTimeLine(msec, this)), - fade_timeline_(new QTimeLine(msec, this)) -{ + : QWidget(parent), + parent_(parent), + blur_timeline_(new QTimeLine(msec, this)), + fade_timeline_(new QTimeLine(msec, this)) { parent->installEventFilter(this); connect(blur_timeline_, SIGNAL(valueChanged(qreal)), SLOT(update())); @@ -43,12 +42,10 @@ WidgetFadeHelper::WidgetFadeHelper(QWidget* parent, int msec) bool WidgetFadeHelper::eventFilter(QObject* obj, QEvent* event) { // We're only interested in our parent's resize events - if (obj != parent_ || event->type() != QEvent::Resize) - return false; + if (obj != parent_ || event->type() != QEvent::Resize) return false; // Don't care if we're hidden - if (!isVisible()) - return false; + if (!isVisible()) return false; QResizeEvent* re = static_cast(event); if (re->oldSize() == re->size()) { @@ -98,8 +95,8 @@ void WidgetFadeHelper::CaptureParent() { const QString loading_text = tr("Loading..."); const QSize loading_size( - kLoadingPadding*2 + loading_font_metrics.width(loading_text), - kLoadingPadding*2 + loading_font_metrics.height()); + kLoadingPadding * 2 + loading_font_metrics.width(loading_text), + kLoadingPadding * 2 + loading_font_metrics.height()); const QRect loading_rect((blurred.width() - loading_size.width()) / 2, 100, loading_size.width(), loading_size.height()); @@ -109,11 +106,13 @@ void WidgetFadeHelper::CaptureParent() { blur_painter.translate(0.5, 0.5); blur_painter.setPen(QColor(200, 200, 200, 255)); blur_painter.setBrush(QColor(200, 200, 200, 192)); - blur_painter.drawRoundedRect(loading_rect, kLoadingBorderRadius, kLoadingBorderRadius); + blur_painter.drawRoundedRect(loading_rect, kLoadingBorderRadius, + kLoadingBorderRadius); blur_painter.setPen(palette().brush(QPalette::Text).color()); blur_painter.setFont(loading_font); - blur_painter.drawText(loading_rect.translated(-1, -1), Qt::AlignCenter, loading_text); + blur_painter.drawText(loading_rect.translated(-1, -1), Qt::AlignCenter, + loading_text); blur_painter.translate(-0.5, -0.5); blur_painter.end(); @@ -144,7 +143,7 @@ void WidgetFadeHelper::StartFade() { setAttribute(Qt::WA_TransparentForMouseEvents, true); } -void WidgetFadeHelper::paintEvent(QPaintEvent* ) { +void WidgetFadeHelper::paintEvent(QPaintEvent*) { QPainter p(this); if (fade_timeline_->state() != QTimeLine::Running) { diff --git a/src/widgets/widgetfadehelper.h b/src/widgets/widgetfadehelper.h index a83af8365..6d73158b0 100644 --- a/src/widgets/widgetfadehelper.h +++ b/src/widgets/widgetfadehelper.h @@ -25,24 +25,24 @@ class QTimeLine; class WidgetFadeHelper : public QWidget { Q_OBJECT -public: + public: WidgetFadeHelper(QWidget* parent, int msec = 500); -public slots: + public slots: void StartBlur(); void StartFade(); -protected: + protected: void paintEvent(QPaintEvent*); bool eventFilter(QObject* obj, QEvent* event); -private slots: + private slots: void FadeFinished(); -private: + private: void CaptureParent(); -private: + private: static const int kLoadingPadding; static const int kLoadingBorderRadius; @@ -54,4 +54,4 @@ private: QPixmap blurred_pixmap_; }; -#endif // WIDGETFADEHELPER_H +#endif // WIDGETFADEHELPER_H diff --git a/src/wiimotedev/consts.h b/src/wiimotedev/consts.h index 0890961d4..1fd275461 100644 --- a/src/wiimotedev/consts.h +++ b/src/wiimotedev/consts.h @@ -60,89 +60,92 @@ const uint8 STATUS_WIIMOTE_CLASSIC_CONNECTED = 0x04; /* Structs --------------------------------------------- */ struct irpoint { - int16 size; - uint16 x; - uint16 y; }; - -struct accdata { - uint8 x; - uint8 y; - uint8 z; - double pitch; - double roll; }; - -struct stickdata { - uint8 x; - uint8 y; }; - -enum GENERAL_BUTTONS { -// 1.0 API - GENERAL_WIIMOTE_BTN_1 = 0, - GENERAL_WIIMOTE_BTN_2, - GENERAL_WIIMOTE_BTN_A, - GENERAL_WIIMOTE_BTN_B, - GENERAL_WIIMOTE_BTN_MINUS, - GENERAL_WIIMOTE_BTN_PLUS, - GENERAL_WIIMOTE_BTN_HOME, - GENERAL_WIIMOTE_BTN_RIGHT, - GENERAL_WIIMOTE_BTN_LEFT, - GENERAL_WIIMOTE_BTN_DOWN, - GENERAL_WIIMOTE_BTN_UP, - GENERAL_WIIMOTE_BTN_SHIFT_BACKWARD, - GENERAL_WIIMOTE_BTN_SHIFT_FORWARD, - GENERAL_WIIMOTE_BTN_SHIFT_RIGHT, - GENERAL_WIIMOTE_BTN_SHIFT_LEFT, - GENERAL_WIIMOTE_BTN_SHIFT_DOWN, - GENERAL_WIIMOTE_BTN_SHIFT_UP, - GENERAL_WIIMOTE_BTN_TILT_FRONT, - GENERAL_WIIMOTE_BTN_TILT_BACK, - GENERAL_WIIMOTE_BTN_TILT_RIGHT, - GENERAL_WIIMOTE_BTN_TILT_LEFT, - GENERAL_NUNCHUK_BTN_C, - GENERAL_NUNCHUK_BTN_Z, - GENERAL_NUNCHUK_BTN_STICK_RIGHT, - GENERAL_NUNCHUK_BTN_STICK_LEFT, - GENERAL_NUNCHUK_BTN_STICK_DOWN, - GENERAL_NUNCHUK_BTN_STICK_UP, - GENERAL_NUNCHUK_BTN_SHIFT_BACKWARD, - GENERAL_NUNCHUK_BTN_SHIFT_FORWARD, - GENERAL_NUNCHUK_BTN_SHIFT_RIGHT, - GENERAL_NUNCHUK_BTN_SHIFT_LEFT, - GENERAL_NUNCHUK_BTN_SHIFT_DOWN, - GENERAL_NUNCHUK_BTN_SHIFT_UP, - GENERAL_NUNCHUK_BTN_TILT_FRONT, - GENERAL_NUNCHUK_BTN_TILT_BACK, - GENERAL_NUNCHUK_BTN_TILT_RIGHT, - GENERAL_NUNCHUK_BTN_TILT_LEFT, - GENERAL_CLASSIC_BTN_X, - GENERAL_CLASSIC_BTN_Y, - GENERAL_CLASSIC_BTN_A, - GENERAL_CLASSIC_BTN_B, - GENERAL_CLASSIC_BTN_L, - GENERAL_CLASSIC_BTN_R, - GENERAL_CLASSIC_BTN_ZL, - GENERAL_CLASSIC_BTN_ZR, - GENERAL_CLASSIC_BTN_MINUS, - GENERAL_CLASSIC_BTN_PLUS, - GENERAL_CLASSIC_BTN_HOME, - GENERAL_CLASSIC_BTN_RIGHT, - GENERAL_CLASSIC_BTN_LEFT, - GENERAL_CLASSIC_BTN_DOWN, - GENERAL_CLASSIC_BTN_UP, - GENERAL_CLASSIC_BTN_LSTICK_RIGHT, - GENERAL_CLASSIC_BTN_LSTICK_LEFT, - GENERAL_CLASSIC_BTN_LSTICK_DOWN, - GENERAL_CLASSIC_BTN_LSTICK_UP, - GENERAL_CLASSIC_BTN_RSTICK_RIGHT, - GENERAL_CLASSIC_BTN_RSTICK_LEFT, - GENERAL_CLASSIC_BTN_RSTICK_DOWN, - GENERAL_CLASSIC_BTN_RSTICK_UP, -// 1.2 API - GENERAL_WIIMOTE_BTN_SHIFT_SHAKE, - GENERAL_NUNCHUK_BTN_SHIFT_SHAKE + int16 size; + uint16 x; + uint16 y; }; -#define calcbit(x) (static_cast( true) << x) +struct accdata { + uint8 x; + uint8 y; + uint8 z; + double pitch; + double roll; +}; + +struct stickdata { + uint8 x; + uint8 y; +}; + +enum GENERAL_BUTTONS { + // 1.0 API + GENERAL_WIIMOTE_BTN_1 = 0, + GENERAL_WIIMOTE_BTN_2, + GENERAL_WIIMOTE_BTN_A, + GENERAL_WIIMOTE_BTN_B, + GENERAL_WIIMOTE_BTN_MINUS, + GENERAL_WIIMOTE_BTN_PLUS, + GENERAL_WIIMOTE_BTN_HOME, + GENERAL_WIIMOTE_BTN_RIGHT, + GENERAL_WIIMOTE_BTN_LEFT, + GENERAL_WIIMOTE_BTN_DOWN, + GENERAL_WIIMOTE_BTN_UP, + GENERAL_WIIMOTE_BTN_SHIFT_BACKWARD, + GENERAL_WIIMOTE_BTN_SHIFT_FORWARD, + GENERAL_WIIMOTE_BTN_SHIFT_RIGHT, + GENERAL_WIIMOTE_BTN_SHIFT_LEFT, + GENERAL_WIIMOTE_BTN_SHIFT_DOWN, + GENERAL_WIIMOTE_BTN_SHIFT_UP, + GENERAL_WIIMOTE_BTN_TILT_FRONT, + GENERAL_WIIMOTE_BTN_TILT_BACK, + GENERAL_WIIMOTE_BTN_TILT_RIGHT, + GENERAL_WIIMOTE_BTN_TILT_LEFT, + GENERAL_NUNCHUK_BTN_C, + GENERAL_NUNCHUK_BTN_Z, + GENERAL_NUNCHUK_BTN_STICK_RIGHT, + GENERAL_NUNCHUK_BTN_STICK_LEFT, + GENERAL_NUNCHUK_BTN_STICK_DOWN, + GENERAL_NUNCHUK_BTN_STICK_UP, + GENERAL_NUNCHUK_BTN_SHIFT_BACKWARD, + GENERAL_NUNCHUK_BTN_SHIFT_FORWARD, + GENERAL_NUNCHUK_BTN_SHIFT_RIGHT, + GENERAL_NUNCHUK_BTN_SHIFT_LEFT, + GENERAL_NUNCHUK_BTN_SHIFT_DOWN, + GENERAL_NUNCHUK_BTN_SHIFT_UP, + GENERAL_NUNCHUK_BTN_TILT_FRONT, + GENERAL_NUNCHUK_BTN_TILT_BACK, + GENERAL_NUNCHUK_BTN_TILT_RIGHT, + GENERAL_NUNCHUK_BTN_TILT_LEFT, + GENERAL_CLASSIC_BTN_X, + GENERAL_CLASSIC_BTN_Y, + GENERAL_CLASSIC_BTN_A, + GENERAL_CLASSIC_BTN_B, + GENERAL_CLASSIC_BTN_L, + GENERAL_CLASSIC_BTN_R, + GENERAL_CLASSIC_BTN_ZL, + GENERAL_CLASSIC_BTN_ZR, + GENERAL_CLASSIC_BTN_MINUS, + GENERAL_CLASSIC_BTN_PLUS, + GENERAL_CLASSIC_BTN_HOME, + GENERAL_CLASSIC_BTN_RIGHT, + GENERAL_CLASSIC_BTN_LEFT, + GENERAL_CLASSIC_BTN_DOWN, + GENERAL_CLASSIC_BTN_UP, + GENERAL_CLASSIC_BTN_LSTICK_RIGHT, + GENERAL_CLASSIC_BTN_LSTICK_LEFT, + GENERAL_CLASSIC_BTN_LSTICK_DOWN, + GENERAL_CLASSIC_BTN_LSTICK_UP, + GENERAL_CLASSIC_BTN_RSTICK_RIGHT, + GENERAL_CLASSIC_BTN_RSTICK_LEFT, + GENERAL_CLASSIC_BTN_RSTICK_DOWN, + GENERAL_CLASSIC_BTN_RSTICK_UP, + // 1.2 API + GENERAL_WIIMOTE_BTN_SHIFT_SHAKE, + GENERAL_NUNCHUK_BTN_SHIFT_SHAKE +}; + +#define calcbit(x) (static_cast(true) << x) const uint64 WIIMOTE_BTN_1 = calcbit(GENERAL_WIIMOTE_BTN_1); const uint64 WIIMOTE_BTN_2 = calcbit(GENERAL_WIIMOTE_BTN_2); @@ -158,8 +161,10 @@ const uint64 WIIMOTE_BTN_LEFT = calcbit(GENERAL_WIIMOTE_BTN_LEFT); const uint64 WIIMOTE_BTN_DOWN = calcbit(GENERAL_WIIMOTE_BTN_DOWN); const uint64 WIIMOTE_BTN_UP = calcbit(GENERAL_WIIMOTE_BTN_UP); -const uint64 WIIMOTE_BTN_SHIFT_BACKWARD = calcbit(GENERAL_WIIMOTE_BTN_SHIFT_BACKWARD); -const uint64 WIIMOTE_BTN_SHIFT_FORWARD = calcbit(GENERAL_WIIMOTE_BTN_SHIFT_FORWARD); +const uint64 WIIMOTE_BTN_SHIFT_BACKWARD = + calcbit(GENERAL_WIIMOTE_BTN_SHIFT_BACKWARD); +const uint64 WIIMOTE_BTN_SHIFT_FORWARD = + calcbit(GENERAL_WIIMOTE_BTN_SHIFT_FORWARD); const uint64 WIIMOTE_BTN_SHIFT_RIGHT = calcbit(GENERAL_WIIMOTE_BTN_SHIFT_RIGHT); const uint64 WIIMOTE_BTN_SHIFT_LEFT = calcbit(GENERAL_WIIMOTE_BTN_SHIFT_LEFT); const uint64 WIIMOTE_BTN_SHIFT_DOWN = calcbit(GENERAL_WIIMOTE_BTN_SHIFT_DOWN); @@ -178,8 +183,10 @@ const uint64 NUNCHUK_BTN_STICK_LEFT = calcbit(GENERAL_NUNCHUK_BTN_STICK_LEFT); const uint64 NUNCHUK_BTN_STICK_DOWN = calcbit(GENERAL_NUNCHUK_BTN_STICK_DOWN); const uint64 NUNCHUK_BTN_STICK_UP = calcbit(GENERAL_NUNCHUK_BTN_STICK_UP); -const uint64 NUNCHUK_BTN_SHIFT_BACKWARD = calcbit(GENERAL_NUNCHUK_BTN_SHIFT_BACKWARD); -const uint64 NUNCHUK_BTN_SHIFT_FORWARD = calcbit(GENERAL_NUNCHUK_BTN_SHIFT_FORWARD); +const uint64 NUNCHUK_BTN_SHIFT_BACKWARD = + calcbit(GENERAL_NUNCHUK_BTN_SHIFT_BACKWARD); +const uint64 NUNCHUK_BTN_SHIFT_FORWARD = + calcbit(GENERAL_NUNCHUK_BTN_SHIFT_FORWARD); const uint64 NUNCHUK_BTN_SHIFT_RIGHT = calcbit(GENERAL_NUNCHUK_BTN_SHIFT_RIGHT); const uint64 NUNCHUK_BTN_SHIFT_LEFT = calcbit(GENERAL_NUNCHUK_BTN_SHIFT_LEFT); const uint64 NUNCHUK_BTN_SHIFT_DOWN = calcbit(GENERAL_NUNCHUK_BTN_SHIFT_DOWN); @@ -206,12 +213,14 @@ const uint64 CLASSIC_BTN_LEFT = calcbit(GENERAL_CLASSIC_BTN_LEFT); const uint64 CLASSIC_BTN_DOWN = calcbit(GENERAL_CLASSIC_BTN_DOWN); const uint64 CLASSIC_BTN_UP = calcbit(GENERAL_CLASSIC_BTN_UP); -const uint64 CLASSIC_BTN_LSTICK_RIGHT = calcbit(GENERAL_CLASSIC_BTN_LSTICK_RIGHT); +const uint64 CLASSIC_BTN_LSTICK_RIGHT = + calcbit(GENERAL_CLASSIC_BTN_LSTICK_RIGHT); const uint64 CLASSIC_BTN_LSTICK_LEFT = calcbit(GENERAL_CLASSIC_BTN_LSTICK_LEFT); const uint64 CLASSIC_BTN_LSTICK_DOWN = calcbit(GENERAL_CLASSIC_BTN_LSTICK_DOWN); const uint64 CLASSIC_BTN_LSTICK_UP = calcbit(GENERAL_CLASSIC_BTN_LSTICK_UP); -const uint64 CLASSIC_BTN_RSTICK_RIGHT = calcbit(GENERAL_CLASSIC_BTN_RSTICK_RIGHT); +const uint64 CLASSIC_BTN_RSTICK_RIGHT = + calcbit(GENERAL_CLASSIC_BTN_RSTICK_RIGHT); const uint64 CLASSIC_BTN_RSTICK_LEFT = calcbit(GENERAL_CLASSIC_BTN_RSTICK_LEFT); const uint64 CLASSIC_BTN_RSTICK_DOWN = calcbit(GENERAL_CLASSIC_BTN_RSTICK_DOWN); @@ -220,87 +229,48 @@ const uint64 CLASSIC_BTN_RSTICK_UP = calcbit(GENERAL_CLASSIC_BTN_RSTICK_UP); const uint64 WIIMOTE_BTN_SHIFT_SHAKE = calcbit(GENERAL_WIIMOTE_BTN_SHIFT_SHAKE); const uint64 NUNCHUK_BTN_SHIFT_SHAKE = calcbit(GENERAL_NUNCHUK_BTN_SHIFT_SHAKE); -const uint64 WIIMOTE_BUTTON_MASK -= WIIMOTE_BTN_1 | - WIIMOTE_BTN_2 | - WIIMOTE_BTN_A | - WIIMOTE_BTN_B | - WIIMOTE_BTN_MINUS | - WIIMOTE_BTN_PLUS | - WIIMOTE_BTN_HOME | - WIIMOTE_BTN_RIGHT | - WIIMOTE_BTN_LEFT | - WIIMOTE_BTN_DOWN | - WIIMOTE_BTN_UP; +const uint64 WIIMOTE_BUTTON_MASK = + WIIMOTE_BTN_1 | WIIMOTE_BTN_2 | WIIMOTE_BTN_A | WIIMOTE_BTN_B | + WIIMOTE_BTN_MINUS | WIIMOTE_BTN_PLUS | WIIMOTE_BTN_HOME | + WIIMOTE_BTN_RIGHT | WIIMOTE_BTN_LEFT | WIIMOTE_BTN_DOWN | WIIMOTE_BTN_UP; -const uint64 WIIMOTE_SHIFT_MASK -= WIIMOTE_BTN_SHIFT_BACKWARD | - WIIMOTE_BTN_SHIFT_FORWARD | - WIIMOTE_BTN_SHIFT_RIGHT | - WIIMOTE_BTN_SHIFT_LEFT | - WIIMOTE_BTN_SHIFT_DOWN | - WIIMOTE_BTN_SHIFT_UP | - WIIMOTE_BTN_SHIFT_SHAKE; +const uint64 WIIMOTE_SHIFT_MASK = + WIIMOTE_BTN_SHIFT_BACKWARD | WIIMOTE_BTN_SHIFT_FORWARD | + WIIMOTE_BTN_SHIFT_RIGHT | WIIMOTE_BTN_SHIFT_LEFT | WIIMOTE_BTN_SHIFT_DOWN | + WIIMOTE_BTN_SHIFT_UP | WIIMOTE_BTN_SHIFT_SHAKE; -const uint64 WIIMOTE_TILT_MASK -= WIIMOTE_BTN_TILT_FRONT | - WIIMOTE_BTN_TILT_BACK | - WIIMOTE_BTN_TILT_RIGHT | - WIIMOTE_BTN_TILT_LEFT; +const uint64 WIIMOTE_TILT_MASK = WIIMOTE_BTN_TILT_FRONT | + WIIMOTE_BTN_TILT_BACK | + WIIMOTE_BTN_TILT_RIGHT | WIIMOTE_BTN_TILT_LEFT; -const uint64 NUNCHUK_BUTTON_MASK -= NUNCHUK_BTN_C | - NUNCHUK_BTN_Z; +const uint64 NUNCHUK_BUTTON_MASK = NUNCHUK_BTN_C | NUNCHUK_BTN_Z; -const uint64 NUNCHUK_STICK_MASK -= NUNCHUK_BTN_STICK_RIGHT | - NUNCHUK_BTN_STICK_LEFT | - NUNCHUK_BTN_STICK_DOWN | - NUNCHUK_BTN_STICK_UP; +const uint64 NUNCHUK_STICK_MASK = NUNCHUK_BTN_STICK_RIGHT | + NUNCHUK_BTN_STICK_LEFT | + NUNCHUK_BTN_STICK_DOWN | NUNCHUK_BTN_STICK_UP; -const uint64 NUNCHUK_SHIFT_MASK -= NUNCHUK_BTN_SHIFT_BACKWARD | - NUNCHUK_BTN_SHIFT_FORWARD | - NUNCHUK_BTN_SHIFT_RIGHT | - NUNCHUK_BTN_SHIFT_LEFT | - NUNCHUK_BTN_SHIFT_DOWN | - NUNCHUK_BTN_SHIFT_UP | - NUNCHUK_BTN_SHIFT_SHAKE; +const uint64 NUNCHUK_SHIFT_MASK = + NUNCHUK_BTN_SHIFT_BACKWARD | NUNCHUK_BTN_SHIFT_FORWARD | + NUNCHUK_BTN_SHIFT_RIGHT | NUNCHUK_BTN_SHIFT_LEFT | NUNCHUK_BTN_SHIFT_DOWN | + NUNCHUK_BTN_SHIFT_UP | NUNCHUK_BTN_SHIFT_SHAKE; -const uint64 NUNCHUK_TILT_MASK -= NUNCHUK_BTN_TILT_FRONT | - NUNCHUK_BTN_TILT_BACK | - NUNCHUK_BTN_TILT_RIGHT | - NUNCHUK_BTN_TILT_LEFT; +const uint64 NUNCHUK_TILT_MASK = NUNCHUK_BTN_TILT_FRONT | + NUNCHUK_BTN_TILT_BACK | + NUNCHUK_BTN_TILT_RIGHT | NUNCHUK_BTN_TILT_LEFT; -const uint64 CLASSIC_BUTTON_MASK -= CLASSIC_BTN_X | - CLASSIC_BTN_Y | - CLASSIC_BTN_A | - CLASSIC_BTN_B | - CLASSIC_BTN_L | - CLASSIC_BTN_R | - CLASSIC_BTN_ZL | - CLASSIC_BTN_ZR | - CLASSIC_BTN_MINUS | - CLASSIC_BTN_PLUS | - CLASSIC_BTN_HOME | - CLASSIC_BTN_RIGHT | - CLASSIC_BTN_LEFT | - CLASSIC_BTN_DOWN | - CLASSIC_BTN_UP; +const uint64 CLASSIC_BUTTON_MASK = + CLASSIC_BTN_X | CLASSIC_BTN_Y | CLASSIC_BTN_A | CLASSIC_BTN_B | + CLASSIC_BTN_L | CLASSIC_BTN_R | CLASSIC_BTN_ZL | CLASSIC_BTN_ZR | + CLASSIC_BTN_MINUS | CLASSIC_BTN_PLUS | CLASSIC_BTN_HOME | + CLASSIC_BTN_RIGHT | CLASSIC_BTN_LEFT | CLASSIC_BTN_DOWN | CLASSIC_BTN_UP; -const uint64 CLASSIC_LSTICK_MASK -= CLASSIC_BTN_LSTICK_RIGHT | - CLASSIC_BTN_LSTICK_LEFT | - CLASSIC_BTN_LSTICK_DOWN | - CLASSIC_BTN_LSTICK_UP; +const uint64 CLASSIC_LSTICK_MASK = + CLASSIC_BTN_LSTICK_RIGHT | CLASSIC_BTN_LSTICK_LEFT | + CLASSIC_BTN_LSTICK_DOWN | CLASSIC_BTN_LSTICK_UP; -const uint64 CLASSIC_RSTICK_MASK -= CLASSIC_BTN_RSTICK_RIGHT | - CLASSIC_BTN_RSTICK_LEFT | - CLASSIC_BTN_RSTICK_DOWN | - CLASSIC_BTN_RSTICK_UP; +const uint64 CLASSIC_RSTICK_MASK = + CLASSIC_BTN_RSTICK_RIGHT | CLASSIC_BTN_RSTICK_LEFT | + CLASSIC_BTN_RSTICK_DOWN | CLASSIC_BTN_RSTICK_UP; const uint64 WIIMOTE_BUTTON_NOTMASK = ~WIIMOTE_BUTTON_MASK; const uint64 WIIMOTE_SHIFT_NOTMASK = ~WIIMOTE_SHIFT_MASK; @@ -313,4 +283,4 @@ const uint64 CLASSIC_BUTTON_NOTMASK = ~CLASSIC_BUTTON_MASK; const uint64 CLASSIC_LSTICK_NOTMASK = ~CLASSIC_LSTICK_MASK; const uint64 CLASSIC_RSTICK_NOTMASK = ~CLASSIC_RSTICK_MASK; -#endif // WIIMOTEDEV_CONSTS_H +#endif // WIIMOTEDEV_CONSTS_H diff --git a/src/wiimotedev/shortcuts.cpp b/src/wiimotedev/shortcuts.cpp index 6379a5ab1..761ba53d8 100644 --- a/src/wiimotedev/shortcuts.cpp +++ b/src/wiimotedev/shortcuts.cpp @@ -23,34 +23,39 @@ const char* WiimotedevShortcuts::kActionsGroup = "WiimotedevActions"; const char* WiimotedevShortcuts::kSettingsGroup = "WiimotedevSettings"; -WiimotedevShortcuts::WiimotedevShortcuts(OSD* osd, QWidget* window, QObject* parent) - :QObject(parent), - osd_(osd), - main_window_(window), - player_(qobject_cast(parent)), - low_battery_notification_(true), - critical_battery_notification_(true), - actived_(false), - wiimotedev_active_(true), - wiimotedev_buttons_(0), - wiimotedev_device_(1), - wiimotedev_enable_(true), - wiimotedev_focus_(false), - wiimotedev_notification_(true) -{ - connect(this, SIGNAL(WiiremoteActived(int)), osd_, SLOT(WiiremoteActived(int))); - connect(this, SIGNAL(WiiremoteDeactived(int)), osd_, SLOT(WiiremoteDeactived(int))); - connect(this, SIGNAL(WiiremoteConnected(int)), osd_, SLOT(WiiremoteConnected(int))); - connect(this, SIGNAL(WiiremoteDisconnected(int)), osd_, SLOT(WiiremoteDisconnected(int))); - connect(this, SIGNAL(WiiremoteLowBattery(int,int)), osd_, SLOT(WiiremoteLowBattery(int,int))); - connect(this, SIGNAL(WiiremoteCriticalBattery(int,int)), osd_, SLOT(WiiremoteCriticalBattery(int,int))); +WiimotedevShortcuts::WiimotedevShortcuts(OSD* osd, QWidget* window, + QObject* parent) + : QObject(parent), + osd_(osd), + main_window_(window), + player_(qobject_cast(parent)), + low_battery_notification_(true), + critical_battery_notification_(true), + actived_(false), + wiimotedev_active_(true), + wiimotedev_buttons_(0), + wiimotedev_device_(1), + wiimotedev_enable_(true), + wiimotedev_focus_(false), + wiimotedev_notification_(true) { + connect(this, SIGNAL(WiiremoteActived(int)), osd_, + SLOT(WiiremoteActived(int))); + connect(this, SIGNAL(WiiremoteDeactived(int)), osd_, + SLOT(WiiremoteDeactived(int))); + connect(this, SIGNAL(WiiremoteConnected(int)), osd_, + SLOT(WiiremoteConnected(int))); + connect(this, SIGNAL(WiiremoteDisconnected(int)), osd_, + SLOT(WiiremoteDisconnected(int))); + connect(this, SIGNAL(WiiremoteLowBattery(int, int)), osd_, + SLOT(WiiremoteLowBattery(int, int))); + connect(this, SIGNAL(WiiremoteCriticalBattery(int, int)), osd_, + SLOT(WiiremoteCriticalBattery(int, int))); ReloadSettings(); } void WiimotedevShortcuts::SetWiimotedevInterfaceActived(bool actived) { - if (!QDBusConnection::systemBus().isConnected()) - return; + if (!QDBusConnection::systemBus().isConnected()) return; // http://code.google.com/p/clementine-player/issues/detail?id=670 // Probably dbus bug, or something else @@ -60,21 +65,22 @@ void WiimotedevShortcuts::SetWiimotedevInterfaceActived(bool actived) { WIIMOTEDEV_DBUS_SERVICE_NAME, WIIMOTEDEV_DBUS_EVENTS_OBJECT, QDBusConnection::systemBus(), this)); - connect(wiimotedev_iface_.get(), SIGNAL(dbusWiimoteGeneralButtons(uint,qulonglong)), - this, SLOT(DbusWiimoteGeneralButtons(uint,qulonglong))); + connect(wiimotedev_iface_.get(), + SIGNAL(dbusWiimoteGeneralButtons(uint, qulonglong)), this, + SLOT(DbusWiimoteGeneralButtons(uint, qulonglong))); connect(wiimotedev_iface_.get(), SIGNAL(dbusWiimoteConnected(uint)), this, SLOT(DbusWiimoteConnected(uint))); - connect(wiimotedev_iface_.get(), SIGNAL(dbusWiimoteDisconnected(uint)), this, - SLOT(DbusWiimoteDisconnected(uint))); - connect(wiimotedev_iface_.get(), SIGNAL(dbusWiimoteBatteryLife(uint,uchar)), this, - SLOT(DbusWiimoteBatteryLife(uint,uchar))); + connect(wiimotedev_iface_.get(), SIGNAL(dbusWiimoteDisconnected(uint)), + this, SLOT(DbusWiimoteDisconnected(uint))); + connect(wiimotedev_iface_.get(), + SIGNAL(dbusWiimoteBatteryLife(uint, uchar)), this, + SLOT(DbusWiimoteBatteryLife(uint, uchar))); if (!wiimotedev_iface_.get()->isValid()) qWarning("Error connecting to the Wiimotedev-daemon DBUS service"); } - if (!actived && wiimotedev_iface_) - wiimotedev_iface_.reset(); + if (!actived && wiimotedev_iface_) wiimotedev_iface_.reset(); } void WiimotedevShortcuts::ReloadSettings() { @@ -86,11 +92,10 @@ void WiimotedevShortcuts::ReloadSettings() { quint64 fvalue, svalue; bool fvalid, svalid; - foreach (const QString& str, settings_.allKeys()) { + foreach(const QString & str, settings_.allKeys()) { fvalue = str.toULongLong(&fvalid, 10); svalue = settings_.value(str, 0).toULongLong(&svalid); - if (fvalid && svalid) - actions_[fvalue] = svalue; + if (fvalid && svalid) actions_[fvalue] = svalue; } settings_.endGroup(); @@ -109,14 +114,11 @@ void WiimotedevShortcuts::ReloadSettings() { void WiimotedevShortcuts::DbusWiimoteGeneralButtons(uint id, qulonglong value) { if (id != wiimotedev_device_ || !wiimotedev_enable_ || !player_) return; - if (wiimotedev_focus_ && !main_window_->isActiveWindow()) - return; + if (wiimotedev_focus_ && !main_window_->isActiveWindow()) return; - quint64 buttons = value & ~( - WIIMOTE_TILT_MASK | - NUNCHUK_TILT_MASK | - WIIMOTE_BTN_SHIFT_SHAKE | - NUNCHUK_BTN_SHIFT_SHAKE); + quint64 buttons = + value & ~(WIIMOTE_TILT_MASK | NUNCHUK_TILT_MASK | + WIIMOTE_BTN_SHIFT_SHAKE | NUNCHUK_BTN_SHIFT_SHAKE); if (wiimotedev_buttons_ == buttons) return; @@ -127,7 +129,8 @@ void WiimotedevShortcuts::DbusWiimoteGeneralButtons(uint id, qulonglong value) { actived_ = !actived_; if (wiimotedev_notification_) { if (actived_) - emit WiiremoteActived(id); else + emit WiiremoteActived(id); + else emit WiiremoteDeactived(id); } } @@ -135,19 +138,45 @@ void WiimotedevShortcuts::DbusWiimoteGeneralButtons(uint id, qulonglong value) { if (actived_ || !wiimotedev_active_) { switch (actions_.value(buttons, ActionNone)) { - case PlayerNextTrack: player_->Next(); break; - case PlayerPreviousTrack: player_->Previous(); break; - case PlayerPlay: player_->Play(); break; - case PlayerStop: player_->Stop(); break; - case PlayerIncVolume: player_->VolumeUp(); break; - case PlayerDecVolume: player_->VolumeDown(); break; - case PlayerMute: player_->Mute(); break; - case PlayerPause: player_->Pause(); break; - case PlayerTogglePause: player_->PlayPause(); break; - case PlayerSeekBackward: player_->SeekBackward(); break; - case PlayerSeekForward: player_->SeekForward(); break; - case PlayerStopAfter: player_->Stop(); break; - case PlayerShowOSD: player_->ShowOSD(); break; + case PlayerNextTrack: + player_->Next(); + break; + case PlayerPreviousTrack: + player_->Previous(); + break; + case PlayerPlay: + player_->Play(); + break; + case PlayerStop: + player_->Stop(); + break; + case PlayerIncVolume: + player_->VolumeUp(); + break; + case PlayerDecVolume: + player_->VolumeDown(); + break; + case PlayerMute: + player_->Mute(); + break; + case PlayerPause: + player_->Pause(); + break; + case PlayerTogglePause: + player_->PlayPause(); + break; + case PlayerSeekBackward: + player_->SeekBackward(); + break; + case PlayerSeekForward: + player_->SeekForward(); + break; + case PlayerStopAfter: + player_->Stop(); + break; + case PlayerShowOSD: + player_->ShowOSD(); + break; } } } @@ -179,5 +208,3 @@ void WiimotedevShortcuts::DbusWiimoteBatteryLife(uint id, uchar life) { } } } - - diff --git a/src/wiimotedev/shortcuts.h b/src/wiimotedev/shortcuts.h index be0206789..b3310a722 100644 --- a/src/wiimotedev/shortcuts.h +++ b/src/wiimotedev/shortcuts.h @@ -28,9 +28,9 @@ class QSettings; -class WiimotedevShortcuts :public QObject { +class WiimotedevShortcuts : public QObject { Q_OBJECT -public: + public: static const char* kActionsGroup; static const char* kSettingsGroup; @@ -51,20 +51,20 @@ public: PlayerSeekForward, PlayerStopAfter, PlayerShowOSD, - ActionNone = 0xff + ActionNone = 0xff }; -public slots: + public slots: void SetWiimotedevInterfaceActived(bool actived); void ReloadSettings(); -private slots: + private slots: void DbusWiimoteBatteryLife(uint id, uchar life); void DbusWiimoteConnected(uint id); void DbusWiimoteDisconnected(uint id); void DbusWiimoteGeneralButtons(uint id, qulonglong value); -private: + private: OSD* osd_; QWidget* main_window_; Player* player_; @@ -81,7 +81,7 @@ private: std::unique_ptr wiimotedev_iface_; bool wiimotedev_notification_; - QHash actions_; + QHash actions_; QSettings settings_; signals: @@ -93,4 +93,4 @@ signals: void WiiremoteCriticalBattery(int, int); }; -#endif // WIIMOTEDEV_SHORTCUTS_H +#endif // WIIMOTEDEV_SHORTCUTS_H diff --git a/src/wiimotedev/wiimotesettingspage.cpp b/src/wiimotedev/wiimotesettingspage.cpp index 1c33c69a1..9fe00dbed 100644 --- a/src/wiimotedev/wiimotesettingspage.cpp +++ b/src/wiimotedev/wiimotesettingspage.cpp @@ -23,11 +23,8 @@ #include - WiimoteSettingsPage::WiimoteSettingsPage(SettingsDialog* dialog) - : SettingsPage(dialog), - ui_(new Ui_WiimoteSettingsPage) -{ + : SettingsPage(dialog), ui_(new Ui_WiimoteSettingsPage) { ui_->setupUi(this); ui_->list->header()->setResizeMode(QHeaderView::ResizeToContents); setWindowIcon(QIcon(":/icons/32x32/wiimotedev.png")); @@ -95,39 +92,55 @@ WiimoteSettingsPage::WiimoteSettingsPage(SettingsDialog* dialog) text_buttons_.insert(WIIMOTE_BTN_SHIFT_SHAKE, "Wiiremote Shift Shake"); text_buttons_.insert(NUNCHUK_BTN_SHIFT_SHAKE, "Nunchuk Shift Shake"); - text_actions_.insert(WiimotedevShortcuts::WiimotedevActiveDeactive, tr("Active/deactive Wiiremote")); + text_actions_.insert(WiimotedevShortcuts::WiimotedevActiveDeactive, + tr("Active/deactive Wiiremote")); text_actions_.insert(WiimotedevShortcuts::PlayerNextTrack, tr("Next track")); - text_actions_.insert(WiimotedevShortcuts::PlayerPreviousTrack, tr("Previous track")); + text_actions_.insert(WiimotedevShortcuts::PlayerPreviousTrack, + tr("Previous track")); text_actions_.insert(WiimotedevShortcuts::PlayerPlay, tr("Play")); text_actions_.insert(WiimotedevShortcuts::PlayerStop, tr("Stop")); - text_actions_.insert(WiimotedevShortcuts::PlayerIncVolume, tr("Increase volume")); - text_actions_.insert(WiimotedevShortcuts::PlayerDecVolume, tr("Decrease volume")); + text_actions_.insert(WiimotedevShortcuts::PlayerIncVolume, + tr("Increase volume")); + text_actions_.insert(WiimotedevShortcuts::PlayerDecVolume, + tr("Decrease volume")); text_actions_.insert(WiimotedevShortcuts::PlayerMute, tr("Mute")); text_actions_.insert(WiimotedevShortcuts::PlayerPause, tr("Pause")); - text_actions_.insert(WiimotedevShortcuts::PlayerTogglePause, tr("Play/Pause")); - text_actions_.insert(WiimotedevShortcuts::PlayerSeekBackward, tr("Seek backward")); - text_actions_.insert(WiimotedevShortcuts::PlayerSeekForward, tr("Seek forward")); + text_actions_.insert(WiimotedevShortcuts::PlayerTogglePause, + tr("Play/Pause")); + text_actions_.insert(WiimotedevShortcuts::PlayerSeekBackward, + tr("Seek backward")); + text_actions_.insert(WiimotedevShortcuts::PlayerSeekForward, + tr("Seek forward")); text_actions_.insert(WiimotedevShortcuts::PlayerStopAfter, tr("Stop after")); text_actions_.insert(WiimotedevShortcuts::PlayerShowOSD, tr("Show OSD")); - connect(ui_->list, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), SLOT(ItemClicked(QTreeWidgetItem*))); + connect(ui_->list, + SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), + SLOT(ItemClicked(QTreeWidgetItem*))); - connect(ui_->wiimotedev_add_action, SIGNAL(clicked()), this, SLOT(AddAction())); - connect(ui_->wiimotedev_delete_action, SIGNAL(clicked()), this, SLOT(DeleteAction())); - connect(ui_->wiimotedev_reload, SIGNAL(clicked()), this , SLOT(DefaultSettings())); + connect(ui_->wiimotedev_add_action, SIGNAL(clicked()), this, + SLOT(AddAction())); + connect(ui_->wiimotedev_delete_action, SIGNAL(clicked()), this, + SLOT(DeleteAction())); + connect(ui_->wiimotedev_reload, SIGNAL(clicked()), this, + SLOT(DefaultSettings())); } - void WiimoteSettingsPage::AddShortcut(quint64 button, quint32 action) { - foreach (const Shortcut& shortcut, actions_) { + foreach(const Shortcut & shortcut, actions_) { if (shortcut.button == button) { - QMessageBox::information(this, tr("Information"), QString(tr("Shortcut for %1 already exists")).arg(GetReadableWiiremoteSequence(button)), QMessageBox::Ok); + QMessageBox::information(this, tr("Information"), + QString(tr("Shortcut for %1 already exists")) + .arg(GetReadableWiiremoteSequence(button)), + QMessageBox::Ok); return; } } Shortcut s; - s.object = new QTreeWidgetItem(ui_->list, QStringList() << GetReadableWiiremoteSequence(button) << text_actions_[action]); + s.object = new QTreeWidgetItem( + ui_->list, QStringList() << GetReadableWiiremoteSequence(button) + << text_actions_[action]); s.button = button; s.action = action; actions_ << s; @@ -137,9 +150,12 @@ void WiimoteSettingsPage::Load() { QSettings s; s.beginGroup(WiimotedevShortcuts::kSettingsGroup); ui_->wiimotedev_enable->setChecked(s.value("enabled", false).toBool()); - ui_->wiimotedev_active->setChecked(s.value("use_active_action", true).toBool()); - ui_->wiimotedev_focus->setChecked(s.value("only_when_focused", false).toBool()); - ui_->wiimotedev_notification->setChecked(s.value("use_notification", true).toBool()); + ui_->wiimotedev_active->setChecked( + s.value("use_active_action", true).toBool()); + ui_->wiimotedev_focus->setChecked( + s.value("only_when_focused", false).toBool()); + ui_->wiimotedev_notification->setChecked( + s.value("use_notification", true).toBool()); ui_->wiimotedev_device->setValue(s.value("device", 1).toUInt()); bool first_conf = s.value("first_conf", true).toBool(); s.endGroup(); @@ -156,11 +172,10 @@ void WiimoteSettingsPage::Load() { quint64 fvalue, svalue; bool fvalid, svalid; - foreach (const QString& str, s.allKeys()) { + foreach(const QString & str, s.allKeys()) { fvalue = str.toULongLong(&fvalid, 10); svalue = s.value(str, 0).toULongLong(&svalid); - if (fvalid && svalid) - AddShortcut(fvalue, svalue); + if (fvalid && svalid) AddShortcut(fvalue, svalue); } s.endGroup(); @@ -172,8 +187,8 @@ void WiimoteSettingsPage::Save() { s.beginGroup(WiimotedevShortcuts::kActionsGroup); s.remove(""); - foreach (const Shortcut& shortcut, actions_) - s.setValue(QString::number(shortcut.button), shortcut.action); + foreach(const Shortcut & shortcut, actions_) + s.setValue(QString::number(shortcut.button), shortcut.action); s.endGroup(); s.beginGroup(WiimotedevShortcuts::kSettingsGroup); @@ -213,15 +228,12 @@ QString WiimoteSettingsPage::GetReadableWiiremoteSequence(quint64 value) { QStringList list; while (text.hasNext()) { text.next(); - if ((text.key() & value) == text.key()) - list << text.value(); + if ((text.key() & value) == text.key()) list << text.value(); } - QString output; if (!list.isEmpty()) { - for (int i = 0; i < (list.count() - 1); ++i) - output += list.at(i) + " + "; + for (int i = 0; i < (list.count() - 1); ++i) output += list.at(i) + " + "; output += list.last(); } else output = tr("Push Wiiremote button"); @@ -232,7 +244,8 @@ QString WiimoteSettingsPage::GetReadableWiiremoteSequence(quint64 value) { void WiimoteSettingsPage::AddAction() { emit SetWiimotedevInterfaceActived(false); WiimoteShortcutGrabber grabber(0, ui_->wiimotedev_device->value(), this); - connect(&grabber, SIGNAL(AddShortcut(quint64,quint32)), this, SLOT(AddShortcut(quint64,quint32)), Qt::QueuedConnection); + connect(&grabber, SIGNAL(AddShortcut(quint64, quint32)), this, + SLOT(AddShortcut(quint64, quint32)), Qt::QueuedConnection); grabber.exec(); emit SetWiimotedevInterfaceActived(true); diff --git a/src/wiimotedev/wiimotesettingspage.h b/src/wiimotedev/wiimotesettingspage.h index af31966d1..6597b91b8 100644 --- a/src/wiimotedev/wiimotesettingspage.h +++ b/src/wiimotedev/wiimotesettingspage.h @@ -28,7 +28,7 @@ class Ui_WiimoteSettingsPage; class WiimoteSettingsPage : public SettingsPage { Q_OBJECT -public: + public: WiimoteSettingsPage(SettingsDialog* dialog); void Load(); @@ -40,14 +40,14 @@ public: signals: void SetWiimotedevInterfaceActived(bool); -private slots: + private slots: void AddAction(); void AddShortcut(quint64 button, quint32 action); void DefaultSettings(); void DeleteAction(); void ItemClicked(QTreeWidgetItem*); -private: + private: struct Shortcut { QTreeWidgetItem* object; quint64 button; @@ -65,4 +65,4 @@ private: QTreeWidgetItem* selected_item_; }; -#endif // WIIMOTESETTINGSPAGE_H +#endif // WIIMOTESETTINGSPAGE_H diff --git a/src/wiimotedev/wiimoteshortcutgrabber.cpp b/src/wiimotedev/wiimoteshortcutgrabber.cpp index 3cfbc57dc..d712681b2 100644 --- a/src/wiimotedev/wiimoteshortcutgrabber.cpp +++ b/src/wiimotedev/wiimoteshortcutgrabber.cpp @@ -21,46 +21,43 @@ WiimoteShortcutGrabber::WiimoteShortcutGrabber(quint32 action, quint32 device, WiimoteSettingsPage* parent) - :QDialog(parent), - pref_action_(action), - ui_(new Ui_WiimoteShortcutGrabber), - config_(parent), - wiimotedev_device_(device), - wiimotedev_buttons_(0), - remember_wiimote_shifts_(0), - remember_nunchuk_shifts_(0) -{ + : QDialog(parent), + pref_action_(action), + ui_(new Ui_WiimoteShortcutGrabber), + config_(parent), + wiimotedev_device_(device), + wiimotedev_buttons_(0), + remember_wiimote_shifts_(0), + remember_nunchuk_shifts_(0) { ui_->setupUi(this); if (QDBusConnection::systemBus().isConnected()) { wiimotedev_iface_.reset(new OrgWiimotedevDeviceEventsInterface( - WIIMOTEDEV_DBUS_SERVICE_NAME, - WIIMOTEDEV_DBUS_EVENTS_OBJECT, - QDBusConnection::systemBus(), - this)); + WIIMOTEDEV_DBUS_SERVICE_NAME, WIIMOTEDEV_DBUS_EVENTS_OBJECT, + QDBusConnection::systemBus(), this)); - connect(wiimotedev_iface_.get(), SIGNAL(dbusWiimoteGeneralButtons(uint,qulonglong)), - this, SLOT(DbusWiimoteGeneralButtons(uint,qulonglong))); + connect(wiimotedev_iface_.get(), + SIGNAL(dbusWiimoteGeneralButtons(uint, qulonglong)), this, + SLOT(DbusWiimoteGeneralButtons(uint, qulonglong))); } - foreach (const QString& name, config_->TextActions()) - ui_->comboBox->addItem(name); + foreach(const QString & name, config_->TextActions()) + ui_->comboBox->addItem(name); ui_->comboBox->setCurrentIndex(pref_action_); ui_->keep_label->setVisible(false); - connect(ui_->remember_shifts, SIGNAL(clicked(bool)), this, SLOT(RememberSwingChecked(bool))); - connect(ui_->buttonBox, SIGNAL(rejected()), this, SLOT(close())); + connect(ui_->remember_shifts, SIGNAL(clicked(bool)), this, + SLOT(RememberSwingChecked(bool))); + connect(ui_->buttonBox, SIGNAL(rejected()), this, SLOT(close())); connect(&line_, SIGNAL(frameChanged(int)), this, SLOT(Timeout(int))); line_.setFrameRange(4, 0); line_.setEasingCurve(QEasingCurve::Linear); - line_.setDuration(line_.startFrame()*1000); + line_.setDuration(line_.startFrame() * 1000); } -WiimoteShortcutGrabber::~WiimoteShortcutGrabber() { - delete ui_; -} +WiimoteShortcutGrabber::~WiimoteShortcutGrabber() { delete ui_; } void WiimoteShortcutGrabber::Timeout(int secs) { if (!secs) { @@ -69,8 +66,11 @@ void WiimoteShortcutGrabber::Timeout(int secs) { } if (secs == 1) - ui_->keep_label->setText(QString(tr("Keep buttons for %1 second...")).arg(QString::number(secs))); else - ui_->keep_label->setText(QString(tr("Keep buttons for %1 seconds...")).arg(QString::number(secs))); + ui_->keep_label->setText(QString(tr("Keep buttons for %1 second...")) + .arg(QString::number(secs))); + else + ui_->keep_label->setText(QString(tr("Keep buttons for %1 seconds...")) + .arg(QString::number(secs))); } void WiimoteShortcutGrabber::RememberSwingChecked(bool checked) { @@ -78,9 +78,8 @@ void WiimoteShortcutGrabber::RememberSwingChecked(bool checked) { line_.stop(); ui_->keep_label->setVisible(false); - if (checked) { - buttons |= remember_wiimote_shifts_ | remember_nunchuk_shifts_; + buttons |= remember_wiimote_shifts_ | remember_nunchuk_shifts_; ui_->combo->setText(config_->GetReadableWiiremoteSequence(buttons)); } else { remember_wiimote_shifts_ = 0; @@ -90,15 +89,13 @@ void WiimoteShortcutGrabber::RememberSwingChecked(bool checked) { } } - -void WiimoteShortcutGrabber::DbusWiimoteGeneralButtons(uint id, qulonglong value) { +void WiimoteShortcutGrabber::DbusWiimoteGeneralButtons(uint id, + qulonglong value) { if (wiimotedev_device_ != id) return; - quint64 buttons = value & ~( - WIIMOTE_TILT_MASK | - NUNCHUK_TILT_MASK | - WIIMOTE_BTN_SHIFT_SHAKE | - NUNCHUK_BTN_SHIFT_SHAKE); + quint64 buttons = + value & ~(WIIMOTE_TILT_MASK | NUNCHUK_TILT_MASK | + WIIMOTE_BTN_SHIFT_SHAKE | NUNCHUK_BTN_SHIFT_SHAKE); if (ui_->remember_shifts->isChecked()) { if (!(buttons & WIIMOTE_SHIFT_MASK)) buttons |= remember_wiimote_shifts_; @@ -114,7 +111,8 @@ void WiimoteShortcutGrabber::DbusWiimoteGeneralButtons(uint id, qulonglong value if (buttons) line_.start(); ui_->keep_label->setVisible(buttons); - ui_->keep_label->setText(QString(tr("Keep buttons for %1 seconds...")).arg(QString::number(line_.startFrame()))); + ui_->keep_label->setText(QString(tr("Keep buttons for %1 seconds...")) + .arg(QString::number(line_.startFrame()))); ui_->combo->setText(config_->GetReadableWiiremoteSequence(buttons)); wiimotedev_buttons_ = buttons; diff --git a/src/wiimotedev/wiimoteshortcutgrabber.h b/src/wiimotedev/wiimoteshortcutgrabber.h index d02c9fc8e..853573987 100644 --- a/src/wiimotedev/wiimoteshortcutgrabber.h +++ b/src/wiimotedev/wiimoteshortcutgrabber.h @@ -28,20 +28,19 @@ class Ui_WiimoteShortcutGrabber; - class WiimoteShortcutGrabber : public QDialog { Q_OBJECT -public: + public: WiimoteShortcutGrabber(quint32 action, quint32 device, WiimoteSettingsPage* parent); ~WiimoteShortcutGrabber(); -private slots: + private slots: void DbusWiimoteGeneralButtons(uint id, qulonglong value); void RememberSwingChecked(bool checked); void Timeout(int); -private: + private: QTimeLine line_; quint32 pref_action_; @@ -56,7 +55,6 @@ private: signals: void AddShortcut(quint64 buttons, quint32 action); - }; -#endif // WIIMOTESHORTCUTGRABBER_H +#endif // WIIMOTESHORTCUTGRABBER_H