summaryrefslogtreecommitdiff
path: root/src/lib/corelib/jsextensions/propertylist_darwin.mm
blob: 69aeefd9296823fa29636c70a6b8550d94513394 (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
/****************************************************************************
**
** Copyright (C) 2015 Petroules Corporation.
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "jsextension.h"
#include "propertylistutils.h"

#include <language/scriptengine.h>
#include <logging/translator.h>
#include <tools/hostosinfo.h>

#include <QtCore/qfile.h>
#include <QtCore/qstring.h>
#include <QtCore/qtextstream.h>
#include <QtCore/qvariant.h>

namespace qbs {
namespace Internal {

class PropertyList : public JsExtension<PropertyList>
{
public:
    static const char *name() { return "PropertyList"; }
    static JSValue ctor(JSContext *ctx, JSValueConst, JSValueConst, int, JSValueConst *, int);
    PropertyList(JSContext *) {}
    static void setupMethods(JSContext *ctx, JSValue obj);

    DEFINE_JS_FORWARDER(jsIsEmpty, &PropertyList::isEmpty, "PropertyList.isEmpty");
    DEFINE_JS_FORWARDER(jsClear, &PropertyList::clear, "PropertyList.clear");
    DEFINE_JS_FORWARDER(jsReadFromObject, &PropertyList::readFromObject,
                        "PropertyList.readFromObject");
    DEFINE_JS_FORWARDER(jsReadFromString, &PropertyList::readFromString,
                        "PropertyList.readFromString");
    DEFINE_JS_FORWARDER(jsReadFromFile, &PropertyList::readFromFile, "PropertyList.readFromFile");
    DEFINE_JS_FORWARDER(jsReadFromData, &PropertyList::readFromData, "PropertyList.readFromData");
    DEFINE_JS_FORWARDER(jsWriteToFile, &PropertyList::writeToFile, "PropertyList.writeToFile");
    DEFINE_JS_FORWARDER(jsFormat, &PropertyList::format, "PropertyList.format");
    DEFINE_JS_FORWARDER(jsToObject, &PropertyList::toObject, "PropertyList.toObject");
    DEFINE_JS_FORWARDER(jsToString, &PropertyList::toString, "PropertyList.toString");
    DEFINE_JS_FORWARDER(jsToXmlString, &PropertyList::toXMLString, "PropertyList.toXMLString");

    static JSValue jsToJson(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
    {
        try {
            QString style;
            if (argc > 0)
                style = fromArg<QString>(ctx, "Process.exec", 1, argv[0]);
            return toJsValue(ctx, fromJsObject(ctx, this_val)->toJSON(style));
        } catch (const QString &error) { return throwError(ctx, error); }
    }

private:
    bool isEmpty() const { return m_propertyListObject.isNull(); }
    void clear();
    void readFromObject(const QVariant &value);
    void readFromString(const QString &input);
    void readFromFile(const QString &filePath);
    void readFromData(const QByteArray &data);
    void writeToFile(const QString &filePath, const QString &plistFormat);
    std::optional<QString> format() const;
    QVariant toObject() const { return m_propertyListObject; }
    QString toString(const QString &plistFormat) const;
    QString toXMLString() const;
    QString toJSON(const QString &style = QString()) const;

    QByteArray writeToData(const QString &format) const;

    QVariant m_propertyListObject;
    int m_propertyListFormat = 0;
};

// Same values as CoreFoundation and Foundation APIs
enum {
    QPropertyListOpenStepFormat = 1,
    QPropertyListXMLFormat_v1_0 = 100,
    QPropertyListBinaryFormat_v1_0 = 200,
    QPropertyListJSONFormat = 1000 // If this conflicts someday, just change it :)
};

JSValue PropertyList::ctor(JSContext *ctx, JSValueConst, JSValueConst, int, JSValueConst *, int)
{
    try {
        JSValue obj = createObject(ctx);
        const auto se = ScriptEngine::engineForContext(ctx);
        const DubiousContextList dubiousContexts{
            DubiousContext(EvalContext::PropertyEvaluation, DubiousContext::SuggestMoving)
        };
        se->checkContext(QStringLiteral("qbs.PropertyList"), dubiousContexts);
        return obj;
    } catch (const QString &error) { return throwError(ctx, error); }
}

void PropertyList::setupMethods(JSContext *ctx, JSValue obj)
{
    setupMethod(ctx, obj, "isEmpty", &jsIsEmpty, 0);
    setupMethod(ctx, obj, "clear", &jsClear, 0);
    setupMethod(ctx, obj, "readFromObject", &jsReadFromObject, 1);
    setupMethod(ctx, obj, "readFromString", &jsReadFromString, 1);
    setupMethod(ctx, obj, "readFromFile", &jsReadFromFile, 1);
    setupMethod(ctx, obj, "readFromData", &jsReadFromData, 1);
    setupMethod(ctx, obj, "writeToFile", &jsWriteToFile, 1);
    setupMethod(ctx, obj, "format", &jsFormat, 0);
    setupMethod(ctx, obj, "toObject", &jsToObject, 0);
    setupMethod(ctx, obj, "toString", &jsToString, 1);
    setupMethod(ctx, obj, "toXMLString", &jsToXmlString, 1);
    setupMethod(ctx, obj, "toJSON", &jsToJson, 1);
}

void PropertyList::clear()
{
    m_propertyListObject = QVariant();
    m_propertyListFormat = 0;
}

void PropertyList::readFromObject(const QVariant &value)
{
    m_propertyListObject = value;
    m_propertyListFormat = 0; // wasn't deserialized from any external format
}

void PropertyList::readFromString(const QString &input)
{
    readFromData(input.toUtf8());
}

void PropertyList::readFromFile(const QString &filePath)
{
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly)) {
        const QByteArray data = file.readAll();
        if (file.error() == QFile::NoError) {
            readFromData(data);
            return;
        }
    }
    throw QStringLiteral("%1: %2").arg(filePath).arg(file.errorString());
}

void PropertyList::readFromData(const QByteArray &data)
{
    @autoreleasepool {
        NSPropertyListFormat format;
        int internalFormat = 0;
        NSString *errorString = nil;
        id plist = [NSPropertyListSerialization propertyListWithData:data.toNSData()
                                                             options:0
                                                              format:&format error:nil];
        if (plist) {
            internalFormat = format;
        } else {
            NSError *error = nil;
            plist = [NSJSONSerialization JSONObjectWithData:data.toNSData()
                                                    options:0
                                                      error:&error];
            if (Q_UNLIKELY(!plist)) {
                errorString = [error localizedDescription];
            } else {
                internalFormat = QPropertyListJSONFormat;
            }
        }

        if (Q_UNLIKELY(!plist))
            throw QString::fromNSString(errorString);
        QVariant obj = QPropertyListUtils::fromPropertyList(plist);
        if (!obj.isNull()) {
            m_propertyListObject = obj;
            m_propertyListFormat = internalFormat;
        } else {
            throw Tr::tr("error converting property list");
        }
    }
}

void PropertyList::writeToFile(const QString &filePath, const QString &plistFormat)
{
    QFile file(filePath);
    QByteArray data = writeToData(plistFormat);
    if (Q_LIKELY(!data.isEmpty())) {
        if (file.open(QIODevice::WriteOnly) && file.write(data) == data.size()) {
            return;
        }
    }

    throw QStringLiteral("%1: %2").arg(filePath).arg(file.errorString());
}

std::optional<QString> PropertyList::format() const
{
    switch (m_propertyListFormat)
    {
    case QPropertyListOpenStepFormat:
        return QStringLiteral("openstep");
    case QPropertyListXMLFormat_v1_0:
        return QStringLiteral("xml1");
    case QPropertyListBinaryFormat_v1_0:
        return QStringLiteral("binary1");
    case QPropertyListJSONFormat:
        return QStringLiteral("json");
    default:
        return {};
    }
}

QString PropertyList::toString(const QString &plistFormat) const
{
    if (plistFormat == QLatin1String("binary1")) {
        throw Tr::tr("Property list object cannot be converted to a "
                     "string in the binary1 format; this format can only "
                     "be written directly to a file");
    }

    if (!isEmpty())
        return QString::fromUtf8(writeToData(plistFormat));
    return {};
}

QString PropertyList::toXMLString() const
{
    return toString(QStringLiteral("xml1"));
}

QString PropertyList::toJSON(const QString &style) const
{
    QString format = QLatin1String("json");
    if (!style.isEmpty())
        format += QLatin1String("-") + style;

    return toString(format);
}

QByteArray PropertyList::writeToData(const QString &format) const
{
    @autoreleasepool {
        NSError *error = nil;
        NSString *errorString = nil;
        NSData *data = nil;

        id obj = QPropertyListUtils::toPropertyList(m_propertyListObject);
        if (!obj)
            throw Tr::tr("error converting property list");

        if (format == QLatin1String("json") || format == QLatin1String("json-pretty") ||
            format == QLatin1String("json-compact")) {
            if ([NSJSONSerialization isValidJSONObject:obj]) {
                error = nil;
                errorString = nil;
                const NSJSONWritingOptions options = format == QLatin1String("json-pretty")
                        ? NSJSONWritingPrettyPrinted : 0;
                data = [NSJSONSerialization dataWithJSONObject:obj
                                                       options:options
                                                         error:&error];
                if (Q_UNLIKELY(!data)) {
                    errorString = [error localizedDescription];
                }
            } else {
                errorString = @"Property list object cannot be converted to JSON data";
            }
        } else if (format == QLatin1String("xml1") || format == QLatin1String("binary1")) {
            const NSPropertyListFormat plistFormat = format == QLatin1String("xml1")
                                                          ? NSPropertyListXMLFormat_v1_0
                                                          : NSPropertyListBinaryFormat_v1_0;

            error = nil;
            errorString = nil;
            data = [NSPropertyListSerialization dataWithPropertyList:obj
                                                              format:plistFormat
                                                             options:0
                                                               error:&error];
            if (Q_UNLIKELY(!data)) {
                errorString = [error localizedDescription];
            }
        } else {
            errorString = [NSString stringWithFormat:@"Property lists cannot be written in the '%s' "
                                                     @"format", format.toUtf8().constData()];
        }

        if (Q_UNLIKELY(!data))
            throw QString::fromNSString(errorString);

        return QByteArray::fromNSData(data);
    }
}

} // namespace Internal
} // namespace qbs

void initializeJsExtensionPropertyList(qbs::Internal::ScriptEngine *engine, JSValue extensionObject)
{
    qbs::Internal::PropertyList::registerClass(engine, extensionObject);
}