on ec95238 help sign in
unity8/plugins/Unity/Launcher/backend/launcherbackend.cpp
584 lines 18 kB history raw
1/*
2 * Copyright (C) 2013 Canonical, Ltd.
3 *
4 * Authors:
5 * Michael Terry <michael.terry@canonical.com>
6 * Michael Zanetti <michael.zanetti@canonical.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; version 3.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
21#include "AccountsServiceDBusAdaptor.h"
22#include "launcherbackend.h"
24#include <QDir>
25#include <QDBusArgument>
26#include <QFileInfo>
27#include <QGSettings>
28#include <QDebug>
29#include <QStandardPaths>
31class LauncherBackendItem
33public:
34 QString desktopFile;
35 QString displayName;
36 QString icon;
37 int count;
38 bool countVisible;
39};
41LauncherBackend::LauncherBackend(bool greeterMode, QObject *parent):
42 QDBusVirtualObject(parent),
43 m_greeterMode(greeterMode),
44 m_accounts(nullptr)
46#ifndef LAUNCHER_TESTING
47 m_accounts = new AccountsServiceDBusAdaptor(this);
48 connect(m_accounts, SIGNAL(propertiesChanged(QString, QString, QStringList)),
49 this, SLOT(accountsListChanged(QString, QString, QStringList)));
50#endif
51 m_user = qgetenv("USER");
52 syncFromAccounts();
54 /* Set up ourselves on DBus */
55 QDBusConnection con = QDBusConnection::sessionBus();
56 if (!con.registerService("com.canonical.Unity.Launcher")) {
57 qDebug() << "Unable to register launcher name";
58 }
59 if (!con.registerVirtualObject("/com/canonical/Unity/Launcher", this, QDBusConnection::VirtualObjectRegisterOption::SubPath)) {
60 qDebug() << "Unable to register launcher object";
61 }
64LauncherBackend::~LauncherBackend()
66 /* Remove oursevles from DBus */
67 QDBusConnection con = QDBusConnection::sessionBus();
68 con.unregisterService("com.canonical.Unity.Launcher");
69 con.unregisterObject("/com/canonical/Unity/Launcher");
71 /* Clear data */
72 m_storedApps.clear();
74 Q_FOREACH(LauncherBackendItem *item, m_itemCache) {
75 delete item;
76 }
77 m_itemCache.clear();
80QStringList LauncherBackend::storedApplications() const
82 return m_storedApps;
85void LauncherBackend::setStoredApplications(const QStringList &appIds)
87 if (appIds.count() < m_storedApps.count()) {
88 Q_FOREACH(const QString &appId, m_storedApps) {
89 if (!appIds.contains(appId)) {
90 delete m_itemCache.take(appId);
91 }
92 }
93 }
94 m_storedApps = appIds;
95 Q_FOREACH(const QString &appId, appIds) {
96 if (!m_itemCache.contains(appId)) {
97 QString df = findDesktopFile(appId);
98 if (!df.isEmpty()) {
99 LauncherBackendItem *item = parseDesktopFile(df);
100 m_itemCache.insert(appId, item);
101 } else {
102 // Cannot find any data for that app... ignoring it.
103 qWarning() << "cannot find desktop file for" << appId << ". discarding app.";
104 m_storedApps.removeAll(appId);
105 }
106 }
107 }
108 syncToAccounts();
111QString LauncherBackend::desktopFile(const QString &appId) const
113 LauncherBackendItem *item = m_itemCache.value(appId, nullptr);
114 if (item) {
115 return item->desktopFile;
116 }
118 return findDesktopFile(appId);
121QString LauncherBackend::displayName(const QString &appId) const
123 LauncherBackendItem *item = m_itemCache.value(appId, nullptr);
124 if (item) {
125 return item->displayName;
126 }
128 QString df = findDesktopFile(appId);
129 if (!df.isEmpty()) {
130 LauncherBackendItem *item = parseDesktopFile(df);
131 m_itemCache.insert(appId, item);
132 return item->displayName;
133 }
135 return QString();
138QString LauncherBackend::icon(const QString &appId) const
140 QString iconName;
141 LauncherBackendItem *item = getItem(appId);
142 if (item) {
143 iconName = item->icon;
144 }
146 return iconName;
149QList<QuickListEntry> LauncherBackend::quickList(const QString &appId) const
151 // TODO: Get static (from .desktop file) and dynamic (from the app itself)
152 // entries and return them here. Frontend related entries (like "Pin to launcher")
153 // don't matter here. This is just the backend part.
154 // TODO: emit quickListChanged() when the dynamic part changes
155 Q_UNUSED(appId)
156 return QList<QuickListEntry>();
159int LauncherBackend::progress(const QString &appId) const
161 // TODO: Return value for progress emblem.
162 // TODO: emit progressChanged() when this value changes.
163 Q_UNUSED(appId)
164 return -1;
167int LauncherBackend::count(const QString &appId) const
169 int count = -1;
170 LauncherBackendItem *item = getItem(appId);
172 if (item) {
173 if (item->countVisible) {
174 count = item->count;
175 }
176 }
178 return count;
181void LauncherBackend::setCount(const QString &appId, int count) const
183 LauncherBackendItem *item = getItem(appId);
185 bool emitchange = false;
186 if (item) {
187 emitchange = (item->count != count);
188 item->count = count;
189 }
191 if (emitchange) {
192 /* TODO: This needs to use the accessor to handle the visibility
193 correctly, but when we have the two properties we can just use
194 the local value */
195 Q_EMIT countChanged(appId, this->count(appId));
196 QVariant vcount(item->count);
197 emitPropChangedDbus(appId, "count", vcount);
198 }
201bool LauncherBackend::countVisible(const QString &appId) const
203 bool visible = false;
204 LauncherBackendItem *item = getItem(appId);
206 if (item) {
207 visible = item->countVisible;
208 }
210 return visible;
213void LauncherBackend::setCountVisible(const QString &appId, bool visible) const
215 LauncherBackendItem *item = getItem(appId);
217 bool emitchange = false;
218 if (item) {
219 emitchange = (item->countVisible != visible);
220 item->countVisible = visible;
221 } else {
222 qDebug() << "Unable to find:" << appId;
223 }
225 if (emitchange) {
226 /* TODO: Because we're using visible in determining the
227 count we need to emit a count changed as well */
228 Q_EMIT countChanged(appId, this->count(appId));
229 Q_EMIT countVisibleChanged(appId, item->countVisible);
230 QVariant vCountVisible(item->countVisible);
231 emitPropChangedDbus(appId, "countVisible", vCountVisible);
232 }
235void LauncherBackend::setUser(const QString &username)
237 if (m_greeterMode && m_user != username) {
238 m_user = username;
239 syncFromAccounts();
240 }
243void LauncherBackend::triggerQuickListAction(const QString &appId, const QString &quickListId)
245 // TODO: execute the given quicklist action
246 Q_UNUSED(appId)
247 Q_UNUSED(quickListId)
250void LauncherBackend::accountsListChanged(const QString &user, const QString &interface, const QStringList &changed)
252 if (m_greeterMode && user == m_user &&
253 interface == "com.canonical.unity.AccountsService" &&
254 changed.contains("launcher-items")) {
255 syncFromAccounts();
256 }
259void LauncherBackend::syncFromAccounts()
261 QList<QVariantMap> apps;
262 bool defaults = true;
264 m_storedApps.clear();
266 if (m_accounts && !m_user.isEmpty()) {
267 QVariant variant = m_accounts->getUserProperty(m_user, "com.canonical.unity.AccountsService", "launcher-items");
268 if (variant.isValid() && variant.canConvert<QDBusArgument>()) {
269 apps = qdbus_cast<QList<QVariantMap>>(variant.value<QDBusArgument>());
270 defaults = isDefaultsItem(apps);
271 }
272 }
274 if (m_accounts && defaults) { // Checking accounts as it'll be null when !useStorage
275 QGSettings gSettings("com.canonical.Unity.Launcher", "/com/canonical/unity/launcher/");
276 Q_FOREACH(const QString &entry, gSettings.get("favorites").toStringList()) {
277 if (entry.startsWith("application://")) {
278 QString appId = entry;
279 // Transform "application://foobar.desktop" to "foobar"
280 appId.remove("application://");
281 if (appId.endsWith(".desktop")) {
282 appId.chop(8);
283 }
284 QString df = findDesktopFile(appId);
286 if (!df.isEmpty()) {
287 m_storedApps << appId;
289 if (!m_itemCache.contains(appId)) {
290 m_itemCache.insert(appId, parseDesktopFile(df));
291 }
292 }
293 }
294 }
295 } else {
296 for (const QVariant &app: apps) {
297 loadFromVariant(app.toMap());
298 }
299 }
301 Q_EMIT refreshApplications();
304void LauncherBackend::syncToAccounts()
306 if (m_accounts && !m_user.isEmpty()) {
307 QList<QVariantMap> items;
309 Q_FOREACH(const QString &appId, m_storedApps) {
310 items << itemToVariant(appId);
311 }
313 m_accounts->setUserProperty(m_user, "com.canonical.unity.AccountsService", "launcher-items", QVariant::fromValue(items));
314 }
317QString LauncherBackend::findDesktopFile(const QString &appId) const
319 int dashPos = -1;
320 QString helper = appId;
322 QStringList searchDirs = QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation);
323#ifdef LAUNCHER_TESTING
324 searchDirs << "";
325#endif
327 do {
328 if (dashPos != -1) {
329 helper = helper.replace(dashPos, 1, '/');
330 }
332 Q_FOREACH(const QString &searchDir, searchDirs) {
333 QFileInfo fileInfo(QDir(searchDir), helper + ".desktop");
334 if (fileInfo.exists()) {
335 return fileInfo.absoluteFilePath();
336 }
337 }
339 dashPos = helper.indexOf("-");
340 } while (dashPos != -1);
342 return QString();
345LauncherBackendItem* LauncherBackend::parseDesktopFile(const QString &desktopFile) const
347 QSettings settings(desktopFile, QSettings::IniFormat);
349 LauncherBackendItem* item = new LauncherBackendItem();
350 item->desktopFile = desktopFile;
351 item->displayName = settings.value("Desktop Entry/Name").toString();
353 QString iconString = settings.value("Desktop Entry/Icon").toString();
354 QString pathString = settings.value("Desktop Entry/Path").toString();
355 if (QFileInfo(iconString).exists()) {
356 item->icon = QFileInfo(iconString).absoluteFilePath();
357 } else if (QFileInfo(pathString + '/' + iconString).exists()) {
358 item->icon = pathString + '/' + iconString;
359 } else {
360 item->icon = "image://theme/" + iconString;
361 }
363 /* TODO: These should be looked up in a cache somewhere */
364 item->count = 0;
365 item->countVisible = false;
367 return item;
370/* Gets an item, and tries to create a new one if we need it to */
371LauncherBackendItem* LauncherBackend::getItem(const QString &appId) const
373 LauncherBackendItem *item = m_itemCache.value(appId, nullptr);
374 if (!item) {
375 QString df = findDesktopFile(appId);
376 if (!df.isEmpty()) {
377 item = parseDesktopFile(df);
378 if (item) {
379 m_itemCache[appId] = item;
380 } else {
381 qWarning() << "Unable to parse desktop file for" << appId << "path" << df;
382 }
383 } else {
384 qDebug() << "Unable to find desktop file for:" << appId;
385 }
386 }
388 if (!item)
389 qWarning() << "Unable to find item for: " << appId;
391 return item;
394void LauncherBackend::loadFromVariant(const QVariantMap &details)
396 if (!details.contains("id")) {
397 return;
398 }
399 QString appId = details.value("id").toString();
401 LauncherBackendItem *item = m_itemCache.value(appId, nullptr);
402 if (item) {
403 delete item;
404 }
406 item = new LauncherBackendItem();
408 item->desktopFile = details.value("desktopFile").toString();
409 item->displayName = details.value("name").toString();
410 item->icon = details.value("icon").toString();
411 item->count = details.value("count").toInt();
412 item->countVisible = details.value("countVisible").toBool();
414 m_itemCache.insert(appId, item);
415 m_storedApps.append(appId);
418QVariantMap LauncherBackend::itemToVariant(const QString &appId) const
420 LauncherBackendItem *item = m_itemCache.value(appId);
421 QVariantMap details;
422 details.insert("id", appId);
423 details.insert("name", item->displayName);
424 details.insert("icon", item->icon);
425 details.insert("desktopFile", item->desktopFile);
426 details.insert("count", item->count);
427 details.insert("countVisible", item->countVisible);
428 return details;
431bool LauncherBackend::isDefaultsItem(const QList<QVariantMap> &apps) const
433 // To differentiate between an empty list and a list that hasn't been set
434 // yet (and should thus be populated with the defaults), we use a special
435 // list of one item with the 'defaults' field set to true.
436 return (apps.size() == 1 && apps[0].value("defaults").toBool());
439bool LauncherBackend::handleMessage(const QDBusMessage& message, const QDBusConnection& connection)
441 /* Check to make sure we're getting properties on our interface */
442 if (message.type() != QDBusMessage::MessageType::MethodCallMessage) {
443 return false;
444 }
445 if (message.interface() != "org.freedesktop.DBus.Properties") {
446 return false;
447 }
448 if (message.arguments()[0].toString() != "com.canonical.Unity.Launcher.Item") {
449 return false;
450 }
452 /* Break down the path to just the app id */
453 QString pathtemp = message.path();
454 if (!pathtemp.startsWith("/com/canonical/Unity/Launcher/")) {
455 return false;
456 }
457 pathtemp.remove("/com/canonical/Unity/Launcher/");
458 if (pathtemp.indexOf('/') >= 0) {
459 return false;
460 }
462 /* Find ourselves an appid */
463 QString appid = decodeAppId(pathtemp);
464 QVariantList retval;
466 if (message.member() == "Get") {
467 if (message.arguments()[1].toString() == "count") {
468 retval.append(QVariant::fromValue(QDBusVariant(this->count(appid))));
469 } else if (message.arguments()[1].toString() == "countVisible") {
470 retval.append(QVariant::fromValue(QDBusVariant(this->countVisible(appid))));
471 }
472 } else if (message.member() == "Set") {
473 if (message.arguments()[1].toString() == "count") {
474 this->setCount(appid, message.arguments()[2].value<QDBusVariant>().variant().toInt());
475 } else if (message.arguments()[1].toString() == "countVisible") {
476 this->setCountVisible(appid, message.arguments()[2].value<QDBusVariant>().variant().toBool());
477 }
478 } else if (message.member() == "GetAll") {
479 retval.append(this->itemToVariant(appid));
480 } else {
481 return false;
482 }
484 QDBusMessage reply = message.createReply(retval);
485 return connection.send(reply);
488QString LauncherBackend::introspect(const QString &path) const
490 /* This case we should just list the nodes */
491 if (path == "/com/canonical/Unity/Launcher/" || path == "/com/canonical/Unity/Launcher") {
492 QString nodes;
494 Q_FOREACH(const QString &appId, m_itemCache.keys()) {
495 nodes.append("<node name=\"");
496 nodes.append(encodeAppId(appId));
497 nodes.append("\"/>\n");
498 }
500 return nodes;
501 }
503 /* Should not happen, but let's handle it */
504 if (!path.startsWith("/com/canonical/Unity/Launcher")) {
505 return "";
506 }
508 /* Now we should be looking at a node */
509 QString nodeiface =
510 "<interface name=\"com.canonical.Unity.Launcher.Item\">"
511 "<property name=\"count\" type=\"i\" access=\"readwrite\" />"
512 "<property name=\"countVisible\" type=\"b\" access=\"readwrite\" />"
513 "</interface>";
514 return nodeiface;
517QString LauncherBackend::decodeAppId(const QString& path)
519 QByteArray bytes = path.toUtf8();
520 QByteArray decoded;
522 for (int i = 0; i < bytes.size(); ++i) {
523 char chr = bytes.at(i);
525 if (chr == '_') {
526 QString number;
527 number.append(bytes.at(i+1));
528 number.append(bytes.at(i+2));
530 bool okay;
531 char newchar = number.toUInt(&okay, 16);
532 if (okay)
533 decoded.append(newchar);
535 i += 2;
536 } else {
537 decoded.append(chr);
538 }
539 }
541 return QString::fromUtf8(decoded);
544QString LauncherBackend::encodeAppId(const QString& appId)
546 QByteArray bytes = appId.toUtf8();
547 QString encoded;
549 for (int i = 0; i < bytes.size(); ++i) {
550 uchar chr = bytes.at(i);
552 if ((chr >= 'a' && chr <= 'z') ||
553 (chr >= 'A' && chr <= 'Z') ||
554 (chr >= '0' && chr <= '9'&& i != 0)) {
555 encoded.append(chr);
556 } else {
557 QString hexval = QString("_%1").arg(chr, 2, 16, QChar('0'));
558 encoded.append(hexval.toUpper());
559 }
560 }
562 return encoded;
565void LauncherBackend::emitPropChangedDbus(const QString& appId, const QString& property, QVariant &value) const
567 QString path("/com/canonical/Unity/Launcher/");
568 path.append(encodeAppId(appId));
570 QDBusMessage message = QDBusMessage::createSignal(path, "org.freedesktop.DBus.Properties", "PropertiesChanged");
572 QList<QVariant> arguments;
573 QVariantHash changedprops;
574 changedprops[property] = QVariant::fromValue(QDBusVariant(value));
575 QVariantList deletedprops;
577 arguments.append(changedprops);
578 arguments.append(deletedprops);
580 message.setArguments(arguments);
582 QDBusConnection con = QDBusConnection::sessionBus();
583 con.send(message);