예제 #1
0
void PlaylistModel::sort(int column, Qt::SortOrder order)
{
    if (m_tracks.count() < 2)
    {
        return;
    }

    QMultiMap<QString, KUrl> keyMap;
    QMultiMap<qint64, KUrl> durationMap;
    KUrl::List tracks;
    const KUrl url = m_tracks.value(m_currentTrack);

    if (column == DurationColumn)
    {
        for (int i = 0; i < m_tracks.count(); ++i)
        {
            durationMap.insert(MetaDataManager::duration(m_tracks.at(i)), m_tracks.at(i));
        }

        tracks = durationMap.values();
    }
    else if (column > FileNameColumn && column < DurationColumn)
    {
        const MetaDataKey key = translateColumn(column);

        for (int i = 0; i < m_tracks.count(); ++i)
        {
            keyMap.insert(MetaDataManager::metaData(m_tracks.at(i), key), m_tracks.at(i));
        }

        tracks = keyMap.values();
    }
    else
    {
        for (int i = 0; i < m_tracks.count(); ++i)
        {
            keyMap.insert(m_tracks.at(i).pathOrUrl(), m_tracks.at(i));
        }

        tracks = keyMap.values();
    }

    if (order == Qt::AscendingOrder)
    {
        KUrl::List items;

        for (int i = (tracks.count() - 1); i >= 0; --i)
        {
            items.append(tracks.at(i));
        }

        tracks = items;
    }

    m_tracks = tracks;

    setCurrentTrack(findTrack(url));

    emit tracksChanged();
}
예제 #2
0
void XCursorThemeData::parseIndexFile () {
  QMultiMap<QString, QString> cfg = loadCfgFile(mPath+"/index.theme", true);
  if (cfg.contains("icon theme/name")) mTitle = cfg.values("icon theme/name").at(0).trimmed();
  if (cfg.contains("icon theme/comment")) mDescription = cfg.values("icon theme/comment").at(0).trimmed();
  if (cfg.contains("icon theme/example")) mSample = cfg.values("icon theme/example").at(0).trimmed();
  if (cfg.contains("icon theme/hidden")) {
      QString hiddenValue = cfg.values("icon theme/hidden").at(0).toLower();
      mHidden = hiddenValue=="false" ? false : true;
  }
  if (cfg.contains("icon theme/inherits")) {
    QStringList i = cfg.values("icon theme/inherits"), res;
    for (int f = i.size()-1; f >= 0; f--) res << i.at(f).trimmed();
  }
  if (mDescription.startsWith("- Converted by")) mDescription.remove(0, 2);
}
void NewProjectPage::buildTemplateList()
{
   QMultiMap<QString, ProjectEntry*> *dirList = mFrontloader->getProjectList()->getTemplateDirectoryList();

   QList<ProjectEntry*> entryList = dirList->values("Templates");

   mTemplateNameList.clear();
   TemplateList->clear();

   for(int i=0; i<entryList.size(); i++)
   {
      ProjectEntry *entry = entryList.at(i);

      if(mTemplateNameList.values(entry->mName).size() == 0)
      {
         mTemplateNameList.insert(entry->mName, entry);

         QPixmap *pixmap = NULL;
         if(mFrontloader != NULL)
         {
            pixmap = mFrontloader->getProjectPixmap(entry);
         }

         if(pixmap == NULL)
         {
            TemplateList->addItem(entry->mName);
         }
         else
         {
            QIcon icon(pixmap->scaled(16, 16));
            TemplateList->addItem(icon, entry->mName);
         }
      }
   }
}
예제 #4
0
int Library::rescan() throw (Exception)
{
    clearDatabaseAndCreateTables();

    int count = 0;
    QMultiMap<QString, FilePath> dirs = getAllElementDirectories();
    count += addCategoriesToDb<ComponentCategory>(  dirs.values("cmpcat"),  "component_categories", "cat_id");
    count += addCategoriesToDb<PackageCategory>(    dirs.values("pkgcat"),  "package_categories",   "cat_id");
    count += addElementsToDb<Symbol>(               dirs.values("sym"),     "symbols",              "symbol_id");
    count += addElementsToDb<SpiceModel>(           dirs.values("spcmdl"),  "spice_models",         "model_id");
    count += addElementsToDb<Package>(              dirs.values("pkg"),     "packages",             "package_id");
    count += addElementsToDb<Component>(            dirs.values("cmp"),     "components",           "component_id");
    count += addDevicesToDb(                        dirs.values("dev"),     "devices",              "device_id");

    return count;
}
예제 #5
0
void MainWindow::on_cVersion_currentIndexChanged(const QString &version)
{
    QHash<QString, QStringList> &hVersion = reports[version];
    QStringList crashLocations = hVersion.keys();
    ui->cLocation->clear();
    if (crashLocations.size())
    {
        QMultiMap<int, QString> sortedMap;
        for (int i=0; i< crashLocations.size(); i++)
        {
            sortedMap.insert(hVersion.value(crashLocations.at(i)).size(), crashLocations.at(i));
        }
        QStringList sortedLocations = sortedMap.values();
        std::reverse(sortedLocations.begin(), sortedLocations.end());
        ui->cLocation->addItems(sortedLocations);
        ui->cLocation->setCurrentIndex(0);

        int acum = 0;
        for (int i = 0; i < crashLocations.size(); i++)
        {
            acum += hVersion.value(crashLocations[i]).size();
        }
        ui->eVersion->setText(QString::number(acum));
    }
    else
    {
        ui->eVersion->setText(QString::number(0));
        ui->cLocation->addItem(tr("Crash location"));
    }
}
예제 #6
0
static QString certToFormattedString(QSslCertificate cert)
{
    QString resultstring = QLatin1String("<p>");
    QStringList tmplist;

    resultstring += cert.subjectInfo(QSslCertificate::CommonName);

    resultstring += QString::fromLatin1("<br/>Issuer: %1")
        .arg(cert.issuerInfo(QSslCertificate::CommonName));

    resultstring += QString::fromLatin1("<br/>Not valid before: %1<br/>Valid Until: %2")
        .arg(cert.effectiveDate().toString(Qt::ISODate))
        .arg(cert.expiryDate().toString(Qt::ISODate));

    QMultiMap<QSsl::AlternateNameEntryType, QString> names = cert.alternateSubjectNames();
    if (names.count() > 0) {
        tmplist = names.values(QSsl::DnsEntry);
        resultstring += QLatin1String("<br/>Alternate Names:<ul><li>")
            + tmplist.join(QLatin1String("</li><li>"))
            + QLatin1String("</li><</ul>");
    }

    resultstring += QLatin1String("</p>");

    return resultstring;
}
예제 #7
0
bool VersionsConverterManager::validateCurrentProject()
{
	QSet<QString> editorsToCheck;
	IdList const allElements = mMainWindow.models()->logicalModelAssistApi().children(Id::rootId());
	for (Id const &element : allElements) {
		editorsToCheck << element.editor();
	}

	QMap<Id, Version> const savedVersions = mMainWindow.models()->logicalModelAssistApi().editorVersions();
	QMultiMap<QString, ProjectConverter> const converters = mMainWindow.toolManager().projectConverters();

	for (QString const &editor : editorsToCheck) {
		Version const currentVersion = mMainWindow.editorManager().version(Id(editor));
		Version const savedVersion = savedVersions[Id(editor)];

		if (currentVersion == savedVersion) {
			continue;
		}

		if (currentVersion < savedVersion) {
			displayTooOldEnviromentError(savedVersion);
			return false;
		}

		if (!convertProject(currentVersion, savedVersion, converters.values(editor))) {
			return false;
		}
	}

	return true;
}
예제 #8
0
파일: task.cpp 프로젝트: zanettea/SAK
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();
}
예제 #9
0
AbstractView* ViewLoader::loadFromPlugin(AbstractView *currentView, const QString &menuAction)
{
	AbstractView *view = nullptr;

	// Other views loaded from plugins
	QMultiMap<QString, QObject*> multiMap = _pluginManager->dependencies();
	QObjectList dep = multiMap.values(menuAction);
	if (dep.isEmpty()) {
		return view;
	}
	qDebug() << Q_FUNC_INFO << "No built-in view was found for this action. Was it from an external plugin?";
	for (BasicPlugin *plugin : _pluginManager->loadedPlugins().values()) {
		if (plugin->name() != menuAction) {
			continue;
		}

		// Check if we need to pass some objects from old view to new view, because new one can be brought by plugins
		// For example, a plugin may need the MediaPlayerControl from the current view
		if (MediaPlayerPlugin *mediaPlayerPlugin = qobject_cast<MediaPlayerPlugin*>(plugin)) {
			mediaPlayerPlugin->setMediaPlayerControl(currentView->mediaPlayerControl());
			if (mediaPlayerPlugin->hasView()) {
				view = mediaPlayerPlugin->instanciateView();
				view->setOrigin(currentView);
			}
		}
	}
	return view;
}
void WidgetChatCenter::channelNames(QStringList names)
{
	WidgetChatTab* tab	= tabByName(names.at(2));
	QString namestr		= names.at(3);
	QStringList list	= namestr.split(" ");

	list.sort();
	QMultiMap<int, int> map;

	for(int i = 0; i < list.size(); ++i)
	{
		QString user = list.at(i);
		int idx = prefixChars.indexOf(user.at(0));
		if(idx < 0)
		{
			idx = prefixChars.length();    // normal user
		}
		map.insert(idx, i);
	}

	QStringList sorted;
	QList<int> values = map.values();
	for(int i = 0; i < values.size(); ++i)
	{
		sorted.append(list.at(values.at(i)));
	}

	tab->channelNames(sorted);
}
예제 #11
0
void VarManager::search()
{
	setEnabled(false);

	QMultiMap<int, QString> vars = fieldArchive->searchAllVars();

	quint32 key;
	qint32 param;
	QTreeWidgetItem *item;
	QMap<int, bool> count;
	int lastVar=-1;

	QMapIterator<int, QString> i(vars);
	while(i.hasNext()) {
		i.next();
		if(lastVar == i.key())	continue;

		lastVar = i.key();
		JsmOpcode op(lastVar);
		key = op.key();
		param = op.param();
		count.insert(param, true);

		item = list->topLevelItem(param);
		item->setBackground(0, QColor(0xff,0xe5,0x99));

		if(key == 10 || key == 11 || key == 16) {
			item->setText(1, QString("%1Byte").arg(key == 16 ? "Signed " : ""));
		}
		else if(key == 12 || key == 13 || key == 17) {
			item->setText(1, QString("%1Word").arg(key == 17 ? "Signed " : ""));
			count.insert(param+1, true);
			list->topLevelItem(param+1)->setBackground(0, QColor(0xff,0xe5,0x99));
		}
		else if(key == 14 || key == 15 || key == 18) {
			item->setText(1, QString("%1Long").arg(key == 18 ? "Signed " : ""));
			count.insert(param+1, true);
			list->topLevelItem(param+1)->setBackground(0, QColor(0xff,0xe5,0x99));
			count.insert(param+2, true);
			list->topLevelItem(param+2)->setBackground(0, QColor(0xff,0xe5,0x99));
			count.insert(param+3, true);
			list->topLevelItem(param+3)->setBackground(0, QColor(0xff,0xe5,0x99));
		}
		QStringList fields(vars.values(lastVar));
		fields.append(item->text(3).split(", ", QString::SkipEmptyParts));
		fields.removeDuplicates();
		item->setText(3, fields.join(", "));
	}

	list->resizeColumnToContents(0);
	list->resizeColumnToContents(1);

	setEnabled(true);
	countLabel->setText(tr("Vars utilisés : %1/1536").arg(count.size()));
}
예제 #12
0
void MERFTag::executeActions(NFA* nfa) {
    MSFormula* formula = (MSFormula*)(nfa->formula);

    /** pre match **/
    QString preMatch = msf->name;
    preMatch.append("_preMatch();\n");
    formula->actionData.append(preMatch);
    /** Done **/

    match->executeActions(nfa);

    /** on match **/
    QString onMatch = msf->name;
    onMatch.append("_onMatch");
    QMultiMap<QString,QPair<QString,QString> > *functionParametersMap = &(formula->functionParametersMap);
    QList<QPair<QString,QString> > params = functionParametersMap->values(onMatch);
    onMatch.append('(');

    for(int j=0; j<params.count(); j++) {
        QString msfName = params.at(j).first;
        QString field = params.at(j).second;

        QString sarfMatches;
        QString paramValue = getParam(msfName,field,&sarfMatches);
        if(field.compare("text") == 0) {
            onMatch.append('\"' + paramValue + "\",");
        }
        else if(field.compare("position") == 0) {
            onMatch.append(paramValue + ',');
        }
        else if(field.compare("length") == 0) {
            onMatch.append(paramValue + ',');
        }
        else if(field.compare("number") == 0) {
            onMatch.append(paramValue + ',');
        }
        else if(field.compare("matches") == 0) {
            onMatch.append(paramValue + ',');
            formula->actionData.append(sarfMatches);
        }
    }
    if(params.count() == 0) {
        onMatch.append(");\n");
    }
    else {
        onMatch.chop(1);
        onMatch.append(");\n");
    }
    formula->actionData.append(onMatch);
    /** Done **/
}
예제 #13
0
void Connector::dumpCertificate( const QSslCertificate &cert )
{
    qDebug() << cert.toPem();

    qDebug() << "== Subject Info ==\b";
    qDebug() << "CommonName:\t\t" << cert.subjectInfo( QSslCertificate::CommonName );
    qDebug() << "Organization:\t\t" << cert.subjectInfo( QSslCertificate::Organization );
    qDebug() << "LocalityName:\t\t" << cert.subjectInfo( QSslCertificate::LocalityName );
    qDebug() << "OrganizationalUnitName:\t" << cert.subjectInfo( QSslCertificate::OrganizationalUnitName );
    qDebug() << "StateOrProvinceName:\t" << cert.subjectInfo( QSslCertificate::StateOrProvinceName );

    QMultiMap<QSsl::AlternateNameEntryType, QString> altNames = cert.alternateSubjectNames();
    if ( !altNames.isEmpty() ) {
        qDebug() << "Alternate Subject Names (DNS):";
        foreach (const QString &altName, altNames.values(QSsl::DnsEntry)) {
            qDebug() << altName;
        }

        qDebug() << "Alternate Subject Names (Email):";
        foreach (const QString &altName, altNames.values(QSsl::EmailEntry)) {
            qDebug() << altName;
        }
    }
예제 #14
0
void AutoTestUnitTests::testCodeParserGTest()
{
    if (qgetenv("GOOGLETEST_DIR").isEmpty())
        QSKIP("This test needs googletest - set GOOGLETEST_DIR (point to googletest repository)");

    QFETCH(QString, projectFilePath);
    CppTools::Tests::ProjectOpenerAndCloser projectManager;
    CppTools::ProjectInfo projectInfo = projectManager.open(projectFilePath, true);
    QVERIFY(projectInfo.isValid());

    QSignalSpy parserSpy(m_model->parser(), SIGNAL(parsingFinished()));
    QSignalSpy modelUpdateSpy(m_model, SIGNAL(sweepingDone()));
    QVERIFY(parserSpy.wait(20000));
    QVERIFY(modelUpdateSpy.wait());

    QCOMPARE(m_model->gtestNamesCount(), 7);

    QMultiMap<QString, int> expectedNamesAndSets;
    expectedNamesAndSets.insert(QStringLiteral("FactorialTest"), 3);
    expectedNamesAndSets.insert(QStringLiteral("FactorialTest_Iterative"), 2);
    expectedNamesAndSets.insert(QStringLiteral("Sum"), 2);
    expectedNamesAndSets.insert(QStringLiteral("QueueTest"), 2);
    expectedNamesAndSets.insert(QStringLiteral("DummyTest"), 1); // used as parameterized test
    expectedNamesAndSets.insert(QStringLiteral("DummyTest"), 1); // used as 'normal' test
    expectedNamesAndSets.insert(QStringLiteral("NamespaceTest"), 1);

    QMultiMap<QString, int> foundNamesAndSets = m_model->gtestNamesAndSets();
    QCOMPARE(expectedNamesAndSets.size(), foundNamesAndSets.size());
    foreach (const QString &name, expectedNamesAndSets.keys())
        QCOMPARE(expectedNamesAndSets.values(name), foundNamesAndSets.values(name));

    // check also that no Qt related tests have been found
    QCOMPARE(m_model->autoTestsCount(), 0);
    QCOMPARE(m_model->namedQuickTestsCount(), 0);
    QCOMPARE(m_model->unnamedQuickTestsCount(), 0);
    QCOMPARE(m_model->dataTagsCount(), 0);
}
예제 #15
0
void AutoTestUnitTests::testCodeParserGTest()
{
    if (qgetenv("GOOGLETEST_DIR").isEmpty())
        QSKIP("This test needs googletest - set GOOGLETEST_DIR (point to googletest repository)");

    NavigationWidget *navigation = NavigationWidget::instance();
    navigation->activateSubWidget(Constants::AUTOTEST_ID);

    CppTools::Tests::ProjectOpenerAndCloser projectManager;
    CppTools::ProjectInfo projectInfo = projectManager.open(
                QString(m_tmpDir->path() + QLatin1String("/simple_gt/simple_gt.pro")), true);
    QVERIFY(projectInfo.isValid());

    QSignalSpy parserSpy(m_model->parser(), SIGNAL(parsingFinished()));
    QVERIFY(parserSpy.wait(20000));

    QCOMPARE(m_model->gtestNamesCount(), 6);

    QMultiMap<QString, int> expectedNamesAndSets;
    expectedNamesAndSets.insert(QStringLiteral("FactorialTest"), 3);
    expectedNamesAndSets.insert(QStringLiteral("FactorialTest_Iterative"), 2);
    expectedNamesAndSets.insert(QStringLiteral("Sum"), 2);
    expectedNamesAndSets.insert(QStringLiteral("QueueTest"), 2);
    expectedNamesAndSets.insert(QStringLiteral("DummyTest"), 1); // used as parameterized test
    expectedNamesAndSets.insert(QStringLiteral("DummyTest"), 1); // used as 'normal' test

    QMultiMap<QString, int> foundNamesAndSets = m_model->gtestNamesAndSets();
    QCOMPARE(expectedNamesAndSets.size(), foundNamesAndSets.size());
    foreach (const QString &name, expectedNamesAndSets.keys())
        QCOMPARE(expectedNamesAndSets.values(name), foundNamesAndSets.values(name));

    // check also that no Qt related tests have been found
    QCOMPARE(m_model->autoTestsCount(), 0);
    QCOMPARE(m_model->namedQuickTestsCount(), 0);
    QCOMPARE(m_model->unnamedQuickTestsCount(), 0);
    QCOMPARE(m_model->dataTagsCount(), 0);
}
예제 #16
0
QList<QSharedPointer<Player> > Drink::playersSortedByCount() const
{
    QMap<QSharedPointer<Player>, int> counts;

    foreach(QSharedPointer<LiveDrink> drink, liveDrinks()) {
        ++counts[drink->player()];
    }

    QMultiMap<int, QSharedPointer<Player> > helperMap;
    for(auto it = counts.constBegin(); it != counts.constEnd(); ++it) {
        helperMap.insert(it.value(), it.key());
    }

    return helperMap.values();
}
예제 #17
0
  int handleMessage(GstMessage *message, QMultiMap<QString, QtCamGstMessageHandler *>& map) {
    const GstStructure *s = gst_message_get_structure(message);
    if (!s) {
      return 0;
    }

#if 0
    qDebug() << "Message" << gst_structure_get_name(s);
#endif

    QList<QtCamGstMessageHandler *> list = map.values(gst_structure_get_name(s));

    foreach (QtCamGstMessageHandler *handler, list) {
      handler->handleMessage(message);
    }
void QgsMapToolNodeTool::createTopologyRubberBands()
{
  QgsVectorLayer* vlayer = mSelectedFeature->vlayer();

  foreach ( const QgsVertexEntry* vertexEntry, mSelectedFeature->vertexMap() )
  {
    if ( !vertexEntry->isSelected() )
    {
      continue;
    }

    // Snap vertex
    QMultiMap<double, QgsSnappingResult> snapResults;
    vlayer->snapWithContext( vertexEntry->pointV1(), ZERO_TOLERANCE, snapResults, QgsSnapper::SnapToVertex );
    foreach ( const QgsSnappingResult& snapResult, snapResults.values() )
    {
      // Get geometry of snapped feature
      QgsFeatureId snapFeatureId = snapResult.snappedAtGeometry;
      QgsFeature feature;
      if ( !vlayer->getFeatures( QgsFeatureRequest( snapFeatureId ).setSubsetOfAttributes( QgsAttributeList() ) ).nextFeature( feature ) )
      {
        continue;
      }

      // Get VertexId of snapped vertex
      QgsVertexId vid;
      if ( !feature.geometry()->vertexIdFromVertexNr( snapResult.snappedVertexNr, vid ) )
      {
        continue;
      }
      // Add rubberband if not already added
      if ( !mMoveRubberBands.contains( snapFeatureId ) )
      {
        QgsGeometryRubberBand* rb = new QgsGeometryRubberBand( mCanvas, feature.geometry()->type() );
        rb->setOutlineColor( Qt::blue );
        rb->setBrushStyle( Qt::NoBrush );
        rb->setOutlineWidth( 2 );
        QgsAbstractGeometryV2* rbGeom = feature.geometry()->geometry()->clone();
        if ( mCanvas->mapSettings().layerTransform( vlayer ) )
          rbGeom->transform( *mCanvas->mapSettings().layerTransform( vlayer ) );
        rb->setGeometry( rbGeom );
        mMoveRubberBands.insert( snapFeatureId, rb );
      }
      // Add to list of vertices to be moved
      mMoveVertices[snapFeatureId].append( qMakePair( vid, toMapCoordinates( vlayer, feature.geometry()->geometry()->vertexAt( vid ) ) ) );
    }
  }
}
예제 #19
0
bool NetworkGraphics::positionBranch(raw_address root, QPointF topLeft){
	if(!cloudAddrMap.contains(root)){
		return false;
	}

	GraphicNetCloud* cloud = getCloudByAddress(root);

	qDebug() << "NetworkGraphics::positionBranch - Moving cloud:" << cloud->getAddress().toString().c_str();

	QSizeF size = computeSize(root);
	qreal centerX = topLeft.x() + (size.width()/2.0);

	cloud->setY(topLeft.y());
	cloud->setX(centerX - (cloud->boundingRect().width() / 2.0));

	//Update to start in next row
	topLeft.setY(topLeft.y() + cloud->boundingRect().height());

	QMultiMap<uint8_t, raw_address> branch = network->getBranchAddresses(root);

	QList<uint8_t> keys = branch.uniqueKeys();

	if(keys.size() > 1){
	//for(int i=1; i<keys.size(); i++){
		QPointF cloudPos = topLeft;
		QList<GraphicNetCloud*> clouds = getCloudsByAddress(branch.values(keys[1]));
		qreal maxHeight = 0.0;

		for(int j=0; j<clouds.size(); j++){
			GraphicNetCloud* cloud = clouds[j];

			//cloud->setPos(cloudPos);

			QSizeF size = computeSize(cloud->getAddress());

			positionBranch(cloud->getAddress(), cloudPos);

			cloudPos.setX(cloudPos.x() + size.width());

			maxHeight = fmax(cloud->boundingRect().height(), maxHeight);
		}

		//topLeft.setY(topLeft.y() + maxHeight);
	}

	return true;
}
예제 #20
0
QList<HistoryModel::HistoryEntryMatch> HistoryModel::findEntries(const QString &prefix, bool markAsTypedIn) const
{
	QList<HistoryEntryItem*> matchedEntries;
	QList<HistoryModel::HistoryEntryMatch> allMatches;
	QList<HistoryModel::HistoryEntryMatch> currentMatches;
	QMultiMap<QDateTime, HistoryModel::HistoryEntryMatch> matchesMap;
	QHash<QUrl, QList<HistoryEntryItem*> >::const_iterator urlsIterator;

	for (urlsIterator = m_urls.constBegin(); urlsIterator != m_urls.constEnd(); ++urlsIterator)
	{
		if (urlsIterator.value().isEmpty() || matchedEntries.contains(urlsIterator.value().first()))
		{
			continue;
		}

		const QString result(Utils::matchUrl(urlsIterator.key(), prefix));

		if (!result.isEmpty())
		{
			HistoryEntryMatch match;
			match.entry = urlsIterator.value().first();
			match.match = result;

			if (markAsTypedIn)
			{
				match.isTypedIn = true;
			}

			matchesMap.insert(match.entry->data(TimeVisitedRole).toDateTime(), match);

			matchedEntries.append(match.entry);
		}
	}

	currentMatches = matchesMap.values();

	matchesMap.clear();

	for (int i = (currentMatches.count() - 1); i >= 0; --i)
	{
		allMatches.append(currentMatches.at(i));
	}

	return allMatches;
}
예제 #21
0
const QList<QPainterPath> TextItems::generateZones(const int Width,
        const int ToleranceR, const int ToleranceY,
        const int Columns) const
{ // Assumes that items are already in column, y, x order!
    // Phase #1: Generate the zones
    QList<QPainterPath> zones;
    foreach (const TextItem &item, items) {
        if (zones.isEmpty()) { // First word becomes first zone
            QPainterPath zone;
            zone.addRect(item.rect);
            zones << zone;
        } else { // Add to an existing zone within tolerance or a new one
            const QRectF tolerantRect = item.rect.adjusted(-ToleranceR,
                    -ToleranceR, ToleranceR, ToleranceR);
            bool found = false;
            for (int i = 0; i < zones.count(); ++i) {
                QPainterPath zone = zones.at(i);
                if (zone.intersects(tolerantRect)) {
                    zone.addRect(item.rect);
                    zones[i] = zone;
                    found = true;
                    break;
                }
            }
            if (!found) {
                QPainterPath zone;
                zone.addRect(item.rect);
                zones << zone;
            }
        }
    }

    // Phase #2: Order the zones by (column, y, x)
    const int Span = Width / Columns;
    QMultiMap<Key, QPainterPath> zonesForColumn;
    foreach (const QPainterPath &zone, zones) {
        const QRect &rect = zone.boundingRect().toRect();
        const int Column = ((Columns == 1) ? 0
            : (rect.width() > Span) ? Columns : rect.right() / Span);
        const int y = normalizedY(static_cast<int>(rect.y()), ToleranceY);
        zonesForColumn.insertMulti(Key(Column, y, rect.x()), zone);
    }
    return zonesForColumn.values();
}
예제 #22
0
 TemplateInfoList()
 {
     QMultiMap<QString, TemplateInfo> multiMap;
     foreach (const QString &templateName, templateNames()) {
         const QString templatePath = templateRootDirectory() + templateName;
         QFile xmlFile(templatePath + QLatin1String("/template.xml"));
         if (!xmlFile.open(QIODevice::ReadOnly)) {
             qWarning().nospace() << QString::fromLatin1("Cannot open %1").arg(QDir::toNativeSeparators(QFileInfo(xmlFile.fileName()).absoluteFilePath()));
             continue;
         }
         TemplateInfo info;
         info.templateName = templateName;
         info.templatePath = templatePath;
         QXmlStreamReader reader(&xmlFile);
         if (parseTemplateXml(reader, &info))
             multiMap.insert(info.priority, info);
     }
     m_templateInfoList = multiMap.values();
 }
예제 #23
0
void ModelicaConnections::getOutside(ModItem* element,bool includeChildren,QStringList &uniquePorts, QList<QStringList> &outsideComps)
{
    QStringList listPorts;
    QStringList listOutsideComps;

    getOutside(element,includeChildren,listPorts,listOutsideComps);

    QMultiMap<QString,QString> map;
    for(int i=0;i<listPorts.size();i++)
    {
        map.insert(listPorts.at(i),listOutsideComps.at(i));
    }

    uniquePorts = map.uniqueKeys();
    outsideComps.clear();
    for(int i=0;i<uniquePorts.size();i++)
    {
        outsideComps.push_back(map.values(uniquePorts.at(i)));
    }
}
예제 #24
0
void PaletteTreeWidgets::refreshUserPalette(bool force)
{
	QList<QPair<QString, QList<gui::PaletteElement>>> groups;
	QMap<QString, QString> descriptions = { { mUserGroupTitle, mUserGroupDescription } };
	QList<gui::PaletteElement> groupElements;

	const QMultiMap<Id, Id> types = mMainWindow->models().exploser().explosions(mDiagram);
	for (const Id &source : types.uniqueKeys()) {
		for (const Id &target : types.values(source)) {
			const QString shape = mMainWindow->models().logicalRepoApi().stringProperty(target, "shape");
			QIcon icon;
			if (shape.isEmpty()) {
				icon = mEditorManager->icon(source);
			} else {
				QDomDocument doc;
				doc.setContent(shape);
				SdfIconEngineV2 * const engine = new SdfIconEngineV2(doc);
				icon = QIcon(engine);
			}

			groupElements << gui::PaletteElement(source
					, mMainWindow->models().logicalRepoApi().name(target)
					, QString(), icon
					, mEditorManager->iconSize(source)
					, target);
		}
	}

	if (!groupElements.isEmpty()) {
		groups << qMakePair(mUserGroupTitle, groupElements);
	}

	// This condition will filter out most of the cases.
	if (groupElements.toSet() != mUserTree->elementsSet() || force) {
		mUserTree->addGroups(groups, descriptions, true, mEditorManager->friendlyName(mDiagram), true);
	}

	if (groupElements.isEmpty()) {
		mUserTree->hide();
	}
}
예제 #25
0
bool keyQtToCodeMac(int keyQt, QList<uint> &keyCodes)
{
    updateScancodes();
    keyCodes.clear();
    keyQt &= ~Qt::KeyboardModifierMask;
    int chr;
    if (!keyQtToSymMac(keyQt, chr)) {
        return false;
    }

    if (chr == kFunctionKeyCharCode) {
        for (int i = 0; functionKeys[i].qt_code; i++) {
            if (functionKeys[i].qt_code == keyQt) {
                keyCodes.append(functionKeys[i].mac_code);
            }
        }
    } else {
        keyCodes += scancodes.values(chr);
    }

    return keyCodes.count() > 0;
}
예제 #26
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

}
예제 #27
0
QGridLayout* WidgetParameters::buildLayoutFromParameters()
{
    //Adding Layout
    QGridLayout *mainLayout = new QGridLayout(this);

    // get groups
    QMultiMap<QString,MOParameter*> groupmap = _localParameters->groupmap();
    QStringList groups = groupmap.uniqueKeys();


    QStringList paramNames;
    for(int i=0;i<_localParameters->size();i++)
        paramNames.push_back(_localParameters->at(i)->name());

    QPushButton *newPush;
    MOParameter* parameter;
    MOParameterListed *paramList;
    QList<MOParameter*> groupParameters;
    QGridLayout *curLayout;
    QGroupBox *curBox;

    // create group box
    for(int iG=0;iG<groups.size();iG++)
    {
        int iRow=0;
        if(groups.size()>1)
        {
            curBox = new QGroupBox(groups.at(iG),this);
            curLayout = new QGridLayout(curBox);
        }
        else
            curLayout = mainLayout;

        groupParameters = groupmap.values(groups.at(iG));

        // to reproduce parameters order, start from the end
        // it seems MultiMap behaves like a pile
        for(int iP=groupParameters.size()-1;iP>=0;iP--)
        {
            parameter = groupParameters.at(iP);
            // add setting
            QString dispName;
            if(parameter->name().contains("/"))
                dispName = parameter->name().section("/",1,-1);
            else
                dispName = parameter->name();

            curLayout->addWidget(new QLabel(parameter->description()),iRow,0);
            //boxLayout->addWidget(new QLabel(dispName),iRow,0);

            int type = parameter->getFieldValue(MOParameter::TYPE).toInt();
            QWidget *valueWidget;
            QVariant value = parameter->getFieldValue(MOParameter::VALUE);

            switch(type)
            {
            case MOParameter::STRING :
                valueWidget = new QLineEdit(this);
                ((QLineEdit*)valueWidget)->setText(value.toString());
                connect(((QLineEdit*)valueWidget),SIGNAL(textChanged(QString)),this,SLOT(onValueChanged()));
                break;
            case MOParameter::FILEPATH :
                valueWidget = new QLineEdit(this);
                ((QLineEdit*)valueWidget)->setText(value.toString());
                connect(((QLineEdit*)valueWidget),SIGNAL(textChanged(QString)),this,SLOT(onValueChanged()));
                // add button
                newPush = new QPushButton("...",this);
                newPush->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Preferred);
                _pathsMap.insert(newPush,((QLineEdit*)valueWidget));
                curLayout->addWidget(newPush,iRow,2);
                connect(newPush,SIGNAL(clicked()),this,SLOT(onSelectFileClicked()));
                break;
            case MOParameter::FOLDERPATH :
                valueWidget = new QLineEdit(this);
                ((QLineEdit*)valueWidget)->setText(value.toString());
                connect(((QLineEdit*)valueWidget),SIGNAL(textChanged(QString)),this,SLOT(onValueChanged()));
                //add button
                newPush = new QPushButton("...",this);
                newPush->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Preferred);
                _pathsMap.insert(newPush,((QLineEdit*)valueWidget));
                curLayout->addWidget(newPush,iRow,2);
                connect(newPush,SIGNAL(clicked()),this,SLOT(onSelectFolderClicked()));
                break;

            case MOParameter::DOUBLE :
                valueWidget = new QScienceSpinBox(this);
                ((QScienceSpinBox*)valueWidget)->setMinimum(parameter->getFieldValue(MOParameter::MIN).toDouble());
                ((QScienceSpinBox*)valueWidget)->setMaximum(parameter->getFieldValue(MOParameter::MAX).toDouble());
                ((QScienceSpinBox*)valueWidget)->setDecimals(10);
                ((QScienceSpinBox*)valueWidget)->setValue(value.toDouble());
                connect(((QScienceSpinBox*)valueWidget),SIGNAL(valueChanged(double)),this,SLOT(onValueChanged()));
                break;
            case MOParameter::INT :
                valueWidget = new QSpinBox(this);
                ((QSpinBox*)valueWidget)->setMinimum(parameter->getFieldValue(MOParameter::MIN).toInt());
                ((QSpinBox*)valueWidget)->setMaximum(parameter->getFieldValue(MOParameter::MAX).toInt());
                ((QSpinBox*)valueWidget)->setValue(value.toInt());
                connect(((QSpinBox*)valueWidget),SIGNAL(valueChanged(int)),this,SLOT(onValueChanged()));
                break;
            case MOParameter::BOOL :
                valueWidget = new QCheckBox(this);
                Qt::CheckState state;
                if(value.toBool())
                    state = Qt::Checked;
                else
                    state = Qt::Unchecked;
                connect(((QCheckBox*)valueWidget),SIGNAL(stateChanged(int)),this,SLOT(onValueChanged()));
                ((QCheckBox*)valueWidget)->setCheckState(state);
                break;
            case MOParameter::LIST :
                //if is a list, param should be a MOParameterListed
                valueWidget = new QComboBox(this);
                paramList = dynamic_cast<MOParameterListed*>(parameter);
                if(paramList)
                {
                    //adding list items in qcombobox
                    for(int iValue = 0 ; iValue<paramList->mapList().keys().size();iValue++)
                    {
                        ((QComboBox*)valueWidget)->addItem(
                                    paramList->mapList().values().at(iValue),
                                    paramList->mapList().keys().at(iValue));
                    }
                    // set current index
                    ((QComboBox*)valueWidget)->setCurrentIndex(((QComboBox*)valueWidget)->findData(value));
                    connect(((QComboBox*)valueWidget),SIGNAL(currentIndexChanged(int)),this,SLOT(onValueChanged()));
                }
                break;
            default :
                valueWidget = new QLineEdit(this);
                ((QLineEdit*)valueWidget)->setText(value.toString());
                connect(((QLineEdit*)valueWidget),SIGNAL(textChanged(QString)),this,SLOT(onValueChanged()));
                break;

            }

            curLayout->addWidget(valueWidget,iRow,1);
            valueWidget->setEnabled(_editable);

            // store (to save data when click ok)
            _mapValueWidgets.insert(parameter,valueWidget);
            _paramNames.push_back(parameter->name());
            _paramTypes.push_back(type);

            iRow++;
        }

        if(groups.size()>1)
        {
            curBox->setLayout(curLayout);
            mainLayout->addWidget(curBox);
        }
    }




    if(_editable)
        updateEnabled(); //update

    return mainLayout;
}
예제 #28
0
파일: job.cpp 프로젝트: JoelB/BITS
bool Job::generateReport(QDateTime startDate,QDateTime endDate,QString filename)
{
	QString currentLine;
	QStringList sessionParts;
	int taskId;

	QMultiMap<int,taskSession> taskSessions;
	
	QFile sessionFile(attributeValues["Filename"].toString().replace(QString(".xml"),QString(".session")));
	if (!sessionFile.open(QIODevice::ReadOnly | QIODevice::Text))
		qDebug() << "Failed to session file!";

	while (!sessionFile.atEnd())
	{
		currentLine = QString(sessionFile.readLine());
		sessionParts = currentLine.split("%");
		taskSession tempsession;
		taskId = sessionParts.at(0).toInt();
		tempsession.start = QDateTime::fromString(sessionParts.at(1),Qt::ISODate);
		tempsession.end = QDateTime::fromString(sessionParts.at(2),Qt::ISODate);
		taskSessions.insert(taskId,tempsession);
	}
	sessionFile.close();
	
	QMap<int,int> totalTimes;
	QMapIterator<int,taskSession> iter(taskSessions);
	while (iter.hasNext())
	{
		iter.next();
		int timeSum = 0;
		QList<taskSession> sessions = taskSessions.values(iter.key());
		for (int i = 0; i < sessions.size(); i++)
		{
			taskSession tempSession = sessions.at(i);
			if (tempSession.start >= startDate && tempSession.end <= endDate) // session happened completely in range
				timeSum += tempSession.start.secsTo(tempSession.end);
			else if (tempSession.start <= startDate && tempSession.end <=endDate) // started out of range, ended in range
				timeSum += startDate.secsTo(tempSession.end);
			else if (tempSession.start >= startDate && tempSession.end >= endDate) // started in range, ended out of range
				timeSum += tempSession.start.secsTo(endDate);
			else if (tempSession.start <= startDate && tempSession.end >= endDate) // continued through entire range
				timeSum += startDate.secsTo(endDate);
		}
		totalTimes.insert(iter.key(),timeSum);
	}
	
	QFile reportFile(filename);
	if (!reportFile.open(QIODevice::WriteOnly | QIODevice::Text))
	{
		qDebug() << "Failed to open new report file!";
		return false;
	}
	
	QTextStream out(&reportFile);
	out << "Job Session Report for " << startDate.toString() << " to " << endDate.toString() << "\n\n";
	out << "Job Name: " << getAttributeValue("Name").toString() << "\n";
	out << "Job Start Date: " << getAttributeValue("StartDate").toDateTime().toString() << "\n";
	out << "Job End Date: " << getAttributeValue("EndDate").toDateTime().toString() << "\n\n";
	Task *tempTask;
	int allTime = 0;
	QStringList completedTasksOutput;
	QStringList otherTasksOutput;
	for (int i=0;i<taskCount();i++)
	{
		tempTask = getTask(i);
		QString name = tempTask->getAttributeValue("Name").toString();
		QString taskNum = QString::number(tempTask->getAttributeValue("TaskID").toInt()).prepend("   ");
		
		for (int j=taskNum.size(); j < 12; j++)
			taskNum.append(" ");
		for (int j=name.size(); j < 25; j++)
			name.append(" ");
		int timeSpent = totalTimes.value(tempTask->getAttributeValue("TaskID").toInt());
		allTime += timeSpent; // keep track of total time for percentages
		QString timeTotal = QString::number(timeSpent/3600) + "hr " + QString::number((timeSpent%3600)/60) + "min " + QString::number((timeSpent%3600)%60) + "sec";

		QDateTime completedDate = QDateTime::fromString(tempTask->getAttributeValue("Completed").toString(),Qt::ISODate);
		if (completedDate >= startDate && completedDate <= endDate)
			completedTasksOutput.append(QString(taskNum + name + timeTotal));
		else if (timeSpent > 0)
			otherTasksOutput.append(QString(taskNum + name + timeTotal));
	}
	completedTasksOutput.sort();
	otherTasksOutput.sort();
	
	out << "Tasks completed during selected time:\n\n";
	out << "\tTask ID     Task Name                 Time Spent            % of Total Time\n";
	out << "\t------------------------------------------------------------------------\n";
	QString tempOutput;
	for (int i = 0; i < completedTasksOutput.size(); i++)
	{
		tempOutput = completedTasksOutput.at(i);
		for (int j = tempOutput.size(); j < 65; j++)
			tempOutput.append(" ");
		QString percentage = QString::number(((double)totalTimes.value(tempOutput.left(10).simplified().toInt())/(double)allTime)*100.0,'f',2);
		out << "\t" << tempOutput << percentage << "\n";
	}
		
	out << "\n\nTasks worked on but not completed during selected time:\n\n";
	out << "\tTask ID     Task Name                 Time Spent            % of Total Time\n";
	out << "\t------------------------------------------------------------------------\n";
	for (int i = 0; i < otherTasksOutput.size(); i++)
	{
		tempOutput = otherTasksOutput.at(i);
		for (int j = tempOutput.size(); j < 65; j++)
			tempOutput.append(" ");
		QString percentage = QString::number((double)(totalTimes.value(tempOutput.left(10).simplified().toInt())/(double)allTime)*100.0,'f',2);
		out << "\t" << tempOutput << percentage << "\n";
	}
		
	reportFile.close();
	return true;
}
void CalculateTaskScore::run()
{

    qDebug() << "CalculateTaskScore: Starting new thread";

    ConfigParser settings;
    QDateTime started = QDateTime::currentDateTime();
    ctemplate::TemplateDictionary dict("user_task_score");
    db = MySQLHandler::getInstance();
    QMultiMap<int, LCCode> users = UserDao::getUserNativeLCCodes(db);
    QList<QSharedPointer<Task> > tasks = this->getTasks();  //Must use custom function to check message for task id

    QMultiMap<int, LCCode> userSecondaryLanguages = UserDao::getUserLCCodes(db);
    QMultiMap<int, int> userTags = UserDao::getUserTagIds(db);
    QMultiMap<int, int> taskTags = TaskDao::getTaskTagIds(db);

    if(users.count() > 0) {
        for(QMultiMap<int, LCCode>::ConstIterator usersIter = users.constBegin(); usersIter != users.constEnd(); ++usersIter) {
            if(tasks.length() > 0) {
                const LCCode userNativeLCCode = users.value(usersIter.key());
                QList<TaskScore> taskScores;
                foreach(QSharedPointer<Task> task, tasks) {
                    int score = 0;

                    Locale taskSourceLocale = task->sourcelocale();

                    if(userNativeLCCode.first == taskSourceLocale.languagecode()) {
                        score += 750;
                        if(userNativeLCCode.second == taskSourceLocale.countrycode()) {
                            score += 75;
                        }
                    }

                    Locale taskTargetLocale = task->targetlocale();

                    if(userNativeLCCode.first == taskTargetLocale.languagecode()) {
                        score += 1000;
                        if(userNativeLCCode.second == taskTargetLocale.countrycode()) {
                            score += 100;
                        }
                    }

                    if(userSecondaryLanguages.contains(usersIter.key())) {
                        const QList<LCCode> lcCodes = userSecondaryLanguages.values(usersIter.key());
                        if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), LidMatch(taskSourceLocale.languagecode()))) {
                            score += 500;
                            if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), CidMatch(taskSourceLocale.countrycode())) ) {
                                score += 50;
                            }
                        }
                        if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), LidMatch(taskTargetLocale.languagecode()))) {
                            score += 500;
                            if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), CidMatch(taskTargetLocale.countrycode())) ) {
                                score += 50;
                            }
                        }
                    }

                    if(userTags.contains(usersIter.key()) && taskTags.contains(task->id())) {
                        int increment_value = 250;
                        QList<int> userTagIds = userTags.values(usersIter.key());
                        QList<int> userTaskTagIds = taskTags.values(task->id());

                        foreach(int userTagId, userTagIds) {
                            if(userTaskTagIds.contains(userTagId)) {
                                    score += increment_value;
                                    increment_value *= 0.75;
                            }
                        }
                    }

                    QDateTime created_time = QDateTime::fromString(
                                            QString::fromStdString(task->createdtime()), Qt::ISODate);
                    //increase score by one per day since created time
                    score += created_time.daysTo(QDateTime::currentDateTime());
                    taskScores.append(TaskScore(task->id(), score));
                }

                    this->saveUserTaskScore(usersIter.key(),taskScores);

            } else {
QList<ShopTemplateManager::ShopTemplateSection> ShopTemplateManager::FetchFromItemsKey(const QString &key, const Items &items, QHash<QString, QString> *options) {
    QList<ShopTemplateManager::ShopTemplateSection> result;
    if (items.size() > 0){
        Items matchingItems;

        bool includeNoBuyouts = options->contains("include.ignored");
        ShopTemplateContainType containType = CONTAIN_TYPE_NONE;

        if (key == "everything") {
            matchingItems = items;
        }
        else if (key.startsWith("stash:")) {
            int index = key.indexOf(":");
            QString name = (index + 1 >= key.length()) ? "" : key.mid(index + 1);
            if (!name.isEmpty()) {
                for (const std::shared_ptr<Item> &item : items) {
                    if (QString::fromStdString(item->location().GetLabel()).compare(name, Qt::CaseInsensitive) == 0) {
                        matchingItems.push_back(item);
                    }
                }
            }
        }
        else {
            Items pool = items;
            QStringList keyParts = key.split("+", QString::SkipEmptyParts);
            for (QString part : keyParts) {
                if (templateMatchers.contains(part)) {
                    matchingItems = FindMatchingItems(pool, part);
                }
                else {
                    // todo(novynn): phase these out? Prefer {Normal+Helmet} over {NormalHelmet}
                    bool matchedRarity = false;
                    const QStringList rarities = {"normal", "magic", "rare", "unique"};
                    for (QString rarity : rarities) {
                        if (part.startsWith(rarity)) {
                            QString type = part.mid(rarity.length());

                            matchingItems = FindMatchingItems(pool, rarity);
                            matchingItems = FindMatchingItems(matchingItems, type);
                            matchedRarity = true;
                        }
                    }

                    if (matchedRarity) continue;

                    if (part.endsWith("gems")) {
                        if (part == "gems" || part == "allgems") {
                            matchingItems = FindMatchingItems(pool, "gems");
                        }
                        else {
                            const QStringList gemTypes = {"AoE", "Attack", "Aura", "Bow", "Cast", "Chaining", "Chaos",
                                                          "Cold", "Curse", "Duration", "Fire", "Lightning", "Melee", "Mine", "Minion",
                                                          "Movement", "Projectile", "Spell", "Totem", "Trap", "Support"};
                            for (QString gemType : gemTypes) {
                                if (!part.startsWith(gemType, Qt::CaseInsensitive)) continue;

                                // This will never just be first key (?)
                                QString firstKey = gemType.toLower() + "gems";
                                matchingItems = FindMatchingItems(pool, firstKey);

                                if (part != firstKey) {
                                    // supportlightninggems
                                    QString secondKey = part.mid(gemType.length());
                                    matchingItems = FindMatchingItems(matchingItems, secondKey);
                                }
                            }
                        }
                    }
                }
                pool = matchingItems;
            }
        }

        // Only select items from your stash unless specified
        if (!options->contains("include.character")) {
            matchingItems = Items::fromStdVector(
                        from(matchingItems.toStdVector())
                        .where([](const std::shared_ptr<Item> item) { return item->location().type() == ItemLocationType::STASH; })
                        .toVector()
                     );
        }

        if (matchingItems.size() == 0)
            return result;

        if (containType == CONTAIN_TYPE_NONE && options->contains("wrap")) containType = CONTAIN_TYPE_WRAP;
        if (containType == CONTAIN_TYPE_NONE && options->contains("group")) containType = CONTAIN_TYPE_GROUP;

        switch (containType) {
            case (CONTAIN_TYPE_WRAP): {
                QString header = "Items";
                Buyout buyout = {};

                if (options->contains("header")) {
                    header = options->value("header");
                }

                const std::shared_ptr<Item> first = matchingItems.first();
                if (parent_->buyout_manager().Exists(*first)) buyout = parent_->buyout_manager().Get(*first);

                bool sameBuyout = from(matchingItems.toStdVector()).all([this, buyout](const std::shared_ptr<Item> item) {
                    Buyout thisBuyout = {};
                    if (parent_->buyout_manager().Exists(*item)) thisBuyout = parent_->buyout_manager().Get(*item);
                    return BuyoutManager::Equal(thisBuyout, buyout);
                });

                if (sameBuyout) {
                    header += BuyoutManager::Generate(buyout);
                }

                QStringList temp = WriteItems(matchingItems, !sameBuyout, includeNoBuyouts);
                if (!temp.isEmpty()) {
                    result << ShopTemplateSection(temp, SECTION_TYPE_SPOILER, header);
                }
                break;
            }
            case CONTAIN_TYPE_GROUP: {
                QMultiMap<QString, std::shared_ptr<Item>> itemsMap;

                for (auto &item : matchingItems) {
                    Buyout b = {};
                    if (parent_->buyout_manager().Exists(*item))
                        b = parent_->buyout_manager().Get(*item);
                    itemsMap.insert(BuyoutManager::Generate(b), item);
                }

                for (QString buyout : itemsMap.uniqueKeys()) {
                    Items itemList = itemsMap.values(buyout).toVector();
                    if (itemList.size() == 0)
                        continue;
                    QString header = buyout;
                    if (header.isEmpty()) header = "Offers Accepted";
                    QStringList temp = WriteItems(itemList, false, includeNoBuyouts);
                    if (temp.isEmpty())
                        continue;

                    result << ShopTemplateSection(temp, SECTION_TYPE_SPOILER, header);
                }
                break;
            }
            default: {
                QStringList temp = WriteItems(matchingItems, true, includeNoBuyouts);
                result << ShopTemplateSection(temp, SECTION_TYPE_NONE);
                break;
            }
        }
    }

    return result;
}