예제 #1
0
void DbModel::insert(QString key, QJSValue callbackFunction)
{
    if(m_name.isEmpty() || key.isEmpty() ||  m_jsonDocument.isNull())
    {
        DEBUG << "cannot insert. name is empty or json document is null";
        if(callbackFunction.isCallable())
        {
            callbackFunction.call(QJSValueList() << 1);
        }
        return;
    }
    QJsonObject root = m_jsonDocument.object();
    QJsonValueRef _arrayRef = root.find(m_name).value();
    QJsonArray _arrayMain = _arrayRef.toArray();
    QVariantMap _obj;
    _obj.insert("name", key);
    _arrayMain.append(QJsonValue::fromVariant(_obj));
    root.insert(m_name, _arrayMain);
    m_jsonDocument.setObject(root);
    qDebug() << m_jsonDocument.toJson();
    saveDatabase();
    if(callbackFunction.isCallable())
    {
        callbackFunction.call(QJSValueList() << 0);
    }
    beginInsertRows(QModelIndex(), _arrayMain.count() - 1, _arrayMain.count() - 1);
    endInsertRows();
}
void JQNetworkClientForQml::sendVariantMapData(
        const QString &hostName,
        const quint16 &port,
        const QString &targetActionFlag,
        const QVariantMap &payloadData,
        QJSValue succeedCallback,
        QJSValue failCallback
    )
{
    if ( !succeedCallback.isCallable() )
    {
        qDebug() << "JQNetworkClientForQml::sendPayloadData: error, succeedCallback not callable";
        return;
    }

    if ( !failCallback.isCallable() )
    {
        qDebug() << "JQNetworkClientForQml::sendPayloadData: error, failCallback not callable";
        return;
    }

    if ( !jqNetworkClient_ )
    {
        qDebug() << "JQNetworkClientForQml::sendPayloadData: error, client need beginClient";
        return;
    }

    jqNetworkClient_->sendVariantMapData(
                hostName,
                port,
                targetActionFlag,
                payloadData,
                { }, // empty appendData
                [ this, succeedCallback ](const auto &, const auto &package)
                {
                    const auto &&received = QJsonDocument::fromJson( package->payloadData() ).object().toVariantMap();

                    QMetaObject::invokeMethod(
                                this,
                                "onSendSucceed",
                                Qt::QueuedConnection,
                                Q_ARG( QVariant, QVariant::fromValue( succeedCallback ) ),
                                Q_ARG( QVariant, received )
                            );
                },
                [ this, failCallback ](const auto &)
                {
                    QMetaObject::invokeMethod(
                                this,
                                "received",
                                Qt::QueuedConnection,
                                Q_ARG( QVariant, QVariant::fromValue( failCallback ) )
                            );
                }
            );
}
예제 #3
0
int JsonDbPartition::find(const QString &query, const QJSValue &options, const QJSValue &callback)
{
    QJSValue actualOptions = options;
    QJSValue actualCallback = callback;
    if (options.isCallable()) {
        if (!callback.isUndefined()) {
            qWarning() << "Callback should be the last parameter.";
            return -1;
        }
        actualCallback = actualOptions;
        actualOptions = QJSValue(QJSValue::UndefinedValue);
    }
    JsonDbQueryObject *newQuery = new JsonDbQueryObject();
    newQuery->setQuery(query);
    if (!actualOptions.isUndefined()) {
        QVariantMap opt = actualOptions.toVariant().toMap();
        if (opt.contains(QLatin1String("limit")))
            newQuery->setLimit(opt.value(QLatin1String("limit")).toInt());
        if (opt.contains(QLatin1String("bindings")))
            newQuery->setBindings(opt.value(QLatin1String("bindings")).toMap());
    }
    newQuery->setPartition(this);
    connect(newQuery, SIGNAL(finished()), this, SLOT(queryFinished()));
    connect(newQuery, SIGNAL(statusChanged(JsonDbQueryObject::Status)), this, SLOT(queryStatusChanged()));
    findCallbacks.insert(newQuery, actualCallback);
    newQuery->componentComplete();
    int id = newQuery->start();
    findIds.insert(newQuery, id);
    return id;
}
예제 #4
0
void JSKitPebble::timelineUnsubscribe(const QString &topic, QJSValue successCallback, QJSValue failureCallback)
{
    getTokenInternal([this,topic,&successCallback,failureCallback]()mutable{
        m_mgr->pebble()->tlSync()->topicUnsubscribe(m_timelineToken,topic,[this,successCallback,topic](const QString &ok)mutable{
            qCDebug(l) << "Successfully unsubscribed from" << topic << ok;
            if(successCallback.isCallable()) {
                successCallback.call(QJSValueList({ok}));
            }
        },[this,topic,failureCallback](const QString &err)mutable{
            qCDebug(l) << "Cannot unsubscribe from" << topic << err;
            if (failureCallback.isCallable()) {
                failureCallback.call(QJSValueList({err}));
            }
        });
    },failureCallback);
}
void JsonDbSortingListModel::setPropertyInjector(const QJSValue &callback)
{
    Q_D(JsonDbSortingListModel);
    d->injectCallback = callback;
    d->isCallable = callback.isCallable();
    refreshItems();
}
static QString qjsValueToString(const QJSValue &v)
{
  if (v.isArray()) {
    return QStringLiteral("<array>");
  } else if (v.isBool()) {
    return v.toBool() ? QStringLiteral("true") : QStringLiteral("false");
  } else if (v.isCallable()) {
    return QStringLiteral("<callable>");
  } else if (v.isDate()) {
    return v.toDateTime().toString();
  } else if (v.isError()) {
    return QStringLiteral("<error>");
  } else if (v.isNull()) {
    return QStringLiteral("<null>");
  } else if (v.isNumber()) {
    return QString::number(v.toNumber());
  } else if (v.isObject()) {
    return QStringLiteral("<object>");
  } else if (v.isQObject()) {
    return Util::displayString(v.toQObject());
  } else if (v.isRegExp()) {
    return QStringLiteral("<regexp>");
  } else if (v.isString()) {
    return v.toString();
  } else if (v.isUndefined()) {
    return QStringLiteral("<undefined>");
  } else if (v.isVariant()) {
    return VariantHandler::displayString(v.toVariant());
  }
  return QStringLiteral("<unknown QJSValue>");
}
예제 #7
0
int JsonDbPartition::create(const QJSValue &object,  const QJSValue &options, const QJSValue &callback)
{
    QJSValue actualOptions = options;
    QJSValue actualCallback = callback;
    if (options.isCallable()) {
        if (!callback.isUndefined()) {
            qWarning() << "Callback should be the last parameter.";
            return -1;
        }
        actualCallback = actualOptions;
        actualOptions = QJSValue(QJSValue::UndefinedValue);
    }
    //#TODO ADD options
    QVariant obj = qjsvalue_to_qvariant(object);
    QJsonDbWriteRequest *request(0);
    if (obj.type() == QVariant::List) {
        request = new QJsonDbCreateRequest(qvariantlist_to_qjsonobject_list(obj.toList()));
    } else {
        request = new QJsonDbCreateRequest(QJsonObject::fromVariantMap(obj.toMap()));
    }
    request->setPartition(_name);
    connect(request, SIGNAL(finished()), this, SLOT(requestFinished()));
    connect(request, SIGNAL(finished()), request, SLOT(deleteLater()));
    connect(request, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)),
            this, SLOT(requestError(QtJsonDb::QJsonDbRequest::ErrorCode,QString)));
    connect(request, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)),
            request, SLOT(deleteLater()));
    JsonDatabase::sharedConnection().send(request);
    writeCallbacks.insert(request, actualCallback);
    return request->property("requestId").toInt();
}
예제 #8
0
void JSKitPebble::getTimelineToken(QJSValue successCallback, QJSValue failureCallback)
{
    getTokenInternal([this,successCallback]()mutable{
        if(successCallback.isCallable()) {
            successCallback.call(QJSValueList({m_timelineToken}));
        }
    },failureCallback);
}
예제 #9
0
void
QPython::call(QVariant func, QVariant args, QJSValue callback)
{
    QJSValue *cb = 0;
    if (!callback.isNull() && !callback.isUndefined() && callback.isCallable()) {
        cb = new QJSValue(callback);
    }
    emit process(func, args, cb);
}
예제 #10
0
void
QPython::importModule(QString name, QJSValue callback)
{
    QJSValue *cb = 0;
    if (!callback.isNull() && !callback.isUndefined() && callback.isCallable()) {
        cb = new QJSValue(callback);
    }
    emit import(name, cb);
}
예제 #11
0
void
QPython::setHandler(QString event, QJSValue callback)
{
    if (!callback.isCallable() || callback.isNull() || callback.isUndefined()) {
        handlers.remove(event);
    } else {
        handlers[event] = callback;
    }
}
예제 #12
0
void ReportItemPara::setTextFn(const QJSValue &val)
{
	if(val.isCallable()) {
		m_getTextJsFn = val;
	}
	else {
		qfError() << "JavaScript callable value (aka function) must be set to textFn property.";
	}
}
예제 #13
0
bool JsonDbReduceDefinition::compileFunctions(QJSEngine *scriptEngine, QJsonObject definition, JsonDbJoinProxy *proxy,
                                              QVector<QJSValue> &functions, QString &message)
{
    bool status = true;
    QStringList functionNames = (QStringList()
                                 << QLatin1String("add")
                                 << QLatin1String("subtract")
                                 << QLatin1String("sourceKeyFunction"));
    int i = 0;
    functions.resize(3);
    foreach (const QString &functionName, functionNames) {
        int functionNumber = i++;
        if (!definition.contains(functionName))
            continue;
        QString script = definition.value(functionName).toString();
        QString jsonDbBinding = proxy
            ? QStringLiteral("{createUuidFromString: proxy.createUuidFromString}")
            : QStringLiteral("{}"); // strict mode causes the above to fail if proxy is undefined

        // first, package it as a function that takes a jsondb proxy and returns the add/subtract function
        QJSValue moduleFunction = scriptEngine->evaluate(QString::fromLatin1("(function (proxy) { %3 var jsondb = %2; return (%1); })")
                                                         .arg(script)
                                                         .arg(jsonDbBinding)
                                                         .arg(jsondbSettings->useStrictMode() ? QLatin1Literal("\"use strict\"; ") : QLatin1Literal("/* use nonstrict mode */")));

        if (moduleFunction.isError() || !moduleFunction.isCallable()) {
            message = QString::fromLatin1("Unable to parse %1 function: %2").arg(functionName).arg(moduleFunction.toString());
            status = false;
            continue;
        }

        // now pass it the jsondb proxy to get the add/subtract function
        QJSValueList args;
        if (proxy)
            args << scriptEngine->newQObject(proxy);
        else
            args << QJSValue(QJSValue::UndefinedValue);
        QJSValue function = moduleFunction.call(args);
        if (function.isError() || !function.isCallable()) {
            message = QString::fromLatin1("Unable to evaluate %1 function: %2").arg(functionName).arg(function.toString());
            status = false;
        }
        functions[functionNumber] = function;
    }
예제 #14
0
uint JSKitPebble::sendAppMessage(QJSValue message, QJSValue callbackForAck, QJSValue callbackForNack)
{
    QVariantMap data = message.toVariant().toMap();
    QPointer<JSKitPebble> pebbObj = this;
    uint transactionId = m_mgr->m_appmsg->nextTransactionId();

    qCDebug(l) << "sendAppMessage" << data;

    m_mgr->m_appmsg->send(
        m_appInfo.uuid(),
        data,
        [this, pebbObj, transactionId, callbackForAck]() mutable {
            if (pebbObj.isNull()) return;

            if (callbackForAck.isCallable()) {
                QJSValue event = pebbObj->buildAckEventObject(transactionId);
                QJSValue result = callbackForAck.call(QJSValueList({event}));

                if (result.isError()) {
                    qCWarning(l) << "error while invoking ACK callback"
                        << callbackForAck.toString() << ":"
                        << JSKitManager::describeError(result);
                }
            }
        },
        [this, pebbObj, transactionId, callbackForNack]() mutable {
            if (pebbObj.isNull()) return;

            if (callbackForNack.isCallable()) {
                QJSValue event = pebbObj->buildAckEventObject(transactionId, "NACK from watch");
                QJSValue result = callbackForNack.call(QJSValueList({event}));

                if (result.isError()) {
                    qCWarning(l) << "error while invoking NACK callback"
                        << callbackForNack.toString() << ":"
                        << JSKitManager::describeError(result);
                }
            }
        }
    );

    return transactionId;
}
예제 #15
0
QJSValue Request::patch(const QJSValue &url, const QJSValue &data, const QJSValue &fn) const
{
    RequestPrototype *proto = new RequestPrototype(
                m_engine,
                RequestPrototype::Patch,
                QUrl(url.toString()));

    if (data.isCallable()) {
        proto->end(data);
    } else if (!data.isUndefined()){
        proto->send(data);
    }

    if (fn.isCallable()) {
        proto->end(fn);
    }

    return proto->self();
}
예제 #16
0
void JSKitPebble::getTimelineToken(QJSValue successCallback, QJSValue failureCallback)
{
    //TODO actually implement this
    qCDebug(l) << "call to unsupported method Pebble.getTimelineToken";
    Q_UNUSED(successCallback);

    if (failureCallback.isCallable()) {
        failureCallback.call();
    }
}
예제 #17
0
void JSKitPebble::timelineSubscriptions(QJSValue successCallback, QJSValue failureCallback)
{
    getTokenInternal([this,&successCallback,&failureCallback](){
        m_mgr->pebble()->tlSync()->getSubscriptions(m_timelineToken,[this,successCallback](const QStringList &topics)mutable{
            qCDebug(l) << "Successfully fetched subscriptions:" << topics.join(", ");
            if(successCallback.isCallable()) {
                QJSValue argArray = m_mgr->engine()->newArray(topics.size());
                for (int i = 0; i < topics.size(); i++) {
                    argArray.setProperty(i, topics.at(i));
                }
                successCallback.call(QJSValueList({argArray}));
            }
        },[failureCallback](const QString &err)mutable{
            if (failureCallback.isCallable()) {
                failureCallback.call(QJSValueList({err}));
            }
        });
    },failureCallback);
}
예제 #18
0
void JSKitPebble::timelineUnsubscribe(const QString &topic, QJSValue successCallback, QJSValue failureCallback)
{
    //TODO actually implement this
    qCDebug(l) << "call to unsupported method Pebble.timelineUnsubscribe";
    Q_UNUSED(topic);
    Q_UNUSED(successCallback);

    if (failureCallback.isCallable()) {
        failureCallback.call();
    }
}
예제 #19
0
void Promise::complete(QJSValue fn, const QVariantList &arguments)
{
  QJSValueList list;
  for (const QVariant &item : arguments) {
    list << mEngine->toScriptValue(item);
  }

  if (fn.isCallable()) {
    fn.call(list);
  }
}
예제 #20
0
QJSValue Request::del(const QJSValue &url, const QJSValue &fn) const
{
    RequestPrototype *proto = new RequestPrototype(
                m_engine,
                RequestPrototype::Delete,
                QUrl(url.toString()));

    if (fn.isCallable()) {
        proto->end(fn);
    }

    return proto->self();
}
예제 #21
0
ServicesBase::CallbackType ServicesBase::fromJSCallback(QJSValue callback)
{
    CallbackType cb = [callback] (int errorType, QString jsonStr) mutable
    {
        if (callback.isCallable())
        {
            QJSValueList args;
            args << QJSValue(errorType) << QJSValue(jsonStr);
            callback.call(args);
        }
    };
    return cb;
}
예제 #22
0
void JSKitPebble::getTokenInternal(Func ack, QJSValue &failureCallback)
{
    if(!m_timelineToken.isEmpty()) {
        ack();
        return;
    }
    m_mgr->pebble()->tlSync()->getTimelineToken(m_appInfo.uuid(),
       [this,failureCallback,ack](const QString &ret)mutable{
        m_timelineToken = ret;
        if(m_timelineToken.isEmpty()) {
            if (failureCallback.isCallable()) {
                failureCallback.call(QJSValueList({"Unknown Error: token is empty"}));
            }
        } else {
            ack();
        }
    }, [failureCallback](const QString &err)mutable{
        if (failureCallback.isCallable()) {
            failureCallback.call(QJSValueList({err}));
        }
    });
}
예제 #23
0
void SortFilterModel::setFilterCallback(const QJSValue& callback)
{
    if (m_filterCallback.strictlyEquals(callback)) {
        return;
    }

    if (!callback.isNull() && !callback.isCallable()) {
        return;
    }

    m_filterCallback = callback;
    invalidateFilter();

    emit filterCallbackChanged(callback);
}
예제 #24
0
// find value using a callback
int ValueModel::find(QJSValue callback, int fromRow) const
{
    if(!callback.isCallable()) {
        return -1;
    }
    if(fromRow < 0 || fromRow >= m_data.count()) {
        return -1;
    }

    for(int i=fromRow; i<m_data.count(); i++) {
        QJSValue value = get(i);
        QJSValueList args({ value });
        if(callback.call(args).toBool()) {
            return i;
        }
    }
    return -1;
}
예제 #25
0
void JsonDatabase::listPartitions(const QJSValue &listCallback)
{
    if (!listCallback.isCallable()) {
        qWarning() << "Invalid callback specified.";
        return;
    }

    QJsonDbReadRequest *request = new QJsonDbReadRequest;
    request->setQuery(QStringLiteral("[?_type=\"Partition\"]"));
    request->setPartition(QStringLiteral("Ephemeral"));
    connect(request, SIGNAL(finished()), this, SLOT(onQueryFinished()));
    connect(request, SIGNAL(finished()), request, SLOT(deleteLater()));
    connect(request, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)),
            this, SLOT(onQueryError(QtJsonDb::QJsonDbRequest::ErrorCode,QString)));
    connect(request, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)),
            request, SLOT(deleteLater()));
    sharedConnection().send(request);
    listCallbacks.insert(request, listCallback);
}
예제 #26
0
void JsonDbPartition::queryFinished()
{
    JsonDbQueryObject *object = qobject_cast<JsonDbQueryObject*>(sender());
    if (object) {
        int id = findIds.value(object);
        QJSValue callback = findCallbacks.value(object);
        QJSEngine *engine = callback.engine();
        if (engine && callback.isCallable()) {
            QJSValueList args;
            // object : id  , statenumber , items
            QJSValue response= engine->newObject();
            response.setProperty(JsonDbStrings::Protocol::stateNumber(), object->stateNumber());
            response.setProperty(JsonDbStrings::Protocol::requestId(),  id);
            response.setProperty(QLatin1String("items"), object->takeResults());
            args << QJSValue(QJSValue::UndefinedValue) << response;
            callback.call(args);
        }
        findIds.remove(object);
        findCallbacks.remove(object);
        object->deleteLater();
    }
}
예제 #27
0
/*!
 * \internal
 * Only visible from QML.
 */
