summaryrefslogtreecommitdiff
path: root/daemon/appmanager.cpp
blob: c10cf2295c05abd2569d193fb9541beb490f550b (plain)
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
#include <QStandardPaths>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDir>
#include "appmanager.h"
#include "unpacker.h"
#include "stm32crc.h"

namespace {
struct ResourceEntry {
    int index;
    quint32 offset;
    quint32 length;
    quint32 crc;
};
}

AppManager::AppManager(QObject *parent)
    : QObject(parent), l(metaObject()->className()),
      _watcher(new QFileSystemWatcher(this))
{
    connect(_watcher, &QFileSystemWatcher::directoryChanged,
            this, &AppManager::rescan);

    QDir dataDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
    if (!dataDir.exists("apps")) {
        if (!dataDir.mkdir("apps")) {
            logger()->warn() << "could not create dir" << dataDir.absoluteFilePath("apps");
        }
    }
    qCDebug(l) << "install apps in" << dataDir.absoluteFilePath("apps");

    rescan();
}

QStringList AppManager::appPaths() const
{
    return QStandardPaths::locateAll(QStandardPaths::DataLocation,
                                     QLatin1String("apps"),
                                     QStandardPaths::LocateDirectory);
}

QList<QUuid> AppManager::appUuids() const
{
    return _apps.keys();
}

AppInfo AppManager::info(const QUuid &uuid) const
{
    return _apps.value(uuid);
}

AppInfo AppManager::info(const QString &name) const
{
    QUuid uuid = _names.value(name);
    if (!uuid.isNull()) {
        return info(uuid);
    } else {
        return AppInfo();
    }
}

void AppManager::rescan()
{
    QStringList watchedDirs = _watcher->directories();
    if (!watchedDirs.isEmpty()) _watcher->removePaths(watchedDirs);
    QStringList watchedFiles = _watcher->files();
    if (!watchedFiles.isEmpty()) _watcher->removePaths(watchedFiles);
    _apps.clear();
    _names.clear();

    Q_FOREACH(const QString &path, appPaths()) {
        QDir dir(path);
        _watcher->addPath(dir.absolutePath());
        qCDebug(l) << "scanning dir" << dir.absolutePath();
        QStringList entries = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable | QDir::Executable);
        qCDebug(l) << "scanning dir results" << entries;
        Q_FOREACH(const QString &path, entries) {
            QString appPath = dir.absoluteFilePath(path);
            _watcher->addPath(appPath);
            if (dir.exists(path + "/appinfo.json")) {
                _watcher->addPath(appPath + "/appinfo.json");
                scanApp(appPath);
            }
        }
    }

    qCDebug(l) << "now watching" << _watcher->directories() << _watcher->files();
    emit appsChanged();
}

