void MainApplication::updateTrains()
{
    QDateTime currentDateTime = QDateTime::currentDateTime();

    qDebug() << "update trains: current time:" << currentDateTime;

    southboundTrainModel_->removeTrainsOlderThan(currentDateTime.time());
    northboundTrainModel_->removeTrainsOlderThan(currentDateTime.time());

    QDateTime endTime = currentDateTime.addSecs(90*60);
    QMultiMap<QTime, Caltrains::Train> currentTrains = caltrains_.getTrainsByTime(currentDateTime, endTime);

    QList<Caltrains::Train> northboundTrainsList;
    QList<Caltrains::Train> southboundTrainsList;

    QMultiMap<QTime, Caltrains::Train>::iterator i;
    for (i = currentTrains.begin(); i != currentTrains.end(); ++i)
    {
        if (i.value().direction == Caltrains::North) {
            northboundTrainsList.append(i.value());
        }
        else {
            southboundTrainsList.append(i.value());
        }
    }

    qDebug() << "update trains: south:" << southboundTrainsList;
    qDebug() << "update trains: north:" << northboundTrainsList;

    southboundTrainModel_->addCaltrains(southboundTrainsList);
    northboundTrainModel_->addCaltrains(northboundTrainsList);
}
Exemple #2
0
void parseHits(QXmlStreamReader & in, Task & task, const QString subtask)
{
    QMultiMap<int, Task::Hit> sortedHits;
    while(!in.atEnd()) {
        QXmlStreamReader::TokenType token = in.readNext();
        if (token == QXmlStreamReader::StartElement) {
            QString elementName = in.name().toString();
            if (0) {
            } else if (elementName.compare("h", Qt::CaseInsensitive) == 0){
                Task::Hit hit;
                QXmlStreamAttributes attrs = in.attributes();
                hit.timestamp = QDateTime::fromString(attrs.value("t").toString(), DATETIMEFORMAT);
                hit.duration = attrs.value("d").toString().toUInt();
                sortedHits.insertMulti(hit.timestamp.toTime_t(), hit);
            }
        } else if (token == QXmlStreamReader::EndElement && in.name().toString().compare("hits", Qt::CaseInsensitive) == 0) {
            break;
        }
    }

    // remove duplicates
    QMultiMap<int, Task::Hit>::iterator itr =  sortedHits.begin();
    Task::Hit prev;
    while(itr != sortedHits.end()) {
        if (itr.value() == prev)
            itr = sortedHits.erase(itr);
        else {
            prev = itr.value();
            itr++;
        }
    }
    task.hits[subtask] = sortedHits.values();
}
Exemple #3
0
void QgsSnapper::cleanResultList( QMultiMap<double, QgsSnappingResult>& list, const QList<QgsPoint>& excludeList ) const
{
  QgsPoint currentResultPoint;
  QgsSnappingResult currentSnappingResult;
  QList<double> keysToRemove;

  QMultiMap<double, QgsSnappingResult>::iterator result_it = list.begin();
  for ( ; result_it != list.end(); ++result_it )
  {
    currentSnappingResult = result_it.value();
    if ( currentSnappingResult.snappedVertexNr != -1 )
    {
      currentResultPoint = currentSnappingResult.snappedVertex;
      if ( excludeList.contains( currentResultPoint ) )
      {
        keysToRemove.push_back( result_it.key() );
      }
    }
  }

  QList<double>::const_iterator remove_it = keysToRemove.constBegin();
  for ( ; remove_it != keysToRemove.constEnd(); ++remove_it )
  {
    list.remove( *remove_it );
  }
}
void QgsSelectedFeature::moveSelectedVertexes( QgsVector v )
{
  int nUpdates = 0;
  Q_FOREACH ( QgsVertexEntry *entry, mVertexMap )
  {
    if ( entry->isSelected() )
      nUpdates++;
  }

  if ( nUpdates == 0 )
    return;

  mVlayer->beginEditCommand( QObject::tr( "Moved vertices" ) );
  int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );

  beginGeometryChange();

  QMultiMap<double, QgsSnappingResult> currentResultList;
  for ( int i = mVertexMap.size() - 1; i > -1 && nUpdates > 0; i-- )
  {
    QgsVertexEntry *entry = mVertexMap.value( i, nullptr );
    if ( !entry || !entry->isSelected() )
      continue;

    if ( topologicalEditing )
    {
      // snap from current vertex
      currentResultList.clear();
      mVlayer->snapWithContext( entry->pointV1(), ZERO_TOLERANCE, currentResultList, QgsSnapper::SnapToVertex );
    }

    // only last update should trigger the geometry update
    // as vertex selection gets lost on the update
    if ( --nUpdates == 0 )
      endGeometryChange();

    QgsPointV2 p = entry->point();
    p.setX( p.x() + v.x() );
    p.setY( p.y() + v.y() );
    mVlayer->moveVertex( p, mFeatureId, i );

    if ( topologicalEditing )
    {
      QMultiMap<double, QgsSnappingResult>::iterator resultIt =  currentResultList.begin();

      for ( ; resultIt != currentResultList.end(); ++resultIt )
      {
        // move all other
        if ( mFeatureId !=  resultIt.value().snappedAtGeometry )
          mVlayer->moveVertex( p, resultIt.value().snappedAtGeometry, resultIt.value().snappedVertexNr );
      }
    }
  }

  if ( nUpdates > 0 )
    endGeometryChange();

  mVlayer->endEditCommand();
}
void tst_QWebPluginDatabase::enabled()
{
    QMultiMap<QString, QWebPluginInfo> pluginsMap;
    QWebPluginDatabase* database = QWebSettings::pluginDatabase();
    QList<QWebPluginInfo> plugins = database->plugins();

    for (int i = 0; i < plugins.count(); ++i) {
        QWebPluginInfo plugin = plugins.at(i);

        QList<MimeType> mimeTypes = plugin.mimeTypes();
        for (int j = 0; j < mimeTypes.count(); ++j) {
            QString mimeType = mimeTypes.at(j).name;
            pluginsMap.insert(mimeType, plugin);
            QVERIFY(plugin.supportsMimeType(mimeType));
        }
    }

    QMultiMap<QString, QWebPluginInfo>::iterator it = pluginsMap.begin();
    while (it != pluginsMap.end()) {
        QString mimeType = it.key();
        QWebPluginInfo plugin = it.value();
        QWebPluginInfo pluginForMimeType = database->pluginForMimeType(mimeType);

        QVERIFY(pluginsMap.count(mimeType) > 0);

        if (pluginsMap.count(mimeType) == 1) {
            QCOMPARE(plugin, pluginForMimeType);

            QVERIFY(plugin.isEnabled());
            QVERIFY(pluginForMimeType.isEnabled());
            plugin.setEnabled(false);
            QVERIFY(!plugin.isEnabled());
            QVERIFY(!pluginForMimeType.isEnabled());
        } else {
            QVERIFY(plugin.isEnabled());
            QVERIFY(pluginForMimeType.isEnabled());
            plugin.setEnabled(false);
            QVERIFY(!plugin.isEnabled());
        }

        QVERIFY(!plugin.isNull());
        QVERIFY(!pluginForMimeType.isNull());

        QWebPluginInfo pluginForMimeType2 = database->pluginForMimeType(mimeType);
        if (pluginsMap.count(mimeType) == 1) {
            QVERIFY(pluginForMimeType2 != plugin);
            QVERIFY(pluginForMimeType2.isNull());
        } else {
            QVERIFY(pluginForMimeType2 != plugin);
            QVERIFY(!pluginForMimeType2.isNull());
        }

        plugin.setEnabled(true);

        ++it;
    }
}
Exemple #6
0
/**
 * Removes all but the given properties from the combined properties
 * collected so far.
 */