bool QQuickItem::grabToImage(const QJSValue &callback, const QSize &targetSize)
{
    QQmlEngine *engine = qmlEngine(this);
    if (!engine) {
        qWarning("Item::grabToImage: no QML Engine");
        return false;
    }

    if (!callback.isCallable()) {
        qWarning("Item::grabToImage: 'callback' is not a function");
        return false;
    }

    QSize size = targetSize;
    if (size.isEmpty())
        size = QSize(width(), height());

    if (size.width() < 1 || size.height() < 1) {
        qWarning("Item::grabToImage: item has invalid dimensions");
        return false;
    }

    if (!window()) {
        qWarning("Item::grabToImage: item is not attached to a window");
        return false;
    }

    QQuickItemGrabResult *result = QQuickItemGrabResultPrivate::create(this, size);
    if (!result)
        return false;

    connect(window(), &QQuickWindow::beforeSynchronizing, result, &QQuickItemGrabResult::setup, Qt::DirectConnection);
    connect(window(), &QQuickWindow::afterRendering, result, &QQuickItemGrabResult::render, Qt::DirectConnection);

    QQuickItemGrabResultPrivate *d = result->d_func();
    d->qmlEngine = engine;
    d->callback = callback;
    return true;
}
예제 #28
0
void JsonDbPartition::queryStatusChanged()
{
    JsonDbQueryObject *object = qobject_cast<JsonDbQueryObject*>(sender());
    if (object && object->status() == JsonDbQueryObject::Error) {
        int id = findIds.value(object);
        QJSValue callback = findCallbacks.value(object);
        QJSEngine *engine = callback.engine();
        if (engine && callback.isCallable()) {
            QJSValueList args;

            QJSValue response = engine->newObject();
            response.setProperty(JsonDbStrings::Protocol::stateNumber(), -1);
            response.setProperty(JsonDbStrings::Protocol::requestId(),  id);
            response.setProperty(QLatin1String("items"), engine->newArray());

            args << engine->toScriptValue(object->error())<< response;
            callback.call(args);
        }
        findIds.remove(object);
        findCallbacks.remove(object);
        object->deleteLater();
    }

}
예제 #29
0
void MediaFrame::get(QJSValue successCallback, QJSValue errorCallback)
{
    int size = m_allFiles.count() - 1;

    QString path;
    QString errorMessage = QString("");
    QJSValueList args;

    if(size < 1) {
        if(size == 0) {
            path = m_allFiles.at(0);

            if(successCallback.isCallable())
            {
                args << QJSValue(path);
                successCallback.call(args);
            }
            return;
        } else {
            errorMessage = "No files available";
            qWarning() << errorMessage;

            args << QJSValue(errorMessage);
            errorCallback.call(args);
            return;
        }
    }

    if(m_random) {
        path = m_allFiles.at(this->random(0, size));
    } else {
        path = m_allFiles.at(m_next);
        m_next++;
        if(m_next > size)
        {
            qDebug() << "Resetting next count from" << m_next << "due to queue size" << size;
            m_next = 0;
        }

    }

    QUrl url = QUrl(path);

    if(url.isValid()) {
        QString localPath = url.toString(QUrl::PreferLocalFile);

        if (!isFile(localPath)) {
            m_filename = path.section('/', -1);

            QString cachedFile = getCacheDirectory()+QLatin1Char('/')+hash(path)+QLatin1Char('_')+m_filename;

            if(isFile(cachedFile)) {
                // File has been cached
                qDebug() << path << "is cached as" << cachedFile;

                if(successCallback.isCallable()) {
                    args << QJSValue(cachedFile);
                    successCallback.call(args);
                }
                return;
            }

            m_successCallback = successCallback;
            m_errorCallback = errorCallback;
            m_filename = cachedFile;

            qDebug() << path << "doesn't exist locally, trying remote.";

            KIO::StoredTransferJob * job = KIO::storedGet( url, KIO::NoReload, KIO::HideProgressInfo);
            connect(job, SIGNAL(finished(KJob*)), this, SLOT(slotFinished(KJob*)));

        } else {
예제 #30
0
파일: Model.cpp 프로젝트: komadori/HsQML
void HsQMLAutoListModel::setKeyFunction(const QJSValue& keyFunction)
{
    mKeyFunction = keyFunction;
    mKeyFunctionValid = keyFunction.isCallable();
    mRehash = true;
}