summaryrefslogtreecommitdiffstats
path: root/src/corelib/io/qsettings_wasm.cpp
blob: 8404a526b65ae5bf99d188427c3cba6f87503ed4 (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
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
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qsettings.h"
#ifndef QT_NO_SETTINGS

#include "qsettings_p.h"
#ifndef QT_NO_QOBJECT
#include "qcoreapplication.h"
#include <QFile>
#endif // QT_NO_QOBJECT
#include <QDebug>

#include <QFileInfo>
#include <QDir>
#include <QList>

#include <emscripten.h>
#include <emscripten/val.h>

QT_BEGIN_NAMESPACE

using emscripten::val;
using namespace Qt::StringLiterals;

//
// Native settings implementation for WebAssembly using window.localStorage
// as the storage backend. localStorage is a key-value store with a synchronous
// API and a 5MB storage limit.
//
class QWasmLocalStorageSettingsPrivate final : public QSettingsPrivate
{
public:
    QWasmLocalStorageSettingsPrivate(QSettings::Scope scope, const QString &organization,
                                     const QString &application);

    void remove(const QString &key) final;
    void set(const QString &key, const QVariant &value) final;
    std::optional<QVariant> get(const QString &key) const final;
    QStringList children(const QString &prefix, ChildSpec spec) const final;
    void clear() final;
    void sync() final;
    void flush() final;
    bool isWritable() const final;
    QString fileName() const final;

private:
    QString prependStoragePrefix(const QString &key) const;
    QStringView removeStoragePrefix(QStringView key) const;
    val m_localStorage = val::global("window")["localStorage"];
    QString m_keyPrefix;
};

QWasmLocalStorageSettingsPrivate::QWasmLocalStorageSettingsPrivate(QSettings::Scope scope,
                                                                   const QString &organization,
                                                                   const QString &application)
    : QSettingsPrivate(QSettings::NativeFormat, scope, organization, application)
{
    // The key prefix contians "qt" to separate Qt keys from other keys on localStorage, a
    // version tag to allow for making changes to the key format in the future, the org
    // and app names.
    //
    // User code could could create separate settings object with different org and app names,
    // and would expect them to have separate settings. Also, different webassembly instanaces
    // on the page could write to the same window.localStorage. Add the org and app name
    // to the key prefix to differentiate, even if that leads to keys with redundant sectons
    // for the common case of a single org and app name.
    const QLatin1String separator("-");
    const QLatin1String doubleSeparator("--");
    const QString escapedOrganization = QString(organization).replace(separator, doubleSeparator);
    const QString escapedApplication = QString(application).replace(separator, doubleSeparator);
    const QLatin1String prefix("qt-v0-");
    m_keyPrefix.reserve(prefix.length() + escapedOrganization.length() +
                        escapedApplication.length() + separator.length() * 2);
    m_keyPrefix = prefix + escapedOrganization + separator + escapedApplication + separator;
}

void QWasmLocalStorageSettingsPrivate::remove(const QString &key)
{
    const std::string keyString = prependStoragePrefix(key).toStdString();
    m_localStorage.call<val>("removeItem", keyString);
}

void QWasmLocalStorageSettingsPrivate::set(const QString &key, const QVariant &value)
{
    const std::string keyString = prependStoragePrefix(key).toStdString();
    const std::string valueString = QSettingsPrivate::variantToString(value).toStdString();
    m_localStorage.call<void>("setItem", keyString, valueString);
}

std::optional<QVariant> QWasmLocalStorageSettingsPrivate::get(const QString &key) const
{
    const std::string keyString = prependStoragePrefix(key).toStdString();
    const emscripten::val value = m_localStorage.call<val>("getItem", keyString);
    if (value.isNull())
        return std::nullopt;
    const QString valueString = QString::fromStdString(value.as<std::string>());
    return QSettingsPrivate::stringToVariant(valueString);
}

QStringList QWasmLocalStorageSettingsPrivate::children(const QString &prefix, ChildSpec spec) const
{
    // Loop through all keys on window.localStorage, return Qt keys belonging to
    // this application, with the correct prefix, and according to ChildSpec.
    QStringList children;
    const int length = m_localStorage["length"].as<int>();
    for (int i = 0; i < length; ++i) {
        const QString keyString =
                QString::fromStdString(m_localStorage.call<val>("key", i).as<std::string>());

        const QStringView key = removeStoragePrefix(QStringView(keyString));
        if (key.isEmpty())
            continue;
        if (!key.startsWith(prefix))
            continue;

        QSettingsPrivate::processChild(key.sliced(prefix.length()), spec, children);
    }

    return children;
}

void QWasmLocalStorageSettingsPrivate::clear()
{
    // Remove all Qt keys from window.localStorage
    const int length = m_localStorage["length"].as<int>();
    for (int i = 0; i < length; ++i) {
        std::string fullKey = (m_localStorage.call<val>("key", i).as<std::string>());
        QString key = QString::fromStdString(fullKey);
        if (removeStoragePrefix(QStringView(key)).isEmpty() == false)
            m_localStorage.call<val>("removeItem", fullKey);
    }
}

void QWasmLocalStorageSettingsPrivate::sync() { }

void QWasmLocalStorageSettingsPrivate::flush() { }

bool QWasmLocalStorageSettingsPrivate::isWritable() const
{
    return true;
}

QString QWasmLocalStorageSettingsPrivate::fileName() const
{
    return QString();
}

QString QWasmLocalStorageSettingsPrivate::prependStoragePrefix(const QString &key) const
{
    return m_keyPrefix + key;
}

QStringView QWasmLocalStorageSettingsPrivate::removeStoragePrefix(QStringView key) const
{
    // Return the key slice after m_keyPrefix, or an empty string view if no match
    if (!key.startsWith(m_keyPrefix))
        return QStringView();
    return key.sliced(m_keyPrefix.length());
}

//
// Native settings implementation for WebAssembly using the indexed database as
// the storage backend
//
class QWasmIDBSettingsPrivate : public QConfFileSettingsPrivate
{
public:
    QWasmIDBSettingsPrivate(QSettings::Scope scope, const QString &organization,
                            const QString &application);
    ~QWasmIDBSettingsPrivate();
    static QWasmIDBSettingsPrivate *get(void *userData);

    std::optional<QVariant> get(const QString &key) const override;
    QStringList children(const QString &prefix, ChildSpec spec) const override;
    void clear() override;
    void sync() override;
    void flush() override;
    bool isWritable() const override;

    void syncToLocal(const char *data, int size);
    void loadLocal(const QByteArray &filename);
    void setReady();
    void initAccess() override;

private:
    QString databaseName;
    QString id;
    static QList<QWasmIDBSettingsPrivate *> liveSettings;
};

QList<QWasmIDBSettingsPrivate *> QWasmIDBSettingsPrivate::liveSettings;
static bool isReadReady = false;

static void QWasmIDBSettingsPrivate_onLoad(void *userData, void *dataPtr, int size)
{
    QWasmIDBSettingsPrivate *settings = QWasmIDBSettingsPrivate::get(userData);
    if (!settings)
        return;

    QFile file(settings->fileName());
    QFileInfo fileInfo(settings->fileName());
    QDir dir(fileInfo.path());
    if (!dir.exists())
        dir.mkpath(fileInfo.path());

    if (file.open(QFile::WriteOnly)) {
        file.write(reinterpret_cast<char *>(dataPtr), size);
        file.close();
        settings->setReady();
    }
}

static void QWasmIDBSettingsPrivate_onError(void *userData)
{
    if (QWasmIDBSettingsPrivate *settings = QWasmIDBSettingsPrivate::get(userData))
        settings->setStatus(QSettings::AccessError);
}

static void QWasmIDBSettingsPrivate_onStore(void *userData)
{
    if (QWasmIDBSettingsPrivate *settings = QWasmIDBSettingsPrivate::get(userData))
        settings->setStatus(QSettings::NoError);
}

static void QWasmIDBSettingsPrivate_onCheck(void *userData, int exists)
{
    if (QWasmIDBSettingsPrivate *settings = QWasmIDBSettingsPrivate::get(userData)) {
        if (exists)
            settings->loadLocal(settings->fileName().toLocal8Bit());
        else
            settings->setReady();
    }
}

QWasmIDBSettingsPrivate::QWasmIDBSettingsPrivate(QSettings::Scope scope,
                                                 const QString &organization,
                                                 const QString &application)
    : QConfFileSettingsPrivate(QSettings::NativeFormat, scope, organization, application)
{
    liveSettings.push_back(this);

    setStatus(QSettings::AccessError); // access error until sandbox gets loaded
    databaseName = organization;
    id = application;

    emscripten_idb_async_exists("/home/web_user",
                                fileName().toLocal8Bit(),
                                reinterpret_cast<void*>(this),
                                QWasmIDBSettingsPrivate_onCheck,
                                QWasmIDBSettingsPrivate_onError);
}

QWasmIDBSettingsPrivate::~QWasmIDBSettingsPrivate()
{
    liveSettings.removeAll(this);
}

QWasmIDBSettingsPrivate *QWasmIDBSettingsPrivate::get(void *userData)
{
    if (QWasmIDBSettingsPrivate::liveSettings.contains(userData))
        return reinterpret_cast<QWasmIDBSettingsPrivate *>(userData);
    return nullptr;
}

void QWasmIDBSettingsPrivate::initAccess()
{
     if (isReadReady)
         QConfFileSettingsPrivate::initAccess();
}

std::optional<QVariant> QWasmIDBSettingsPrivate::get(const QString &key) const
{
    if (isReadReady)
        return QConfFileSettingsPrivate::get(key);

    return std::nullopt;
}

QStringList QWasmIDBSettingsPrivate::children(const QString &prefix, ChildSpec spec) const
{
    return QConfFileSettingsPrivate::children(prefix, spec);
}

void QWasmIDBSettingsPrivate::clear()
{
    QConfFileSettingsPrivate::clear();
    emscripten_idb_async_delete("/home/web_user",
                                fileName().toLocal8Bit(),
                                reinterpret_cast<void*>(this),
                                QWasmIDBSettingsPrivate_onStore,
                                QWasmIDBSettingsPrivate_onError);
}

void QWasmIDBSettingsPrivate::sync()
{
    QConfFileSettingsPrivate::sync();

    QFile file(fileName());
    if (file.open(QFile::ReadOnly)) {
        QByteArray dataPointer = file.readAll();

        emscripten_idb_async_store("/home/web_user",
                                  fileName().toLocal8Bit(),
                                   reinterpret_cast<void *>(dataPointer.data()),
                                   dataPointer.length(),
                                   reinterpret_cast<void*>(this),
                                   QWasmIDBSettingsPrivate_onStore,
                                   QWasmIDBSettingsPrivate_onError);
    }
}

void QWasmIDBSettingsPrivate::flush()
{
    sync();
}

bool QWasmIDBSettingsPrivate::isWritable() const
{
    return isReadReady && QConfFileSettingsPrivate::isWritable();
}

void QWasmIDBSettingsPrivate::syncToLocal(const char *data, int size)
{
    QFile file(fileName());

    if (file.open(QFile::WriteOnly)) {
        file.write(data, size + 1);
        QByteArray data = file.readAll();

        emscripten_idb_async_store("/home/web_user",
                                   fileName().toLocal8Bit(),
                                   reinterpret_cast<void *>(data.data()),
                                   data.length(),
                                   reinterpret_cast<void*>(this),
                                   QWasmIDBSettingsPrivate_onStore,
                                   QWasmIDBSettingsPrivate_onError);
        setReady();
    }
}

void QWasmIDBSettingsPrivate::loadLocal(const QByteArray &filename)
{
    emscripten_idb_async_load("/home/web_user",
                              filename.data(),
                              reinterpret_cast<void*>(this),
                              QWasmIDBSettingsPrivate_onLoad,
                              QWasmIDBSettingsPrivate_onError);
}

void QWasmIDBSettingsPrivate::setReady()
{
    isReadReady = true;
    setStatus(QSettings::NoError);
    QConfFileSettingsPrivate::initAccess();
}

QSettingsPrivate *QSettingsPrivate::create(QSettings::Format format, QSettings::Scope scope,
                                           const QString &organization, const QString &application)
{
    const auto WebLocalStorageFormat = QSettings::IniFormat + 1;
    const auto WebIdbFormat = QSettings::IniFormat + 2;

    // Make WebLocalStorageFormat the default native format
    if (format == QSettings::NativeFormat)
        format = QSettings::Format(WebLocalStorageFormat);

    // Check if cookies are enabled (required for using persistent storage)
    const bool cookiesEnabled = val::global("navigator")["cookieEnabled"].as<bool>();
    constexpr QLatin1StringView cookiesWarningMessage
        ("QSettings::%1 requires cookies, falling back to IniFormat with temporary file");
    if (format == WebLocalStorageFormat && !cookiesEnabled) {
        qWarning() << cookiesWarningMessage.arg("WebLocalStorageFormat");
        format = QSettings::IniFormat;
    } else if (format == WebIdbFormat && !cookiesEnabled) {
        qWarning() << cookiesWarningMessage.arg("WebIdbFormat");
        format = QSettings::IniFormat;
    }

    // Create settings backend according to selected format
    if (format == WebLocalStorageFormat) {
        return new QWasmLocalStorageSettingsPrivate(scope, organization, application);
    } else if (format == WebIdbFormat) {
        return new QWasmIDBSettingsPrivate(scope, organization, application);
    } else if (format == QSettings::IniFormat) {
        return new QConfFileSettingsPrivate(format, scope, organization, application);
    }

    qWarning() << "Unsupported settings format" << format;
    return nullptr;
}

QT_END_NAMESPACE
#endif // QT_NO_SETTINGS