Example #1
0
void MainWindow::loadSettings()
{
	QVariantHash settings;
	QString settingsSavePath;

	qDebug() << "loading settings";

	settingsSavePath = QString("%1/Hussein.conf").arg(QCoreApplication::applicationDirPath());

	JsonSerializer::deserializeSettings(settingsSavePath, settings);

	if ( settings.contains(tr("geometry")) )
		restoreGeometry(QByteArray::fromHex(settings.value(tr("geometry"), QByteArray()).toByteArray()));

	if ( settings.contains(tr("state")) )
		restoreState(QByteArray::fromHex(settings.value(tr("state"), QByteArray()).toByteArray()));

	if ( settings.contains(tr("files")) )
		openFiles(settings.value(tr("files"), QStringList()).toStringList());

	if ( settings.contains(tr("current")) )
		ui->tabWidget->setCurrentIndex( settings.value(tr("current"), -1).toInt() );
}
Example #2
0
void AVEncoder::setOptions(const QVariantHash &dict)
{
    DPTR_D(AVEncoder);
    d.options = dict;
    // if dict is empty, can not return here, default options will be set for AVCodecContext
    // apply to AVCodecContext
    d.applyOptionsForContext();
    /* set AVEncoder meta properties.
     * we do not check whether the property exists thus we can set dynamic properties.
     */
    if (dict.isEmpty())
        return;
    if (name() == "avcodec")
        return;
    QVariant opt;
    if (dict.contains(name()))
        opt = dict.value(name());
    else if (dict.contains(name().toLower()))
        opt = dict.value(name().toLower());
    else
        return; // TODO: set property if no name() key found?
    Internal::setOptionsForQObject(opt, this);
}
Example #3
0
RssArticlePtr hashToRssArticle(RssFeed* parent, const QVariantHash& h) {
  const QString guid = h.value("id").toString();
  if (guid.isEmpty())
    return RssArticlePtr();

  RssArticlePtr art(new RssArticle(parent, guid));
  art->m_title = h.value("title", "").toString();
  art->m_torrentUrl = h.value("torrent_url", "").toString();
  art->m_link = h.value("news_link", "").toString();
  art->m_description = h.value("description").toString();
  art->m_date = h.value("date").toDateTime();
  art->m_author = h.value("author").toString();
  art->m_read = h.value("read", false).toBool();

  return art;
}
Example #4
0
bool GeoIPDatabase::parseMetadata(const QVariantHash &metadata, QString &error)
{
    const QString errMsgNotFound = tr("Metadata error: '%1' entry not found.");
    const QString errMsgInvalid = tr("Metadata error: '%1' entry has invalid type.");

    qDebug() << "Parsing MaxMindDB metadata...";

    CHECK_METADATA_REQ(binary_format_major_version, UShort);
    CHECK_METADATA_REQ(binary_format_minor_version, UShort);
    uint versionMajor = metadata.value("binary_format_major_version").toUInt();
    uint versionMinor = metadata.value("binary_format_minor_version").toUInt();
    if (versionMajor != 2) {
        error = tr("Unsupported database version: %1.%2").arg(versionMajor).arg(versionMinor);
        return false;
    }

    CHECK_METADATA_REQ(ip_version, UShort);
    m_ipVersion = metadata.value("ip_version").value<quint16>();
    if (m_ipVersion != 6) {
        error = tr("Unsupported IP version: %1").arg(m_ipVersion);
        return false;
    }

    CHECK_METADATA_REQ(record_size, UShort);
    m_recordSize = metadata.value("record_size").value<quint16>();
    if (m_recordSize != 24) {
        error = tr("Unsupported record size: %1").arg(m_recordSize);
        return false;
    }
    m_nodeSize = m_recordSize / 4;
    m_recordBytes = m_nodeSize / 2;

    CHECK_METADATA_REQ(node_count, UInt);
    m_nodeCount = metadata.value("node_count").value<quint32>();
    m_indexSize = m_nodeCount * m_nodeSize;

    CHECK_METADATA_REQ(database_type, QString);
    QString dbType = metadata.value("database_type").toString();
    if (dbType != DB_TYPE) {
        error = tr("Invalid database type: %1").arg(dbType);
        return false;
    }

    CHECK_METADATA_REQ(build_epoch, ULongLong);
    m_buildEpoch = QDateTime::fromTime_t(metadata.value("build_epoch").toULongLong());

    CHECK_METADATA_OPT(languages, QVariantList);
    CHECK_METADATA_OPT(description, QVariantHash);

    return true;
}
void DFMSideBarDeviceItem::doUnmountOrEject()
{
    QVariantHash info = getExtensionPropertys();

    if (info.value("isRemovable", false).toBool() && info.value("canEject", false).toBool()) {
        gvfsMountManager->eject(info.value("deviceId").toString());
        return;
    }

    if (info.value("canUnmount", false).toBool()) {
        gvfsMountManager->unmount(info.value("deviceId").toString());
    }

    if (info.value("canStop", false).toBool()) {
        DUrl deviceIdUrl;
        deviceIdUrl.setQuery(info.value("deviceId").toString());
        AppController::instance()->actionSafelyRemoveDrive(dMakeEventPointer<DFMUrlBaseEvent>(this, deviceIdUrl));
    }
}
bool RegisterFileTypeOperation::undoOperation()
{
#ifdef Q_OS_WIN
    ensureOptionalArgumentsRead();
    QStringList args = arguments();

    if (!checkArgumentCount(2, 5, tr("Register File Type: Invalid arguments")))
        return false;

    bool allUsers = false;
    PackageManagerCore *const core = packageManager();
    if (core && core->value(scAllUsers) == scTrue)
        allUsers = true;

    QSettingsWrapper settings(QLatin1String(allUsers ? "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER")
        , QSettingsWrapper::NativeFormat);

    const QString classesProgId = QString::fromLatin1("Software/Classes/") + m_progId;
    const QString classesFileType = QString::fromLatin1("Software/Classes/.%2").arg(args.at(0));
    const QString classesApplications = QString::fromLatin1("Software/Classes/Applications/") + m_progId;

    // Quoting MSDN here: When uninstalling an application, the ProgIDs and most other registry information
    // associated with that application should be deleted as part of the uninstallation.However, applications
    // that have taken ownership of a file type (by setting the Default value of the file type's
    // HKEY...\.extension subkey to the ProgID of the application) should not attempt to remove that value
    // when uninstalling. Leaving the data in place for the Default value avoids the difficulty of
    // determining whether another application has taken ownership of the file type and overwritten the
    // Default value after the original application was installed. Windows respects the Default value only
    // if the ProgID found there is a registered ProgID. If the ProgID is unregistered, it is ignored.

    // if the hive didn't change since we touched it
    if (value(QLatin1String("newType")).toHash() == readHive(&settings, classesFileType)) {
        // reset to the values we found
        settings.remove(classesFileType);
        settings.beginGroup(classesFileType);
        const QVariantHash keyValues = value(QLatin1String("oldType")).toHash();
        foreach (const QString &key, keyValues.keys())
            settings.setValue(key, keyValues.value(key));
        settings.endGroup();
    } else {
Example #7
0
	QSharedPointer<Jreen::Payload> JPersonMoodConverter::convertTo(const QVariantHash &map) const
	{
		QString mood = map.value(QLatin1String("mood")).toString();
		QString text = map.value(QLatin1String("description")).toString();
		return Jreen::Payload::Ptr(new Jreen::Mood(mood, text));
	}
Example #8
0
QVariantHash PlayerSource::getPlayerMprisInfo(const QString mpris) const
{
    qCDebug(LOG_ESM) << "MPRIS" << mpris;

    QVariantHash info = defaultInfo();
    if (mpris.isEmpty())
        return info;

    QDBusConnection bus = QDBusConnection::sessionBus();
    // comes from the following request:
    // qdbus org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2
    // org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.Player
    // Metadata
    // or the same but using dbus-send:
    // dbus-send --print-reply --session --dest=org.mpris.MediaPlayer2.vlc
    // /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get
    // string:'org.mpris.MediaPlayer2.Player' string:'Metadata'
    QVariantList args = QVariantList()
                        << QString("org.mpris.MediaPlayer2.Player")
                        << QString("Metadata");
    QDBusMessage request = QDBusMessage::createMethodCall(
        QString("org.mpris.MediaPlayer2.%1").arg(mpris),
        QString("/org/mpris/MediaPlayer2"), QString(""), QString("Get"));
    request.setArguments(args);
    QDBusMessage response = bus.call(request, QDBus::BlockWithGui);
    if ((response.type() != QDBusMessage::ReplyMessage)
        || (response.arguments().isEmpty())) {
        qCWarning(LOG_ESM) << "Error message" << response.errorMessage();
    } else {
        // another portion of dirty magic
        QVariantHash map
            = qdbus_cast<QVariantHash>(response.arguments()
                                           .first()
                                           .value<QDBusVariant>()
                                           .variant()
                                           .value<QDBusArgument>());
        info[QString("player/album")]
            = map.value(QString("xesam:album"), QString("unknown"));
        // artist is array
        info[QString("player/artist")]
            = map.value(QString("xesam:artist"), QString("unknown")).toString();
        info[QString("player/duration")]
            = map.value(QString("mpris:length"), 0).toInt() / (1000 * 1000);
        info[QString("player/title")]
            = map.value(QString("xesam:title"), QString("unknown"));
    }

    // position
    args[1] = QString("Position");
    request.setArguments(args);
    response = bus.call(request, QDBus::BlockWithGui);
    if ((response.type() != QDBusMessage::ReplyMessage)
        || (response.arguments().isEmpty())) {
        qCWarning(LOG_ESM) << "Error message" << response.errorMessage();
    } else {
        // this cast is simpler than the previous one ;)
        info[QString("player/progress")] = response.arguments()
                                               .first()
                                               .value<QDBusVariant>()
                                               .variant()
                                               .toLongLong()
                                           / (1000 * 1000);
    }

    return info;
}
Example #9
0
	void start(const QVariant &vrequest, Mode mode)
	{
		outSeq = 0;
		outCredits = 0;
		quiet = false;

		ZhttpRequestPacket request;
		if(!request.fromVariant(vrequest))
		{
			log_warning("failed to parse zurl request");

			QVariantHash vhash = vrequest.toHash();
			rid = vhash.value("id").toByteArray();
			toAddress = vhash.value("from").toByteArray();
			QByteArray type = vhash.value("type").toByteArray();
			if(!toAddress.isEmpty() && type != "error" && type != "cancel")
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			}
			else
			{
				cleanup();
				QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection);
			}

			return;
		}

		rid = request.id;
		toAddress = request.from;
		userData = request.userData;
		sentHeader = false;
		stuffToRead = false;
		bytesReceived = 0;

		ignorePolicies = request.ignorePolicies;

		if(request.uri.isEmpty())
		{
			log_warning("missing request uri");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		QString scheme = request.uri.scheme();
		if(scheme == "https" || scheme == "http")
		{
			transport = HttpTransport;
		}
		else if(scheme == "wss" || scheme == "ws")
		{
			transport = WebSocketTransport;
		}
		else
		{
			log_warning("unsupported scheme");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		if(transport == WebSocketTransport && mode != Worker::Stream)
		{
			log_warning("websocket must be used from stream interface");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		int defaultPort;
		if(scheme == "https" || scheme == "wss")
			defaultPort = 443;
		else // http || wss
			defaultPort = 80;

		HttpHeaders headers = request.headers;

		if(transport == HttpTransport)
		{
			// fire and forget
			if(mode == Worker::Stream && (rid.isEmpty() || toAddress.isEmpty()))
				quiet = true;

			// streaming only allowed on streaming interface
			if(mode == Worker::Stream)
				outStream = request.stream;
			else
				outStream = false;

			if(request.method.isEmpty())
			{
				log_warning("missing request method");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			log_info("IN id=%s, %s %s", request.id.data(), qPrintable(request.method), request.uri.toEncoded().data());

			// inbound streaming must start with sequence number of 0
			if(mode == Worker::Stream && request.more && request.seq != 0)
			{
				log_warning("streamed input must start with seq 0");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			// can't use these two together
			if(mode == Worker::Single && request.more)
			{
				log_warning("cannot use streamed input on router interface");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			bodySent = false;

			inSeq = request.seq;

			if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
				return;
			}

			QByteArray hostHeader = request.uri.host().toUtf8();

			// only tack on the port if it isn't being overridden
			int port = request.uri.port(defaultPort);
			if(request.connectPort == -1 && port != defaultPort)
				hostHeader += ":" + QByteArray::number(port);

			headers.removeAll("Host");
			headers += HttpHeader("Host", hostHeader);

			hreq = new HttpRequest(dns, this);
			connect(hreq, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
			connect(hreq, SIGNAL(readyRead()), SLOT(req_readyRead()));
			connect(hreq, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
			connect(hreq, SIGNAL(error()), SLOT(req_error()));

			maxResponseSize = request.maxSize;
			sessionTimeout = request.timeout;

			if(!request.connectHost.isEmpty())
				hreq->setConnectHost(request.connectHost);
			if(request.connectPort != -1)
				request.uri.setPort(request.connectPort);

			hreq->setIgnoreTlsErrors(request.ignoreTlsErrors);
			if(request.followRedirects)
				hreq->setFollowRedirects(8);

			if(request.credits != -1)
				outCredits += request.credits;
		}
		else // WebSocketTransport
		{
			log_info("IN id=%s, %s", request.id.data(), request.uri.toEncoded().data());

			// inbound streaming must start with sequence number of 0
			if(request.seq != 0)
			{
				log_warning("websocket input must start with seq 0");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			if(toAddress.isEmpty())
			{
				log_warning("websocket input must provide from address");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			inSeq = request.seq;

			if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
				return;
			}

			QByteArray hostHeader = request.uri.host().toUtf8();

			// only tack on the port if it isn't being overridden
			int port = request.uri.port(defaultPort);
			if(request.connectPort == -1 && port != defaultPort)
				hostHeader += ":" + QByteArray::number(port);

			headers.removeAll("Host");
			headers += HttpHeader("Host", hostHeader);

			ws = new WebSocket(dns, this);
			connect(ws, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
			connect(ws, SIGNAL(connected()), SLOT(ws_connected()));
			connect(ws, SIGNAL(readyRead()), SLOT(ws_readyRead()));
			connect(ws, SIGNAL(framesWritten(int)), SLOT(ws_framesWritten(int)));
			connect(ws, SIGNAL(peerClosing()), SLOT(ws_peerClosing()));
			connect(ws, SIGNAL(closed()), SLOT(ws_closed()));
			connect(ws, SIGNAL(error()), SLOT(ws_error()));

			if(!request.connectHost.isEmpty())
				ws->setConnectHost(request.connectHost);
			if(request.connectPort != -1)
				request.uri.setPort(request.connectPort);

			ws->setIgnoreTlsErrors(request.ignoreTlsErrors);
			ws->setMaxFrameSize(config->sessionBufferSize);

			if(request.credits != -1)
				outCredits += request.credits;
		}

		httpActivityTimer = new QTimer(this);
		connect(httpActivityTimer, SIGNAL(timeout()), SLOT(httpActivity_timeout()));
		httpActivityTimer->setSingleShot(true);
		httpActivityTimer->start(config->activityTimeout * 1000);

		if(sessionTimeout != -1)
		{
			httpSessionTimer = new QTimer(this);
			connect(httpSessionTimer, SIGNAL(timeout()), SLOT(httpSession_timeout()));
			httpSessionTimer->setSingleShot(true);
			httpSessionTimer->start(sessionTimeout);
		}

		if(transport == WebSocketTransport || (transport == HttpTransport && mode == Worker::Stream))
		{
			expireTimer = new QTimer(this);
			connect(expireTimer, SIGNAL(timeout()), SLOT(expire_timeout()));
			expireTimer->setSingleShot(true);
			expireTimer->start(SESSION_EXPIRE);

			keepAliveTimer = new QTimer(this);
			connect(keepAliveTimer, SIGNAL(timeout()), SLOT(keepAlive_timeout()));
			keepAliveTimer->start(SESSION_EXPIRE / 2);
		}

		if(transport == HttpTransport)
		{
			if(!request.body.isEmpty() && !request.more && !headers.contains("Content-Length"))
				headers += HttpHeader("Content-Length", QByteArray::number(request.body.size()));

			bool hasOrMightHaveBody = (!request.body.isEmpty() || request.more);

			hreq->start(request.method, request.uri, headers, hasOrMightHaveBody);

			if(hasOrMightHaveBody)
			{
				if(!request.body.isEmpty())
					hreq->writeBody(request.body);

				if(!request.more)
				{
					bodySent = true;
					hreq->endBody();
				}
			}
			else
				bodySent = true;

			if(mode == Stream)
			{
				if(request.more)
				{
					// send cts
					ZhttpResponsePacket resp;
					resp.type = ZhttpResponsePacket::Credit;
					resp.credits = config->sessionBufferSize;
					writeResponse(resp);
				}
				else
				{
					// send ack
					ZhttpResponsePacket resp;
					resp.type = ZhttpResponsePacket::KeepAlive;
					writeResponse(resp);
				}
			}
		}
		else // WebSocketTransport
		{
			ws->start(request.uri, headers);
		}
	}
Example #10
0
/**
 * @brief Login::do_login
 *      Sets all UI parameters and calls a function to proceed according to the state of the login.
 * @param username
 * @param password
 * @param proxy_hostname
 * @param proxy_hostport
 * @param proxy_username
 * @param proxy_password
 * @date
 *      Created:  Filipe, 2 Jan 2014
 *      Modified: Filipe, 7 Mar 2014
 */
void Login::do_login(const QVariantHash &options)
{
    //Password or user change, the process has to be repeted.
    if(username != options.value("username").toString() || password != options.value("password").toString())
    {
        state = persistent;
        username = options.value("username").toString();
        password = options.value("password").toString();
    }

    //Set proxy settings.
    if(options.value("proxy_hostname", "").toString() != "" || options.value("proxy_hostport", "").toString() != "")
    {
        network_manager->set_proxy(Helper::proxy_type(options.value("proxy_type").toString()),
                                   options.value("proxy_hostname").toString(),
                                   options.value("proxy_hostport").toInt(),
                                   options.value("proxy_username").toString(),
                                   options.value("proxy_password").toString());
    }
    else
    {
        network_manager->set_proxy(QNetworkProxy::NoProxy);
    }

    output(network_manager->print(), 3);

    //Set captcha and steamguard code.
    captcha_text = options.value("captcha").toString();
    guard_code = options.value("guard_code").toString();
    guard_name = options.value("guard_name").toString();
    remember_login = options.value("remember_login").toBool();

    //Proceed acording to state.
    process_state();
}
Example #11
0
	void start(const QVariant &vrequest, Mode mode)
	{
		outSeq = 0;

		ZurlRequestPacket request;
		if(!request.fromVariant(vrequest))
		{
			log_warning("failed to parse zurl request");

			QVariantHash vhash = vrequest.toHash();
			rid = vhash.value("id").toByteArray();
			assert(!rid.isEmpty()); // app layer ensures this
			receiver = vhash.value("sender").toByteArray();
			bool cancel = vhash.value("cancel").toBool();
			if(!receiver.isEmpty() && !cancel)
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			}
			else
			{
				cleanup();
				QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection);
			}

			return;
		}

		rid = request.id;
		receiver = request.sender;
		outCredits = 0;
		userData = request.userData;
		quiet = false;
		sentHeader = false;
		stuffToRead = false;
		bytesReceived = 0;

		ignorePolicies = request.ignorePolicies;

		// streaming only allowed on streaming interface
		if(mode == Worker::Stream)
			outStream = request.stream;
		else
			outStream = false;

		// some required fields
		if(request.method.isEmpty() || request.uri.isEmpty())
		{
			log_warning("missing request method or missing uri");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		log_info("IN id=%s, %s %s", request.id.data(), qPrintable(request.method), request.uri.toEncoded().data());

		// inbound streaming must start with sequence number of 0
		if(mode == Worker::Stream && request.more && request.seq != 0)
		{
			log_warning("streamed input must start with seq 0");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		// fire and forget
		if(mode == Worker::Stream && receiver.isEmpty())
			quiet = true;

		// can't use these two together
		if(mode == Worker::Single && request.more)
		{
			log_warning("cannot use streamed input on router interface");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		bodySent = false;

		inSeq = request.seq;

		if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
		{
			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
			return;
		}

		hreq = new HttpRequest(dns, this);
		connect(hreq, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
		connect(hreq, SIGNAL(readyRead()), SLOT(req_readyRead()));
		connect(hreq, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
		connect(hreq, SIGNAL(error()), SLOT(req_error()));
		maxResponseSize = request.maxSize;
		if(!request.connectHost.isEmpty())
			hreq->setConnectHost(request.connectHost);

		hreq->setIgnoreTlsErrors(request.ignoreTlsErrors);

		if(request.credits != -1)
			outCredits += request.credits;

		HttpHeaders headers = request.headers;
		// ensure content-length (or overwrite it, if not streaming input)
		if((request.method == "POST" || request.method == "PUT") && (!headers.contains("content-length") || !request.more))
			headers += HttpHeader("Content-Length", QByteArray::number(request.body.size()));

		timer = new QTimer(this);
		connect(timer, SIGNAL(timeout()), SLOT(timer_timeout()));
		timer->setSingleShot(true);
		timer->start(config->sessionTimeout * 1000);

		hreq->start(request.method, request.uri, headers);

		// note: unlike follow-up requests, the initial request is assumed to have a body.
		//   if no body field is present, we act as if it is present but empty.

		if(!request.body.isEmpty())
		{
			if(request.more && !request.headers.contains("content-length"))
			{
				log_warning("streamed input requires content-length");
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "length-required"));
				return;
			}

			hreq->writeBody(request.body);
		}

		if(!request.more)
		{
			bodySent = true;
			hreq->endBody();
		}
		else
		{
			// send cts
			ZurlResponsePacket resp;
			resp.credits = config->sessionBufferSize;
			writeResponse(resp);
		}
	}
Example #12
0
void GeometryReader::run() {
    DependencyManager::get<StatTracker>()->decrementStat("PendingProcessing");
    CounterStat counter("Processing");
    PROFILE_RANGE_EX(resource_parse_geometry, "GeometryReader::run", 0xFF00FF00, 0, { { "url", _url.toString() } });
    auto originalPriority = QThread::currentThread()->priority();
    if (originalPriority == QThread::InheritPriority) {
        originalPriority = QThread::NormalPriority;
    }
    QThread::currentThread()->setPriority(QThread::LowPriority);
    Finally setPriorityBackToNormal([originalPriority]() {
        QThread::currentThread()->setPriority(originalPriority);
    });

    if (!_resource.data()) {
        return;
    }

    try {
        if (_data.isEmpty()) {
            throw QString("reply is NULL");
        }

        // Ensure the resource has not been deleted
        auto resource = _resource.toStrongRef();
        if (!resource) {
            qCWarning(modelnetworking) << "Abandoning load of" << _url << "; could not get strong ref";
            return;
        }

        if (_url.path().isEmpty()) {
            throw QString("url is invalid");
        }

        HFMModel::Pointer hfmModel;
        QVariantHash serializerMapping = _mapping.second;
        serializerMapping["combineParts"] = _combineParts;
        serializerMapping["deduplicateIndices"] = true;

        if (_url.path().toLower().endsWith(".gz")) {
            QByteArray uncompressedData;
            if (!gunzip(_data, uncompressedData)) {
                throw QString("failed to decompress .gz model");
            }
            // Strip the compression extension from the path, so the loader can infer the file type from what remains.
            // This is okay because we don't expect the serializer to be able to read the contents of a compressed model file.
            auto strippedUrl = _url;
            strippedUrl.setPath(_url.path().left(_url.path().size() - 3));
            hfmModel = _modelLoader.load(uncompressedData, serializerMapping, strippedUrl, "");
        } else {
            hfmModel = _modelLoader.load(_data, serializerMapping, _url, _webMediaType.toStdString());
        }

        if (!hfmModel) {
            throw QString("unsupported format");
        }

        if (hfmModel->meshes.empty() || hfmModel->joints.empty()) {
            throw QString("empty geometry, possibly due to an unsupported model version");
        }

        // Add scripts to hfmModel
        if (!serializerMapping.value(SCRIPT_FIELD).isNull()) {
            QVariantList scripts = serializerMapping.values(SCRIPT_FIELD);
            for (auto &script : scripts) {
                hfmModel->scripts.push_back(script.toString());
            }
        }

        // Do processing on the model
        baker::Baker modelBaker(hfmModel, _mapping.second, _mapping.first);
        modelBaker.run();

        auto processedHFMModel = modelBaker.getHFMModel();
        auto materialMapping = modelBaker.getMaterialMapping();

        QMetaObject::invokeMethod(resource.data(), "setGeometryDefinition",
                Q_ARG(HFMModel::Pointer, processedHFMModel), Q_ARG(MaterialMapping, materialMapping));
    } catch (const std::exception&) {
        auto resource = _resource.toStrongRef();
        if (resource) {
            QMetaObject::invokeMethod(resource.data(), "finishedLoading",
                Q_ARG(bool, false));
        }
    } catch (QString& e) {
        qCWarning(modelnetworking) << "Exception while loading model --" << e;
        auto resource = _resource.toStrongRef();
        if (resource) {
            QMetaObject::invokeMethod(resource.data(), "finishedLoading",
                                      Q_ARG(bool, false));
        }
    }
}
Example #13
0
QByteArray ViewEmail::render(Context *c) const
{
    Q_D(const ViewEmail);

    QVariantHash email = c->stash(d->stashKey).toHash();
    if (email.isEmpty()) {
        c->error(QStringLiteral("Cannot render template, template name or template stash key not defined"));
        return QByteArray();
    }

    MimeMessage message;

    QVariant value;
    value = email.value(QStringLiteral("to"));
    if (value.type() == QVariant::String && !value.toString().isEmpty()) {
        message.addTo(value.toString());
    }

    value = email.value(QStringLiteral("cc"));
    if (value.type() == QVariant::String && !value.toString().isEmpty()) {
        message.addCc(value.toString());
    }

    value = email.value(QStringLiteral("from"));
    if (value.type() == QVariant::String && !value.toString().isEmpty()) {
        message.setSender(value.toString());
    }

    value = email.value(QStringLiteral("subject"));
    if (value.type() == QVariant::String && !value.toString().isEmpty()) {
        message.setSubject(value.toString());
    }

    QVariant body = email.value(QStringLiteral("body"));
    QVariant parts = email.value(QStringLiteral("parts"));
    if (body.isNull() && parts.isNull()) {
        c->error(QStringLiteral("Can't send email without parts or body, check stash"));
        return QByteArray();
    }

    if (!parts.isNull()) {
        const QVariantList partsVariant = parts.toList();
        Q_FOREACH (const QVariant &part, partsVariant) {
            MimePart *mime = part.value<MimePart*>();
            if (mime) {
                message.addPart(mime);
            } else {
                qCCritical(CUTELYST_VIEW_EMAIL) << "Failed to cast MimePart";
            }
        }

        auto contentTypeIt = email.constFind(QStringLiteral("content_type"));
        if (contentTypeIt != email.constEnd()
                && !contentTypeIt.value().isNull()
                && !contentTypeIt.value().toString().isEmpty()) {
            const QByteArray contentType = contentTypeIt.value().toString().toLatin1();
            qCDebug(CUTELYST_VIEW_EMAIL) << "Using specified content_type" << contentType;
            message.getContent().setContentType(contentType);
        } else if (!d->defaultContentType.isEmpty()) {
            qCDebug(CUTELYST_VIEW_EMAIL) << "Using default content_type" << d->defaultContentType;
            message.getContent().setContentType(d->defaultContentType);
        }
    } else {
Example #14
0
void AVDecoder::setOptions(const QVariantHash &dict)
{
    DPTR_D(AVDecoder);
    d.options = dict;
    if (d.dict) {
        av_dict_free(&d.dict);
        d.dict = 0; //aready 0 in av_free
    }
    if (dict.isEmpty())
        return;
    // TODO: use QVariantMap only
    QVariant opt;
    if (dict.contains("avcodec"))
        opt = dict.value("avcodec");
    if (opt.type() == QVariant::Hash) {
        QVariantHash avcodec_dict = opt.toHash();
        // workaround for VideoDecoderFFmpeg. now it does not call av_opt_set_xxx, so set here in dict
        // TODO: wrong if opt is empty
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toHash());
        QHashIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Hash: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::Int: {
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toInt()).constData(), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toInt(), 0);
            }
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong: {
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toLongLong()).constData(), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toLongLong(), 0);
            }
                break;
            default:
                // avcodec key and value are in lower case
                av_dict_set(&d.dict, i.key().toLower().toUtf8().constData(), i.value().toByteArray().toLower().constData(), 0);
                break;
            }
            qDebug("avcodec option: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    } else if (opt.type() == QVariant::Map) {
        QVariantMap avcodec_dict = opt.toMap();
        // workaround for VideoDecoderFFmpeg. now it does not call av_opt_set_xxx, so set here in dict
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toMap());
        QMapIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Map: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::UInt:
            case QVariant::Int: {
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toInt()), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toInt(), 0);
            }
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong: {
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toLongLong()).constData(), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toLongLong(), 0);
            }
                break;
            default:
                // avcodec key and value are in lower case
                av_dict_set(&d.dict, i.key().toLower().toUtf8().constData(), i.value().toByteArray().toLower().constData(), 0);
                break;
            }
            qDebug("avcodec option: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    }
    if (name() == "avcodec")
        return;
    if (dict.contains(name()))
        opt = dict.value(name());
    else if (dict.contains(name().toLower()))
        opt = dict.value(name().toLower());
    else
        return;
    if (opt.type() == QVariant::Hash) {
        QVariantHash property_dict(opt.toHash());
        if (property_dict.isEmpty())
            return;
        QHashIterator<QString, QVariant> i(property_dict);
        while (i.hasNext()) {
            i.next();
            if (i.value().type() == QVariant::Hash) // for example "vaapi": {...}
                continue;
            setProperty(i.key().toUtf8().constData(), i.value());
            qDebug("decoder property: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    } else if (opt.type() == QVariant::Map) {
        QVariantMap property_dict(opt.toMap());
        if (property_dict.isEmpty())
            return;
        QMapIterator<QString, QVariant> i(property_dict);
        while (i.hasNext()) {
            i.next();
            if (i.value().type() == QVariant::Map) // for example "vaapi": {...}
                continue;
            setProperty(i.key().toUtf8().constData(), i.value());
            qDebug("decoder property: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    }

}
/*!
    Creates widget. \a params must include 'uri' for the desired widget type.
    'preferences' is optional.
*/
bool HsContentService::createWidget(const QVariantHash &params)
{
    return addWidget(params.value(Hs::uri).toString(),
                     params.value(Hs::preferences).toHash(),
                     params.value(Hs::homescreenData));
}
QMenu *DFMSideBarDeviceItem::createStandardContextMenu() const
{
    QMenu *menu = new QMenu();
    const DAbstractFileInfoPointer infoPointer = fileService->createFileInfo(this, url());
    DFileManagerWindow *wnd = qobject_cast<DFileManagerWindow *>(topLevelWidget());
    bool shouldDisable = !WindowManager::tabAddableByWinId(wnd->windowId());
    QVariantHash info = getExtensionPropertys();
    DUrl deviceIdUrl;

    deviceIdUrl.setQuery(info.value("deviceId").toString());

    menu->addAction(QObject::tr("Open in new window"), [this, info, deviceIdUrl]() {
        if (info.value("isMounted", false).toBool()) {
            WindowManager::instance()->showNewWindow(url(), true);
        } else {
            appController->actionOpenDiskInNewWindow(dMakeEventPointer<DFMUrlBaseEvent>(this, deviceIdUrl));
        }
    });

    menu->addAction(QObject::tr("Open in new tab"), [wnd, this, info, deviceIdUrl]() {
        if (info.value("isMounted", false).toBool()) {
            wnd->openNewTab(url());
        } else {
            appController->actionOpenDiskInNewTab(dMakeEventPointer<DFMUrlBaseEvent>(this, deviceIdUrl));
        }
    })->setDisabled(shouldDisable);

    menu->addSeparator();

    if (infoPointer->canRename()) {
        menu->addAction(QObject::tr("Rename"), [this]() {
            DFMSideBarDeviceItem *ccItem = const_cast<DFMSideBarDeviceItem *>(this);
            ccItem->showRenameEditor();
        });
    }

//    if (info.value("canEject", false).toBool()) {
//        menu->addAction(QObject::tr("Eject"), [this, info]() {
//            gvfsMountManager->eject(info.value("deviceId").toString());
//        });
//    }

    if (info.value("canStop", false).toBool()) {
        menu->addAction(QObject::tr("Safely Remove"), [this, info, deviceIdUrl]() {
            AppController::instance()->actionSafelyRemoveDrive(dMakeEventPointer<DFMUrlBaseEvent>(this, deviceIdUrl));
        });
    }

    if (info.value("canMount", false).toBool() && !info.value("isMounted", false).toBool()) {
        menu->addAction(QObject::tr("Mount"), [info]() {
            gvfsMountManager->mount(info.value("deviceId").toString());
        });
    }

//    if (info.value("canUnmount", false).toBool()) {
//        menu->addAction(QObject::tr("Unmount"), [this, info]() {
//            gvfsMountManager->unmount(info.value("deviceId").toString());
//        });
//    }

    // According to the designer and PM, we should use "Unmount" even we are actually doing *Eject* for removable device.
    // This behavior should be discussed later.
    if (info.value("canUnmount", false).toBool()) {
        menu->addAction(QObject::tr("Unmount"), this, SLOT(doUnmountOrEject()));
    }

    if (info.value("mediaType", 0).toInt() == UDiskDeviceInfo::MediaType::removable) {
        menu->addAction(QObject::tr("Format"), [this, info, deviceIdUrl]() {
            AppController::instance()->actionFormatDevice(dMakeEventPointer<DFMUrlBaseEvent>(this, deviceIdUrl));
        });
    }

    // Device can be a network scheme, like smb://, ftp:// and sftp://
    QString devicePathScheme = DUrl::fromUserInput(info.value("deviceId").toString()).scheme();
    if (devicePathScheme == SMB_SCHEME || devicePathScheme == FTP_SCHEME || devicePathScheme == SFTP_SCHEME || devicePathScheme == DAV_SCHEME) {
        menu->addAction(QObject::tr("Log out and unmount"), [this, info, deviceIdUrl]() {
            AppController::instance()->actionForgetPassword(dMakeEventPointer<DFMUrlBaseEvent>(this, deviceIdUrl));
        });
    }

    menu->addSeparator();

    QAction *propertyAction = new QAction(QObject::tr("Disk info"), menu);
    connect(propertyAction, &QAction::triggered, this, [this, info]() {
        DUrl mountPointUrl(info.value("mountPointUrl", QString()).toString());
        mountPointUrl = mountPointUrl.isEmpty() ? url() : mountPointUrl;
        mountPointUrl.setQuery(info.value("deviceId", "what?").toString());
        fileSignalManager->requestShowPropertyDialog(DFMUrlListBaseEvent(this, {mountPointUrl}));
    });
    propertyAction->setDisabled(!info.value("isMounted", false).toBool());
    menu->addAction(propertyAction);

    return menu;
}
/*!
  Validates the specified parameter \a hash by the set rules.
  
  As default, TF::Required is set for all parameters. If not required, 
  set the rule to \a false like this:
    setRule("xxx", Tf::Required, false);
 */
bool TFormValidator::validate(const QVariantHash &hash)
{
    errors.clear();

    // Add default rules, Tf::Required.
    QString msg = Tf::app()->validationErrorMessage(Tf::Required);
    for (QStringListIterator i(hash.keys()); i.hasNext(); ) {
        const QString &k = i.next();
        if (!containsRule(k, Tf::Required)) {
            rules.append(RuleEntry(k, (int)Tf::Required, true, msg));
        }
    }

    for (QListIterator<RuleEntry> i(rules); i.hasNext(); ) {
        const RuleEntry &r = i.next();
        QString str = hash.value(r.key).toString();  // value string

        if (str.isEmpty()) {
            bool req = r.value.toBool();
            if (r.rule == Tf::Required && req) {
                tSystemDebug("validation error: required parameter is empty, key:%s", qPrintable(r.key)); 
                errors << qMakePair(r.key, r.rule);
            }
        } else {
            bool ok1, ok2;
            tSystemDebug("validating key:%s value: %s", qPrintable(r.key), qPrintable(str)); 
            switch (r.rule) {
            case Tf::Required:
                break;

            case Tf::MaxLength: {
                int max = r.value.toInt(&ok2);
                if (!ok2 || str.length() > max) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::MinLength: {
                int min = r.value.toInt(&ok2);
                if (!ok2 || str.length() < min) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::IntMax: {
                qint64 n = str.toLongLong(&ok1);
                qint64 max = r.value.toLongLong(&ok2);
                if (!ok1 || !ok2 || n > max) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::IntMin: {
                qint64 n = str.toLongLong(&ok1);
                qint64 min = r.value.toLongLong(&ok2);
                if (!ok1 || !ok2  || n < min) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::DoubleMax: {
                double n = str.toDouble(&ok1);
                double max = r.value.toLongLong(&ok2);
                if (!ok1 || !ok2 || n > max) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::DoubleMin: {
                double n = str.toDouble(&ok1);
                double min = r.value.toDouble(&ok2);
                if (!ok1 || !ok2 || n < min) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }
                
            case Tf::EmailAddress: { // refer to RFC5321
                if ( r.value.toBool() ) {
                    QRegExp reg("^" ADDR_SPEC "$");
                    if (!reg.exactMatch(str)) {
                        errors << qMakePair(r.key, r.rule);
                    }
                }
                break; }

            case Tf::Url: {
                if ( r.value.toBool() ) {
                    QUrl url(str, QUrl::StrictMode);
                    if (!url.isValid()) {
                        errors << qMakePair(r.key, r.rule);
                    }
                }
                break; }

            case Tf::Date: {
                if ( r.value.toBool() ) {
                    QDate date = QLocale().toDate(str, dateFormat());
                    if (!date.isValid()) {
                        errors << qMakePair(r.key, r.rule);
                        tSystemDebug("Validation error: Date format: %s", qPrintable(dateFormat()));
                    }
                }
                break; }

            case Tf::Time: {
                if ( r.value.toBool() ) {
                    QTime time = QLocale().toTime(str, timeFormat());
                    if (!time.isValid()) {
                        errors << qMakePair(r.key, r.rule);
                        tSystemDebug("Validation error: Time format: %s", qPrintable(timeFormat()));
                    }
                }
                break; }

            case Tf::DateTime: {
                if ( r.value.toBool() ) {
                    QDateTime dt = QLocale().toDateTime(str, dateTimeFormat());
                    if (!dt.isValid()) {
                        errors << qMakePair(r.key, r.rule);
                        tSystemDebug("Validation error: DateTime format: %s", qPrintable(dateTimeFormat()));
                    }
                }
                break; }

            case Tf::Pattern: {
                QRegExp rx = r.value.toRegExp();
                if (rx.isEmpty() || !rx.exactMatch(str)) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            default:
                tSystemError("Internal Error, invalid rule: %d  [%s:%d]", r.rule, __FILE__, __LINE__);
                break;
            }
        }
    }
    return errors.isEmpty();
}
Example #18
0
void RssParser::parseAtomArticle(QXmlStreamReader& xml, const QString& feedUrl, const QString& baseUrl)
{
  QVariantHash article;
  bool double_content = false;

  while(!xml.atEnd()) {
    xml.readNext();

    if(xml.isEndElement() && xml.name() == "entry")
      break;

    if (xml.isStartElement()) {
      if (xml.name() == "title") {
        // Workaround for CDATA (QString cannot parse html escapes on it's own)
        QTextDocument doc;
        doc.setHtml(xml.readElementText());
        article["title"] = doc.toPlainText();
      }
      else if (xml.name() == "link") {
        QString theLink = ( xml.attributes().isEmpty() ?
                              xml.readElementText() :
                              xml.attributes().value("href").toString() );

        // Atom feeds can have relative links, work around this and
        // take the stress of figuring article full URI from UI

        // Assemble full URI
        article["news_link"] = ( baseUrl.isEmpty() ?
                                   theLink :
                                   baseUrl + theLink );
      }
      else if (xml.name() == "summary" || xml.name() == "content"){
        if(double_content) { // Duplicate content -> ignore
          xml.readNext();

          while(xml.name() != "summary" && xml.name() != "content")
            xml.readNext();

          continue;
        }

        // Try to also parse broken articles, which don't use html '&' escapes
        // Actually works great for non-broken content too
        QString feedText = xml.readElementText(QXmlStreamReader::IncludeChildElements);
        if (!feedText.isEmpty())
          article["description"] = feedText;

        double_content = true;
      }
      else if (xml.name() == "updated"){
        // ATOM uses standard compliant date, don't do fancy stuff
        QDateTime articleDate = QDateTime::fromString(xml.readElementText(), Qt::ISODate);
        article["date"] = ( articleDate.isValid() ?
                              articleDate :
                              QDateTime::currentDateTime() );
      }
      else if (xml.name() == "author") {
        xml.readNext();
        while(xml.name() != "author") {
          if(xml.name() == "name")
            article["author"] = xml.readElementText();
          xml.readNext();
        }
      }
      else if (xml.name() == "id")
        article["id"] = xml.readElementText();
    }
  }

  if (!article.contains("id")) {
    // Item does not have a guid, fall back to some other identifier
    const QString link = article.value("news_link").toString();
    if (!link.isEmpty())
      article["id"] = link;
    else {
      const QString title = article.value("title").toString();
      if (!title.isEmpty())
        article["id"] = title;
      else {
        qWarning() << "Item has no guid, link or title, ignoring it...";
        return;
      }
    }
  }

  emit newArticle(feedUrl, article);
}
WebsiteInformationDialog::WebsiteInformationDialog(WebWidget *widget, QWidget *parent) : Dialog(parent),
	m_sslInformation(widget->getSslInformation()),
	m_ui(new Ui::WebsiteInformationDialog)
{
	m_ui->setupUi(this);

	const QVariantHash statistics(widget->getStatistics());
	const WindowsManager::ContentStates state(widget->getContentState());
	const QString characterEncoding(widget->getCharacterEncoding());
	QString host(widget->getUrl().host());

	if (host.isEmpty())
	{
		host = (widget->getUrl().scheme() == QLatin1String("file") ? QLatin1String("localhost") : tr("(unknown)"));
	}

	if (state.testFlag(WindowsManager::FraudContentState))
	{
		m_ui->stateLabel->setText(tr("This website was marked as fraud."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-fraud"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::TrustedContentState))
	{
		m_ui->stateLabel->setText(tr("Your connection with this website is private."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-trusted"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::SecureContentState))
	{
		m_ui->stateLabel->setText(tr("Your connection with this website is private."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-secure"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::RemoteContentState))
	{
		m_ui->stateLabel->setText(tr("Your connection with this website is not private."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-remote"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::LocalContentState))
	{
		m_ui->stateLabel->setText(tr("You are viewing content from your local filesystem."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-local"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::ApplicationContentState))
	{
		m_ui->stateLabel->setText(tr("You are viewing safe page from Otter Browser."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("otter-browser"), false).pixmap(16, 16));
	}
	else
	{
		m_ui->stateLabel->setText(tr("No information."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-unknown"), false).pixmap(16, 16));
	}

	m_ui->hostLabel->setText(host);
	m_ui->addressLabelWidget->setText(widget->getUrl().toString());
	m_ui->titleLabelWidget->setText(widget->getTitle());
	m_ui->encodingLabelWidget->setText(characterEncoding.isEmpty() ? tr("unknown") : characterEncoding);
	m_ui->sizeLabelWidget->setText(Utils::formatUnit(statistics.value(QLatin1String("bytesTotal")).toLongLong(), false, 1, true));
	m_ui->elementsLabelWidget->setText((statistics.value(QLatin1String("requestsBlocked")).toInt() > 0) ? tr("%1 (%n blocked)", "", statistics.value(QLatin1String("requestsBlocked")).toInt()).arg(statistics.value(QLatin1String("requestsStarted")).toInt()) : QString::number(statistics.value(QLatin1String("requestsStarted")).toInt()));
	m_ui->downloadDateLabelWidget->setText(Utils::formatDateTime(statistics.value(QLatin1String("dateDownloaded")).toDateTime()));

	const QString cookiesPolicy(widget->getOption(QLatin1String("Network/CookiesPolicy")).toString());

	if (cookiesPolicy == QLatin1String("acceptExisting"))
	{
		m_ui->cookiesValueLabel->setText(tr("Only existing"));
	}
	else if (cookiesPolicy == QLatin1String("readOnly"))
	{
		m_ui->cookiesValueLabel->setText(tr("Only read existing"));
	}
	else if (cookiesPolicy == QLatin1String("ignore"))
	{
		m_ui->cookiesValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->cookiesValueLabel->setText(tr("Always"));
	}

	const QString thirdPartyCookiesPolicy(widget->getOption(QLatin1String("Network/ThirdPartyCookiesPolicy")).toString());

	if (thirdPartyCookiesPolicy == QLatin1String("acceptExisting"))
	{
		m_ui->thirdPartyCookiesValueLabel->setText(tr("Only existing"));
	}
	else if (thirdPartyCookiesPolicy == QLatin1String("ignore"))
	{
		m_ui->thirdPartyCookiesValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->thirdPartyCookiesValueLabel->setText(tr("Always"));
	}

	const QString pluginsPolicy(widget->getOption(QLatin1String("Browser/EnablePlugins")).toString());

	if (pluginsPolicy == QLatin1String("enabled"))
	{
		m_ui->pluginsValueLabel->setText(tr("Always"));
	}
	else if (pluginsPolicy == QLatin1String("disabled"))
	{
		m_ui->pluginsValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->pluginsValueLabel->setText(tr("On demand"));
	}

	const QString imagesPolicy(widget->getOption(QLatin1String("Browser/EnableImages")).toString());

	if (imagesPolicy == QLatin1String("onlyCached"))
	{
		m_ui->imagesValueLabel->setText(tr("Only cached"));
	}
	else if (imagesPolicy == QLatin1String("disabled"))
	{
		m_ui->imagesValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->imagesValueLabel->setText(tr("Always"));
	}

	m_ui->javascriptValueLabel->setText(widget->getOption(QLatin1String("Browser/EnableJavaScript")).toBool() ? tr("Always") : tr("Never"));

	const QString geolocationPolicy(widget->getOption(QLatin1String("Browser/EnableGeolocation")).toString());

	if (geolocationPolicy == QLatin1String("enabled"))
	{
		m_ui->geolocationValueLabel->setText(tr("Always"));
	}
	else if (geolocationPolicy == QLatin1String("disabled"))
	{
		m_ui->geolocationValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->geolocationValueLabel->setText(tr("Always ask"));
	}

	const QString fullScreenPolicy(widget->getOption(QLatin1String("Browser/EnableFullScreen")).toString());

	if (fullScreenPolicy == QLatin1String("enabled"))
	{
		m_ui->fullScreenValueLabel->setText(tr("Always"));
	}
	else if (fullScreenPolicy == QLatin1String("disabled"))
	{
		m_ui->fullScreenValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->fullScreenValueLabel->setText(tr("Always ask"));
	}

	const QString notificationsPolicy(widget->getOption(QLatin1String("Browser/EnableNotifications")).toString());

	if (notificationsPolicy == QLatin1String("enabled"))
	{
		m_ui->notificationsValueLabel->setText(tr("Always"));
	}
	else if (notificationsPolicy == QLatin1String("disabled"))
	{
		m_ui->notificationsValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->notificationsValueLabel->setText(tr("Always ask"));
	}

	const QString popupsPolicy(widget->getOption(QLatin1String("Content/PopupsPolicy")).toString());

	if (popupsPolicy == QLatin1String("openAll"))
	{
		m_ui->popupsValueLabel->setText(tr("Always"));
	}
	else if (popupsPolicy == QLatin1String("openAllInBackground"))
	{
		m_ui->popupsValueLabel->setText(tr("Always (open in backgound)"));
	}
	else if (popupsPolicy == QLatin1String("blockAll"))
	{
		m_ui->popupsValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->popupsValueLabel->setText(tr("Ask"));
	}

	if (m_sslInformation.certificates.isEmpty())
	{
		m_ui->tabWidget->setTabEnabled(2, false);
	}
	else
	{
		const QSslCertificate certificate(m_sslInformation.certificates.first());

		m_ui->certificateIssuedToLabelWidget->setText(certificate.subjectInfo(QSslCertificate::CommonName).join(QLatin1String(", ")));
		m_ui->certificateIssuedByLabelWidget->setText(certificate.issuerInfo(QSslCertificate::CommonName).join(QLatin1String(", ")));
		m_ui->certificateIssuedOnLabelWidget->setText(Utils::formatDateTime(certificate.effectiveDate()));
		m_ui->certificateExpiresOnLabelWidget->setText(Utils::formatDateTime(certificate.expiryDate()));
		m_ui->cipherProtocolLabelWidget->setText(m_sslInformation.cipher.protocolString());
		m_ui->cipherAuthenticationMethodLabelWidget->setText(m_sslInformation.cipher.authenticationMethod());
		m_ui->cipherEncryptionMethodLabelWidget->setText(m_sslInformation.cipher.encryptionMethod());
		m_ui->cipherKeyExchangeMethodLabelWidget->setText(m_sslInformation.cipher.keyExchangeMethod());
	}

	if (m_sslInformation.errors.isEmpty())
	{
		m_ui->sslErrorsHeaderLabel->hide();
		m_ui->sslErrorsViewWidget->hide();
	}
	else
	{
		QStandardItemModel *sslErrorsModel(new QStandardItemModel(this));
		sslErrorsModel->setHorizontalHeaderLabels(QStringList({tr("Error Message"), tr("URL")}));

		for (int i = 0; i < m_sslInformation.errors.count(); ++i)
		{
			QList<QStandardItem*> items({new QStandardItem(m_sslInformation.errors.at(i).second.errorString()), new QStandardItem(m_sslInformation.errors.at(i).first.toDisplayString())});
			items[0]->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
			items[0]->setToolTip(items[0]->text());
			items[1]->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
			items[1]->setToolTip(items[1]->text());

			sslErrorsModel->appendRow(items);
		}

		m_ui->sslErrorsViewWidget->setModel(sslErrorsModel);
	}

	setWindowTitle(tr("Information for %1").arg(host));

	connect(m_ui->preferencesDetailsButton, SIGNAL(clicked(bool)), this, SLOT(showPreferences()));
	connect(m_ui->certificateDetailsButton, SIGNAL(clicked(bool)), this, SLOT(showCertificate()));
}
Example #20
0
void ModelPackager::populateBasicMapping(QVariantHash& mapping, QString filename, const hfm::Model& hfmModel) {

    // mixamo files - in the event that a mixamo file was edited by some other tool, it's likely the applicationName will
    // be rewritten, so we detect the existence of several different blendshapes which indicate we're likely a mixamo file
    bool likelyMixamoFile = hfmModel.applicationName == "mixamo.com" ||
                            (hfmModel.blendshapeChannelNames.contains("BrowsDown_Right") &&
                             hfmModel.blendshapeChannelNames.contains("MouthOpen") &&
                             hfmModel.blendshapeChannelNames.contains("Blink_Left") &&
                             hfmModel.blendshapeChannelNames.contains("Blink_Right") &&
                             hfmModel.blendshapeChannelNames.contains("Squint_Right"));
    
    if (!mapping.contains(NAME_FIELD)) {
        mapping.insert(NAME_FIELD, QFileInfo(filename).baseName());
    }
    
    if (!mapping.contains(FILENAME_FIELD)) {
        QDir root(_modelFile.path());
        mapping.insert(FILENAME_FIELD, root.relativeFilePath(filename));
    }
    if (!mapping.contains(TEXDIR_FIELD)) {
        mapping.insert(TEXDIR_FIELD, ".");
    }
    if (!mapping.contains(SCRIPT_FIELD)) {
        mapping.insert(SCRIPT_FIELD, ".");
    }
    // mixamo/autodesk defaults
    if (!mapping.contains(SCALE_FIELD)) {
        mapping.insert(SCALE_FIELD, 1.0);
    }
    QVariantHash joints = mapping.value(JOINT_FIELD).toHash();
    if (!joints.contains("jointEyeLeft")) {
        joints.insert("jointEyeLeft", hfmModel.jointIndices.contains("jointEyeLeft") ? "jointEyeLeft" :
                      (hfmModel.jointIndices.contains("EyeLeft") ? "EyeLeft" : "LeftEye"));
    }
    if (!joints.contains("jointEyeRight")) {
        joints.insert("jointEyeRight", hfmModel.jointIndices.contains("jointEyeRight") ? "jointEyeRight" :
                      hfmModel.jointIndices.contains("EyeRight") ? "EyeRight" : "RightEye");
    }
    if (!joints.contains("jointNeck")) {
        joints.insert("jointNeck", hfmModel.jointIndices.contains("jointNeck") ? "jointNeck" : "Neck");
    }
    
    if (!joints.contains("jointRoot")) {
        joints.insert("jointRoot", "Hips");
    }
    if (!joints.contains("jointLean")) {
        joints.insert("jointLean", "Spine");
    }
    if (!joints.contains("jointLeftHand")) {
        joints.insert("jointLeftHand", "LeftHand");
    }
    if (!joints.contains("jointRightHand")) {
        joints.insert("jointRightHand", "RightHand");
    }
    
    if (!joints.contains("jointHead")) {
        const char* topName = likelyMixamoFile ? "HeadTop_End" : "HeadEnd";
        joints.insert("jointHead", hfmModel.jointIndices.contains(topName) ? topName : "Head");
    }

    mapping.insert(JOINT_FIELD, joints);

    if (!mapping.contains(FREE_JOINT_FIELD)) {
        mapping.insertMulti(FREE_JOINT_FIELD, "LeftArm");
        mapping.insertMulti(FREE_JOINT_FIELD, "LeftForeArm");
        mapping.insertMulti(FREE_JOINT_FIELD, "RightArm");
        mapping.insertMulti(FREE_JOINT_FIELD, "RightForeArm");
    }
    
    // If there are no blendshape mappings, and we detect that this is likely a mixamo file,
    // then we can add the default mixamo to "faceshift" mappings
    if (!mapping.contains(BLENDSHAPE_FIELD) && likelyMixamoFile) {
        QVariantHash blendshapes;
        blendshapes.insertMulti("BrowsD_L", QVariantList() << "BrowsDown_Left" << 1.0);
        blendshapes.insertMulti("BrowsD_R", QVariantList() << "BrowsDown_Right" << 1.0);
        blendshapes.insertMulti("BrowsU_C", QVariantList() << "BrowsUp_Left" << 1.0);
        blendshapes.insertMulti("BrowsU_C", QVariantList() << "BrowsUp_Right" << 1.0);
        blendshapes.insertMulti("BrowsU_L", QVariantList() << "BrowsUp_Left" << 1.0);
        blendshapes.insertMulti("BrowsU_R", QVariantList() << "BrowsUp_Right" << 1.0);
        blendshapes.insertMulti("ChinLowerRaise", QVariantList() << "Jaw_Up" << 1.0);
        blendshapes.insertMulti("ChinUpperRaise", QVariantList() << "UpperLipUp_Left" << 0.5);
        blendshapes.insertMulti("ChinUpperRaise", QVariantList() << "UpperLipUp_Right" << 0.5);
        blendshapes.insertMulti("EyeBlink_L", QVariantList() << "Blink_Left" << 1.0);
        blendshapes.insertMulti("EyeBlink_R", QVariantList() << "Blink_Right" << 1.0);
        blendshapes.insertMulti("EyeOpen_L", QVariantList() << "EyesWide_Left" << 1.0);
        blendshapes.insertMulti("EyeOpen_R", QVariantList() << "EyesWide_Right" << 1.0);
        blendshapes.insertMulti("EyeSquint_L", QVariantList() << "Squint_Left" << 1.0);
        blendshapes.insertMulti("EyeSquint_R", QVariantList() << "Squint_Right" << 1.0);
        blendshapes.insertMulti("JawFwd", QVariantList() << "JawForeward" << 1.0);
        blendshapes.insertMulti("JawLeft", QVariantList() << "JawRotateY_Left" << 0.5);
        blendshapes.insertMulti("JawOpen", QVariantList() << "MouthOpen" << 0.7);
        blendshapes.insertMulti("JawRight", QVariantList() << "Jaw_Right" << 1.0);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "JawForeward" << 0.39);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "Jaw_Down" << 0.36);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "MouthNarrow_Left" << 1.0);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "MouthNarrow_Right" << 1.0);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "MouthWhistle_NarrowAdjust_Left" << 0.5);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "MouthWhistle_NarrowAdjust_Right" << 0.5);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "TongueUp" << 1.0);
        blendshapes.insertMulti("LipsLowerClose", QVariantList() << "LowerLipIn" << 1.0);
        blendshapes.insertMulti("LipsLowerDown", QVariantList() << "LowerLipDown_Left" << 0.7);
        blendshapes.insertMulti("LipsLowerDown", QVariantList() << "LowerLipDown_Right" << 0.7);
        blendshapes.insertMulti("LipsLowerOpen", QVariantList() << "LowerLipOut" << 1.0);
        blendshapes.insertMulti("LipsPucker", QVariantList() << "MouthNarrow_Left" << 1.0);
        blendshapes.insertMulti("LipsPucker", QVariantList() << "MouthNarrow_Right" << 1.0);
        blendshapes.insertMulti("LipsUpperClose", QVariantList() << "UpperLipIn" << 1.0);
        blendshapes.insertMulti("LipsUpperOpen", QVariantList() << "UpperLipOut" << 1.0);
        blendshapes.insertMulti("LipsUpperUp", QVariantList() << "UpperLipUp_Left" << 0.7);
        blendshapes.insertMulti("LipsUpperUp", QVariantList() << "UpperLipUp_Right" << 0.7);
        blendshapes.insertMulti("MouthDimple_L", QVariantList() << "Smile_Left" << 0.25);
        blendshapes.insertMulti("MouthDimple_R", QVariantList() << "Smile_Right" << 0.25);
        blendshapes.insertMulti("MouthFrown_L", QVariantList() << "Frown_Left" << 1.0);
        blendshapes.insertMulti("MouthFrown_R", QVariantList() << "Frown_Right" << 1.0);
        blendshapes.insertMulti("MouthLeft", QVariantList() << "Midmouth_Left" << 1.0);
        blendshapes.insertMulti("MouthRight", QVariantList() << "Midmouth_Right" << 1.0);
        blendshapes.insertMulti("MouthSmile_L", QVariantList() << "Smile_Left" << 1.0);
        blendshapes.insertMulti("MouthSmile_R", QVariantList() << "Smile_Right" << 1.0);
        blendshapes.insertMulti("Puff", QVariantList() << "CheekPuff_Left" << 1.0);
        blendshapes.insertMulti("Puff", QVariantList() << "CheekPuff_Right" << 1.0);
        blendshapes.insertMulti("Sneer", QVariantList() << "NoseScrunch_Left" << 0.75);
        blendshapes.insertMulti("Sneer", QVariantList() << "NoseScrunch_Right" << 0.75);
        blendshapes.insertMulti("Sneer", QVariantList() << "Squint_Left" << 0.5);
        blendshapes.insertMulti("Sneer", QVariantList() << "Squint_Right" << 0.5);
        mapping.insert(BLENDSHAPE_FIELD, blendshapes);
    }
}
Example #21
0
 void SessionEntryTunnel::IncomingData(const Request &request)
 {
   QVariantHash hash = request.GetData().toHash();
   m_tunnel.IncomingData(hash.value("data").toByteArray());
 }