summaryrefslogtreecommitdiff
path: root/daemon/jskitobjects.cpp
blob: 3386f163fef3f25c301ccbad4e610c8443f33e38 (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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
#include <QStandardPaths>
#include <QDesktopServices>
#include <QUrl>
#include <QBuffer>
#include <QDir>
#include <limits>
#include "jskitobjects.h"

JSKitPebble::JSKitPebble(const AppInfo &info, JSKitManager *mgr)
    : QObject(mgr), _appInfo(info), _mgr(mgr)
{
}

void JSKitPebble::addEventListener(const QString &type, QJSValue function)
{
    _callbacks[type].append(function);
}

void JSKitPebble::removeEventListener(const QString &type, QJSValue function)
{
    if (!_callbacks.contains(type)) return;
    QList<QJSValue> &callbacks = _callbacks[type];

    for (QList<QJSValue>::iterator it = callbacks.begin(); it != callbacks.end(); ) {
        if (it->strictlyEquals(function)) {
            it = callbacks.erase(it);
        } else {
            ++it;
        }
    }

    if (callbacks.empty()) {
        _callbacks.remove(type);
    }
}

uint JSKitPebble::sendAppMessage(QJSValue message, QJSValue callbackForAck, QJSValue callbackForNack)
{
    QVariantMap data = message.toVariant().toMap();
    QPointer<JSKitPebble> pebbObj = this;
    uint transactionId = _mgr->_appmsg->nextTransactionId();

    logger()->debug() << "sendAppMessage" << data;

    _mgr->_appmsg->send(_appInfo.uuid(), data,
    [pebbObj, transactionId, callbackForAck]() mutable {
        if (pebbObj.isNull()) return;
        if (callbackForAck.isCallable()) {
            pebbObj->logger()->debug() << "Invoking ack callback";
            QJSValue event = pebbObj->buildAckEventObject(transactionId);
            QJSValue result = callbackForAck.call(QJSValueList({event}));
            if (result.isError()) {
                pebbObj->logger()->warn() << "error while invoking ACK callback" << callbackForAck.toString() << ":"
                                          << JSKitManager::describeError(result);
            }
        } else {
            pebbObj->logger()->debug() << "Ack callback not callable";
        }
    },
    [pebbObj, transactionId, callbackForNack]() mutable {
        if (pebbObj.isNull()) return;
        if (callbackForNack.isCallable()) {
            pebbObj->logger()->debug() << "Invoking nack callback";
            QJSValue event = pebbObj->buildAckEventObject(transactionId, "NACK from watch");
            QJSValue result = callbackForNack.call(QJSValueList({event}));
            if (result.isError()) {
                pebbObj->logger()->warn() << "error while invoking NACK callback" << callbackForNack.toString() << ":"
                                          << JSKitManager::describeError(result);
            }
        } else {
            pebbObj->logger()->debug() << "Nack callback not callable";
        }
    });

    return transactionId;
}

void JSKitPebble::showSimpleNotificationOnPebble(const QString &title, const QString &body)
{
    logger()->debug() << "showSimpleNotificationOnPebble" << title << body;
    emit _mgr->appNotification(_appInfo.uuid(), title, body);
}

void JSKitPebble::openURL(const QUrl &url)
{
    logger()->debug() << "opening url" << url.toString();
    emit _mgr->appOpenUrl(url);
}

QJSValue JSKitPebble::createXMLHttpRequest()
{
    JSKitXMLHttpRequest *xhr = new JSKitXMLHttpRequest(_mgr, 0);
    // Should be deleted by JS engine.
    return _mgr->engine()->newQObject(xhr);
}

QJSValue JSKitPebble::buildAckEventObject(uint transaction, const QString &message) const
{
    QJSEngine *engine = _mgr->engine();
    QJSValue eventObj = engine->newObject();
    QJSValue dataObj = engine->newObject();

    dataObj.setProperty("transactionId", engine->toScriptValue(transaction));
    eventObj.setProperty("data", dataObj);

    if (!message.isEmpty()) {
        QJSValue errorObj = engine->newObject();
        errorObj.setProperty("message", engine->toScriptValue(message));
        eventObj.setProperty("error", errorObj);
    }

    return eventObj;
}

void JSKitPebble::invokeCallbacks(const QString &type, const QJSValueList &args)
{
    if (!_callbacks.contains(type)) return;
    QList<QJSValue> &callbacks = _callbacks[type];

    for (QList<QJSValue>::iterator it = callbacks.begin(); it != callbacks.end(); ++it) {
        logger()->debug() << "invoking callback" << type << it->toString();
        QJSValue result = it->call(args);
        if (result.isError()) {
            logger()->warn() << "error while invoking callback" << type << it->toString() << ":"
                             << JSKitManager::describeError(result);
        }
    }
}

JSKitConsole::JSKitConsole(JSKitManager *mgr)
    : QObject(mgr)
{
}

void JSKitConsole::log(const QString &msg)
{
    logger()->info() << msg;
}

JSKitLocalStorage::JSKitLocalStorage(const QUuid &uuid, JSKitManager *mgr)
    : QObject(mgr), _storage(new QSettings(getStorageFileFor(uuid), QSettings::IniFormat, this))
{
    _len = _storage->allKeys().size();
}

int JSKitLocalStorage::length() const
{
    return _len;
}

QJSValue JSKitLocalStorage::getItem(const QString &key) const
{
    QVariant value = _storage->value(key);
    if (value.isValid()) {
        return QJSValue(value.toString());
    } else {
        return QJSValue(QJSValue::NullValue);
    }
}

void JSKitLocalStorage::setItem(const QString &key, const QString &value)
{
    _storage->setValue(key, QVariant::fromValue(value));
    checkLengthChanged();
}

void JSKitLocalStorage::removeItem(const QString &key)
{
    _storage->remove(key);
    checkLengthChanged();
}

void JSKitLocalStorage::clear()
{
    _storage->clear();
    _len = 0;
    emit lengthChanged();
}

void JSKitLocalStorage::checkLengthChanged()
{
    int curLen = _storage->allKeys().size();
    if (_len != curLen) {
        _len = curLen;
        emit lengthChanged();
    }
}

QString JSKitLocalStorage::getStorageFileFor(const QUuid &uuid)
{
    QDir dataDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
    dataDir.mkdir("js-storage");
    QString fileName = uuid.toString();
    fileName.remove('{');
    fileName.remove('}');
    return dataDir.absoluteFilePath("js-storage/" + fileName + ".ini");
}

JSKitXMLHttpRequest::JSKitXMLHttpRequest(JSKitManager *mgr, QObject *parent)
    : QObject(parent), _mgr(mgr),
      _net(new QNetworkAccessManager(this)), _timeout(0), _reply(0)
{
    logger()->debug() << "constructed";
}

JSKitXMLHttpRequest::~JSKitXMLHttpRequest()
{
    logger()->debug() << "destructed";
}

void JSKitXMLHttpRequest::open(const QString &method, const QString &url, bool async, const QString &username, const QString &password)
{
    if (_reply) {
        _reply->deleteLater();
        _reply = 0;
    }

    _request = QNetworkRequest(QUrl(url));
    _verb = method;
    Q_UNUSED(async);
}

void JSKitXMLHttpRequest::setRequestHeader(const QString &header, const QString &value)
{
    logger()->debug() << "setRequestHeader" << header << value;
    _request.setRawHeader(header.toLatin1(), value.toLatin1());
}

void JSKitXMLHttpRequest::send(const QJSValue &data)
{
    QByteArray byteData;

    if (data.isUndefined() || data.isNull()) {
        // Do nothing, byteData is empty.
    } else if (data.isString()) {
        byteData == data.toString().toUtf8();
    } else if (data.isObject()) {
        if (data.hasProperty("byteLength")) {
            // Looks like an ArrayView or an ArrayBufferView!
            QJSValue buffer = data.property("buffer");
            if (buffer.isUndefined()) {
                // We must assume we've been passed an ArrayBuffer directly
                buffer = data;
            }

            QJSValue array = data.property("_bytes");
            int byteLength = data.property("byteLength").toInt();

            if (array.isArray()) {
                byteData.reserve(byteLength);

                for (int i = 0; i < byteLength; i++) {
                    byteData.append(array.property(i).toInt());
                }

                logger()->debug() << "passed an ArrayBufferView of" << byteData.length() << "bytes";
            } else {
                logger()->warn() << "passed an unknown/invalid ArrayBuffer" << data.toString();
            }
        } else {
            logger()->warn() << "passed an unknown object" << data.toString();
        }

    }

    QBuffer *buffer;
    if (!byteData.isEmpty()) {
        buffer = new QBuffer;
        buffer->setData(byteData);
    } else {
        buffer = 0;
    }

    logger()->debug() << "sending" << _verb << "to" << _request.url() << "with" << QString::fromUtf8(byteData);
    _reply = _net->sendCustomRequest(_request, _verb.toLatin1(), buffer);

    connect(_reply, &QNetworkReply::finished,
            this, &JSKitXMLHttpRequest::handleReplyFinished);
    connect(_reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
            this, &JSKitXMLHttpRequest::handleReplyError);

    if (buffer) {
        // So that it gets deleted alongside the reply object.
        buffer->setParent(_reply);
    }
}

void JSKitXMLHttpRequest::abort()
{
    if (_reply) {
        _reply->deleteLater();
        _reply = 0;
    }
}

QJSValue JSKitXMLHttpRequest::onload() const
{
    return _onload;
}

void JSKitXMLHttpRequest::setOnload(const QJSValue &value)
{
    _onload = value;
}

QJSValue JSKitXMLHttpRequest::ontimeout() const
{
    return _ontimeout;
}

void JSKitXMLHttpRequest::setOntimeout(const QJSValue &value)
{
    _ontimeout = value;
}

QJSValue JSKitXMLHttpRequest::onerror() const
{
    return _onerror;
}

void JSKitXMLHttpRequest::setOnerror(const QJSValue &value)
{
    _onerror = value;
}

uint JSKitXMLHttpRequest::readyState() const
{
    if (!_reply) {
        return UNSENT;
    } else if (_reply->isFinished()) {
        return DONE;
    } else {
        return LOADING;
    }
}

uint JSKitXMLHttpRequest::timeout() const
{
    return _timeout;
}

void JSKitXMLHttpRequest::setTimeout(uint value)
{
    _timeout = value;
    // TODO Handle fetch in-progress.
}

uint JSKitXMLHttpRequest::status() const
{
    if (!_reply || !_reply->isFinished()) {
        return 0;
    } else {
        return _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt();
    }
}

QString JSKitXMLHttpRequest::statusText() const
{
    if (!_reply || !_reply->isFinished()) {
        return QString();
    } else {
        return _reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    }
}

QString JSKitXMLHttpRequest::responseType() const
{
    return _responseType;
}

void JSKitXMLHttpRequest::setResponseType(const QString &type)
{
    logger()->debug() << "response type set to" << type;
    _responseType = type;
}

QJSValue JSKitXMLHttpRequest::response() const
{
    QJSEngine *engine = _mgr->engine();
    if (_responseType.isEmpty() || _responseType == "text") {
        return engine->toScriptValue(QString::fromUtf8(_response));
    } else if (_responseType == "arraybuffer") {
        QJSValue arrayBufferProto = engine->globalObject().property("ArrayBuffer").property("prototype");
        QJSValue arrayBuf = engine->newObject();
        if (!arrayBufferProto.isUndefined()) {
            arrayBuf.setPrototype(arrayBufferProto);
            arrayBuf.setProperty("byteLength", engine->toScriptValue<uint>(_response.size()));
            QJSValue array = engine->newArray(_response.size());
            for (int i = 0; i < _response.size(); i++) {
                array.setProperty(i, engine->toScriptValue<int>(_response[i]));
            }
            arrayBuf.setProperty("_bytes", array);
            logger()->debug() << "returning ArrayBuffer of" << _response.size() << "bytes";
        } else {
            logger()->warn() << "Cannot find proto of ArrayBuffer";
        }
        return arrayBuf;
    } else {
        logger()->warn() << "unsupported responseType:" << _responseType;
        return engine->toScriptValue<void*>(0);
    }
}

QString JSKitXMLHttpRequest::responseText() const
{
    return QString::fromUtf8(_response);
}

void JSKitXMLHttpRequest::handleReplyFinished()
{
    if (!_reply) {
        logger()->info() << "reply finished too late";
        return;
    }

    _response = _reply->readAll();
    logger()->debug() << "reply finished, reply text:" << QString::fromUtf8(_response);

    emit readyStateChanged();
    emit statusChanged();
    emit statusTextChanged();
    emit responseChanged();
    emit responseTextChanged();

    if (_onload.isCallable()) {
        logger()->debug() << "going to call onload handler:" << _onload.toString();
        QJSValue result = _onload.callWithInstance(_mgr->engine()->newQObject(this));
        if (result.isError()) {
            logger()->warn() << "JS error on onload handler:" << JSKitManager::describeError(result);
        }
    } else {
        logger()->debug() << "No onload set";
    }
}

void JSKitXMLHttpRequest::handleReplyError(QNetworkReply::NetworkError code)
{
    if (!_reply) {
        logger()->info() << "reply error too late";
        return;
    }

    logger()->info() << "reply error" << code;

    emit readyStateChanged();
    emit statusChanged();
    emit statusTextChanged();

    if (_onerror.isCallable()) {
        logger()->debug() << "going to call onerror handler:" << _onload.toString();
        QJSValue result = _onerror.callWithInstance(_mgr->engine()->newQObject(this));
        if (result.isError()) {
            logger()->warn() << "JS error on onerror handler:" << JSKitManager::describeError(result);
        }
    }
}

JSKitGeolocation::JSKitGeolocation(JSKitManager *mgr)
    : QObject(mgr), _mgr(mgr), _source(0), _lastWatchId(0)
{
}

void JSKitGeolocation::getCurrentPosition(const QJSValue &successCallback, const QJSValue &errorCallback, const QVariantMap &options)
{
    setupWatcher(successCallback, errorCallback, options, true);
}

int JSKitGeolocation::watchPosition(const QJSValue &successCallback, const QJSValue &errorCallback, const QVariantMap &options)
{
    return setupWatcher(successCallback, errorCallback, options, false);
}

void JSKitGeolocation::clearWatch(int watchId)
{
    removeWatcher(watchId);
}

void JSKitGeolocation::handleError(QGeoPositionInfoSource::Error error)
{
    logger()->warn() << "positioning error: " << error;
    // TODO
}

void JSKitGeolocation::handlePosition(const QGeoPositionInfo &pos)
{
    logger()->debug() << "got position at" << pos.timestamp() << "type" << pos.coordinate().type();

    if (_watches.empty()) {
        logger()->warn() << "got position update but no one is watching";
        _source->stopUpdates(); // Just in case.
        return;
    }

    QJSValue obj = buildPositionObject(pos);

    for (auto it = _watches.begin(); it != _watches.end(); /*no adv*/) {
        invokeCallback(it->successCallback, obj);

        if (it->once) {
            it = _watches.erase(it);
        } else {
            it->timer.restart();
            ++it;
        }
    }
}

void JSKitGeolocation::handleTimeout()
{
    logger()->info() << "positioning timeout";

    if (_watches.empty()) {
        logger()->warn() << "got position timeout but no one is watching";
        _source->stopUpdates();
        return;
    }

    QJSValue obj = buildPositionErrorObject(TIMEOUT, "timeout");

    for (auto it = _watches.begin(); it != _watches.end(); /*no adv*/) {
        if (it->timer.hasExpired(it->timeout)) {
            logger()->info() << "positioning timeout for watch" << it->watchId
                             << ", watch is" << it->timer.elapsed() << "ms old, timeout is" << it->timeout;
            invokeCallback(it->errorCallback, obj);

            if (it->once) {
                it = _watches.erase(it);
            } else {
                it->timer.restart();
                ++it;
            }
        } else {
            ++it;
        }
    }

    QMetaObject::invokeMethod(this, "updateTimeouts", Qt::QueuedConnection);
}

void JSKitGeolocation::updateTimeouts()
{
    int once_timeout = -1, updates_timeout = -1;

    logger()->debug() << Q_FUNC_INFO;

    Q_FOREACH(const Watcher &watcher, _watches) {
        qint64 rem_timeout = watcher.timeout - watcher.timer.elapsed();
        logger()->debug() << "watch" << watcher.watchId << "rem timeout" << rem_timeout;
        if (rem_timeout >= 0) {
            // In case it is too large...
            rem_timeout = qMin<qint64>(rem_timeout, std::numeric_limits<int>::max());
            if (watcher.once) {
                once_timeout = once_timeout >= 0 ? qMin<int>(once_timeout, rem_timeout) : rem_timeout;
            } else {
                updates_timeout = updates_timeout >= 0 ? qMin<int>(updates_timeout, rem_timeout) : rem_timeout;
            }
        }
    }

    if (updates_timeout >= 0) {
        logger()->debug() << "setting location update interval to" << updates_timeout;
        _source->setUpdateInterval(updates_timeout);
        _source->startUpdates();
    } else {
        logger()->debug() << "stopping updates";
        _source->stopUpdates();
    }

    if (once_timeout >= 0) {
        logger()->debug() << "requesting single location update with timeout" << once_timeout;
        _source->requestUpdate(once_timeout);
    }
}

int JSKitGeolocation::setupWatcher(const QJSValue &successCallback, const QJSValue &errorCallback, const QVariantMap &options, bool once)
{
    Watcher watcher;
    watcher.successCallback = successCallback;
    watcher.errorCallback = errorCallback;
    watcher.highAccuracy = options.value("enableHighAccuracy").toBool();
    watcher.timeout = options.value("timeout", std::numeric_limits<int>::max() - 1).toInt();
    watcher.once = once;
    watcher.watchId = ++_lastWatchId;

    qlonglong maximumAge = options.value("maximumAge", 0).toLongLong();

    logger()->debug() << "setting up watcher, gps=" << watcher.highAccuracy << "timeout=" << watcher.timeout << "maximumAge=" << maximumAge << "once=" << once;

    if (!_source) {
        _source = QGeoPositionInfoSource::createDefaultSource(this);
        connect(_source, static_cast<void (QGeoPositionInfoSource::*)(QGeoPositionInfoSource::Error)>(&QGeoPositionInfoSource::error),
                this, &JSKitGeolocation::handleError);
        connect(_source, &QGeoPositionInfoSource::positionUpdated,
                this, &JSKitGeolocation::handlePosition);
        connect(_source, &QGeoPositionInfoSource::updateTimeout,
                this, &JSKitGeolocation::handleTimeout);
    }

    if (maximumAge > 0) {
        QDateTime threshold = QDateTime::currentDateTime().addMSecs(-qint64(maximumAge));
        QGeoPositionInfo pos = _source->lastKnownPosition(watcher.highAccuracy);
        logger()->debug() << "got pos timestamp" << pos.timestamp() << " but we want" << threshold;
        if (pos.isValid() && pos.timestamp() >= threshold) {
            invokeCallback(watcher.successCallback, buildPositionObject(pos));
            if (once) {
                return -1;
            }
        } else if (watcher.timeout == 0 && once) {
            // If the timeout has already expired, and we have no cached data
            // Do not even bother to turn on the GPS; return error object now.
            invokeCallback(watcher.errorCallback, buildPositionErrorObject(TIMEOUT, "no cached position"));
            return -1;
        }
    }

    watcher.timer.start();
    _watches.append(watcher);

    logger()->debug() << "added new watch" << watcher.watchId;

    QMetaObject::invokeMethod(this, "updateTimeouts", Qt::QueuedConnection);

    return watcher.watchId;
}

void JSKitGeolocation::removeWatcher(int watchId)
{
    Watcher watcher;

    logger()->debug() << "removing watchId" << watcher.watchId;

    for (int i = 0; i < _watches.size(); i++) {
        if (_watches[i].watchId == watchId) {
            watcher = _watches.takeAt(i);
            break;
        }
    }

    if (watcher.watchId != watchId) {
        logger()->warn() << "watchId not found";
        return;
    }

    QMetaObject::invokeMethod(this, "updateTimeouts", Qt::QueuedConnection);
}

QJSValue JSKitGeolocation::buildPositionObject(const QGeoPositionInfo &pos)
{
    QJSEngine *engine = _mgr->engine();
    QJSValue obj = engine->newObject();
    QJSValue coords = engine->newObject();
    QJSValue timestamp = engine->toScriptValue<quint64>(pos.timestamp().toMSecsSinceEpoch());

    coords.setProperty("latitude", engine->toScriptValue(pos.coordinate().latitude()));
    coords.setProperty("longitude", engine->toScriptValue(pos.coordinate().longitude()));
    if (pos.coordinate().type() == QGeoCoordinate::Coordinate3D) {
        coords.setProperty("altitude", engine->toScriptValue(pos.coordinate().altitude()));
    } else {
        coords.setProperty("altitude", engine->toScriptValue<void*>(0));
    }

    coords.setProperty("accuracy", engine->toScriptValue(pos.attribute(QGeoPositionInfo::HorizontalAccuracy)));

    if (pos.hasAttribute(QGeoPositionInfo::VerticalAccuracy)) {
        coords.setProperty("altitudeAccuracy", engine->toScriptValue(pos.attribute(QGeoPositionInfo::VerticalAccuracy)));
    } else {
        coords.setProperty("altitudeAccuracy", engine->toScriptValue<void*>(0));
    }

    if (pos.hasAttribute(QGeoPositionInfo::Direction)) {
        coords.setProperty("heading", engine->toScriptValue(pos.attribute(QGeoPositionInfo::Direction)));
    } else {
        coords.setProperty("heading", engine->toScriptValue<void*>(0));
    }

    if (pos.hasAttribute(QGeoPositionInfo::GroundSpeed)) {
        coords.setProperty("speed", engine->toScriptValue(pos.attribute(QGeoPositionInfo::GroundSpeed)));
    } else {
        coords.setProperty("speed", engine->toScriptValue<void*>(0));
    }

    obj.setProperty("coords", coords);
    obj.setProperty("timestamp", timestamp);

    return obj;
}

QJSValue JSKitGeolocation::buildPositionErrorObject(PositionError error, const QString &message)
{
    QJSEngine *engine = _mgr->engine();
    QJSValue obj = engine->newObject();

    obj.setProperty("code", engine->toScriptValue<unsigned short>(error));
    obj.setProperty("message", engine->toScriptValue(message));

    return obj;
}

void JSKitGeolocation::invokeCallback(QJSValue callback, QJSValue event)
{
    if (callback.isCallable()) {
        logger()->debug() << "invoking callback" << callback.toString();
        QJSValue result = callback.call(QJSValueList({event}));
        if (result.isError()) {
            logger()->warn() << "while invoking callback: " << JSKitManager::describeError(result);
        }
    } else {
        logger()->warn() << "callback is not callable";
    }
}