示例#1
0
QList<QgsWCSSourceSelect::SupportedFormat> QgsWCSSourceSelect::providerFormats()
{
  QgsDebugMsg( "entered" );
  QList<SupportedFormat> formats;

  QMap<QString, QString> mimes = QgsWcsProvider::supportedMimes();
  Q_FOREACH ( const QString& mime, mimes.keys() )
  {
    SupportedFormat format = { mime, mimes.value( mime ) };

    // prefer tiff
    if ( mime == "image/tiff" )
    {
      formats.prepend( format );
    }
    else
    {
      formats.append( format );
    }
  }

  return formats;
}
示例#2
0
文件: style.cpp 项目: Grokafar/qTox
QString Style::resolve(QString qss, const QFont& baseFont)
{
    if (dict.isEmpty()) {
        dict = {// colors
                {"@green", Style::getColor(Style::Green).name()},
                {"@yellow", Style::getColor(Style::Yellow).name()},
                {"@red", Style::getColor(Style::Red).name()},
                {"@black", Style::getColor(Style::Black).name()},
                {"@darkGrey", Style::getColor(Style::DarkGrey).name()},
                {"@mediumGrey", Style::getColor(Style::MediumGrey).name()},
                {"@mediumGreyLight", Style::getColor(Style::MediumGreyLight).name()},
                {"@lightGrey", Style::getColor(Style::LightGrey).name()},
                {"@white", Style::getColor(Style::White).name()},
                {"@orange", Style::getColor(Style::Orange).name()},
                {"@themeDark", Style::getColor(Style::ThemeDark).name()},
                {"@themeMediumDark", Style::getColor(Style::ThemeMediumDark).name()},
                {"@themeMedium", Style::getColor(Style::ThemeMedium).name()},
                {"@themeLight", Style::getColor(Style::ThemeLight).name()},

                // fonts
                {"@baseFont",
                 QString::fromUtf8("'%1' %2px").arg(baseFont.family()).arg(QFontInfo(baseFont).pixelSize())},
                {"@extraBig", qssifyFont(Style::getFont(Style::ExtraBig))},
                {"@big", qssifyFont(Style::getFont(Style::Big))},
                {"@bigBold", qssifyFont(Style::getFont(Style::BigBold))},
                {"@medium", qssifyFont(Style::getFont(Style::Medium))},
                {"@mediumBold", qssifyFont(Style::getFont(Style::MediumBold))},
                {"@small", qssifyFont(Style::getFont(Style::Small))},
                {"@smallLight", qssifyFont(Style::getFont(Style::SmallLight))}};
    }

    for (const QString& key : dict.keys()) {
        qss.replace(QRegularExpression(QString("%1\\b").arg(key)), dict[key]);
    }

    return qss;
}
示例#3
0
void MyImageList::setStatus(const QMap<QUrl, int>& status)
{
    foreach (const QUrl& url, status.keys())
    {
        KPImagesListViewItem* const item = listView()->findItem(url);

        if (item)
        {
            QStringList errors;
            int         flags = status.value(url);

            if (flags & META_TIME_ERROR)
            {
                errors << i18n("Failed to update metadata timestamp");
            }

            if (flags & FILE_TIME_ERROR)
            {
                errors << i18n("Failed to update file timestamp");
            }

            if (flags & FILE_NAME_ERROR)
            {
                errors << i18n("Failed to rename file");
            }

            if (errors.isEmpty())
            {
                item->setText(STATUS, i18n("Processed without error"));
            }
            else
            {
                item->setText(STATUS, errors.join(QLatin1String(" | ")));
            }
        }
    }
}
示例#4
0
QString QDjangoCompiler::databaseColumn(const QString &name)
{
    QDjangoMetaModel model = baseModel;
    QString modelName;
    QString modelPath;
    QString modelRef = referenceModel(QString(), &model, false);
    QStringList bits = name.split(QLatin1String("__"));

    while (bits.size() > 1) {
        const QByteArray fk = bits.first().toLatin1();
        QDjangoMetaModel foreignModel;
        bool foreignNullable = false;

        if (!modelPath.isEmpty())
            modelPath += QLatin1String("__");
        modelPath += bits.first();

        if (!model.foreignFields().contains(fk)) {
            // this might be a reverse relation, so look for the model
            // and if it exists continue
            foreignModel = QDjango::metaModel(fk);
            QDjangoReverseReference rev;
            const QMap<QByteArray, QByteArray> foreignFields = foreignModel.foreignFields();
            foreach (const QByteArray &foreignKey, foreignFields.keys()) {
                if (foreignFields[foreignKey] == baseModel.className()) {
                    rev.leftHandKey = foreignModel.localField(foreignKey + "_id").column();
                    break;
                }
            }

            if (rev.leftHandKey.isEmpty()) {
                qWarning() << "Invalid field lookup" << name;
                return QString();
            }
            rev.rightHandKey = foreignModel.primaryKey();
            reverseModelRefs[modelPath] = rev;
        } else {
示例#5
0
void ProcessingManager::distributeProcesses() {
    QMutexLocker locker(&ProcessingManager::mutex_);
    
    int numJobs = ProjectPreferences().processJobs();
    setupProcessors(numJobs);
    
    //Loop over all the processors that are free
    for (int np = 0; np < numJobs; ++np) {
        ImageScriptProcessor* processor = processors_[np];
        int queueSize = queueModel_->rowCount();
        if (processor->state() == QProcess::NotRunning && queueSize > 0) {
            QMap<ProjectImage*, QStringList> next = queueModel_->nextInQueue();
            ProjectImage* image=0;
            QStringList scripts;
            if (!next.isEmpty()) {
                image = next.keys().first();
                scripts = next[image];
            }

            if (image && !scripts.isEmpty()) {
                processor->execute(image, scripts);
            }
        }
    }

    //Check if all the processors are free, if yes stop the execution
    bool running = false;
    for (ImageScriptProcessor* processor : processors_) {
        if(processor->state() == QProcess::Running || processor->state() == QProcess::Starting){
            running = true;
            break;
        }
    }
    
    if(!running) executeProcesses(false);
    
}
QGeoSearchManagerEngineCm::QGeoSearchManagerEngineCm(
    const QMap<QString, QVariant> &parameters, QGeoServiceProvider::Error *error,
    QString *errorString)
        : QGeoSearchManagerEngine(parameters),
	  m_host("geocoding.cloudmade.com"),
	  m_token(QGeoServiceProviderFactoryCm::defaultToken)
{
    m_networkManager = new QNetworkAccessManager(this);

    QList<QString> keys = parameters.keys();

    if (keys.contains("places.proxy")) {
        QString proxy = parameters.value("places.proxy").toString();
        if (!proxy.isEmpty())
            m_networkManager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, 8080));
    }

    if (keys.contains("places.host")) {
        QString host = parameters.value("places.host").toString();
        if (!host.isEmpty())
            m_host = host;
    }

    setSupportsGeocoding(true);
    setSupportsReverseGeocoding(true);

    QGeoSearchManager::SearchTypes supportedSearchTypes;
    supportedSearchTypes |= QGeoSearchManager::SearchLandmarks;
    supportedSearchTypes |= QGeoSearchManager::SearchGeocode;
    setSupportedSearchTypes(supportedSearchTypes);

    if (error)
        *error = QGeoServiceProvider::NoError;

    if (errorString)
        *errorString = "";
}
void Mp3tunesServiceCollectionLocation::copyUrlsToCollection (
        const QMap<Meta::TrackPtr, KUrl> &sources,
        const Transcoding::Configuration &configuration )
{
    DEBUG_BLOCK
    Q_UNUSED( configuration ); // TODO: we might support transcoding here

    QStringList urls;
    QString error;
    debug() << "sources has " << sources.count();
    foreach( const Meta::TrackPtr &track, sources.keys() )
    {
        debug() << "copying " << sources[ track ] << " to mp3tunes locker";
        debug() << "file is at " << sources[ track ].pathOrUrl();

        QString supported_types = "mp3 mp4 m4a m4b m4p aac wma ogg";
        
        if( supported_types.contains( track->type() ) )
        {   

            debug() << "Added " << sources[ track ].pathOrUrl() << " to queue.";
            urls.push_back( sources[ track ].pathOrUrl() );

        } 
        else 
        {
            error = i18n( "Only the following types of tracks can be uploaded to MP3tunes: mp3, mp4, m4a, m4p, aac, wma, and ogg. " );
            debug() << "File type not supprted " << track->type();
        }
    }
    if( !error.isEmpty() )
        Amarok::Components::logger()->longMessage( error );
    Mp3tunesSimpleUploader * uploadWorker = new Mp3tunesSimpleUploader( m_collection->locker(), urls );
    connect( uploadWorker, SIGNAL(uploadComplete()), this, SLOT(slotCopyOperationFinished()) );
    ThreadWeaver::Weaver::instance()->enqueue( uploadWorker );
}
示例#8
0
//! ----------------------- restoreSettings ------------------------------------
void Equalizer_Dialog::restoreSettings()
{
    _presetList.clear();
    _comboBoxPreset->clear();

    QMap<QString, Equalizer::EqPreset> presetsEq = SETTINGS()->_presetEq;

    //! Load presets
    if ( presetsEq.isEmpty() ) {
      addDefaultPreset();
    }
    else {
      foreach (const QString& name, presetsEq.keys()) {
        addPreset( name , presetsEq[name] );
      }
    }

    //! Load selected preset
    const QString selected_preset = SETTINGS()->_currentPreset;
    const int selectedIdx = _comboBoxPreset->findText(selected_preset);

    if (selectedIdx != -1) {
      _comboBoxPreset->setCurrentIndex(selectedIdx);
      for (int i=0 ; i < Equalizer::kBands ; ++i) {
        eqSliderList[i]->setValue(_presetList[selected_preset].gain[i]);
      }
    }

    //! Load Enabled state
    _enableCheckBox->setChecked( SETTINGS()->_enableEq );
    _slider_container->setEnabled(_enableCheckBox->isChecked());

    //! signal loaded preset
    if(_enableCheckBox->isChecked())
      equalizerChanged();
}
示例#9
0
QMap<QString, int> VersionFinal::getExistingOrder() const
{

	QMap<QString, int> order;
	// default
	{
		for (auto file : versionFiles)
		{
			order.insert(file->fileId, file->order);
		}
	}
	// overriden
	{
		QMap<QString, int> overridenOrder = OneSixVersionBuilder::readOverrideOrders(m_instance);
		for (auto id : order.keys())
		{
			if (overridenOrder.contains(id))
			{
				order[id] = overridenOrder[id];
			}
		}
	}
	return order;
}
示例#10
0
/*!
   Returns a URI that completely describes a manager implementation, datastore, and the parameters
   with which to instantiate the manager, from the given \a managerName, \a params and an optional
   \a implementationVersion.  This function is generally useful only if you intend to construct a
   manager with the \l fromUri() function, or wish to construct a contact id
   manually (for synchronization or other purposes).  Most clients will not need to use this function.
*/
QString QContactManager::buildUri(const QString &managerName, const QMap<QString, QString> &params, int implementationVersion)
{
    QString ret(QStringLiteral("qtcontacts:%1:%2"));
    // we have to escape each param
    QStringList escapedParams;
    QStringList keys = params.keys();
    for (int i=0; i < keys.size(); i++) {
        QString key = keys.at(i);
        QString arg = params.value(key);
        arg = QContactId::escapeUriParam(arg);
        key = QContactId::escapeUriParam(key);
        key = key + QLatin1Char('=') + arg;
        escapedParams.append(key);
    }

    if (implementationVersion != -1) {
        QString versionString = QString(QStringLiteral(QTCONTACTS_IMPLEMENTATION_VERSION_NAME));
        versionString += QString::fromLatin1("=");
        versionString += QString::number(implementationVersion);
        escapedParams.append(versionString);
    }

    return ret.arg(managerName, escapedParams.join(QStringLiteral("&")));
}
示例#11
0
void MainWindow::requestsDone()
{
    switch(action) {
    case NIX:
        break;
    case CENSUS:
        break;
    case PLAYERS:
        break;
    case GUILDS:
        break;
    case TESTACHIEVE:
        QMap<int,int> acount;
        QMap<int,int> ts;
        for(Character c: ArmoryCharacter::characters) {
            qDebug() << c.achievements.size() << c.achievementsTimestamp.size() << c.name;
            for (int i=0; i<c.achievements.size(); i++) {
                int a = c.achievements[i];
                if (i==0) qDebug() << a << c.achievementsTimestamp[i];
                if (acount[a] > 0) {
                    if (ts[a] == c.achievementsTimestamp[i])
                        acount[a]++;
                } else {
                    acount[a] = 1;
                    ts[a] = c.achievementsTimestamp[i];
                }
            }
        }
        for(int a: acount.keys()) {
            if (acount[a] == 4) {
                qDebug() << Armory::achievementIndex[a];
            }
        }
        break;
    }
}
示例#12
0
void SM_FilePanel::fillComboBox(QMap<QString, QString> accountsMap, const QString &currentAccount)
{
    QStringList keys(accountsMap.keys());

    accountsComboBox->clear();

    for(int i = 0; i < keys.count(); ++i)
    {
        QString discLetter(keys[i]);

        discLetter = discLetter.rightJustified(2,' ');
        discLetter = discLetter.leftJustified(6, ' ');

        accountsComboBox->addItem(discLetter + ACCOUNT_SEPARATOR_BEGIN + accountsMap[keys[i]] + ACCOUNT_SEPARATOR_END);
        accountsComboBox->setItemIcon(i, QIcon(QApplication::style()->standardIcon(QStyle::SP_DriveFDIcon)));

        if(currentAccount == accountsMap[keys[i]] && accountsComboBox->currentIndex() != i)
        {
            accountsComboBox->setCurrentIndex(i);
        }
    }

    accountsComboBox->setMinimumWidth(80);
}
示例#13
0
void MenuBar::AddShowPlatformsMenu(QMenu* view_menu)
{
  static const QMap<QString, bool*> platform_map{
      {tr("Show Wii"), &SConfig::GetInstance().m_ListWii},
      {tr("Show GameCube"), &SConfig::GetInstance().m_ListGC},
      {tr("Show WAD"), &SConfig::GetInstance().m_ListWad},
      {tr("Show ELF/DOL"), &SConfig::GetInstance().m_ListElfDol}};

  QActionGroup* platform_group = new QActionGroup(this);
  QMenu* plat_menu = view_menu->addMenu(tr("Show Platforms"));
  platform_group->setExclusive(false);

  for (const auto& key : platform_map.keys())
  {
    bool* config = platform_map[key];
    QAction* action = platform_group->addAction(plat_menu->addAction(key));
    action->setCheckable(true);
    action->setChecked(*config);
    connect(action, &QAction::toggled, [this, config, key](bool value) {
      *config = value;
      emit GameListPlatformVisibilityToggled(key, value);
    });
  }
}
示例#14
0
void PropertiesDialog::saveShortcuts()
{
    QMap<QString, QAction*> actions = QTerminalApp::Instance()->getWindowList()[0]->leaseActions();
    QList< QString > shortcutKeys = actions.keys();
    int shortcutCount = shortcutKeys.count();

    shortcutsWidget->setRowCount( shortcutCount );

    for( int x=0; x < shortcutCount; x++ )
    {
        QString keyValue = shortcutKeys.at(x);
        QAction *keyAction = actions[keyValue];

        QTableWidgetItem *item = shortcutsWidget->item(x, 1);
        QKeySequence sequence = QKeySequence(item->text());
        QString sequenceString = sequence.toString();

        QList<QKeySequence> shortcuts;
        foreach (sequenceString, item->text().split('|'))
            shortcuts.append(QKeySequence(sequenceString));
        keyAction->setShortcuts(shortcuts);
    }
    Properties::Instance()->saveSettings();
}
SpellCheckerCoreOptionsWidget::SpellCheckerCoreOptionsWidget(const SpellChecker::Internal::SpellCheckerCoreSettings * const settings, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SpellCheckerCoreOptionsWidget)
{
    ui->setupUi(this);
    /* Hide the error widget by default, since there should not be errors. */
    ui->widgetErrorOutput->setVisible(false);
    ui->toolButtonAddProject->setIcon(Utils::Icons::PLUS.icon());
    /* Manually create the correct Minus icon in the same way that the Icon
     * Utils creates the PLUS icon. The reason for this is that the PLUS
     * icon also has a PLUS_TOOLBAR icon for toolbars, but the Minus icon
     * does not have these two icons, it only has the one, and that one
     * is for the toolbar since nowhere else is a normal one needed. */
    ui->toolButtonRemoveProject->setIcon(Utils::Icon({{QLatin1String(":/utils/images/minus.png")
                                                       , Utils::Theme::PaletteText}}, Utils::Icon::Tint).icon());

    ui->comboBoxSpellChecker->addItem(QLatin1String(""));
    QMap<QString, ISpellChecker*> availableSpellCheckers = SpellCheckerCore::instance()->addedSpellCheckers();
    foreach(const QString& name, availableSpellCheckers.keys()) {
        ui->comboBoxSpellChecker->addItem(name);
    }

    updateWithSettings(settings);
}
示例#16
0
void UIDaemonHandler::AddComplex(QString name)
{
    if(SubstitutionFileParser::IsSubstituted(((UIAppDesc*)appList[name])->getAppDesktopFile()))
    {
	qDebug() << "Locking Complex App";
	QMap<QString,QString> dbusList = SubstitutionFileParser::GetApplicationDBusSearches(((UIAppDesc*)appList[name])->getAppDesktopFile());
	QMap<QString,QString> pathList = SubstitutionFileParser::GetApplicationPaths(((UIAppDesc*)appList[name])->getAppDesktopFile());
	QMap<QString,QString> cmdList = SubstitutionFileParser::GetApplicationCommandLines(((UIAppDesc*)appList[name])->getAppDesktopFile());

	QDBusReply<bool> result;

	for(int i = 0; i < dbusList.count(); i++)
	{
#ifndef DBUSSETTINGS
	    settings->AddSearch(dbusList.keys().at(i),1,dbusList.values().at(i));
#endif
	    dbus->call("AddSearch",dbusList.keys()[i],"session",dbusList.values().at(i));
	}

	for(int i = 0; i < pathList.count(); i++)
	{
#ifndef DBUSSETTINGS
	    settings->AddApp(pathList.keys().at(i),pathList.values().at(i));
#endif

	    dbus->call("AddPath", pathList.keys().at(i),pathList.values().at(i));
	}

	for(int i = 0; i < cmdList.count(); i++)
	{
#ifndef DBUSSETTINGS
	    settings->AddCommandLine(cmdList.keys().at(i),cmdList.values().at(i));
#endif
	    dbus->call("AddCMD",cmdList.keys().at(i),cmdList.values().at(i));
	}

	((UIAppDesc*)appList[name])->OnLockChanged();
	QMLDaemonInterface::AppLocked();
    }
}
示例#17
0
void UIDaemonHandler::RemoveComplex(QString name)
{
    if(SubstitutionFileParser::IsSubstituted(((UIAppDesc*)appList[name])->getAppDesktopFile()))
    {
	qDebug() << "Unlocking Complex App:" << name;
	QMap<QString,QString> dbusList = SubstitutionFileParser::GetApplicationDBusSearches(((UIAppDesc*)appList[name])->getAppDesktopFile());
	QMap<QString,QString> pathList = SubstitutionFileParser::GetApplicationPaths(((UIAppDesc*)appList[name])->getAppDesktopFile());
	QMap<QString,QString> cmdList = SubstitutionFileParser::GetApplicationCommandLines(((UIAppDesc*)appList[name])->getAppDesktopFile());

	for(int i = 0; i < dbusList.count(); i++)
	{
#ifndef DBUSSETTINGS
	    settings->RemoveSearch(dbusList.keys().at(i));
#endif
	    dbus->call("RemoveSearch",dbusList.keys().at(i));
	}

	for(int i = 0; i < pathList.count(); i++)
	{
#ifndef DBUSSETTINGS
	    settings->RemoveApp(pathList.keys().at(i));
#endif
	    dbus->call("RemoveApp",pathList.keys().at(i));
	}

	for(int i = 0; i < cmdList.count(); i++)
	{
#ifndef DBUSSETTINGS
	    settings->RemoveCommandLine(cmdList.keys().at(i));
#endif
	    dbus->call("RemoveCMD",cmdList.keys().at(i));
	}

	((UIAppDesc*)appList[name])->OnLockChanged();
	QMLDaemonInterface::AppUnlocked();

	emit appListChanged();
    }

}
Assignments CorrespondenceGenerator::generateGroupAssignments()
{		
	Assignments generatedAssignments;

	auto & segsA = sA->property["segments"].value<Segments>();
	auto & segsB = sB->property["segments"].value<Segments>();

	auto boxA = sA->bbox(), boxB = sB->bbox();

	auto & groupsA = sA->property["groups"].value< std::vector< std::vector<size_t> > >();
	auto & groupsB = sB->property["groups"].value< std::vector< std::vector<size_t> > >();

	/// Build similarity matrix of groups:
	Eigen::MatrixXd similiarity = Eigen::MatrixXd::Ones( groupsA.size(), groupsB.size() + 1 );

	for(size_t i = 0; i < similiarity.rows(); i++){
		double minVal = DBL_MAX;
		for(size_t j = 0; j < similiarity.cols(); j++){
			double val = 0;

			if( j < groupsB.size() )
			{
				Eigen::AlignedBox3d groupBoxA, groupBoxB;

				for(auto sid : groupsA[i]) groupBoxA.extend( segsA[sid].property["bbox"].value<Eigen::AlignedBox3d>() );
				for(auto sid : groupsB[j]) groupBoxB.extend( segsB[sid].property["bbox"].value<Eigen::AlignedBox3d>() );

				Vector3 relativeCenterA = (groupBoxA.center()-boxA.min()).array() / boxA.sizes().array();
				Vector3 relativeCenterB = (groupBoxB.center()-boxB.min()).array() / boxB.sizes().array();

				val = ( relativeCenterA - relativeCenterB ).norm();

				minVal = std::min(minVal, val);
			}

			similiarity(i,j) = val;
		}
		double maxVal = similiarity.row(i).maxCoeff();
		if(maxVal == 0) maxVal = 1.0;

		for(size_t j = 0; j < groupsB.size(); j++)
			similiarity(i,j) = (similiarity(i,j) - minVal) / maxVal;
	}

	std::vector< std::vector<float> > data;
	for(int i = 0; i < similiarity.rows(); i++){
		std::vector<float> dataRow;
		for(int j = 0; j < similiarity.cols(); j++) 
			dataRow.push_back( similiarity(i,j) );
		data.push_back(dataRow);
	}
	if(false) showTableColorMap(data, true); // DEBUG

	// Parameters:
	double similarity_threshold = 0.25;
	int count_threshold = 1;

	// Collect good candidates
	Assignments candidates;
	for(size_t i = 0; i < similiarity.rows(); i++){
		QVector<size_t> candidate;
		for(size_t j = 0; j < similiarity.cols(); j++){
			if(similiarity(i,j) < similarity_threshold)
				candidate << j;
		}
		candidates << candidate;
	}

	Assignments assignments;
	cart_product(assignments, candidates);

	// Filter assignments
	Assignments filtered;
	for(auto & a : assignments)
	{
		QMap<size_t,size_t> counts;
		bool accept = true;
		auto NOTHING_SEGMENT = similiarity.cols()-1;

		for(auto i : a) counts[i]++;
		for(auto k : counts.keys()){
			if(k != NOTHING_SEGMENT && counts[k] > count_threshold){
				accept = false;
				break;
			}
		}

		if( accept ) filtered << a;
	}

	// DEBUG:
	if(true) saveToTextFile("assignments.txt", vecToString2(filtered));

	generatedAssignments = filtered;
	
	return generatedAssignments;
}
示例#19
0
QScriptObjectSnapshot::Delta QScriptObjectSnapshot::capture(const QScriptValue &object)
{
    Delta result;
    QMap<QString, QScriptValueProperty> currProps;
    QHash<QString, int> propertyNameToIndex;
    {
        int i = 0;
        QScriptValueIterator it(object);
        while (it.hasNext()) {
            it.next();
            QScriptValueProperty prop(it.name(), it.value(), it.flags());
            currProps.insert(it.name(), prop);
            propertyNameToIndex.insert(it.name(), i);
            ++i;
        }
        if (object.prototype().isValid()) {
            QString __proto__ = QString::fromLatin1("__proto__");
            QScriptValueProperty protoProp(
                __proto__, object.prototype(),
                QScriptValue::Undeletable | QScriptValue::ReadOnly);
            currProps.insert(__proto__, protoProp);
            propertyNameToIndex.insert(__proto__, i);
            ++i;
        }
    }

    QSet<QString> prevSet;
    for (int i = 0; i < m_properties.size(); ++i)
        prevSet.insert(m_properties.at(i).name());
    QSet<QString> currSet = currProps.keys().toSet();
    QSet<QString> removedProperties = prevSet - currSet;
    QSet<QString> addedProperties = currSet - prevSet;
    QSet<QString> maybeChangedProperties = currSet & prevSet;

    {
        QMap<int, QScriptValueProperty> am;
        QSet<QString>::const_iterator it;
        for (it = addedProperties.constBegin(); it != addedProperties.constEnd(); ++it) {
            int idx = propertyNameToIndex[*it];
            am[idx] = currProps[*it];
        }
        result.addedProperties = am.values();
    }

    {
        QSet<QString>::const_iterator it;
        for (it = maybeChangedProperties.constBegin(); it != maybeChangedProperties.constEnd(); ++it) {
            const QScriptValueProperty &p1 = currProps[*it];
            const QScriptValueProperty &p2 = findProperty(*it);
            if (!_q_equal(p1.value(), p2.value())
                || (p1.flags() != p2.flags())) {
                result.changedProperties.append(p1);
            }
        }
    }

    result.removedProperties = removedProperties.toList();

    m_properties = currProps.values();

    return result;
}
示例#20
0
  QPair<QString, QString> GUI_EXPORT getSaveAsImageName( QWidget *parent, const QString &message, const QString &defaultFilename )
  {
    // get a list of supported output image types
    QMap<QString, QString> filterMap;
    Q_FOREACH ( const QByteArray &format, QImageWriter::supportedImageFormats() )
    {
      //svg doesn't work so skip it
      if ( format == "svg" )
        continue;

      filterMap.insert( createFileFilter_( format ), format );
    }

#ifdef QGISDEBUG
    QgsDebugMsg( QStringLiteral( "Available Filters Map: " ) );
    for ( QMap<QString, QString>::iterator it = filterMap.begin(); it != filterMap.end(); ++it )
    {
      QgsDebugMsg( it.key() + "  :  " + it.value() );
    }
#endif

    QgsSettings settings;  // where we keep last used filter in persistent state
    QString lastUsedDir = settings.value( QStringLiteral( "UI/lastSaveAsImageDir" ), QDir::homePath() ).toString();

    // Prefer "png" format unless the user previously chose a different format
    QString pngExtension = QStringLiteral( "png" );
    QString pngFilter = createFileFilter_( pngExtension );
    QString selectedFilter = settings.value( QStringLiteral( "UI/lastSaveAsImageFilter" ), pngFilter ).toString();

    QString initialPath;
    if ( defaultFilename.isNull() )
    {
      //no default filename provided, just use last directory
      initialPath = lastUsedDir;
    }
    else
    {
      //a default filename was provided, so use it to build the initial path
      initialPath = QDir( lastUsedDir ).filePath( defaultFilename );
    }

    QString outputFileName;
    QString ext;
#if defined(Q_OS_WIN) || defined(Q_OS_MAC) || defined(Q_OS_LINUX)
    outputFileName = QFileDialog::getSaveFileName( parent, message, initialPath, QStringList( filterMap.keys() ).join( QStringLiteral( ";;" ) ), &selectedFilter );

    if ( !outputFileName.isNull() )
    {
      ext = filterMap.value( selectedFilter, QString() );
      if ( !ext.isNull() )
        settings.setValue( QStringLiteral( "UI/lastSaveAsImageFilter" ), selectedFilter );
      settings.setValue( QStringLiteral( "UI/lastSaveAsImageDir" ), QFileInfo( outputFileName ).absolutePath() );
    }
#else

    //create a file dialog using the filter list generated above
    std::unique_ptr<QFileDialog> fileDialog( new QFileDialog( parent, message, initialPath, QStringList( filterMap.keys() ).join( ";;" ) ) );

    // allow for selection of more than one file
    fileDialog->setFileMode( QFileDialog::AnyFile );
    fileDialog->setAcceptMode( QFileDialog::AcceptSave );
    fileDialog->setOption( QFileDialog::DontConfirmOverwrite, false );

    if ( !selectedFilter.isEmpty() )     // set the filter to the last one used
    {
      fileDialog->selectNameFilter( selectedFilter );
    }

    //prompt the user for a fileName
    if ( fileDialog->exec() == QDialog::Accepted )
    {
      outputFileName = fileDialog->selectedFiles().first();
    }

    selectedFilter = fileDialog->selectedNameFilter();
    QgsDebugMsg( "Selected filter: " + selectedFilter );
    ext = filterMap.value( selectedFilter, QString() );

    if ( !ext.isNull() )
      settings.setValue( "/UI/lastSaveAsImageFilter", selectedFilter );

    settings.setValue( "/UI/lastSaveAsImageDir", fileDialog->directory().absolutePath() );
#endif

    // Add the file type suffix to the fileName if required
    if ( !ext.isNull() && !outputFileName.endsWith( '.' + ext.toLower(), Qt::CaseInsensitive ) )
    {
      outputFileName += '.' + ext;
    }

    return qMakePair<QString, QString>( outputFileName, ext );
  }
示例#21
0
bool
PathGroups::keyPressEvent(QKeyEvent *event)
{
  for(int i=0; i<m_paths.count(); i++)
    {
      if (m_paths[i]->grabsMouse())
	{
	  if (event->key() == Qt::Key_G)
	    {
	      m_paths[i]->removeFromMouseGrabberPool();
	      return true;
	    }
	  if (event->key() == Qt::Key_C)
	    {
	      bool b = m_paths[i]->closed();
	      m_paths[i]->setClosed(!b);
	      return true;
	    }
	  else if (event->key() == Qt::Key_P)
	    {
	      bool b = m_paths[i]->showPoints();
	      m_paths[i]->setShowPoints(!b);    
	      return true;
	    }
	  else if (event->key() == Qt::Key_L)
	    {
	      bool b = m_paths[i]->showLength();
	      m_paths[i]->setShowLength(!b);    
	      return true;
	    }
	  else if (event->key() == Qt::Key_X)
	    {
	      m_paths[i]->setMoveAxis(PathGroupGrabber::MoveX);
	      return true;
	    }
	  else if (event->key() == Qt::Key_Y)
	    {
	      if (event->modifiers() & Qt::ControlModifier ||
		  event->modifiers() & Qt::MetaModifier)
		m_paths[i]->redo();
	      else
		m_paths[i]->setMoveAxis(PathGroupGrabber::MoveY);
	      return true;
	    }
	  else if (event->key() == Qt::Key_Z)
	    {
	      if (event->modifiers() & Qt::ControlModifier ||
		  event->modifiers() & Qt::MetaModifier)
		m_paths[i]->undo();
	      else
		m_paths[i]->setMoveAxis(PathGroupGrabber::MoveZ);
	      return true;
	    }
	  else if (event->key() == Qt::Key_W)
	    {
	      m_paths[i]->setMoveAxis(PathGroupGrabber::MoveAll);
	      return true;
	    }
	  else if (event->key() == Qt::Key_S)
	    {
	      int idx = m_paths[i]->pointPressed();
	      if (idx > -1)
		{
		  float radx = m_paths[i]->getRadX(idx);
		  if (event->modifiers() & Qt::ShiftModifier)
		    radx--;
		  else
		    radx++;
		  radx = qMax(1.0f, radx);
		  m_paths[i]->setRadX(idx, radx, m_sameForAll);
		  return true;
		}
	    }
	  else if (event->key() == Qt::Key_T)
	    {
	      int idx = m_paths[i]->pointPressed();
	      if (idx > -1)
		{
		  float rady = m_paths[i]->getRadY(idx);
		  if (event->modifiers() & Qt::ShiftModifier)
		    rady--;
		  else
		    rady++;
		  rady = qMax(1.0f, rady);
		  m_paths[i]->setRadY(idx, rady, m_sameForAll);
		}
	      else // switch to tube mode
		{
		  if (event->modifiers() & Qt::ShiftModifier)
		    {
		      m_paths[i]->loadCaption();
		    }
		  else
		    {
		      bool b = m_paths[i]->tube();
		      m_paths[i]->setTube(!b);
		    }
		}

	      return true;
	    }
	  else if (event->key() == Qt::Key_A)
	    {
	      int idx = m_paths[i]->pointPressed();
	      if (idx > -1)
		{
		  float a = m_paths[i]->getAngle(idx);
		  if (event->modifiers() & Qt::ShiftModifier)
		    a--;
		  else
		    a++;
		  m_paths[i]->setAngle(idx, a, m_sameForAll);
		  return true;
		}
	    }
	  else if (event->key() == Qt::Key_Delete ||
		   event->key() == Qt::Key_Backspace ||
		   event->key() == Qt::Key_Backtab)
	    {
	      m_paths[i]->removeFromMouseGrabberPool();
	      m_paths.removeAt(i);
	      return true;
	    }

	  if (event->key() == Qt::Key_Space)
	    {
	      PropertyEditor propertyEditor;
	      QMap<QString, QVariantList> plist;

	      QVariantList vlist;

	      vlist.clear();
	      vlist << QVariant("double");
	      vlist << QVariant(m_paths[i]->opacity());
	      vlist << QVariant(0.0);
	      vlist << QVariant(1.0);
	      vlist << QVariant(0.1); // singlestep
	      vlist << QVariant(1); // decimals
	      plist["opacity"] = vlist;

	      vlist.clear();
	      vlist << QVariant("colorgradient");
	      QGradientStops stops = m_paths[i]->stops();
	      for(int s=0; s<stops.size(); s++)
		{
		  float pos = stops[s].first;
		  QColor color = stops[s].second;
		  int r = color.red();
		  int g = color.green();
		  int b = color.blue();
		  int a = color.alpha();
		  vlist << QVariant(pos);
		  vlist << QVariant(r);
		  vlist << QVariant(g);
		  vlist << QVariant(b);
		  vlist << QVariant(a);
		}
	      plist["color"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->filterPathLen());
	      plist["filter on length"] = vlist;

	      float vmin, vmax;
	      m_paths[i]->userPathlenMinmax(vmin, vmax);
	      vlist.clear();
	      vlist << QVariant("string");
	      vlist << QVariant(QString("%1 %2").arg(vmin).arg(vmax));
	      plist["length bounds"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->scaleType());
	      plist["scale type"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->depthcue());
	      plist["depthcue"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->segments());
	      vlist << QVariant(1);
	      vlist << QVariant(100);
	      plist["smoothness"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->sections());
	      vlist << QVariant(1);
	      vlist << QVariant(100);
	      plist["sections"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->sparseness());
	      vlist << QVariant(1);
	      vlist << QVariant(100);
	      plist["sparseness"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->separation());
	      vlist << QVariant(0);
	      vlist << QVariant(10);
	      plist["screen separation"] = vlist;

	      vlist.clear();
	      vlist << QVariant("combobox");
	      vlist << QVariant(m_paths[i]->capType());
	      vlist << QVariant("flat");
	      vlist << QVariant("round");
	      vlist << QVariant("arrow");
	      plist["cap style"] = vlist;

	      vlist.clear();
	      vlist << QVariant("combobox");
	      vlist << QVariant(m_paths[i]->arrowDirection());
	      vlist << QVariant("forward");
	      vlist << QVariant("backward");
	      plist["arrow direction"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->animate());
	      plist["animate"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->allowInterpolate());
	      plist["interpolate"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->animateSpeed());
	      vlist << QVariant(10);
	      vlist << QVariant(100);
	      plist["animation speed"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->arrowForAll());
	      plist["arrows for all"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_sameForAll);
	      plist["same for all"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->clip());
	      plist["clip"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->allowEditing());
	      plist["allow editing"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->blendMode());
	      plist["blend with volume"] = vlist;

	      vlist.clear();
	      plist["command"] = vlist;

	      vlist.clear();
	      QFile helpFile(":/pathgroups.help");
	      if (helpFile.open(QFile::ReadOnly))
		{
		  QTextStream in(&helpFile);
		  QString line = in.readLine();
		  while (!line.isNull())
		    {
		      if (line == "#begin")
			{
			  QString keyword = in.readLine();
			  QString helptext;
			  line = in.readLine();
			  while (!line.isNull())
			    {
			      helptext += line;
			      helptext += "\n";
			      line = in.readLine();
			      if (line == "#end") break;
			    }
			  vlist << keyword << helptext;
			}
		      line = in.readLine();
		    }
		}	      
	      plist["commandhelp"] = vlist;


	      vlist.clear();
	      QString mesg;
	      float pmin, pmax;
	      m_paths[i]->pathlenMinmax(pmin, pmax);
	      mesg = QString("min/max path lengths : %1 %2\n").arg(pmin).arg(pmax);
	      float mins,maxs;
	      mins = m_paths[i]->minScale();
	      maxs = m_paths[i]->maxScale();
	      mesg += QString("min/max scale : %1 %2\n").arg(mins).arg(maxs);
	      vlist << mesg;
	      plist["message"] = vlist;


	      QStringList keys;
	      keys << "color";
	      keys << "opacity";
	      keys << "depthcue";
	      keys << "gap";
	      keys << "filter on length";
	      keys << "length bounds";
	      keys << "scale type";
	      keys << "gap";
	      keys << "smoothness";
	      keys << "sections";
	      keys << "sparseness";
	      keys << "screen separation";
	      keys << "gap";
	      keys << "cap style";
	      keys << "arrow direction";
	      keys << "arrows for all";
	      keys << "gap";
	      keys << "animate";
	      keys << "interpolate";
	      keys << "animation speed";
	      keys << "gap";
	      keys << "same for all";
	      keys << "clip";
	      keys << "blend with volume";
	      keys << "allow editing";
	      keys << "command";
	      keys << "commandhelp";
	      keys << "message";
	      

	      propertyEditor.set("Path Group Parameters", plist, keys);

	      
	      QMap<QString, QPair<QVariant, bool> > vmap;

	      if (propertyEditor.exec() == QDialog::Accepted)
		vmap = propertyEditor.get();
	      else
		return true;

	      keys = vmap.keys();

	      for(int ik=0; ik<keys.count(); ik++)
		{
		  QPair<QVariant, bool> pair = vmap.value(keys[ik]);


		  if (pair.second)
		    {
		      if (keys[ik] == "color")
			{
			  QGradientStops stops = propertyEditor.getGradientStops(keys[ik]);
			  m_paths[i]->setStops(stops);
			}
		      else if (keys[ik] == "opacity")
			m_paths[i]->setOpacity(pair.first.toDouble());
		      else if (keys[ik] == "scale type")
			m_paths[i]->setScaleType(pair.first.toBool());
		      else if (keys[ik] == "sections")
			m_paths[i]->setSections(pair.first.toInt());
		      else if (keys[ik] == "smoothness")
			m_paths[i]->setSegments(pair.first.toInt());
		      else if (keys[ik] == "sparseness")
			m_paths[i]->setSparseness(pair.first.toInt());
		      else if (keys[ik] == "screen separation")
			m_paths[i]->setSeparation(pair.first.toInt());
		      else if (keys[ik] == "depthcue")
			m_paths[i]->setDepthcue(pair.first.toBool());
		      else if (keys[ik] == "animate")
			m_paths[i]->setAnimate(pair.first.toBool());
		      else if (keys[ik] == "interpolate")
			m_paths[i]->setAllowInterpolate(pair.first.toBool());
		      else if (keys[ik] == "animation speed")
			m_paths[i]->setAnimateSpeed(pair.first.toInt());
		      else if (keys[ik] == "cap style")
			m_paths[i]->setCapType(pair.first.toInt());
		      else if (keys[ik] == "arrow direction")
			m_paths[i]->setArrowDirection(pair.first.toInt());
		      else if (keys[ik] == "arrows for all")
			m_paths[i]->setArrowForAll(pair.first.toBool());
		      else if (keys[ik] == "same for all")
			{
			  m_sameForAll = pair.first.toBool();
			  m_paths[i]->setSameForAll(m_sameForAll);
			}
		      else if (keys[ik] == "clip")
			m_paths[i]->setClip(pair.first.toBool());
		      else if (keys[ik] == "allow editing")
			m_paths[i]->setAllowEditing(pair.first.toBool());
		      else if (keys[ik] == "blend with volume")
			m_paths[i]->setBlendMode(pair.first.toBool());
		      else if (keys[ik] == "filter on length")
			m_paths[i]->setFilterPathLen(pair.first.toBool());
		      else if (keys[ik] == "length bounds")
			{
			  QString vstr = pair.first.toString();
			  QStringList vl = vstr.split(" ", QString::SkipEmptyParts);
			  if (vl.count() == 2)
			    m_paths[i]->setUserPathlenMinmax(vl[0].toDouble(),
							     vl[1].toDouble());
			}
		    }
		}

	      QString cmd = propertyEditor.getCommandString();
	      if (!cmd.isEmpty())
		processCommand(i, cmd);	
	      	      
	      updateGL();
	    }
	}
    }
  
  return true;
}
示例#22
0
bool
ClipObject::commandEditor()
{
  PropertyEditor propertyEditor;
  QMap<QString, QVariantList> plist;
  QVariantList vlist;
  vlist.clear();
  plist["command"] = vlist;


  vlist.clear();
  vlist << QVariant("double");
  vlist << QVariant(m_opacity);
  vlist << QVariant(0.0);
  vlist << QVariant(1.0);
  vlist << QVariant(0.1); // singlestep
  vlist << QVariant(1); // decimals
  plist["opacity"] = vlist;
  
  vlist.clear();
  vlist << QVariant("color");
  Vec pcolor = m_color;
  QColor dcolor = QColor::fromRgbF(pcolor.x,
				   pcolor.y,
				   pcolor.z);
  vlist << dcolor;
  plist["color"] = vlist;
  
  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_apply);
  plist["apply clipping"] = vlist;

  vlist.clear();
  vlist << QVariant("int");
  vlist << QVariant(m_tfset);
  vlist << QVariant(-1);
  vlist << QVariant(15);
  plist["tfset"] = vlist;

  vlist.clear();
  vlist << QVariant("int");
  vlist << QVariant(m_thickness);
  vlist << QVariant(0);
  vlist << QVariant(200);
  plist["thickness"] = vlist;

  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_solidColor);
  plist["solid color"] = vlist;

  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_showSlice);
  plist["show slice"] = vlist;

  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_showThickness);
  plist["show thickness"] = vlist;

  vlist.clear();
  vlist << QVariant("combobox");
  if (m_viewportType)
    vlist << QVariant(1);
  else
    vlist << QVariant(0);
  vlist << QVariant("orthographic");
  vlist << QVariant("perspective");
  plist["camera type"] = vlist;

  vlist.clear();
  vlist << QVariant("double");
  vlist << QVariant(m_stereo);
  vlist << QVariant(0.0);
  vlist << QVariant(1.0);
  vlist << QVariant(0.1); // singlestep
  vlist << QVariant(1); // decimals
  plist["stereo"] = vlist;
  
  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_showOtherSlice);
  plist["show other slice"] = vlist;


  QString vpstr = QString("%1 %2 %3 %4").\
                  arg(m_viewport.x()).\
                  arg(m_viewport.y()).\
                  arg(m_viewport.z()).\
                  arg(m_viewport.w());
  vlist.clear();
  vlist << QVariant("string");
  vlist << QVariant(vpstr);
  plist["viewport"] = vlist;

  vlist.clear();
  vlist << QVariant("double");
  vlist << QVariant(m_viewportScale);
  vlist << QVariant(0.5);
  vlist << QVariant(30.0);
  vlist << QVariant(0.1); // singlestep
  vlist << QVariant(1); // decimals
  plist["viewport scale"] = vlist;  


  vlist.clear();
  QFile helpFile(":/clipobject.help");
  if (helpFile.open(QFile::ReadOnly))
    {
      QTextStream in(&helpFile);
      QString line = in.readLine();
      while (!line.isNull())
	{
	  if (line == "#begin")
	    {
	      QString keyword = in.readLine();
	      QString helptext;
	      line = in.readLine();
	      while (!line.isNull())
		{
		  helptext += line;
		  helptext += "\n";
		  line = in.readLine();
		  if (line == "#end") break;
		}
	      vlist << keyword << helptext;
	    }
	  line = in.readLine();
	}
    }
  
  plist["commandhelp"] = vlist;
  
  //---------------------
  vlist.clear();
  QString mesg;
  if (m_scale1 < 0 || m_scale2 < 0)
    mesg += QString("scales : %1 %2\n").arg(-m_scale1).arg(-m_scale2);
  else
    mesg += QString("vscales : %1 %2\n").arg(m_scale1).arg(m_scale2);

  mesg += QString("opacity : %1\n").arg(m_opacity);
  mesg += QString("position : %1 %2 %3\n").			\
    arg(m_position.x).arg(m_position.y).arg(m_position.z);

  Quaternion q = orientation();
  Vec axis;
  qreal angle;
  q.getAxisAngle(axis, angle);
  mesg += QString("rotation : %1 %2 %3 : %4\n").			\
    arg(axis.x).arg(axis.y).arg(axis.z).arg(RAD2DEG(angle));
  
  
  mesg += QString("Red axis : %1 %2 %3\n").		\
    arg(m_xaxis.x).arg(m_xaxis.y).arg(m_xaxis.z);
  mesg += QString("Green axis : %1 %2 %3\n").		\
    arg(m_yaxis.x).arg(m_yaxis.y).arg(m_yaxis.z);
  mesg += QString("Blue axis : %1 %2 %3\n").		\
    arg(m_tang.x).arg(m_tang.y).arg(m_tang.z);
  
  vlist << mesg;
  
  plist["message"] = vlist;
  //---------------------



  QStringList keys;
  keys << "apply clipping";
  keys << "solid color";
  keys << "show slice";
  keys << "show thickness";
  keys << "show other slice";
  keys << "gap";
  keys << "color";
  keys << "opacity";
  keys << "gap";
  keys << "viewport";
  keys << "tfset";
  keys << "thickness";
  keys << "viewport scale";
  keys << "camera type";
  keys << "stereo";
  keys << "gap";
  keys << "command";
  keys << "commandhelp";
  keys << "message";
  
  propertyEditor.set("Clip Plane Dialog", plist, keys);
  
  QMap<QString, QPair<QVariant, bool> > vmap;

  if (propertyEditor.exec() == QDialog::Accepted)
    vmap = propertyEditor.get();
  else
    return true;
	      
  keys = vmap.keys();

  for(int ik=0; ik<keys.count(); ik++)
    {
      QPair<QVariant, bool> pair = vmap.value(keys[ik]);
      
      
      if (pair.second)
	{
	  if (keys[ik] == "color")
	    {
	      QColor color = pair.first.value<QColor>();
	      float r = color.redF();
	      float g = color.greenF();
	      float b = color.blueF();
	      m_color = Vec(r,g,b);
	    }
	  else if (keys[ik] == "opacity")
	    m_opacity = pair.first.toDouble();
	  else if (keys[ik] == "solid color")
	    m_solidColor = pair.first.toBool();
	  else if (keys[ik] == "apply clipping")
	    m_apply = pair.first.toBool();
	  else if (keys[ik] == "show slice")
	    m_showSlice = pair.first.toBool();
	  else if (keys[ik] == "show thickness")
	    m_showThickness = pair.first.toBool();
	  else if (keys[ik] == "show other slice")
	    m_showOtherSlice = pair.first.toBool();
	  else if (keys[ik] == "tfset")
	    m_tfset = pair.first.toInt();
	  else if (keys[ik] == "thickness")
	    m_thickness = pair.first.toInt();
	  else if (keys[ik] == "viewport scale")
	    m_viewportScale = pair.first.toDouble();
	  else if (keys[ik] == "camera type")
	    m_viewportType = (pair.first.toInt() == 1);
	  else if (keys[ik] == "stereo")
	    m_stereo = pair.first.toDouble();
	  else if (keys[ik] == "viewport")
	    {
	      vpstr = pair.first.toString();
	      QStringList list = vpstr.split(" ", QString::SkipEmptyParts);
	      if (list.count() == 4)
		{
		  float x = list[0].toFloat();
		  float y = list[1].toFloat();
		  float z = list[2].toFloat();
		  float w = list[3].toFloat();
		  if (x < 0.0f || x > 1.0f ||
		      y < 0.0f || y > 1.0f ||
		      z < 0.0f || z > 1.0f ||
		      w < 0.0f || w > 1.0f)
		    QMessageBox::information(0, "",
		      QString("Values for viewport must be between 0.0 and 1.0 : %1 %2 %3 %4").\
					     arg(x).arg(y).arg(z).arg(w));
		  else
		    m_viewport = QVector4D(x,y,z,w);
		}
	      else if (list.count() == 3)
		{
		  float x = list[0].toFloat();
		  float y = list[1].toFloat();
		  float z = list[2].toFloat();
		  if (x < 0.0f || x > 1.0f ||
		      y < 0.0f || y > 1.0f ||
		      z < 0.0f || z > 1.0f)
		    QMessageBox::information(0, "",
		      QString("Values for viewport must be between 0.0 and 1.0 : %1 %2 %3").\
					     arg(x).arg(y).arg(z));
		  else
		    m_viewport = QVector4D(x,y,z,z);
		}
	      else if (list.count() == 2)
		{
		  float x = list[0].toFloat();
		  float y = list[1].toFloat();
		  if (x < 0.0f || x > 1.0f ||
		      y < 0.0f || y > 1.0f)
		    QMessageBox::information(0, "",
		      QString("Values for viewport must be between 0.0 and 1.0 : %1 %2").\
					     arg(x).arg(y));
		  else
		    m_viewport = QVector4D(x,y,0.5,0.5);
		}
	      else
		{
		  QMessageBox::information(0, "", "Switching off the viewport");
		  m_viewport = QVector4D(-1,-1,-1,-1);
		}
	    }
	}
    }

  QString cmd = propertyEditor.getCommandString();
  if (!cmd.isEmpty())
    return processCommand(cmd);
  else
    return true;

