Esempio n. 1
0
void MScenePrivate::onDisplayChangeEvent(MOnDisplayChangeEvent *event)
{
    Q_Q(MScene);

    if (event->state() == MOnDisplayChangeEvent::FullyOnDisplay ||
            event->state() == MOnDisplayChangeEvent::FullyOffDisplay) {
        // Simple cases. Just forward the event as it is.
        sendEventToMWidgets(filterMWidgets(q->items()), event);
        return;
    }

    QList<MWidget *> fullyOnWidgets;
    QList<MWidget *> partiallyOnWidgets;
    QList<MWidget *> fullyOffWidgets;

    QList<MWidget *> intersectingWidgets = filterMWidgets(q->items(event->viewRect(),
            Qt::IntersectsItemBoundingRect));

    QList<MWidget *> allWidgets = filterMWidgets(q->items());

    // Find who is fully on, partially on and fully off

    QSet<MWidget *> fullyOffWidgetsSet = allWidgets.toSet().subtract(intersectingWidgets.toSet());
    fullyOffWidgets = fullyOffWidgetsSet.toList();

    int intersectingWidgetsCount = intersectingWidgets.count();
    MWidget *widget;
    for (int i = 0; i < intersectingWidgetsCount; i++) {
        widget = intersectingWidgets.at(i);
        if (event->viewRect().contains(widget->sceneBoundingRect())) {
            fullyOnWidgets << widget;
        } else {
            partiallyOnWidgets << widget;
        }
    }

    // Send the events to the corresponding MWidgets

    if (fullyOnWidgets.count() > 0) {
        MOnDisplayChangeEvent fullyOnEvent(MOnDisplayChangeEvent::FullyOnDisplay,
                                             event->viewRect());

        sendEventToMWidgets(fullyOnWidgets, &fullyOnEvent);
    }

    if (fullyOffWidgets.count() > 0) {
        MOnDisplayChangeEvent fullyOffEvent(MOnDisplayChangeEvent::FullyOffDisplay,
                                              event->viewRect());

        sendEventToMWidgets(fullyOffWidgets, &fullyOffEvent);
    }

    if (partiallyOnWidgets.count() > 0) {
        MOnDisplayChangeEvent partiallyOnEvent(MOnDisplayChangeEvent::PartiallyOnDisplay,
                event->viewRect());

        sendEventToMWidgets(partiallyOnWidgets, &partiallyOnEvent);
    }

}
Esempio n. 2
0
bool Engine::selectFormat()
{
    bool foundSupportedFormat = false;

    if (m_file || QAudioFormat() != m_format) {
        QAudioFormat format = m_format;
        if (m_file)
            // Header is read from the WAV file; just need to check whether
            // it is supported by the audio output device
            format = m_file->fileFormat();
        if (m_audioOutputDevice.isFormatSupported(format)) {
            setFormat(format);
            foundSupportedFormat = true;
        }
    } else {

        QList<int> sampleRatesList;

        if (!m_generateTone)

            sampleRatesList += m_audioOutputDevice.supportedSampleRates();
        sampleRatesList = sampleRatesList.toSet().toList(); // remove duplicates
        qSort(sampleRatesList);
        ENGINE_DEBUG << "Engine::initialize frequenciesList" << sampleRatesList;

        QList<int> channelsList;
        channelsList += m_audioOutputDevice.supportedChannelCounts();
        channelsList = channelsList.toSet().toList();
        qSort(channelsList);
        ENGINE_DEBUG << "Engine::initialize channelsList" << channelsList;

        QAudioFormat format;
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setCodec("audio/pcm");
        format.setSampleSize(16);
        format.setSampleType(QAudioFormat::SignedInt);
        int sampleRate, channels;
        foreach (sampleRate, sampleRatesList) {
            if (foundSupportedFormat)
                break;
            format.setSampleRate(sampleRate);
            foreach (channels, channelsList) {
                format.setChannelCount(channels);
                const bool outputSupport = m_audioOutputDevice.isFormatSupported(format);
                ENGINE_DEBUG << "Engine::initialize checking " << format
                             << "output" << outputSupport;
                if (outputSupport)
                {
                    foundSupportedFormat = true;
                    break;
                }
            }
        }

        if (!foundSupportedFormat)
            format = QAudioFormat();

        setFormat(format);
    }
void SelectProfileWidget::updateProfiles()
{
	IDiscoIdentity identity;
	identity.category = "gateway";
	identity.type = FDescriptor.type;

	QList<Jid> nativeGates;
	if (FDescriptor.id == GSID_RAMBLER)
		nativeGates.append(streamJid());

	QList<Jid> gates = FGateways->gateDescriptorServices(streamJid(),FDescriptor,FDescriptor.needLogin);
	for (QList<Jid>::iterator it=gates.begin(); it!=gates.end(); )
	{
		if (!(FGateways->serviceRestrictions(streamJid(),*it) & GSR_ADD_CONTACT))
		{
			IGateServiceDescriptor descriptor = FGateways->serviceDescriptor(streamJid(),*it);
			if (FDescriptor.id == descriptor.id)
				nativeGates.append(*it);
			it++;
		}
		else
		{
			it = gates.erase(it);
		}
	}

	Jid oldSelected = selectedProfile();
	QList<Jid> newProfiles = (gates.toSet() - FProfiles.keys().toSet()).toList();
	QList<Jid> oldProfiles = (FProfiles.keys().toSet() - gates.toSet()).toList();

	qSort(newProfiles);
	if (!FDescriptor.needGate && !FProfiles.contains(streamJid()))
		newProfiles.prepend(streamJid());
	else if (FDescriptor.needGate && FProfiles.contains(streamJid()))
		oldProfiles.prepend(streamJid());
	else
		oldProfiles.removeAll(streamJid());

	foreach(Jid serviceJid, newProfiles)
	{
		QRadioButton *button = new QRadioButton(ui.wdtProfiles);
		button->setAutoExclusive(true);
		connect(button,SIGNAL(toggled(bool)),SLOT(onProfileButtonToggled(bool)));
		FProfiles.insert(serviceJid,button);

		QLabel *label = new QLabel(ui.wdtProfiles);
		connect(label,SIGNAL(linkActivated(const QString &)),SLOT(onProfileLabelLinkActivated(const QString &)));
		FProfileLabels.insert(serviceJid,label);

		QHBoxLayout *layout = new QHBoxLayout();
		layout->setMargin(0);
		layout->setSpacing(0);
		layout->addWidget(button);
		layout->addWidget(label);
		layout->addStretch();
		qobject_cast<QVBoxLayout *>(ui.wdtProfiles->layout())->addLayout(layout);
	}
Esempio n. 4
0
void AutoProfileWatcher::clearProfileAssignments()
{
    QSet<AutoProfileInfo*> terminateProfiles;

    QListIterator<QList<AutoProfileInfo*> > iterDelete(appProfileAssignments.values());
    while (iterDelete.hasNext())
    {
        QList<AutoProfileInfo*> templist = iterDelete.next();
        terminateProfiles.unite(templist.toSet());
    }
    appProfileAssignments.clear();

    QListIterator<QList<AutoProfileInfo*> > iterClassDelete(windowClassProfileAssignments.values());
    while (iterClassDelete.hasNext())
    {
        QList<AutoProfileInfo*> templist = iterClassDelete.next();
        terminateProfiles.unite(templist.toSet());
    }
    windowClassProfileAssignments.clear();

    QListIterator<QList<AutoProfileInfo*> > iterNameDelete(windowNameProfileAssignments.values());
    while (iterNameDelete.hasNext())
    {
        QList<AutoProfileInfo*> templist = iterNameDelete.next();
        terminateProfiles.unite(templist.toSet());
    }
    windowNameProfileAssignments.clear();

    QSetIterator<AutoProfileInfo*> iterTerminate(terminateProfiles);
    while (iterTerminate.hasNext())
    {
        AutoProfileInfo *info = iterTerminate.next();
        if (info)
        {
            delete info;
            info = 0;
        }
    }

    QListIterator<AutoProfileInfo*> iterDefaultsDelete(defaultProfileAssignments.values());
    while (iterDefaultsDelete.hasNext())
    {
        AutoProfileInfo *info = iterDefaultsDelete.next();
        if (info)
        {
            delete info;
            info = 0;
        }
    }
    defaultProfileAssignments.clear();

    allDefaultInfo = 0;
    guidSet.clear();
}
Esempio n. 5
0
void tst_QList::toSet() const
{
    QList<QString> list;
    list << "foo" << "bar" << "baz";

    // no duplicates
    QCOMPARE(list.toSet(), QSet<QString>() << "foo" << "bar" << "baz");
    QCOMPARE(list, QList<QString>() << "foo" << "bar" << "baz");

    // duplicates (is this more of a QSet test?)
    list << "foo" << "bar" << "baz";
    QCOMPARE(list.toSet(), QSet<QString>() << "foo" << "bar" << "baz");
    QCOMPARE(list, QList<QString>() << "foo" << "bar" << "baz" << "foo" << "bar" << "baz");
}
Esempio n. 6
0
void SubgraphMatching::cut(Solution *sol, CutMethod cm) {
    LinearConstraint *c;
    QList<Variable *> vars = sol->getVariables().keys();
    switch(cm) {
        case SOLUTION:
            c = new LinearConstraint(LinearExpression::sum(vars), Constraint::LESS_EQ, vars.size() - 1);
            break;
        case MATCHINGS:
            c = new LinearConstraint(LinearExpression::sum(vars), Constraint::EQUAL, 0);
            break;
        case ELEMENTS: {
            QStringList sl;
            QSet<Variable *> vset = vars.toSet();
            for(auto s : vars) {
                if(s->getID().startsWith("x")) {
                    sl = s->getID().mid(2).split(',');
                    for(auto v : x_variables.getCol(sl[1].toInt())) {
                        vset.insert(v);
                    }
                }
            }
            c = new LinearConstraint(LinearExpression::sum(vset.toList()), Constraint::EQUAL, 0);
            break;
        }
        default:
            break;
    }
    *lp_ += c;
}
Esempio n. 7
0
bool BloombergVector::SetVector(const QList<QDate>& Dates, const QList<double>& Values) {
    Q_D(BloombergVector);
	if (
		Dates.size() != Values.size() //Each date has a value and vice versa
		|| Values.isEmpty() //The vectors are not empty
		|| Dates.toSet().size()!=Dates.size() //There are no duplicates in the dates
	) return false;
	QMap<QDate, double> SortedValues;
	for (int i = 0; i <Dates.size(); i++) {
		if (Dates.at(i).isNull())
            return false;
		if (Values.at(i)<0.0)
            return false;
		SortedValues.insert(Dates.at(i), Values.at(i));
	}
	d->m_AnchorDate = SortedValues.firstKey();
    d->m_VectVal.clear();
	int NumMonths;
	for (auto i = SortedValues.constBegin()+1; i != SortedValues.constEnd(); i++) {
		NumMonths = MonthDiff(i.key(), (i - 1).key());
		for (int j = 0; j < NumMonths; j++)
            d->m_VectVal.append((i - 1).value());
	}
    d->m_VectVal.append(SortedValues.last());

	RepackVector();
	return true;
}
Esempio n. 8
0
QOpenGLExtensionMatcher::QOpenGLExtensionMatcher()
{
    QOpenGLContext *ctx = QOpenGLContext::currentContext();
    QOpenGLFunctions *funcs = ctx->functions();
    const char *extensionStr = 0;

    if (ctx->isOpenGLES() || ctx->format().majorVersion() < 3)
        extensionStr = reinterpret_cast<const char *>(funcs->glGetString(GL_EXTENSIONS));

    if (extensionStr) {
        QByteArray ba(extensionStr);
        QList<QByteArray> extensions = ba.split(' ');
        m_extensions = extensions.toSet();
    } else {
#ifdef QT_OPENGL_3
        // clear error state
        while (funcs->glGetError()) {}

        if (ctx) {
            qt_glGetStringi glGetStringi = (qt_glGetStringi)ctx->getProcAddress("glGetStringi");

            if (!glGetStringi)
                return;

            GLint numExtensions;
            funcs->glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);

            for (int i = 0; i < numExtensions; ++i) {
                const char *str = reinterpret_cast<const char *>(glGetStringi(GL_EXTENSIONS, i));
                m_extensions.insert(str);
            }
        }
#endif // QT_OPENGL_3
    }
}
Esempio n. 9
0
QMimeData *MsgListModel::mimeData(const QModelIndexList &indexes) const
{
    if (indexes.isEmpty())
        return 0;

    QMimeData *res = new QMimeData();
    QByteArray encodedData;
    QDataStream stream(&encodedData, QIODevice::WriteOnly);
    stream.setVersion(QDataStream::Qt_4_6);

    TreeItemMailbox *mailbox = dynamic_cast<TreeItemMailbox *>(Model::realTreeItem(
                                   indexes.front())->parent()->parent());
    Q_ASSERT(mailbox);
    stream << mailbox->mailbox() << mailbox->syncState.uidValidity();

    QList<uint> uids;
    for (QModelIndexList::const_iterator it = indexes.begin(); it != indexes.end(); ++it) {
        TreeItemMessage *message = dynamic_cast<TreeItemMessage *>(Model::realTreeItem(*it));
        Q_ASSERT(message);
        Q_ASSERT(message->parent()->parent() == mailbox);
        Q_ASSERT(message->uid() > 0);
        uids << message->uid();
    }
    uids = uids.toSet().toList();
    stream << uids;
    res->setData(QLatin1String("application/x-trojita-message-list"), encodedData);
    return res;
}
Esempio n. 10
0
    void shouldCallHandlersWithJob()
    {
        // GIVEN
        int callCount = 0;
        QList<KJob*> seenJobs;

        auto handlerWithJob = [&](KJob *job) {
            callCount++;
            seenJobs << job;
        };

        FakeJob *job1 = new FakeJob(this);
        FakeJob *job2 = new FakeJob(this);
        CompositeJob *compositeJob = new CompositeJob(this);
        compositeJob->setAutoDelete(false);
        QVERIFY(compositeJob->install(job1, handlerWithJob));
        QVERIFY(compositeJob->install(job2, handlerWithJob));

        // WHEN
        compositeJob->start();
        QTest::qWait(FakeJob::DURATION + 10);

        // THEN
        QCOMPARE(callCount, 2);
        QCOMPARE(seenJobs.toSet(), QSet<KJob*>() << job1 << job2);
        QVERIFY(!compositeJob->error());
        delete compositeJob;
    }
Esempio n. 11
0
void
SourceFileModel::removeFiles(QList<SourceFile *> const &files) {
  auto filesToRemove  = files.toSet();
  auto tracksToRemove = QSet<Track *>{};

  for (auto const &file : files) {
    for (auto const &track : file->m_tracks)
      tracksToRemove << track.get();

    for (auto const &appendedFile : file->m_appendedFiles) {
      filesToRemove << appendedFile.get();
      for (auto const &track : appendedFile->m_tracks)
        tracksToRemove << track.get();
    }
  }

  m_tracksModel->reDistributeAppendedTracksForFileRemoval(filesToRemove);
  m_tracksModel->removeTracks(tracksToRemove);

  auto filesToRemoveLast = QList<SourceFile *>{};
  for (auto &file : filesToRemove)
    if (!file->isRegular())
      removeFile(file);
    else
      filesToRemoveLast << file;

  for (auto &file : filesToRemoveLast)
    if (file->isRegular())
      removeFile(file);
}
Esempio n. 12
0
void AnchorTool::itemsAboutToRemoved(const QList<FormEditorItem*> &removedItems)
{
    QList<FormEditorItem*> newItemList = items().toSet().subtract(removedItems.toSet()).toList();
    setItems(newItemList);
    m_anchorIndicator.setItems(newItemList);
    m_anchorLineIndicator.clear();
}
Esempio n. 13
0
MessageFilter::MessageFilter(MessageModel *source, const QList<BufferId> &buffers, QObject *parent)
  : QSortFilterProxyModel(parent),
    _validBuffers(buffers.toSet()),
    _messageTypeFilter(0)
{
  init();
  setSourceModel(source);
}
void AddLegacyAccountOptions::onServicesChanged(const Jid &AStreamJid)
{
	if (FStreamJid == AStreamJid)
	{
		QList<Jid> availRegisters = FGateways->availRegistrators(AStreamJid,true);
		foreach(Jid serviceJid, availRegisters.toSet() - FWidgets.keys().toSet())
			appendServiceButton(serviceJid);
		foreach(Jid serviceJid, FWidgets.keys().toSet() - availRegisters.toSet())
			removeServiceButton(serviceJid);

		if (FWidgets.isEmpty())
			ui.lblInfo->setText(tr("All available accounts are already linked"));
		ui.lblInfo->setVisible(FWidgets.isEmpty());

		emit updated();
	}
}
Esempio n. 15
0
void DraftsModel::setFilterGroups(const QList<int> &list)
{
    Q_D(DraftsModel);
    QSet<int> groupIds = list.toSet();
    if (groupIds == d->filterGroups)
        return;

    d->filterGroups = groupIds;
    emit filterGroupsChanged();
}
Esempio n. 16
0
 bool setData(int column, const QVariant &data, int role)
 {
     if (column == LoadedColumn && role == Qt::CheckStateRole) {
         const QList<PluginSpec *> affectedPlugins =
                 Utils::filtered(m_plugins, [](PluginSpec *spec) { return !spec->isRequired(); });
         if (m_view->setPluginsEnabled(affectedPlugins.toSet(), data.toBool())) {
             update();
             return true;
         }
     }
     return false;
 }
void VcsFileChangesModel::checkUrls(QStandardItem *parent, const QList<KUrl>& urls) const
{
    QSet<KUrl> urlSet(urls.toSet());

    if(!d->allowSelection)
        return;

    for(int i = 0; i < parent->rowCount(); i++) {
        QStandardItem* item = parent->child(i);
        item->setCheckState(urlSet.contains(statusInfo(item).url()) ? Qt::Checked : Qt::Unchecked);
    }
}
Esempio n. 18
0
    void testFindingTables()
    {
        // How to find all the tables in a QTextDocument?
        QTextDocument textDoc;
        QTextCursor c( &textDoc );
        QTextTable* firstTable = c.insertTable( 2, 2 );
        QTextTableCell bottomRight = firstTable->cellAt( 1, 1 );
        QTextTable* secondTable = bottomRight.firstCursorPosition().insertTable( 3, 3 ); // a nested table
        c.movePosition( QTextCursor::End );
        QTextTable* thirdTable = c.insertTable( 1, 1 );
        thirdTable->firstCursorPosition().insertText( "in table" );
        c.insertText( "Foo" );
        QList<QTextTable *> origTables;
        origTables << firstTable << secondTable << thirdTable;

        // A generic and slow solution is
        //    curs.currentTable() && !tablesFound.contains(curs.currentTable())
        // for each cursor position. Surely there's better.
        // We could jump to currentFrame().lastCursorPosition() but then it would skip
        // nested tables.
        QTextDocument* clonedDoc = textDoc.clone();
        QSet<QTextTable *> tablesFound;
        {
            QTextCursor curs(clonedDoc);
            while (!curs.atEnd()) {
                QTextTable* currentTable = curs.currentTable();
                if ( currentTable && !tablesFound.contains(currentTable) ) {
                    tablesFound.insert( currentTable );
                }
                curs.movePosition( QTextCursor::NextCharacter );
            }
            QCOMPARE( tablesFound.size(), 3 );
        }

        // Let's do something else then, let's find them by cursor position
        QList<QTextTable *> tablesByPos;
        {
            // first test
            const int firstPos = firstTable->firstCursorPosition().position();
            QTextCursor curs( clonedDoc );
            curs.setPosition( firstPos );
            QVERIFY( curs.currentTable() );

            // generic loop. works this approach is in TextDocument::breakTables now.
            Q_FOREACH( QTextTable* origTable, origTables ) {
                QTextCursor curs( clonedDoc );
                curs.setPosition( origTable->firstCursorPosition().position() );
                tablesByPos.append( curs.currentTable() );
            }
            QCOMPARE( tablesByPos.size(), 3 );
            QCOMPARE( tablesByPos.toSet(), tablesFound );
        }
Esempio n. 19
0
void setSidebarUrls (QFileDialog *fd, QString dir)
{
  QList<QUrl> urls;
  urls = fd->sidebarUrls ();
  urls += QUrl::fromLocalFile (QDir (dir).absolutePath ());
  urls += QUrl::fromLocalFile (QDir (".").absolutePath ());


  //  QSet will get rid of duplicates.

  QSet<QUrl> set = urls.toSet ();
  urls = set.toList ();


  //  Sort them.

  qSort (urls);


  //  Get rid of nonexistant URLs.

  NV_BOOL *kill_list = new NV_BOOL[urls.size ()];

  for (NV_INT32 i = 0 ; i < urls.size () ; i++)
    {
      kill_list[i] = NVFalse;

      if (!urls.at (i).path ().isEmpty () && urls.at (i).toString ().contains ("file:"))
        {
          QFileInfo qf = QFileInfo (urls.at (i).path ());
          if (!qf.exists ()) kill_list[i] = NVTrue;
        }
    }

  NV_INT32 loop = urls.size ();
  for (NV_INT32 i = loop ; i >= 0 ; i--)
    {
      if (kill_list[i]) urls.removeAt (i);
    }

  delete (kill_list);


  //  Set the sidebarUrls.

  fd->setSidebarUrls (urls);


  //  Set the directory to the last used directory.

  fd->setDirectory (QDir (dir).absolutePath ());
}
Esempio n. 20
0
void loadUserCaCertificate()
{
    QList<QSslCertificate> certificates;
    const std::vector<QByteArray> certs = utils::mac::getSystemCaCertificates();
    for (unsigned i = 0; i < certs.size(); ++i)
    {
        certificates.append(QSslCertificate::fromData(certs[i], QSsl::Der));
    }

    // remove duplicates
    certificates = certificates.toSet().toList();

    QSslSocket::setDefaultCaCertificates(certificates);
}
Esempio n. 21
0
void QgsColorSchemeList::removeSelection()
{
  QList<int> rows;
  foreach ( const QModelIndex &index, selectedIndexes() )
  {
    rows << index.row();
  }
  //remove duplicates
  QList<int> rowsToRemove =  QList<int>::fromSet( rows.toSet() );

  //remove rows in descending order
  qSort( rowsToRemove.begin(), rowsToRemove.end(), qGreater<int>() );
  foreach ( const int row, rowsToRemove )
  {
    mModel->removeRow( row );
  }
Esempio n. 22
0
void
KMixWindow::loadBaseConfig()
{
  KConfigGroup config(KGlobal::config(), "Global");

//  GlobalConfig& gcfg = GlobalConfig::instance();
  GlobalConfigData& gcd = GlobalConfig::instance().data;

  QList<QString> preferredMixersInSoundMenu;
  preferredMixersInSoundMenu = config.readEntry("Soundmenu.Mixers", preferredMixersInSoundMenu);
  GlobalConfig::instance().setMixersForSoundmenu(preferredMixersInSoundMenu.toSet());

  setBeepOnVolumeChange(gcd.volumeFeedback);
  m_startVisible = config.readEntry("Visible", false);
  m_multiDriverMode = config.readEntry("MultiDriver", false);
  m_defaultCardOnStart = config.readEntry("DefaultCardOnStart", "");
  m_configVersion = config.readEntry("ConfigVersion", 0);
  // WARNING Don't overwrite m_configVersion with the "correct" value, before having it
  // evaluated. Better only write that in saveBaseConfig()
  m_autouseMultimediaKeys = config.readEntry("AutoUseMultimediaKeys", true);
  QString mixerMasterCard = config.readEntry("MasterMixer", "");
  QString masterDev = config.readEntry("MasterMixerDevice", "");
  Mixer::setGlobalMaster(mixerMasterCard, masterDev, true);
  QString mixerIgnoreExpression = config.readEntry("MixerIgnoreExpression",
      "Modem");
  MixerToolBox::instance()->setMixerIgnoreExpression(mixerIgnoreExpression);

  // --- Advanced options, without GUI: START -------------------------------------
  QString volumePercentageStepString = config.readEntry("VolumePercentageStep");
  if (!volumePercentageStepString.isNull())
    {
      float volumePercentageStep = volumePercentageStepString.toFloat();
      if (volumePercentageStep > 0 && volumePercentageStep <= 100)
        Volume::VOLUME_STEP_DIVISOR = (100 / volumePercentageStep);
    }

  // --- Advanced options, without GUI: END -------------------------------------

  m_backendFilter = config.readEntry<>("Backends", QList<QString>());
  kDebug() << "Backends: " << m_backendFilter;

  // show/hide menu bar
  bool showMenubar = config.readEntry("Menubar", true);

  if (_actionShowMenubar)
    _actionShowMenubar->setChecked(showMenubar);
}
Esempio n. 23
0
QList<QString> BrisaConfigurationManager::getSectionNames() {

    if (this->getDirectAccess())
        this->update();

    QList<QString> sections = this->state.keys();

    for (int i = 0; i < sections.size(); ++i) {
        sections.replace(i, sections.at(i).split('.').value(0));
    }

    QSet<QString> set = sections.toSet();
    QList<QString> auxList = set.toList();
    qSort(auxList.begin(), auxList.end());

    return auxList;
}
Esempio n. 24
0
/**
  * Return true if one or more download have been paused or unpaused.
  */
bool DownloadQueue::pauseDownloads(QList<quint64> IDs, bool pause)
{
   QSet<quint64> IDsRemaining(IDs.toSet());

   bool stateChanged = false;

   for (QListIterator<Download*> i(this->downloads); i.hasNext() && !IDsRemaining.isEmpty();)
   {
      Download* download = i.next();
      if (IDsRemaining.remove(download->getID()))
      {
         if (download->pause(pause))
            stateChanged = true;
      }
   }

   return stateChanged;
}
void LiveRubberBandSelectionManipulator::select(SelectionType selectionType)
{
    QDeclarativeViewInspectorPrivate *inspectorPrivate
            = QDeclarativeViewInspectorPrivate::get(m_editorView);
    QList<QGraphicsItem*> itemList
            = inspectorPrivate->selectableItems(m_selectionRectangleElement.rect(),
                                               Qt::IntersectsItemShape);
    QList<QGraphicsItem*> newSelectionList;

    foreach (QGraphicsItem* item, itemList) {
        if (item
                && item->parentItem()
                && !newSelectionList.contains(item)
                //&& m_beginFormEditorItem->childItems().contains(item) // TODO activate this test
                )
        {
            newSelectionList.append(item);
        }
    }

    if (newSelectionList.isEmpty() && m_beginFormEditorItem)
        newSelectionList.append(m_beginFormEditorItem);

    QList<QGraphicsItem*> resultList;

    switch(selectionType) {
    case AddToSelection: {
        resultList.append(m_oldSelectionList);
        resultList.append(newSelectionList);
    }
        break;
    case ReplaceSelection: {
        resultList.append(newSelectionList);
    }
        break;
    case RemoveFromSelection: {
        QSet<QGraphicsItem*> oldSelectionSet(m_oldSelectionList.toSet());
        QSet<QGraphicsItem*> newSelectionSet(newSelectionList.toSet());
        resultList.append(oldSelectionSet.subtract(newSelectionSet).toList());
    }
    }

    m_editorView->setSelectedItems(resultList);
}
Esempio n. 26
0
QString GEF::asRobertson(const float interval)
{
    QString result = "";
    QList<GEFLayer> layers;
    QList<int> ids;

    //step 1, break into interval sized soillayers and find common soiltype
    GEFLayer layer;
    layer.van = m_depth[0];
    for(int i=1; i<m_depth.count(); i++){
        layer.tot = m_depth[i];
        if(qFabs(layer.van - layer.tot) > interval){
            QSet<int> set = ids.toSet();
            layer.id = -1;
            int maxcount = 0;

            foreach (int id, set){
                int count = 0;
                for(int j=0; j<ids.count(); j++){
                    if(ids[j] == id) count++;
                }
                if(count > maxcount){
                    layer.id = id;
                    maxcount = count;
                }
            }

            if(layer.id==-1){
                //probably missing values (columnvoid values?) > use previous soil layer
                //give feedback
                if(layers.count()>0){
                    layer.id = layers[layers.count()-1].id;
                }else{
                    //first layer, we do not accept bad info there
                    qFatal(QString("Error, id -1 found in GEF %0").arg(getShortName()).toStdString().c_str());
                }
            }

            layers.append(layer);
            ids.clear();
            layer.van = layer.tot;
        }else{
Esempio n. 27
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();
	}
}
Esempio n. 28
0
void Domain::constructNewDomainFromTermInLiteral(short int arityOfInput)
{
    int ie = 0;

    for(QList<QList<QMultiHash<int, int> > >::iterator iexample = termInLiteral.begin(); iexample != termInLiteral.end(); ++iexample)
    {
        if(this->maksOfEmptyDomain.testBit(ie))
        {
            termOccurences4Examples[ie].clear();
            ie++;
            continue;
        }
        QList<int> inputdomain = findDomainInInputForExample(ie, arityOfInput);

        //remove duplicities
        QSet<int> mys = inputdomain.toSet();
        inputdomain = mys.toList();

        int termsize = 0;
        for(QList<int>::iterator itermid = inputdomain.begin(); itermid != inputdomain.end(); ++itermid)
        {
            int pos = *itermid;
            QString nameterm = myExamples->getTermText(pos);
            if((*itermid) > termsize)
                termsize = (*itermid);
        }

        this->termOccurences4Examples[ie].resize(termsize+1);
        for(QList<int>::iterator itermid = inputdomain.begin(); itermid != inputdomain.end(); ++itermid)
        {
            this->termOccurences4Examples[ie].setBit((*itermid), true);
        }

        ie++;
    }
    //termInLiteral.clear();
    //lookupTermInLiteral.clear();
}
Esempio n. 29
0
void QgsOverlayAnalyzer::intersectFeature( QgsFeature &f, QgsVectorFileWriter *vfw,
    QgsVectorLayer *vl, QgsSpatialIndex *index )
{
  if ( !f.hasGeometry() )
  {
    return;
  }

  QgsGeometry featureGeometry = f.geometry();
  QgsGeometry intersectGeometry;
  QgsFeature overlayFeature;

  QList<QgsFeatureId> intersects = index->intersects( featureGeometry.boundingBox() );
  QgsFeatureRequest req = QgsFeatureRequest().setFilterFids( intersects.toSet() );
  QgsFeatureIterator intersectIt = vl->getFeatures( req );
  QgsFeature outFeature;
  while ( intersectIt.nextFeature( overlayFeature ) )
  {
    if ( featureGeometry.intersects( overlayFeature.geometry() ) )
    {
      intersectGeometry = featureGeometry.intersection( overlayFeature.geometry() );

      outFeature.setGeometry( intersectGeometry );
      QgsAttributes attributesA = f.attributes();
      QgsAttributes attributesB = overlayFeature.attributes();
      combineAttributeMaps( attributesA, attributesB );
      outFeature.setAttributes( attributesA );

      //add it to vector file writer
      if ( vfw )
      {
        vfw->addFeature( outFeature );
      }
    }
  }
}
Esempio n. 30
0
bool Engine::selectFormat()
{
    bool foundSupportedFormat = false;

    if (m_file || QAudioFormat() != m_format) {
        QAudioFormat format = m_format;
        if (m_file)
            // Header is read from the WAV file; just need to check whether
            // it is supported by the audio output device
            format = m_file->fileFormat();
        if (m_audioOutputDevice.isFormatSupported(format)) {
            setFormat(format);
            foundSupportedFormat = true;
        }
    } else {

        QList<int> sampleRatesList;
    #ifdef Q_OS_WIN
        // The Windows audio backend does not correctly report format support
        // (see QTBUG-9100).  Furthermore, although the audio subsystem captures
        // at 11025Hz, the resulting audio is corrupted.
        sampleRatesList += 8000;
    #endif

        if (!m_generateTone)
            sampleRatesList += m_audioInputDevice.supportedSampleRates();

        sampleRatesList += m_audioOutputDevice.supportedSampleRates();
        sampleRatesList = sampleRatesList.toSet().toList(); // remove duplicates
        qSort(sampleRatesList);
        ENGINE_DEBUG << "Engine::initialize frequenciesList" << sampleRatesList;

        QList<int> channelsList;
        channelsList += m_audioInputDevice.supportedChannelCounts();
        channelsList += m_audioOutputDevice.supportedChannelCounts();
        channelsList = channelsList.toSet().toList();
        qSort(channelsList);
        ENGINE_DEBUG << "Engine::initialize channelsList" << channelsList;

        QAudioFormat format;
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setCodec("audio/pcm");
        format.setSampleSize(16);
        format.setSampleType(QAudioFormat::SignedInt);
        int sampleRate, channels;
        foreach (sampleRate, sampleRatesList) {
            if (foundSupportedFormat)
                break;
            format.setSampleRate(sampleRate);
            foreach (channels, channelsList) {
                format.setChannelCount(channels);
                const bool inputSupport = m_generateTone ||
                                          m_audioInputDevice.isFormatSupported(format);
                const bool outputSupport = m_audioOutputDevice.isFormatSupported(format);
                ENGINE_DEBUG << "Engine::initialize checking " << format
                             << "input" << inputSupport
                             << "output" << outputSupport;
                if (inputSupport && outputSupport) {
                    foundSupportedFormat = true;
                    break;
                }
            }
        }

        if (!foundSupportedFormat)
            format = QAudioFormat();

        setFormat(format);
    }