void OptionsDialog::setSettings() {
    passwordEdit->setText(getSetting("password", "").toString());
    coreEdit->setText(getSetting("coreAddress", "localhost").toString());
    refreshSpin->setValue(getSetting("refresh", 3).toInt());
    savePassword->setChecked(getSetting("savePassword", false).toBool());
    useCompression->setChecked(getSetting("useCompression", false).toBool());
    showSplash->setChecked(getSetting("showSplash", true).toBool());
    trayCheckBox->setChecked(getSetting("useTray", false).toBool());
    altRowsCheckBox->setChecked(getSetting("altRows", false).toBool());
    serverEdit->setText(getSetting("serverURL", "http://www.applejuicenet.de/18.0.html").toString());
    launchCombo->setEditText(getSetting("launcher", launchCombo->itemText(0)).toString());
    int location = getSetting("location", AjSettings::SAME).toInt();
    sameComputerRadio->setChecked(location == AjSettings::SAME);
    specificRadio->setChecked(location == AjSettings::SPECIFIC);
    ftpRadio->setChecked(location == AjSettings::FTP);
    incomingSpecificEdit->setText(getSetting("incomingDirSpecific", "/").toString());
    tempSpecificEdit->setText(getSetting("tempDirSpecific", "/").toString());
    ftpServerEdit->setText(getSetting("ftp", "server", "localhost").toString());
    ftpPortEdit->setText(getSetting("ftp", "port", "21").toString());
    ftpUserEdit->setText(getSetting("ftp", "user", "anonymous").toString());
    ftpPasswordEdit->setText(getSetting("ftp", "password", "").toString());
    ftpInDirEdit->setText(getSetting("ftp", "inDir", "/").toString());
    ftpTmpDirEdit->setText(getSetting("ftp", "tmpDir", "/").toString());
    ftpActiveRadioButton->setChecked(getSetting("ftp", "mode", QFtp::Active) == QFtp::Active);
    ftpPassiveRadioButton->setChecked(getSetting("ftp", "mode", QFtp::Active) == QFtp::Passive);
    ftpMbSpinBox->setValue(getSetting("ftp", "mb", "10").toInt());
    bool ftpFull = getSetting("ftp", "full", false).toBool();
    ftpFullRadioButton->setChecked(ftpFull);
    ftpMbRadioButton->setChecked(!ftpFull);
    fetchServersCheckBox->setChecked(getSetting("fetchServersOnStartup", false).toBool());
    languageComboBox->setCurrentIndex(languageComboBox->findData(getSetting("language", "en").toString().split("_")[0]));

    // -- lists for optionaly showing columns/labales --
    statusbarList->clear();
    QList<QVariant> statusbarShow = getStatusbarShows(juicer->statusBarWidgets.size());
    for(int i=0; i<juicer->statusBarWidgets.size(); i++) {
        statusbarList->addItem(juicer->statusBarWidgets.at(i)->toolTip());
        statusbarList->item(statusbarList->count()-1)->setCheckState(
            statusbarShow.at(i).toBool()?Qt::Checked:Qt::Unchecked);
    }
    downloadTabList->clear();
    QTreeWidgetItem* h = juicer->downloadsTreeWidget->headerItem();
    for(int i=0; i<h->columnCount(); i++) {
        downloadTabList->addItem(h->text(i));
        downloadTabList->item(downloadTabList->count()-1)->setCheckState(
            juicer->downloadsTreeWidget->isColumnHidden(i)?Qt::Unchecked:Qt::Checked);
    }
    uploadTabList->clear();
    h = juicer->uploadsTreeWidget->headerItem();
    for(int i=0; i<h->columnCount(); i++) {
        uploadTabList->addItem(h->text(i));
        uploadTabList->item(uploadTabList->count()-1)->setCheckState(
            juicer->uploadsTreeWidget->isColumnHidden(i)?Qt::Unchecked:Qt::Checked);
    }

    QFont font;
    QVariant v = getSetting("font", QApplication::font());
    if (v.isValid() && ! v.toString().isEmpty()) {
        font = v.value<QFont>();
    }
    else {
      font = QFont("Arial", 9, QFont::Normal);
    }
    QApplication::setFont(font);
    fontComboBox->setCurrentFont(font);
    setFontSizes(font);
#ifdef Q_WS_WIN
    handlerCheckCheckBox->setChecked(!OptionsDialog::hasSetting("handler") || OptionsDialog::getSetting("handler", false).toBool());
    handlerDefaultCheckBox->setChecked(OptionsDialog::hasSetting("handler") && OptionsDialog::getSetting("handler", false).toBool());
    handlerDefaultCheckBox->setEnabled(handlerCheckCheckBox->isChecked());
#endif
    checkUpdatesCheckBox->setChecked(getSetting("checkUpdates", true).toBool());
    observeClipboardCheckBox->setChecked(getSetting("observeClipboard", false).toBool());
    quitGUIAfterCoreExitCheckBox->setChecked(getSetting("quitGUIAfterCoreExit", true).toBool());
    profilesStatusbarCheckBox->setChecked(getSetting("profilesStatusbar", false).toBool());
    videoEdit->setText(video());
    audioEdit->setText(audio());
    imageEdit->setText(image());
    textEdit->setText(text());
    archiveEdit->setText(archive());
    cddvdEdit->setText(cddvd());
}
void _LogListener::logged(ctkLogEntryPtr entry)
{
    // This is where the assembly as specified in 133.6.6 OSGi R4
    // compendium is taking place (i.e., the log entry is adapted to
    // an event and posted via the ctkEventAdmin)

    ctkDictionary properties;

    QSharedPointer<ctkPlugin> plugin = entry->getPlugin();
    if (plugin)
    {
        properties.insert("plugin.id", QVariant::fromValue<long>(plugin->getPluginId()));

        const QString symbolicName = plugin->getSymbolicName();

        if (!symbolicName.isEmpty())
        {
            properties.insert(ctkEventConstants::PLUGIN_SYMBOLICNAME,
                              symbolicName);
        }

        properties.insert("plugin", QVariant::fromValue(plugin));
    }

    properties.insert("log.level", entry->getLevel());
    properties.insert(ctkEventConstants::MESSAGE, entry->getMessage());
    properties.insert(ctkEventConstants::TIMESTAMP, entry->getTime());
    properties.insert("log.entry", QVariant::fromValue(entry));

    const std::exception* exc = entry->getException();
    if (exc)
    {
        //properties.insert(ctkEventConstants::EXCEPTION_CLASS,
        //        exception.getClass().getName());

        const QString message(exc->what());
        if (!message.isEmpty())
        {
            properties.insert(ctkEventConstants::EXCEPTION_MESSAGE,
                              message);
        }

        properties.insert(ctkEventConstants::EXCEPTION, exc);
    }

    ctkServiceReference service = entry->getServiceReference();
    if (service)
    {
        properties.insert(ctkEventConstants::SERVICE, QVariant::fromValue(service));

        QVariant id = service.getProperty(ctkEventConstants::SERVICE_ID);

        if (id.isValid())
        {
            properties.insert(ctkEventConstants::SERVICE_ID, id);
            QVariant pid = service.getProperty(ctkEventConstants::SERVICE_PID);
            if (pid.isValid())
            {
                properties.insert(ctkEventConstants::SERVICE_PID, pid);
            }

            QVariant objectClass = service.getProperty(ctkPluginConstants::OBJECTCLASS);
            if (objectClass.isValid())
            {
                properties.insert(ctkEventConstants::SERVICE_OBJECTCLASS, objectClass);
            }
        }
    }

    QString topic("org/commontk/service/log/LogEntry/");

    int level = entry->getLevel();
    if (level == ctkLogService::LOG_ERROR)
    {
        topic.append("LOG_ERROR");
    }
    else if (level == ctkLogService::LOG_WARNING)
    {
        topic.append("LOG_WARNING");
    }
    else if (level == ctkLogService::LOG_INFO)
    {
        topic.append("LOG_INFO");
    }
    else if (level == ctkLogService::LOG_DEBUG)
    {
        topic.append("LOG_DEBUG");
    }
    else
    {
        topic.append("LOG_OTHER");
    }

    try
    {
        adapter->getEventAdmin()->postEvent(ctkEvent(topic, properties));
    }
    catch(const std::logic_error&)
    {
        // This is o.k. - indicates that we are stopped.
    }
}
/*!

*/
void
DebugMessageWindow::readSettings()
{
#ifndef Q_WS_WIN
    QSettings settings( QDir::homePath() + "/.soccerwindow2-qt4",
                        QSettings::IniFormat );
#else
    QSettings settings( QDir::currentPath() + "/soccerwindow2.ini",
                        QSettings::IniFormat );
#endif
    //QSettings settings( QSettings::IniFormat,
    //                    QSettings::UserScope,
    //                    PACKAGE_NAME );

    settings.beginGroup( "DebugMessageWindow" );

    // read debug view switch status
    {
        QVariant val;

        val = settings.value( tr( "debug_view_all" ) );
        if ( val.isValid() )
        {
            M_show_debug_view_all_act->setChecked( val.toBool() );
            toggleShowDebugViewAll( val.toBool() );
        }

        val = settings.value( tr( "debug_view_self" ) );
        if ( val.isValid() )
        {
            M_show_debug_view_self_act->setChecked( val.toBool() );
            toggleShowDebugViewSelf( val.toBool() );
        }

        val = settings.value( tr( "debug_view_ball" ) );
        if ( val.isValid() )
        {
            M_show_debug_view_ball_act->setChecked( val.toBool() );
            toggleShowDebugViewBall( val.toBool() );
        }

        val = settings.value( tr( "debug_view_teammates" ) );
        if ( val.isValid() )
        {
            M_show_debug_view_teammates_act->setChecked( val.toBool() );
            toggleShowDebugViewTeammates( val.toBool() );
        }

        val = settings.value( tr( "debug_view_opponents" ) );
        if ( val.isValid() )
        {
            M_show_debug_view_opponents_act->setChecked( val.toBool() );
            toggleShowDebugViewOpponents( val.toBool() );
        }

        val = settings.value( tr( "debug_view_comment" ) );
        if ( val.isValid() )
        {
            M_show_debug_view_comment_act->setChecked( val.toBool() );
            toggleShowDebugViewComment( val.toBool() );
        }

        val = settings.value( tr( "debug_view_shape" ) );
        if ( val.isValid() )
        {
            M_show_debug_view_shape_act->setChecked( val.toBool() );
            toggleShowDebugViewShape( val.toBool() );
        }

        val = settings.value( tr( "debug_view_target" ) );
        if ( val.isValid() )
        {
            M_show_debug_view_target_act->setChecked( val.toBool() );
            toggleShowDebugViewTarget( val.toBool() );
        }

        val = settings.value( tr( "debug_view_message" ) );
        if ( val.isValid() )
        {
            M_show_debug_view_message_act->setChecked( val.toBool() );
            toggleShowDebugViewMessage( val.toBool() );
        }

        val = settings.value( tr( "debug_log_objects" ) );
        if ( val.isValid() )
        {
            M_show_debug_log_objects_act->setChecked( val.toBool() );
            toggleShowDebugLogObjects( val.toBool() );
        }

    }

    // read debug switch status
    for ( int i = 0; i < 32; ++i )
    {
        //snprintf( key, 16, "debug%02d", i + 1 );
        QVariant val = settings.value( QString( "debug%1" ).arg( i + 1, 2, 10, QChar( '0' ) ) );
        if ( val.isValid() )
        {
            bool enable = val.toBool();

            boost::int32_t level = DebugLogData::LEVEL_01 << i;
            M_main_data.getDebugLogHolder().setLevel( level, enable );

            M_debug_level_act[i]->setChecked( enable );
        }
        else
        {
            M_debug_level_act[i]->setChecked( true );
        }
    }

    // read debug text string
    for ( int i = 0; i < 32; ++i )
    {
        //snprintf( key, 32, "debug_text_%02d", i + 1 );
        QVariant val = settings.value( QString( "debug_text_%1" ).arg( i + 1, 2, 10, QChar( '0' ) ) );
        if ( val.isValid() )
        {
            M_debug_text[i] = val.toString();
            //QString text = tr( "Level %1 " ).arg( i + 1 );
            //text += M_debug_text[i];
            //M_debug_level_act[i]->setText( text );
            //M_debug_level_act[i]->setStatusTip( tr( "Debug " ) + text );
            M_debug_level_act[i]->setText( M_debug_text[i] );
            M_debug_level_act[i]->setStatusTip( tr( "Debug " ) + M_debug_text[i] );
        }
    }

    settings.endGroup();
}
void LocationManager::onFinished(QNetworkReply *reply) {
	if (!manager) return;
	if (reply->error() != QNetworkReply::NoError) return onFailed(reply);

	QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	if (statusCode.isValid()) {
		int status = statusCode.toInt();
		if (status == 301 || status == 302) {
			QString loc = reply->header(QNetworkRequest::LocationHeader).toString();
			if (!loc.isEmpty()) {
				QMap<QNetworkReply*, LocationData*>::iterator i = dataLoadings.find(reply);
				if (i != dataLoadings.cend()) {
					LocationData *d = i.value();
					if (serverRedirects.constFind(d) == serverRedirects.cend()) {
						serverRedirects.insert(d, 1);
					} else if (++serverRedirects[d] > MaxHttpRedirects) {
						DEBUG_LOG(("Network Error: Too many HTTP redirects in onFinished() for image link: %1").arg(loc));
						return onFailed(reply);
					}
					dataLoadings.erase(i);
					dataLoadings.insert(manager->get(QNetworkRequest(loc)), d);
					return;
				} else if ((i = imageLoadings.find(reply)) != imageLoadings.cend()) {
					LocationData *d = i.value();
					if (serverRedirects.constFind(d) == serverRedirects.cend()) {
						serverRedirects.insert(d, 1);
					} else if (++serverRedirects[d] > MaxHttpRedirects) {
						DEBUG_LOG(("Network Error: Too many HTTP redirects in onFinished() for image link: %1").arg(loc));
						return onFailed(reply);
					}
					imageLoadings.erase(i);
					imageLoadings.insert(manager->get(QNetworkRequest(loc)), d);
					return;
				}
			}
		}
		if (status != 200) {
			DEBUG_LOG(("Network Error: Bad HTTP status received in onFinished() for image link: %1").arg(status));
			return onFailed(reply);
		}
	}

	LocationData *d = 0;
	QMap<QNetworkReply*, LocationData*>::iterator i = dataLoadings.find(reply);
	if (i != dataLoadings.cend()) {
		d = i.value();
		dataLoadings.erase(i);

		QJsonParseError e;
		QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &e);
		if (e.error != QJsonParseError::NoError) {
			DEBUG_LOG(("JSON Error: Bad json received in onFinished() for image link"));
			return onFailed(reply);
		}
		failed(d);

		if (App::main()) App::main()->update();
	} else {
		i = imageLoadings.find(reply);
		if (i != imageLoadings.cend()) {
			d = i.value();
			imageLoadings.erase(i);

			QPixmap thumb;
			QByteArray format;
			QByteArray data(reply->readAll());
			{
				QBuffer buffer(&data);
				QImageReader reader(&buffer);
#ifndef OS_MAC_OLD
				reader.setAutoTransform(true);
#endif // OS_MAC_OLD
				thumb = QPixmap::fromImageReader(&reader, Qt::ColorOnly);
				format = reader.format();
				thumb.setDevicePixelRatio(cRetinaFactor());
				if (format.isEmpty()) format = QByteArray("JPG");
			}
			d->loading = false;
			d->thumb = thumb.isNull() ? (*notLoadedPlaceholder) : ImagePtr(thumb, format);
			serverRedirects.remove(d);
			if (App::main()) App::main()->update();
		}
	}
}
/*!
  Applies the given \a command to the given \a backend.
*/
QScriptDebuggerResponse QScriptDebuggerCommandExecutor::execute(
    QScriptDebuggerBackend *backend,
    const QScriptDebuggerCommand &command)
{
    QScriptDebuggerResponse response;
    switch (command.type()) {
    case QScriptDebuggerCommand::None:
        break;

    case QScriptDebuggerCommand::Interrupt:
        backend->interruptEvaluation();
        break;

    case QScriptDebuggerCommand::Continue:
        if (backend->engine()->isEvaluating()) {
            backend->continueEvalution();
            response.setAsync(true);
        }
        break;

    case QScriptDebuggerCommand::StepInto: {
        QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount);
        int count = attr.isValid() ? attr.toInt() : 1;
        backend->stepInto(count);
        response.setAsync(true);
    }   break;

    case QScriptDebuggerCommand::StepOver: {
        QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount);
        int count = attr.isValid() ? attr.toInt() : 1;
        backend->stepOver(count);
        response.setAsync(true);
    }   break;

    case QScriptDebuggerCommand::StepOut:
        backend->stepOut();
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::RunToLocation:
        backend->runToLocation(command.fileName(), command.lineNumber());
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::RunToLocationByID:
        backend->runToLocation(command.scriptId(), command.lineNumber());
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::ForceReturn: {
        int contextIndex = command.contextIndex();
        QScriptDebuggerValue value = command.scriptValue();
        QScriptEngine *engine = backend->engine();
        QScriptValue realValue = value.toScriptValue(engine);
        backend->returnToCaller(contextIndex, realValue);
        response.setAsync(true);
    }   break;

    case QScriptDebuggerCommand::Resume:
        backend->resume();
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::SetBreakpoint: {
        QScriptBreakpointData data = command.breakpointData();
        if (!data.isValid())
            data = QScriptBreakpointData(command.fileName(), command.lineNumber());
        int id = backend->setBreakpoint(data);
        response.setResult(id);
    }   break;

    case QScriptDebuggerCommand::DeleteBreakpoint: {
        int id = command.breakpointId();
        if (!backend->deleteBreakpoint(id))
            response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
    }   break;

    case QScriptDebuggerCommand::DeleteAllBreakpoints:
        backend->deleteAllBreakpoints();
        break;

    case QScriptDebuggerCommand::GetBreakpoints: {
        QScriptBreakpointMap bps = backend->breakpoints();
        if (!bps.isEmpty())
            response.setResult(bps);
    }   break;

    case QScriptDebuggerCommand::GetBreakpointData: {
        int id = command.breakpointId();
        QScriptBreakpointData data = backend->breakpointData(id);
        if (data.isValid())
            response.setResult(data);
        else
            response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
    }   break;

    case QScriptDebuggerCommand::SetBreakpointData: {
        int id = command.breakpointId();
        QScriptBreakpointData data = command.breakpointData();
        if (!backend->setBreakpointData(id, data))
            response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
    }   break;

    case QScriptDebuggerCommand::GetScripts: {
        QScriptScriptMap scripts = backend->scripts();
        if (!scripts.isEmpty())
            response.setResult(scripts);
    }   break;

    case QScriptDebuggerCommand::GetScriptData: {
        qint64 id = command.scriptId();
        QScriptScriptData data = backend->scriptData(id);
        if (data.isValid())
            response.setResult(data);
        else
            response.setError(QScriptDebuggerResponse::InvalidScriptID);
    }   break;

    case QScriptDebuggerCommand::ScriptsCheckpoint:
        backend->scriptsCheckpoint();
        response.setResult(QVariant::fromValue(backend->scriptsDelta()));
        break;

    case QScriptDebuggerCommand::GetScriptsDelta:
        response.setResult(QVariant::fromValue(backend->scriptsDelta()));
        break;

    case QScriptDebuggerCommand::ResolveScript:
        response.setResult(backend->resolveScript(command.fileName()));
        break;

    case QScriptDebuggerCommand::GetBacktrace:
        response.setResult(backend->backtrace());
        break;

    case QScriptDebuggerCommand::GetContextCount:
        response.setResult(backend->contextCount());
        break;

    case QScriptDebuggerCommand::GetContextState: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(static_cast<int>(ctx->state()));
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetContextID: {
        int idx = command.contextIndex();
        if ((idx >= 0) && (idx < backend->contextCount()))
            response.setResult(backend->contextIds()[idx]);
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetContextInfo: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(QScriptContextInfo(ctx));
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetThisObject: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(ctx->thisObject());
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetActivationObject: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(ctx->activationObject());
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetScopeChain: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx) {
            QScriptDebuggerValueList dest;
            QScriptValueList src = ctx->scopeChain();
            for (int i = 0; i < src.size(); ++i)
                dest.append(src.at(i));
            response.setResult(dest);
        } else {
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
        }
    }   break;

    case QScriptDebuggerCommand::ContextsCheckpoint: {
        response.setResult(QVariant::fromValue(backend->contextsCheckpoint()));
    }   break;

    case QScriptDebuggerCommand::GetPropertyExpressionValue: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        int lineNumber = command.lineNumber();
        QVariant attr = command.attribute(QScriptDebuggerCommand::UserAttribute);
        QStringList path = attr.toStringList();
        if (!ctx || path.isEmpty())
            break;
        QScriptContextInfo ctxInfo(ctx);
        if (ctx->callee().isValid()
            && ((lineNumber < ctxInfo.functionStartLineNumber())
                || (lineNumber > ctxInfo.functionEndLineNumber()))) {
            break;
        }
        QScriptValueList objects;
        int pathIndex = 0;
        if (path.at(0) == QLatin1String("this")) {
            objects.append(ctx->thisObject());
            ++pathIndex;
        } else {
            objects << ctx->scopeChain();
        }
        for (int i = 0; i < objects.size(); ++i) {
            QScriptValue val = objects.at(i);
            for (int j = pathIndex; val.isValid() && (j < path.size()); ++j) {
                val = val.property(path.at(j));
            }
            if (val.isValid()) {
                bool hadException = (ctx->state() == QScriptContext::ExceptionState);
                QString str = val.toString();
                if (!hadException && backend->engine()->hasUncaughtException())
                    backend->engine()->clearExceptions();
                response.setResult(str);
                break;
            }
        }
    }   break;

    case QScriptDebuggerCommand::GetCompletions: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        QVariant attr = command.attribute(QScriptDebuggerCommand::UserAttribute);
        QStringList path = attr.toStringList();
        if (!ctx || path.isEmpty())
            break;
        QScriptValueList objects;
        QString prefix = path.last();
        QSet<QString> matches;
        if (path.size() > 1) {
            const QString &topLevelIdent = path.at(0);
            QScriptValue obj;
            if (topLevelIdent == QLatin1String("this")) {
                obj = ctx->thisObject();
            } else {
                QScriptValueList scopeChain;
                scopeChain = ctx->scopeChain();
                for (int i = 0; i < scopeChain.size(); ++i) {
                    QScriptValue oo = scopeChain.at(i).property(topLevelIdent);
                    if (oo.isObject()) {
                        obj = oo;
                        break;
                    }
                }
            }
            for (int i = 1; obj.isObject() && (i < path.size()-1); ++i)
                obj = obj.property(path.at(i));
            if (obj.isValid())
                objects.append(obj);
        } else {
            objects << ctx->scopeChain();
            QStringList keywords;
            keywords.append(QString::fromLatin1("this"));
            keywords.append(QString::fromLatin1("true"));
            keywords.append(QString::fromLatin1("false"));
            keywords.append(QString::fromLatin1("null"));
            for (int i = 0; i < keywords.size(); ++i) {
                const QString &kwd = keywords.at(i);
                if (isPrefixOf(prefix, kwd))
                    matches.insert(kwd);
            }
        }

        for (int i = 0; i < objects.size(); ++i) {
            QScriptValue obj = objects.at(i);
            while (obj.isObject()) {
                QScriptValueIterator it(obj);
                while (it.hasNext()) {
                    it.next();
                    QString propertyName = it.name();
                    if (isPrefixOf(prefix, propertyName))
                        matches.insert(propertyName);
                }
                obj = obj.prototype();
            }
        }
        QStringList matchesList = matches.toList();
        qStableSort(matchesList);
        response.setResult(matchesList);
    }   break;

    case QScriptDebuggerCommand::NewScriptObjectSnapshot: {
        int id = backend->newScriptObjectSnapshot();
        response.setResult(id);
    }   break;

    case QScriptDebuggerCommand::ScriptObjectSnapshotCapture: {
        int id = command.snapshotId();
        QScriptObjectSnapshot *snap = backend->scriptObjectSnapshot(id);
        Q_ASSERT(snap != 0);
        QScriptDebuggerValue object = command.scriptValue();
        Q_ASSERT(object.type() == QScriptDebuggerValue::ObjectValue);
        QScriptEngine *engine = backend->engine();
        QScriptValue realObject = object.toScriptValue(engine);
        Q_ASSERT(realObject.isObject());
        QScriptObjectSnapshot::Delta delta = snap->capture(realObject);
        QScriptDebuggerObjectSnapshotDelta result;
        result.removedProperties = delta.removedProperties;
        bool didIgnoreExceptions = backend->ignoreExceptions();
        backend->setIgnoreExceptions(true);
        for (int i = 0; i < delta.changedProperties.size(); ++i) {
            const QScriptValueProperty &src = delta.changedProperties.at(i);
            bool hadException = engine->hasUncaughtException();
            QString str = src.value().toString();
            if (!hadException && engine->hasUncaughtException())
                engine->clearExceptions();
            QScriptDebuggerValueProperty dest(src.name(), src.value(), str, src.flags());
            result.changedProperties.append(dest);
        }
        for (int j = 0; j < delta.addedProperties.size(); ++j) {
            const QScriptValueProperty &src = delta.addedProperties.at(j);
            bool hadException = engine->hasUncaughtException();
            QString str = src.value().toString();
            if (!hadException && engine->hasUncaughtException())
                engine->clearExceptions();
            QScriptDebuggerValueProperty dest(src.name(), src.value(), str, src.flags());
            result.addedProperties.append(dest);
        }
        backend->setIgnoreExceptions(didIgnoreExceptions);
        response.setResult(QVariant::fromValue(result));
    }   break;

    case QScriptDebuggerCommand::DeleteScriptObjectSnapshot: {
        int id = command.snapshotId();
        backend->deleteScriptObjectSnapshot(id);
    }   break;

    case QScriptDebuggerCommand::NewScriptValueIterator: {
        QScriptDebuggerValue object = command.scriptValue();
        Q_ASSERT(object.type() == QScriptDebuggerValue::ObjectValue);
        QScriptEngine *engine = backend->engine();
        QScriptValue realObject = object.toScriptValue(engine);
        Q_ASSERT(realObject.isObject());
        int id = backend->newScriptValueIterator(realObject);
        response.setResult(id);
    }   break;

    case QScriptDebuggerCommand::GetPropertiesByIterator: {
        int id = command.iteratorId();
        int count = 1000;
        QScriptValueIterator *it = backend->scriptValueIterator(id);
        Q_ASSERT(it != 0);
        QScriptDebuggerValuePropertyList props;
        for (int i = 0; (i < count) && it->hasNext(); ++i) {
            it->next();
            QString name = it->name();
            QScriptValue value = it->value();
            QString valueAsString = value.toString();
            QScriptValue::PropertyFlags flags = it->flags();
            QScriptDebuggerValueProperty prp(name, value, valueAsString, flags);
            props.append(prp);
        }
        response.setResult(props);
    }   break;

    case QScriptDebuggerCommand::DeleteScriptValueIterator: {
        int id = command.iteratorId();
        backend->deleteScriptValueIterator(id);
    }   break;

    case QScriptDebuggerCommand::Evaluate: {
        int contextIndex = command.contextIndex();
        QString program = command.program();
        QString fileName = command.fileName();
        int lineNumber = command.lineNumber();
        backend->evaluate(contextIndex, program, fileName, lineNumber);
        response.setAsync(true);
    }   break;

    case QScriptDebuggerCommand::ScriptValueToString: {
        QScriptDebuggerValue value = command.scriptValue();
        QScriptEngine *engine = backend->engine();
        QScriptValue realValue = value.toScriptValue(engine);
        response.setResult(realValue.toString());
    }   break;

    case QScriptDebuggerCommand::SetScriptValueProperty: {
        QScriptDebuggerValue object = command.scriptValue();
        QScriptEngine *engine = backend->engine();
        QScriptValue realObject = object.toScriptValue(engine);
        QScriptDebuggerValue value = command.subordinateScriptValue();
        QScriptValue realValue = value.toScriptValue(engine);
        QString name = command.name();
        realObject.setProperty(name, realValue);
    }   break;

    case QScriptDebuggerCommand::ClearExceptions:
        backend->engine()->clearExceptions();
        break;

    case QScriptDebuggerCommand::UserCommand:
    case QScriptDebuggerCommand::MaxUserCommand:
        break;
    }
    return response;
}
Example #6
0
QWidget* QmitkPropertyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option
  , const QModelIndex &index) const
{
  QVariant data = index.data(Qt::EditRole);
  QVariant displayData = index.data(Qt::DisplayRole);
  QString name = index.model()->data(index.model()->index(index.row(), index.column()-1)).value<QString>();

  if(data.isValid())
  {

    QWidget* editorWidget = NULL;

    if(data.type() == QVariant::Color)
    {
      QPushButton* colorBtn = new QPushButton(parent);
      QColor color = data.value<QColor>();

      QColor result = QColorDialog::getColor(color);
      if(result.isValid())
      {
        QPalette palette = colorBtn->palette();
        palette.setColor(QPalette::Button, result);
        colorBtn->setPalette(palette);
        colorBtn->setStyleSheet(QString("background-color: %1;foreground-color: %1; border-style: none;").arg(result.name()));
      }
      // QColorDialog closed by 'Cancel' button, use the old property color
      else
      {
        QPalette palette = colorBtn->palette();
        palette.setColor(QPalette::Button, color);
        colorBtn->setPalette(palette);
        colorBtn->setStyleSheet(QString("background-color: %1;foreground-color: %1; border-style: none;").arg(color.name()));

      }

      connect(colorBtn, SIGNAL(pressed()), this, SLOT(commitAndCloseEditor()));

      editorWidget = colorBtn;
    }

    else if(data.type() == QVariant::Int)
    {
      QSpinBox* spinBox = new QSpinBox(parent);
      spinBox->setSingleStep(1);
      spinBox->setMinimum(std::numeric_limits<int>::min());
      spinBox->setMaximum(std::numeric_limits<int>::max());
      editorWidget = spinBox;
    }
    // see qt documentation. cast is correct, it would be obsolete if we
    // store doubles
    else if(static_cast<QMetaType::Type>(data.type()) == QMetaType::Float)
    {
      QDoubleSpinBox* spinBox = new QDoubleSpinBox(parent);
      spinBox->setDecimals(2);
      spinBox->setSingleStep(0.1);
      if(name == "opacity")
      {
        spinBox->setMinimum(0.0);
        spinBox->setMaximum(1.0);
      }
      else
      {
        spinBox->setMinimum(std::numeric_limits<float>::min());
        spinBox->setMaximum(std::numeric_limits<float>::max());
      }

      editorWidget = spinBox;
    }

    else if(data.type() == QVariant::StringList)
    {
      QStringList entries = data.value<QStringList>();
      QComboBox* comboBox = new QComboBox(parent);
      comboBox->setEditable(false);
      comboBox->addItems(entries);

      editorWidget = comboBox;
    }


    else
    {
      editorWidget = QStyledItemDelegate::createEditor(parent, option, index);
    }

    if ( editorWidget )
    {
      // install event filter
      editorWidget->installEventFilter( const_cast<QmitkPropertyDelegate*>(this) );
    }

    return editorWidget;

  }
  else
    return new QLabel(displayData.toString(), parent);

}
Example #7
0
void MainWindow::openLastFiles()
{
    mSettings.beginGroup(QLatin1String("recentFiles"));

    QStringList lastOpenFiles = mSettings.value(
                QLatin1String("lastOpenFiles")).toStringList();
    QVariant openCountVariant = mSettings.value(
                QLatin1String("recentOpenedFiles"));

    // Backwards compatibility mode
    if (openCountVariant.isValid()) {
        const QStringList recentFiles = mSettings.value(
                    QLatin1String("fileNames")).toStringList();
        int openCount = qMin(openCountVariant.toInt(), recentFiles.size());
        for (; openCount; --openCount)
            lastOpenFiles.append(recentFiles.at(openCount - 1));
        mSettings.remove(QLatin1String("recentOpenedFiles"));
    }

    QStringList mapScales = mSettings.value(
                QLatin1String("mapScale")).toStringList();
    QStringList scrollX = mSettings.value(
                QLatin1String("scrollX")).toStringList();
    QStringList scrollY = mSettings.value(
                QLatin1String("scrollY")).toStringList();
    QStringList selectedLayer = mSettings.value(
                QLatin1String("selectedLayer")).toStringList();

    for (int i = 0; i < lastOpenFiles.size(); i++) {
        if (!(i < mapScales.size()))
            continue;
        if (!(i < scrollX.size()))
            continue;
        if (!(i < scrollY.size()))
            continue;
        if (!(i < selectedLayer.size()))
            continue;

        if (openFile(lastOpenFiles.at(i))) {
            MapView *mapView = mDocumentManager->currentMapView();

            // Restore camera to the previous position
            qreal scale = mapScales.at(i).toDouble();
            if (scale > 0)
                mapView->zoomable()->setScale(scale);

            const int hor = scrollX.at(i).toInt();
            const int ver = scrollY.at(i).toInt();
            mapView->horizontalScrollBar()->setSliderPosition(hor);
            mapView->verticalScrollBar()->setSliderPosition(ver);

            int layer = selectedLayer.at(i).toInt();
            if (layer > 0 && layer < mMapDocument->map()->layerCount())
                mMapDocument->setCurrentLayerIndex(layer);
        }
    }
    QString lastActiveDocument =
            mSettings.value(QLatin1String("lastActive")).toString();
    int documentIndex = mDocumentManager->findDocument(lastActiveDocument);
    if (documentIndex != -1)
        mDocumentManager->switchToDocument(documentIndex);

    mSettings.endGroup();
}
void QgsRelationReferenceWidget::setForeignKey( const QVariant& value )
{
  if ( !value.isValid() || value.isNull() )
  {
    deleteForeignKey();
    return;
  }

  if ( !mReferencedLayer )
    return;

  QgsFeatureIterator fit;

  // TODO: Rewrite using expression
  if ( mMasterModel )
  {
    fit = mMasterModel->layerCache()->getFeatures( QgsFeatureRequest() );
  }
  else
  {
    fit = mReferencedLayer->getFeatures( QgsFeatureRequest() );
  }
  while ( fit.nextFeature( mFeature ) )
  {
    if ( mFeature.attribute( mFkeyFieldIdx ) == value )
    {
      break;
    }
  }

  if ( !mFeature.isValid() )
  {
    deleteForeignKey();
    return;
  }

  mForeignKey = mFeature.attribute( mFkeyFieldIdx );

  if ( mReadOnlySelector )
  {
    QgsExpression expr( mReferencedLayer->displayExpression() );
    QString title = expr.evaluate( &mFeature ).toString();
    if ( expr.hasEvalError() )
    {
      title = mFeature.attribute( mFkeyFieldIdx ).toString();
    }
    mLineEdit->setText( title );
  }
  else
  {
    int i = mComboBox->findData( value, QgsAttributeTableModel::FeatureIdRole );
    if ( i == -1 && mAllowNull )
    {
      mComboBox->setCurrentIndex( 0 );
    }
    else
    {
      mComboBox->setCurrentIndex( i );
    }
  }

  mRemoveFKButton->setEnabled( mIsEditable );
  highlightFeature( mFeature );
  updateAttributeEditorFrame( mFeature );
  emit foreignKeyChanged( foreignKey() );
}
Example #9
0
void DLListDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
	QString byteUnits[4] = {tr("B"), tr("KB"), tr("MB"), tr("GB")};
	QStyleOptionViewItem opt = option;
	QStyleOptionProgressBarV2 newopt;
	QRect pixmapRect;
	QPixmap pixmap;
	qlonglong fileSize;
	double dlspeed, multi;
	int seconds,minutes, hours, days;
	qlonglong remaining;
    QString temp ;
	qlonglong completed;
	qlonglong downloadtime;
    qint64 qi64Value;

	// prepare
	painter->save();
	painter->setClipRect(opt.rect);

	//set text color
        QVariant value = index.data(Qt::TextColorRole);
        if(value.isValid() && qvariant_cast<QColor>(value).isValid()) {
                opt.palette.setColor(QPalette::Text, qvariant_cast<QColor>(value));
        }
        QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled;
        if(option.state & QStyle::State_Selected){
                painter->setPen(opt.palette.color(cg, QPalette::HighlightedText));
        } else {
                painter->setPen(opt.palette.color(cg, QPalette::Text));
        }

        // draw the background color if not the progress column or if progress is not displayed
        if(index.column() != COLUMN_PROGRESS) {
                if(option.showDecorationSelected && (option.state & QStyle::State_Selected)) {
                        if(cg == QPalette::Normal && !(option.state & QStyle::State_Active)) {
                                cg = QPalette::Inactive;
                        }
                        painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
                } else {
                        value = index.data(Qt::BackgroundRole);
                        if(value.isValid() && qvariant_cast<QColor>(value).isValid()) {
                                painter->fillRect(option.rect, qvariant_cast<QColor>(value));
                        }
                }
        }
	switch(index.column()) {
        case COLUMN_SIZE:
			fileSize = index.data().toLongLong();
                        if(fileSize <= 0){
                                temp = "";
			} else {
				multi = 1.0;
				for(int i = 0; i < 5; ++i) {
					if (fileSize < 1024) {
						fileSize = index.data().toLongLong();
						temp.sprintf("%.2f ", fileSize / multi);
						temp += byteUnits[i];
						break;
					}
					fileSize /= 1024;
					multi *= 1024.0;
				}
			}
			painter->drawText(option.rect, Qt::AlignRight, temp);
			break;
        case COLUMN_REMAINING:
			remaining = index.data().toLongLong();
			if(remaining <= 0){
        temp = "";
			} else {
				multi = 1.0;
				for(int i = 0; i < 5; ++i) {
					if (remaining < 1024) {
						remaining = index.data().toLongLong();
						temp.sprintf("%.2f ", remaining / multi);
						temp += byteUnits[i];
						break;
					}
					remaining /= 1024;
					multi *= 1024.0;
				}
			}
			painter->drawText(option.rect, Qt::AlignRight, temp);
			break;
        case COLUMN_COMPLETED:
			completed = index.data().toLongLong();
                        if(completed <= 0){
                                temp = "";
			} else {
				multi = 1.0;
				for(int i = 0; i < 5; ++i) {
					if (completed < 1024) {
						completed = index.data().toLongLong();
						temp.sprintf("%.2f ", completed / multi);
						temp += byteUnits[i];
						break;
					}
					completed /= 1024;
					multi *= 1024.0;
				}
			}
			painter->drawText(option.rect, Qt::AlignRight, temp);
			break;
        case COLUMN_DLSPEED:
                        dlspeed = index.data().toDouble();
                        if (dlspeed <= 0) {
                            temp = "";
                        } else {
                            temp.clear();
                            temp.sprintf("%.2f", dlspeed/1024.);
                            temp += " KB/s";
                        }
			painter->drawText(option.rect, Qt::AlignRight, temp);
			break;
        case COLUMN_PROGRESS:
			{
				// create a xProgressBar
				FileProgressInfo pinfo = index.data().value<FileProgressInfo>() ;

//				std::cerr << "drawing progress info: nb_chunks = " << pinfo.nb_chunks ;
//				for(uint i=0;i<pinfo.cmap._map.size();++i)
//					std::cerr << pinfo.cmap._map[i] << " " ;
//				std::cerr << std::endl ;
				
				painter->save() ;
				xProgressBar progressBar(pinfo,option.rect, painter); // the 3rd param is the  color schema (0 is the default value)
				if(pinfo.type == FileProgressInfo::DOWNLOAD_LINE)
				{
					progressBar.setDisplayText(true); // should display % text?
					progressBar.setColorSchema(0) ;
				}
				else
				{
					progressBar.setDisplayText(false); // should display % text?
					progressBar.setColorSchema(1) ;
				}
				progressBar.setVerticalSpan(1);
				progressBar.paint(); // paint the progress bar

				painter->restore() ;
			}
			painter->drawText(option.rect, Qt::AlignCenter, newopt.text);
			break;
	case COLUMN_SOURCES:
	{
		double dblValue = index.data().toDouble();

		temp = dblValue!=0 ? QString("%1 (%2)").arg((int)dblValue).arg((int)((fmod(dblValue,1)*1000)+0.5)) : "";
		painter->drawText(option.rect, Qt::AlignCenter, temp);
	}
			break;
        case COLUMN_DOWNLOADTIME:
			downloadtime = index.data().toLongLong();
			minutes = downloadtime / 60;
			seconds = downloadtime % 60;
			hours = minutes / 60;
			minutes = minutes % 60 ;
			days = hours / 24;
			hours = hours % 24 ;
			if(days > 0) {
				temp = QString::number(days)+"d "+QString::number(hours)+"h" ;
			} else if(hours > 0 || days > 0) {
				temp = QString::number(hours)+"h "+QString::number(minutes)+"m" ;
			} else if(minutes > 0 || hours > 0) {
				temp = QString::number(minutes)+"m"+QString::number(seconds)+"s" ;
			} else if(seconds > 0) {
				temp = QString::number(seconds)+"s" ;
			} else
				temp = "" ;
			painter->drawText(option.rect, Qt::AlignCenter, temp);
			break;
        case COLUMN_NAME:
        		// decoration
                        value = index.data(Qt::DecorationRole);
                        temp = index.data().toString();
                        pixmap = qvariant_cast<QIcon>(value).pixmap(option.decorationSize, option.state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled, option.state & QStyle::State_Open ? QIcon::On : QIcon::Off);
                        pixmapRect = (pixmap.isNull() ? QRect(0, 0, 0, 0): QRect(QPoint(0, 0), option.decorationSize));
                        if (pixmapRect.isValid()){
                                QPoint p = QStyle::alignedRect(option.direction, Qt::AlignLeft, pixmap.size(), option.rect).topLeft();
                                painter->drawPixmap(p, pixmap);
                                temp = " " + temp;
                        }
                        painter->drawText(option.rect.translated(pixmap.size().width(), 0), Qt::AlignLeft, temp);
                        break;
    case COLUMN_LASTDL:
        qi64Value = index.data().value<qint64>();
        if (qi64Value < std::numeric_limits<qint64>::max()){
            QDateTime qdtLastDL = QDateTime::fromTime_t(qi64Value);
            painter->drawText(option.rect, Qt::AlignCenter, qdtLastDL.toString("yyyy-MM-dd_hh:mm:ss"));
        } else {
            painter->drawText(option.rect, Qt::AlignCenter, tr("File Never Seen"));
        }
        break;
		default:
			painter->drawText(option.rect, Qt::AlignCenter, index.data().toString());
	}

	// done
	painter->restore();
}
Example #10
0
void BWListDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
	QString strNA = tr("N/A");
	QStyleOptionViewItem opt = option;

	QString temp ;
	float flValue;
	qint64 qi64Value;

	// prepare
	painter->save();
	painter->setClipRect(opt.rect);

	//set text color
	QVariant value = index.data(Qt::TextColorRole);
	if(value.isValid() && qvariant_cast<QColor>(value).isValid()) {
		opt.palette.setColor(QPalette::Text, qvariant_cast<QColor>(value));
	}
	QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled;
	if(option.state & QStyle::State_Selected){
		painter->setPen(opt.palette.color(cg, QPalette::HighlightedText));
	} else {
		painter->setPen(opt.palette.color(cg, QPalette::Text));
	}

	// draw the background color
	if(option.showDecorationSelected && (option.state & QStyle::State_Selected)) {
		if(cg == QPalette::Normal && !(option.state & QStyle::State_Active)) {
			cg = QPalette::Inactive;
		}
		painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
	} else {
		value = index.data(Qt::BackgroundRole);
		if(value.isValid() && qvariant_cast<QColor>(value).isValid()) {
			painter->fillRect(option.rect, qvariant_cast<QColor>(value));
		}
	}

	switch(index.column()) {
	case COLUMN_IN_RATE:
		temp.sprintf("%.3f ", index.data().toFloat());
		//temp=QString::number(index.data().toFloat());
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	case COLUMN_IN_MAX:
		temp.sprintf("%.3f ", index.data().toFloat());
		//temp=QString::number(index.data().toFloat());
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	case COLUMN_IN_QUEUE:
		temp=QString::number(index.data().toInt());
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	case COLUMN_IN_ALLOC:
		flValue = index.data().toFloat();
		if (flValue < std::numeric_limits<float>::max()){
			temp.sprintf("%.3f ", flValue);
		} else {
			temp=strNA;
		}
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	case COLUMN_IN_ALLOC_SENT:
		qi64Value = index.data().value<qint64>();
		if (qi64Value < std::numeric_limits<qint64>::max()){
			temp= QString::number(qi64Value);
		} else {
			temp = strNA;
		}
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	case COLUMN_OUT_RATE:
		temp.sprintf("%.3f ", index.data().toFloat());
		//temp=QString::number(index.data().toFloat());
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	case COLUMN_OUT_MAX:
		temp.sprintf("%.3f ", index.data().toFloat());
		//temp=QString::number(index.data().toFloat());
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	case COLUMN_OUT_QUEUE:
		temp=QString::number(index.data().toInt());
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	case COLUMN_OUT_ALLOC:
		flValue = index.data().toFloat();
		if (flValue < std::numeric_limits<float>::max()){
			temp=QString::number(flValue);
		} else {
			temp = strNA;
		}
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	case COLUMN_OUT_ALLOC_SENT:
		qi64Value = index.data().value<qint64>();
		if (qi64Value < std::numeric_limits<qint64>::max()){
			temp= QString::number(qi64Value);
		} else {
			temp = strNA;
		}
		painter->drawText(option.rect, Qt::AlignRight, temp);
		break;
	default:
		painter->drawText(option.rect, Qt::AlignLeft, index.data().toString());
	}

	// done
	painter->restore();
}
Example #11
0
ObjectGroup *VariantToMapConverter::toObjectGroup(const QVariantMap &variantMap)
{
    typedef QScopedPointer<ObjectGroup> ObjectGroupPtr;
    ObjectGroupPtr objectGroup(new ObjectGroup(variantMap[QLatin1String("name")].toString(),
                                               variantMap[QLatin1String("x")].toInt(),
                                               variantMap[QLatin1String("y")].toInt(),
                                               variantMap[QLatin1String("width")].toInt(),
                                               variantMap[QLatin1String("height")].toInt()));

    const qreal opacity = variantMap[QLatin1String("opacity")].toReal();
    const bool visible = variantMap[QLatin1String("visible")].toBool();

    objectGroup->setOpacity(opacity);
    objectGroup->setVisible(visible);

    objectGroup->setColor(variantMap.value(QLatin1String("color")).value<QColor>());

    const QString drawOrderString = variantMap.value(QLatin1String("draworder")).toString();
    if (!drawOrderString.isEmpty()) {
        objectGroup->setDrawOrder(drawOrderFromString(drawOrderString));
        if (objectGroup->drawOrder() == ObjectGroup::UnknownOrder) {
            mError = tr("Invalid draw order: %1").arg(drawOrderString);
            return nullptr;
        }
    }

    foreach (const QVariant &objectVariant, variantMap[QLatin1String("objects")].toList()) {
        const QVariantMap objectVariantMap = objectVariant.toMap();

        const QString name = objectVariantMap[QLatin1String("name")].toString();
        const QString type = objectVariantMap[QLatin1String("type")].toString();
        const int id = objectVariantMap[QLatin1String("id")].toInt();
        const int gid = objectVariantMap[QLatin1String("gid")].toInt();
        const qreal x = objectVariantMap[QLatin1String("x")].toReal();
        const qreal y = objectVariantMap[QLatin1String("y")].toReal();
        const qreal width = objectVariantMap[QLatin1String("width")].toReal();
        const qreal height = objectVariantMap[QLatin1String("height")].toReal();
        const qreal rotation = objectVariantMap[QLatin1String("rotation")].toReal();

        const QPointF pos(x, y);
        const QSizeF size(width, height);

        MapObject *object = new MapObject(name, type, pos, size);
        object->setId(id);
        object->setRotation(rotation);

        if (gid) {
            bool ok;
            object->setCell(mGidMapper.gidToCell(gid, ok));

            if (!object->cell().isEmpty()) {
                const QSizeF &tileSize = object->cell().tile->size();
                if (width == 0)
                    object->setWidth(tileSize.width());
                if (height == 0)
                    object->setHeight(tileSize.height());
            }
        }

        if (objectVariantMap.contains(QLatin1String("visible")))
            object->setVisible(objectVariantMap[QLatin1String("visible")].toBool());

        object->setProperties(extractProperties(objectVariantMap));
        objectGroup->addObject(object);

        const QVariant polylineVariant = objectVariantMap[QLatin1String("polyline")];
        const QVariant polygonVariant = objectVariantMap[QLatin1String("polygon")];

        if (polygonVariant.isValid()) {
            object->setShape(MapObject::Polygon);
            object->setPolygon(toPolygon(polygonVariant));
        }
        if (polylineVariant.isValid()) {
            object->setShape(MapObject::Polyline);
            object->setPolygon(toPolygon(polylineVariant));
        }
        if (objectVariantMap.contains(QLatin1String("ellipse")))
            object->setShape(MapObject::Ellipse);
    }

    return objectGroup.take();
}
Example #12
0
AudioEditor::AudioEditor(QWidget* parent, Audio *audio, Doc* doc)
    : QWidget(parent)
    , m_doc(doc)
    , m_audio(audio)
    , m_speedDials(NULL)
{
    Q_ASSERT(doc != NULL);
    Q_ASSERT(audio != NULL);

    setupUi(this);

    m_nameEdit->setText(m_audio->name());
    m_nameEdit->setSelection(0, m_nameEdit->text().length());

    m_fadeInEdit->setText(Function::speedToString(audio->fadeInSpeed()));
    m_fadeOutEdit->setText(Function::speedToString(audio->fadeOutSpeed()));

    connect(m_nameEdit, SIGNAL(textEdited(const QString&)),
            this, SLOT(slotNameEdited(const QString&)));
    connect(m_fileButton, SIGNAL(clicked()),
            this, SLOT(slotSourceFileClicked()));

    connect(m_speedDialButton, SIGNAL(toggled(bool)),
            this, SLOT(slotSpeedDialToggle(bool)));

    connect(m_fadeInEdit, SIGNAL(returnPressed()),
            this, SLOT(slotFadeInEdited()));
    connect(m_fadeOutEdit, SIGNAL(returnPressed()),
            this, SLOT(slotFadeOutEdited()));

    connect(m_previewButton, SIGNAL(toggled(bool)),
            this, SLOT(slotPreviewToggled(bool)));

    AudioDecoder *adec = m_audio->getAudioDecoder();

    m_filenameLabel->setText(m_audio->getSourceFileName());
    if (adec != NULL)
    {
        AudioParameters ap = adec->audioParameters();
        m_durationLabel->setText(Function::speedToString(m_audio->getDuration()));
        m_srateLabel->setText(QString("%1 Hz").arg(ap.sampleRate()));
        m_channelsLabel->setText(QString("%1").arg(ap.channels()));
        m_bitrateLabel->setText(QString("%1 kb/s").arg(adec->bitrate()));
    }

    QList<AudioDeviceInfo> devList;
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
 #if defined( __APPLE__) || defined(Q_OS_MAC)
    devList = AudioRendererPortAudio::getDevicesInfo();
 #elif defined(WIN32) || defined(Q_OS_WIN)
    devList = AudioRendererWaveOut::getDevicesInfo();
 #else
    devList = AudioRendererAlsa::getDevicesInfo();
 #endif
#else
    devList = AudioRendererQt::getDevicesInfo();
#endif
    QSettings settings;
    QString outputName;
    int i = 0, selIdx = 0;

    m_audioDevCombo->addItem(tr("Default device"), "__qlcplusdefault__");
    if (m_audio->audioDevice().isEmpty())
    {
        QVariant var = settings.value(SETTINGS_AUDIO_OUTPUT_DEVICE);
        if (var.isValid() == true)
            outputName = var.toString();
    }
    else
        outputName = m_audio->audioDevice();

    foreach( AudioDeviceInfo info, devList)
    {
        if (info.capabilities & AUDIO_CAP_OUTPUT)
        {
            m_audioDevCombo->addItem(info.deviceName, info.privateName);

            if (info.privateName == outputName)
                selIdx = i;
            i++;
        }
    }
    m_audioDevCombo->setCurrentIndex(selIdx);
    connect(m_audioDevCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(slotAudioDeviceChanged(int)));

    // Set focus to the editor
    m_nameEdit->setFocus();
}
Example #13
0
bool FEMemoryMetaData::parseMetaData(QString json)
{
	QJson::Parser parser;
	QVariant top = parser.parse(json.toStdString().c_str());
	if (!top.isValid())
	{
		QString errormsg = QString("Error parsing JSON from config file on line number: ") + QString::number(parser.errorLine()) + " error text: " + parser.errorString();
		qDebug() << "Error parsing JSON";
		qDebug() << "Line number:" << parser.errorLine() << "error text:" << parser.errorString();
		qDebug() << "Start Json";
		qDebug() << "Json:" << json;
		qDebug() << "End Json";
		return false;
	}
	QVariantMap topmap = top.toMap();
	QVariantMap errormap = topmap["errormap"].toMap();
	QVariantMap::iterator i = errormap.begin();
	while (i != errormap.end())
	{
		bool ok = false;
		m_errorMap[i.value().toString().mid(2).toInt(&ok,16)] = i.key();
		i++;
	}

	QVariantMap ramvars = topmap["ramvars"].toMap();
	i = ramvars.begin();
	while (i != ramvars.end())
	{
		bool ok = false;
		unsigned short locid = i.key().mid(2).toInt(&ok,16);
		m_readOnlyMetaDataMap[locid] = ReadOnlyRamBlock();
		QVariantMap locidlist = i.value().toMap();
		QString title = locidlist["title"].toString();
		m_readOnlyMetaDataMap[locid].title = title;
		QVariantList locidmap = locidlist["vars"].toList();
		int offset = 0;
		for (int j=0;j<locidmap.size();j++)
		{
			QVariantMap newlocidmap = locidmap[j].toMap();
			ReadOnlyRamData rdata;
			rdata.dataTitle = newlocidmap["name"].toString();
			rdata.dataDescription = newlocidmap["title"].toString();
			rdata.locationId = locid;
			rdata.offset = offset;
			rdata.size = newlocidmap["size"].toInt();
			offset += rdata.size;
			m_readOnlyMetaDataMap[locid].m_ramData.append(rdata);
			m_readOnlyMetaData.append(rdata);
		}
		i++;
	}

	QVariantMap lookups = topmap["lookuptables"].toMap();
	i = lookups.begin();
	while (i != lookups.end())
	{
		QVariantMap lookupmap = i.value().toMap();
		QString keystr = i.key();
		bool ok = false;
		unsigned short keyint = keystr.mid(2).toInt(&ok,16);
		LookupMetaData meta;
		meta.locationid = keyint;
		meta.title = lookupmap["title"].toString();
		if (lookupmap["editable"].toString().toLower() == "true")
		{
			meta.editable = true;
		}
		else
		{
			meta.editable = false;
		}
		m_lookupMetaData[keyint] = meta;
		i++;
	}
	qDebug() << m_readOnlyMetaData.size() << "Ram entries found";
	QVariantMap tables = topmap["tables"].toMap();
	i = tables.begin();
	while (i != tables.end())
	{
		QVariantMap tabledata = i.value().toMap();
		if (tabledata["type"] == "3D")
		{
			Table3DMetaData meta;
			QString id = tabledata["locationid"].toString();
			QString xtitle = tabledata["xtitle"].toString();
			QVariantList xcalc = tabledata["xcalc"].toList();
			QString xdp = tabledata["xdp"].toString();
			unsigned int size = tabledata["size"].toInt();

			QString ytitle = tabledata["ytitle"].toString();
			QVariantList ycalc = tabledata["ycalc"].toList();
			QString ydp = tabledata["ydp"].toString();

			QString ztitle = tabledata["ztitle"].toString();
			QVariantList zcalc = tabledata["zcalc"].toList();
			QString zdp = tabledata["zdp"].toString();

			QString xhighlight = tabledata["xhighlight"].toString();
			QString yhighlight = tabledata["yhighlight"].toString();

			QList<QPair<QString,double> > xcalclist;
			QList<QPair<QString,double> > ycalclist;
			QList<QPair<QString,double> > zcalclist;
			for (int j=0;j<xcalc.size();j++)
			{
				qDebug() << "XCalc:" << xcalc[j].toMap()["type"].toString() << xcalc[j].toMap()["value"].toDouble();
				xcalclist.append(QPair<QString,double>(xcalc[j].toMap()["type"].toString(),xcalc[j].toMap()["value"].toDouble()));
			}
			for (int j=0;j<ycalc.size();j++)
			{
				ycalclist.append(QPair<QString,double>(ycalc[j].toMap()["type"].toString(),ycalc[j].toMap()["value"].toDouble()));
			}
			for (int j=0;j<zcalc.size();j++)
			{
				zcalclist.append(QPair<QString,double>(zcalc[j].toMap()["type"].toString(),zcalc[j].toMap()["value"].toDouble()));
			}

			bool ok = false;
			meta.locationId = id.mid(2).toInt(&ok,16);
			meta.tableTitle = i.key();
			meta.xAxisCalc = xcalclist;
			meta.xAxisTitle = xtitle;
			meta.xDp = xdp.toInt();
			meta.yAxisCalc = ycalclist;
			meta.yAxisTitle = ytitle;
			meta.yDp = ydp.toInt();
			meta.zAxisCalc = zcalclist;
			meta.zAxisTitle = ztitle;
			meta.zDp = zdp.toInt();
			meta.size = size;
			meta.valid = true;
			meta.xHighlight = xhighlight;
			meta.yHighlight = yhighlight;
            for (int i=0;i<m_table3DMetaData.size();i++)
            {
                if (m_table3DMetaData[i].locationId == meta.locationId)
                {
                    //Error, already exists;
                    qDebug() << "Error: Location ID 0x" + QString::number(meta.locationId,16).toUpper() + " is defined twice in the metadata file";
                    return false;
                }
            }
			m_table3DMetaData.append(meta);
		}
		else if (tabledata["type"] == "2D")
		{
			Table2DMetaData meta;
			QString id = tabledata["locationid"].toString();
			QString xtitle = tabledata["xtitle"].toString();
			QVariantList xcalc = tabledata["xcalc"].toList();
			QString xdp = tabledata["xdp"].toString();
			QString ytitle = tabledata["ytitle"].toString();
			QVariantList ycalc = tabledata["ycalc"].toList();
			QString ydp = tabledata["ydp"].toString();
			unsigned int size = tabledata["size"].toInt();
			QString xhighlight = tabledata["xhighlight"].toString();

			QList<QPair<QString,double> > xcalclist;
			QList<QPair<QString,double> > ycalclist;

			for (int j=0;j<xcalc.size();j++)
			{
				qDebug() << "XCalc:" << xcalc[j].toMap()["type"].toString() << xcalc[j].toMap()["value"].toDouble();
				xcalclist.append(QPair<QString,double>(xcalc[j].toMap()["type"].toString(),xcalc[j].toMap()["value"].toDouble()));
			}
			for (int j=0;j<ycalc.size();j++)
			{
				ycalclist.append(QPair<QString,double>(ycalc[j].toMap()["type"].toString(),ycalc[j].toMap()["value"].toDouble()));
			}
			bool ok = false;
			meta.locationId = id.mid(2).toInt(&ok,16);
			meta.tableTitle = i.key();
			meta.xAxisCalc = xcalclist;
			meta.xAxisTitle = xtitle;
			meta.xDp = xdp.toInt();
			meta.yAxisCalc = ycalclist;
			meta.yAxisTitle = ytitle;
			meta.yDp = ydp.toInt();
			meta.size = size;
			meta.valid = true;
			meta.xHighlight = xhighlight;
            for (int i=0;i<m_table2DMetaData.size();i++)
            {
                if (m_table2DMetaData[i].locationId == meta.locationId)
                {
                    //Error, already exists;
                    qDebug() << "Error: Location ID 0x" + QString::number(meta.locationId,16).toUpper() + " is defined twice in the metadata file";
                    return false;
                }
            }
			m_table2DMetaData.append(meta);
		}
		i++;
	}
	return true;
}
SeasideCache::SeasideCache()
    : m_manager(managerName())
