~mterry/unity-scope-click/allow-legacy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*
 * Copyright (C) 2014-2016 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3, as published
 * by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY, 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 */

#include <click.h>

#include "interface.h"

#include <QDebug>
#include <QDir>
#include <QProcess>
#include <QStandardPaths>
#include <QString>
#include <QTimer>

#include <cstdio>
#include <list>
#include <sys/stat.h>
#include <map>
#include <sstream>

#include <boost/locale/collator.hpp>
#include <boost/locale/generator.hpp>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/exceptions.hpp>
#include <boost/foreach.hpp>

#include <unity/UnityExceptions.h>
#include <unity/util/IniParser.h>

#include <click/departments-db.h>

#include <ubuntu-app-launch/registry.h>

#include <click/click-i18n.h>

namespace ual = ubuntu::app_launch;

namespace {

/* Thanks to
 *   - http://stackoverflow.com/a/14031349
 *   - http://stackoverflow.com/questions/12278448/removing-accents-from-a-qstring
 */
QString unaccent(const QString &str)
{
    QString tmp = str.normalized(QString::NormalizationForm_KD,
                                 QChar::currentUnicodeVersion());
    QString ret;
    for (int i = 0, j = tmp.length();
         i < j;
         i++) {

        // strip diacritic marks
        if (tmp.at(i).category() != QChar::Mark_NonSpacing       &&
            tmp.at(i).category() != QChar::Mark_SpacingCombining &&
            tmp.at(i).category() != QChar::Mark_Enclosing) {
            ret.append(tmp.at(i));
        }
    }

    return ret;
}

}

