Example #1
0
void App::readResources(QFile &file, QList<QPair<QString, QString> > &readonlyList, QList<QPair<QString, QString> > &readwriteList) {
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    QTextStream in(&file);
    QString line;
    QPair<QString, QString> pair;
    bool readwrite = true;
    while(!(line = in.readLine()).isNull()) {
        QStringList t = line.split(",");
        if(line.compare("#readonly") == 0)
            readwrite = false;
        if(t.size() <= 1)
            continue;
        if(!t.at(0).isNull())
            pair.first = t.at(0);
        if(!t.at(1).isNull())
            pair.second = t.at(1);
        readonlyList << pair;
        if(readwrite)
            readwriteList << pair;
    }
    file.close();
    qSort(readwriteList.begin(), readwriteList.end());
    qSort(readonlyList.begin(), readonlyList.end());
}
void ProfileManager::setProfiles(const QList<Profile*>& profiles)
{
	QList<Profile*> currentProfiles = this->profiles;

	QList<Profile*>::const_iterator it;

	for (it = currentProfiles.begin() ; it != currentProfiles.end() ; it++) {
		Profile* profile = *it;

		if (!profiles.contains(profile)) {
			if (getCurrentProfile() == profile) {
				setCurrentProfile(NULL);
			}

			removeProfile(profile);
			delete profile;
		}
	}

	for (it = profiles.begin() ; it != profiles.end() ; it++) {
		Profile* profile = *it;

		if (!currentProfiles.contains(profile)) {
			addProfile(profile);
		}
	}
}
Example #3
0
QString Utility::timeToDescriptiveString(QList<QPair<QString,quint32> > &timeMapping, quint64 msecs, quint8 precision, QString separator, bool specific)
{       
    quint64 secs = msecs / 1000;
    QString retStr = QString(timeMapping.last().first).arg(0); // default value in case theres no actual time in msecs.
    QList<QPair<QString,quint32> > values;
    bool timeStartFound = false;
   
    for(QList<QPair<QString,quint32> >::Iterator itr = timeMapping.begin(); itr != timeMapping.end() && precision > 0; itr++) {
        quint64 result = itr == timeMapping.end() ?  qRound64( secs / itr->second )  :  secs / itr->second;
        if(!timeStartFound) {
            if(result == 0 ) {
                continue;
            }
            retStr = "";
            timeStartFound= true;        
        }        
        secs -= result * itr->second;
        values.append(QPair<QString,quint32>(itr->first,result));
        precision--;
    }
    
    for(QList<QPair<QString,quint32> >::Iterator itr = values.begin(); itr < values.end(); itr++) {
        retStr = retStr.append((specific || itr == values.end()-1) ? itr->first : "%1").arg(itr->second, (itr == values.begin() ? 1 :2 ), 10, QChar('0'));        
        if(itr < values.end()-1) {
            retStr.append(separator);
        }
        
            
    }
    
    return retStr;
}
Example #4
0
QString CheatsModel::toString(const QModelIndexList& indices) const {
	QMap<int, GBACheatSet*> setOrder;
	QMap<GBACheatSet*, QSet<size_t>> setIndices;
	for (const QModelIndex& index : indices) {
		GBACheatSet* set = static_cast<GBACheatSet*>(index.internalPointer());
		if (!set) {
			set = *GBACheatSetsGetPointer(&m_device->cheats, index.row());
			setOrder[index.row()] = set;
			QSet<size_t> range;
			for (size_t i = 0; i < StringListSize(&set->lines); ++i) {
				range.insert(i);
			}
			setIndices[set] = range;
		} else {
			setOrder[index.parent().row()] = set;
			setIndices[set].insert(index.row());
		}
	}

	QStringList strings;
	QList<int> order = setOrder.keys();
	std::sort(order.begin(), order.end());
	for (int i : order) {
		GBACheatSet* set = setOrder[i];
		QList<size_t> indexOrdex = setIndices[set].toList();
		std::sort(indexOrdex.begin(), indexOrdex.end());
		for (size_t j : indexOrdex) {
			strings.append(*StringListGetPointer(&set->lines, j));
		}
	}

	return strings.join('\n');
}
Example #5
0
/*!
  \reimp
*/
void QStringListModel::sort(int, Qt::SortOrder order)
{
    emit layoutAboutToBeChanged();

    QList<QPair<QString, int> > list;
    for (int i = 0; i < lst.count(); ++i)
        list.append(QPair<QString, int>(lst.at(i), i));

    if (order == Qt::AscendingOrder)
        qSort(list.begin(), list.end(), ascendingLessThan);
    else
        qSort(list.begin(), list.end(), decendingLessThan);

    lst.clear();
    QVector<int> forwarding(list.count());
    for (int i = 0; i < list.count(); ++i) {
        lst.append(list.at(i).first);
        forwarding[list.at(i).second] = i;
    }

    QModelIndexList oldList = persistentIndexList();
    QModelIndexList newList;
    for (int i = 0; i < oldList.count(); ++i)
        newList.append(index(forwarding.at(oldList.at(i).row()), 0));
    changePersistentIndexList(oldList, newList);

    emit layoutChanged();
}
Example #6
0
int main()
{
  QList<int> list;
  list << 3 << 3 << 6 << 6 << 6 << 8;

  QList<int>::iterator it;
  it = qLowerBound(list.begin(), list.end(), 5);
  list.insert(it, 5);
  qDebug() << list; // output: ( 3, 3, 5, 6, 6, 6, 8 )

  it = qLowerBound(list.begin(), list.end(), 12);
  list.insert(it, 12);
  qDebug() << list; // output: ( 3, 3, 5, 6, 6, 6, 8, 12 )

  it = qLowerBound(list.begin(), list.end(), 12);
  list.insert(it, 12);
  qDebug() << list; // output: ( 3, 3, 5, 6, 6, 6, 8, 12, 12 )
  QVector<int> vect;
  vect << 3 << 3 << 6 << 6 << 6 << 8;
  QVector<int>::iterator begin6 =
        qLowerBound(vect.begin(), vect.end(), 6);
  QVector<int>::iterator end6 =
        qUpperBound(vect.begin(), vect.end(), 6);
  QVector<int> vect2(end6-begin6);
  qCopy(begin6, end6, vect2.begin());
  qDebug() << vect2; // output: ( 6, 6, 6 )
  int count6 = 0;
  qCount(vect.begin(), vect.end(), 6, count6);
  qDebug() << count6; // output: 3
  return 0;
}
Example #7
0
void CFontFileListView::removeFiles()
{
    QTreeWidgetItem          *root=invisibleRootItem();
    QList<QTreeWidgetItem *> removeFonts;

    for(int t=0; t<root->childCount(); ++t)
    {
        QList<QTreeWidgetItem *> removeFiles;
        QTreeWidgetItem          *font=root->child(t);

        for(int c=0; c<font->childCount(); ++c)
        {
            QTreeWidgetItem *file=font->child(c);

            if(!Misc::fExists(file->text(0)))
                removeFiles.append(file);
        }

        QList<QTreeWidgetItem *>::ConstIterator it(removeFiles.begin()),
                                                end(removeFiles.end());

        for(; it!=end; ++it)
            delete (*it);
        if(0==font->childCount())
            removeFonts.append(font);
    }

    QList<QTreeWidgetItem *>::ConstIterator it(removeFonts.begin()),
                                            end(removeFonts.end());
    for(; it!=end; ++it)
        delete (*it);
}
Example #8
0
void GetSupportedFileFormats(QList<QByteArray> &g_supportedFormats)
{

    // Assemble list of supported Image Formats from our plugin
    int numPlugins = g_pluginManager.getNumPlugins();
    for (int i = 0; i< numPlugins; i++)
    {
        if (strcmp(g_pluginManager.getPluginType(i), "IMAGE") == 0)
        {
            QByteArray bArray = g_pluginManager.getPluginName(i);
            QByteArray fformat = bArray.toUpper();
            if (!g_supportedFormats.contains(fformat))
                g_supportedFormats.append(fformat);
        }
    }

    // Get a list of all Supported file formats from Qt Plugins
    QList<QByteArray> QtFormats = QImageReader::supportedImageFormats();

    // Upppercase List
    QList<QByteArray>::Iterator i;
    for (i = QtFormats.begin(); i != QtFormats.end(); ++i)
    {
        QByteArray fformat = (*i);
        fformat = fformat.toUpper();
        if (!g_supportedFormats.contains(fformat))
            g_supportedFormats.append(fformat);
    }
    
    // Sort the list to alphabetical order
    std::sort(g_supportedFormats.begin(), g_supportedFormats.end());

}
    /* Update our model of the wallet incrementally, to synchronize our model of the wallet
       with that of the core.

       Call with transaction that was added, removed or changed.
     */
    void updateWallet(const uint256 &hash, int status, bool showTransaction)
    {
        qDebug() << "TransactionTablePriv::updateWallet: " + QString::fromStdString(hash.ToString()) + " " + QString::number(status);

        // Find bounds of this transaction in model
        QList<TransactionRecord>::iterator lower = qLowerBound(
            cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
        QList<TransactionRecord>::iterator upper = qUpperBound(
            cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
        int lowerIndex = (lower - cachedWallet.begin());
        int upperIndex = (upper - cachedWallet.begin());
        bool inModel = (lower != upper);

        if(status == CT_UPDATED)
        {
            if(showTransaction && !inModel)
                status = CT_NEW; /* Not in model, but want to show, treat as new */
            if(!showTransaction && inModel)
                status = CT_DELETED; /* In model, but want to hide, treat as deleted */
        }

        qDebug() << "    inModel=" + QString::number(inModel) +
                    " Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) +
                    " showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status);

        switch(status)
        {
        case CT_NEW:
            if(inModel)
            {
                qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is already in model";
                break;
            }
            if(showTransaction)
            {
                LOCK2(cs_main, wallet->cs_wallet);
                // Find transaction in wallet
                std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
                if(mi == wallet->mapWallet.end())
                {
                    qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is not in wallet";
                    break;
                }
                // Added -- insert at the right position
                QList<TransactionRecord> toInsert =
                        TransactionRecord::decomposeTransaction(wallet, mi->second);
                if(!toInsert.isEmpty()) /* only if something to insert */
                {
                    parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1);
                    int insert_idx = lowerIndex;
                    Q_FOREACH(const TransactionRecord &rec, toInsert)
                    {
                        cachedWallet.insert(insert_idx, rec);
                        insert_idx += 1;
                    }
                    parent->endInsertRows();
                }
            }
Example #10
0
void MenuManager::setup(MenuItem* menuItems) const
{
    if (!menuItems)
        return; // empty menu bar

    QMenuBar* menuBar = getMainWindow()->menuBar();
    //menuBar->setUpdatesEnabled(false);

    QList<MenuItem*> items = menuItems->getItems();
    QList<QAction*> actions = menuBar->actions();
    for (QList<MenuItem*>::ConstIterator it = items.begin(); it != items.end(); ++it)
    {
        // search for the menu action
        QAction* action = findAction(actions, QString::fromAscii((*it)->command().c_str()));
        if (!action) {
            // There must be not more than one separator in the menu bar, so
            // we can safely remove it if available and append it at the end
            if ((*it)->command() == "Separator") {
                action = menuBar->addSeparator();
                action->setObjectName(QLatin1String("Separator"));
            }
            else {
                // create a new menu
                std::string menuName = (*it)->command();
                QMenu* menu = menuBar->addMenu(
                    QApplication::translate("Workbench", menuName.c_str(),
                                            0, QApplication::UnicodeUTF8));
                action = menu->menuAction();
                menu->setObjectName(QString::fromAscii(menuName.c_str()));
                action->setObjectName(QString::fromAscii(menuName.c_str()));
            }

            // set the menu user data
            action->setData(QString::fromAscii((*it)->command().c_str()));
        }
        else {
            // put the menu at the end
            menuBar->removeAction(action);
            menuBar->addAction(action);
            action->setVisible(true);
            int index = actions.indexOf(action);
            actions.removeAt(index);
        }

        // flll up the menu
        if (!action->isSeparator())
            setup(*it, action->menu());
    }

    // hide all menus which we don't need for the moment
    for (QList<QAction*>::Iterator it = actions.begin(); it != actions.end(); ++it) {
        (*it)->setVisible(false);
    }

    // enable update again
    //menuBar->setUpdatesEnabled(true);
}
Example #11
0
	void FSDisplayer::MakeItems (const QList<QList<Util::XDG::Item_ptr>>& items)
	{
		MakeStdItems ();

		const auto& curLang = Util::GetLanguage ().toLower ();

		QList<Util::XDG::Item_ptr> uniqueItems;
		for (const auto& sublist : items)
			for (const auto& item : sublist)
				if (!item->IsHidden () &&
						std::none_of (uniqueItems.begin (), uniqueItems.end (),
								[&item] (const auto& other) { return *other == *item; }))
					uniqueItems << item;

		std::sort (uniqueItems.begin (), uniqueItems.end (),
				[&curLang] (const auto& left, const auto& right)
				{
					return QString::localeAwareCompare (left->GetName (curLang), right->GetName (curLang)) < 0;
				});
		for (const auto& item : uniqueItems)
		{
			const auto& itemName = item->GetName (curLang);

			auto appItem = new QStandardItem ();
			appItem->setData (itemName, ModelRoles::ItemName);

			appItem->setData (item->GetCommand (), ModelRoles::ItemCommand);

			auto comment = item->GetComment (curLang);
			if (comment.isEmpty ())
				comment = item->GetGenericName (curLang);
			appItem->setData (comment, ModelRoles::ItemDescription);

			const auto& iconName = item->GetIconName ();
			appItem->setData (iconName, ModelRoles::ItemIcon);
			IconsProvider_->AddIcon (iconName, item->GetIcon (Proxy_));

			appItem->setData (item->GetCategories (), ModelRoles::ItemNativeCategories);
			appItem->setData (item->GetPermanentID (), ModelRoles::ItemID);
			appItem->setData (FavManager_->IsFavorite (item->GetPermanentID ()),
					ModelRoles::IsItemFavorite);

			const auto isRecent = RecentManager_->IsRecent (item->GetPermanentID ());
			appItem->setData (isRecent,
					ModelRoles::IsItemRecent);
			if (isRecent)
				appItem->setData (RecentManager_->GetRecentOrder (item->GetPermanentID ()),
						ModelRoles::ItemRecentPos);

			auto executor = [this, item] { item->Execute (Proxy_); };
			appItem->setData (QVariant::fromValue<Executor_f> (executor),
					ModelRoles::ExecutorFunctor);

			ItemsModel_->appendRow (appItem);
		}
	}
Example #12
0
    void updateEntry(const QString &name, const QString &value, const QString &address, int nExpiresAt, int status, int *outNewRowIndex = NULL)
    {
        // Find name in model
        QList<NameTableEntry>::iterator lower = qLowerBound(
            cachedNameTable.begin(), cachedNameTable.end(), name, NameTableEntryLessThan());
        QList<NameTableEntry>::iterator upper = qUpperBound(
            cachedNameTable.begin(), cachedNameTable.end(), name, NameTableEntryLessThan());
        int lowerIndex = (lower - cachedNameTable.begin());
        int upperIndex = (upper - cachedNameTable.begin());
        bool inModel = (lower != upper);

        switch(status)
        {
        case CT_NEW:
            if (inModel)
            {
                if (outNewRowIndex)
                {
                    *outNewRowIndex = parent->index(lowerIndex, 0).row();
                    // HACK: ManageNamesPage uses this to ensure updating and get selected row,
                    // so we do not write warning into the log in this case
                }
                else
                    LogPrintf("Warning: NameTablePriv::updateEntry: Got CT_NEW, but entry is already in model\n");
                break;
            }
            parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
            cachedNameTable.insert(lowerIndex, NameTableEntry(name, value, address, nExpiresAt));
            parent->endInsertRows();
            if (outNewRowIndex)
                *outNewRowIndex = parent->index(lowerIndex, 0).row();
            break;
        case CT_UPDATED:
            if (!inModel)
            {
                LogPrintf("Warning: NameTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\n");
                break;
            }
            lower->name = name;
            lower->value = value;
            lower->address = address;
            lower->nExpiresAt = nExpiresAt;
            parent->emitDataChanged(lowerIndex);
            break;
        case CT_DELETED:
            if (!inModel)
            {
                LogPrintf("Warning: NameTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\n");
                break;
            }
            parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
            cachedNameTable.erase(lower, upper);
            parent->endRemoveRows();
            break;
        }
    }
Example #13
0
void QGIViewPart::updateView(bool update)
{
    if (getViewObject() == 0 ||
        !getViewObject()->isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId())) {
        return;
    }

    QGIView::updateView(update);

    TechDraw::DrawViewPart *viewPart = dynamic_cast<TechDraw::DrawViewPart *>(getViewObject());

    if (update ||
       viewPart->isTouched() ||
       viewPart->Source.isTouched() ||
       viewPart->Direction.isTouched() ||
       viewPart->XAxisDirection.isTouched() ||
       viewPart->Tolerance.isTouched() ||
       viewPart->Scale.isTouched() ||
       viewPart->ShowHiddenLines.isTouched() ||
       viewPart->ShowSmoothLines.isTouched() ||
       viewPart->ShowSeamLines.isTouched() ) {
        // Remove all existing graphical representations (QGIxxxx)  otherwise BRect only grows, never shrinks?
        // is this where selection messes up?
        prepareGeometryChange();
        QList<QGraphicsItem*> items = childItems();
        for(QList<QGraphicsItem*>::iterator it = items.begin(); it != items.end(); ++it) {
            if (dynamic_cast<QGIEdge *> (*it) ||
                dynamic_cast<QGIFace *>(*it) ||
                dynamic_cast<QGIVertex *>(*it)) {
                removeFromGroup(*it);
                scene()->removeItem(*it);

                // We store these and delete till later to prevent rendering crash ISSUE
                deleteItems.append(*it);
            }
        }
        draw();
    } else if (update ||
              viewPart->LineWidth.isTouched() ||
              viewPart->HiddenWidth.isTouched()) {
        QList<QGraphicsItem*> items = childItems();
        for(QList<QGraphicsItem*>::iterator it = items.begin(); it != items.end(); ++it) {
            QGIEdge *edge = dynamic_cast<QGIEdge *>(*it);
            if(edge  && edge->getHiddenEdge()) {
                edge->setStrokeWidth(viewPart->HiddenWidth.getValue() * lineScaleFactor);
            } else {
                edge->setStrokeWidth(viewPart->LineWidth.getValue() * lineScaleFactor);
            }
        }
        draw();
    } else {
        QGIView::draw();
    }
}
Example #14
0
void QUSongFileData::sort(QList<QUSongFile*> &songs) {
	if(this->next())
		this->next()->sort(songs);

	if(QString::compare(_property, "path", Qt::CaseInsensitive) == 0)
		qStableSort(songs.begin(), songs.end(), QUSongFile::pathLessThan);
	else if(QString::compare(_property, "filePath", Qt::CaseInsensitive) == 0)
		qStableSort(songs.begin(), songs.end(), QUSongFile::filePathLessThan);
	else if(QString::compare(_property, "relativeFilePath", Qt::CaseInsensitive) == 0)
		qStableSort(songs.begin(), songs.end(), QUSongFile::relativeFilePathLessThan);
}
Example #15
0
void QgsLabelingGui::populateDataDefinedCombos( QgsPalLayerSettings& s )
{
  QList<QComboBox*> comboList;
  comboList << mSizeAttributeComboBox;
  comboList << mColorAttributeComboBox;
  comboList << mBoldAttributeComboBox;
  comboList << mItalicAttributeComboBox;
  comboList << mUnderlineAttributeComboBox;
  comboList << mStrikeoutAttributeComboBox;
  comboList << mFontFamilyAttributeComboBox;
  comboList << mBufferSizeAttributeComboBox;
  comboList << mBufferColorAttributeComboBox;
  comboList << mXCoordinateComboBox;
  comboList << mYCoordinateComboBox;
  comboList << mHorizontalAlignmentComboBox;
  comboList << mVerticalAlignmentComboBox;
  comboList << mLabelDistanceComboBox;
  comboList << mRotationComboBox;

  QList<QComboBox*>::iterator comboIt = comboList.begin();
  for ( ; comboIt != comboList.end(); ++comboIt )
  {
    ( *comboIt )->addItem( "", QVariant() );
  }

  const QgsFieldMap& fields = mLayer->dataProvider()->fields();
  for ( QgsFieldMap::const_iterator it = fields.constBegin(); it != fields.constEnd(); it++ )
  {
    for ( comboIt = comboList.begin(); comboIt != comboList.end(); ++comboIt )
    {
      ( *comboIt )->addItem( it.value().name(), it.key() );
    }

  }

  //set current combo boxes to already existing indices
  setCurrentComboValue( mSizeAttributeComboBox, s, QgsPalLayerSettings::Size );
  setCurrentComboValue( mColorAttributeComboBox, s, QgsPalLayerSettings::Color );
  setCurrentComboValue( mBoldAttributeComboBox, s, QgsPalLayerSettings::Bold );
  setCurrentComboValue( mItalicAttributeComboBox, s, QgsPalLayerSettings::Italic );
  setCurrentComboValue( mUnderlineAttributeComboBox, s, QgsPalLayerSettings::Underline );
  setCurrentComboValue( mStrikeoutAttributeComboBox, s, QgsPalLayerSettings::Strikeout );
  setCurrentComboValue( mFontFamilyAttributeComboBox, s, QgsPalLayerSettings::Family );
  setCurrentComboValue( mBufferSizeAttributeComboBox, s , QgsPalLayerSettings::BufferSize );
  setCurrentComboValue( mBufferColorAttributeComboBox, s, QgsPalLayerSettings::BufferColor );
  setCurrentComboValue( mXCoordinateComboBox, s, QgsPalLayerSettings::PositionX );
  setCurrentComboValue( mYCoordinateComboBox, s, QgsPalLayerSettings::PositionY );
  setCurrentComboValue( mHorizontalAlignmentComboBox, s, QgsPalLayerSettings::Hali );
  setCurrentComboValue( mVerticalAlignmentComboBox, s, QgsPalLayerSettings::Vali );
  setCurrentComboValue( mLabelDistanceComboBox, s, QgsPalLayerSettings::LabelDistance );
  setCurrentComboValue( mRotationComboBox, s, QgsPalLayerSettings::Rotation );
}
Example #16
0
    void updateEntry(const QString &address, const QString &label, bool isMine, int status)
    {
        // Find address / label in model
        QList<AddressTableEntry>::iterator lower = qLowerBound(
            cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
        QList<AddressTableEntry>::iterator upper = qUpperBound(
            cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
        int lowerIndex = (lower - cachedAddressTable.begin());
        int upperIndex = (upper - cachedAddressTable.begin());
        bool inModel = (lower != upper);
        AddressTableEntry::Type newEntryType = isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending;

        switch(status)
        {
        case CT_NEW:
            if(inModel)
            {
                OutputDebugStringF("Warning: AddressTablePriv::updateEntry: Got CT_NOW, but entry is already in model\n");
                break;
            }
            {
                CBitcoinAddress addr(address.toStdString());
                AddressTableEntry::Category cate = IsMyShare(*wallet, addr.Get()) ? AddressTableEntry::MultiSig : AddressTableEntry::Normal;

                parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
                cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address, cate));
                parent->endInsertRows();
            }
            break;
        case CT_UPDATED:
            if(!inModel)
            {
                OutputDebugStringF("Warning: AddressTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\n");
                break;
            }
            lower->type = newEntryType;
            lower->label = label;
            parent->emitDataChanged(lowerIndex);
            break;
        case CT_DELETED:
            if(!inModel)
            {
                OutputDebugStringF("Warning: AddressTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\n");
                break;
            }
            parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
            cachedAddressTable.erase(lower, upper);
            parent->endRemoveRows();
            break;
        }
    }
Example #17
0
	void FSDisplayer::MakeItems (const QList<QList<Item_ptr>>& items)
	{
		MakeStdItems ();

		const auto& curLang = Util::GetLanguage ().toLower ();

		QList<Item_ptr> uniqueItems;
		for (const auto& sublist : items)
			for (auto item : sublist)
				if (!item->IsHidden () &&
					std::find_if (uniqueItems.begin (), uniqueItems.end (),
							[&item] (const Item_ptr other) { return *other == *item; }) == uniqueItems.end ())
					uniqueItems << item;
		std::sort (uniqueItems.begin (), uniqueItems.end (),
				[&curLang] (Item_ptr left, Item_ptr right)
				{
					return QString::localeAwareCompare (left->GetName (curLang), right->GetName (curLang)) < 0;
				});
		for (const auto& item : uniqueItems)
		{
			const auto& itemName = item->GetName (curLang);

			auto appItem = new QStandardItem ();
			appItem->setData (itemName, ModelRoles::ItemName);

			auto comment = item->GetComment (curLang);
			if (comment.isEmpty ())
				comment = item->GetGenericName (curLang);
			appItem->setData (comment, ModelRoles::ItemDescription);

			const auto& iconName = item->GetIconName ();
			appItem->setData (iconName, ModelRoles::ItemIcon);
			IconsProvider_->AddIcon (iconName, item->GetIcon ());

			appItem->setData (item->GetCategories (), ModelRoles::ItemNativeCategories);

			appItem->setData (itemName, ModelRoles::ItemID);

			appItem->setData (FavManager_->IsFavorite (item->GetPermanentID ()), ModelRoles::IsItemFavorite);

			ItemInfos_ [itemName] =
			{
				[this, item] () { item->Execute (Proxy_); },
				item->GetPermanentID ()
			};

			ItemsModel_->appendRow (appItem);
		}
	}
Example #18
0
QList<Page *> FileEngine::listPages(QObject *parent, Engine::Filters filters, Engine::SortFlags sort, int depth, int limit)
{
    Q_D(const FileEngine);
    Q_UNUSED(parent)

    QList<Page *> ret;
    QList<Page *> pages;

    if (filters != NoFilter) {
        if (filters & Posts) {
            pages.append(d->posts);
        }

        if (filters & Pages) {
            pages.append(d->pages);
        }
    } else {
        pages = d->pages + d->posts;
    }


    if (depth == -1) {
        ret = pages;
    } else {
        Q_FOREACH (Page *page, pages) {
            if (depth != -1 && page->path().count(QLatin1Char('/')) > depth) {
                continue;
            }

            ret.append(page);
        }
    }

    // apply the sorting
    if (sort & Date && sort & Name) {
        qSort(ret.begin(), ret.end(), sort & Reversed ? dateNameGreaterThan : dateNameLessThan);
    } else if (sort & Date) {
        qSort(ret.begin(), ret.end(), sort & Reversed ? dateGreaterThan : dateLessThan);
    } else if (sort & Name) {
        qSort(ret.begin(), ret.end(), sort & Reversed ? nameGreaterThan : nameLessThan);
    }

    // Limit the list
    if (limit == -1) {
        return ret;
    } else {
        return ret.mid(0, limit);
    }
}
Example #19
0
QList<Article *> Folder::articles() const
{
    QList<Article *> news;

    for (Item *item : asConst(items())) {
        int n = news.size();
        news << item->articles();
        std::inplace_merge(news.begin(), news.begin() + n, news.end()
                           , [](Article *a1, Article *a2)
        {
            return Article::articleDateRecentThan(a1, a2->date());
        });
    }
    return news;
}
Example #20
0
/**
 * @brief WidgetCompLineChart::drawChart draw the chart
 */
void WidgetCompLineChart::drawChart()
{

    ui->widgetCompLineChart_2->clearPlottables();
    int j = 0;
    QList<QListWidgetItem*> tempMuniList = ui->listLineChartMunicipality_4->selectedItems();
    for(QList<QListWidgetItem*>::Iterator it = tempMuniList.begin(); it != tempMuniList.end(); ++it) {
        ui->widgetCompLineChart_2->addGraph();
        QPen tempPen(COLOUR_LIST[j%5]);
        tempPen.setWidth(PEN_WIDTH);
        ui->widgetCompLineChart_2->graph(j)->setPen(tempPen);
        ++j;
    }
    int k = 0;
    for(QList<QListWidgetItem*>::Iterator it = tempMuniList.begin(); it != tempMuniList.end(); ++it) {
        ui->widgetCompLineChart_2->addGraph(ui->widgetCompLineChart_2->xAxis2,ui->widgetCompLineChart_2->yAxis2);
        QPen tempPen(COLOUR_LIST2[k%5]);
        tempPen.setWidth(PEN_WIDTH);
        ui->widgetCompLineChart_2->graph(k+j)->setPen(tempPen);
        ++k;
    }
    ui->widgetCompLineChart_2->xAxis->setAutoTickStep(false);
    ui->widgetCompLineChart_2->xAxis->setTickStep(1.0);
    ui->widgetCompLineChart_2->xAxis->setTickLabelRotation(-60);
    ui->widgetCompLineChart_2->xAxis2->setAutoTickStep(false);
    ui->widgetCompLineChart_2->xAxis2->setTickStep(1.0);
    ui->widgetCompLineChart_2->xAxis2->setTickLabelRotation(-60);
    if(_ylist->size() > 0) {
        ui->widgetCompLineChart_2->xAxis->setRange(_ylist->at(0).toInt(),_ylist->at(_ylist->size()-1).toInt());
        ui->widgetCompLineChart_2->xAxis2->setRange(_ylist->at(0).toInt(),_ylist->at(_ylist->size()-1).toInt());
    }
    ui->widgetCompLineChart_2->yAxis->setLabel(_meas->id()+":"+_meas->name());
    ui->widgetCompLineChart_2->yAxis2->setLabel(_meas2->id()+":"+_meas2->name());
    ui->widgetCompLineChart_2->yAxis->setRange(_meas->maxmin().first*GRAPH_LOW_RATIO,_meas->maxmin().second*GRAPH_HIGH_RATIO);
    ui->widgetCompLineChart_2->yAxis2->setRange(_meas2->maxmin().first*GRAPH_LOW_RATIO,_meas2->maxmin().second*GRAPH_HIGH_RATIO);
    ui->widgetCompLineChart_2->yAxis2->setVisible(true);

    for(int i = 0; i < _meas->yearRange().size(); ++i) {
        if(ui->listLineChartYears_4->item(i)->isSelected()) {
            drawYear(i);
            drawYear2(i,k);
        }

    }

    ui->widgetCompLineChart_2->legend->setVisible(true);
    ui->widgetCompLineChart_2->replot();
}
void GitoriousRepositoryWizardPage::initializePage()
{
    // Populate the model
    ui->repositoryTreeView->selectionModel()->clearSelection();
    if (const int oldRowCount = m_model->rowCount())
        m_model->removeRows(0, oldRowCount);
    ui->filterLineEdit->clear();
    // fill model
    const QSharedPointer<GitoriousProject> proj = m_projectPage->project();
    setSubTitle(tr("Choose a repository of the project '%1'.").arg(proj->name));
    // Create a hierarchical list by repository type, sort by type
    QList<GitoriousRepository> repositories = proj->repositories;
    QStandardItem *firstEntry = 0;
    if (!repositories.empty()) {
        int lastRepoType = -1;
        QStandardItem *header = 0;
        qStableSort(repositories.begin(), repositories.end(), gitRepoLessThanByType);
        const QString types[GitoriousRepository::PersonalRepository + 1] =
            { tr("Mainline Repositories"), tr("Clones"), tr("Baseline Repositories"), tr("Shared Project Repositories"), tr("Personal Repositories") };
        foreach(const GitoriousRepository &r, repositories) {
            // New Header?
            if (r.type != lastRepoType || !header) {
                lastRepoType = r.type;
                const QList<QStandardItem *> headerRow = headerEntry(types[r.type]);
                m_model->appendRow(headerRow);
                header = headerRow.front();
            }
            // Repository row
            const QList<QStandardItem *> row = repositoryEntry(r);
            header->appendRow(row);
            if (!firstEntry)
                firstEntry = row.front();
        }
    }
Example #22
0
    void refreshAddressTable()
    {
        cachedAddressTable.clear();
        {
            LOCK(wallet->cs_wallet);
            BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& item, wallet->mapAddressBook)
            {
                const CBitcoinAddress& address = item.first;
                const std::string& strName = item.second;
                bool fMine = IsMine(*wallet, address.Get());
                bool fMyShare = IsMyShare(*wallet, address.Get());
                AddressTableEntry::Type type = fMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending;
                AddressTableEntry::Category cate = AddressTableEntry::Normal;
                if ( fMyShare )
                {
                    cate = AddressTableEntry::MultiSig;
                    type = AddressTableEntry::Sending;
                }

                cachedAddressTable.append(AddressTableEntry(type,
                                  QString::fromStdString(strName),
                                  QString::fromStdString(address.ToString()), cate));
            }
        }
        // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
        qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
    }
Example #23
0
  void switchRegisterSelection(std::vector<std::string> RegisterToSelect) {
    registerToBeFound = NULL;
    QList<QTreeWidgetItem*> registerList = qtHardMon->ui.registerTreeWidget->findItems(
        RegisterToSelect.back().c_str(), Qt::MatchExactly | Qt::MatchRecursive);
    RegisterToSelect.pop_back();

    for(std::vector<std::string>::reverse_iterator nameIter = RegisterToSelect.rbegin();
        nameIter != RegisterToSelect.rend();
        ++nameIter) {
      // Iterate the list until we find the one with the right module

      for(QList<QTreeWidgetItem*>::iterator registerIter = registerList.begin(); registerIter != registerList.end();
          ++registerIter) {
        // if we found the right register select it and quit the loop
        if((*registerIter)->parent()->text(0) == (*nameIter).c_str()) {
          registerToBeFound = *registerIter;
          break;
        }
      }
    }
    if(!registerToBeFound) {
      BOOST_FAIL("Register not found...");
    }
    else {
      qtHardMon->ui.registerTreeWidget->setCurrentItem(registerToBeFound);
    }
  }
void QgsAtlasComposition::endRender()
{
  if ( !mComposerMap || !mCoverageLayer )
  {
    return;
  }

  // reset label expression contexts
  QList<QgsComposerLabel*> labels;
  mComposition->composerItems( labels );
  for ( QList<QgsComposerLabel*>::iterator lit = labels.begin(); lit != labels.end(); ++lit )
  {
    ( *lit )->setExpressionContext( 0, 0 );
  }

  // restore the coverage visibility
  if ( mRestoreLayer )
  {
    QStringList& layerSet = mComposition->mapRenderer()->layerSet();

    layerSet.push_back( mCoverageLayer->id() );
    mComposerMap->cache();
    mComposerMap->update();
  }
  mComposerMap->setNewExtent( mOrigExtent );
}
Example #25
0
  /** 
   * This method is called when the user selects a row or rows
   * uses the delete button or selects the delete row menu item
   * from the file menu.
   * 
   */
  void TableMainWindow::deleteRows () {
    QList<QTableWidgetItem*> list = p_table->selectedItems();
    QList<int> selectedRows;

    for(int i = 0; i < list.size(); i++) {
      if(selectedRows.size() == 0) {
        selectedRows.push_back(p_table->row(list[i]));
      } else if(!selectedRows.contains(p_table->row(list[i]))){
        selectedRows.push_back(p_table->row(list[i]));
      }
    }
    
    qSort(selectedRows.begin(), selectedRows.end());
    for(int d = selectedRows.size(); d > 0; d--) {
      p_table->removeRow(selectedRows[d-1]);
    }
  
    // get the number of rows that are filled in
    int filledRows = 0;
    for(int r = 0; r <  p_table->rowCount(); r++ ) {
      for(int c =0; c < p_table->columnCount(); c++) {
        if(!p_table->item(r,c) || p_table->item(r,c)->text() != "") {
          filledRows++;
          break;
        }
      }
    }
 
    p_currentRow = filledRows;    
  }
void OsmAnd::RoutePlannerContext::unloadUnusedTiles(size_t memoryTarget) {
    float desirableSize = memoryTarget * 0.7f;
    QList< std::shared_ptr<RoutingSubsectionContext> > list;
    int loaded = 0;
    for(std::shared_ptr<RoutingSubsectionContext>  t : this->_subsectionsContexts) {
        if(t->isLoaded()) {
            list.push_back(t);
            loaded++;
        }
    }
    if(_routeStatistics) {
        _routeStatistics->maxLoadedTiles = qMax(_routeStatistics->maxLoadedTiles , getCurrentlyLoadedTiles());
    }
    qSort(list.begin(), list.end(), compareSections);

    int i = 0;
    while(getCurrentEstimatedSize() >= desirableSize && (list.size() - i) > loaded / 5 && i < list.size()) {
        std::shared_ptr<RoutingSubsectionContext>  unload = list[i];
        i++;
        unload->unload();
        if(_routeStatistics) {
            _routeStatistics->unloadedTiles ++;
        }

    }
    if(_routeStatistics) {
        OsmAnd::LogPrintf(OsmAnd::LogSeverityLevel::Info, "Unloaded tiles %d (loaded prevUnloaded %d, currently loaded %d)",  _routeStatistics->unloadedTiles,  _routeStatistics->loadedPrevUnloadedTiles, getCurrentlyLoadedTiles());
        OsmAnd::LogFlush();
    }
    for(std::shared_ptr<OsmAnd::RoutePlannerContext::RoutingSubsectionContext> t : _subsectionsContexts) {
        t->_access /= 3;
    }
}
Example #27
0
std::shared_ptr<Node>
locateNodeAt(QPointF scenePoint, FlowScene &scene, QTransform viewTransform)
{
  // items under cursor
  QList<QGraphicsItem*> items =
    scene.items(scenePoint,
                Qt::IntersectsItemShape,
                Qt::DescendingOrder,
                viewTransform);

  //// items convertable to NodeGraphicsObject
  std::vector<QGraphicsItem*> filteredItems;

  std::copy_if(items.begin(),
               items.end(),
               std::back_inserter(filteredItems),
               [] (QGraphicsItem * item)
               {
                 return (dynamic_cast<NodeGraphicsObject*>(item) != nullptr);
               });

  std::shared_ptr<Node> resultNode;

  if (!filteredItems.empty())
  {
    QGraphicsItem* graphicsItem = filteredItems.front();
    auto ngo = dynamic_cast<NodeGraphicsObject*>(graphicsItem);

    resultNode = ngo->node().lock();
  }

  return resultNode;
}
Example #28
0
/*!
    Returns the first charset from the preferred list that is capable of encoding
    the content of \a text.

    \since 1.0
    \sa preferredCharsets(), setBody()
*/
QByteArray QMessage::preferredCharsetFor(const QString &text)
{
    QList<QTextCodec*> codecs;
    foreach (const QByteArray &name, charsets) {
        if (QTextCodec* codec = QTextCodec::codecForName(name)) {
            codecs.append(codec);
        } else {
            qWarning() << "No codec is available for:" << name;
        }
    }

    if (!codecs.isEmpty()) {
        // See if any of these codecs can encode the data
        QString::const_iterator sit = text.begin(), end = text.end();
        for ( ; sit != end; ++sit) {
            QList<QTextCodec*>::iterator cit = codecs.begin();
            if (!(*cit)->canEncode(*sit)) {
                // This codec is not acceptable
                cit = codecs.erase(cit);
                if (codecs.isEmpty()) {
                    break;
                }
            } else {
                ++cit;
            }
        }

        if (!codecs.isEmpty()) {
            // Return the first remaining codec
            return codecs.first()->name();
        }
    }

    return QByteArray();
}
Example #29
0
/**
 * Exports the surfaces of the given box.
 * This is a convenience function that exports 12 triangles but may
 * also be re-implemented to do something else.
 */
void RExporter::exportBox(const RBox& box) {
    QList<RTriangle> triangles = box.getTriangles();
    QList<RTriangle>::iterator it;
    for (it=triangles.begin(); it!=triangles.end(); ++it) {
        exportTriangle(*it);
    }
}
 void dump() const {
     QTextStream outs(stderr, QIODevice::WriteOnly);
     QList<Line> lines;
     foreach (const char *func, counters.keys()) {
         const Counters &fCount = counters[func];
         for (int i = 0, ei = fCount.size(); i != ei; ++i) {
             quint64 count = fCount[i];
             if (!count)
                 continue;
             Line line;
             line.func = func;
             unmangle(i, line.tag1, line.tag2);
             line.count = count;
             lines.append(line);
         }
     }
     qSort(lines.begin(), lines.end(), Line::less);
     outs << lines.size() << " counters:" << endl;
     foreach (const Line &line, lines)
         outs << qSetFieldWidth(10) << line.count << qSetFieldWidth(0)
              << " | " << line.func
              << " | " << pretty(line.tag1)
              << " | " << pretty(line.tag2)
              << endl;
 }