#ifdef HAS_MLITE
    , m_displayLabelOrderConf(QLatin1String("/org/nemomobile/contacts/display_label_order"))
#endif
    , m_resultsRead(0)
    , m_populated(0)
    , m_cacheIndex(0)
    , m_queryIndex(0)
    , m_selfId(0)
    , m_fetchFilter(SeasideFilteredModel::FilterFavorites)
    , m_displayLabelOrder(SeasideFilteredModel::FirstNameFirst)
    , m_updatesPending(true)
    , m_refreshRequired(false)
{
    Q_ASSERT(!instance);
    instance = this;

    m_timer.start();

#ifdef HAS_MLITE
    connect(&m_displayLabelOrderConf, SIGNAL(valueChanged()), this, SLOT(displayLabelOrderChanged()));
    QVariant displayLabelOrder = m_displayLabelOrderConf.value();
    if (displayLabelOrder.isValid())
        m_displayLabelOrder = SeasideFilteredModel::DisplayLabelOrder(displayLabelOrder.toInt());
#endif

    connect(&m_manager, SIGNAL(dataChanged()), this, SLOT(updateContacts()));
    connect(&m_manager, SIGNAL(contactsChanged(QList<QContactLocalId>)),
            this, SLOT(updateContacts(QList<QContactLocalId>)));
    connect(&m_manager, SIGNAL(contactsAdded(QList<QContactLocalId>)),
            this, SLOT(updateContacts(QList<QContactLocalId>)));
    connect(&m_manager, SIGNAL(contactsRemoved(QList<QContactLocalId>)),
            this, SLOT(contactsRemoved(QList<QContactLocalId>)));

    connect(&m_fetchRequest, SIGNAL(resultsAvailable()), this, SLOT(contactsAvailable()));
    connect(&m_contactIdRequest, SIGNAL(resultsAvailable()), this, SLOT(contactIdsAvailable()));

    connect(&m_fetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
            this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
    connect(&m_contactIdRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
            this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
    connect(&m_removeRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
            this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
    connect(&m_saveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
            this, SLOT(requestStateChanged(QContactAbstractRequest::State)));

    m_fetchRequest.setManager(&m_manager);
    m_removeRequest.setManager(&m_manager);
    m_saveRequest.setManager(&m_manager);

#ifdef SEASIDE_SPARQL_QUERIES
    m_contactIdRequest.setQueryData(true);
    m_contactIdRequest.setFavoritesOnly(true);
    m_contactIdRequest.setSortOnFirstName(m_displayLabelOrder == SeasideFilteredModel::FirstNameFirst);

    m_contactIdRequest.start();
#else
    m_selfId = m_manager.selfContactId();
    m_contactIdRequest.setManager(&m_manager);

    QContactFetchHint fetchHint;
    fetchHint.setOptimizationHints(QContactFetchHint::NoRelationships
                                   | QContactFetchHint::NoActionPreferences
                                   | QContactFetchHint::NoBinaryBlobs);
    fetchHint.setDetailDefinitionsHint(QStringList()
                                       << QContactName::DefinitionName
                                       << QContactAvatar::DefinitionName
                                       << QContactPhoneNumber::DefinitionName
                                       << QContactEmailAddress::DefinitionName
                                       << QContactOrganization::DefinitionName
                                       << QContactOnlineAccount::DefinitionName);

    m_fetchRequest.setFetchHint(fetchHint);
    m_fetchRequest.setFilter(QContactFavorite::match());

    QContactSortOrder firstLabelOrder;
    firstLabelOrder.setDetailDefinitionName(
        QContactName::DefinitionName, QContactName::FieldFirstName);
    firstLabelOrder.setCaseSensitivity(Qt::CaseInsensitive);
    firstLabelOrder.setDirection(Qt::AscendingOrder);
    firstLabelOrder.setBlankPolicy(QContactSortOrder::BlanksFirst);

    QContactSortOrder secondLabelOrder;
    secondLabelOrder.setDetailDefinitionName(
        QContactName::DefinitionName, QContactName::FieldLastName);
    secondLabelOrder.setCaseSensitivity(Qt::CaseInsensitive);
    secondLabelOrder.setDirection(Qt::AscendingOrder);
    secondLabelOrder.setBlankPolicy(QContactSortOrder::BlanksFirst);

    QList<QContactSortOrder> sorting = m_displayLabelOrder == SeasideFilteredModel::FirstNameFirst
                                       ? (QList<QContactSortOrder>() << firstLabelOrder << secondLabelOrder)
                                       : (QList<QContactSortOrder>() << secondLabelOrder << firstLabelOrder);

    m_fetchRequest.setSorting(sorting);
    m_contactIdRequest.setSorting(sorting);

    m_fetchRequest.start();
#endif

}
    void httpFinished() {
        DEBUG("httpFinished()");
        QVariant redirectionTarget = qreply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if (!redirectionTarget.isNull())
        {
            QUrl newUrl = url.resolved(redirectionTarget.toUrl());
            DEBUG("Handled redirect to: " << newUrl.toString());
            qreply->deleteLater();
            qreply = nullptr;
            doOperation(newUrl);
            return;
        }
        else if (qreply->error())
        {
            WARN("HTTP ERROR:" << qreply->error() << qreply->errorString());

            httpStatus = HTTPInvocationDefinition::UNDEFINED;
            invocationStatus = Invocation::ERROR;
            result << InvocationErrors::CONNECTION_FAILED
                   << Result::Meta("qnetworkreply_error_string", qreply->errorString())
                   << Result::Meta("qnetworkreply_error_number", qreply->error());

            QNetworkReply::NetworkError err = qreply->error();
            result << NetworkErrorReasons::from(err, qreply->errorString());

            // get possible return data
            replyData = qreply->readAll();
            if (!replyData.isEmpty())
                result << Result::Meta("response_data", replyData);

            emit q->finishedError(q);
        }
        else
        {
            // we have data
            replyData = qreply->readAll();
            QVariant statusCode = qreply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
            if (statusCode.isValid())
            {
                // TODO: handle more codes!
                switch (statusCode.toInt())
                {
                case 200:
                    httpStatus = HTTPInvocationDefinition::OK_200;
                    break;
                default:
                    httpStatus = HTTPInvocationDefinition::UNDEFINED;
                }
            } else {
                result << InvocationErrors::INVOCATION_FAILED
                       << Result::reasonFromDesc("Invalid http status code");
            }

            invocationStatus = Invocation::RESPONSE_RECEIVED;
            TRACE("DATA:" << replyData);
            emit q->finishedOK(q);
        }

        qreply->deleteLater();
        qreply = nullptr;
    }
QDBusMessage qDBusPropertyGet(const QDBusConnectionPrivate::ObjectTreeNode &node,
                              const QDBusMessage &msg)
{
    Q_ASSERT(msg.arguments().count() == 2);
    Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
               "QDBusConnection: internal threading error",
               "function called for an object that is in another thread!!");

    QString interface_name = msg.arguments().at(0).toString();
    QByteArray property_name = msg.arguments().at(1).toString().toUtf8();

    QDBusAdaptorConnector *connector;
    QVariant value;
    bool interfaceFound = false;
    if (node.flags & QDBusConnection::ExportAdaptors &&
        (connector = qDBusFindAdaptorConnector(node.obj))) {

        // find the class that implements interface_name or try until we've found the property
        // in case of an empty interface
        if (interface_name.isEmpty()) {
            for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
                 end = connector->adaptors.constEnd(); it != end; ++it) {
                const QMetaObject *mo = it->adaptor->metaObject();
                int pidx = mo->indexOfProperty(property_name);
                if (pidx != -1) {
                    value = mo->property(pidx).read(it->adaptor);
                    break;
                }
            }
        } else {
            QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
            it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
                             interface_name);
            if (it != connector->adaptors.constEnd() && interface_name == QLatin1String(it->interface)) {
                interfaceFound = true;
                value = it->adaptor->property(property_name);
            }
        }
    }

    if (!interfaceFound && !value.isValid()
        && node.flags & (QDBusConnection::ExportAllProperties |
                         QDBusConnection::ExportNonScriptableProperties)) {
        // try the object itself
        if (!interface_name.isEmpty())
            interfaceFound = qDBusInterfaceInObject(node.obj, interface_name);

        if (interfaceFound) {
            int pidx = node.obj->metaObject()->indexOfProperty(property_name);
            if (pidx != -1) {
                QMetaProperty mp = node.obj->metaObject()->property(pidx);
                if ((mp.isScriptable() && (node.flags & QDBusConnection::ExportScriptableProperties)) ||
                    (!mp.isScriptable() && (node.flags & QDBusConnection::ExportNonScriptableProperties)))
                    value = mp.read(node.obj);
            }
        }
    }

    if (!value.isValid()) {
        // the property was not found
        if (!interfaceFound)
            return interfaceNotFoundError(msg, interface_name);
        return propertyNotFoundError(msg, interface_name, property_name);
    }

    return msg.createReply(qVariantFromValue(QDBusVariant(value)));
}
Example #17
0
VCXYPad::VCXYPad(QWidget* parent, Doc* doc) : VCWidget(parent, doc)
{
    /* Set the class name "VCXYPad" as the object name as well */
    setObjectName(VCXYPad::staticMetaObject.className());

    m_hbox = new QHBoxLayout(this);
    m_lvbox = new QVBoxLayout;
    m_lvbox->addSpacing(20);
    m_vRangeSlider = new ctkRangeSlider(this);
    m_lvbox->addWidget(m_vRangeSlider);
    m_lvbox->addSpacing(25);

    m_hbox->addLayout(m_lvbox);

    m_cvbox = new QVBoxLayout;
    m_hbox->addLayout(m_cvbox);

    m_hRangeSlider = new ctkRangeSlider(Qt::Horizontal, this);
    m_cvbox->addWidget(m_hRangeSlider);

    m_area = new VCXYPadArea(this);
    m_cvbox->addWidget(m_area);

    m_hSlider = new QSlider(Qt::Horizontal, this);
    m_cvbox->addWidget(m_hSlider);

    m_rvbox = new QVBoxLayout;
    m_hbox->addLayout(m_rvbox);
    m_rvbox->addSpacing(20);
    m_vSlider = new QSlider(this);
    m_rvbox->addWidget(m_vSlider);
    m_rvbox->addSpacing(25);

    m_vSlider->setRange(0, 256);
    m_hSlider->setRange(0, 256);
    m_vSlider->setInvertedAppearance(true);
    m_vSlider->setTickPosition(QSlider::TicksLeft);
    m_vSlider->setTickInterval(16);
    m_hSlider->setTickPosition(QSlider::TicksAbove);
    m_hSlider->setTickInterval(16);
    m_vSlider->setStyle(AppUtil::saneStyle());
    m_hSlider->setStyle(AppUtil::saneStyle());

    m_hRangeSlider->setRange(0, 256);
    m_vRangeSlider->setInvertedAppearance(true);
    m_vRangeSlider->setRange(0, 256);
    m_hRangeSlider->setMaximumPosition(256);
    m_vRangeSlider->setMaximumPosition(256);

    connect(m_area, SIGNAL(positionChanged(const QPointF&)),
            this, SLOT(slotPositionChanged(const QPointF&)));
    connect(this, SIGNAL(fixturePositions(const QVariantList)),
            m_area, SLOT(slotFixturePositions(const QVariantList)));
    connect(m_vSlider, SIGNAL(valueChanged(int)),
            this, SLOT(slotSliderValueChanged()));
    connect(m_hSlider, SIGNAL(valueChanged(int)),
            this, SLOT(slotSliderValueChanged()));
    connect(m_hRangeSlider, SIGNAL(positionsChanged(int,int)),
            this, SLOT(slotRangeValueChanged()));
    connect(m_vRangeSlider, SIGNAL(positionsChanged(int,int)),
            this, SLOT(slotRangeValueChanged()));

    setFrameStyle(KVCFrameStyleSunken);
    setType(VCWidget::XYPadWidget);
    setCaption("XY Pad");
    setMinimumSize(20, 20);

    QSettings settings;
    QVariant var = settings.value(SETTINGS_XYPAD_SIZE);
    if (var.isValid() == true)
        resize(var.toSize());
    else
        resize(QSize(230, 230));
    m_padInteraction = false;
    m_sliderInteraction = false;
    m_inputValueChanged = false;

    slotModeChanged(Doc::Design);
}
int QgsInterpolator::cacheBaseData()
{
  if ( mLayerData.size() < 1 )
  {
    return 0;
  }

  //reserve initial memory for 100000 vertices
  mCachedBaseData.clear();
  mCachedBaseData.reserve( 100000 );

  Q_FOREACH ( const LayerData& layer, mLayerData )
  {
    if ( !layer.vectorLayer )
    {
      continue;
    }

    QgsVectorLayer* vlayer = layer.vectorLayer;
    if ( !vlayer )
    {
      return 2;
    }

    QgsAttributeList attList;
    if ( !layer.zCoordInterpolation )
    {
      attList.push_back( layer.interpolationAttribute );
    }


    double attributeValue = 0.0;
    bool attributeConversionOk = false;

    QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( attList ) );

    QgsFeature theFeature;
    while ( fit.nextFeature( theFeature ) )
    {
      if ( !layer.zCoordInterpolation )
      {
        QVariant attributeVariant = theFeature.attribute( layer.interpolationAttribute );
        if ( !attributeVariant.isValid() ) //attribute not found, something must be wrong (e.g. NULL value)
        {
          continue;
        }
        attributeValue = attributeVariant.toDouble( &attributeConversionOk );
        if ( !attributeConversionOk || qIsNaN( attributeValue ) ) //don't consider vertices with attributes like 'nan' for the interpolation
        {
          continue;
        }
      }

      if ( addVerticesToCache( theFeature.geometry(), layer.zCoordInterpolation, attributeValue ) != 0 )
      {
        return 3;
      }
    }
  }

  return 0;
}
void
PlayerPainter::readSettings()
{
#ifndef Q_WS_WIN
    QSettings settings( QDir::homePath() + "/.rcsslogplayer",
                        QSettings::IniFormat );
#else
    QSettings settings( QDir::currentPath() + "/rcsslogplayer.ini",
                        QSettings::IniFormat );
#endif

    settings.beginGroup( "PlayerPainter" );

    QVariant val;

    val = settings.value( "player_font" );
    if ( val.isValid() ) M_player_font.fromString( val.toString() );

    val = settings.value( "player_pen" );
    if ( val.isValid() ) M_player_pen.setColor( val.toString() );

    val = settings.value( "left_team" );
    if ( val.isValid() )
    {
        M_left_team_pen.setColor( val.toString() );
        M_left_team_brush.setColor( val.toString() );
    }

    val = settings.value( "left_goalie" );
    if ( val.isValid() )
    {
        M_left_goalie_pen.setColor( val.toString() );
        M_left_goalie_brush.setColor( val.toString() );
    }

    val = settings.value( "left_goalie_unreliable_catch" );
    if ( val.isValid() )
    {
        M_left_goalie_stretch_pen.setColor( val.toString() );
    }

    val = settings.value( "right_team" );
    if ( val.isValid() )
    {
        M_right_team_pen.setColor( val.toString() );
        M_right_team_brush.setColor( val.toString() );
    }

    val = settings.value( "right_goalie" );
    if ( val.isValid() )
    {
        M_right_goalie_pen.setColor( val.toString() );
        M_right_goalie_brush.setColor( val.toString() );
    }

    val = settings.value( "right_goalie_unreliable_catch" );
    if ( val.isValid() )
    {
        M_right_goalie_stretch_pen.setColor( val.toString() );
    }

    val = settings.value( "player_number_pen" );
    if ( val.isValid() ) M_player_number_pen.setColor( val.toString() );

    val = settings.value( "player_number_inner_pen" );
    if ( val.isValid() ) M_player_number_inner_pen.setColor( val.toString() );

    val = settings.value( "neck_pen" );
    if ( val.isValid() ) M_neck_pen.setColor( val.toString() );

    val = settings.value( "view_area_pen" );
    if ( val.isValid() ) M_view_area_pen.setColor( val.toString() );

    val = settings.value( "large_view_area_pen" );
    if ( val.isValid() ) M_large_view_area_pen.setColor( val.toString() );

    val = settings.value( "ball_collide_brush" );
    if ( val.isValid() ) M_ball_collide_brush.setColor( val.toString() );

    val = settings.value( "kick_pen" );
    if ( val.isValid() ) M_kick_pen.setColor( val.toString() );

    val = settings.value( "kick_fault_brush" );
    if ( val.isValid() ) M_kick_fault_brush.setColor( val.toString() );

    val = settings.value( "kick_accel_pen" );
    if ( val.isValid() ) M_kick_accel_pen.setColor( val.toString() );

    val = settings.value( "catch_brush" );
    if ( val.isValid() ) M_catch_brush.setColor( val.toString() );

    val = settings.value( "catch_fault_brush" );
    if ( val.isValid() ) M_catch_fault_brush.setColor( val.toString() );

    val = settings.value( "tackle_pen" );
    if ( val.isValid() ) M_tackle_pen.setColor( val.toString() );

    val = settings.value( "tackle_brush" );
    if ( val.isValid() ) M_tackle_brush.setColor( val.toString() );

    val = settings.value( "tackle_fault_brush" );
    if ( val.isValid() ) M_tackle_fault_brush.setColor( val.toString() );

    val = settings.value( "foul_charged_brush" );
    if ( val.isValid() ) M_foul_charged_brush.setColor( val.toString() );

    settings.endGroup();
}
Example #20
0
VCSlider::VCSlider(QWidget* parent, Doc* doc) : VCWidget(parent, doc)
{
    /* Set the class name "VCSlider" as the object name as well */
    setObjectName(VCSlider::staticMetaObject.className());

    m_hbox = NULL;
    m_topLabel = NULL;
    m_slider = NULL;
    m_bottomLabel = NULL;

    m_valueDisplayStyle = ExactValue;

    m_levelLowLimit = 0;
    m_levelHighLimit = UCHAR_MAX;

    m_levelValue = 0;
    m_levelValueChanged = false;
    m_monitorEnabled = false;
    m_monitorValue = 0;

    m_playbackFunction = Function::invalidId();
    m_playbackValue = 0;
    m_playbackValueChanged = false;

    m_widgetMode = WSlider;

    setType(VCWidget::SliderWidget);
    setCaption(QString());
    setFrameStyle(KVCFrameStyleSunken);

    /* Main VBox */
    new QVBoxLayout(this);

    /* Top label */
    m_topLabel = new QLabel(this);
    m_topLabel->setAlignment(Qt::AlignHCenter);

    layout()->addWidget(m_topLabel);

    /* Slider's HBox |stretch|slider|stretch| */
    m_hbox = new QHBoxLayout();

    /* Put stretchable space before the slider (to its left side) */
    m_hbox->addStretch();

    /* The slider */
    m_slider = new ClickAndGoSlider(this);

    m_hbox->addWidget(m_slider);
    m_slider->setRange(0, 255);
    m_slider->setPageStep(1);
    m_slider->setInvertedAppearance(false);
    m_slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    m_slider->setMinimumWidth(32);
    m_slider->setMaximumWidth(80);
    m_slider->setStyleSheet(CNG_DEFAULT_STYLE);

    connect(m_slider, SIGNAL(valueChanged(int)),
            this, SLOT(slotSliderMoved(int)));
    m_externalMovement = false;

    /* Put stretchable space after the slider (to its right side) */
    m_hbox->addStretch();

    layout()->addItem(m_hbox);

    /* Click & Go button */
    m_cngType = ClickAndGoWidget::None;

    m_cngButton = new QToolButton(this);
    m_cngButton->setFixedSize(48, 48);
    m_cngButton->setIconSize(QSize(42, 42));
    m_menu = new QMenu(this);
    QWidgetAction* action = new QWidgetAction(this);
    m_cngWidget = new ClickAndGoWidget();
    action->setDefaultWidget(m_cngWidget);
    m_menu->addAction(action);
    m_cngButton->setMenu(m_menu);
    m_cngButton->setPopupMode(QToolButton::InstantPopup);
    layout()->addWidget(m_cngButton);
    layout()->setAlignment(m_cngButton, Qt::AlignHCenter);
    m_cngButton->hide();

    connect(m_cngWidget, SIGNAL(levelChanged(uchar)),
            this, SLOT(slotClickAndGoLevelChanged(uchar)));
    connect(m_cngWidget, SIGNAL(colorChanged(QRgb)),
            this, SLOT(slotClickAndGoColorChanged(QRgb)));
    connect(m_cngWidget, SIGNAL(levelAndPresetChanged(uchar,QImage)),
            this, SLOT(slotClickAndGoLevelAndPresetChanged(uchar, QImage)));
    connect(this, SIGNAL(monitorDMXValueChanged(int)),
            this, SLOT(slotMonitorDMXValueChanged(int)));

    /* Bottom label */
    m_bottomLabel = new QLabel(this);
    layout()->addWidget(m_bottomLabel);
    m_bottomLabel->setAlignment(Qt::AlignCenter);
    m_bottomLabel->setWordWrap(true);
    m_bottomLabel->hide();

    setMinimumSize(20, 20);
    QSettings settings;
    QVariant var = settings.value(SETTINGS_SLIDER_SIZE);
    if (var.isValid() == true)
        resize(var.toSize());
    else
        resize(VCSlider::defaultSize);

    /* Initialize to playback mode by default */
    setInvertedAppearance(false);
    m_sliderMode = SliderMode(-1); // avoid use of uninitialized value
    setSliderMode(Playback);

    /* Update the slider according to current mode */
    slotModeChanged(m_doc->mode());
    setLiveEdit(m_liveEdit);

    /* Listen to fixture removals so that LevelChannels can be removed when
       they no longer point to an existing fixture->channel */
    connect(m_doc, SIGNAL(fixtureRemoved(quint32)),
            this, SLOT(slotFixtureRemoved(quint32)));
}
Example #21
0
{
    if (i < 0 || i >= rowCount())
        return InvalidExampleSet;
    QModelIndex modelIndex = index(i, 0);
    QVariant variant = data(modelIndex, Qt::UserRole + 2); /*Qt version uniqueId*/
    if (variant.isValid())
        return QtExampleSet;
    return ExtraExampleSet;
}

