void JSKitXMLHttpRequest::handleReplyFinished()
{
    if (!m_reply) {
        qCDebug(l) << "reply finished too late";
        return;
    }

    m_response = m_reply->readAll();
    qCDebug(l) << "reply finished, reply text:" << QString::fromUtf8(m_response) << "status:" << status();

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

    if (m_onload.isCallable()) {
        qCDebug(l) << "going to call onload handler:" << m_onload.toString();

        QJSValue result = m_onload.callWithInstance(m_engine->newQObject(this));
        if (result.isError()) {
            qCWarning(l) << "JS error on onload handler:" << JSKitManager::describeError(result);
        }
    } else {
        qCDebug(l) << "No onload set";
    }

    if (m_onreadystatechange.isCallable()) {
        qCDebug(l) << "going to call onreadystatechange handler:" << m_onreadystatechange.toString();
        QJSValue result = m_onreadystatechange.callWithInstance(m_engine->newQObject(this));
        if (result.isError()) {
            qCWarning(l) << "JS error on onreadystatechange handler:" << JSKitManager::describeError(result);
        }
    }
}
QJsonValue JsonDbReduceDefinition::addObject(JsonDbReduceDefinition::FunctionNumber functionNumber,
                                             const QJsonValue &keyValue, QJsonValue previousValue, JsonDbObject object)
{
    initScriptEngine();
    QJSValue svKeyValue = mScriptEngine->toScriptValue(keyValue);
    if (!mTargetValueName.isEmpty())
        previousValue = previousValue.toObject().value(mTargetValueName);
    QJSValue svPreviousValue = mScriptEngine->toScriptValue(previousValue);
    QJSValue svObject = mScriptEngine->toScriptValue(static_cast<QJsonObject>(object));

    QJSValueList reduceArgs;
    reduceArgs << svKeyValue << svPreviousValue << svObject;
    QJSValue reduced = mFunctions[functionNumber].call(reduceArgs);

    if (!reduced.isUndefined() && !reduced.isError()) {
        QJsonValue jsonReduced = mScriptEngine->fromScriptValue<QJsonValue>(reduced);
        QJsonObject jsonReducedObject;
        if (!mTargetValueName.isEmpty())
            jsonReducedObject.insert(mTargetValueName, jsonReduced);
        else
            jsonReducedObject = jsonReduced.toObject();
        return jsonReducedObject;
    } else {

        if (reduced.isError())
            setError(QString::fromLatin1("Error executing %1 function: %2")
                     .arg((functionNumber == JsonDbReduceDefinition::Add ? QStringLiteral("add") : QStringLiteral("subtract")))
                     .arg(reduced.toString()));
        return QJsonValue(QJsonValue::Undefined);
    }
}
Bluemonkey::Bluemonkey(QObject *parent)
	:QObject(parent), engine(nullptr), configuration(std::map<std::string, std::string>())
{
	engine = new QJSEngine(this);

	QJSValue value = engine->newQObject(this);
	engine->globalObject().setProperty("bluemonkey", value);

	QJSValue val = engine->evaluate(bmJS);

	if(val.isError())
	{
		qCritical() << "Failed to load bluemonkey javascript extensions";
		qCritical() << "Error: ";
		qCritical() <<  val.property("name").toString();
		qCritical() <<  val.property("message").toString();
		qCritical() << "line: " << val.property("lineNumber").toString();

		int line = val.property("lineNumber").toInt();
		QStringList lines = bmJS.split("\n");

		if(line - 1 >= 0)
			qWarning() << lines.at(line-1);

		qWarning() << lines.at(line) << "<--";

		if(lines.size() > line + 1)
			qWarning() << lines.at(line+1);

		qCritical() << "Aborting";
		throw std::runtime_error("Die die die");
	}
}
示例#4
0
void
QPython::receive(QVariant variant)
{
    QVariantList list = variant.toList();
    QString event = list[0].toString();
    if (handlers.contains(event)) {
        QJSValue callback = handlers[event];
        QJSValueList args;
        for (int i=1; i<list.size(); i++) {
            args << callback.engine()->toScriptValue(list[i]);
        }
        QJSValue result = callback.call(args);
        if (result.isError()) {
            // Ideally we would throw the error back to Python (so that the
            // pyotherside.send() method fails, as this is where the call
            // originated). We can't do this, because the pyotherside.send()
            // call is asynchronous (it returns before we call into JS), so do
            // the next best thing and report the error to our error handler in
            // QML instead.
            emitError("pyotherside.send() failed handler: " +
                    result.property("fileName").toString() + ":" +
                    result.property("lineNumber").toString() + ": " +
                    result.toString());
        }
    } else {
        // Default action
        emit received(variant);
    }
}
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>");
}
示例#6
0
float JSEndpoint::peek() const {
    QJSValue result = _callable.call();
    if (result.isError()) {
        qCDebug(controllers).noquote() << formatException(result);
        return 0.0f;
    } else {
        return (float)result.toNumber();
    }
}
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;
    }