//  if (propertyEditor.exec() == QDialog::Accepted)
//    {
//      QString cmd = propertyEditor.getCommandString();
//      if (!cmd.isEmpty())
//	return processCommand(cmd);
//    }
//  else
//    return true;
}
示例#23
0
文件: utils.cpp 项目: Rockbox/rockbox
/** Check if a process with a given name is running
 *  @param names list of names to filter on. All processes if empty list.
 *  @return list of processname, process ID pairs.
 */
QMap<QString, QList<int> > Utils::findRunningProcess(QStringList names)
{
    QMap<QString, QList<int> > processlist;
    QMap<QString, QList<int> > found;
#if defined(Q_OS_WIN32)
    HANDLE hdl;
    PROCESSENTRY32 entry;
    bool result;

    hdl = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(hdl == INVALID_HANDLE_VALUE) {
        LOG_ERROR() << "CreateToolhelp32Snapshot failed.";
        return found;
    }
    entry.dwSize = sizeof(PROCESSENTRY32);
    entry.szExeFile[0] = '\0';
    if(!Process32First(hdl, &entry)) {
        LOG_ERROR() << "Process32First failed.";
        return found;
    }

    do {
        int pid = entry.th32ProcessID;  // FIXME: DWORD vs int!
        QString name = QString::fromWCharArray(entry.szExeFile);
        if(processlist.find(name) == processlist.end()) {
            processlist.insert(name, QList<int>());
        }
        processlist[name].append(pid);
        entry.dwSize = sizeof(PROCESSENTRY32);
        entry.szExeFile[0] = '\0';
        result = Process32Next(hdl, &entry);
    } while(result);
    CloseHandle(hdl);
#endif
#if defined(Q_OS_MACX)
    ProcessSerialNumber psn = { 0, kNoProcess };
    OSErr err;
    do {
        pid_t pid;
        err = GetNextProcess(&psn);
        err = GetProcessPID(&psn, &pid);
        if(err == noErr) {
            char buf[32] = {0};
            ProcessInfoRec info;
            memset(&info, 0, sizeof(ProcessInfoRec));
            info.processName = (unsigned char*)buf;
            info.processInfoLength = sizeof(ProcessInfoRec);
            err = GetProcessInformation(&psn, &info);
            if(err == noErr) {
                // some processes start with nonprintable characters. Skip those.
                int i;
                for(i = 0; i < 32; i++) {
                    if(isprint(buf[i])) break;
                }
                // avoid adding duplicates.
                QString name = QString::fromUtf8(&buf[i]);
                if(processlist.find(name) == processlist.end()) {
                    processlist.insert(name, QList<int>());
                }
                processlist[name].append(pid);
            }
        }
    } while(err == noErr);
#endif
#if defined(Q_OS_LINUX)
    // not implemented for Linux!
#endif
    //  Filter for names (unless empty)
    if(names.size() > 0) {
        for(int i = 0; i < names.size(); ++i) {
            QStringList k(processlist.keys());
#if defined(Q_OS_WIN32)
            // the process name might be truncated. Allow the extension to be partial.
            int index = k.indexOf(QRegExp(names.at(i) + "(\\.(e(x(e?)?)?)?)?",
                                          Qt::CaseInsensitive));
#else
            int index = k.indexOf(names.at(i));
#endif
            if(index != -1) {
                found.insert(k[index], processlist[k[index]]);
            }
        }
    }
    else {
        found = processlist;
    }
    LOG_INFO() << "Looking for processes" << names << "found" << found;
    return found;
}
示例#24
0
bool SimFile::readLfr(QString fileName)
{
  clearLfr();
  QVector<QString> day;
  QVector<QString> time;
  QFile file(fileName);
  if(!file.open(QFile::ReadOnly))
  {
    LOG(Error,"Failed to open LFR file '" << fileName.toStdString() << "'");
    return false;
  }
  QTextStream textStream(&file);
  QMap<int,int> nrMap;
  // Read the header
  QString header = textStream.readLine();
  if(header.isNull())
  {
    LOG(Error,"No data in LFR file '" << fileName.toStdString() << "'");
    return false;
  }
  QStringList row = header.split('\t');
  int ncols = 6;
  if(row.size() != ncols)
  {
    LOG(Error,"LFR file has " << row.size() << " columns, not the expected " << ncols);
    return false;
  }
  // Read the data
  QString line;
  while(!(line=textStream.readLine()).isNull())
  {
    QStringList row = line.split('\t');
    if(row.size() != ncols)
    {
      clearLfr();
      LOG(Error,"LFR data line has " << row.size() << " columns, not the expected " << ncols);
      return false;
    }
    if(time.size())
    {
      if(time[time.size()-1] != row[1])
      {
        day << row[0];
        time << row[1];
      }
    }
    else
    {
      day << row[0];
      time << row[1];
    }
    bool convOk;
    int nr = row[2].toInt(&convOk);
    if(!convOk)
    {
      clearLfr();
      LOG(Error,"Invalid link number '" << row[2].toStdString() << "'");
      return false;
    }
    if(!nrMap.contains(nr))
    {
      int sz = nrMap.size();
      nrMap[nr] = sz;
      m_dP.resize(sz+1);
      m_F0.resize(sz+1);
      m_F1.resize(sz+1);
    }
    double dP = row[3].toDouble(&convOk);
    if(!convOk)
    {
      clearLfr();
      LOG(Error,"Invalid pressure difference '" << row[3].toStdString() << "'");
      return false;
    }
    double F0 = row[4].toDouble(&convOk);
    if(!convOk)
    {
      clearLfr();
      LOG(Error,"Invalid flow 0 '" << row[4].toStdString() << "'");
      return false;
    }
    double F1 = row[5].toDouble(&convOk);
    if(!convOk)
    {
      clearLfr();
      LOG(Error,"Invalid flow 1 '" << row[5].toStdString() << "'");
      return false;
    }
    m_dP[nrMap[nr]].push_back(dP);
    m_F0[nrMap[nr]].push_back(F0);
    m_F1[nrMap[nr]].push_back(F1);

  }
  // Unwind the zone number map;
  QList<int> keys = nrMap.keys();
  m_pathNr.resize(keys.size());
  for(int i=0;i<keys.size();i++)
  {
    m_pathNr[nrMap[keys[i]]] = keys[i];
  }
  file.close();
  // Compute the required date/time objects - this needs to be moved elsewhere if the NCR and NFR are also read
  if(!computeDateTimes(day,time))
  {
    clearLfr();
    m_dateTimes.clear();
    LOG(Error,"Failed to compute date and time objects from LFR input");
    return false;
  }
  return true;
}
示例#25
0
bool SimFile::readNfr(QString fileName)
{
  clearNfr();
  QVector<QString> day;
  QVector<QString> time;
  QFile file(fileName);
  if(!file.open(QFile::ReadOnly))
  {
    LOG(Error,"Failed to open NFR file '" << fileName.toStdString() << "'");
    return false;
  }
  QTextStream textStream(&file);
  QMap<int,int> nrMap;
  // Read the header
  QString header = textStream.readLine();
  if(header.isNull())
  {
    LOG(Error,"No data in LFR file '" << fileName.toStdString() << "'");
    return false;
  }
  QStringList row = header.split('\t');
  int ncols = 6;
  if(row.size() != ncols && row.size() != ncols+2)
  {
    LOG(Error,"NFR file has " << row.size() << " columns, not the expected " << ncols);
    return false;
  }
  // Read the data
  QString line;
  while(!(line=textStream.readLine()).isNull())
  {
    QStringList row = line.split('\t');
    if(row.size() != ncols && row.size() != ncols+2)
    {
      clearNfr();
      LOG(Error,"NFR data line has " << row.size() << " columns, not the expected " << ncols);
      return false;
    }
    if(time.size())
    {
      if(time[time.size()-1] != row[1])
      {
        day << row[0];
        time << row[1];
      }
    }
    else
    {
      day << row[0];
      time << row[1];
    }
    bool convOk;
    int nr = row[2].toInt(&convOk);
    if(!convOk)
    {
      clearNfr();
      LOG(Error,"Invalid node number '" << row[2].toStdString() << "'");
      return false;
    }
    if(!nrMap.contains(nr))
    {
      int sz = nrMap.size();
      nrMap[nr] = sz;
      m_T.resize(sz+1);
      m_P.resize(sz+1);
      m_D.resize(sz+1);
    }
    double T = row[3].toDouble(&convOk);
    if(!convOk)
    {
      clearNfr();
      LOG(Error,"Invalid temperature '" << row[3].toStdString() << "'");
      return false;
    }
    double P = row[4].toDouble(&convOk);
    if(!convOk)
    {
      clearNfr();
      LOG(Error,"Invalid pressure '" << row[4].toStdString() << "'");
      return false;
    }
    double D = row[5].toDouble(&convOk);
    if(!convOk)
    {
      if(nr==0)
      {
        D=0.0;
      }
      else
      {
        clearNfr();
        LOG(Error,"Invalid density '" << row[5].toStdString() << "'");
        return false;
      }
    }
    m_T[nrMap[nr]].push_back(T);
    m_P[nrMap[nr]].push_back(P);
    m_D[nrMap[nr]].push_back(D);

  }
  // Unwind the zone number map;
  QList<int> keys = nrMap.keys();
  m_nodeNr.resize(keys.size());
  for(int i=0;i<keys.size();i++)
  {
    m_nodeNr[nrMap[keys[i]]] = keys[i];
  }
  file.close();
  // Something should probably be done here to make sure that the times here match up with what we
  // already have. For now, if nothing is known about the dates, then try to compute it
  if(m_dateTimes.size() == 0)
  {
    if(!computeDateTimes(day,time))
    {
      clearLfr();
      m_dateTimes.clear();
      LOG(Error,"Failed to compute date and time objects from NFR input");
      return false;
    }
  }
  return true;
}
void MarkTrainingDialog::addSubActivities() {
    QMap<QString, QString> findMap;
    findMap.insert("ID", QString::number(activityID));
    QVector<QStringList> activity = athleteDB.findActivity(findMap);

    if (activity.size() != 1) {
        QMessageBox::critical(this, "Error! Cannot find current activity!",
                              "Activities vector size is " + QString::number(activity.size()) +".");
        close();
        return;
    }

    trainingID = activity.at(0).at(1).toInt();
    activityName = activity.at(0).at(3);
    QString trainingDataStr = activity.at(0).at(4);
    QMap<QString, QString> tempMap = AthleteDB::dumpQString2QMap(trainingDataStr);
    trainingData.clear();
    timeLineLong.clear();

    for(QString key : tempMap.keys()) {
        trainingData.insert(key.toULongLong(), tempMap[key].toDouble());
        timeLineLong.append(key.toULongLong());
    }
    qSort(timeLineLong);

    findMap.clear();
    findMap.insert("training_id", QString::number(trainingID));
    QVector<QStringList> subActivities = athleteDB.findActivity(findMap);

    for (auto i(0); i < subActivities.size(); i++) {
        if (subActivities.at(i).at(0).toInt() == activityID)
            continue;
        int subActivityID = subActivities.at(i).at(0).toInt();
        QString subActivityName = subActivities.at(i).at(3);
        if (!subActivityName.endsWith("_" + activityName))
            continue;
        subActivityName.replace("_" + activityName, "");


        QString subTrainingDataStr = subActivities.at(i).at(4);
        QMap<QString, QString> tempSubMap = AthleteDB::dumpQString2QMap(subTrainingDataStr);
        unsigned long long min(-1), max(0);
        for(QString key : tempSubMap.keys()) {
            if (min < 0)
                min = key.toULongLong();
            if (max < 0)
                max = key.toULongLong();
            if (key.toULongLong() > max)
                max = key.toULongLong();
            if (key.toULongLong() < min)
                min = key.toULongLong();
        }

        addMarkSlider(subActivityID, subActivityName, timeLineLong.indexOf(min), timeLineLong.indexOf(max));

    }

    if (!slidersList.size()) {
        addMarkSlider();
    }
}
示例#27
0
void ProjectPanel::inspect(set<Firewall *> fws)
{
    if (fws.empty())
        return;

    QMessageBox messageBox(this);
    messageBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
    messageBox.addButton(tr("Compile and Inspect files"), QMessageBox::AcceptRole);
    messageBox.setIcon(QMessageBox::Critical);

    set<Firewall*> needCompile;
    foreach(Firewall *fw, fws)
        if (fw->needsCompile())
            needCompile.insert(fw);

    if (!needCompile.empty())
    {
        QString text;
        QStringList names;
        foreach(Firewall *fw, needCompile)
            names.append(fw->getName().c_str());

        if (needCompile.size() > 1 && needCompile.size() < 5)
        {
            QString last = names.last();
            names.pop_back();
            QString firewalls = "\"" + names.join("\", \"") + "\" " + tr("and") + " \"" + last + "\"";
            text = tr("Firewall objects %1 have been modified and need to be recompiled.").arg(firewalls);
        }
        else
            if (needCompile.size() == 1)
                text = tr("Firewall object \"%1\" has been modified and needs to be recompiled.").arg(names.first());
            else
            {
                text = tr("%1 firewall objects have been modified and need to be recompiled.").arg(needCompile.size());
            }

        messageBox.setText(text);
        messageBox.exec();
        if (messageBox.result() == QMessageBox::Accepted)
        {
            this->compile(needCompile);
        }
        return;
    }

    QStringList files;

    QSet<Firewall*> filesMissing;
    Firewall *first_fw = NULL;
    foreach(Firewall *fw, fws)
    {
        if (first_fw == NULL) first_fw = fw;

        /*
         * get full path to the generated file. The path is built from
         * the file name returned by
         * FirewallInstaller::getGeneratedFileName() and directory
         * path from the .fwb file. Note that we use the same
         * algorithm when GUI launches policy compiler, except there
         * the path is passed to it via "-d" command line option.
         */
        QString mainFile = FirewallInstaller::getGeneratedFileFullPath(fw);
//        QString mainFile = FirewallInstaller::getGeneratedFileName(fw);

        if (QFile::exists(mainFile))
        {
            instConf cnf;
            cnf.fwobj = fw;
            cnf.script = mainFile;
            QMap<QString, QString> res;
            FirewallInstaller(NULL, &cnf, "").readManifest(mainFile, &res);
            QStringList current_files = res.keys();
            foreach(QString file, current_files)
            {
                if (!QFile::exists(file))
                    filesMissing.insert(fw);
                else
                    files.append(file);
            }
        }
        else
            filesMissing.insert(fw);
    }
	void PendingDisco::handleLookupFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to parse"
					<< data;
			emit error (tr ("Unable to parse MusicBrainz reply."));
			deleteLater ();
		}

		QMap<QString, QMap<QString, Media::ReleaseInfo>> infos;

		auto releaseElem = doc
				.documentElement ()
				.firstChildElement ("artist")
				.firstChildElement ("release-list")
				.firstChildElement ("release");
		while (!releaseElem.isNull ())
		{
			std::shared_ptr<void> guard (nullptr,
					[&releaseElem] (void*)
						{ releaseElem = releaseElem.nextSiblingElement ("release"); });

			auto elemText = [&releaseElem] (const QString& sub)
			{
				return releaseElem.firstChildElement (sub).text ();
			};

			if (elemText ("status") != "Official")
				continue;

			const auto& dateStr = elemText ("date");
			const int dashPos = dateStr.indexOf ('-');
			const int date = (dashPos > 0 ? dateStr.left (dashPos) : dateStr).toInt ();
			if (date < 1000)
				continue;

			const auto& title = elemText ("title");
			if (!ReleaseName_.isEmpty () && title.toLower () != ReleaseName_)
				continue;

			infos [title] [elemText ("country")] =
			{
				releaseElem.attribute ("id"),
				title,
				date,
				Media::ReleaseInfo::Type::Standard,
				QList<QList<Media::ReleaseTrackInfo>> ()
			};
		}

		for (const auto& key : infos.keys ())
		{
			const auto& countries = infos [key];
			const auto& release = countries.contains ("US") ?
					countries ["US"] :
					countries.values ().first ();
			Releases_ << release;

			++PendingReleases_;

			const auto urlStr = "http://musicbrainz.org/ws/2/release/" + release.ID_ + "?inc=recordings";

			Queue_->Schedule ([this, urlStr] () -> void
				{
					auto reply = NAM_->get (QNetworkRequest (QUrl (urlStr)));
					connect (reply,
							SIGNAL (finished ()),
							this,
							SLOT (handleReleaseLookupFinished ()));
					connect (reply,
							SIGNAL (error (QNetworkReply::NetworkError)),
							this,
							SLOT (handleReleaseLookupError ()));
				}, this);
		}

		std::sort (Releases_.begin (), Releases_.end (),
				[] (decltype (Releases_.at (0)) left, decltype (Releases_.at (0)) right)
					{ return left.Year_ < right.Year_; });
	}
