on ac987a2 help sign in
unity8/plugins/Unity/Launcher/backend/launcherbackend.cpp
621 lines 19 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 displayName;
35 QString icon;
36 int count;
37 bool countVisible;
38};
40LauncherBackend::LauncherBackend(QObject *parent):
41 QDBusVirtualObject(parent),
42 m_accounts(nullptr)
44#ifndef LAUNCHER_TESTING
45 m_accounts = new AccountsServiceDBusAdaptor(this);
46#endif
47 m_user = qgetenv("USER");
48 syncFromAccounts();
50 /* Set up ourselves on DBus */
51 QDBusConnection con = QDBusConnection::sessionBus();
52 if (!con.registerService("com.canonical.Unity.Launcher")) {
53 qDebug() << "Unable to register launcher name";
54 }
55 if (!con.registerVirtualObject("/com/canonical/Unity/Launcher", this, QDBusConnection::VirtualObjectRegisterOption::SubPath)) {
56 qDebug() << "Unable to register launcher object";
57 }
60LauncherBackend::~LauncherBackend()
62 /* Remove oursevles from DBus */
63 QDBusConnection con = QDBusConnection::sessionBus();
64 con.unregisterService("com.canonical.Unity.Launcher");
65 con.unregisterObject("/com/canonical/Unity/Launcher");
67 /* Clear data */
68 m_storedApps.clear();
70 Q_FOREACH(LauncherBackendItem *item, m_itemCache) {
71 delete item;
72 }
73 m_itemCache.clear();
76QStringList LauncherBackend::storedApplications() const
78 return m_storedApps;
81void LauncherBackend::setStoredApplications(const QStringList &appIds)
83 if (appIds.count() < m_storedApps.count()) {
84 Q_FOREACH(const QString &appId, m_storedApps) {
85 if (!appIds.contains(appId)) {
86 delete m_itemCache.take(appId);
87 }
88 }
89 }
90 m_storedApps = appIds;
91 Q_FOREACH(const QString &appId, appIds) {
92 if (!m_itemCache.contains(appId)) {
93 QString df = findDesktopFile(appId);
94 if (!df.isEmpty()) {
95 LauncherBackendItem *item = parseDesktopFile(df);
96 m_itemCache.insert(appId, item);
97 } else {
98 // Cannot find any data for that app... ignoring it.
99 qWarning() << "cannot find desktop file for" << appId << ". discarding app.";
100 m_storedApps.removeAll(appId);
101 }
102 }
103 }
104 syncToAccounts();
107QString LauncherBackend::desktopFile(const QString &appId) const
109 return findDesktopFile(appId);
112QString LauncherBackend::displayName(const QString &appId) const
114 LauncherBackendItem *item = m_itemCache.value(appId, nullptr);
115 if (item) {
116 return item->displayName;
117 }
119 QString df = findDesktopFile(appId);
120 if (!df.isEmpty()) {
121 LauncherBackendItem *item = parseDesktopFile(df);
122 m_itemCache.insert(appId, item);
123 return item->displayName;
124 }
126 return QString();
129QString LauncherBackend::icon(const QString &appId) const
131 QString iconName;
132 LauncherBackendItem *item = getItem(appId);
133 if (item) {
134 iconName = item->icon;
135 }
137 return iconName;
140QList<QuickListEntry> LauncherBackend::quickList(const QString &appId) const
142 // TODO: Get static (from .desktop file) and dynamic (from the app itself)
143 // entries and return them here. Frontend related entries (like "Pin to launcher")
144 // don't matter here. This is just the backend part.
145 // TODO: emit quickListChanged() when the dynamic part changes
146 Q_UNUSED(appId)
147 return QList<QuickListEntry>();
150int LauncherBackend::progress(const QString &appId) const
152 // TODO: Return value for progress emblem.
153 // TODO: emit progressChanged() when this value changes.
154 Q_UNUSED(appId)
155 return -1;
158int LauncherBackend::count(const QString &appId) const
160 int count = -1;
161 LauncherBackendItem *item = getItem(appId);
163 if (item) {
164 if (item->countVisible) {
165 count = item->count;
166 }
167 }
169 return count;
172void LauncherBackend::setCount(const QString &appId, int count) const
174 LauncherBackendItem *item = getItem(appId);
176 bool emitchange = false;
177 if (item) {
178 emitchange = (item->count != count);
179 item->count = count;
180 }
182 if (emitchange) {
183 /* TODO: This needs to use the accessor to handle the visibility
184 correctly, but when we have the two properties we can just use
185 the local value */
186 Q_EMIT countChanged(appId, this->count(appId));
187 QVariant vcount(item->count);
188 emitPropChangedDbus(appId, "count", vcount);
189 }
192bool LauncherBackend::countVisible(const QString &appId) const
194 bool visible = false;
195 LauncherBackendItem *item = getItem(appId);
197 if (item) {
198 visible = item->countVisible;
199 }
201 return visible;
204void LauncherBackend::setCountVisible(const QString &appId, bool visible) const
206 LauncherBackendItem *item = getItem(appId);
208 bool emitchange = false;
209 if (item) {
210 emitchange = (item->countVisible != visible);
211 item->countVisible = visible;
212 } else {
213 qDebug() << "Unable to find:" << appId;
214 }
216 if (emitchange) {
217 /* TODO: Because we're using visible in determining the
218 count we need to emit a count changed as well */
219 Q_EMIT countChanged(appId, this->count(appId));
220 Q_EMIT countVisibleChanged(appId, item->countVisible);
221 QVariant vCountVisible(item->countVisible);
222 emitPropChangedDbus(appId, "countVisible", vCountVisible);
223 }
226void LauncherBackend::setUser(const QString &username)
228 if (qgetenv("USER") == "lightdm" && m_user != username) {
229 m_user = username;
230 syncFromAccounts();
231 }
234void LauncherBackend::triggerQuickListAction(const QString &appId, const QString &quickListId)
236 // TODO: execute the given quicklist action
237 Q_UNUSED(appId)
238 Q_UNUSED(quickListId)
241void LauncherBackend::syncFromAccounts()
243 QList<QVariantMap> apps;
244 bool defaults = true;
246 m_storedApps.clear();
248 if (m_accounts && !m_user.isEmpty()) {
249 QVariant variant = m_accounts->getUserProperty(m_user, "com.canonical.unity.AccountsService", "launcher-items");
250 if (variant.isValid() && variant.canConvert<QDBusArgument>()) {
251 apps = qdbus_cast<QList<QVariantMap>>(variant.value<QDBusArgument>());
252 defaults = isDefaultsItem(apps);
253 }
254 }
256 if (m_accounts && defaults) { // Checking accounts as it'll be null when !useStorage
257 QGSettings gSettings("com.canonical.Unity.Launcher", "/com/canonical/unity/launcher/");
258 Q_FOREACH(const QString &entry, gSettings.get("favorites").toStringList()) {
259 if (entry.startsWith("application://")) {
260 QString appId = entry;
261 // Transform "application://foobar.desktop" to "application://foobar"
262 appId.remove("application://");
263 if (appId.endsWith(".desktop")) {
264 appId.chop(8);
265 }
266 QString df = findDesktopFile(appId);
268 if (!df.isEmpty()) {
269 m_storedApps << appId;
271 if (!m_itemCache.contains(appId)) {
272 m_itemCache.insert(appId, parseDesktopFile(df));
273 }
274 }
275 }
276 if (entry.startsWith("appid://")) {
277 QString appId = entry;
278 appId.remove("appid://");
279 // Strip hook name and current-user-version in case its there
281 if (appId.split('/').count() != 3) {
282 qWarning() << "ignoring entry " + appId + ". Not a valid appId.";
283 continue;
284 }
285 appId = appId.split('/').first() + "_" + appId.split('/').at(1);
286 QString df = findDesktopFile(appId);
288 if (!df.isEmpty()) {
289 m_storedApps << appId;
291 if (!m_itemCache.contains(appId)) {
292 m_itemCache.insert(appId, parseDesktopFile(df));
293 }
294 }
295 }
296 }
297 } else {
298 for (const QVariant &app: apps) {
299 loadFromVariant(app.toMap());
300 }
301 }
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 }
317void LauncherBackend::refresh()
319 QList<QString> removedApps;
320 Q_FOREACH (const QString &appId, m_storedApps) {
321 if (findDesktopFile(appId).isEmpty()) {
322 removedApps << appId;
323 }
324 }
325 Q_FOREACH (const QString &appId, removedApps) {
326 Q_EMIT appUninstalled(appId);
327 }
330QString LauncherBackend::findDesktopFile(const QString &appId) const
332 int dashPos = -1;
333 QString helper = appId;
335 QStringList searchDirs = QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation);
336#ifdef LAUNCHER_TESTING
337 searchDirs << "";
338#endif
340 do {
341 if (dashPos != -1) {
342 helper = helper.replace(dashPos, 1, '/');
343 }
345 Q_FOREACH(const QString &searchDirName, searchDirs) {
346 QDir searchDir(searchDirName);
347 Q_FOREACH(const QString &desktopFile, searchDir.entryList(QStringList() << "*.desktop")) {
348 if (desktopFile.startsWith(helper)) {
349 QFileInfo fileInfo(searchDir, desktopFile);
350 return fileInfo.absoluteFilePath();
351 }
352 }
353 }
355 dashPos = helper.indexOf("-");
356 } while (dashPos != -1);
358 return QString();
361LauncherBackendItem* LauncherBackend::parseDesktopFile(const QString &desktopFile) const
363 QSettings settings(desktopFile, QSettings::IniFormat);
365 LauncherBackendItem* item = new LauncherBackendItem();
366 item->displayName = settings.value("Desktop Entry/Name").toString();
368 QString iconString = settings.value("Desktop Entry/Icon").toString();
369 QString pathString = settings.value("Desktop Entry/Path").toString();
370 if (QFileInfo(iconString).exists()) {
371 item->icon = QFileInfo(iconString).absoluteFilePath();
372 } else if (QFileInfo(pathString + '/' + iconString).exists()) {
373 item->icon = pathString + '/' + iconString;
374 } else {
375 item->icon = "image://theme/" + iconString;
376 }
378 /* TODO: These should be looked up in a cache somewhere */
379 item->count = 0;
380 item->countVisible = false;
382 return item;
385/* Gets an item, and tries to create a new one if we need it to */
386LauncherBackendItem* LauncherBackend::getItem(const QString &appId) const
388 LauncherBackendItem *item = m_itemCache.value(appId, nullptr);
389 if (!item) {
390 QString df = findDesktopFile(appId);
391 if (!df.isEmpty()) {
392 item = parseDesktopFile(df);
393 if (item) {
394 m_itemCache[appId] = item;
395 } else {
396 qWarning() << "Unable to parse desktop file for" << appId << "path" << df;
397 }
398 } else {
399 qWarning() << "Unable to find desktop file for:" << appId;
400 }
401 }
403 if (!item)
404 qWarning() << "Unable to find item for: " << appId;
406 return item;
409void LauncherBackend::loadFromVariant(const QVariantMap &details)
411 if (!details.contains("id")) {
412 return;
413 }
414 QString appId = details.value("id").toString();
416 QString desktopFile = findDesktopFile(appId);
417 if (desktopFile.isEmpty()) {
418 return;
419 }
421 LauncherBackendItem *item = m_itemCache.value(appId, nullptr);
422 if (item) {
423 delete item;
424 }
426 if (qgetenv("USER") == "lightdm") {
427 item = new LauncherBackendItem();
428 item->displayName = details.value("name").toString();
429 item->icon = details.value("icon").toString();
430 } else {
431 item = parseDesktopFile(desktopFile);
432 }
433 item->count = details.value("count").toInt();
434 item->countVisible = details.value("countVisible").toBool();
436 m_itemCache.insert(appId, item);
437 m_storedApps.append(appId);
440QVariantMap LauncherBackend::itemToVariant(const QString &appId) const
442 LauncherBackendItem *item = m_itemCache.value(appId);
443 QVariantMap details;
444 details.insert("id", appId);
445 details.insert("name", item->displayName);
446 details.insert("icon", item->icon);
447 details.insert("count", item->count);
448 details.insert("countVisible", item->countVisible);
449 return details;
452bool LauncherBackend::isDefaultsItem(const QList<QVariantMap> &apps) const
454 // To differentiate between an empty list and a list that hasn't been set
455 // yet (and should thus be populated with the defaults), we use a special
456 // list of one item with the 'defaults' field set to true.
457 return (apps.size() == 1 && apps[0].value("defaults").toBool());
460bool LauncherBackend::handleMessage(const QDBusMessage& message, const QDBusConnection& connection)
462 /* Check to make sure we're getting properties on our interface */
463 if (message.type() != QDBusMessage::MessageType::MethodCallMessage) {
464 return false;
465 }
466 // First handle methods of the Launcher interface
467 if (message.interface() == "com.canonical.Unity.Launcher") {
468 if (message.member() == "Refresh") {
469 QDBusMessage reply = message.createReply();
470 refresh();
471 return connection.send(reply);
472 }
473 }
475 // Now handle dynamic properties (for launcher emblems)
476 if (message.interface() != "org.freedesktop.DBus.Properties") {
477 return false;
478 }
479 if (message.arguments()[0].toString() != "com.canonical.Unity.Launcher.Item") {
480 return false;
481 }
483 /* Break down the path to just the app id */
484 QString pathtemp = message.path();
485 if (!pathtemp.startsWith("/com/canonical/Unity/Launcher/")) {
486 return false;
487 }
488 pathtemp.remove("/com/canonical/Unity/Launcher/");
489 if (pathtemp.indexOf('/') >= 0) {
490 return false;
491 }
493 /* Find ourselves an appid */
494 QString appid = decodeAppId(pathtemp);
495 QVariantList retval;
497 if (message.member() == "Get") {
498 if (message.arguments()[1].toString() == "count") {
499 retval.append(QVariant::fromValue(QDBusVariant(this->count(appid))));
500 } else if (message.arguments()[1].toString() == "countVisible") {
501 retval.append(QVariant::fromValue(QDBusVariant(this->countVisible(appid))));
502 }
503 } else if (message.member() == "Set") {
504 if (message.arguments()[1].toString() == "count") {
505 this->setCount(appid, message.arguments()[2].value<QDBusVariant>().variant().toInt());
506 } else if (message.arguments()[1].toString() == "countVisible") {
507 this->setCountVisible(appid, message.arguments()[2].value<QDBusVariant>().variant().toBool());
508 }
509 } else if (message.member() == "GetAll") {
510 retval.append(this->itemToVariant(appid));
511 } else {
512 return false;
513 }
515 QDBusMessage reply = message.createReply(retval);
516 return connection.send(reply);
519QString LauncherBackend::introspect(const QString &path) const
521 /* This case we should just list the nodes */
522 if (path == "/com/canonical/Unity/Launcher/" || path == "/com/canonical/Unity/Launcher") {
523 QString nodes;
525 // Add Refresh to introspect
526 nodes = "<interface name=\"com.canonical.Unity.Launcher\">"
527 "<method name=\"Refresh\"/>"
528 "</interface>";
530 // Add dynamic properties for launcher emblems
531 Q_FOREACH(const QString &appId, m_itemCache.keys()) {
532 nodes.append("<node name=\"");
533 nodes.append(encodeAppId(appId));
534 nodes.append("\"/>\n");
535 }
537 return nodes;
538 }
540 /* Should not happen, but let's handle it */
541 if (!path.startsWith("/com/canonical/Unity/Launcher")) {
542 return "";
543 }
545 /* Now we should be looking at a node */
546 QString nodeiface =
547 "<interface name=\"com.canonical.Unity.Launcher.Item\">"
548 "<property name=\"count\" type=\"i\" access=\"readwrite\" />"
549 "<property name=\"countVisible\" type=\"b\" access=\"readwrite\" />"
550 "</interface>";
551 return nodeiface;
554QString LauncherBackend::decodeAppId(const QString& path)
556 QByteArray bytes = path.toUtf8();
557 QByteArray decoded;
559 for (int i = 0; i < bytes.size(); ++i) {
560 char chr = bytes.at(i);
562 if (chr == '_') {
563 QString number;
564 number.append(bytes.at(i+1));
565 number.append(bytes.at(i+2));
567 bool okay;
568 char newchar = number.toUInt(&okay, 16);
569 if (okay)
570 decoded.append(newchar);
572 i += 2;
573 } else {
574 decoded.append(chr);
575 }
576 }
578 return QString::fromUtf8(decoded);
581QString LauncherBackend::encodeAppId(const QString& appId)
583 QByteArray bytes = appId.toUtf8();
584 QString encoded;
586 for (int i = 0; i < bytes.size(); ++i) {
587 uchar chr = bytes.at(i);
589 if ((chr >= 'a' && chr <= 'z') ||
590 (chr >= 'A' && chr <= 'Z') ||
591 (chr >= '0' && chr <= '9'&& i != 0)) {
592 encoded.append(chr);
593 } else {
594 QString hexval = QString("_%1").arg(chr, 2, 16, QChar('0'));
595 encoded.append(hexval.toUpper());
596 }
597 }
599 return encoded;
602void LauncherBackend::emitPropChangedDbus(const QString& appId, const QString& property, QVariant &value) const
604 QString path("/com/canonical/Unity/Launcher/");
605 path.append(encodeAppId(appId));
607 QDBusMessage message = QDBusMessage::createSignal(path, "org.freedesktop.DBus.Properties", "PropertiesChanged");
609 QList<QVariant> arguments;
610 QVariantHash changedprops;
611 changedprops[property] = QVariant::fromValue(QDBusVariant(value));
612 QVariantList deletedprops;
614 arguments.append(changedprops);
615 arguments.append(deletedprops);
617 message.setArguments(arguments);
619 QDBusConnection con = QDBusConnection::sessionBus();
620 con.send(message);