예제 #1
0
QJSValue Image::read(const QJSValue& options)
{
    QByteArray format = m_reader->format();
    int quality = -1;

    if (options.isObject()) {
        QJSValue transcodeOptions = options.property("transcode");
        if (!transcodeOptions.isUndefined()) {
            QJSValue f = transcodeOptions.property("format");
            if (!f.isUndefined())
                format = f.toString().toUtf8();

            QJSValue q = transcodeOptions.property("quality");
            if (!q.isUndefined())
                quality = q.toInt();
        }
    }

    QImage img = m_reader->read();
    QBuffer buffer(&m_data);
    buffer.open(QIODevice::WriteOnly);
    img.save(&buffer, format.constData(), quality);
    m_mimeType = QStringLiteral("image/%1")
        .arg(QString::fromLatin1(format.constData()));

    return self();
}
예제 #2
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;
}
예제 #3
0
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());
                }

                qCDebug(l) << "passed an ArrayBufferView of" << byteData.length() << "bytes";
            } else {
                qCWarning(l) << "passed an unknown/invalid ArrayBuffer" << data.toString();
            }
        } else {
            qCWarning(l) << "passed an unknown object" << data.toString();
        }

    }

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

    qCDebug(l) << "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);
    }
}
예제 #4
0
void QQuickWebEngineViewExperimental::findText(const QString &subString, FindFlags options, const QJSValue &callback)
{
    if (subString.isEmpty()) {
        d_ptr->adapter->stopFinding();
        if (!callback.isUndefined()) {
            QJSValueList args;
            args.append(QJSValue(0));
            const_cast<QJSValue&>(callback).call(args);
        }
    } else {
        quint64 requestId = d_ptr->adapter->findText(subString, options & FindCaseSensitively, options & FindBackward);
        if (!callback.isUndefined())
            d_ptr->m_callbacks.insert(requestId, callback);
    }
}
void tst_QJSValueIterator::iterateOverObjectFromDeletedEngine()
{
    QJSEngine *engine = new QJSEngine;
    QJSValue objet = engine->newObject();

    // populate object with properties
    QHash<QString, int> properties;
    properties.insert("foo",1235);
    properties.insert("oof",5321);
    properties.insert("ofo",3521);
    QHash<QString, int>::const_iterator i = properties.constBegin();
    for (; i != properties.constEnd(); ++i) {
        objet.setProperty(i.key(), i.value());
    }

    // start iterating
    QJSValueIterator it(objet);
    it.next();
    QVERIFY(properties.contains(it.name()));

    delete engine;

    QVERIFY(objet.isUndefined());
    QVERIFY(it.name().isEmpty());
    QVERIFY(it.value().isUndefined());

    QVERIFY(!it.hasNext());
    it.next();

    QVERIFY(it.name().isEmpty());
    QVERIFY(it.value().isUndefined());

}
예제 #6
0
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);
            qCDebug(l) << "returning ArrayBuffer of" << _response.size() << "bytes";
        } else {
            qCWarning(l) << "Cannot find proto of ArrayBuffer";
        }
        return arrayBuf;
    } else {
        qCWarning(l) << "unsupported responseType:" << _responseType;
        return engine->toScriptValue<void*>(0);
    }
}
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>");
}
void InstagramClient::login(QString username, QString password, QJSValue callback)
{
    qDebug() << SETTINGS_PATH;
    qDebug() << phoneIDConfItem->key();

    QJsonObject json;
    json["phone_id"] = phoneID();
    //json["_csrftoken"] = createCleanedUuid().remove(QChar('-'));
    json["username"] = username;
    json["guid"] = guid();
    json["device_id"] = deviceID();
    json["password"] = password;
    json["login_attempt_count"] = 0;

    QByteArray body = this->getSignedBody(json);

    qDebug() << "Signed Body:" << body;


    auto key = QUuid::createUuid();

    if (!callback.isUndefined())
        callbacks->insert(key, callback);

    QNetworkRequest req(QUrl("https://i.instagram.com/api/v1/accounts/login/"));
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded; charset=UTF-8");
    req.setAttribute(QNetworkRequest::User, key);

    this->setRequiredHeaders(req);

    loginNetworkAccessManager->setCookieJar(DConfCookieJar::createTemporaryCookieJar(this));
    loginNetworkAccessManager->post(req, body);
}
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);
    }
}
예제 #10
0
bool QmlCovPlugin::saveCoverageData(QJSEngine *scriptEngine)
{
    Q_ASSERT(scriptEngine);
    Q_ASSERT(!g_coverageData.isUndefined());

    QString path = QmlCovPlugin::coverageFilePath();

    QString content;
    bool okay = jsStringify(scriptEngine, g_coverageData, content);

    if (!okay) {
        return false;
    }

    QFile outFile(path);
    if (!outFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        qCritical() << "Cannot write" << path << ":" << outFile.errorString();
        return false;
    }

    QTextStream stream( &outFile );
    stream << content;
    outFile.close();

    return true;
}
예제 #11
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();
}
예제 #12
0
void QQuickWebEngineView::runJavaScript(const QString &script, const QJSValue &callback)
{
    Q_D(QQuickWebEngineView);
    if (!callback.isUndefined()) {
        quint64 requestId = d_ptr->adapter->runJavaScriptCallbackResult(script);
        d->m_callbacks.insert(requestId, callback);
    } else
        d->adapter->runJavaScript(script);
}
예제 #13
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);
}
예제 #14
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);
}
예제 #15
0
void
QPython::setHandler(QString event, QJSValue callback)
{
    if (!callback.isCallable() || callback.isNull() || callback.isUndefined()) {
        handlers.remove(event);
    } else {
        handlers[event] = callback;
    }
}
예제 #16
0
ServerBookmarksImportDialog::ServerBookmarksImportDialog(
        QJSValue bookmarks, MainWindow *mainWindow, QWidget *parent) :
        MasterDialog(parent),
        ui(new Ui::ServerBookmarksImportDialog) {
    ui->setupUi(this);
    ui->infoLabel->clear();

    // init the iterator for the versions
    QJSValueIterator bookmarksIterator(bookmarks);

    QJsonArray bookmarkList;
    QString url;
    QString title;
    QString description;
    QStringList tags;
    int bookmarksCount = 0;
    qDebug() << __func__ << " - 'jsonObject': " << jsonObject;

    // iterate over the bookmarks
    while (bookmarksIterator.hasNext()) {
        bookmarksIterator.next();

        QJSValue property = bookmarksIterator.value().property("url");

        if (property.isUndefined()) {
            continue;
        }

        url = property.toString();

        if (url == "") {
            continue;
        }

        title = bookmarksIterator.value().property("title").toString();
        description = bookmarksIterator.value().property("description")
                .toString().remove("#");
        tags = bookmarksIterator.value().property("tags").toVariant()
                .toStringList();

        Q_FOREACH(QString tag, tags) {
                description.prepend("#" + tag.replace(" ", "-") + " ");
        }

        QJsonObject data {
                {"name", title},
                {"url", url},
                {"description", description.trimmed()}
        };
        
        bookmarkList.append(data);
        bookmarksCount++;
    }
예제 #17
0
static QJSValue coverage_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine)

    QJSValue example = scriptEngine->newObject();
    if (g_coverageData.isUndefined()) {
        g_engine = engine;
        g_coverageData = QmlCovPlugin::loadCoverageData(scriptEngine);
        example.setProperty("data", g_coverageData);
    }
    return example;
}
예제 #18
0
파일: consoledock.cpp 프로젝트: bjorn/tiled
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();
}
예제 #19
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();
}
QVariantList DeclarativeDBusInterface::argumentsFromScriptValue(const QJSValue &arguments)
{
    QVariantList dbusArguments;

    if (arguments.isArray()) {
        QJSValueIterator it(arguments);
        while (it.hasNext()) {
            it.next();
            // Arrays carry the size as last value
            if (!it.hasNext())
                continue;
            dbusArguments.append(it.value().toVariant());
        }
    } else if (!arguments.isUndefined()) {
        dbusArguments.append(arguments.toVariant());
    }

    return dbusArguments;
}
예제 #21
0
TrashDialog::TrashDialog(QJSValue notes, MainWindow *mainWindow,
                         QWidget *parent) :
        MasterDialog(parent),
        ui(new Ui::TrashDialog) {
    this->mainWindow = mainWindow;
    ui->setupUi(this);

    setupMainSplitter();

    QPushButton *button;
    ui->buttonBox->clear();

    button = new QPushButton(tr("&Restore selected note on server"));
    button->setToolTip(tr("<h3>Slower, but with note versions</h3>"
          "<p>The note will be restored on your ownCloud "
                                  "server with all versions.</p>"
          "<p>You will have to wait until it is synced to "
                                  "QOwnNotes by ownCloud sync.</p>"));
    button->setProperty("ActionRole", RestoreOnServer);
    button->setDefault(false);
    button->setIcon(
            QIcon::fromTheme(
                    "view-restore",
                    QIcon(":/icons/breeze-qownnotes/16x16/view-restore.svg")));
    ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole);

    button = new QPushButton(tr("&Download selected note"));
    button->setToolTip(tr("<h3>Faster, but without versions</h3>"
          "<p>The note will be created with the text from the preview.</p>"
          "<p>The note versions on your ownCloud server will not be restored "
                                  "and the note will remain in the trash.</p>"
          "<p>You can always restore the note and its versions later.</p>"));
    button->setProperty("ActionRole", Download);
    button->setDefault(false);
    button->setIcon(
            QIcon::fromTheme(
                    "edit-download",
                    QIcon(":/icons/breeze-qownnotes/16x16/edit-download.svg")));
    ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole);

    button = new QPushButton(tr("&Cancel"));
    button->setProperty("ActionRole", Cancel);
    button->setIcon(
            QIcon::fromTheme(
                    "dialog-cancel",
                    QIcon(":/icons/breeze-qownnotes/16x16/dialog-cancel.svg")));
    button->setDefault(true);
    ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole);

    connect(this->ui->buttonBox, SIGNAL(clicked(QAbstractButton *)),
            SLOT(dialogButtonClicked(QAbstractButton *)));
    connect(this, SIGNAL(finished(int)), this, SLOT(storeSettings()));

    QString itemName;
    QString dateString;
    QString data;
    int timestamp;
    ui->trashListWidget->clear();
    dataList = new QStringList();
    timestampList = new QList<int>;

    // init the iterator for the versions
    QJSValueIterator notesIterator(notes);

    // iterate over the trashed notes
    while (notesIterator.hasNext()) {
        notesIterator.next();

        QJSValue property = notesIterator.value().property("noteName");

        if (property.isUndefined()) {
            continue;
        }

        itemName = property.toString();

        if (itemName == "") {
            continue;
        }

        dateString = notesIterator.value().property("dateString").toString();
        data = notesIterator.value().property("data").toString();
        timestamp = notesIterator.value().property("timestamp").toInt();
        QString fileName =
                notesIterator.value().property("fileName").toString();

        QListWidgetItem *item = new QListWidgetItem();
        item->setText(itemName);
        item->setData(Qt::UserRole, fileName);
        item->setToolTip(dateString);
        ui->trashListWidget->addItem(item);
        dataList->append(data);
        timestampList->append(timestamp);
    }

    ui->trashListWidget->setCurrentRow(0);
    ui->noteBrowser->setText(dataList->at(0));
}