示例#29
0
void MainWindow::updatePropertyTable(int nodeID) {
    if(nodeID == -2)
        nodeID = Data::instance()->getFocusedID();
    QTableWidget *table = ui->tableWidget;
    if (nodeID >= 0 && Data::instance()->nodesInMesh()->contains(nodeID)) {
        deleteTable();
        oldfocus = nodeID;
        Node *n = Data::instance()->getNodeByID(nodeID);
        QMap<QString, Node::Parameter> *map = n->getParams();
        table->setRowCount(map->size() + 6);
        int i = 0;
        // create the entries all nodes have
        QTableWidgetItem *name = new QTableWidgetItem(),
                *ID = new QTableWidgetItem(),
                *type = new QTableWidgetItem(),
                *category = new QTableWidgetItem();

        // set the data
        ID->setData(0, nodeID);
        name->setData(0, n->getName());
        type->setData(0, n->getType());
        category->setData(0,n->getCategory());
        // asign to table:

        // NodeID
        table->setItem(i, 0, new QTableWidgetItem("NodeID"));
        table->setItem(i, 1, ID);
        table->item(i, 0)->setFlags(table->item(0, 0)->flags() ^
                                    (Qt::ItemIsEnabled | Qt::ItemIsSelectable));
        i++;

        // Node Class
        table->setItem(i, 0, new QTableWidgetItem("Node Class"));
        table->setItem(i, 1, type);
        table->item(i, 0)->setFlags(table->item(i, 0)->flags() ^
                                    (Qt::ItemIsEnabled | Qt::ItemIsSelectable));
        i++;

        //Node Category
        table->setItem(i, 0, new QTableWidgetItem("Node Category"));
        table->setItem(i, 1, category);
        table->item(i, 0)->setFlags(table->item(i, 0)->flags() ^
                                    (Qt::ItemIsEnabled | Qt::ItemIsSelectable));
        i++;


        // input Gates

        bool moreThanOne = n->getInputGates()->size() > 1;
        if (!n->getInputGates()->isEmpty()) {
            QString types;
            for (Gate *g : *n->getInputGates())
                for (QString s : g->getTypes()) types += s + ", ";
            types.chop(2);
            QTableWidgetItem *in = new QTableWidgetItem();
            in->setText(types);
            in->setFlags(in->flags() ^ (Qt::ItemIsEditable | Qt::ItemIsSelectable));
            table->setItem(i, 0, new QTableWidgetItem(
                               "Input" + QString((moreThanOne ? "s" : ""))));
            table->setItem(i, 1, in);
            table->item(i, 1)->setToolTip(types);
            i++;
        }

        // output gates
        moreThanOne = n->getOutputGates()->size() > 1;
        if (!n->getOutputGates()->isEmpty()) {
            QString types;
            for (Gate *g : *n->getOutputGates())
                for (QString s : g->getTypes()) types += s + ", ";
            types.chop(2);
            QTableWidgetItem *out = new QTableWidgetItem;
            out->setText(types);
            out->setFlags(out->flags() ^ (Qt::ItemIsEditable | Qt::ItemIsSelectable));
            table->setItem(i, 0, new QTableWidgetItem(
                               "Output" + QString((moreThanOne ? "s" : ""))));
            table->setItem(i, 1, out);
            table->item(i, 1)->setToolTip(types);
            i++;
        }
        table->setItem(i, 0, new QTableWidgetItem("Node Name"));
        table->setItem(i, 1, name);
        i++;

        // make name editable
        name->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable |
                       Qt::ItemIsSelectable);

        // avoid editing keys, and nodeID/type
        ID->setFlags(ID->flags() ^ (Qt::ItemIsEditable | Qt::ItemIsSelectable |
                                    Qt::ItemIsEnabled));
        type->setFlags(type->flags() ^ (Qt::ItemIsEditable | Qt::ItemIsSelectable |
                                        Qt::ItemIsEnabled));

        for (int j = 0; j < i; j++)
            table->item(j, 0)->setFlags(table->item(j, 0)->flags() ^
                                        (Qt::ItemIsEditable | Qt::ItemIsSelectable));
        QStringList keys = map->keys();
        int count = i;
        for (int j = 0; j < keys.size(); j++) {
            count++;
            // create key item
            QString key = keys.value(j);
            QTableWidgetItem *key_item = new QTableWidgetItem((*map)[key].name);
            key_item->setData(Qt::UserRole, key);
            key_item->setFlags(key_item->flags() ^
                               (Qt::ItemIsEditable | Qt::ItemIsSelectable));
            key_item->setToolTip((*map)[key].descr);
            table->setItem(i + j, 0, key_item);

            // create value item
            QVariant value = map->value(key).value;
            QTableWidgetItem *value_item = new QTableWidgetItem();
            value_item->setToolTip((*map)[key].descr);
            // QSpinBox *spinner;
            switch (value.userType()) {
            case QVariant::Bool:
                // value_item->setData(0, value);
                value_item->setCheckState(value.toBool() ? Qt::Checked
                                                         : Qt::Unchecked);
                table->setItem(i + j, 1, value_item);
                break;
            default:
                value_item->setData(Qt::UserRole, value);
                value_item->setText(value.toString());
                table->setItem(i + j, 1, value_item);
                if (key.contains("file")) {
                    connect(table, SIGNAL(cellDoubleClicked(int, int)), this,
                            SLOT(onFilebuttonClicked(int, int)));
                }
                break;
            }
        }
示例#30
0
QString PostFilter::match(const QMap<QString, Token> &tokens, QString filter, bool invert)
{
	// Invert the filter by prepending '-'
	if (filter.startsWith('-'))
	{
		filter = filter.right(filter.length() - 1);
		invert = !invert;
	}

	// Tokens
	if (filter.startsWith('%') && filter.endsWith('%'))
	{
		QString key = filter.mid(1, filter.length() - 2);
		bool cond = tokens.contains(key) && !isVariantEmpty(tokens[key].value());

		if (cond && invert)
		{ return QObject::tr("image has a \"%1\" token").arg(key); }
		else if (!cond && !invert)
		{ return QObject::tr("image does not have a \"%1\" token").arg(key); }
	}

	// Meta-tags
	else if (filter.contains(":"))
	{
		QString type = filter.section(':', 0, 0).toLower();
		filter = filter.section(':', 1).toLower();
		if (!tokens.contains(type))
		{
			QStringList keys = tokens.keys();
			return QObject::tr("unknown type \"%1\" (available types: \"%2\")").arg(type, keys.join("\", \""));
		}

		QVariant token = tokens[type].value();
		if (token.type() == QVariant::Int || token.type() == QVariant::DateTime || token.type() == QVariant::ULongLong)
		{
			int input = 0;
			if (token.type() == QVariant::Int)
			{ input = token.toInt(); }
			else if (token.type() == QVariant::DateTime)
			{ input = token.toDateTime().toString("yyyyMMdd").toInt(); }
			else if (token.type() == QVariant::ULongLong)
			{ input = token.toULongLong(); }

			bool cond;
			if (token.type() == QVariant::DateTime)
			{
				if (filter.startsWith("..") || filter.startsWith("<="))
				{ cond = input <= toDate(filter.right(filter.size()-2)); }
				else if (filter.endsWith(".."))
				{ cond = input >= toDate(filter.left(filter.size()-2)); }
				else if (filter.startsWith(">="))
				{ cond = input >= toDate(filter.right(filter.size()-2)); }
				else if (filter.startsWith("<"))
				{ cond = input < toDate(filter.right(filter.size()-1)); }
				else if (filter.startsWith(">"))
				{ cond = input > toDate(filter.right(filter.size()-1)); }
				else if (filter.contains(".."))
				{ cond = input >= toDate(filter.left(filter.indexOf(".."))) && input <= toDate(filter.right(filter.size()-filter.indexOf("..")-2));	}
				else
				{ cond = input == toDate(filter); }
			}
			else
			{
				if (filter.startsWith("..") || filter.startsWith("<="))
				{ cond = input <= filter.rightRef(filter.size()-2).toInt(); }
				else if (filter.endsWith(".."))
				{ cond = input >= filter.leftRef(filter.size()-2).toInt(); }
				else if (filter.startsWith(">="))
				{ cond = input >= filter.rightRef(filter.size()-2).toInt(); }
				else if (filter.startsWith("<"))
				{ cond = input < filter.rightRef(filter.size()-1).toInt(); }
				else if (filter.startsWith(">"))
				{ cond = input > filter.rightRef(filter.size()-1).toInt(); }
				else if (filter.contains(".."))
				{ cond = input >= filter.leftRef(filter.indexOf("..")).toInt() && input <= filter.rightRef(filter.size()-filter.indexOf("..")-2).toInt();	}
				else
				{ cond = input == filter.toInt(); }
			}

			if (!cond && !invert)
			{ return QObject::tr("image's %1 does not match").arg(type); }
			if (cond && invert)
			{ return QObject::tr("image's %1 match").arg(type); }
		}
		else
		{
			if (type == "rating")
			{
				QMap<QString, QString> assoc;
				assoc["s"] = "safe";
				assoc["q"] = "questionable";
				assoc["e"] = "explicit";

				if (assoc.contains(filter))
					filter = assoc[filter];

				bool cond = !filter.isEmpty() && token.toString().toLower().startsWith(filter.at(0));
				if (!cond && !invert)
				{ return QObject::tr("image is not \"%1\"").arg(filter); }
				if (cond && invert)
				{ return QObject::tr("image is \"%1\"").arg(filter); }
			}
			else if (type == "source")
			{
				QRegExp rx(filter + "*", Qt::CaseInsensitive, QRegExp::Wildcard);
				bool cond = rx.exactMatch(token.toString());
				if (!cond && !invert)
				{ return QObject::tr("image's source does not starts with \"%1\"").arg(filter); }
				if (cond && invert)
				{ return QObject::tr("image's source starts with \"%1\"").arg(filter); }
			}
			else
			{
				QString input = token.toString();

				bool cond = input == filter;

				if (!cond && !invert)
				{ return QObject::tr("image's %1 does not match").arg(type); }
				if (cond && invert)
				{ return QObject::tr("image's %1 match").arg(type); }
			}
		}
	}
	else if (!filter.isEmpty())
	{
		QStringList tags = tokens["allos"].value().toStringList();

		// Check if any tag match the filter (case insensitive plain text with wildcards allowed)
		bool cond = false;
		for (const QString &tag : tags)
		{
			QRegExp reg(filter.trimmed(), Qt::CaseInsensitive, QRegExp::Wildcard);
			if (reg.exactMatch(tag))
			{
				cond = true;
				break;
			}
		}

		if (!cond && !invert)
		{ return QObject::tr("image does not contains \"%1\"").arg(filter); }
		if (cond && invert)
		{ return QObject::tr("image contains \"%1\"").arg(filter); }
	}

	return QString();
}