on a5ed19d help sign in
unity8/plugins/Unity/Launcher/backend/launcherbackend.cpp
555 lines 17 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(QObject *parent):
42 QDBusVirtualObject(parent),
43 m_accounts(nullptr)
45#ifndef LAUNCHER_TESTING
46 m_accounts = new AccountsServiceDBusAdaptor(this);
47#endif
48 m_user = qgetenv("USER");
49 syncFromAccounts();
51 /* Set up ourselves on DBus */
52 QDBusConnection con = QDBusConnection::sessionBus();
53 if (!con.registerService("com.canonical.unity.launcher"))
54 qDebug() << "Unable to register launcher name";
55 if (!con.registerVirtualObject("/com/canonical/unity/launcher", this, QDBusConnection::VirtualObjectRegisterOption::SubPath))
56 qDebug() << "Unable to register launcher object";
59LauncherBackend::~LauncherBackend()
61 /* Remove oursevles from DBus */
62 QDBusConnection con = QDBusConnection::sessionBus();
63 con.unregisterService("com.canonical.unity.launcher");
64 con.unregisterObject("/com/canonical/unity/launcher");
66 /* Clear data */
67 m_storedApps.clear();
69 Q_FOREACH(LauncherBackendItem *item, m_itemCache) {
70 delete item;
71 }
72 m_itemCache.clear();
75QStringList LauncherBackend::storedApplications() const
77 return m_storedApps;
80void LauncherBackend::setStoredApplications(const QStringList &appIds)
82 if (appIds.count() < m_storedApps.count()) {
83 Q_FOREACH(const QString &appId, m_storedApps) {
84 if (!appIds.contains(appId)) {
85 delete m_itemCache.take(appId);
86 }
87 }
88 }
89 m_storedApps = appIds;
90 Q_FOREACH(const QString &appId, appIds) {
91 if (!m_itemCache.contains(appId)) {
92 QString df = findDesktopFile(appId);
93 if (!df.isEmpty()) {
94 LauncherBackendItem *item = parseDesktopFile(df);
95 m_itemCache.insert(appId, item);
96 } else {
97 // Cannot find any data for that app... ignoring it.
98 qWarning() << "cannot find desktop file for" << appId << ". discarding app.";
99 m_storedApps.removeAll(appId);
100 }
101 }
102 }
103 syncToAccounts();
106QString LauncherBackend::desktopFile(const QString &appId) const
108 LauncherBackendItem *item = m_itemCache.value(appId);
109 if (item) {
110 return item->desktopFile;
111 }
113 return findDesktopFile(appId);
116QString LauncherBackend::displayName(const QString &appId) const
118 LauncherBackendItem *item = m_itemCache.value(appId);
119 if (item) {
120 return item->displayName;
121 }
123 QString df = findDesktopFile(appId);
124 if (!df.isEmpty()) {
125 LauncherBackendItem *item = parseDesktopFile(df);
126 m_itemCache.insert(appId, item);
127 return item->displayName;
128 }
130 return QString();
133QString LauncherBackend::icon(const QString &appId) const
135 QString iconName;
136 LauncherBackendItem *item = getItem(appId);
137 if (item) {
138 iconName = item->icon;
139 }
141 return iconName;
144QList<QuickListEntry> LauncherBackend::quickList(const QString &appId) const
146 // TODO: Get static (from .desktop file) and dynamic (from the app itself)
147 // entries and return them here. Frontend related entries (like "Pin to launcher")
148 // don't matter here. This is just the backend part.
149 // TODO: emit quickListChanged() when the dynamic part changes
150 Q_UNUSED(appId)
151 return QList<QuickListEntry>();
154int LauncherBackend::progress(const QString &appId) const
156 // TODO: Return value for progress emblem.
157 // TODO: emit progressChanged() when this value changes.
158 Q_UNUSED(appId)
159 return -1;
162int LauncherBackend::count(const QString &appId) const
164 int count = -1;
165 LauncherBackendItem *item = getItem(appId);
167 if (!item) {
168 if (item->countVisible) {
169 count = item->count;
170 }
171 }
173 return count;
176void LauncherBackend::setCount(const QString &appId, int count) const
178 LauncherBackendItem *item = getItem(appId);
180 bool emitchange = false;
181 if (!item) {
182 emitchange = (item->count != count);
183 item->count = count;
184 }
186 if (emitchange) {
187 /* TODO: This needs to use the accessor to handle the visibility
188 correctly, but when we have the two properties we can just use
189 the local value */
190 Q_EMIT countChanged(appId, this->count(appId));
191 QVariant vcount(item->count);
192 emitPropChangedDbus(appId, "count", vcount);
193 }
196bool LauncherBackend::countVisible(const QString &appId) const
198 bool visible = false;
199 LauncherBackendItem *item = getItem(appId);
201 if (!item) {
202 visible = item->countVisible;
203 }
205 return visible;
208void LauncherBackend::setCountVisible(const QString &appId, bool visible) const
210 LauncherBackendItem *item = getItem(appId);
212 bool emitchange = false;
213 if (!item) {
214 emitchange = (item->countVisible != visible);
215 item->countVisible = visible;
216 }
218 if (emitchange) {
219 /* TODO: Because we're using visible in determining the
220 count we need to emit a count changed as well */
221 Q_EMIT countChanged(appId, this->count(appId));
222 Q_EMIT countVisibleChanged(appId, item->countVisible);
223 QVariant vCountVisible(item->countVisible);
224 emitPropChangedDbus(appId, "countVisible", vCountVisible);
225 }
228void LauncherBackend::setUser(const QString &username)
230 if (qgetenv("USER") == "lightdm" && m_user != username) {
231 m_user = username;
232 syncFromAccounts();
233 }
236void LauncherBackend::triggerQuickListAction(const QString &appId, const QString &quickListId)
238 // TODO: execute the given quicklist action
239 Q_UNUSED(appId)
240 Q_UNUSED(quickListId)
243void LauncherBackend::syncFromAccounts()
245 QList<QVariantMap> apps;
246 bool defaults = true;
248 m_storedApps.clear();
250 if (m_accounts && !m_user.isEmpty()) {
251 QVariant variant = m_accounts->getUserProperty(m_user, "com.canonical.unity.AccountsService", "launcher-items");
252 if (variant.isValid() && variant.canConvert<QDBusArgument>()) {
253 apps = qdbus_cast<QList<QVariantMap>>(variant.value<QDBusArgument>());
254 defaults = isDefaultsItem(apps);
255 }
256 }
258 if (m_accounts && defaults) { // Checking accounts as it'll be null when !useStorage
259 QGSettings gSettings("com.canonical.Unity.Launcher", "/com/canonical/unity/launcher/");
260 Q_FOREACH(const QString &entry, gSettings.get("favorites").toStringList()) {
261 if (entry.startsWith("application://")) {
262 QString appId = entry;
263 // Transform "application://foobar.desktop" to "foobar"
264 appId.remove("application://");
265 if (appId.endsWith(".desktop")) {
266 appId.chop(8);
267 }
268 QString df = findDesktopFile(appId);
270 if (!df.isEmpty()) {
271 m_storedApps << appId;
273 if (!m_itemCache.contains(appId)) {
274 m_itemCache.insert(appId, parseDesktopFile(df));
275 }
276 }
277 }
278 }
279 } else {
280 for (const QVariant &app: apps) {
281 loadFromVariant(app.toMap());
282 }
283 }
286void LauncherBackend::syncToAccounts()
288 if (m_accounts && !m_user.isEmpty()) {
289 QList<QVariantMap> items;
291 Q_FOREACH(const QString &appId, m_storedApps) {
292 items << itemToVariant(appId);
293 }
295 m_accounts->setUserProperty(m_user, "com.canonical.unity.AccountsService", "launcher-items", QVariant::fromValue(items));
296 }
299QString LauncherBackend::findDesktopFile(const QString &appId) const
301 int dashPos = -1;
302 QString helper = appId;
304 QStringList searchDirs = QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation);
305#ifdef LAUNCHER_TESTING
306 searchDirs << "";
307#endif
309 do {
310 if (dashPos != -1) {
311 helper = helper.replace(dashPos, 1, '/');
312 }
314 Q_FOREACH(const QString &searchDir, searchDirs) {
315 QFileInfo fileInfo(QDir(searchDir), helper + ".desktop");
316 if (fileInfo.exists()) {
317 return fileInfo.absoluteFilePath();
318 }
319 }
321 dashPos = helper.indexOf("-");
322 } while (dashPos != -1);
324 return QString();
327LauncherBackendItem* LauncherBackend::parseDesktopFile(const QString &desktopFile) const
329 QSettings settings(desktopFile, QSettings::IniFormat);
331 LauncherBackendItem* item = new LauncherBackendItem();
332 item->desktopFile = desktopFile;
333 item->displayName = settings.value("Desktop Entry/Name").toString();
335 QString iconString = settings.value("Desktop Entry/Icon").toString();
336 QString pathString = settings.value("Desktop Entry/Path").toString();
337 if (QFileInfo(iconString).exists()) {
338 item->icon = QFileInfo(iconString).absoluteFilePath();
339 } else if (QFileInfo(pathString + '/' + iconString).exists()) {
340 item->icon = pathString + '/' + iconString;
341 } else {
342 item->icon = "image://theme/" + iconString;
343 }
345 /* TODO: These should be looked up in a cache somewhere */
346 item->count = 0;
347 item->countVisible = false;
349 return item;
352/* Gets an item, and tries to create a new one if we need it to */
353LauncherBackendItem* LauncherBackend::getItem (const QString &appId) const
355 LauncherBackendItem *item = m_itemCache.value(appId);
356 if (!item) {
357 QString df = findDesktopFile(appId);
358 if (!df.isEmpty()) {
359 item = parseDesktopFile(df);
360 if (item) {
361 m_itemCache.insert(appId, item);
362 }
363 }
364 }
366 if (!item)
367 qDebug() << "Unable to find item for: " << appId;
369 return item;
372void LauncherBackend::loadFromVariant(const QVariantMap &details)
374 if (!details.contains("id")) {
375 return;
376 }
377 QString appId = details.value("id").toString();
379 LauncherBackendItem *item = m_itemCache.value(appId);
380 if (item) {
381 delete item;
382 }
384 item = new LauncherBackendItem();
386 item->desktopFile = details.value("desktopFile").toString();
387 item->displayName = details.value("name").toString();
388 item->icon = details.value("icon").toString();
389 item->count = details.value("count").toInt();
390 item->countVisible = details.value("countVisible").toBool();
392 m_itemCache.insert(appId, item);
393 m_storedApps.append(appId);
396QVariantMap LauncherBackend::itemToVariant(const QString &appId) const
398 LauncherBackendItem *item = m_itemCache.value(appId);
399 QVariantMap details;
400 details.insert("id", appId);
401 details.insert("name", item->displayName);
402 details.insert("icon", item->icon);
403 details.insert("desktopFile", item->desktopFile);
404 details.insert("count", item->count);
405 details.insert("countVisible", item->countVisible);
406 return details;
409bool LauncherBackend::isDefaultsItem(const QList<QVariantMap> &apps) const
411 // To differentiate between an empty list and a list that hasn't been set
412 // yet (and should thus be populated with the defaults), we use a special
413 // list of one item with the 'defaults' field set to true.
414 return (apps.size() == 1 && apps[0].value("defaults").toBool());
417bool LauncherBackend::handleMessage(const QDBusMessage& message, const QDBusConnection& connection)
419 /* Check to make sure we're getting properties on our interface */
420 if (message.type() != QDBusMessage::MessageType::MethodCallMessage)
421 return false;
422 if (message.interface() != "org.freedesktop.DBus.Properties")
423 return false;
424 if (message.arguments()[0].toString() != "com.canonical.unity.Launcher.Item")
425 return false;
427 /* Break down the path to just the app id */
428 QString pathtemp = message.path();
429 if (!pathtemp.startsWith("/com/canonical/unity/launcher/"))
430 return false;
431 pathtemp.remove("/com/canonical/unity/launcher/");
432 if (pathtemp.indexOf('/') >= 0)
433 return false;
435 /* Find ourselves an appid */
436 QString appid = decodeAppId(pathtemp);
437 QVariantList retval;
439 if (message.member() == "Get") {
440 if (message.arguments()[1].toString() == "count")
441 retval.append(this->count(appid));
442 else if (message.arguments()[1].toString() == "countVisible")
443 retval.append(this->countVisible(appid));
444 } else if (message.member() == "Set") {
445 if (message.arguments()[1].toString() == "count")
446 this->setCount(appid, message.arguments()[2].toInt());
447 else if (message.arguments()[1].toString() == "countVisible")
448 this->setCountVisible(appid, message.arguments()[2].toBool());
449 } else if (message.member() == "GetAll") {
450 retval.append(this->itemToVariant(appid));
451 } else {
452 return false;
453 }
455 QDBusMessage reply = message.createReply(retval);
456 return connection.send(reply);
459QString LauncherBackend::introspect (const QString &path) const
461 /* This case we should just list the nodes */
462 if (path == "/com/canonical/unity/launcher/" || path == "/com/canonical/unity/launcher") {
463 QString nodes;
465 Q_FOREACH(const QString &appId, m_itemCache.keys()) {
466 nodes.append("<node name=\"");
467 nodes.append(encodeAppId(appId));
468 nodes.append("\"/>\n");
469 }
471 return nodes;
472 }
474 /* Should not happen, but let's handle it */
475 if (!path.startsWith("/com/canonical/unity/launcher")) {
476 return "";
477 }
479 /* Now we should be looking at a node */
480 QString nodeiface =
481 "<interface name=\"com.canonical.unity.Launcher.Item\">"
482 "<property name=\"count\" type=\"i\" access=\"readwrite\" />"
483 "<property name=\"countVisible\" type=\"b\" access=\"readwrite\" />"
484 "</interface>";
485 return nodeiface;
488QString LauncherBackend::decodeAppId (const QString& path) const
490 QByteArray bytes = path.toUtf8();
491 QByteArray decoded;
493 for (int i = 0; i < bytes.size(); ++i) {
494 char chr = bytes.at(i);
496 if (chr == '_') {
497 QString number;
498 number.append(bytes.at(i+1));
499 number.append(bytes.at(i+2));
501 bool okay;
502 char newchar = number.toUInt(&okay, 16);
503 if (okay)
504 decoded.append(newchar);
506 i += 2;
507 } else {
508 decoded.append(chr);
509 }
510 }
512 return decoded;
515QString LauncherBackend::encodeAppId (const QString& appId) const
517 QByteArray bytes = appId.toUtf8();
518 QString encoded;
520 for (int i = 0; i < bytes.size(); ++i) {
521 char chr = bytes.at(i);
523 if ((chr >= 'a' && chr <= 'z') ||
524 (chr >= 'A' && chr <= 'Z') ||
525 (chr >= '0' && chr <= '9'&& i != 0)) {
526 encoded.append(chr);
527 } else {
528 QString hexval = QString("_%1").arg((ushort)chr, 2, 16, QChar('0'));
529 encoded.append(hexval);
530 }
531 }
533 return encoded;
536void LauncherBackend::emitPropChangedDbus (const QString& appId, const QString& property, QVariant &value) const
538 QString path("/com/canonical/unity/launcher/");
539 path.append(encodeAppId(appId));
541 QDBusMessage message = QDBusMessage::createSignal(path, "org.freedesktop.DBus.Properties", "PropertiesChanged");
543 QList<QVariant> arguments;
544 QVariantHash changedprops;
545 changedprops[property] = value;
546 QVariantList deletedprops;
548 arguments.append(changedprops);
549 arguments.append(deletedprops);
551 message.setArguments(arguments);
553 QDBusConnection con = QDBusConnection::sessionBus();
554 con.send(message);