int ExampleSetModel::getQtId(int i) const
{
    QTC_ASSERT(i >= 0, return -1);
    QModelIndex modelIndex = index(i, 0);
    QVariant variant = data(modelIndex, Qt::UserRole + 2);
    QTC_ASSERT(variant.isValid(), return -1);
    QTC_ASSERT(variant.canConvert<int>(), return -1);
    return variant.toInt();
}

int ExampleSetModel::getExtraExampleSetIndex(int i) const
{
    QTC_ASSERT(i >= 0, return -1);
    QModelIndex modelIndex = index(i, 0);
    QVariant variant = data(modelIndex, Qt::UserRole + 3);
    QTC_ASSERT(variant.isValid(), return -1);
    QTC_ASSERT(variant.canConvert<int>(), return -1);
    return variant.toInt();
}

QHash<int, QByteArray> ExampleSetModel::roleNames() const
Example #22
0
void Peers::ctx_p2p_connect()
{
	if (ctx_item == NULL)
		return;
	QString addr = ctx_item->data(peer_role_address).toString();
	QString arg;
	int config_methods =
		ctx_item->data(peer_role_config_methods).toInt();
	enum selected_method method = SEL_METHOD_NONE;
	QVariant var = ctx_item->data(peer_role_selected_method);
	if (var.isValid())
		method = (enum selected_method) var.toInt();
	if (method == SEL_METHOD_PIN_LOCAL_DISPLAY) {
		arg = ctx_item->data(peer_role_selected_pin).toString();
		char cmd[100];
		char reply[100];
		size_t reply_len;
		snprintf(cmd, sizeof(cmd), "P2P_CONNECT %s %s display",
			 addr.toAscii().constData(),
			 arg.toAscii().constData());
		reply_len = sizeof(reply) - 1;
		if (wpagui->ctrlRequest(cmd, reply, &reply_len) < 0) {
			QMessageBox msg;
			msg.setIcon(QMessageBox::Warning);
			msg.setText("Failed to initiate P2P connect.");
			msg.exec();
			return;
		}
		QMessageBox::information(this,
					 tr("PIN for ") + ctx_item->text(),
					 tr("Enter the following PIN on the\n"
					    "peer device: ") + arg);
	} else if (method == SEL_METHOD_PIN_PEER_DISPLAY) {
		StringQuery input(tr("PIN from peer display:"));
		input.setWindowTitle(tr("PIN for ") + ctx_item->text());
		if (input.exec() != QDialog::Accepted)
			return;
		arg = input.get_string();
	} else if (config_methods == 0x0080 /* PBC */) {
		arg = "pbc";
	} else {
		StringQuery input(tr("PIN:"));
		input.setWindowTitle(tr("PIN for ") + ctx_item->text());
		if (input.exec() != QDialog::Accepted)
			return;
		arg = input.get_string();
	}

	char cmd[100];
	char reply[100];
	size_t reply_len;
	snprintf(cmd, sizeof(cmd), "P2P_CONNECT %s %s",
		 addr.toAscii().constData(),
		 arg.toAscii().constData());
	reply_len = sizeof(reply) - 1;
	if (wpagui->ctrlRequest(cmd, reply, &reply_len) < 0) {
		QMessageBox msg;
		msg.setIcon(QMessageBox::Warning);
		msg.setText("Failed to initiate P2P connect.");
		msg.exec();
	}
}
/*!
    Tests model's implementation of QAbstractItemModel::data()
 */
