on xenial help sign in
Implementation of albumart image provider for audio content.

Approved by Michal Hruby, Albert Astals Cid.

commit11b8d32f62e66dd2348e1f6f1a829f93ab9f7782 authorPawel Stolowski <pawel.stolowski@canonical.com> dateWed 9 Oct 2013, 22:40 (13 years ago) parente878ba0f780fdb
14 files changed+672−8
debian/control+2 plugins/Unity/categoryresults.cpp+2−1 plugins/Unity/iconutils.cpp+24−3 plugins/Unity/iconutils.h+2−1 plugins/Unity/preview.cpp+1−1 plugins/Utils/CMakeLists.txt+12−1 plugins/Utils/albumartprovider.cpp+231 plugins/Utils/albumartprovider.h+56 plugins/Utils/mediaartcache.cpp+178 plugins/Utils/mediaartcache.h+54 plugins/Utils/plugin.cpp+20−1 plugins/Utils/plugin.h+1 tests/plugins/Unity/resultstest.cpp+87 tests/plugins/Unity/resultstest.h+2
debian/control+2
@@ -26,6 +26,7 @@ Build-Depends: cmake,
2626 libupstart-dev,
2727 libusermetricsoutput1-dev,
2828 libxcb1-dev,
29+ libglib2.0-dev,
2930 pkg-config,
3031 python:any (>= 2.7),
3132 python-setuptools,
@@ -41,6 +42,7 @@ Build-Depends: cmake,
4142 qtdeclarative5-test-plugin,
4243 qtdeclarative5-ubuntu-ui-toolkit-plugin,
4344 qtdeclarative5-xmllistmodel-plugin,
45+ libqt5xmlpatterns5-dev,
4446 ttf-ubuntu-font-family,
4547Standards-Version: 3.9.4
4648Homepage: http://launchpad.net/unity
plugins/Unity/categoryresults.cpp+2−1
@@ -81,8 +81,9 @@ CategoryResults::data(const QModelIndex& index, int role) const
8181 case RoleIconHint: {
8282 QString giconString(DeeListModel::data(index, ResultsColumn::ICON_HINT).toString());
8383 if (giconString.isEmpty()) {
84+ QString mimetype(DeeListModel::data(index, ResultsColumn::MIMETYPE).toString());
8485 QString uri(DeeListModel::data(index, ResultsColumn::URI).toString());
85− QString thumbnailerUri(uriToThumbnailerProviderString(uri));
86+ QString thumbnailerUri(uriToThumbnailerProviderString(uri, mimetype, DeeListModel::data(index, ResultsColumn::METADATA).toHash()));
8687 if (!thumbnailerUri.isNull()) {
8788 return QVariant::fromValue(thumbnailerUri);
8889 }
plugins/Unity/iconutils.cpp+24−3
@@ -25,6 +25,7 @@
2525
2626#define BASE_THEME_ICON_URI "image://theme/"
2727#define BASE_THUMBNAILER_URI "image://thumbnailer/"
28+#define BASE_ALBUMART_URI "image://albumart/"
2829
2930QString gIconToDeclarativeImageProviderString(QString const &giconString)
3031{
@@ -91,11 +92,31 @@ QString gIconToDeclarativeImageProviderString(QString const &giconString)
9192 return result;
9293}
9394
94−QString uriToThumbnailerProviderString(QString const &uri)
95+QString uriToThumbnailerProviderString(QString const &uri, QString const &mimetype, QVariantHash const &metadata)
9596{
9697 if (uri.startsWith(QLatin1String("file:///"))) {
97− QString thumbnailerUri(BASE_THUMBNAILER_URI);
98− thumbnailerUri.append(uri.midRef(7));
98+ bool isAudio = mimetype.startsWith(QLatin1String("audio/"));
99+ QString thumbnailerUri;
100+ if (isAudio) {
101+ thumbnailerUri = BASE_ALBUMART_URI;
102+ if (metadata.contains("content")) {
103+ QVariantHash contentHash = metadata["content"].toHash();
104+ if (contentHash.contains("content")) { // nested content in Home?
105+ contentHash = contentHash["content"].toHash();
106+ }
107+ if (contentHash.contains("album") &&
108+ contentHash.contains("artist")) {
109+ const QString album = contentHash["album"].toString();
110+ const QString artist = contentHash["artist"].toString();
111+ thumbnailerUri.append(QUrl::toPercentEncoding(artist));
112+ thumbnailerUri.append("/");
113+ thumbnailerUri.append(QUrl::toPercentEncoding(album));
114+ }
115+ }
116+ } else {
117+ thumbnailerUri = BASE_THUMBNAILER_URI;
118+ thumbnailerUri.append(uri.midRef(7));
119+ }
99120 return thumbnailerUri;
100121 }
101122
plugins/Unity/iconutils.h+2−1
@@ -21,8 +21,9 @@
2121#define ICONUTILS_H
2222
2323#include <QString>
24+#include <QVariant>
2425
2526QString gIconToDeclarativeImageProviderString(QString const &giconString);
26−QString uriToThumbnailerProviderString(QString const &uri);
27+QString uriToThumbnailerProviderString(QString const &uri, QString const &mimetype, QVariantHash const &metadata);
2728
2829#endif
plugins/Unity/preview.cpp+1−1
@@ -113,7 +113,7 @@ QString Preview::image() const
113113 return result;
114114 } else {
115115 QString sourceMedia(QString::fromStdString(m_unityPreview->image_source_uri()));
116− QString thumbnailUri(uriToThumbnailerProviderString(sourceMedia));
116+ QString thumbnailUri(uriToThumbnailerProviderString(sourceMedia, m_result->mimeType(), m_result->metadata().toHash()));
117117 if (!thumbnailUri.isNull()) return thumbnailUri;
118118 }
119119 } else {
plugins/Utils/CMakeLists.txt+12−1
@@ -1,11 +1,19 @@
1+# Dependencies
2+include(FindPkgConfig)
3+
4+pkg_search_module(GIO REQUIRED gio-2.0)
5+
16include_directories(
27 ${CMAKE_CURRENT_SOURCE_DIR}
38 ${CMAKE_CURRENT_BINARY_DIR}
49 ${Qt5Gui_PRIVATE_INCLUDE_DIRS}
10+ ${GIO_INCLUDE_DIRS}
511)
612
713set(QMLPLUGIN_SRC
14+ albumartprovider.cpp
815 applicationpaths.h
16+ mediaartcache.cpp
917 qlimitproxymodelqml.cpp
1018 qsortfilterproxymodelqml.cpp
1119 ubuntuwindow.cpp
@@ -16,13 +24,16 @@ set(QMLPLUGIN_SRC
1624add_library(Utils-qml SHARED
1725 ${QMLPLUGIN_SRC}
1826 )
27+
28+target_link_libraries(Utils-qml ${GIO_LDFLAGS})
29+
1930# Because this is an internal support library, we want
2031# to expose all symbols in it. Consider changing this
2132# either to a static library or just using the
2233# files directly in targets.
2334set_target_properties(Utils-qml PROPERTIES COMPILE_FLAGS -fvisibility=default)
2435
25−qt5_use_modules(Utils-qml Qml Quick DBus)
36+qt5_use_modules(Utils-qml Qml Quick DBus Network XmlPatterns)
2637
2738# export the qmldir qmltypes and plugin files
2839export_qmlfiles(Utils Utils)
plugins/Utils/albumartprovider.cppnew file+231
@@ -0,0 +1,231 @@
1+/*
2+ * Copyright 2013 Canonical Ltd.
3+ *
4+ * This program is free software; you can redistribute it and/or modify
5+ * it under the terms of the GNU Lesser General Public License as published by
6+ * the Free Software Foundation; version 3.
7+ *
8+ * This program is distributed in the hope that it will be useful,
9+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11+ * GNU Lesser General Public License for more details.
12+ *
13+ * You should have received a copy of the GNU Lesser General Public License
14+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
15+ *
16+ * Authors: Jussi Pakkanen <jussi.pakkanen@canonical.com>
17+ * Pawel Stolowski <pawel.stolowski@canonical.com>
18+*/
19+
20+#include "albumartprovider.h"
21+#include <QString>
22+#include <QNetworkAccessManager>
23+#include <QEventLoop>
24+#include <QNetworkRequest>
25+#include <QNetworkReply>
26+#include <QXmlQuery>
27+#include <QTemporaryFile>
28+#include <QBuffer>
29+#include <QDebug>
30+#include <QFile>
31+#include <QStringList>
32+#include <QByteArray>
33+#include <QImage>
34+#include <QUrl>
35+
36+using namespace std;
37+
38+const std::string AlbumArtProvider::DEFAULT_ALBUM_ART = "/usr/share/unity/icons/album_missing.png";
39+const std::string AlbumArtProvider::UNITY_LENS_SCHEMA = "com.canonical.Unity.Lenses";
40+
41+AlbumArtProvider::AlbumArtProvider()
42+ : QQuickImageProvider(QQmlImageProviderBase::Image, QQmlImageProviderBase::ForceAsynchronousImageLoading),
43+ m_settings(nullptr)
44+{
45+ auto schemas = g_settings_list_schemas();
46+ if (schemas) {
47+ for (int i = 0; schemas[i]; i++) {
48+ if (g_strcmp0(schemas[i], UNITY_LENS_SCHEMA.c_str()) == 0) {
49+ m_settings = g_settings_new(UNITY_LENS_SCHEMA.c_str());
50+ break;
51+ }
52+ }
53+ }
54+ if (m_settings == nullptr) {
55+ qWarning() << "Missing" << QString::fromStdString(UNITY_LENS_SCHEMA) << "schema";
56+ }
57+}
58+
59+AlbumArtProvider::~AlbumArtProvider()
60+{
61+ if (m_settings)
62+ g_object_unref(m_settings);
63+}
64+
65+std::string AlbumArtProvider::get_lastfm_url(const albuminfo &ai) {
66+ QString artist = QString::fromStdString(ai.artist);
67+ QString album = QString::fromStdString(ai.album);
68+
69+ /// @todo: this is the old API which will probably get axed at some point in the future
70+ /// The new 2.0 API requires an API key, but supports JSON output, etc, so switching
71+ /// to it should be done ASAP.
72+ QString request = QString("http://ws.audioscrobbler.com/1.0/album/%1/%2/info.xml").arg(artist)
73+ .arg(album)
74+ .toHtmlEscaped();
75+ QScopedPointer<QNetworkAccessManager> am(new QNetworkAccessManager);
76+ QNetworkReply *reply = am->get(QNetworkRequest(QUrl(request)));
77+ QEventLoop loop;
78+ QObject::connect(am.data(), &QNetworkAccessManager::finished, &loop, &QEventLoop::quit);
79+ loop.exec();
80+
81+ if (reply->error() != QNetworkReply::NoError) {
82+ qWarning() << "Error getting the XML:" << reply->errorString();
83+ return "";
84+ }
85+
86+ QXmlQuery query;
87+ QBuffer tmp;
88+ tmp.setData(reply->readAll());
89+ tmp.open(QIODevice::ReadOnly);
90+ query.bindVariable("reply", &tmp);
91+ query.setQuery("doc($reply)/album/coverart/large[1]/text()");
92+ QString image;
93+ query.evaluateTo(&image);
94+ image = image.trimmed();
95+
96+ // return empty if last.fm tries to offer their default
97+ // fallback artwork
98+ if (image.contains("catalogue/noimage")) {
99+ return "";
100+ }
101+
102+ return image.toStdString();
103+}
104+
105+bool AlbumArtProvider::download_and_store(const std::string &image_url, const std::string &output_file) {
106+ QString url = QString::fromStdString(image_url);
107+ QString fileName = QString::fromStdString(output_file);
108+
109+ QScopedPointer<QNetworkAccessManager> am(new QNetworkAccessManager);
110+ QNetworkReply *reply = am->get(QNetworkRequest(QUrl(url)));
111+ QEventLoop loop;
112+ QObject::connect(am.data(), &QNetworkAccessManager::finished, &loop, &QEventLoop::quit);
113+ loop.exec();
114+
115+ if (reply->error() != QNetworkReply::NoError) {
116+ qWarning() << "Error getting the image:" << reply->errorString();
117+ return false;
118+ }
119+
120+ QFile file(fileName);
121+ if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
122+ qWarning() << "Could not open file for writing:" << file.errorString();
123+ return false;
124+ }
125+ if (file.write(reply->readAll()) == -1){
126+ qWarning() << "Could not write the image:" << file.error();
127+ return false;
128+ }
129+
130+ return true;
131+}
132+
133+void AlbumArtProvider::fix_format(const std::string &fname) {
134+ // MediaArtSpec requires jpg. Convert to it if necessary.
135+ FILE *f = fopen(fname.c_str(), "r");
136+ if(!f)
137+ return;
138+ unsigned char buf[2];
139+ fread(buf, 1, 2, f);
140+ fclose(f);
141+ if(buf[0] == 0xff && buf[1] == 0xd8) {
142+ return;
143+ }
144+ QImage im(fname.c_str());
145+ im.save(fname.c_str(), "JPEG");
146+}
147+
148+std::string AlbumArtProvider::get_image(const std::string &artist, const std::string &album) {
149+ albuminfo info;
150+
151+ info.artist = artist;
152+ info.album = album;
153+
154+ if(info.album.empty() || info.artist.empty()) {
155+ return DEFAULT_ALBUM_ART;
156+ }
157+ if(cache.has_art(info.artist, info.album)) {
158+ // Image may have expired from cache between these two lines.
159+ // It might expire before we return. C'est la vie.
160+ return cache.get_art_file(info.artist, info.album);
161+ }
162+
163+ if (m_settings != nullptr && g_strcmp0(g_settings_get_string(m_settings, "remote-content-search"), "all") !=0) {
164+ qDebug() << "Remote content disabled";
165+ return DEFAULT_ALBUM_ART;
166+ }
167+
168+ std::string image_url = get_lastfm_url(info);
169+ if(image_url.empty()) {
170+ return DEFAULT_ALBUM_ART;
171+ }
172+ QTemporaryFile tempFile;
173+ tempFile.open();
174+ tempFile.setAutoRemove(true);
175+ QString fname = tempFile.fileName();
176+ std::string tmpname = fname.toUtf8().data();
177+
178+ if(!download_and_store(image_url, tmpname)) {
179+ return DEFAULT_ALBUM_ART;
180+ }
181+ fix_format(tmpname.c_str());
182+ QFile f(fname);
183+ if(!f.open(QIODevice::ReadWrite)) {
184+ return DEFAULT_ALBUM_ART;
185+ }
186+ QByteArray arr = f.readAll();
187+ f.close();
188+
189+ cache.add_art(info.artist, info.album, arr.data(), arr.size());
190+ try {
191+ std::string res = cache.get_art_file(info.artist, info.album);
192+ if(res.empty())
193+ return DEFAULT_ALBUM_ART;
194+ return res;
195+ } catch(...) {
196+ }
197+ return DEFAULT_ALBUM_ART;
198+}
199+
200+QImage AlbumArtProvider::requestImage(const QString &id, QSize *realSize, const QSize &requestedSize) {
201+ Q_UNUSED(requestedSize)
202+
203+ const QStringList parts = id.split("/");
204+ if (parts.size() != 2) {
205+ qWarning() << "Invalid albumart uri:" << id;
206+ return QImage(QString::fromStdString(DEFAULT_ALBUM_ART));
207+ }
208+ const std::string artist = QUrl::fromPercentEncoding(parts[0].toUtf8()).toStdString();
209+ const std::string album = QUrl::fromPercentEncoding(parts[1].toUtf8()).toStdString();
210+
211+ std::string tgt_path;
212+ try {
213+ tgt_path = get_image(artist, album);
214+ if(!tgt_path.empty()) {
215+ QString tgt(tgt_path.c_str());
216+ QImage image;
217+ image.load(tgt);
218+ // FIXME: Rescale to requested size preserving aspect.
219+ *realSize = image.size();
220+ return image;
221+ }
222+ } catch(std::exception &e) {
223+ qDebug() << "Album art loader failed: " << e.what();
224+ } catch(...) {
225+ qDebug() << "Unknown error when generating image.";
226+ }
227+
228+ QImage fallback(QString::fromStdString(DEFAULT_ALBUM_ART));
229+ *realSize = fallback.size();
230+ return fallback;
231+}
plugins/Utils/albumartprovider.hnew file+56
@@ -0,0 +1,56 @@
1+/*
2+ * Copyright 2013 Canonical Ltd.
3+ *
4+ * This program is free software; you can redistribute it and/or modify
5+ * it under the terms of the GNU Lesser General Public License as published by
6+ * the Free Software Foundation; version 3.
7+ *
8+ * This program is distributed in the hope that it will be useful,
9+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11+ * GNU Lesser General Public License for more details.
12+ *
13+ * You should have received a copy of the GNU Lesser General Public License
14+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
15+ *
16+ * Authors: Jussi Pakkanen <jussi.pakkanen@canonical.com>
17+*/
18+
19+#ifndef ALBUMART_PROVIDER_H_
20+#define ALBUMART_PROVIDER_H_
21+
22+#include <string>
23+#include <stdexcept>
24+#include <QQuickImageProvider>
25+#include <gio/gio.h>
26+
27+#include "mediaartcache.h"
28+
29+struct albuminfo {
30+ std::string artist;
31+ std::string album;
32+};
33+
34+class AlbumArtProvider : public QQuickImageProvider
35+{
36+public:
37+ AlbumArtProvider();
38+ ~AlbumArtProvider();
39+ QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize);
40+
41+ std::string get_image(const std::string &artist, const std::string &album);
42+
43+ const static std::string DEFAULT_ALBUM_ART;
44+ const static std::string UNITY_LENS_SCHEMA;
45+private:
46+ MediaArtCache cache;
47+ GSettings *m_settings;
48+
49+ void fix_format(const std::string &fname);
50+
51+ std::string get_lastfm_url(const albuminfo &ai);
52+
53+ bool download_and_store(const std::string &image_url, const std::string &output_file);
54+};
55+
56+#endif
plugins/Utils/mediaartcache.cppnew file+178
@@ -0,0 +1,178 @@
1+/*
2+ * This file is part of the Ubuntu TV Media Scanner
3+ * Copyright (C) 2012-2013 Canonical Ltd.
4+ *
5+ * This program is free software: you can redistribute it and/or modify
6+ * it under the terms of the GNU Lesser General Public License version 3 as
7+ * published by the Free Software Foundation.
8+ *
9+ * This program is distributed in the hope that it will be useful,
10+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
11+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+ * GNU Lesser General Public License for more details.
13+ *
14+ * You should have received a copy of the GNU Lesser General Public License
15+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
16+ *
17+ * Authored by: Jussi Pakkanen <jussi.pakkanen@canonical.com>
18+ */
19+
20+#include"mediaartcache.h"
21+
22+#include<dirent.h>
23+#include<sys/stat.h>
24+#include<fcntl.h>
25+#include<unistd.h>
26+#include<errno.h>
27+#include<stdio.h>
28+#include<string.h>
29+#include<stdlib.h>
30+#include<assert.h>
31+#include<utime.h>
32+
33+#include<glib.h>
34+
35+#include<vector>
36+#include<algorithm>
37+#include<stdexcept>
38+
39+using namespace std;
40+
41+static string md5(const string &str) {
42+ const unsigned char *buf = (const unsigned char *)str.c_str();
43+ char *normalized = g_utf8_normalize((const gchar*)buf, str.size(), G_NORMALIZE_ALL);
44+ string final;
45+ gchar *result;
46+
47+ if(normalized) {
48+ buf = (const unsigned char*)normalized;
49+ }
50+ gssize bytes = str.length();
51+
52+ result = g_compute_checksum_for_data(G_CHECKSUM_MD5, buf, bytes);
53+ final = result;
54+ g_free((gpointer)normalized);
55+ g_free(result);
56+ return final;
57+}
58+
59+MediaArtCache::MediaArtCache() {
60+ string xdg_base = g_get_user_cache_dir();
61+
62+ if (xdg_base == "") {
63+ string s("Could not determine cache dir.");
64+ throw runtime_error(s);
65+ }
66+ int ec = mkdir(xdg_base.c_str(), S_IRUSR | S_IWUSR | S_IXUSR);
67+ if (ec < 0 && errno != EEXIST) {
68+ string s("Could not create base dir.");
69+ throw runtime_error(s);
70+ }
71+ root_dir = xdg_base + "/media-art";
72+ ec = mkdir(root_dir.c_str(), S_IRUSR | S_IWUSR | S_IXUSR);
73+ if (ec < 0 && errno != EEXIST) {
74+ string s("Could not create cache dir.");
75+ throw runtime_error(s);
76+ }
77+}
78+
79+bool MediaArtCache::has_art(const std::string &artist, const std::string &album) const {
80+ string fname = get_art_file(artist, album);
81+ return access(fname.c_str(), R_OK) == 0;
82+}
83+
84+void MediaArtCache::add_art(const std::string &artist, const std::string &album,
85+ char *data, unsigned int datalen) {
86+ string abs_fname = get_full_filename(artist, album);
87+ GError *err = nullptr;
88+ if(!g_file_set_contents(abs_fname.c_str(), data, datalen, &err)) {
89+ string e("Could not write file ");
90+ e += abs_fname;
91+ e += ": ";
92+ e += err->message;
93+ g_error_free(err);
94+ throw runtime_error(e);
95+ }
96+}
97+
98+string MediaArtCache::get_art_file(const std::string &artist, const std::string &album) const {
99+ string abs_fname = get_full_filename(artist, album);
100+
101+ if (access(abs_fname.c_str(), R_OK) == 0) {
102+ utime(abs_fname.c_str(), nullptr); // update access times to current time
103+ return abs_fname;
104+ }
105+ return "";
106+}
107+
108+std::string MediaArtCache::get_full_filename(const std::string &artist, const std::string & album) const {
109+ return root_dir + "/" + compute_base_name(artist, album);
110+}
111+
112+
113+std::string MediaArtCache::compute_base_name(const std::string &artist, const std::string &album) const {
114+ string type = "album";
115+ string h1 = md5(artist);
116+ string h2 = md5(album);
117+ return type + "-" + h1 + "-" + h2 + ".jpg";
118+}
119+
120+
121+void MediaArtCache::clear() const {
122+ DIR *d = opendir(root_dir.c_str());
123+ if(!d) {
124+ string s = "Something went wrong.";
125+ throw runtime_error(s);
126+ }
127+ struct dirent *entry, *de;
128+ entry = (dirent*)malloc(sizeof(dirent) + NAME_MAX);
129+ while(readdir_r(d, entry, &de) == 0 && de) {
130+ string basename = entry->d_name;
131+ if (basename == "." || basename == "..")
132+ continue;
133+ string fname = root_dir + "/" + basename;
134+ if(remove(fname.c_str()) < 0) {
135+ // This is not really an error worth
136+ // halting everything for.
137+ fprintf(stderr, "Could not delete file %s: %s.\n", fname.c_str(),
138+ strerror(errno));
139+ }
140+ }
141+ free(entry);
142+ closedir(d);
143+}
144+
145+void MediaArtCache::prune() {
146+ vector<pair<double, string>> mtimes;
147+ DIR *d = opendir(root_dir.c_str());
148+ if(!d) {
149+ string s = "Something went wrong.";
150+ throw runtime_error(s);
151+ }
152+ struct dirent *entry, *de;
153+ entry = (dirent*)malloc(sizeof(dirent) + NAME_MAX);
154+ while(readdir_r(d, entry, &de) == 0 && de) {
155+ string basename = entry->d_name;
156+ if (basename == "." || basename == "..")
157+ continue;
158+ string fname = root_dir + "/" + basename;
159+ struct stat sbuf;
160+ if(stat(fname.c_str(), &sbuf) != 0) {
161+ continue;
162+ }
163+ // Use mtime because atime is not guaranteed to work if, for example
164+ // the filesystem is mounted with noatime or relatime.
165+ mtimes.push_back(make_pair(sbuf.st_mtim.tv_sec + sbuf.st_mtim.tv_nsec/1000000000.0, fname));
166+ }
167+ free(entry);
168+ closedir(d);
169+ if (mtimes.size() <= MAX_SIZE)
170+ return;
171+ sort(mtimes.begin(), mtimes.end());
172+ for(size_t i=0; i < mtimes.size()-MAX_SIZE; i++) {
173+ if(remove(mtimes[i].second.c_str()) < 0) {
174+ fprintf(stderr, "Could not remove file %s: %s.\n",
175+ mtimes[i].second.c_str(), strerror(errno));
176+ }
177+ }
178+}
plugins/Utils/mediaartcache.hnew file+54
@@ -0,0 +1,54 @@
1+/*
2+ * This file is part of the Ubuntu TV Media Scanner
3+ * Copyright (C) 2012-2013 Canonical Ltd.
4+ *
5+ * This program is free software: you can redistribute it and/or modify
6+ * it under the terms of the GNU Lesser General Public License version 3 as
7+ * published by the Free Software Foundation.
8+ *
9+ * This program is distributed in the hope that it will be useful,
10+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
11+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+ * GNU Lesser General Public License for more details.
13+ *
14+ * You should have received a copy of the GNU Lesser General Public License
15+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
16+ *
17+ * Authored by: Jussi Pakkanen <jussi.pakkanen@canonical.com>
18+ */
19+
20+#ifndef MEDIAARTCACHE_H
21+#define MEDIAARTCACHE_H
22+
23+#include<string>
24+
25+/*
26+ * A class to store thumbnails for files according to
27+ * https://wiki.gnome.org/MediaArtStorageSpec
28+ *
29+ * As this class deals mostly with the filesystem, all
30+ * errors are reported with runtime_error exceptions.
31+ */
32+
33+
34+class MediaArtCache {
35+private:
36+ std::string root_dir;
37+
38+ std::string compute_base_name(const std::string &artist, const std::string &album) const;
39+ std::string get_full_filename(const std::string &artist, const std::string & album) const;
40+
41+public:
42+ static const unsigned int MAX_SIZE = 200;
43+
44+ MediaArtCache();
45+ bool has_art(const std::string &artist, const std::string &album) const;
46+ void add_art(const std::string &artist, const std::string &album,
47+ char *data, unsigned int datalen);
48+ std::string get_art_file(const std::string &artist, const std::string &album) const;
49+ void clear() const;
50+ void prune();
51+ std::string get_cache_dir() const { return root_dir; }
52+};
53+
54+#endif
plugins/Utils/plugin.cpp+20−1
@@ -19,11 +19,12 @@
1919// Qt
2020#include <QtQml/qqml.h>
2121#include <QtQuick/QQuickWindow>
22−
22+#include <QDebug>
2323// self
2424#include "plugin.h"
2525
2626// local
27+#include "albumartprovider.h"
2728#include "applicationpaths.h"
2829#include "qlimitproxymodelqml.h"
2930#include "qsortfilterproxymodelqml.h"
@@ -46,3 +47,21 @@ void UtilsPlugin::registerTypes(const char *uri)
4647 qmlRegisterExtendedType<QQuickWindow, UbuntuWindow>(uri, 0, 1, "Window");
4748 qmlRegisterSingletonType<ApplicationPaths>(uri, 0, 1, "ApplicationPaths", applicationsPathsSingleton);
4849}
50+
51+void UtilsPlugin::initializeEngine(QQmlEngine *engine, const char *uri)
52+{
53+ QQmlExtensionPlugin::initializeEngine(engine, uri);
54+
55+ try
56+ {
57+ engine->addImageProvider(QLatin1String("albumart"), new AlbumArtProvider);
58+ }
59+ catch (const std::runtime_error &e)
60+ {
61+ qWarning() << "Failed to register image provider for albumart:" << e.what();
62+ }
63+ catch (...)
64+ {
65+ qWarning() << "Failed to register image provider for albumart (unknown error)";
66+ }
67+}
plugins/Utils/plugin.h+1
@@ -29,6 +29,7 @@ class UtilsPlugin : public QQmlExtensionPlugin
2929
3030public:
3131 void registerTypes(const char *uri);
32+ void initializeEngine(QQmlEngine *engine, const char *uri);
3233};
3334
3435#endif
tests/plugins/Unity/resultstest.cpp+87
@@ -19,6 +19,7 @@
1919
2020#include <QTest>
2121#include <dee.h>
22+#include <glib.h>
2223
2324#include "resultstest.h"
2425#include "categoryresults.h"
@@ -106,4 +107,90 @@ void ResultsTest::testIconColumn()
106107 QCOMPARE(transformedIcon, result);
107108}
108109
110+class GVariantWrapper
111+{
112+public:
113+ GVariantWrapper() : variant(NULL) {}
114+ GVariantWrapper(GVariant* v) {
115+ variant = v ? g_variant_ref_sink(v) : NULL;
116+ }
117+ GVariantWrapper(const GVariantWrapper& other) {
118+ variant = other.variant ? g_variant_ref(other.variant) : NULL;
119+ }
120+ ~GVariantWrapper() {
121+ if (variant) g_variant_unref(variant);
122+ }
123+
124+ GVariant* variant;
125+};
126+
127+Q_DECLARE_METATYPE(GVariantWrapper)
128+
129+void ResultsTest::testSpecialIcons_data()
130+{
131+ QTest::addColumn<QString>("uri");
132+ QTest::addColumn<GVariantWrapper>("metadata");
133+ QTest::addColumn<QString>("result");
134+
135+ GVariant *inner;
136+ GVariantBuilder builder, inner_builder;
137+
138+ g_variant_builder_init(&inner_builder, G_VARIANT_TYPE_VARDICT);
139+ g_variant_builder_add(&inner_builder, "{sv}", "artist", g_variant_new_string("U2"));
140+ g_variant_builder_add(&inner_builder, "{sv}", "album", g_variant_new_string("War"));
141+
142+ g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
143+ g_variant_builder_add(&builder, "{sv}", "content", g_variant_builder_end(&inner_builder));
144+
145+ QTest::newRow("simple") << "file:///foo.mp3" << GVariantWrapper(g_variant_builder_end(&builder)) << "image://albumart/U2/War";
146+
147+ g_variant_builder_init(&inner_builder, G_VARIANT_TYPE_VARDICT);
148+ g_variant_builder_add(&inner_builder, "{sv}", "artist", g_variant_new_string("U2"));
149+ g_variant_builder_add(&inner_builder, "{sv}", "album", g_variant_new_string("War/Joshua tree"));
150+ inner = g_variant_builder_end(&inner_builder);
151+
152+ g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
153+ g_variant_builder_add(&builder, "{sv}", "content", inner);
154+
155+ QTest::newRow("with-slash") << "file:///foo.mp3" << GVariantWrapper(g_variant_builder_end(&builder)) << "image://albumart/U2/War%2FJoshua%20tree";
156+
157+ g_variant_builder_init(&inner_builder, G_VARIANT_TYPE_VARDICT);
158+ g_variant_builder_add(&inner_builder, "{sv}", "artist", g_variant_new_string("U2"));
159+ g_variant_builder_add(&inner_builder, "{sv}", "album", g_variant_new_string("War"));
160+ inner = g_variant_builder_end(&inner_builder);
161+
162+ g_variant_builder_init(&inner_builder, G_VARIANT_TYPE_VARDICT);
163+ g_variant_builder_add(&inner_builder, "{sv}", "content", inner);
164+
165+ g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
166+ g_variant_builder_add(&builder, "{sv}", "content", g_variant_builder_end(&inner_builder));
167+
168+ QTest::newRow("nested") << "file:///foo.mp3" << GVariantWrapper(g_variant_builder_end(&builder)) << "image://albumart/U2/War";
169+}
170+
171+void ResultsTest::testSpecialIcons()
172+{
173+ QFETCH(QString, uri);
174+ QFETCH(GVariantWrapper, metadata);
175+ QFETCH(QString, result);
176+ auto deeModel = createBackendModel();
177+ dee_model_append (deeModel,
178+ uri.toLocal8Bit().constData(),
179+ "",
180+ 0,
181+ 0,
182+ "audio/mp3",
183+ "Test",
184+ "",
185+ uri.toLocal8Bit().constData(),
186+ metadata.variant);
187+
188+ CategoryResults* results = new CategoryResults(this);
189+ results->setModel(deeModel);
190+
191+ auto index = results->index(0, 0); // there's just one result
192+ auto transformedIcon = index.data(CategoryResults::Roles::RoleIconHint).toString();
193+ QCOMPARE(transformedIcon, result);
194+}
195+
109196QTEST_MAIN(ResultsTest)
tests/plugins/Unity/resultstest.h+2
@@ -30,6 +30,8 @@ class ResultsTest : public QObject
3030 void testAllColumns();
3131 void testIconColumn_data();
3232 void testIconColumn();
33+ void testSpecialIcons_data();
34+ void testSpecialIcons();
3335};
3436
3537#endif