NatspecExpressionEvaluator::NatspecExpressionEvaluator(QString const& _abi, QString const& _transaction, QString const& _method)
: m_abi(_abi), m_transaction(_transaction), m_method(_method)
{
	Q_INIT_RESOURCE(natspec);
	QJSValue result = m_engine.evaluate(contentsOfQResource(":/natspec/natspec.js"));
	if (result.isError())
		BOOST_THROW_EXCEPTION(FileError());
	
	m_engine.evaluate("var natspec = require('natspec')");
}
示例#9
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;
}
示例#10
0
void MainWindow::on_pokeIt_clicked()
{
    //Executing some function from binded object
    QJSValue result = myEngine.evaluate("mainWindow.beep();");

    //Just for case, check a result
    if (result.isError())
    {
        //If script ran with errors
        QMessageBox::critical(this, "Script error", "HOLY #@&*?!\n"
                              "Look yourself what happen:\n" + result.toString() );
    }
}
示例#11
0
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) {
        qCDebug(l) << "invoking callback" << type << it->toString();
        QJSValue result = it->call(args);
        if (result.isError()) {
            qCWarning(l) << "error while invoking callback" << type << it->toString() << ":"
                             << JSKitManager::describeError(result);
        }
    }
}
示例#12
0
bool QmlCovPlugin::jsParse(QJSEngine *engine, const QString &content, QJSValue &value)
{
    QJSValue JSON = engine->evaluate("JSON");
    if (JSON.isError()) {
        qCritical() << "Uncaught exception:" << JSON.toString();
        return false;
    }

    QJSValue parse = JSON.property("parse");
    if (parse.isError()) {
        qCritical() << "Uncaught exception:" << parse.toString();
        return false;
    }

    QJSValue results = parse.callWithInstance(JSON, QJSValueList() << content);
    if (results.isError()) {
        qCritical() << "Uncaught exception:" << results.toString();
        return false;
    }

    value = results;

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

    for (QList<QJSValue>::iterator it = callbacks.begin(); it != callbacks.end(); ++it) {
        qCDebug(l) << "invoking callback" << type << it->toString();
        QJSValue result = it->callWithInstance(m_engine->newQObject(this), args);
        if (result.isError()) {
            qCWarning(l) << "error while invoking callback"
                << type << it->toString() << ":"
                << JSKitManager::describeError(result);
        }
    }
}
示例#14
0
bool QmlCovPlugin::jsStringify(QJSEngine *engine, const QJSValue &value, QString &content)
{
    QJSValue JSON = engine->evaluate("JSON");
    if (JSON.isError()) {
        qCritical() << "Uncaught exception:" << JSON.toString();
        return false;
    }

    QJSValue stringify = JSON.property("stringify");
    if (stringify.isError()) {
        qCritical() << "Uncaught exception:" << stringify.toString();
        return false;
    }

    QJSValue results = stringify.callWithInstance(JSON, QJSValueList() << value);
    if (results.isError()) {
        qCritical() << "Uncaught exception:" << results.toString();
        return false;
    }

    content = results.toString();

    return true;
}
示例#15
0
void
QPython::imported(bool result, QJSValue *callback)
{
    QJSValueList args;
    QJSValue v = callback->engine()->toScriptValue(QVariant(result));
    args << v;
    QJSValue callbackResult = callback->call(args);
    if (SINCE_API_VERSION(1, 2)) {
        if (callbackResult.isError()) {
            emitError(callbackResult.property("fileName").toString() + ":" +
                    callbackResult.property("lineNumber").toString() + ": " +
                    callbackResult.toString());
        }
    }
    delete callback;
}
示例#16
0
void ConsoleDock::executeScript()
{
    const QString script = mLineEdit->text();
    if (script.isEmpty())
        return;

    appendScript(script);

    const QJSValue result = ScriptManager::instance().evaluate(script);
    if (!result.isError() && !result.isUndefined())
        appendInfo(result.toString());

    mLineEdit->clear();

    mHistory.append(script);
    mHistoryPosition = mHistory.size();
}
bool TReactComponent::load(const QString &scriptFile)
{
    bool ok;
    if (QFileInfo(scriptFile).suffix().compare("jsx", Qt::CaseInsensitive) == 0) {
        // Loads JSX file
        QString program = compileJsxFile(scriptFile);
        QJSValue res = context->evaluate(program, scriptFile);
        ok = !res.isError();
    } else {
        ok = context->load(scriptFile);
    }

    if (ok) {
        loadedTime = QDateTime::currentDateTime();
        scriptPath = scriptFile;
    } else {
        loadedTime = QDateTime();
        scriptPath = QString();
    }
    return ok;
}
示例#18
0
void JSKitXMLHttpRequest::handleReplyError(QNetworkReply::NetworkError code)
{
    if (!_reply) {
        qCDebug(l) << "reply error too late";
        return;
    }

    qCDebug(l) << "reply error" << code;

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

    if (_onerror.isCallable()) {
        qCDebug(l) << "going to call onerror handler:" << _onload.toString();
        QJSValue result = _onerror.callWithInstance(_mgr->engine()->newQObject(this));
        if (result.isError()) {
            qCWarning(l) << "JS error on onerror handler:" << JSKitManager::describeError(result);
        }
    }
}
示例#19
0
bool TemplateEngine::evaluateBooleanJavaScriptExpression(QJSEngine &engine,
                                                         const QString &expression, bool *result,
                                                         QString *errorMessage)
{
    if (errorMessage)
        errorMessage->clear();
    if (result)
        *result = false;
    const QJSValue value = engine.evaluate(expression);
    if (value.isError()) {
        if (errorMessage)
            *errorMessage = QString::fromLatin1("Error in \"%1\": %2")
                .arg(expression, value.toString());
        return false;
    }
    // Try to convert to bool, be that an int or whatever.
    if (value.isBool()) {
        if (result)
            *result = value.toBool();
        return true;
    }
    if (value.isNumber()) {
        if (result)
            *result = !qFuzzyCompare(value.toNumber(), 0);
        return true;
    }
    if (value.isString()) {
        if (result)
            *result = !value.toString().isEmpty();
        return true;
    }
    if (errorMessage)
        *errorMessage = QString::fromLatin1("Cannot convert result of \"%1\" (\"%2\"to bool.")
            .arg(expression, value.toString());

    return false;
}
示例#20
0
void QFListener::dispatch(QFAppDispatcher *dispatcher,QString type, QJSValue message)
{

    if (m_waitFor.size() > 0) {
        dispatcher->waitFor(m_waitFor);
    }

    if (m_callback.isCallable()) {
        QJSValueList args;
        args << type << message;
        QJSValue ret = m_callback.call(args);

        if (ret.isError()) {
            QString message = QString("%1:%2: %3: %4")
                              .arg(ret.property("fileName").toString())
                              .arg(ret.property("lineNumber").toString())
                              .arg(ret.property("name").toString())
                              .arg(ret.property("message").toString());
            qWarning() << message;
        }
    }

    emit dispatched(type,message);
}
示例#21
0
void QFAppScriptRunnable::run(QJSValue message)
{
    QJSValueList args;
    if (m_isSignalCondition &&
        message.hasProperty("length")) {
        int count = message.property("length").toInt();
        for (int i = 0 ; i < count;i++) {
            args << message.property(i);
        }
    } else {
        args << message;
    }
    QJSValue ret = m_script.call(args);

    if (ret.isError()) {
        QString message = QString("%1:%2: %3: %4")
                          .arg(ret.property("fileName").toString())
                          .arg(ret.property("lineNumber").toString())
                          .arg(ret.property("name").toString())
                          .arg(ret.property("message").toString());
        qWarning() << message;
    }

}
示例#22
0
void JSEndpoint::apply(float newValue, const Pointer& source) {
    QJSValue result = _callable.call(QJSValueList({ QJSValue(newValue) }));
    if (result.isError()) {
        qCDebug(controllers).noquote() << formatException(result);
    }
}