namespace click {

static const std::string DESKTOP_FILE_GROUP("Desktop Entry");
static const std::string DESKTOP_FILE_KEY_NAME("Name");
static const std::string DESKTOP_FILE_KEY_ICON("Icon");
static const std::string DESKTOP_FILE_KEY_KEYWORDS("Keywords");
static const std::string DESKTOP_FILE_KEY_APP_ID("X-Ubuntu-Application-ID");
static const std::string DESKTOP_FILE_KEY_DOMAIN("X-Ubuntu-Gettext-Domain");
static const std::string DESKTOP_FILE_UBUNTU_TOUCH("X-Ubuntu-Touch");
static const std::string DESKTOP_FILE_UBUNTU_DEFAULT_DEPARTMENT("X-Ubuntu-Default-Department-ID");
static const std::string DESKTOP_FILE_COMMENT("Comment");
static const std::string DESKTOP_FILE_SCREENSHOT("X-Screenshot");
static const std::string DESKTOP_FILE_NODISPLAY("NoDisplay");
static const std::string DESKTOP_FILE_ONLYSHOWIN("OnlyShowIn");
static const std::string ONLYSHOWIN_UNITY("Unity");


std::vector<click::Application> Interface::sort_apps(const std::vector<click::Application>& apps)
{
    std::vector<click::Application> result = apps;
    boost::locale::generator gen;
    const char* lang = getenv(click::Configuration::LANGUAGE_ENVVAR);
    if (lang == NULL) {
        lang = "C.UTF-8";
    }
    std::locale loc = gen(lang);
    std::locale::global(loc);
    typedef boost::locale::collator<char> coll_type;

    // Sort applications alphabetically.
    std::sort(result.begin(), result.end(), [&loc](const Application& a,
                                                   const Application& b) {
                  bool lesser = false;
                  int order = std::use_facet<coll_type>(loc)
                      .compare(boost::locale::collator_base::quaternary,
                               a.title, b.title);
                  if (order == 0) {
                      lesser = a.name < b.name;
                  } else {
                      // Because compare returns int, not bool, we have to check
                      // that 0 is greater than the result, which tells us the
                      // first element should be sorted priori
                      lesser = order < 0;
                  }
                  return lesser;
              });

    return result;
}

std::list<std::shared_ptr<ual::Application>> Interface::installed_apps() const
{
    return ual::Registry::installedApps();
}

/* search()
 *
 * Find all of the installed apps matching @query in a timeout.
 */
std::vector<click::Application> Interface::search(const std::string& query,
        const std::vector<std::string>& ignored_apps,
        const std::string& current_department,
        const std::shared_ptr<click::DepartmentsDb>& depts_db)
{
    //
    // only apply department filtering if not in root of all departments.
    bool apply_department_filter = !current_department.empty();

    // get the set of packages that belong to current deparment;
    std::unordered_set<std::string> packages_in_department;
    if (depts_db && apply_department_filter)
    {
        try
        {
            packages_in_department = depts_db->get_packages_for_department(current_department);
        }
        catch (const std::exception& e)
        {
            qWarning() << "Failed to get packages of department" << QString::fromStdString(current_department);
            apply_department_filter = false; // disable so that we are not loosing any apps if something goes wrong
        }
    }

    std::vector<click::Application> result;

    for (const auto& ualapp: installed_apps()) {
        click::Application app;

        // Get the package name and APP_ID info.
        app.name = ualapp->appId().package.value();
        app.version = ualapp->appId().version.value();
        if (app.name.empty()) {
            app.name = std::string{ualapp->appId().appname.value()} + ".desktop";
            app.url = "application:///" + app.name;
        } else {
            app.url = "appid://" + app.name + "/" + ualapp->appId().appname.value() + "/current-user-version";
        }

        if (std::find(ignored_apps.begin(), ignored_apps.end(),
                      app.name) != ignored_apps.end()) {
            // The app is ignored. Get out of here.
            qDebug() << "App is ignored, skipping:" << QString::fromStdString(app.name);
            continue;
        }

        // Get the .desktop file info from UAL, since we're not ignoring
        try {
            auto appinfo = ualapp->info();
            app.title = appinfo->name();
            app.description = appinfo->description();
            app.icon_url = appinfo->iconPath();
            app.default_department = appinfo->defaultDepartment();
            app.main_screenshot = appinfo->screenshotPath();
            app.keywords = appinfo->keywords();
        } catch (const std::exception& e) {
            qDebug() << "Unable to get info, skipping:" << QString::fromStdString(app.name);
            continue;
        }

        // app from click package has non-empty name; for non-click apps use desktop filename
        const auto& department_key = app.name;
        qDebug() << "Using department key:" << QString::fromStdString(department_key);

        // check if apps is present in current department
        if (apply_department_filter) {
            if (packages_in_department.find(department_key) ==
                packages_in_department.end()) {
                if (app.default_department.empty()) {
                    // default department not present in the keyfile, skip this app
                    continue;
                } else {
                    // default department not empty: check if this app is in a different
                    // department in the db (i.e. got moved from the default department);
                    if (depts_db->has_package(department_key)) {
                        // app is now in a different department
                        continue;
                    }

                    if (app.default_department != current_department) {
                        continue;
                    }
                    // else - this package is in current department
                }
            }
        }

        // the packages_in_department set contains packages from
        // all its subdepartments; we need to find actual department now
        // to update app.real_department.
        if (depts_db) {
            if (depts_db->has_package(department_key)) {
                try {
                    app.real_department = depts_db->get_department_for_package(department_key);
                } catch (const std::exception &e) {
                    qWarning() << "Failed to get department of package:" << QString::fromStdString(department_key);
                }
            } else {
                app.real_department = app.default_department;
                if (app.real_department.empty()) {
                    qWarning() << "No default department set in the .desktop file and no entry in the database for" << QString::fromStdString(department_key);
                }
            }
        }

        if (query.empty()) {
            result.push_back(app);
        } else {
            QString lquery = ::unaccent(QString::fromStdString(query));

            // Check keywords for the search query as well.
            for (const auto& kwd: app.keywords) {
                QString keyword = ::unaccent(QString::fromStdString(kwd));
                if (keyword.contains(lquery, Qt::CaseInsensitive)) {
                    result.push_back(app);
                }
            }

            QString search_title = ::unaccent(QString::fromStdString(app.title));
            // check the app title for the search query.
            if (search_title.contains(lquery, Qt::CaseInsensitive)) {
                result.push_back(app);
            }
        }
    }

    return sort_apps(result);
}

/*
 * is_icon_identifier()
 *
 * Checks if @filename has no / in it
 */
bool Interface::is_icon_identifier(const std::string &icon_id)
{
    return icon_id.find("/") == std::string::npos;
}

/*
 * add_theme_scheme()
 *
 * Adds the theme prefix if the filename is not an icon identifier
 */
std::string Interface::add_theme_scheme(const std::string& icon_id)
{
    if (is_icon_identifier(icon_id)) {
        return "image://theme/" + icon_id;
    }
    return icon_id;
}

Manifest manifest_from_json(const std::string& json)
{
    using namespace boost::property_tree;

    std::istringstream is(json);

    ptree pt;
    read_json(is, pt);

    Manifest manifest;

    manifest.name = pt.get<std::string>("name");
    manifest.version = pt.get<std::string>("version");
    manifest.removable = pt.get<bool>("_removable");

    BOOST_FOREACH(ptree::value_type &sv, pt.get_child("hooks"))
    {
        // FIXME: "primary app or scope" for a package is not defined,
        // we just use the first one in the manifest:
        auto app_name = sv.second.get("desktop", "");
        if (manifest.first_app_name.empty() && !app_name.empty()) {
            manifest.first_app_name = sv.first;
        }
        auto scope_id = sv.second.get("scope", "");
        if (manifest.first_scope_id.empty() && !scope_id.empty()) {
            manifest.first_scope_id = manifest.name + "_" + sv.first;
        }
    }
    qDebug() << "adding manifest: " << manifest.name.c_str() << manifest.version.c_str() << manifest.first_app_name.c_str();

    return manifest;
}

void Interface::get_installed_packages(std::function<void(PackageSet, InterfaceError)> callback)
{
    PackageSet packages;
    for (const auto& app: installed_apps()) {
        Package p;
        const auto appid = app->appId();
        p.name = appid.package.value();
        p.version = appid.version.value();
        if (!p.name.empty() && !p.version.empty()) {
            packages.insert(p);
        }
    }
    callback(packages, InterfaceError::NoError);
}

std::string Interface::get_manifest_json(const std::string &package) const
{
    GError* error = nullptr;

    std::shared_ptr<ClickDB> clickdb{click_db_new(),
            [](ClickDB* db){g_clear_object(&db);}};
    click_db_read(clickdb.get(), nullptr, &error);
    if (error != nullptr) {
        qCritical() << "Error reading click DB:" << error->message;
        g_error_free(error);
        return "";
    }

    std::shared_ptr<ClickUser> clickuser{click_user_new_for_user(clickdb.get(),
                                                                 nullptr,
                                                                 &error),
            [](ClickUser* cu){g_clear_object(&cu);}};
    if (error != nullptr) {
        qCritical() << "Error setting up click user:" << error->message;
        g_error_free(error);
        return "";
    }

    auto result = click_user_get_manifest_as_string(clickuser.get(),
                                                    package.c_str(),
                                                    &error);
    if (error != nullptr) {
        qCritical() << "Error getting manifest:" << error->message;
        g_error_free(error);
        return "";
    }

    std::string retval;
    if (result != nullptr) {
        retval = result;
        g_free(result);
    }
    return retval;
}

void Interface::get_manifest_for_app(const std::string &app_id,
                                     std::function<void(Manifest, InterfaceError)> callback)
{
    Manifest manifest;
    InterfaceError error;
    try {
        manifest = manifest_from_json(get_manifest_json(app_id));
        error = InterfaceError::NoError;
    } catch (...) {
        qWarning() << "Can't parse manifest for:" << QString::fromStdString(app_id);
        error = InterfaceError::ParseError;
    }
    callback(manifest, error);
}

} // namespace click