void RPropertyEditor::removeAllButThese(
        const QMultiMap<QString, QString>& propertyTitles, bool customOnly) {

    // iterate through all groups of properties (e.g. "Start Point", "End Point", ...):
    QStringList removableGroups;
    RPropertyGroupMap::iterator it;
    for (it = combinedProperties.begin(); it != combinedProperties.end(); ++it) {

        // iterate through all properties in the current group (e.g. "X", "Y"):
        QStringList removableProperties;
        RPropertyMap::iterator it2;
        for (it2 = it.value().begin(); it2 != it.value().end(); ++it2) {
            if (customOnly && !it2.value().second.getPropertyTypeId().isCustom()) {
                continue;
            }

            bool keep = false;

            // check if the current property is among the given properties
            // we want to keep:
            QMultiMap<QString, QString>::const_iterator it3;
            for (it3 = propertyTitles.begin(); it3 != propertyTitles.end(); ++it3) {
                if (it3.key() == it.key() && it3.value() == it2.key()) {
                    keep = true;
                    break;
                }
            }

            if (keep == false) {
                // schedule property for removal:
                removableProperties.push_back(it2.key());
            }
        }

        // remove all properties in the current group that are scheduled for removal:
        QStringList::iterator it4;
        for (it4 = removableProperties.begin(); it4
                != removableProperties.end(); ++it4) {
            it.value().remove(*it4);
            propertyOrder[it.key()].removeAll(*it4);
        }

        // schedule empty groups for removal:
        if (it.value().empty()) {
            removableGroups.push_back(it.key());
        }
    }

    // remove all groups that are scheduled for removal:
    QStringList::iterator it5;
    for (it5 = removableGroups.begin(); it5 != removableGroups.end(); ++it5) {
        combinedProperties.remove(*it5);
        groupOrder.removeAll(*it5);
    }
}
Exemple #7
0
QString SDBCache::convertMapToString(QMultiMap<uint, uint> &map){
    QStringList tmp;

    QMultiMap<uint,uint>::iterator it = map.begin();
    while(it != map.end()){
        tmp.append(QString::number(it.key()));
        tmp.append(QString::number(it.value()));
        it++;
    }
    return tmp.join(",");
}
Exemple #8
0
void Transact::updateDestination()
{
	// TODO: should be a Qt model.
	ui->destination->clear();
	ui->destination->addItem("(Create Contract)");
	QMultiMap<QString, QString> in;
	for (Address const& a: m_main->allKnownAddresses())
		in.insert(QString::fromStdString(m_main->toName(a) + " (" + ICAP(a).encoded() + ")"), QString::fromStdString(a.hex()));
	for (auto i = in.begin(); i != in.end(); ++i)
		ui->destination->addItem(i.key(), i.value());

}
bool PlanTableManager::is_excluded(const QMultiMap<QString, QString>& allowed_regions,
																		const format_reader::Record& record) const 
{
	const QString& current_code = record["CODE"];
	QString current_code_region = current_code.mid(0, 2);
	QMultiMap<QString, QString>::const_iterator it = allowed_regions.find(current_code_region);
	while (it != allowed_regions.end() && it.key() == current_code_region) {
     if (is_same_region(current_code, *it))
			 return false;
     ++it;
	}
	return true;
}
Exemple #10
0
void EntityTreeWidget::update()
{
    this->clear();
    QMultiMap<QString, QString> entityCatalogue;
    _entityModelHash = ModelsManager::getOrCreate()->getEntityModelHash();
    QStringList availableEntities = ModelsManager::getOrCreate()->getAvailableEntities().keys();

    foreach (NtgEntityModel entityModel, _entityModelHash)
    {

        if (entityModel.browsable && availableEntities.contains(entityModel.name))
        {
          entityCatalogue.insert(entityModel.category,entityModel.name);
        }
    }

    QTreeWidgetItem * categoryItem = NULL;
    EntityTreeWidgetItem * entityItem = NULL;
    QList<QTreeWidgetItem *> treeWidgetList;
    QMultiMap<QString, QString>::iterator i = entityCatalogue.begin();
    while (i != entityCatalogue.end())
    {
    QString categoryName = i.key();
    QString entityName = i.value();
    treeWidgetList = findItems(categoryName,Qt::MatchExactly,0);
    if (treeWidgetList.size() == 0)
    {
      categoryItem = new QTreeWidgetItem(this);
      categoryItem->setText(0,categoryName);
    }
    else
    {
      categoryItem = treeWidgetList.at(0);
    }
    entityItem = new EntityTreeWidgetItem(categoryItem);


    QString uuidName = entityName.toLower().simplified().replace(" ","");
    entityItem->setText(0, _entityModelHash.value(entityName).longName);
    entityItem->setText(1, entityName);
    QPixmap pixmap;
    pixmap.loadFromData(_entityModelHash.value(entityName).imagePNG,"PNG");
    entityItem->setIcon(0, QIcon(pixmap));

    ++i;
    }
    sortItems (0, Qt::AscendingOrder);
    expandAll();
}
DailyCleaning DirtiestCleaner::toClean(QDate date, const FacilityState &state)
{
  QMultiMap<double,unsigned int> loops;
  for(unsigned int loop=0;loop<state.getFacility().loopNumber;loop++)
    loops.insert(state.getCleanliness(loop),loop);

  DailyCleaning toReturn;

  unsigned int day=loopsperday, night=loopspernight;
  for(auto loop=loops.begin();loop!=loops.end();loop++){
    if(day){toReturn.dayTruck.append(loop.value()); day--;}
    else if(night){toReturn.nightTruck.append(loop.value()); night--;}
    else break;
  }
  return toReturn;
}
CreateIndexDialog::CreateIndexDialog(DBBrowserDB* db, QWidget* parent)
    : QDialog(parent),
      pdb(db),
      ui(new Ui::CreateIndexDialog)
{
    // Create UI
    ui->setupUi(this);

    // Get list of tables, sort it alphabetically and fill the combobox
    QMultiMap<QString, DBBrowserObject> dbobjs;
    QList<DBBrowserObject> tables = pdb->objMap.values("table");
    for(QList<DBBrowserObject>::ConstIterator it=tables.begin();it!=tables.end();++it)
        dbobjs.insert((*it).getname(), (*it));
    for(QMultiMap<QString, DBBrowserObject>::ConstIterator it=dbobjs.begin(); it != dbobjs.end(); ++it)
        ui->comboTableName->addItem(QIcon(QString(":icons/table")), (*it).getname());
}
bool AbstractRuleBinder::parseRuleReferences(QString& strRule)
{
    QMultiMap<size_t, QMap<size_t,size_t> > mapLookups;
    if (!ruleCheckerPtr->parseRule(strRule,mapLookups)) return false;
    if (mapLookups.size()>0){

        QMultiMap<size_t,  QMap<size_t,size_t> >::iterator j = mapLookups.begin();
         while (j != mapLookups.end()) {

             QString strResult;

             size_t field=j.value().begin().value();
             size_t mapper=j.value().begin().key();

             QVariant var=getVal(field,mapper);
             if (var.type()==QVariant::Invalid) return false;
             if (var.type()==QVariant::String) strResult=tr("'") + var.toString() + tr("'");
             else strResult=var.toString();

             QString searchStr=StrRulePtr + tr("(") + QVariant(j.key()).toString() + tr(")");
             strRule=strRule.replace(searchStr,
                 strResult);

             ++j;
         }

    }

    //search for references to the current sample
    QMap<QString, QString> mapSample;
    if (!parseSample(strRule,mapSample)) return false;

    QMap<QString, QString>::iterator j = mapSample.begin();
     while (j != mapSample.end()) {

             QString searchStr=StrRuleSample + tr("(") + QVariant(j.key()).toString() + tr(")");
             strRule=strRule.replace(searchStr,
                 j.value());

             //qDebug() << strRule << endl;

         ++j;
     }

    return true;
}
Exemple #14
0
QString XmppUriQueries::makeXmppUri(const Jid &AContactJid, const QString &AAction, const QMultiMap<QString, QString> &AParams) const
{
	if (AContactJid.isValid() && !AAction.isEmpty())
	{
		QUrl url;
		url.setQueryDelimiters('=',';');

		url.setScheme(XMPP_URI_SCHEME);
		url.setPath(AContactJid.full());

		QList< QPair<QString, QString> > query;
		query.append(qMakePair<QString,QString>(AAction,QString::null));
		for(QMultiMap<QString, QString>::const_iterator it=AParams.constBegin(); it!=AParams.end(); ++it)
			query.append(qMakePair<QString,QString>(it.key(),it.value()));
		url.setQueryItems(query);

		return url.toString().replace(QString("?%1=;").arg(AAction),QString("?%1;").arg(AAction));
	}
	return QString::null;
}
Exemple #15
0
int main()
{
    QSet<QString *> s;
    qDeleteAll(s);
    qDeleteAll(s.begin(), s.end());
    qDeleteAll(s.values()); // warning

    QHash<int, QString *> h;
    qDeleteAll(h);
    qDeleteAll(h.begin(), h.end());
    qDeleteAll(h.values()); // warning

    QMap<int*, QString *> m;
    qDeleteAll(m);
    qDeleteAll(m.begin(), m.end());
    qDeleteAll(m.values()); // warning

    QMultiHash<int, QString *> mh;
    qDeleteAll(mh);
    qDeleteAll(mh.begin(), mh.end());
    qDeleteAll(mh.values()); // warning

    QMultiMap<int, QString *> mm;
    qDeleteAll(mm);
    qDeleteAll(mm.begin(), mm.end());
    qDeleteAll(mm.values()); // warning

    qDeleteAll(values());  // ok

    Foo foo;
    qDeleteAll(foo.values());  // ok
    qDeleteAll(foo.doSomethingWithValues(h.values()));  // ok

    qDeleteAll(m.keys()); // warning
    qDeleteAll(keys()); // ok

    qDeleteAll(h.values(1)); // warning

}
QMultiMap<QString, QPair<FoodCollection::ContainedTypes::ContainedType, int> >
  FoodCollection::getFoodsForUser(int userId)
{
  QMultiMap<QString, QPair<BackEnd::FoodTypes::FoodType, int> > foodNames;
  QMultiMap<QString, QPair<ContainedTypes::ContainedType, int> > rv_foodNames;

  foodNames = BackEnd::getBackEnd()->loadFoodNamesForUser(userId, true);

  for (QMultiMap<QString, QPair<BackEnd::FoodTypes::FoodType, int> >::const_iterator i =
       foodNames.begin(); i != foodNames.end(); ++i)
  {
    // TODO: Get rid of ContainedType entirely in favor of BackEnd::FoodTypes

    ContainedTypes::ContainedType ctype =
      ContainedTypes::fromHumanReadable
        (BackEnd::FoodTypes::toContainedType(i.value().first));

    rv_foodNames.insert(i.key(), qMakePair(ctype, i.value().second));
  }

  return rv_foodNames;
}
Exemple #17
0
void Level1::updateFile()
{
    QFile file("/Users/alireza/Documents/QT/chickenInvaders-local5/records.txt");
    QMultiMap<int,QString> recs;
    QTextStream in(&file);
    QString line;
    QStringList list;

    if(file.open(QFile::Text | QFile::ReadOnly))
    {
        qDebug() << "ENTERED";
        while(!in.atEnd())
        {
            line = in.readLine();
            list = line.split(" ");
            recs.insert(list.at(1).toInt(),list.at(0));
        }
        recs.insert(game->lvl->sc->getScore(),game->player);
    }

    file.close();
    //qDebug()<<recs.keys();
    //qDebug()<<recs.values();
    QTextStream out(&file);
    QMultiMap<int,QString>::iterator it = --(recs.end());

    if(file.open(QFile::Text | QFile::WriteOnly|QFile::Truncate))
    {

        while(it != --(recs.begin()))
        {
            out << it.value()<<" "<<it.key()<<endl;
            --it;
        }
    }
    file.close();
    game->lvl->timer3->stop();
}
QMultiMap<QString, QPair<FoodCollection::ContainedTypes::ContainedType, int> >
  FoodCollection::getFoodsForUser(int userId, ContainedTypes::ContainedType type)
{
  QMultiMap<QString, QPair<FoodCollection::ContainedTypes::ContainedType, int> > foods;
  QMultiMap<QString, int> rawFoods;

  if (type == ContainedTypes::SingleFood) {
    rawFoods = SingleFood::getFoodsForUser(userId);
  } else if (type == ContainedTypes::CompositeFood) {
    rawFoods = CompositeFood::getFoodsForUser(userId);
  } else if (type == ContainedTypes::Template) {
    rawFoods = Template::getFoodsForUser(userId);
  }

  for (QMultiMap<QString, int>::const_iterator i = rawFoods.begin();
       i != rawFoods.end(); ++i)
  {
    foods.insert(i.key(), QPair<ContainedTypes::ContainedType, int>
      (type, i.value()));
  }

  return foods;
}
CreateIndexDialog::CreateIndexDialog(DBBrowserDB* db, QWidget* parent)
    : QDialog(parent),
      pdb(db),
      ui(new Ui::CreateIndexDialog)
{
    // Create UI
    ui->setupUi(this);

    // Get list of tables, sort it alphabetically and fill the combobox
    QMultiMap<QString, DBBrowserObject> dbobjs;
    QList<DBBrowserObject> tables = pdb->objMap.values("table");
    for(QList<DBBrowserObject>::ConstIterator it=tables.begin();it!=tables.end();++it)
        dbobjs.insert((*it).getname(), (*it));
    for(QMultiMap<QString, DBBrowserObject>::ConstIterator it=dbobjs.begin(); it != dbobjs.end(); ++it)
        ui->comboTableName->addItem(QIcon(QString(":icons/table")), (*it).getname());

    QHeaderView *tableHeaderView = ui->tableIndexColumns->horizontalHeader();

#if QT_VERSION < 0x050000
    tableHeaderView->setResizeMode(0, QHeaderView::Stretch);
#else
    tableHeaderView->setSectionResizeMode(0, QHeaderView::Stretch);
#endif
}
void QgsMapToolNodeTool::createTopologyRubberBands( QgsVectorLayer* vlayer, const QList<QgsVertexEntry*> &vertexMap, int vertex )
{
  QMultiMap<double, QgsSnappingResult> currentResultList;
  QgsGeometry *geometry = mSelectedFeature->geometry();

  // snap from current vertex
  currentResultList.clear();
  vlayer->snapWithContext( vertexMap[vertex]->point(), ZERO_TOLERANCE, currentResultList, QgsSnapper::SnapToVertex );
  QMultiMap<double, QgsSnappingResult>::iterator resultIt =  currentResultList.begin();

  for ( ; resultIt != currentResultList.end(); ++resultIt )
  {
    // move all other
    if ( mSelectedFeature->featureId() != resultIt.value().snappedAtGeometry )
    {
      if ( mTopologyMovingVertexes.contains( resultIt.value().snappedAtGeometry ) )
      {
        if ( mTopologyMovingVertexes[resultIt.value().snappedAtGeometry]->contains( resultIt.value().snappedVertexNr ) )
        {
          // skip vertex already exists in some rubberband
          continue;
        }
      }
      QgsRubberBand* trb = new QgsRubberBand( mCanvas, QGis::Line );
      mTopologyRubberBand.append( trb );
      int rbId = mTopologyRubberBand.size() - 1;
      trb->setWidth( 1 );
      trb->setColor( Qt::red );

      int tVertex = resultIt.value().snappedVertexNr;
      int tVertexBackup = -1, tVertexAfter = -1;
      int tVertexFirst = tVertex; // vertex number to check for cycling
      QgsFeature topolFeature;

      vlayer->getFeatures( QgsFeatureRequest().setFilterFid( resultIt.value().snappedAtGeometry ).setSubsetOfAttributes( QgsAttributeList() ) ).nextFeature( topolFeature );
      QgsGeometry* topolGeometry = topolFeature.geometry();

      while ( tVertex != -1 ) // looking for first vertex to rubberband
      {
        tVertexBackup = tVertex;
        topolGeometry->adjacentVertices( tVertex, tVertex, tVertexAfter );
        if ( tVertex == -1 || tVertex == tVertexFirst )
          break; // check if this is not first vertex of the feature or cycling error
        // if closest vertex is not from selected feature or is not selected end
        double dist;
        QgsPoint point = topolGeometry->vertexAt( tVertex );
        int at, before, after;
        geometry->closestVertex( point, at, before, after, dist );
        if ( dist > ZERO_TOLERANCE || !vertexMap[at]->isSelected() ) // problem with double precision
        {
          break; // found first vertex
        }
      }

      int movingPointIndex = 0;
      Vertexes* movingPoints = new Vertexes();
      Vertexes* addedPoints = new Vertexes();
      if ( mTopologyMovingVertexes.contains( resultIt.value().snappedAtGeometry ) )
      {
        addedPoints = mTopologyMovingVertexes[ resultIt.value().snappedAtGeometry ];
      }
      if ( tVertex == -1 ) // adding first point if needed
      {
        tVertex = tVertexBackup;
      }
      else
      {
        trb->addPoint( toMapCoordinates( vlayer, topolGeometry->vertexAt( tVertex ) ) );
        if ( tVertex == tVertexFirst ) // cycle first vertex need to be added also
        {
          movingPoints->insert( movingPointIndex );
        }
        movingPointIndex = 1;
        topolGeometry->adjacentVertices( tVertex, tVertexAfter, tVertex );
      }

      while ( tVertex != -1 )
      {
        // if closest vertex is not from selected feature or is not selected end
        double dist;
        QgsPoint point = topolGeometry->vertexAt( tVertex );
        int at, before, after;
        geometry->closestVertex( point, at, before, after, dist );
        // find first no matching vertex
        if ( dist > ZERO_TOLERANCE || !vertexMap[at]->isSelected() ) // problem with double precision
        {
          trb->addPoint( toMapCoordinates( vlayer, topolGeometry->vertexAt( tVertex ) ) );
          break; // found first vertex
        }
        else // add moving point to rubberband
        {
          if ( addedPoints->contains( tVertex ) )
            break; // just preventing to circle
          trb->addPoint( toMapCoordinates( vlayer, topolGeometry->vertexAt( tVertex ) ) );
          movingPoints->insert( movingPointIndex );
          movingPointIndex++;
          addedPoints->insert( tVertex );
        }
        topolGeometry->adjacentVertices( tVertex, tVertexAfter, tVertex );
      }
      mTopologyMovingVertexes.insert( resultIt.value().snappedAtGeometry, addedPoints );
      mTopologyRubberBandVertexes.insert( rbId, movingPoints );
    }
  }
}
void multipleCheckDialog::writeToGui()
{

    QMultiMap<QString,contactWidgetFastBook*> fastList;
    QString filter = ui->lineEdit->text();

    for (libJackSMS::dataTypes::phoneBookType::const_iterator i = rubrica.begin(); i != rubrica.end(); ++i) {

        //Controllo che non sia già presente nella lista destinatari
        if (!padre->isInRecipients(i.value().getPhone()))
        {
            if (i->getName().contains(filter, Qt::CaseInsensitive))
            {
                QIcon ico;
                libJackSMS::dataTypes::configuredServicesType::const_iterator x = elencoServiziConfigurati.find(i->getAccount());

                if (x == elencoServiziConfigurati.end())
                {
                    ico = QIcon(":/resource/ico_contact.png");
                }
                else
                {
                    QString serv = x.value().getService();
                    libJackSMS::dataTypes::servicesType::const_iterator tmp = elencoServizi.find(serv);
                    ico = tmp->getIcon();
                }

                contactWidgetFastBook *ww = new contactWidgetFastBook(i.value(), ico.pixmap(16,16), true);
                fastList.insert(i->getName().toUpper(), ww);
            }
        }
    }

    if (fastList.size() > 0)
    {
        for (QMultiMap<QString,contactWidgetFastBook*>::ConstIterator xx = fastList.begin(); xx != fastList.end(); ++xx)
        {
           QListWidgetItem *item = new QListWidgetItem;
           item->setSizeHint(xx.value()->size());
           ui->listWidget->addItem(item);
           ui->listWidget->setItemWidget(item, xx.value());
        }
    }
}
void TagModificationHelper::slotMultipleTagDel(QList<TAlbum* >& tags)
{
    QString tagWithChildrens;
    QString tagWithImages;
    QMultiMap<int, TAlbum*> sortedTags;

    foreach(TAlbum* const t, tags)
    {

        if (!t || t->isRoot())
        {
            continue;
        }

        AlbumPointer<TAlbum> tag(t);

        // find number of subtags
        int children = 0;
        AlbumIterator iter(tag);

        while (iter.current())
        {
            ++children;
            ++iter;
        }

        if(children)
            tagWithChildrens.append(tag->title() + QString(" "));

        QList<qlonglong> assignedItems = DatabaseAccess().db()->getItemIDsInTag(tag->id());

        if(!assignedItems.isEmpty())
            tagWithImages.append(tag->title() + QString(" "));

        /**
         * Tags must be deleted from children to parents, if we don't want
         * to step on invalid index. Use QMultiMap to order them by distance
         * to root tag
         */

        Album* parent = t;
        int depth = 0;

        while(!parent->isRoot())
        {
            parent = parent->parent();
            depth++;
        }

        sortedTags.insert(depth,tag);

    }

    // ask for deletion of children

    if (!tagWithChildrens.isEmpty())
    {
        int result = KMessageBox::warningContinueCancel(0,
                                                        i18n("Tags '%1' have one or more subtags. "
                                                             "Deleting them will also delete "
                                                             "the subtags. "
                                                             "Do you want to continue?",
                                                             tagWithChildrens));

        if (result != KMessageBox::Continue)
        {
            return;
        }
    }

    QString message;

    if (!tagWithImages.isEmpty())
    {
        message = i18n("Tags '%1' are assigned to one or more items. "
                        "Do you want to continue?",
                        tagWithImages);
    }
    else
    {
        message = i18n("Delete '%1' tag(s)?", tagWithImages);
    }

    int result = KMessageBox::warningContinueCancel(0, message,
                                                    i18n("Delete Tag"),
                                                    KGuiItem(i18n("Delete"),
                                                            "edit-delete"));

    if (result == KMessageBox::Continue)
    {
        QMultiMap<int, TAlbum*>::iterator it;
        /**
         * QMultimap doesn't provide reverse iterator, -1 is required
         * because end() points after the last element
         */
        for(it = sortedTags.end()-1; it != sortedTags.begin()-1; --it)
        {
            emit aboutToDeleteTag(it.value());
            QString errMsg;

            if (!AlbumManager::instance()->deleteTAlbum(it.value(), errMsg))
            {
                KMessageBox::error(0, errMsg);
            }
        }
    }
}
void DbStructureModel::reloadData(DBBrowserDB* db)
{
    // Save pointer to DB object
    m_db = db;

    beginResetModel();

    // Remove all data except for the root item
    while(rootItem->childCount())
    {
        delete rootItem->child(0);
        rootItem->removeChild(rootItem->child(0));
    }

    // Return here if no DB is opened
    if(!db->isOpen())
    {
        endResetModel();
        return;
    }

    // Create the nodes for tables, indices, views and triggers
    QMap<QString, QTreeWidgetItem*> typeToParentItem;
    QTreeWidgetItem* itemTables = new QTreeWidgetItem(rootItem);
    itemTables->setIcon(0, QIcon(QString(":/icons/table")));
    itemTables->setText(0, tr("Tables (%1)").arg(db->objMap.values("table").count()));
    typeToParentItem.insert("table", itemTables);
    QTreeWidgetItem* itemIndices = new QTreeWidgetItem(rootItem);
    itemIndices->setIcon(0, QIcon(QString(":/icons/index")));
    itemIndices->setText(0, tr("Indices (%1)").arg(db->objMap.values("index").count()));
    typeToParentItem.insert("index", itemIndices);
    QTreeWidgetItem* itemViews = new QTreeWidgetItem(rootItem);
    itemViews->setIcon(0, QIcon(QString(":/icons/view")));
    itemViews->setText(0, tr("Views (%1)").arg(db->objMap.values("view").count()));
    typeToParentItem.insert("view", itemViews);
    QTreeWidgetItem* itemTriggers = new QTreeWidgetItem(rootItem);
    itemTriggers->setIcon(0, QIcon(QString(":/icons/trigger")));
    itemTriggers->setText(0, tr("Triggers (%1)").arg(db->objMap.values("trigger").count()));
    typeToParentItem.insert("trigger", itemTriggers);

    // Get all database objects and sort them by their name
    QMultiMap<QString, DBBrowserObject> dbobjs;
    for(objectMap::ConstIterator it=db->objMap.begin(); it != db->objMap.end(); ++it)
        dbobjs.insert((*it).getname(), (*it));

    // Add the actual table objects
    for(QMultiMap<QString, DBBrowserObject>::ConstIterator it=dbobjs.begin(); it != dbobjs.end(); ++it)
    {
        // Object node
        QTreeWidgetItem *tableItem = new QTreeWidgetItem(typeToParentItem.value((*it).gettype()));
        tableItem->setIcon(0, QIcon(QString(":/icons/%1").arg((*it).gettype())));
        tableItem->setText(0, (*it).getname());
        tableItem->setText(1, (*it).gettype());
        tableItem->setText(3, (*it).getsql());

        // If it is a table or view add the field Nodes
        if((*it).gettype() == "table" || (*it).gettype() == "view")
        {
            for(int i=0; i < it->fldmap.size(); ++i)
            {
                QTreeWidgetItem *fldItem = new QTreeWidgetItem(tableItem);
                fldItem->setText(0, (*it).fldmap.at(i)->name());
                fldItem->setText(1, "field");
                fldItem->setText(2, (*it).fldmap.at(i)->type());
                fldItem->setIcon(0, QIcon(":/icons/field"));
            }
        }
    }

    // Refresh the view
    endResetModel();
}
Exemple #24
0
int QgsSnapper::snapMapPoint( const QgsPoint& mapCoordPoint, QList<QgsSnappingResult>& snappingResult, const QList<QgsPoint>& excludePoints )
{
  snappingResult.clear();

  QMultiMap<double, QgsSnappingResult> snappingResultList;//all snapping results
  QMultiMap<double, QgsSnappingResult> currentResultList; //snapping results of examined layer

  //start point in (output) map coordinates

  QgsPoint layerCoordPoint; //start point in layer coordinates
  QgsSnappingResult newResult;

  QList<QgsSnapper::SnapLayer>::iterator snapLayerIt;
  for ( snapLayerIt = mSnapLayers.begin(); snapLayerIt != mSnapLayers.end(); ++snapLayerIt )
  {
    if ( !snapLayerIt->mLayer->hasGeometryType() )
      continue;

    currentResultList.clear();
    //transform point from map coordinates to layer coordinates
    layerCoordPoint = mMapSettings.mapToLayerCoordinates( snapLayerIt->mLayer, mapCoordPoint );

    double tolerance = QgsTolerance::toleranceInMapUnits( snapLayerIt->mTolerance, snapLayerIt->mLayer, mMapSettings, snapLayerIt->mUnitType );
    if ( snapLayerIt->mLayer->snapWithContext( layerCoordPoint, tolerance,
         currentResultList, snapLayerIt->mSnapTo ) != 0 )
    {
      //error
    }

    //transform each result from layer crs to map crs (including distance)
    QMultiMap<double, QgsSnappingResult>::iterator currentResultIt;
    for ( currentResultIt = currentResultList.begin(); currentResultIt != currentResultList.end(); ++currentResultIt )
    {
      //for each snapping result: transform start point, snap point and other points into map coordinates to find out distance
      //store results in snapping result list
      newResult = currentResultIt.value();
      newResult.snappedVertex = mMapSettings.layerToMapCoordinates( snapLayerIt->mLayer, currentResultIt.value().snappedVertex );
      newResult.beforeVertex = mMapSettings.layerToMapCoordinates( snapLayerIt->mLayer, currentResultIt.value().beforeVertex );
      newResult.afterVertex = mMapSettings.layerToMapCoordinates( snapLayerIt->mLayer, currentResultIt.value().afterVertex );
      snappingResultList.insert( sqrt( newResult.snappedVertex.sqrDist( mapCoordPoint ) ), newResult );
    }
  }

  //excluded specific points from result
  cleanResultList( snappingResultList, excludePoints );

  //evaluate results according to snap mode
  QMultiMap<double, QgsSnappingResult>::iterator evalIt =  snappingResultList.begin();
  if ( evalIt == snappingResultList.end() )
  {
    return 0;
  }


  //Gives a priority to vertex snapping over segment snapping
  QgsSnappingResult returnResult = evalIt.value();
  for ( evalIt = snappingResultList.begin(); evalIt != snappingResultList.end(); ++evalIt )
  {
    if ( evalIt.value().snappedVertexNr != -1 )
    {
      returnResult = evalIt.value();
      snappingResultList.erase( evalIt );
      break;
    }
  }

  //We return the preferred result
  snappingResult.push_back( returnResult );

  if ( mSnapMode == QgsSnapper::SnapWithOneResult )
  {
    //return only a single  result, nothing more to do
  }
  else if ( mSnapMode == QgsSnapper::SnapWithResultsForSamePosition )
  {
    //take all snapping results within a certain tolerance because rounding differences may occur
    double tolerance = 0.000001;

    for ( evalIt = snappingResultList.begin(); evalIt != snappingResultList.end(); ++evalIt )
    {
      if ( returnResult.snappedVertex.sqrDist( evalIt.value().snappedVertex ) < tolerance*tolerance )
      {
        snappingResult.push_back( evalIt.value() );
      }
    }

  }

  else //take all results
  {
    for ( evalIt = snappingResultList.begin(); evalIt != snappingResultList.end(); ++evalIt )
    {
      snappingResult.push_back( evalIt.value() );
    }
  }

  return 0;
}
Exemple #25
0
// virtual
void SkeletonRagdoll::buildConstraints() {
    QVector<JointState>& jointStates = _model->getJointStates();

    // NOTE: the length of DistanceConstraints is computed and locked in at this time
    // so make sure the ragdoll positions are in a normal configuration before here.
    const int numPoints = _points.size();
    assert(numPoints == jointStates.size());

    float minBone = FLT_MAX;
    float maxBone = -FLT_MAX;
    QMultiMap<int, int> families;
    for (int i = _rootIndex; i < numPoints; ++i) {
        const JointState& state = jointStates.at(i);
        int parentIndex = state.getParentIndex();
        if (parentIndex != -1) {
            DistanceConstraint* bone = new DistanceConstraint(&(_points[i]), &(_points[parentIndex]));
            bone->setDistance(state.getDistanceToParent());
            _boneConstraints.push_back(bone);
            families.insert(parentIndex, i);
        }
        float boneLength = glm::length(state.getPositionInParentFrame());
        if (boneLength > maxBone) {
            maxBone = boneLength;
        } else if (boneLength < minBone) {
            minBone = boneLength;
        }
    }
    // Joints that have multiple children effectively have rigid constraints between the children
    // in the parent frame, so we add DistanceConstraints between children in the same family.
    QMultiMap<int, int>::iterator itr = families.begin();
    while (itr != families.end()) {
        QList<int> children = families.values(itr.key());
        int numChildren = children.size();
        if (numChildren > 1) {
            for (int i = 1; i < numChildren; ++i) {
                DistanceConstraint* bone = new DistanceConstraint(&(_points[children[i-1]]), &(_points[children[i]]));
                _boneConstraints.push_back(bone);
            }
            if (numChildren > 2) {
                DistanceConstraint* bone = new DistanceConstraint(&(_points[children[numChildren-1]]), &(_points[children[0]]));
                _boneConstraints.push_back(bone);
            }
        }
        ++itr;
    }

    float MAX_STRENGTH = 0.6f;
    float MIN_STRENGTH = 0.05f;
    // each joint gets a MuscleConstraint to its parent
    for (int i = _rootIndex + 1; i < numPoints; ++i) {
        const JointState& state = jointStates.at(i);
        int p = state.getParentIndex();
        if (p == -1) {
            continue;
        }
        MuscleConstraint* constraint = new MuscleConstraint(&(_points[p]), &(_points[i]));
        _muscleConstraints.push_back(constraint);

        // Short joints are more susceptible to wiggle so we modulate the strength based on the joint's length: 
        // long = weak and short = strong.
        constraint->setIndices(p, i);
        float boneLength = glm::length(state.getPositionInParentFrame());

        float strength = MIN_STRENGTH + (MAX_STRENGTH - MIN_STRENGTH) * (maxBone - boneLength) / (maxBone - minBone);
        if (!families.contains(i)) {
            // Although muscles only pull on the children not parents, nevertheless those joints that have
            // parents AND children are more stable than joints at the end such as fingers.  For such joints we
            // bestow maximum strength which helps reduce wiggle.
            strength = MAX_MUSCLE_STRENGTH;
        }
        constraint->setStrength(strength);
    }
}
void QgsSelectedFeature::deleteSelectedVertexes()
{
  int nSelected = 0;
  foreach ( QgsVertexEntry *entry, mVertexMap )
  {
    if ( entry->isSelected() )
      nSelected++;
  }

  if ( nSelected == 0 )
    return;

  int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );
  QMultiMap<double, QgsSnappingResult> currentResultList;

  mVlayer->beginEditCommand( QObject::tr( "Deleted vertices" ) );

  beginGeometryChange();

  int count = 0;
  for ( int i = mVertexMap.size() - 1; i > -1; i-- )
  {
    if ( mVertexMap[i]->isSelected() )
    {
      if ( mVertexMap[i]->equals() != -1 )
      {
        // to avoid try to delete some vertex twice
        mVertexMap[ mVertexMap[i]->equals()]->setSelected( false );
        nSelected--;
      }

      if ( topologicalEditing )
      {
        // snap from current vertex
        currentResultList.clear();
        mVlayer->snapWithContext( mVertexMap[i]->point(), ZERO_TOLERANCE, currentResultList, QgsSnapper::SnapToVertex );
      }

      // only last update should trigger the geometry update
      // as vertex selection gets lost on the update
      if ( --nSelected == 0 )
        endGeometryChange();

      if ( !mVlayer->deleteVertex( mFeatureId, i ) )
      {
        count = 0;
        QgsDebugMsg( QString( "Deleting vertex %1 failed - resetting" ).arg( i ) );
        break;
      }

      count++;

      if ( topologicalEditing )
      {
        QMultiMap<double, QgsSnappingResult>::iterator resultIt =  currentResultList.begin();

        for ( ; resultIt != currentResultList.end(); ++resultIt )
        {
          // move all other
          if ( mFeatureId !=  resultIt.value().snappedAtGeometry )
            mVlayer->deleteVertex( resultIt.value().snappedAtGeometry, resultIt.value().snappedVertexNr );
        }
      }
    }
  }

  if ( count > 0 )
  {
    mVlayer->endEditCommand();
  }
  else
  {
    mVlayer->destroyEditCommand();
  }
}
void DbStructureModel::reloadData()
{
    beginResetModel();

    // Remove all data except for the root item
    while(rootItem->childCount())
    {
        delete rootItem->child(0);
        rootItem->removeChild(rootItem->child(0));
    }

    // Return here if no DB is opened
    if(!m_db.isOpen())
    {
        endResetModel();
        return;
    }

    // Create the nodes for browsables and for tables, indices, views and triggers. The idea here is to basically have two trees in one model:
    // In the root node there are two nodes: 'browsables' and 'all'. The first node contains a list of a all browsable objects, i.e. views and tables.
    // The seconds node contains four sub-nodes (tables, indices, views and triggers), each containing a list of objects of that type.
    // This way we only have to have and only have to update one model and can use it in all sorts of places, just by setting a different root node.
    QMap<QString, QTreeWidgetItem*> typeToParentItem;

    QTreeWidgetItem* itemBrowsables = new QTreeWidgetItem(rootItem);
    itemBrowsables->setIcon(0, QIcon(QString(":/icons/view")));
    itemBrowsables->setText(0, tr("Browsables (%1)").arg(m_db.objMap.values("table").count() + m_db.objMap.values("view").count()));
    typeToParentItem.insert("browsable", itemBrowsables);

    QTreeWidgetItem* itemAll = new QTreeWidgetItem(rootItem);
    itemAll->setIcon(0, QIcon(QString(":/icons/view")));
    itemAll->setText(0, tr("All"));

    QTreeWidgetItem* itemTables = new QTreeWidgetItem(itemAll);
    itemTables->setIcon(0, QIcon(QString(":/icons/table")));
    itemTables->setText(0, tr("Tables (%1)").arg(m_db.objMap.values("table").count()));
    typeToParentItem.insert("table", itemTables);

    QTreeWidgetItem* itemIndices = new QTreeWidgetItem(itemAll);
    itemIndices->setIcon(0, QIcon(QString(":/icons/index")));
    itemIndices->setText(0, tr("Indices (%1)").arg(m_db.objMap.values("index").count()));
    typeToParentItem.insert("index", itemIndices);

    QTreeWidgetItem* itemViews = new QTreeWidgetItem(itemAll);
    itemViews->setIcon(0, QIcon(QString(":/icons/view")));
    itemViews->setText(0, tr("Views (%1)").arg(m_db.objMap.values("view").count()));
    typeToParentItem.insert("view", itemViews);

    QTreeWidgetItem* itemTriggers = new QTreeWidgetItem(itemAll);
    itemTriggers->setIcon(0, QIcon(QString(":/icons/trigger")));
    itemTriggers->setText(0, tr("Triggers (%1)").arg(m_db.objMap.values("trigger").count()));
    typeToParentItem.insert("trigger", itemTriggers);

    // Get all database objects and sort them by their name
    QMultiMap<QString, DBBrowserObject> dbobjs;
    for(objectMap::ConstIterator it=m_db.objMap.begin(); it != m_db.objMap.end(); ++it)
        dbobjs.insert((*it).getname(), (*it));

    // Add the actual table objects
    for(QMultiMap<QString, DBBrowserObject>::ConstIterator it=dbobjs.begin(); it != dbobjs.end(); ++it)
    {
        // Object node
        QTreeWidgetItem* item = addNode(typeToParentItem.value((*it).gettype()), *it);

        // If it is a table or view add the field nodes
        if((*it).gettype() == "table" || (*it).gettype() == "view")
        {
            // Add extra node for browsable section
            addNode(typeToParentItem.value("browsable"), *it);

            // Add field nodes
            for(int i=0; i < (*it).table.fields().size(); ++i)
            {
                QTreeWidgetItem *fldItem = new QTreeWidgetItem(item);
                fldItem->setText(0, (*it).table.fields().at(i)->name());
                fldItem->setText(1, "field");
                fldItem->setText(2, (*it).table.fields().at(i)->type());
                fldItem->setText(3, (*it).table.fields().at(i)->toString("  ", " "));
                if((*it).table.fields().at(i)->primaryKey())
                    fldItem->setIcon(0, QIcon(":/icons/field_key"));
                else
                    fldItem->setIcon(0, QIcon(":/icons/field"));
            }
        }
    }

    // Refresh the view
    endResetModel();
}
void QgsSelectedFeature::deleteSelectedVertexes()
{
  int nSelected = 0;
  Q_FOREACH ( QgsVertexEntry *entry, mVertexMap )
  {
    if ( entry->isSelected() )
      nSelected++;
  }

  if ( nSelected == 0 )
    return;

  int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );
  QMultiMap<double, QgsSnappingResult> currentResultList;

  mVlayer->beginEditCommand( QObject::tr( "Deleted vertices" ) );

  beginGeometryChange();

  bool success = false;
  QgsVectorLayer::EditResult res = QgsVectorLayer::Success;
  for ( int i = mVertexMap.size() - 1; i > -1 && nSelected > 0; i-- )
  {
    if ( mVertexMap.at( i )->isSelected() )
    {
      if ( topologicalEditing )
      {
        // snap from current vertex
        currentResultList.clear();
        mVlayer->snapWithContext( mVertexMap.at( i )->pointV1(), ZERO_TOLERANCE, currentResultList, QgsSnapper::SnapToVertex );
      }

      // only last update should trigger the geometry update
      // as vertex selection gets lost on the update
      if ( --nSelected == 0 )
        endGeometryChange();

      if ( res != QgsVectorLayer::EmptyGeometry )
        res = mVlayer->deleteVertexV2( mFeatureId, i );

      if ( res != QgsVectorLayer::Success && res != QgsVectorLayer::EmptyGeometry )
      {
        success = false;
        QgsDebugMsg( QString( "Deleting vertex %1 failed - resetting" ).arg( i ) );
        break;
      }

      success = true;

      if ( topologicalEditing )
      {
        QMultiMap<double, QgsSnappingResult>::iterator resultIt =  currentResultList.begin();

        for ( ; resultIt != currentResultList.end(); ++resultIt )
        {
          // move all other
          if ( mFeatureId !=  resultIt.value().snappedAtGeometry )
            mVlayer->deleteVertexV2( resultIt.value().snappedAtGeometry, resultIt.value().snappedVertexNr );
        }
      }

      if ( res == QgsVectorLayer::EmptyGeometry )
      {
        //geometry has been cleared as a result of deleting vertices (eg not enough vertices left to leave a valid geometry),
        //so nothing more to do
        QgsGeometry empty;
        geometryChanged( mFeatureId, empty );
        break;
      }
    }
  }

  if ( nSelected > 0 )
    endGeometryChange();

  if ( success )
  {
    mVlayer->endEditCommand();
  }
  else
  {
    mVlayer->destroyEditCommand();
  }
}
void tst_QWebPluginDatabase::preferredPlugin()
{
    QMultiMap<QString, QWebPluginInfo> pluginsMap;
    QWebPluginDatabase* database = QWebSettings::pluginDatabase();
    QList<QWebPluginInfo> plugins = database->plugins();

    for (int i = 0; i < plugins.count(); ++i) {
        QWebPluginInfo plugin = plugins.at(i);

        QList<MimeType> mimeTypes = plugin.mimeTypes();
        for (int j = 0; j < mimeTypes.count(); ++j) {
            QString mimeType = mimeTypes.at(j).name;
            pluginsMap.insert(mimeType, plugin);
        }
    }

    QMultiMap<QString, QWebPluginInfo>::iterator it = pluginsMap.begin();
    while (it != pluginsMap.end()) {
        QString mimeType = it.key();

        if (pluginsMap.count(mimeType) > 1) {
            QList<QWebPluginInfo> pluginsForMimeType = pluginsMap.values(mimeType);
            QWebPluginInfo plugin = database->pluginForMimeType(mimeType);
            QVERIFY(plugin.supportsMimeType(mimeType));

            pluginsForMimeType.removeAll(plugin);
            for (int i = 0; i < pluginsForMimeType.count(); ++i) {
                QWebPluginInfo anotherPlugin = pluginsForMimeType.at(i);
                QVERIFY(plugin.supportsMimeType(mimeType));
                QVERIFY(plugin != anotherPlugin);

                QCOMPARE(database->pluginForMimeType(mimeType), plugin);
                database->setPreferredPluginForMimeType(mimeType, anotherPlugin);
                QCOMPARE(database->pluginForMimeType(mimeType), anotherPlugin);

                anotherPlugin.setEnabled(false);
                QCOMPARE(database->pluginForMimeType(mimeType), plugin);

                anotherPlugin.setEnabled(true);
                QCOMPARE(database->pluginForMimeType(mimeType), anotherPlugin);
                database->setSearchPaths(database->searchPaths());
                QCOMPARE(database->pluginForMimeType(mimeType), anotherPlugin);

                database->setPreferredPluginForMimeType(mimeType, QWebPluginInfo());
                QCOMPARE(database->pluginForMimeType(mimeType), plugin);
            }
        } else {
            QWebPluginInfo plugin = database->pluginForMimeType(mimeType);
            QCOMPARE(pluginsMap.value(mimeType), plugin);

            database->setPreferredPluginForMimeType(mimeType, plugin);
            QCOMPARE(database->pluginForMimeType(mimeType), plugin);

            plugin.setEnabled(false);
            QCOMPARE(database->pluginForMimeType(mimeType), QWebPluginInfo());
            plugin.setEnabled(true);

            database->setPreferredPluginForMimeType(mimeType, QWebPluginInfo());
            QCOMPARE(database->pluginForMimeType(mimeType), plugin);
        }

        ++it;
    }

    if (pluginsMap.keys().count() >= 2) {
        QStringList mimeTypes = pluginsMap.uniqueKeys();

        QString mimeType1 = mimeTypes.at(0);
        QString mimeType2 = mimeTypes.at(1);
        QWebPluginInfo plugin1 = database->pluginForMimeType(mimeType1);
        QWebPluginInfo plugin2 = database->pluginForMimeType(mimeType2);

        int i = 2;
        while (plugin2.supportsMimeType(mimeType1)
               && !mimeType2.isEmpty()
               && i < mimeTypes.count()) {
            mimeType2 = mimeTypes.at(i);
            plugin2 = database->pluginForMimeType(mimeType2);
            ++i;
        }

        plugin1 = database->pluginForMimeType(mimeType1);
        QVERIFY(plugin1.supportsMimeType(mimeType1));
        QVERIFY(!plugin1.isNull());
        plugin2 = database->pluginForMimeType(mimeType2);
        QVERIFY(plugin2.supportsMimeType(mimeType2));
        QVERIFY(!plugin2.isNull());

        database->setPreferredPluginForMimeType(mimeType2, plugin1);
        QVERIFY(!plugin1.supportsMimeType(mimeType2));
        QCOMPARE(database->pluginForMimeType(mimeType2), plugin2);

        database->setPreferredPluginForMimeType(mimeType1, plugin1);
        QVERIFY(!plugin2.supportsMimeType(mimeType1));
        QCOMPARE(database->pluginForMimeType(mimeType2), plugin2);
    }
}