void ModelTest::data()
{
    // Invalid index should return an invalid qvariant
    Q_ASSERT(!model->data(QModelIndex()).isValid());

    if (model->rowCount() == 0)
        return;

    // A valid index should have a valid QVariant data
    Q_ASSERT(model->index(0, 0).isValid());

    // shouldn't be able to set data on an invalid index
    Q_ASSERT(model->setData(QModelIndex(), QLatin1String("foo"), Qt::DisplayRole) == false);

    // General Purpose roles that should return a QString
    QVariant variant = model->data(model->index(0, 0), Qt::ToolTipRole);
    if (variant.isValid()) {
        Q_ASSERT(qVariantCanConvert<QString>(variant));
    }
    variant = model->data(model->index(0, 0), Qt::StatusTipRole);
    if (variant.isValid()) {
        Q_ASSERT(qVariantCanConvert<QString>(variant));
    }
    variant = model->data(model->index(0, 0), Qt::WhatsThisRole);
    if (variant.isValid()) {
        Q_ASSERT(qVariantCanConvert<QString>(variant));
    }

    // General Purpose roles that should return a QSize
    variant = model->data(model->index(0, 0), Qt::SizeHintRole);
    if (variant.isValid()) {
        Q_ASSERT(qVariantCanConvert<QSize>(variant));
    }

    // General Purpose roles that should return a QFont
    QVariant fontVariant = model->data(model->index(0, 0), Qt::FontRole);
    if (fontVariant.isValid()) {
        Q_ASSERT(qVariantCanConvert<QFont>(fontVariant));
    }

    // Check that the alignment is one we know about
    QVariant textAlignmentVariant = model->data(model->index(0, 0), Qt::TextAlignmentRole);
    if (textAlignmentVariant.isValid()) {
        int alignment = textAlignmentVariant.toInt();
        Q_ASSERT(alignment == Qt::AlignLeft ||
                 alignment == Qt::AlignRight ||
                 alignment == Qt::AlignHCenter ||
                 alignment == Qt::AlignJustify ||
                 alignment == Qt::AlignTop ||
                 alignment == Qt::AlignBottom ||
                 alignment == Qt::AlignVCenter ||
                 alignment == Qt::AlignCenter ||
                 alignment == Qt::AlignAbsolute ||
                 alignment == Qt::AlignLeading ||
                 alignment == Qt::AlignTrailing);
    }

    // General Purpose roles that should return a QColor
    QVariant colorVariant = model->data(model->index(0, 0), Qt::BackgroundColorRole);
    if (colorVariant.isValid()) {
        Q_ASSERT(qVariantCanConvert<QColor>(colorVariant));
    }

    colorVariant = model->data(model->index(0, 0), Qt::TextColorRole);
    if (colorVariant.isValid()) {
        Q_ASSERT(qVariantCanConvert<QColor>(colorVariant));
    }

    // Check that the "check state" is one we know about.
    QVariant checkStateVariant = model->data(model->index(0, 0), Qt::CheckStateRole);
    if (checkStateVariant.isValid()) {
        int state = checkStateVariant.toInt();
        Q_ASSERT(state == Qt::Unchecked ||
                 state == Qt::PartiallyChecked ||
                 state == Qt::Checked);
    }
}
Example #24
0
void Peers::properties()
{
	if (ctx_item == NULL)
		return;

	QMessageBox msg(this);
	msg.setStandardButtons(QMessageBox::Ok);
	msg.setDefaultButton(QMessageBox::Ok);
	msg.setEscapeButton(QMessageBox::Ok);
	msg.setWindowTitle(tr("Peer Properties"));

	int type = ctx_item->data(peer_role_type).toInt();
	QString title = Peers::ItemType(type);

	msg.setText(title + QString("\n") + tr("Name: ") + ctx_item->text());

	QVariant var;
	QString info;

	var = ctx_item->data(peer_role_address);
	if (var.isValid())
		info += tr("Address: ") + var.toString() + QString("\n");

	var = ctx_item->data(peer_role_uuid);
	if (var.isValid())
		info += tr("UUID: ") + var.toString() + QString("\n");

	var = ctx_item->data(peer_role_pri_dev_type);
	if (var.isValid())
		info += tr("Primary Device Type: ") + var.toString() +
			QString("\n");

	var = ctx_item->data(peer_role_ssid);
	if (var.isValid())
		info += tr("SSID: ") + var.toString() + QString("\n");

	var = ctx_item->data(peer_role_config_methods);
	if (var.isValid()) {
		int methods = var.toInt();
		info += tr("Configuration Methods: ");
		if (methods & 0x0001)
			info += tr("[USBA]");
		if (methods & 0x0002)
			info += tr("[Ethernet]");
		if (methods & 0x0004)
			info += tr("[Label]");
		if (methods & 0x0008)
			info += tr("[Display]");
		if (methods & 0x0010)
			info += tr("[Ext. NFC Token]");
		if (methods & 0x0020)
			info += tr("[Int. NFC Token]");
		if (methods & 0x0040)
			info += tr("[NFC Interface]");
		if (methods & 0x0080)
			info += tr("[Push Button]");
		if (methods & 0x0100)
			info += tr("[Keypad]");
		info += "\n";
	}

	var = ctx_item->data(peer_role_selected_method);
	if (var.isValid()) {
		enum selected_method method =
			(enum selected_method) var.toInt();
		switch (method) {
		case SEL_METHOD_NONE:
			break;
		case SEL_METHOD_PIN_PEER_DISPLAY:
			info += tr("Selected Method: PIN on peer display\n");
			break;
		case SEL_METHOD_PIN_LOCAL_DISPLAY:
			info += tr("Selected Method: PIN on local display\n");
			break;
		}
	}

	var = ctx_item->data(peer_role_selected_pin);
	if (var.isValid()) {
		info += tr("PIN to enter on peer: ") + var.toString() + "\n";
	}

	var = ctx_item->data(peer_role_dev_passwd_id);
	if (var.isValid()) {
		info += tr("Device Password ID: ") + var.toString();
		switch (var.toInt()) {
		case 0:
			info += tr(" (Default PIN)");
			break;
		case 1:
			info += tr(" (User-specified PIN)");
			break;
		case 2:
			info += tr(" (Machine-specified PIN)");
			break;
		case 3:
			info += tr(" (Rekey)");
			break;
		case 4:
			info += tr(" (Push Button)");
			break;
		case 5:
			info += tr(" (Registrar-specified)");
			break;
		}
		info += "\n";
	}

	msg.setInformativeText(info);

	var = ctx_item->data(peer_role_details);
	if (var.isValid())
		msg.setDetailedText(var.toString());

	msg.exec();
}
Example #25
0
int main(int argc, char *argv[])
{
    // TODO: Clean this up, update API, etc.
    if (argc < 5 || argc > 6)
    {
        qWarning() << "Error detected! Insufficient number of arguments.";
        qWarning() << "";
        qWarning() << "Usage: ambdbusaccess <R/W> <Object> <Property> <Zone> [Value]";
        qWarning() << "- <R/W>";
        qWarning() << "  Used for specifying [R]ead or [W]rite.";
        qWarning() << "- <Object>";
        qWarning() << "  The AMB object to access.";
        qWarning() << "- <Property>";
        qWarning() << "  The property within the object to access.";
        qWarning() << "- <Zone>";
        qWarning() << "  The AMB zone to access.";
        qWarning() << "- [Value]";
        qWarning() << "  The value to write, if writing.";
        qWarning() << "Example: ambdbusaccess Write ClimateControl FanSpeedLevel 0 7";
        qWarning() << "";
        qWarning() << "This program returns an int under the following conditions:";
        qWarning() << "Successful Read: <Value Read>";
        qWarning() << "Unsuccessful Read: -1";
        qWarning() << "Successful Write: <Value Written>";
        qWarning() << "Unsuccessful Write: -1";

        return -1;
    }

    // TODO: Error check input.
    bool read = !strncmp(argv[1], "R", 1);
    QString object = argv[2];
    QString property = argv[3];
    qint32 zone = atoi(argv[4]);
    qint32 value = 0;

    if (argc == 6)
    {
        value = atoi(argv[5]);
    }

    // Necessary to suppress Qt messages about touching the D-Bus before the application was created.
    QCoreApplication a(argc, argv);

    // Sanity check that the system bus is actually present.
    if (!QDBusConnection::systemBus().isConnected())
    {
        qCritical() << "Could not access system D-Bus!";
        return -1;
    }

    // Get ahold of the manager object.
    QDBusInterface *manager = new QDBusInterface("org.automotive.message.broker", "/", "org.automotive.Manager",
                                                 QDBusConnection::systemBus());

    // Go fetch the path for the AMB object we are concerned with.
    qDebug().nospace() << "Looking for property " << property.toStdString().c_str() << " of object " <<
                          object.toStdString().c_str() << " in zone " << zone << ".";
    QDBusReply<QDBusObjectPath> propertyPath = manager->call("FindObjectForZone", object.toStdString().c_str(), zone);
    if (!propertyPath.isValid())
    {
        qDebug() << "Invalid reply!" << propertyPath.error() << "Got the path:" << propertyPath.value().path();
    }

    // Now that we have the path, open an interface to the object.
    QDBusInterface *propertyInterface = new QDBusInterface("org.automotive.message.broker", propertyPath.value().path(),
                                                           "org.automotive.ClimateControl", QDBusConnection::systemBus());

    // Perform our read or write operation.
    if (read)
    {
        QVariant reply = propertyInterface->property(property.toStdString().c_str());
        if (!reply.isValid())
        {
            qDebug() << "Invalid reply when reading the property!" << propertyInterface->lastError() << "Property:" <<
                        reply.toString();
            value = -1;
        }
        else
        {
            qDebug().nospace() << "Got a valid reply for the property of " << reply.toString().toStdString().c_str() << ".";
            value = reply.toInt();
        }
    }
    else
    {
        QVariant reply = propertyInterface->setProperty(property.toStdString().c_str(), value);
        if (reply.toBool())
        {
            qDebug() << "Successfully wrote the property.";
        }
        else
        {
            qDebug() << "Failed to write the property.";
            value = -1;
        }
    }

    // Clean up.
    delete propertyInterface;
    delete manager;

    // Either provide the read value or some feedback to the calling application.
    return value;
}
Example #26
0
void Peers::context_menu(const QPoint &pos)
{
	QMenu *menu = new QMenu;
	if (menu == NULL)
		return;

	QModelIndex idx = peers->indexAt(pos);
	if (idx.isValid()) {
		ctx_item = model.itemFromIndex(idx);
		int type = ctx_item->data(peer_role_type).toInt();
		menu->addAction(Peers::ItemType(type))->setEnabled(false);
		menu->addSeparator();

		int config_methods = -1;
		QVariant var = ctx_item->data(peer_role_config_methods);
		if (var.isValid())
			config_methods = var.toInt();

		enum selected_method method = SEL_METHOD_NONE;
		var = ctx_item->data(peer_role_selected_method);
		if (var.isValid())
			method = (enum selected_method) var.toInt();

		if ((type == PEER_TYPE_ASSOCIATED_STATION ||
		     type == PEER_TYPE_AP_WPS ||
		     type == PEER_TYPE_WPS_PIN_NEEDED ||
		     type == PEER_TYPE_WPS_ER_ENROLLEE ||
		     type == PEER_TYPE_WPS_ENROLLEE) &&
		    (config_methods == -1 || (config_methods & 0x010c))) {
			menu->addAction(tr("Enter WPS PIN"), this,
					SLOT(enter_pin()));
		}

		if (type == PEER_TYPE_P2P || type == PEER_TYPE_P2P_CLIENT) {
			menu->addAction(tr("P2P Connect"), this,
					SLOT(ctx_p2p_connect()));
			if (method == SEL_METHOD_NONE &&
			    config_methods > -1 &&
			    config_methods & 0x0080 /* PBC */ &&
			    config_methods != 0x0080)
				menu->addAction(tr("P2P Connect (PBC)"), this,
						SLOT(connect_pbc()));
			if (method == SEL_METHOD_NONE) {
				menu->addAction(tr("P2P Request PIN"), this,
						SLOT(ctx_p2p_req_pin()));
				menu->addAction(tr("P2P Show PIN"), this,
						SLOT(ctx_p2p_show_pin()));
			}

			if (config_methods > -1 && (config_methods & 0x0100)) {
				/* Peer has Keypad */
				menu->addAction(tr("P2P Display PIN"), this,
						SLOT(ctx_p2p_display_pin()));
			}

			if (config_methods > -1 && (config_methods & 0x000c)) {
				/* Peer has Label or Display */
				menu->addAction(tr("P2P Enter PIN"), this,
						SLOT(ctx_p2p_enter_pin()));
			}
		}

		if (type == PEER_TYPE_P2P_GROUP) {
			menu->addAction(tr("Show passphrase"), this,
					SLOT(ctx_p2p_show_passphrase()));
			menu->addAction(tr("Remove P2P Group"), this,
					SLOT(ctx_p2p_remove_group()));
		}

		if (type == PEER_TYPE_P2P_PERSISTENT_GROUP_GO ||
		    type == PEER_TYPE_P2P_PERSISTENT_GROUP_CLIENT ||
		    type == PEER_TYPE_P2P_INVITATION) {
			menu->addAction(tr("Start group"), this,
					SLOT(ctx_p2p_start_persistent()));
		}

		if (type == PEER_TYPE_P2P_PERSISTENT_GROUP_GO ||
		    type == PEER_TYPE_P2P_PERSISTENT_GROUP_CLIENT) {
			menu->addAction(tr("Invite"), this,
					SLOT(ctx_p2p_invite()));
		}

		if (type == PEER_TYPE_P2P_INVITATION) {
			menu->addAction(tr("Ignore"), this,
					SLOT(ctx_p2p_delete()));
		}

		if (type == PEER_TYPE_AP_WPS) {
			menu->addAction(tr("Connect (PBC)"), this,
					SLOT(connect_pbc()));
		}

		if ((type == PEER_TYPE_ASSOCIATED_STATION ||
		     type == PEER_TYPE_WPS_ER_ENROLLEE ||
		     type == PEER_TYPE_WPS_ENROLLEE) &&
		    config_methods >= 0 && (config_methods & 0x0080)) {
			menu->addAction(tr("Enroll (PBC)"), this,
					SLOT(connect_pbc()));
		}

		if (type == PEER_TYPE_WPS_ER_AP) {
			menu->addAction(tr("Learn Configuration"), this,
					SLOT(learn_ap_config()));
		}

		menu->addAction(tr("Properties"), this, SLOT(properties()));
	} else {
		ctx_item = NULL;
		menu->addAction(QString(tr("Refresh")), this,
				SLOT(ctx_refresh()));
		menu->addAction(tr("Start P2P discovery"), this,
				SLOT(ctx_p2p_start()));
		menu->addAction(tr("Stop P2P discovery"), this,
				SLOT(ctx_p2p_stop()));
		menu->addAction(tr("P2P listen only"), this,
				SLOT(ctx_p2p_listen()));
		menu->addAction(tr("Start P2P group"), this,
				SLOT(ctx_p2p_start_group()));
		if (hide_ap)
			menu->addAction(tr("Show AP entries"), this,
					SLOT(ctx_show_ap()));
		else
			menu->addAction(tr("Hide AP entries"), this,
					SLOT(ctx_hide_ap()));
	}

	menu->exec(peers->mapToGlobal(pos));
}
Example #27
0
int QgsTINInterpolator::insertData( QgsFeature* f, bool zCoord, int attr, InputType type )
{
  if ( !f )
  {
    return 1;
  }

  QgsGeometry g = f->geometry();
  {
    if ( g.isNull() )
    {
      return 2;
    }
  }

  //check attribute value
  double attributeValue = 0;
  bool attributeConversionOk = false;
  if ( !zCoord )
  {
    QVariant attributeVariant = f->attribute( attr );
    if ( !attributeVariant.isValid() ) //attribute not found, something must be wrong (e.g. NULL value)
    {
      return 3;
    }
    attributeValue = attributeVariant.toDouble( &attributeConversionOk );
    if ( !attributeConversionOk || qIsNaN( attributeValue ) ) //don't consider vertices with attributes like 'nan' for the interpolation
    {
      return 4;
    }
  }

  //parse WKB. It is ugly, but we cannot use the methods with QgsPoint because they don't contain z-values for 25D types
  bool hasZValue = false;
  double x, y, z;
  QByteArray wkb( g.exportToWkb() );
  QgsConstWkbPtr currentWkbPtr( wkb );
  currentWkbPtr.readHeader();
  //maybe a structure or break line
  Line3D* line = nullptr;

  QgsWkbTypes::Type wkbType = g.wkbType();
  switch ( wkbType )
  {
    case QgsWkbTypes::Point25D:
      hasZValue = true;
      FALLTHROUGH;
    case QgsWkbTypes::Point:
    {
      currentWkbPtr >> x >> y;
      if ( zCoord && hasZValue )
      {
        currentWkbPtr >> z;
      }
      else
      {
        z = attributeValue;
      }
      Point3D* thePoint = new Point3D( x, y, z );
      if ( mTriangulation->addPoint( thePoint ) == -100 )
      {
        return -1;
      }
      break;
    }
Example #28
0
void Peers::event_notify(WpaMsg msg)
{
	QString text = msg.getMsg();

	if (text.startsWith(WPS_EVENT_PIN_NEEDED)) {
		/*
		 * WPS-PIN-NEEDED 5a02a5fa-9199-5e7c-bc46-e183d3cb32f7
		 * 02:2a:c4:18:5b:f3
		 * [Wireless Client|Company|cmodel|123|12345|1-0050F204-1]
		 */
		QStringList items = text.split(' ');
		QString uuid = items[1];
		QString addr = items[2];
		QString name = "";

		QStandardItem *item = find_addr(addr);
		if (item)
			return;

		int pos = text.indexOf('[');
		if (pos >= 0) {
			int pos2 = text.lastIndexOf(']');
			if (pos2 >= pos) {
				items = text.mid(pos + 1, pos2 - pos - 1).
					split('|');
				name = items[0];
				items.append(addr);
			}
		}

		item = new QStandardItem(*laptop_icon, name);
		if (item) {
			item->setData(addr, peer_role_address);
			item->setData(PEER_TYPE_WPS_PIN_NEEDED,
				      peer_role_type);
			item->setToolTip(ItemType(PEER_TYPE_WPS_PIN_NEEDED));
			item->setData(items.join("\n"), peer_role_details);
			item->setData(items[5], peer_role_pri_dev_type);
			model.appendRow(item);
		}
		return;
	}

	if (text.startsWith(AP_STA_CONNECTED)) {
		/* AP-STA-CONNECTED 02:2a:c4:18:5b:f3 */
		QStringList items = text.split(' ');
		QString addr = items[1];
		QStandardItem *item = find_addr(addr);
		if (item == NULL || item->data(peer_role_type).toInt() !=
		    PEER_TYPE_ASSOCIATED_STATION)
			add_single_station(addr.toAscii().constData());
		return;
	}

	if (text.startsWith(AP_STA_DISCONNECTED)) {
		/* AP-STA-DISCONNECTED 02:2a:c4:18:5b:f3 */
		QStringList items = text.split(' ');
		QString addr = items[1];

		if (model.rowCount() == 0)
			return;

		QModelIndexList lst = model.match(model.index(0, 0),
						  peer_role_address, addr, -1);
		for (int i = 0; i < lst.size(); i++) {
			QStandardItem *item = model.itemFromIndex(lst[i]);
			if (item && item->data(peer_role_type).toInt() ==
			    PEER_TYPE_ASSOCIATED_STATION) {
				model.removeRow(lst[i].row());
				break;
			}
		}
		return;
	}

	if (text.startsWith(P2P_EVENT_DEVICE_FOUND)) {
		/*
		 * P2P-DEVICE-FOUND 02:b5:64:63:30:63
		 * p2p_dev_addr=02:b5:64:63:30:63 pri_dev_type=1-0050f204-1
		 * name='Wireless Client' config_methods=0x84 dev_capab=0x21
		 * group_capab=0x0
		 */
		QStringList items =
			text.split(QRegExp(" (?=[^']*('[^']*'[^']*)*$)"));
		QString addr = items[1];
		QString name = "";
		QString pri_dev_type;
		int config_methods = 0;
		for (int i = 0; i < items.size(); i++) {
			QString str = items.at(i);
			if (str.startsWith("name='"))
				name = str.section('\'', 1, -2);
			else if (str.startsWith("config_methods="))
				config_methods =
					str.section('=', 1).toInt(0, 0);
			else if (str.startsWith("pri_dev_type="))
				pri_dev_type = str.section('=', 1);
		}

		QStandardItem *item = find_addr(addr);
		if (item) {
			int type = item->data(peer_role_type).toInt();
			if (type == PEER_TYPE_P2P)
				return;
		}

		item = new QStandardItem(*default_icon, name);
		if (item) {
			item->setData(addr, peer_role_address);
			item->setData(config_methods,
				      peer_role_config_methods);
			item->setData(PEER_TYPE_P2P, peer_role_type);
			if (!pri_dev_type.isEmpty())
				item->setData(pri_dev_type,
					      peer_role_pri_dev_type);
			item->setData(items.join(QString("\n")),
				      peer_role_details);
			item->setToolTip(ItemType(PEER_TYPE_P2P));
			model.appendRow(item);
		}

		item = find_addr_type(addr,
				      PEER_TYPE_P2P_PERSISTENT_GROUP_CLIENT);
		if (item)
			item->setBackground(Qt::NoBrush);
	}

	if (text.startsWith(P2P_EVENT_GROUP_STARTED)) {
		/* P2P-GROUP-STARTED wlan0-p2p-0 GO ssid="DIRECT-3F"
		 * passphrase="YOyTkxID" go_dev_addr=02:40:61:c2:f3:b7
		 * [PERSISTENT] */
		QStringList items = text.split(' ');
		if (items.size() < 4)
			return;

		int pos = text.indexOf(" ssid=\"");
		if (pos < 0)
			return;
		QString ssid = text.mid(pos + 7);
		pos = ssid.indexOf(" passphrase=\"");
		if (pos < 0)
			pos = ssid.indexOf(" psk=");
		if (pos >= 0)
			ssid.truncate(pos);
		pos = ssid.lastIndexOf('"');
		if (pos >= 0)
			ssid.truncate(pos);

		QStandardItem *item = new QStandardItem(*group_icon, ssid);
		if (item) {
			item->setData(PEER_TYPE_P2P_GROUP, peer_role_type);
			item->setData(items[1], peer_role_ifname);
			QString details;
			if (items[2] == "GO") {
				details = tr("P2P GO for interface ") +
					items[1];
			} else {
				details = tr("P2P client for interface ") +
					items[1];
			}
			if (text.contains(" [PERSISTENT]"))
				details += "\nPersistent group";
			item->setData(details, peer_role_details);
			item->setToolTip(ItemType(PEER_TYPE_P2P_GROUP));
			model.appendRow(item);
		}
	}

	if (text.startsWith(P2P_EVENT_GROUP_REMOVED)) {
		/* P2P-GROUP-REMOVED wlan0-p2p-0 GO */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;

		if (model.rowCount() == 0)
			return;

		QModelIndexList lst = model.match(model.index(0, 0),
						  peer_role_ifname, items[1]);
		for (int i = 0; i < lst.size(); i++)
			model.removeRow(lst[i].row());
		return;
	}

	if (text.startsWith(P2P_EVENT_PROV_DISC_SHOW_PIN)) {
		/* P2P-PROV-DISC-SHOW-PIN 02:40:61:c2:f3:b7 12345670 */
		QStringList items = text.split(' ');
		if (items.size() < 3)
			return;
		QString addr = items[1];
		QString pin = items[2];

		QStandardItem *item = find_addr_type(addr, PEER_TYPE_P2P);
		if (item == NULL)
			return;
		item->setData(SEL_METHOD_PIN_LOCAL_DISPLAY,
			      peer_role_selected_method);
		item->setData(pin, peer_role_selected_pin);
		QVariant var = item->data(peer_role_requested_method);
		if (var.isValid() &&
		    var.toInt() == SEL_METHOD_PIN_LOCAL_DISPLAY) {
			ctx_item = item;
			ctx_p2p_display_pin_pd();
		}
		return;
	}

	if (text.startsWith(P2P_EVENT_PROV_DISC_ENTER_PIN)) {
		/* P2P-PROV-DISC-ENTER-PIN 02:40:61:c2:f3:b7 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		QString addr = items[1];

		QStandardItem *item = find_addr_type(addr, PEER_TYPE_P2P);
		if (item == NULL)
			return;
		item->setData(SEL_METHOD_PIN_PEER_DISPLAY,
			      peer_role_selected_method);
		QVariant var = item->data(peer_role_requested_method);
		if (var.isValid() &&
		    var.toInt() == SEL_METHOD_PIN_PEER_DISPLAY) {
			ctx_item = item;
			ctx_p2p_connect();
		}
		return;
	}

	if (text.startsWith(P2P_EVENT_INVITATION_RECEIVED)) {
		/* P2P-INVITATION-RECEIVED sa=02:f0:bc:44:87:62 persistent=4 */
		QStringList items = text.split(' ');
		if (items.size() < 3)
			return;
		if (!items[1].startsWith("sa=") ||
		    !items[2].startsWith("persistent="))
			return;
		QString addr = items[1].mid(3);
		int id = items[2].mid(11).toInt();

		char cmd[100];
		char reply[100];
		size_t reply_len;

		snprintf(cmd, sizeof(cmd), "GET_NETWORK %d ssid", id);
		reply_len = sizeof(reply) - 1;
		if (wpagui->ctrlRequest(cmd, reply, &reply_len) < 0)
			return;
		reply[reply_len] = '\0';
		QString name;
		char *pos = strrchr(reply, '"');
		if (pos && reply[0] == '"') {
			*pos = '\0';
			name = reply + 1;
		} else
			name = reply;

		QStandardItem *item;
		item = find_addr_type(addr, PEER_TYPE_P2P_INVITATION);
		if (item)
			model.removeRow(item->row());

		item = new QStandardItem(*invitation_icon, name);
		if (!item)
			return;
		item->setData(PEER_TYPE_P2P_INVITATION, peer_role_type);
		item->setToolTip(ItemType(PEER_TYPE_P2P_INVITATION));
		item->setData(addr, peer_role_address);
		item->setData(id, peer_role_network_id);

		model.appendRow(item);

		enable_persistent(id);

		return;
	}

	if (text.startsWith(P2P_EVENT_INVITATION_RESULT)) {
		/* P2P-INVITATION-RESULT status=1 */
		/* TODO */
		return;
	}

	if (text.startsWith(WPS_EVENT_ER_AP_ADD)) {
		/*
		 * WPS-ER-AP-ADD 87654321-9abc-def0-1234-56789abc0002
		 * 02:11:22:33:44:55 pri_dev_type=6-0050F204-1 wps_state=1
		 * |Very friendly name|Company|Long description of the model|
		 * WAP|http://w1.fi/|http://w1.fi/hostapd/
		 */
		QStringList items = text.split(' ');
		if (items.size() < 5)
			return;
		QString uuid = items[1];
		QString addr = items[2];
		QString pri_dev_type = items[3].mid(13);
		int wps_state = items[4].mid(10).toInt();

		int pos = text.indexOf('|');
		if (pos < 0)
			return;
		items = text.mid(pos + 1).split('|');
		if (items.size() < 1)
			return;

		QStandardItem *item = find_uuid(uuid);
		if (item)
			return;

		item = new QStandardItem(*ap_icon, items[0]);
		if (item) {
			item->setData(uuid, peer_role_uuid);
			item->setData(addr, peer_role_address);
			int type = wps_state == 2 ? PEER_TYPE_WPS_ER_AP:
				PEER_TYPE_WPS_ER_AP_UNCONFIGURED;
			item->setData(type, peer_role_type);
			item->setToolTip(ItemType(type));
			item->setData(pri_dev_type, peer_role_pri_dev_type);
			item->setData(items.join(QString("\n")),
				      peer_role_details);
			model.appendRow(item);
		}

		return;
	}

	if (text.startsWith(WPS_EVENT_ER_AP_REMOVE)) {
		/* WPS-ER-AP-REMOVE 87654321-9abc-def0-1234-56789abc0002 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		if (model.rowCount() == 0)
			return;

		QModelIndexList lst = model.match(model.index(0, 0),
						  peer_role_uuid, items[1]);
		for (int i = 0; i < lst.size(); i++) {
			QStandardItem *item = model.itemFromIndex(lst[i]);
			if (item &&
			    (item->data(peer_role_type).toInt() ==
			     PEER_TYPE_WPS_ER_AP ||
			     item->data(peer_role_type).toInt() ==
			     PEER_TYPE_WPS_ER_AP_UNCONFIGURED))
				model.removeRow(lst[i].row());
		}
		return;
	}

	if (text.startsWith(WPS_EVENT_ER_ENROLLEE_ADD)) {
		/*
		 * WPS-ER-ENROLLEE-ADD 2b7093f1-d6fb-5108-adbb-bea66bb87333
		 * 02:66:a0:ee:17:27 M1=1 config_methods=0x14d dev_passwd_id=0
		 * pri_dev_type=1-0050F204-1
		 * |Wireless Client|Company|cmodel|123|12345|
		 */
		QStringList items = text.split(' ');
		if (items.size() < 3)
			return;
		QString uuid = items[1];
		QString addr = items[2];
		QString pri_dev_type = items[6].mid(13);
		int config_methods = -1;
		int dev_passwd_id = -1;

		for (int i = 3; i < items.size(); i++) {
			int pos = items[i].indexOf('=') + 1;
			if (pos < 1)
				continue;
			QString val = items[i].mid(pos);
			if (items[i].startsWith("config_methods=")) {
				config_methods = val.toInt(0, 0);
			} else if (items[i].startsWith("dev_passwd_id=")) {
				dev_passwd_id = val.toInt();
			}
		}

		int pos = text.indexOf('|');
		if (pos < 0)
			return;
		items = text.mid(pos + 1).split('|');
		if (items.size() < 1)
			return;
		QString name = items[0];
		if (name.length() == 0)
			name = addr;

		remove_enrollee_uuid(uuid);

		QStandardItem *item;
		item = new QStandardItem(*laptop_icon, name);
		if (item) {
			item->setData(uuid, peer_role_uuid);
			item->setData(addr, peer_role_address);
			item->setData(PEER_TYPE_WPS_ER_ENROLLEE,
				      peer_role_type);
			item->setToolTip(ItemType(PEER_TYPE_WPS_ER_ENROLLEE));
			item->setData(items.join(QString("\n")),
				      peer_role_details);
			item->setData(pri_dev_type, peer_role_pri_dev_type);
			if (config_methods >= 0)
				item->setData(config_methods,
					      peer_role_config_methods);
			if (dev_passwd_id >= 0)
				item->setData(dev_passwd_id,
					      peer_role_dev_passwd_id);
			model.appendRow(item);
		}

		return;
	}

	if (text.startsWith(WPS_EVENT_ER_ENROLLEE_REMOVE)) {
		/*
		 * WPS-ER-ENROLLEE-REMOVE 2b7093f1-d6fb-5108-adbb-bea66bb87333
		 * 02:66:a0:ee:17:27
		 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		remove_enrollee_uuid(items[1]);
		return;
	}

	if (text.startsWith(WPS_EVENT_ENROLLEE_SEEN)) {
		/* TODO: need to time out this somehow or remove on successful
		 * WPS run, etc. */
		/*
		 * WPS-ENROLLEE-SEEN 02:00:00:00:01:00
		 * 572cf82f-c957-5653-9b16-b5cfb298abf1 1-0050F204-1 0x80 4 1
		 * [Wireless Client]
		 * (MAC addr, UUID-E, pri dev type, config methods,
		 * dev passwd id, request type, [dev name])
		 */
		QStringList items = text.split(' ');
		if (items.size() < 7)
			return;
		QString addr = items[1];
		QString uuid = items[2];
		QString pri_dev_type = items[3];
		int config_methods = items[4].toInt(0, 0);
		int dev_passwd_id = items[5].toInt();
		QString name;

		QStandardItem *item = find_addr(addr);
		if (item) {
			int type = item->data(peer_role_type).toInt();
			if (type == PEER_TYPE_ASSOCIATED_STATION)
				return; /* already associated */
		}

		int pos = text.indexOf('[');
		if (pos >= 0) {
			int pos2 = text.lastIndexOf(']');
			if (pos2 >= pos) {
				QStringList items2 =
					text.mid(pos + 1, pos2 - pos - 1).
					split('|');
				name = items2[0];
			}
		}
		if (name.isEmpty())
			name = addr;

		item = find_uuid(uuid);
		if (item) {
			QVariant var = item->data(peer_role_config_methods);
			QVariant var2 = item->data(peer_role_dev_passwd_id);
			if ((var.isValid() && config_methods != var.toInt()) ||
			    (var2.isValid() && dev_passwd_id != var2.toInt()))
				remove_enrollee_uuid(uuid);
			else
				return;
		}

		item = new QStandardItem(*laptop_icon, name);
		if (item) {
			item->setData(uuid, peer_role_uuid);
			item->setData(addr, peer_role_address);
			item->setData(PEER_TYPE_WPS_ENROLLEE,
				      peer_role_type);
			item->setToolTip(ItemType(PEER_TYPE_WPS_ENROLLEE));
			item->setData(items.join(QString("\n")),
				      peer_role_details);
			item->setData(pri_dev_type, peer_role_pri_dev_type);
			item->setData(config_methods,
				      peer_role_config_methods);
			item->setData(dev_passwd_id, peer_role_dev_passwd_id);
			model.appendRow(item);
		}

		return;
	}

	if (text.startsWith(WPA_EVENT_BSS_ADDED)) {
		/* CTRL-EVENT-BSS-ADDED 34 00:11:22:33:44:55 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		char cmd[20];
		snprintf(cmd, sizeof(cmd), "BSS ID-%d", items[1].toInt());
		add_bss(cmd);
		return;
	}

	if (text.startsWith(WPA_EVENT_BSS_REMOVED)) {
		/* CTRL-EVENT-BSS-REMOVED 34 00:11:22:33:44:55 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		remove_bss(items[1].toInt());
		return;
	}
}
Example #29
0
// Author & Date: Ehsan Azar       3 April 2012
// Purpose: Begin a new Xml group or navigate to it if it exists
// Inputs:
//   nodeName  - the node tag (it can be in the form of relative/path/to/node)
//                node index (0-based) is enclosed (relative/path/to/node<2>/subnode)
//             Note: nodeName tags are always created if they do not exist
//   attribs   - attribute name, attribute value pairs
//   value     - new node value, if non-empty
// Outputs:
//  Returns true if nodeName is created
bool XmlFile::beginGroup(QString nodeName, const QMap<QString, QVariant> attribs, const QVariant & value)
{
    bool bRet = false;
    QDomElement set;

    if (nodeName.isEmpty())
        nodeName = firstChildKey();
    if (nodeName.isEmpty())
        nodeName = "XmlItem";
    // Get the node path
    QStringList nodepath = nodeName.split("/");
    int level = nodepath.count();
    m_levels.append(level);
    for (int i = 0; i < level; ++i)
    {
        QString strTagName = nodepath[i];
        // Extract index
        int index = 0;
        {
            int idx = strTagName.indexOf("<");
            if (idx >= 0)
            {
                index = strTagName.mid(idx + 1, strTagName.length() - idx - 2).toInt();
                strTagName = strTagName.left(idx);
                nodepath[i] = strTagName;
            }
        }
        // Look if the element (with given index) exists then get it
        QDomNode parent;
        if (!m_nodes.isEmpty())
        {
            // Get the current node
            parent = m_nodes.last();
        } else {
            parent = m_doc;
        }
        int count = 0;
        for(QDomElement elem = parent.firstChildElement(strTagName); !elem.isNull(); elem = elem.nextSiblingElement(strTagName))
        {
            count++;
            if (count == index + 1)
            {
                set = elem;
                break;
            }
        }
        // Create all new subnodes
        for (int j = 0; j < (index + 1 - count); ++j)
        {
            bRet = true;
            set = m_doc.createElement(strTagName);
            parent.appendChild(set);
        }
        // Add all the parent nodes without attribute or value
        if (i < level - 1)
            m_nodes.append(set);
    }
    
    // Now add the node to the end of the list
    m_nodes.append(set);

    // if there is some text/value to set
    if (value.isValid())
    {
        bool bTextLeaf = false;
        QVariantList varlst;
        switch (value.type())
        {
        case QVariant::StringList:
        case QVariant::List:
            varlst = value.toList();
            if (AddList(varlst, nodepath.last()))
                set.setAttribute("Type", "Array");
            break;
        default:
            QString text;
            if (value.type() == QVariant::UserType)
            {
                const XmlItem * item = static_cast<const XmlItem *>(value.data());
                QVariant subval = item->XmlValue();
                
                if (subval.type() == QVariant::UserType)
                {
                    const XmlItem * subitem = static_cast<const XmlItem *>(subval.data());
                    QString strSubKey = subitem->XmlName();
                    QMap<QString, QVariant> attribs = subitem->XmlAttribs();
                    // Recursively add this item
                    beginGroup(strSubKey, attribs, subval);
                    endGroup();
                } 
                else if (subval.type() == QVariant::List || subval.type() == QVariant::StringList)
                {
                    varlst = subval.toList();
                    if (AddList(varlst, nodepath.last()))
                        set.setAttribute("Type", "Array");
                } else {
                    text = subval.toString();
                    bTextLeaf = true;
                }
            } else {
                text = value.toString();
                bTextLeaf = true;
            }
            if (bTextLeaf)
            {
                // Remove all the children
                while (set.hasChildNodes())
                    set.removeChild(set.lastChild());
                // See if this is Xml fragment string
                XmlFile xml;
                if (!xml.setContent(text))
                {
                    QDomNode frag = m_doc.importNode(xml.getFragment(), true);
                    set.appendChild(frag);
                } else {
                    QDomText domText = m_doc.createTextNode(text);
                    set.appendChild(domText);
                }
            }
        }
    }

    // Add all the additional attributes
    QMap<QString, QVariant>::const_iterator iterator;
    for (iterator = attribs.begin(); iterator != attribs.end(); ++iterator)
    {
        QString attrName = iterator.key();
        QVariant attrValue = iterator.value();
        switch (attrValue.type())
        {
        case QVariant::String:
            set.setAttribute(attrName, attrValue.toString());
            break;
        case QVariant::Int:
            set.setAttribute(attrName, attrValue.toInt());
            break;
        case QVariant::UInt:
            set.setAttribute(attrName, attrValue.toUInt());
            break;
        case QVariant::LongLong:
            set.setAttribute(attrName, attrValue.toLongLong());
            break;
        case QVariant::ULongLong:
            set.setAttribute(attrName, attrValue.toULongLong());
            break;
        default:
            // everything else is treated as double floating point
            set.setAttribute(attrName, attrValue.toDouble());
            break;
        }
    }
    return bRet;
}
void
TestMetaConstants::testValueForField()
{
    Meta::TrackPtr trackPtr;

    // When track is null, an invalid QVariant is returned
    trackPtr = 0;
    QVERIFY( !valueForField( 0, trackPtr ).isValid() );

    // Set up mock track details and create mock track
    QVariantMap trackData;
    trackData[ Meta::Field::URL ] = KUrl( "file:///test/url" );
    trackData[ Meta::Field::TITLE ] = "test track";
    trackData[ Meta::Field::COMMENT ] = "test comment" ;
    trackData[ Meta::Field::TRACKNUMBER ] = 1;
    trackData[ Meta::Field::DISCNUMBER ] = 1;
    trackData[ Meta::Field::BPM ] = qreal( 1 );
    trackData[ Meta::Field::LENGTH ] = qint64( 1 );
    trackData[ Meta::Field::BITRATE ] = 1;
    trackData[ Meta::Field::SAMPLERATE ] = 1;
    trackData[ Meta::Field::FILESIZE ] = 1;
    trackData[ Meta::Field::SCORE ] = double( 1 );
    trackData[ Meta::Field::RATING ] = 1;
    trackData[ Meta::Field::FIRST_PLAYED ] = QDateTime( QDate( 2012, 1, 1) );
    trackData[ Meta::Field::LAST_PLAYED ] = QDateTime( QDate( 2012, 1, 1) );
    trackData[ Meta::Field::PLAYCOUNT ] = 1;
    trackData[ Meta::Field::UNIQUEID ] = "test uid";

    MetaMock *testTrack = new MetaMock( trackData );

    // Associate track with album, artist, etc.
    MockAlbum *testAlbum = new MockAlbum( "test album" );
    MockArtist *testArtist = new MockArtist( "test artist" );
    MockComposer *testComposer = new MockComposer( "test composer" );
    MockGenre *testGenre = new MockGenre( "test genre" );
    MockYear *testYear = new MockYear( "2012" );
    MockLabel *testLabel1 = new MockLabel( "test label 1");
    MockLabel *testLabel2 = new MockLabel( "test label 2" );
    MockLabel *testLabel3 = new MockLabel( "test label 3" );

    // For valAlbumArtist
    testAlbum->m_albumArtist = testArtist;

    testTrack->m_album = testAlbum;
    testTrack->m_artist = testArtist;
    testTrack->m_composer = testComposer;
    testTrack->m_genre = testGenre;
    testTrack->m_year = testYear;
    testTrack->m_labels << Meta::LabelPtr( testLabel1 )
                        << Meta::LabelPtr( testLabel2 )
                        << Meta::LabelPtr( testLabel3 );

    // Make the track pointer point to the created track
    trackPtr = Meta::TrackPtr( testTrack );

    // Case 0
    QVariant trackValue = valueForField( qint64( 0 ), trackPtr );
    QVERIFY( trackValue.toStringList().contains( trackData.value( Meta::Field::URL ).value<KUrl>().path()
        + trackData.value( Meta::Field::TITLE ).toString()
        + trackData.value( Meta::Field::COMMENT ).toString() ) );
    QVERIFY( trackValue.toStringList().contains( testAlbum->name() ) );
    QVERIFY( trackValue.toStringList().contains( testArtist->name() ) );
    QVERIFY( trackValue.toStringList().contains( testGenre->name() ) );

    // Case Meta::valUrl
    trackValue = valueForField( Meta::valUrl, trackPtr );
    QVERIFY( trackValue.toString() == trackData.value( Meta::Field::URL ).value<KUrl>().path() );

    // Case Meta::valTitle
    trackValue = valueForField( Meta::valTitle, trackPtr );
    QVERIFY( trackValue.toString() == trackData.value( Meta::Field::TITLE ).toString() );

    // Case Meta::valArtist for non-null artist
    trackValue = valueForField( Meta::valArtist, trackPtr );
    QVERIFY( trackValue.toString() == testArtist->name() );

    // Case Meta::valAlbum for non-null album
    trackValue = valueForField( Meta::valAlbum, trackPtr );
    QVERIFY( trackValue.toString() == testAlbum->name() );

    // Case Meta::valComposer for non-null composer
    trackValue = valueForField( Meta::valComposer, trackPtr );
    QVERIFY( trackValue.toString() == testComposer->name() );

    // Case Meta::valGenre for non-null genre
    trackValue = valueForField( Meta::valGenre, trackPtr );
    QVERIFY( trackValue.toString() == testGenre->name() );

    // Case Meta::valYear for non-null year
    trackValue = valueForField( Meta::valYear, trackPtr );
    QVERIFY( trackValue.toInt() == testYear->name().toInt() );

    // Case Meta::valComment
    trackValue = valueForField( Meta::valComment, trackPtr );
    QVERIFY( trackValue.toString() == trackData.value( Meta::Field::COMMENT ).toString() );

    // Case Meta::valTrackNr
    trackValue = valueForField( Meta::valTrackNr, trackPtr );
    QVERIFY( trackValue.toInt() == trackData.value( Meta::Field::TRACKNUMBER ).toInt() );

    // Case Meta::valDiscNr
    trackValue = valueForField( Meta::valDiscNr, trackPtr );
    QVERIFY( trackValue.toInt() == trackData.value( Meta::Field::DISCNUMBER ).toInt() );

    // Case Meta::valBpm
    trackValue = valueForField( Meta::valBpm, trackPtr );
    QVERIFY( trackValue.toDouble() == trackData.value( Meta::Field::BPM ).toDouble() );

    // Case Meta::valLength
    trackValue = valueForField( Meta::valLength, trackPtr );
    QVERIFY( trackValue.toInt() == trackData.value( Meta::Field::LENGTH ).toInt());

    // Case Meta::valBitrate
    trackValue = valueForField( Meta::valBitrate, trackPtr );
    QVERIFY( trackValue.toInt() == trackData.value( Meta::Field::BITRATE ).toInt() );

    // Case Meta::valSamplerate
    trackValue = valueForField( Meta::valSamplerate, trackPtr );
    QVERIFY( trackValue.toInt() == trackData.value( Meta::Field::SAMPLERATE ).toInt() );

    // Case Meta::valFilesize
    trackValue = valueForField( Meta::valFilesize, trackPtr );
    QVERIFY( trackValue.toInt() == trackData.value( Meta::Field::FILESIZE ).toInt() );

    // Case Meta::valFormat
    trackValue = valueForField( Meta::valFormat, trackPtr );
     QVERIFY( trackValue.toInt() == int( Amarok::FileTypeSupport::fileType(trackPtr->type() ) ) );

    // Case Meta::valCreateDate
    trackValue = valueForField( Meta::valCreateDate, trackPtr );
    QVERIFY( trackValue.toDateTime().isNull() );

    // Case Meta::valScore
    trackValue = valueForField( Meta::valScore, trackPtr );
    QVERIFY( trackValue.toInt() == trackData.value( Meta::Field::SCORE ).toInt() );

    // Case Meta::valRating
    trackValue = valueForField( Meta::valRating, trackPtr );
    QVERIFY( trackValue.toInt() == trackData.value( Meta::Field::RATING ).toInt() );

    // Case Meta::valFirstPlayed
    trackValue = valueForField( Meta::valFirstPlayed, trackPtr );
    QVERIFY( trackValue.toDateTime() == trackData.value( Meta::Field::FIRST_PLAYED ).toDateTime() );

    // Case Meta::valLastPlayed
    trackValue = valueForField( Meta::valLastPlayed, trackPtr );
    QVERIFY( trackValue.toDateTime() == trackData.value( Meta::Field::LAST_PLAYED ).toDateTime() );

    // Case Meta::valFilesize
    trackValue = valueForField( Meta::valPlaycount, trackPtr );
    QVERIFY( trackValue.toInt() == trackData.value( Meta::Field::PLAYCOUNT ).toInt() );

    // Case Meta::valUniqueId
    trackValue = valueForField( Meta::valUniqueId, trackPtr );
    QVERIFY( trackValue.toString() == trackData.value( Meta::Field::UNIQUEID ).toString() );

    // Case Meta::valTrackGain
    trackValue = valueForField( Meta::valTrackGain, trackPtr );
    QVERIFY( trackValue.toString() == "track gain" );

    // Case Meta::valTrackGainPeak
    trackValue = valueForField( Meta::valTrackGainPeak, trackPtr );
    QVERIFY( trackValue.toString() == "track gain peak" );

    // Case Meta::valAlbumGainGain
    trackValue = valueForField( Meta::valAlbumGain, trackPtr );
    QVERIFY( trackValue.toString() == "album gain" );

    // Case Meta::valAlbumGain
    trackValue = valueForField( Meta::valAlbumGainPeak, trackPtr );
    QVERIFY( trackValue.toString() == "album gain peak" );

    // Case Meta::valAlbumArtist
    trackValue = valueForField( Meta::valAlbumArtist, trackPtr );
    QVERIFY( trackValue.toString() == testAlbum->albumArtist()->name() );

    // Case Meta::valLabel, order of the label names remains same
    trackValue = valueForField( Meta::valLabel, trackPtr );
    QStringList labelNames;
    labelNames << testLabel1->name() << testLabel2->name() << testLabel3->name();
    QVERIFY( trackValue.toStringList() == labelNames );

    // Case Meta::valModified
    trackValue = valueForField( Meta::valModified, trackPtr );
    QVERIFY( trackValue.toDateTime().isNull() );

    // Default, returns an invalid QVariant
    trackValue = valueForField( qint64( -1 ), trackPtr );
    QVERIFY( !trackValue.isValid() );

    // Cases with null artist, album, etc. where an invalid QVariant is returned
    testAlbum->m_albumArtist = 0;
    testTrack->m_album = 0;
    testTrack->m_artist = 0;
    testTrack->m_composer = 0;
    testTrack->m_genre = 0;
    testTrack->m_year = 0;

    // Case Meta::valArtist for null artist
    trackValue = valueForField( Meta::valArtist, trackPtr );
    QVERIFY( !trackValue.isValid() );

    // Case Meta::valAlbum for null album
    trackValue = valueForField( Meta::valAlbum, trackPtr );
    QVERIFY( !trackValue.isValid() );

    // Case Meta::valComposer for null composer
    trackValue = valueForField( Meta::valComposer, trackPtr );
    QVERIFY( !trackValue.isValid() );

    // Case Meta::valGenre for null genre
    trackValue = valueForField( Meta::valGenre, trackPtr );
    QVERIFY( !trackValue.isValid() );

    // Case Meta::valYear for null year
    trackValue = valueForField( Meta::valYear, trackPtr );
    QVERIFY( !trackValue.isValid() );

    // Case Meta::valAlbumArtist for null album artist
    trackValue = valueForField( Meta::valAlbumArtist, trackPtr );
    QVERIFY( !trackValue.isValid() );
}