void AppManager::scanApp(const QString &path)
{
    qCDebug(l) << "scanning app" << path;
    QDir appDir(path);
    if (!appDir.isReadable()) {
        qCWarning(l) << "app" << appDir.absolutePath() << "is not readable";
        return;
    }

    QFile appInfoFile(path + "/appinfo.json");
    if (!appInfoFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCWarning(l) << "cannot open app info file" << appInfoFile.fileName() << ":"
                         << appInfoFile.errorString();
        return;
    }

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(appInfoFile.readAll(), &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qCWarning(l) << "cannot parse app info file" << appInfoFile.fileName() << ":"
                         << parseError.errorString();
        return;
    }

    const QJsonObject root = doc.object();
    AppInfo info;
    info.setUuid(QUuid(root["uuid"].toString()));
    info.setShortName(root["shortName"].toString());
    info.setLongName(root["longName"].toString());
    info.setCompanyName(root["companyName"].toString());
    info.setVersionCode(root["versionCode"].toInt());
    info.setVersionLabel(root["versionLabel"].toString());

    const QJsonObject watchapp = root["watchapp"].toObject();
    info.setWatchface(watchapp["watchface"].toBool());
    info.setJSKit(appDir.exists("pebble-js-app.js"));

    if (root.contains("capabilities")) {
        const QJsonArray capabilities = root["capabilities"].toArray();
        AppInfo::Capabilities caps = 0;
        for (auto it = capabilities.constBegin(); it != capabilities.constEnd(); ++it) {
            QString cap = (*it).toString();
            if (cap == "location") caps |= AppInfo::Location;
            if (cap == "configurable") caps |= AppInfo::Configurable;
        }
        info.setCapabilities(caps);
    }

    if (root.contains("appKeys")) {
        const QJsonObject appkeys = root["appKeys"].toObject();
        for (auto it = appkeys.constBegin(); it != appkeys.constEnd(); ++it) {
            info.addAppKey(it.key(), it.value().toInt());
        }
    }

    if (root.contains("resources")) {
        const QJsonObject resources = root["resources"].toObject();
        const QJsonArray media = resources["media"].toArray();
        int index = 0;

        for (auto it = media.constBegin(); it != media.constEnd(); ++it) {
            const QJsonObject res = (*it).toObject();
            const QJsonValue menuIcon = res["menuIcon"];

            bool is_menu_icon = false;
            switch (menuIcon.type()) {
            case QJsonValue::Bool:
                is_menu_icon = menuIcon.toBool();
                break;
            case QJsonValue::String:
                is_menu_icon = !menuIcon.toString().isEmpty();
                break;
            default:
                break;
            }

            if (is_menu_icon) {
                QByteArray data = extractFromResourcePack(appDir.filePath("app_resources.pbpack"), index);
                if (!data.isEmpty()) {
                    QImage icon = decodeResourceImage(data);
                    info.setMenuIcon(icon);
                }
            }

            index++;
        }
    }

    info.setPath(path);

    if (info.uuid().isNull() || info.shortName().isEmpty()) {
        qCWarning(l) << "invalid or empty uuid/name in" << appInfoFile.fileName();
        return;
    }

    _apps.insert(info.uuid(), info);
    _names.insert(info.shortName(), info.uuid());

    const char *type = info.isWatchface() ? "watchface" : "app";
    qCDebug(l) << "found installed" << type << info.shortName() << info.versionLabel() << "with uuid" << info.uuid().toString();
}

QByteArray AppManager::extractFromResourcePack(const QString &file, int wanted_id) const
{
    QFile f(file);
    if (!f.open(QIODevice::ReadOnly)) {
        qCWarning(l) << "cannot open resource file" << f.fileName();
        return QByteArray();
    }

    QByteArray data = f.readAll();
    Unpacker u(data);

    int num_files = u.readLE<quint32>();
    u.readLE<quint32>(); // crc for entire file
    u.readLE<quint32>(); // timestamp

    qCDebug(l) << "reading" << num_files << "resources from" << file;

    QList<ResourceEntry> table;

    for (int i = 0; i < num_files; i++) {
        ResourceEntry e;
        e.index = u.readLE<quint32>();
        e.offset = u.readLE<quint32>();
        e.length = u.readLE<quint32>();
        e.crc = u.readLE<quint32>();

        if (u.bad()) {
            qCWarning(l) << "short read on resource file";
            return QByteArray();
        }

        table.append(e);
    }

    if (wanted_id >= table.size()) {
        qCWarning(l) << "specified resource does not exist";
        return QByteArray();
    }

    const ResourceEntry &e = table[wanted_id];

    int offset = 12 + 256 * 16 + e.offset;

    QByteArray res = data.mid(offset, e.length);

    Stm32Crc crc;
    crc.addData(res);

    if (crc.result() != e.crc) {
        qCWarning(l) << "CRC failure in resource" << e.index << "on file" << file;
        return QByteArray();
    }

    return res;
}

QImage AppManager::decodeResourceImage(const QByteArray &data) const
{
    Unpacker u(data);
    int scanline = u.readLE<quint16>();
    u.skip(sizeof(quint16) + sizeof(quint32));
    int width = u.readLE<quint16>();
    int height = u.readLE<quint16>();

    QImage img(width, height, QImage::Format_MonoLSB);
    const uchar *src = reinterpret_cast<const uchar *>(&data.constData()[12]);
    for (int line = 0; line < height; ++line) {
        memcpy(img.scanLine(line), src, qMin(scanline, img.bytesPerLine()));
        src += scanline;
    }

    return img;
}