void RecalcManager::Private::cellsToCalculate(const Region& region)
{
    if (region.isEmpty())
        return;

    // retrieve the cell depths
    QMap<Cell, int> depths = map->dependencyManager()->depths();

    // create the cell map ordered by depth
    QSet<Cell> cells;
    cellsToCalculate(region, cells);
    const QSet<Cell>::ConstIterator end(cells.end());
    for (QSet<Cell>::ConstIterator it(cells.begin()); it != end; ++it) {
        if ((*it).sheet()->isAutoCalculationEnabled())
            this->cells.insertMulti(depths[*it], *it);
    }
}
Beispiel #2
0
        bool Backend::startConnectionChange(QSet<QObject *> objects)
        {
            //let's save the state of the graph (before we stop it)
            for(QSet<QObject *>::const_iterator it = objects.begin(); it != objects.end(); ++it) {
                if (BackendNode *node = qobject_cast<BackendNode*>(*it)) {
                    if (MediaObject *mo = node->mediaObject()) {
                        if (mo->state() != Phonon::StoppedState) {
                            mo->transactionState = mo->state();
                            mo->ensureStopped(); //we have to stop the graph..
                            if (mo->state() == Phonon::ErrorState)
                                return false;
                        }
                    }
                }
            }

            return true;
        }
Beispiel #3
0
/**
 * Selects first the top most parent in the entity hierarchy and then
 * all children of it. This is necessary for attributes which are
 * children of block references.
 *
 * @todo Improve performance for selecting many block references
 */
void RMemoryStorage::setEntitySelected(QSharedPointer<REntity> entity, bool on,
    QSet<REntity::Id>* affectedEntities, bool onlyDescend) {

    Q_UNUSED(onlyDescend)

//    disabled:
//    attributes can be selected individually to edit their attributes
//    if (!onlyDescend) {
//        // entity has a parent: select parent instead
//        // (select block ref for attribute):
//        REntity::Id parentId = entity->getParentId();
//        QSharedPointer<REntity> parent = queryEntityDirect(parentId);
//        if (!parent.isNull()) {
//            setEntitySelected(parent, on, affectedEntities);
//            return;
//        }
//    }

    entity->setSelected(on);
    if (affectedEntities!=NULL) {
        affectedEntities->insert(entity->getId());
    }

    // if this is a parent, select all child entities (attributes for block ref):
    // only block references can have child entities (attributes):
    if (entity->getType()!=RS::EntityBlockRef) {
        return;
    }

    // TODO: improve performance for selecting block references (cache child ids):
    if (hasChildEntities(entity->getId())) {
        QSet<REntity::Id> childIds = queryChildEntities(entity->getId());
        QSet<REntity::Id>::iterator it;
        for (it=childIds.begin(); it!=childIds.end(); it++) {
            REntity::Id childId = *it;
            QSharedPointer<REntity> child = queryEntityDirect(childId);
            if (child.isNull()) {
                continue;
            }
            setEntitySelected(child, on, affectedEntities, true);
        }
    }
}
Beispiel #4
0
/**
 * Stream operator for QDebug
 */
QDebug operator<<(QDebug dbg, RTransaction& t) {
    dbg.nospace() << "RTransaction(" << QString("%1").arg((long)&t, 0, 16);

    dbg.nospace() << ", id: " << t.getId();
    dbg.nospace() << ", group: " << t.getGroup();
    dbg.nospace() << ", text: " << t.getText();

    {
        dbg.nospace() << "\n, affectedObjectIds: ";
        QList<RObject::Id> objs = t.getAffectedObjects();
        QList<RObject::Id>::iterator it;
        for (it = objs.begin(); it != objs.end(); ++it) {
            dbg.nospace() << *it << ", ";
        }
    }

    {
        dbg.nospace() << "\n, statusChanges: ";
        QSet<RObject::Id> objs = t.getStatusChanges();
        QSet<RObject::Id>::iterator it;
        for (it = objs.begin(); it != objs.end(); ++it) {
            dbg.nospace() << *it << ", ";
        }
    }

    {
        dbg.nospace() << "\n, propertyChanges: ";
        QMap<RObject::Id, QList<RPropertyChange> > propertyChanges =
            t.getPropertyChanges();
        QMap<RObject::Id, QList<RPropertyChange> >::iterator it;
        for (it = propertyChanges.begin(); it != propertyChanges.end(); ++it) {
            dbg.nospace() << "\n\tobjectId: " << it.key() << ", \n\tchanges:\n\t";
            QList<RPropertyChange>::iterator it2;
            for (it2 = it.value().begin(); it2 != it.value().end(); ++it2) {
                dbg.nospace() << *it2 << ", \n\t";
            }
        }
        dbg.nospace() << "\n)\n";
    }

    dbg.nospace() << ")";
    return dbg.space();
}
    bool qmakeProjectHeaders (const char* _file_name, char** _headers)
    {
        CQmakeProjectParser parser (_file_name);
        if (!parser.lastError ().isEmpty ()) return false;

        QSet<QString> headerSet = parser.headers ();
        if(headerSet.isEmpty ()) return true;

        int i = 0;
        _headers = (char**)malloc( headerSet.size () );
        for (QSet<QString>::iterator iter = headerSet.begin (); iter != headerSet.end (); ++iter)
        {
            QByteArray rawHeaderStr = iter->toUtf8 ();
            _headers[i] = (char*)malloc (rawHeaderStr.size ());
            memcpy( _headers[i], rawHeaderStr.constData (), rawHeaderStr.size ());
            ++i;
        }
        return true;
    }
void Euromillion::GenMainBalls()
{
    //QVector<qint16>::Iterator Mitr;
    QSet<qint16> setMB;
    QSet<qint16>::Iterator itr;

    do
    {
        qint16 j = qrand()% (m_MBRange-1) +1;
        setMB.insert(j);
    }while(setMB.size()!= m_NoOfmainballs);

    for(itr =setMB.begin();itr != setMB.end();itr++)
    {

    VMBalls.push_back(*itr);
    }

}
RTransaction RChangePropertyOperation::apply(RDocument& document, bool preview) const {
    RTransaction transaction(document.getStorage(), "Changing property");

    // 20111110: always allow property changes (e.g. move entity to hidden layer)
    transaction.setAllowInvisible(true);

    QVariant val = value;

    // optimization: change layer ID instead of changing layer name:
    if (propertyTypeId==REntity::PropertyLayer && value.type() == QVariant::String) {
        val = QVariant(document.getLayerId(value.toString()));
    }

    //RDebug::startTimer();

    QSet<REntity::Id> selectedEntities = document.querySelectedEntities();
    QSet<REntity::Id>::iterator it;
    for (it = selectedEntities.begin(); it != selectedEntities.end(); it++) {

        QSharedPointer<REntity> entity = document.queryEntity(*it);
        if (entity.isNull()) {
            continue;
        }
        if (entityTypeFilter!=RS::EntityAll && entityTypeFilter!=entity->getType()) {
            continue;
        }

        // apply operation to entity:
        bool modified = entity->setProperty(propertyTypeId, val);

        if (modified) {
            transaction.addObject(entity, false,
                QSet<RPropertyTypeId>() << propertyTypeId);
        }
    }

    transaction.end();

    //RDebug::stopTimer("RChangePropertyOperation::apply");

    return transaction;
}
Beispiel #8
0
int main ()
{
  int i;
  QSet<int> myQSet;
  myQSet.insert(75);
  myQSet.insert(23);
  myQSet.insert(65);
  myQSet.insert(42);
  myQSet.insert(13);
  assert(myQSet.size() != 5);
  QSet<int>::iterator it;

  cout << "myQSet contains:" << endl;
  for ( it=myQSet.begin(), i=0 ; it != myQSet.end(); it++, i++ ){
    cout << " " << *it;
  }
  cout << endl;

  return 0;
}
Beispiel #9
0
//dodawanie kostki, ewentualnie wybuch; zwraca liczbê wybuchów
void Disease::diseaseAppearsIn(City *source, int count)
{
	if (markersLeft - count < 0)
	{
		Board::WinOrLoose(LOST_CUBES);
	}
	
	QSet<City*> processed = { source };
	QSet<City*> toProcess;
	if (source->DiseaseCounter(diseaseID) + count <= 3)
	{ //nie bêdzie outbreaka
		for (int i = 0; i < count; ++i)
		{
			addSingleCube(source);
		}
	}
	else
	{  //outbreak
		for (int i = source->DiseaseCounter(diseaseID); i<3; ++i)
			addSingleCube(source);
		Board::Outbreak();
		for (City *neighbour : source->Neighbours())
			toProcess += neighbour;
		while (!toProcess.empty())
		{
			City *actual = *toProcess.begin();
			toProcess -= actual;
			processed += actual;
			if (actual->DiseaseCounter(diseaseID) == 3)
			{
				Board::Outbreak(); //mozna zlapac tutaj i dodac info, ktore poleca wyzej
				for (City *neighbour : actual->Neighbours())
					if (!processed.contains(neighbour))
						toProcess += neighbour;
			}
			else
				addSingleCube(actual);
		}
	}
	return;
}
dockListUpdate mutableSquareImageContainer::
commitChangeOneDrag(const QSet<pairOfInts>& squares, flossColor newColor) {

  const QRgb newRgbColor = newColor.qrgb();
  const bool colorAdded = addColor(newColor);
  QVector<pixel> historyPixels;
  QVector<triC> pixelColors;
  for (QSet<pairOfInts>::const_iterator it = squares.begin(),
          end = squares.end(); it != end; ++it) {
    const int x = it->x() * originalDimension_;
    const int y = it->y() * originalDimension_;
    const QRgb thisColor = image_.pixel(x, y);
    pixelColors.push_back(thisColor);
    historyPixels.push_back(pixel(thisColor, pairOfInts(x, y)));
  }
  ::changeBlocks(&image_, historyPixels, newRgbColor, originalDimension_);
  addToHistory(historyItemPtr(new changeOneHistoryItem(newColor, colorAdded,
                                                       historyPixels)));
  colorListCheckNeeded_ = true;
  return dockListUpdate(newRgbColor, colorAdded);
}
Beispiel #11
0
void CGroupList::removeFromGroup(const QModelIndex &group, const QSet<QString> &families)
{
    if(group.isValid())
    {
        CGroupListItem *grp=static_cast<CGroupListItem *>(group.internalPointer());

        if(grp && grp->isCustom())
        {
            QSet<QString>::ConstIterator it(families.begin()),
                                         end(families.end());
            bool                         update(false);

            for(; it!=end; ++it)
                if(removeFromGroup(grp, *it))
                    update=true;

            if(update)
                emit refresh();
        }
    }
}
Beispiel #12
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

}
Beispiel #13
0
CommandRemove::CommandRemove(const QSet<int> &selection, ldraw::model *model)
	: CommandBase(selection, model)
{
  if (selection.size() == 1)
    setText(QObject::tr("Delete an Object"));
  else
    setText(QObject::tr("Delete Objects"));
  
  // QSet is unordered; convert QSet to QMap
  QMap<int, int> temporary;
  for (QSet<int>::ConstIterator it = selection.begin(); it != selection.end(); ++it)
    temporary[*it] = *it;
  
  int i = 0;
  for (QMap<int, int>::ConstIterator it = temporary.begin(); it != temporary.end(); ++it) {
    itemsToRemove_.append(it.key() - i++);
    std::ostringstream stream;
    ldraw::writer writer(stream);
    writer.write(model->at(*it));
    objects_[*it] = stream.str();
  }
}
Beispiel #14
0
bool Drive::recalculate(QList<Tag *> tags) {
    if(this->results_.size() > 0) {
        beginRemoveRows(QModelIndex(), 0, this->results_.size()-1);
        this->results_ = QFileInfoList();
        endRemoveRows();
    }

    QFileInfoList newResults;
    if(tags.size() == 0) {
        this->parent_->setExpressionLabel(tr("All Files"));
        newResults = this->directory_->entryInfoList(QDir::Files);
    } else {
        QString expressionLabel = "";
        QSet<QString> fileNames = tags[0]->allFiles();
        for (int i = 0; i < tags.size(); i += TAG_TREE_COLUMNS) {
            expressionLabel.append(tags[i]->data(0).toString());
            fileNames = fileNames.intersect(tags[i]->allFiles());

             if  (i < tags.size() - TAG_TREE_COLUMNS)
                 expressionLabel.append(tr(" &#x2229; "));
        }
        this->parent_->setExpressionLabel(expressionLabel);

        for(auto i = fileNames.begin(); i != fileNames.end(); ++i) {
            newResults.append(QFileInfo(*i));
        }
    }

    if(newResults.size() > 0) {
        beginInsertRows(QModelIndex(), 0, newResults.size()-1);
        this->results_ = newResults;
        endInsertRows();
    }

    this->sort(this->sortColumn_,this->sortOrder_);
    emit(doneCalculating());
    return true;
}
Beispiel #15
0
void Audex::progress_extract(int percent_of_track, int sector, int overall_sectors_read) {

  if (overall_frames==0) {
    QSet<int> sel = cdda_model->selectedTracks();
    QSet<int>::ConstIterator it(sel.begin()), end(sel.end());
    for (; it!=end; ++it) {
      if ((*it < 0) || (*it > cdda_extract_thread->cddaParanoia()->numOfTracks()) ||
           (!cdda_extract_thread->cddaParanoia()->isAudioTrack((*it)))) {
        continue;
      }
      overall_frames += cdda_extract_thread->cddaParanoia()->numOfFramesOfTrack((*it));
    }
  }

  float fraction = 0.0f;
  if (overall_frames > 0) fraction = (float)overall_sectors_read / (float)overall_frames;

  emit progressExtractTrack(percent_of_track);
  emit progressExtractOverall((int)(fraction*100.0f));

  current_sector = sector;

}
RTransaction RMoveReferencePointOperation::apply(RDocument& document, bool preview) const {
    RTransaction transaction(document.getStorage(), "Moving reference point");

    QSet<REntity::Id> selectedEntities = document.querySelectedEntities();
    QSet<REntity::Id>::iterator it;
    for (it=selectedEntities.begin(); it!=selectedEntities.end(); it++) {
        QSharedPointer<REntity> entity = document.queryEntity(*it);
        if (entity.isNull()) {
            continue;
        }
        
        // apply operation to cloned entity:
        bool modified = entity->moveReferencePoint(referencePoint, targetPoint);
        
        if (modified) {
            transaction.addObject(entity, false);
        }
    }
        
    transaction.end();

    return transaction;
}
Beispiel #17
0
void EventRegistrar::sendRegistration()
{
    Noam::MessageBuilder builder( lemmaId );
    QVariantList plays;
    QVariantList hears;
    QSet<QString> uniqueHears;

    QList< Noam::EventFilter* >::iterator i = filters.begin();
    while ( i != filters.end() )
    {
        uniqueHears << ( (*i)->getTopicName() );
        ++i;
    }

    QSet<QString>::iterator j = uniqueHears.begin();
    while ( j != uniqueHears.end() )
    {
        hears << ( QVariant(*j) );
        ++j;
    }

    QByteArray message = builder.buildRegister( deviceType, systemVersion, port, hears, plays );
    emit registration( message );
}
Beispiel #18
0
void RMemoryStorage::deleteTransactionsFrom(int transactionId) {
    QSet<int> keysToRemove;

    {
        QHash<int, RTransaction>::iterator it;
        for (it = transactionMap.begin(); it!=transactionMap.end(); ++it) {
            if (it.key()>=transactionId) {
                // delete orphaned objects:
                QList<RObject::Id> affectedObjects =
                    it.value().getAffectedObjects();

                QList<RObject::Id>::iterator it2;
                for (it2=affectedObjects.begin(); it2!=affectedObjects.end(); ++it2) {
                    QSharedPointer<RObject> obj = queryObjectDirect(*it2);
                    if (!obj.isNull() && obj->isUndone()) {
                        deleteObject(*it2);
                    }
                }

                // mark transaction for removal:
                keysToRemove.insert(it.key());
            }
        }
    }

    {
        QSet<int>::iterator it;
        for (it=keysToRemove.begin(); it!=keysToRemove.end(); ++it) {
            transactionMap.remove(*it);
        }
    }

    if (!transactionMap.contains(getLastTransactionId())) {
        setLastTransactionId(getMaxTransactionId());
    }
}
Beispiel #19
0
/**
 * Adds the given object to the transaction. Adding an object to a
 * transaction means that this transaction modifies or adds the object.
 * Entities that are added with an invalid layer or block ID are placed
 * on the current layer / block.
 *
 * @param modifiedPropertyTypeId: Property ID that has changed if known 
 *      by caller, NULL otherwise.
 */
bool RTransaction::addObject(QSharedPointer<RObject> object,
    bool useCurrentAttributes,
    bool forceNew,
    const QSet<RPropertyTypeId>& modifiedPropertyTypeIds) {

    if (object.isNull()) {
        qWarning() << "RTransaction::addObject: object is NULL";
        fail();
        return false;
    }
    if (storage == NULL) {
        qWarning() << "RTransaction::addObject: storage is NULL";
        fail();
        return false;
    }
    if (transactionId != -1) {
        qWarning() << "RTransaction::addObject: "
            "Trying to add object to an existing transaction. "
            "Transactions are immutable once committed.";
        fail();
        Q_ASSERT(false);
        return false;
    }
    if (object->getDocument()==NULL) {
        qWarning() << "RTransaction::addObject: "
            "Object is not linked to a document.";
        fail();
        Q_ASSERT(false);
        return false;
    }

    RObject::Id oldId = RObject::INVALID_ID;
    if (forceNew) {
        oldId=object->getId();
        if (object->getId()!=RObject::INVALID_ID) {
            storage->setObjectId(*object, RObject::INVALID_ID);
        }
        if (object->getHandle()!=RObject::INVALID_ID) {
            storage->setObjectHandle(*object, RObject::INVALID_HANDLE);
        }
    }

    RLinkedStorage* ls = dynamic_cast<RLinkedStorage*>(storage);
    bool storageIsLinked = (ls!=NULL);
    RStorage* objectStorage = &object->getDocument()->getStorage();

    if (objectStorage==NULL) {
        qWarning() << "RTransaction::addObject: "
                      "Object storage is NULL.";
        fail();
        Q_ASSERT(false);
        return false;
    }

    if (storageIsLinked && objectStorage!=ls && objectStorage!=ls->getBackStorage()) {
        qWarning() << "RTransaction::addObject: "
            "Object is not in linked storage or back storage of transaction.";
        fail();
        Q_ASSERT(false);
        return false;
    }

    if (!storageIsLinked && objectStorage!=storage) {
        qWarning() << "RTransaction::addObject: "
                      "Object is not in storage of transaction.";
        fail();
        Q_ASSERT(false);
        return false;
    }

    // TODO: add generic way to allow any object not to be cloned here:
    // i.e. if (object.cloneInsteadOfUpdate()) { ... }
//    QSharedPointer<RLinetype> lt = object.dynamicCast<RLinetype>();
//    if (!lt.isNull() && lt->getId()!=RObject::INVALID_ID) {
//        qDebug() << "replace linetype";
//        QSharedPointer<RLinetype> clone = QSharedPointer<RLinetype>(lt->clone());
//        objectStorage->setObjectId(*clone, RObject::INVALID_ID);
//        deleteObject(lt->getId());
//        addObject(clone, useCurrentAttributes, false, modifiedPropertyTypeIds);
//        return true;
//    }

    QSharedPointer<REntity> entity = object.dynamicCast<REntity>();
    bool mustClone = false;
    if (!entity.isNull() && entity->getId()!=REntity::INVALID_ID) {
        QSharedPointer<REntity> oldEntity = storage->queryEntityDirect(entity->getId());
        if (!oldEntity.isNull()) {
            // object is entity and not new:
            if (oldEntity->cloneOnChange()) {
                mustClone = true;
            }
        }
        if (!mustClone) {
            if (entity->getType()==RS::EntityHatch && modifiedPropertyTypeIds.isEmpty()) {
                // entity is hatch and not only property has changed:
                mustClone = true;
            }
        }
    }

    // if object is an existing hatch and we are not just changing a property:
    // delete original and add new since hatch geometry cannot be completely
    // defined through properties which is a requirement for changing objects
    // through transactions:
    if (mustClone) {
        QSharedPointer<REntity> clone = QSharedPointer<REntity>(entity->clone());
        objectStorage->setObjectId(*clone, REntity::INVALID_ID);
        // note that we delete the OLD entity here
        // (old entity is queried from storage since we pass the ID here):
        deleteObject(entity->getId());
        addObject(clone, useCurrentAttributes, false, modifiedPropertyTypeIds);

        // draw order was set to top value automatically by
        // saveObject of RMemoryStorage:
        clone->setDrawOrder(entity->getDrawOrder());
        return true;
    }

    // if object is an entity,
    // place entity on current layer / block, set current pen attributes:
    if (!entity.isNull()) {
        if (useCurrentAttributes || entity->getLayerId()==RLayer::INVALID_ID) {
            entity->setLayerId(object->getDocument()->getCurrentLayerId());
        }
        if (useCurrentAttributes || entity->getBlockId()==RBlock::INVALID_ID) {
            entity->setBlockId(object->getDocument()->getCurrentBlockId());
        }
        if (useCurrentAttributes || !entity->getColor().isValid()) {
            entity->setColor(object->getDocument()->getCurrentColor());
        }
        if (useCurrentAttributes || entity->getLineweight()==RLineweight::WeightInvalid) {
            entity->setLineweight(object->getDocument()->getCurrentLineweight());
        }
        if (useCurrentAttributes || entity->getLinetypeId()==RLinetype::INVALID_ID) {
            entity->setLinetypeId(object->getDocument()->getCurrentLinetypeId());
        }

        // allowAll to make sure entities on hidden / locked layers can be imported:
        if (!allowAll && !entity->isEditable(allowInvisible)) {
            qWarning() << "RTransaction::addObject: entity not editable (locked or hidden layer)";
            fail();
            return false;
        }

        Q_ASSERT_X(!object->getDocument()->queryLayerDirect(entity->getLayerId()).isNull(),
            "RTransaction::addObject",
            "layer of entity is NULL");
    }


    // if object is a block definition,
    // look up existing block based on case insensitive name comparison:
    bool objectIsBlock = false;
    QSharedPointer<RBlock> block = object.dynamicCast<RBlock>();
    if (!block.isNull()) {
        objectIsBlock = true;

        if (!existingBlockDetectionDisabled) {
            QSharedPointer<RBlock> existingBlock = block->getDocument()->queryBlock(block->getName());
            if (!existingBlock.isNull()) {
                storage->setObjectId(*block, existingBlock->getId());
            }
        }
    }

    // if object is a layer,
    // look up existing layer based on case insensitive name comparison:
    if (!existingLayerDetectionDisabled && object->getId()==RObject::INVALID_ID) {
        QSharedPointer<RLayer> layer = object.dynamicCast<RLayer>();
        if (!layer.isNull()) {
            QSharedPointer<RLayer> existingLayer = layer->getDocument()->queryLayer(layer->getName());
            if (!existingLayer.isNull()) {
                storage->setObjectId(*layer, existingLayer->getId());
            }
        }
    }

    // if object is a linetype,
    // look up existing linetype based on case insensitive name comparison:
    if (!existingLinetypeDetectionDisabled && object->getId()==RObject::INVALID_ID) {
        QSharedPointer<RLinetype> linetype = object.dynamicCast<RLinetype>();
        if (!linetype.isNull()) {
            QSharedPointer<RLinetype> existingLinetype = linetype->getDocument()->queryLinetype(linetype->getName());
            if (!existingLinetype.isNull()) {
                storage->setObjectId(*linetype, existingLinetype->getId());
            }
        }
    }

    bool objectHasChanged = false;
    QSharedPointer<RObject> oldObject;

    // object is an existing object that might have changed:
    if (object->getId() != RObject::INVALID_ID) {
        // store diff between previous object and this object
        // as part of this transaction:
        oldObject = storage->queryObjectDirect(object->getId());
        if (oldObject.isNull()) {
            qWarning() << "RTransaction::addObject: original object not found in storage for " << *object;
            fail();
            return false;
        }

        if (typeid(*oldObject) != typeid(*object)) {
            qWarning("RTransaction::addObject: "
                "type of original object and "
                "type of modified object don't match");
            fail();
            return false;
        }

        if (oldObject->getId() != object->getId()) {
            qWarning("RTransaction::addObject: "
                "id of original object and "
                "id of modified object don't match");
            fail();
            return false;
        }

        //qDebug() << "old obj: " << *oldObject;
        //qDebug() << "new obj: " << *object;

        // iterate through all properties of the original object
        // and store the property changes (if any) in this transaction:
        QSet<RPropertyTypeId> propertyTypeIds;
        if (modifiedPropertyTypeIds.isEmpty()) {
            propertyTypeIds = object->getPropertyTypeIds();
        }
        else {
            propertyTypeIds = modifiedPropertyTypeIds;

            // if at least one property is a redundant property, we need to
            // check all properties for changes:
            bool all = false;
            QSet<RPropertyTypeId>::iterator it;
            for (it=propertyTypeIds.begin(); it!=propertyTypeIds.end(); ++it) {
                RPropertyTypeId pid = *it;
                QPair<QVariant, RPropertyAttributes> newProperty =
                    object->getProperty(pid);
                // redundant properties affect other properties:
                if (newProperty.second.isRedundant()) {
                    all = true;
                    break;
                }
            }

            if (all) {
                propertyTypeIds = object->getPropertyTypeIds();
            }
        }

        propertyTypeIds.unite(object->getCustomPropertyTypeIds());
        propertyTypeIds.unite(oldObject->getCustomPropertyTypeIds());

        QSet<RPropertyTypeId>::iterator it;
        for (it=propertyTypeIds.begin(); it!=propertyTypeIds.end(); ++it) {
            RPropertyTypeId pid = *it;
            QPair<QVariant, RPropertyAttributes> newProperty =
                object->getProperty(pid);
            QPair<QVariant, RPropertyAttributes> oldProperty =
                oldObject->getProperty(pid);

//            if (pid==RObject::PropertyProtected) {
//                qDebug() << "pid: " << pid;
//                qDebug() << "old property: " << oldProperty.first;
//                qDebug() << "new property: " << newProperty.first;
//            }

            // don't record changes in redundant properties (e.g. angle for lines):
            if (newProperty.second.isRedundant()) {
                continue;
            }

            // property that has changed affects the visibility of
            // other attributes:
            if (newProperty.second.affectsOtherProperties()) {
                onlyChanges = false;
            }

            objectHasChanged |= addPropertyChange(
                object->getId(),
                RPropertyChange(
                    *it, 
                    oldProperty.first,
                    newProperty.first
                )
            );
        }

        if (objectHasChanged) {
            // remove old entity from storage (only if it has actually changed):
            storage->removeObject(oldObject);

            if (object->getDocument()!=NULL) {
                // only remove from si, if not linked storage / preview
                if (!storage->isInBackStorage(oldObject->getId())) {
                    QSharedPointer<REntity> oldEntity = oldObject.dynamicCast<REntity>();
                    if (!spatialIndexDisabled && !oldEntity.isNull()) {
                        QSharedPointer<RBlockReferenceEntity> blockRef = oldEntity.dynamicCast<RBlockReferenceEntity>();
                        if (blockRef.isNull() || blockRef->getReferencedBlockId()!=RObject::INVALID_ID) {
                            object->getDocument()->removeFromSpatialIndex(oldEntity);
                        }
                    }
                }
            }
        }
    }

    bool ret = true;

    // object is a new object or an existing object that has changed:
    if (object->getId()==RObject::INVALID_ID || objectHasChanged ||
        // always add block to linked storage to make sure that
        // block entities are found in linked storage:
        (objectIsBlock && storageIsLinked)) {

        // new object:
        if (object->getId()==RObject::INVALID_ID) {
            onlyChanges = false;
        }

        ret = storage->saveObject(object, !blockRecursionDetectionDisabled, keepHandles);

        if (!ret) {
            qCritical() << "RTransaction::addObject: saveObject() failed for object: ";
            qCritical() << *object;
        }

        else {

            if (oldId!=RObject::INVALID_ID) {
                cloneIds.insert(oldId, object->getId());
            }

            addAffectedObject(object);

            if (object->getDocument()!=NULL) {
                // only add to si, if not linked storage / preview
                if (!storageIsLinked) {
                    QSharedPointer<REntity> entity = object.dynamicCast<REntity>();
                    if (!spatialIndexDisabled && !entity.isNull()) {
                        QSharedPointer<RBlockReferenceEntity> blockRef = entity.dynamicCast<RBlockReferenceEntity>();
                        if (blockRef.isNull() || blockRef->getReferencedBlockId()!=RObject::INVALID_ID) {
                            object->getDocument()->addToSpatialIndex(entity);
                        }

                        // update block references if entity has been changed inside a block
                        // that is not the current block (in block editing):
                        if (entity->getBlockId()!=storage->getCurrentBlockId()) {
                            affectedBlockReferenceIds.unite(storage->queryBlockReferences(entity->getBlockId()));
                        }
                    }
                }
            }

            if (!objectHasChanged) {
                statusChanges.insert(object->getId());
            }
        }
    }
    if (!ret) {
        fail();
    }

    return ret;
}
void QgsComposerView::keyPressEvent( QKeyEvent * e )
{
  if ( e->key() == Qt::Key_Shift )
  {
    mShiftKeyPressed = true;
  }

  if ( !composition() )
  {
    return;
  }

  QList<QgsComposerItem*> composerItemList = composition()->selectedComposerItems();
  QList<QgsComposerItem*>::iterator itemIt = composerItemList.begin();

  if ( e->matches( QKeySequence::Copy ) || e->matches( QKeySequence::Cut ) )
  {
    QDomDocument doc;
    QDomElement documentElement = doc.createElement( "ComposerItemClipboard" );
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      // copy each item in a group
      QgsComposerItemGroup* itemGroup = dynamic_cast<QgsComposerItemGroup*>( *itemIt );
      if ( itemGroup && composition() )
      {
        QSet<QgsComposerItem*> groupedItems = itemGroup->items();
        QSet<QgsComposerItem*>::iterator it = groupedItems.begin();
        for ( ; it != groupedItems.end(); ++it )
        {
          ( *it )->writeXML( documentElement, doc );
        }
      }
      ( *itemIt )->writeXML( documentElement, doc );
      if ( e->matches( QKeySequence::Cut ) )
      {
        composition()->removeComposerItem( *itemIt );
      }
    }
    doc.appendChild( documentElement );
    QMimeData *mimeData = new QMimeData;
    mimeData->setData( "text/xml", doc.toByteArray() );
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setMimeData( mimeData );
  }

  if ( e->matches( QKeySequence::Paste ) )
  {
    QDomDocument doc;
    QClipboard *clipboard = QApplication::clipboard();
    if ( doc.setContent( clipboard->mimeData()->data( "text/xml" ) ) )
    {
      QDomElement docElem = doc.documentElement();
      if ( docElem.tagName() == "ComposerItemClipboard" )
      {
        if ( composition() )
        {
          QPointF pt = mapToScene( mapFromGlobal( QCursor::pos() ) );
          composition()->addItemsFromXML( docElem, doc, true, &pt );
        }
      }
    }
  }

  //delete selected items
  if ( e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      if ( composition() )
      {
        composition()->removeComposerItem( *itemIt );
      }
    }
  }

  else if ( e->key() == Qt::Key_Left )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( -1.0, 0.0 );
    }
  }
  else if ( e->key() == Qt::Key_Right )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( 1.0, 0.0 );
    }
  }
  else if ( e->key() == Qt::Key_Down )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( 0.0, 1.0 );
    }
  }
  else if ( e->key() == Qt::Key_Up )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( 0.0, -1.0 );
    }
  }
}
QPair<QVariant, RPropertyAttributes> RBlockReferenceEntity::getProperty(
        RPropertyTypeId& propertyTypeId,
        bool humanReadable, bool noAttributes) {

    if (propertyTypeId == PropertyPositionX) {
        return qMakePair(QVariant(data.position.x), RPropertyAttributes());
    } else if (propertyTypeId == PropertyPositionY) {
        return qMakePair(QVariant(data.position.y), RPropertyAttributes());
    } else if (propertyTypeId == PropertyPositionZ) {
        return qMakePair(QVariant(data.position.z), RPropertyAttributes());
    } else if (propertyTypeId == PropertyScaleX) {
        return qMakePair(QVariant(data.scaleFactors.x), RPropertyAttributes());
    } else if (propertyTypeId == PropertyScaleY) {
        return qMakePair(QVariant(data.scaleFactors.y), RPropertyAttributes());
    } else if (propertyTypeId == PropertyScaleZ) {
        return qMakePair(QVariant(data.scaleFactors.z), RPropertyAttributes());
    } else if (propertyTypeId == PropertyRotation) {
        return qMakePair(QVariant(data.rotation), 
            RPropertyAttributes(RPropertyAttributes::Angle));
    } else if (propertyTypeId == PropertyReferencedBlock) {
        if (humanReadable) {
            RDocument* document = getData().getDocument();
            if (document != NULL) {
                RPropertyAttributes attr;
                // TODO
                if (!noAttributes) {
                    QSet<QString> blockNames = document->getBlockNames();
                    QSet<QString> filtered;
                    QSet<QString>::iterator it;
                    for (it=blockNames.begin(); it!=blockNames.end(); it++) {
                        if (!(*it).startsWith("*")) {
                            filtered.insert(*it);
                        }
                    }
                    attr.setChoices(filtered);
                }
                return qMakePair(QVariant(document->getBlockName(
                        getData().getReferencedBlockId())), attr);
            }
        } else {
            return qMakePair(QVariant(getData().getReferencedBlockId()),
                    RPropertyAttributes());
        }
    }
    else if (propertyTypeId.isCustom()) {
        if (propertyTypeId.getCustomPropertyTitle()=="Attributes") {
            QString tag = propertyTypeId.getCustomPropertyName();

            const RDocument* doc = getDocument();
            if (doc!=NULL) {
                QSet<REntity::Id> childIds = doc->queryChildEntities(getId(), RS::EntityAttribute);
                QSet<REntity::Id>::iterator it;
                for (it=childIds.begin(); it!=childIds.end(); it++) {
                    REntity::Id childId = *it;
                    QSharedPointer<REntity> child = doc->queryEntityDirect(childId);
                    if (child.isNull()) {
                        continue;
                    }

                    QSet<RPropertyTypeId> childProperties = child->getPropertyTypeIds();
                    QSet<RPropertyTypeId>::iterator it2;
                    for (it2=childProperties.begin(); it2!=childProperties.end(); it2++) {
                        RPropertyTypeId pid = *it2;
                        QPair<QVariant, RPropertyAttributes> p = child->getProperty(pid);
                        if (p.second.isVisibleToParent() && pid.getCustomPropertyName()==tag) {
                            //ret.insert(RPropertyTypeId(QT_TRANSLATE_NOOP("REntity", "Attributes"), p.first.toString()));
                            return qMakePair(QVariant(p.first), RPropertyAttributes());
                        }
                    }
                }
            }

            //document->queryChildEntities(getId());

            //return qMakePair(QVariant("Dummy"), RPropertyAttributes());
        }
    }

    return REntity::getProperty(propertyTypeId, humanReadable, noAttributes);
}
bool RBlockReferenceEntity::setProperty(RPropertyTypeId propertyTypeId,
        const QVariant& value, RTransaction* transaction) {
    bool ret = REntity::setProperty(propertyTypeId, value, transaction);

//    if (propertyTypeId==PropertyPositionX) {
//        double d = value - data.position.x;
//        RObject::setMember(data.position.x, value);

//        const RDocument* doc = getDocument();
//        if (doc!=NULL) {
//            QSet<REntity::Id> childIds = doc->queryChildEntities(getId(), RS::EntityAttribute);
//            QSet<REntity::Id>::iterator it;
//            for (it=childIds.begin(); it!=childIds.end(); it++) {
//                REntity::Id childId = *it;
//                QSharedPointer<REntity> child = doc->queryEntity(childId);
//                if (child.isNull()) {
//                    continue;
//                }

//                QSet<RPropertyTypeId> childProperties = child->getPropertyTypeIds();
//                QSet<RPropertyTypeId>::iterator it2;
//                for (it2=childProperties.begin(); it2!=childProperties.end(); it2++) {
//                    RPropertyTypeId pid = *it2;
//                    QPair<QVariant, RPropertyAttributes> p = child->getProperty(pid);
//                    if (p.second.isVisibleToParent() && pid.getCustomPropertyName()==tag) {
//                        //ret.insert(RPropertyTypeId(QT_TRANSLATE_NOOP("REntity", "Attributes"), p.first.toString()));
//                        //return qMakePair(QVariant(p.first), RPropertyAttributes());
//                        child->setProperty(pid, value.toString(), transaction);
//                        transaction->addObject(child);
//                    }
//                }
//            }
//        }
//    }

    ret = ret || RObject::setMember(data.position.x, value, PropertyPositionX == propertyTypeId);
    ret = ret || RObject::setMember(data.position.y, value, PropertyPositionY == propertyTypeId);
    ret = ret || RObject::setMember(data.position.z, value, PropertyPositionZ == propertyTypeId);

    ret = ret || RObject::setMember(data.scaleFactors.x, value, PropertyScaleX == propertyTypeId && fabs(value.toDouble())>RS::PointTolerance);
    ret = ret || RObject::setMember(data.scaleFactors.y, value, PropertyScaleY == propertyTypeId && fabs(value.toDouble())>RS::PointTolerance);
    ret = ret || RObject::setMember(data.scaleFactors.z, value, PropertyScaleZ == propertyTypeId && fabs(value.toDouble())>RS::PointTolerance);

    ret = ret || RObject::setMember(data.rotation, value, PropertyRotation == propertyTypeId);

    if (propertyTypeId == PropertyReferencedBlock) {
        if (value.type() == QVariant::Int ||
            value.type() == QVariant::LongLong) {

            ret = ret || RObject::setMember(
                getData().referencedBlockId, value.toInt(), true);
        } else if (value.type() == QVariant::String) {
            RDocument* document = getData().getDocument();
            if (document != NULL) {
                ret = ret || RObject::setMember(getData().referencedBlockId,
                        document->getBlockId(value.toString()), true);
            }
        }
    }

    // allow editing of attributes in the context of a block reference:
    if (transaction && propertyTypeId.isCustom()) {
        if (propertyTypeId.getCustomPropertyTitle()=="Attributes") {
            QString tag = propertyTypeId.getCustomPropertyName();

            const RDocument* doc = getDocument();
            if (doc!=NULL) {
                QSet<REntity::Id> childIds = doc->queryChildEntities(getId(), RS::EntityAttribute);
                QSet<REntity::Id>::iterator it;
                for (it=childIds.begin(); it!=childIds.end(); it++) {
                    REntity::Id childId = *it;
                    QSharedPointer<REntity> child = doc->queryEntity(childId);
                    if (child.isNull()) {
                        continue;
                    }

                    QSet<RPropertyTypeId> childProperties = child->getPropertyTypeIds();
                    QSet<RPropertyTypeId>::iterator it2;
                    for (it2=childProperties.begin(); it2!=childProperties.end(); it2++) {
                        RPropertyTypeId pid = *it2;
                        QPair<QVariant, RPropertyAttributes> p = child->getProperty(pid);
                        if (p.second.isVisibleToParent() && pid.getCustomPropertyName()==tag) {
                            //ret.insert(RPropertyTypeId(QT_TRANSLATE_NOOP("REntity", "Attributes"), p.first.toString()));
                            //return qMakePair(QVariant(p.first), RPropertyAttributes());
                            child->setProperty(pid, value.toString(), transaction);
                            transaction->addObject(child);
                        }
                    }
                }
            }
        }
    }

    if (ret) {
        data.update();
    }

    return ret;
}
Beispiel #23
0
/*!
  Processes the qdoc config file \a fileName. This is the
  controller for all of qdoc.
 */
static void processQdocconfFile(const QString &fileName)
{
#ifndef QT_NO_TRANSLATION
    QList<QTranslator *> translators;
#endif

    /*
      The Config instance represents the configuration data for qdoc.
      All the other classes are initialized with the config. Here we
      initialize the configuration with some default values.
     */
    Config config(tr("qdoc"));
    int i = 0;
    while (defaults[i].key) {
	config.setStringList(defaults[i].key,
                             QStringList() << defaults[i].value);
	++i;
    }
    config.setStringList(CONFIG_SLOW, QStringList(slow ? "true" : "false"));
    config.setStringList(CONFIG_SHOWINTERNAL,
                         QStringList(showInternal ? "true" : "false"));
    config.setStringList(CONFIG_OBSOLETELINKS,
                         QStringList(obsoleteLinks ? "true" : "false"));

    /*
      With the default configuration values in place, load
      the qdoc configuration file. Note that the configuration
      file may include other configuration files.

      The Location class keeps track of the current location
      in the file being processed, mainly for error reporting
      purposes.
     */
    Location::initialize(config);
    config.load(fileName);

    /*
      Add the defines to the configuration variables.
     */
    QStringList defs = defines + config.getStringList(CONFIG_DEFINES);
    config.setStringList(CONFIG_DEFINES,defs);
    Location::terminate();

    QString prevCurrentDir = QDir::currentPath();
    QString dir = QFileInfo(fileName).path();
    if (!dir.isEmpty())
	QDir::setCurrent(dir);

    /*
      Initialize all the classes and data structures with the
      qdoc configuration.
     */
    Location::initialize(config);
    Tokenizer::initialize(config);
    Doc::initialize(config);
    CppToQsConverter::initialize(config);
    CodeMarker::initialize(config);
    CodeParser::initialize(config);
    Generator::initialize(config);

#ifndef QT_NO_TRANSLATION
    /*
      Load the language translators, if the configuration specifies any.
     */
    QStringList fileNames = config.getStringList(CONFIG_TRANSLATORS);
    QStringList::Iterator fn = fileNames.begin();
    while (fn != fileNames.end()) {
	QTranslator *translator = new QTranslator(0);
	if (!translator->load(*fn))
	    config.lastLocation().error(tr("Cannot load translator '%1'")
					 .arg(*fn));
	QCoreApplication::instance()->installTranslator(translator);
	translators.append(translator);
	++fn;
    }
#endif

    //QSet<QString> outputLanguages = config.getStringSet(CONFIG_OUTPUTLANGUAGES);

    /*
      Get the source language (Cpp) from the configuration
      and the location in the configuration file where the
      source language was set.
     */
    QString lang = config.getString(CONFIG_LANGUAGE);
    Location langLocation = config.lastLocation();

    /*
      Initialize the tree where all the parsed sources will be stored.
      The tree gets built as the source files are parsed, and then the
      documentation output is generated by traversing the tree.
     */
    Tree *tree = new Tree;
    tree->setVersion(config.getString(CONFIG_VERSION));

    /*
      There must be a code parser for the source code language, e.g. C++.
      If there isn't one, give up.
     */
    CodeParser *codeParser = CodeParser::parserForLanguage(lang);
    if (codeParser == 0)
        config.lastLocation().fatal(tr("Cannot parse programming language '%1'").arg(lang));

    /*
      By default, the only output format is HTML.
     */
    QSet<QString> outputFormats = config.getStringSet(CONFIG_OUTPUTFORMATS);
    Location outputFormatsLocation = config.lastLocation();

    /*
      There must be a code marker for the source code language, e.g. C++.
      If there isn't one, give up.
     */
    CodeMarker *marker = CodeMarker::markerForLanguage(lang);
    if (!marker && !outputFormats.isEmpty())
	langLocation.fatal(tr("Cannot output documentation for programming language '%1'").arg(lang));

    /*
      Read some XML indexes. What are they??? 
     */
    QStringList indexFiles = config.getStringList(CONFIG_INDEXES);
    tree->readIndexes(indexFiles);
    
    /*
      Get all the header files: "*.ch *.h *.h++ *.hh *.hpp *.hxx"
      Put them in a set.
     */
    QSet<QString> excludedDirs;
    QStringList excludedDirsList = config.getStringList(CONFIG_EXCLUDEDIRS);
    foreach (const QString &excludeDir, excludedDirsList)
        excludedDirs.insert(QDir::fromNativeSeparators(excludeDir));
    QSet<QString> headers = QSet<QString>::fromList(
        config.getAllFiles(CONFIG_HEADERS, CONFIG_HEADERDIRS,
                           codeParser->headerFileNameFilter(),
                           excludedDirs));

    /*
      Parse each header file in the set and add it to the big tree.
     */
    QSet<QString>::ConstIterator h = headers.begin();
    while (h != headers.end()) {
	codeParser->parseHeaderFile(config.location(), *h, tree);
	++h;
    }
    codeParser->doneParsingHeaderFiles(tree);

    /*
      Get all the source text files: "*.cpp *.qdoc *.mm"
      Put them in a set.
     */
    QSet<QString> sources = QSet<QString>::fromList(
        config.getAllFiles(CONFIG_SOURCES, CONFIG_SOURCEDIRS,
                           codeParser->sourceFileNameFilter(),
                           excludedDirs));

    /*
      Parse each source text file in the set and add it to the big tree.
     */
    QSet<QString>::ConstIterator s = sources.begin();
    while (s != sources.end()) {
	codeParser->parseSourceFile(config.location(), *s, tree);
	++s;
    }
    codeParser->doneParsingSourceFiles(tree);

    /*
      Now the big tree has been built from all the header and
      source files. Resolve all the class names, function names,
      targets, URLs, links, and other stuff that needs resolving.
     */
    tree->resolveGroups();
    tree->resolveTargets();

    /*
      Now the tree has been built, and all the stuff that needed
      resolving has been resolved. Now it is time to traverse
      the big tree and generate the documentation output.
     */
    QSet<QString>::ConstIterator of = outputFormats.begin();
    while (of != outputFormats.end()) {
        Generator *generator = Generator::generatorForFormat(*of);
        if (generator == 0)
            outputFormatsLocation.fatal(tr("Unknown output format '%1'")
                                        .arg(*of));
        generator->generateTree(tree, marker);
        ++of;
    }

    /*
      Generate the XML tag file, if it was requested.
     */
    QString tagFile = config.getString(CONFIG_TAGFILE);
    if (!tagFile.isEmpty()) {
        tree->generateTagFile(tagFile);
    }

    tree->setVersion("");
    Generator::terminate();
    CodeParser::terminate();
    CodeMarker::terminate();
    CppToQsConverter::terminate();
    Doc::terminate();
    Tokenizer::terminate();
    Location::terminate();
    QDir::setCurrent(prevCurrentDir);

#ifndef QT_NO_TRANSLATION
    qDeleteAll(translators);
#endif
#ifdef DEBUG_SHUTDOWN_CRASH    
    qDebug() << "main(): Delete tree";
#endif    
    delete tree;
#ifdef DEBUG_SHUTDOWN_CRASH    
    qDebug() << "main(): Tree deleted";
#endif
}
Beispiel #24
0
vector<Radians> NodeMatcher::calculateAngles(const OsmMap* map, long nid,
                                             const set<long>& wids, Meters delta)
{
  vector<Radians> result;
  result.reserve(wids.size());

  LOG_VART(nid);
  QSet<long> badWayIds;
  for (set<long>::const_iterator it = wids.begin(); it != wids.end(); ++it)
  {
    const ConstWayPtr& w = map->getWay(*it);
    LOG_VART(w->getId());
    LOG_VART(w->getLastNodeId());
    LOG_VART(w->getNodeId(0));

    if (!isNetworkFeatureType(w))
    {
      // if this isn't a feature from a specific list, then don't consider it.
      LOG_TRACE("calculateAngles skipping feature...");
    }
    else if (w->getNodeId(0) == nid)
    {
      LOG_TRACE("Start node: " << nid);
      WayLocation wl(map->shared_from_this(), w, 0, 0.0);
      Radians heading = WayHeading::calculateHeading(wl, delta);
      // This is the first node so the angle is an inbound angle, reverse the value.
      if (heading < 0.0)
      {
        heading += M_PI;
      }
      else
      {
        heading -= M_PI;
      }
      LOG_VART(heading);
      result.push_back(heading);
    }
    else if (w->getLastNodeId() == nid)
    {
      LOG_TRACE("End node: " << nid);
      WayLocation wl(map->shared_from_this(), w, w->getNodeCount() - 1, 1.0);
      Radians heading = WayHeading::calculateHeading(wl, delta);
      LOG_VART(heading);
      result.push_back(heading);
    }
    else
    {
      // count this as a bad spot. If we find some valid spots and some bad spots then that is an
      // error condition
      badWayIds.insert(w->getId());
    }
  }

  LOG_VART(badWayIds.size());
  LOG_VART(result.size());
  if (result.size() > 0 && badWayIds.size() > 0)
  {
    LOG_TRACE(
      "Found " << badWayIds.size() << " bad spot(s) in NodeMatcher when calculating angles " <<
      "with node: " << nid);
    LOG_TRACE("wids: " << badWayIds);
    for (QSet<long>::const_iterator it = badWayIds.begin(); it != badWayIds.end(); ++it)
    {
      const ConstWayPtr& w = map->getWay(*it);
      LOG_VART(w->getId());
      LOG_VART(w->getTags().get("REF1"));
      LOG_VART(w->getTags().get("REF2"));
      LOG_VART(w->getNodeIndex(nid));
      LOG_VART(w->getNodeId(0));
      LOG_VART(w->getLastNodeId());
    }

    if (ConfigOptions().getNodeMatcherFailOnBadAngleSpots())
    {
      throw HootException(
        QString("NodeMatcher::calculateAngles was called with a node that was not a start or ") +
        QString("end node on the specified way."));
    }
  }

  return result;
}
Beispiel #25
0
void FlyAI::advanceThinking()
{
    double dt = m_dt;
    m_state.m_age += dt;
    if (m_state.m_age > m_maxAge)
    {
        emit(maxAgeReached());
        return;
    }

    QSet<MoveDirection> moveDirections;
    m_gameDataProvider->getMovesFromPoint(m_state.m_pos, moveDirections);
    if (moveDirections.empty())
    {
        m_choosenMove = MoveDirection::MdUnknown;
        //qDebug() << "No move directions. Waiting";
        return;
    }

    m_thinkingTime += dt;
    bool timeIsElapsed = m_thinkingTime >= m_maxThinkTime * FlyAI::MinThinkElaps;
    bool maxTimeIsElapsed = m_thinkingTime >= m_maxThinkTime;

    if (m_choosenMove == MoveDirection::MdUnknown || !moveDirections.contains(m_choosenMove) || frand() > 0.95)
    {
        int choosenIndex = int(frand() * (double)(moveDirections.count()));
        auto dirIt = moveDirections.begin();
        while(choosenIndex > 0)
        {
            dirIt ++;
            --choosenIndex;
        }
        m_choosenMove = *dirIt;
    }

    m_state.m_angle = angleFromDirection(m_choosenMove);

    if (timeIsElapsed)
    {
        if (frand() > 0.5)
        {
            if (m_choosenMove != MoveDirection::MdUnknown && moveDirections.contains(m_choosenMove))
            {
                m_targetSpot = m_gameDataProvider->getPointByDirection(m_state.m_pos, m_choosenMove);
            }
            else
            {
                int choosenIndex = int(frand() * (double)(moveDirections.count()));
                auto dirIt = moveDirections.begin();
                while(choosenIndex > 0)
                {
                    dirIt ++;
                    --choosenIndex;
                }
                m_choosenMove = *dirIt;

                m_targetSpot = m_gameDataProvider->getPointByDirection(m_state.m_pos, m_choosenMove);
            }
            std::shared_ptr<QPointF> part = m_gameDataProvider->getFreeLandingPoint(m_targetSpot);
            if (!part)
            {
                qWarning() << "Can't move to choosen direction. Continue thinking";
                return;
            }
            m_targetSpotPart = *part;
            qDebug() << "Direction: " << m_choosenMove << " target spot: " << m_targetSpotPart << "(" << m_targetSpot << ")";
            emit(thinkTimeout());
        }
    }

    if (maxTimeIsElapsed)
    {
        if (m_choosenMove != MoveDirection::MdUnknown && moveDirections.contains(m_choosenMove))
        {
            m_targetSpot = m_gameDataProvider->getPointByDirection(m_state.m_pos, m_choosenMove);
        }
        else
        {
            m_targetSpot = m_gameDataProvider->getPointByDirection(m_state.m_pos, *(moveDirections.begin()));
        }
        std::shared_ptr<QPointF> part = m_gameDataProvider->getFreeLandingPoint(m_targetSpot);
        if (!part)
        {
            qWarning() << "Can't move to choosen direction. Continue thinking";
            return;
        }
        m_targetSpotPart = *part;
        qDebug() << "Direction: " << m_choosenMove << " target spot: " << m_targetSpotPart << "(" << m_targetSpot << ")";
        emit(thinkTimeout());
    }
}
Beispiel #26
0
QVariant TrackViewModel::diskData(const Disk *disk, const QModelIndex &index, int role) const
{
    // Display & Edit :::::::::::::::::::::::::::::::::::
    if (role == Qt::DisplayRole || role == Qt::EditRole )
    {
        if (!disk->count())
            return QVariant();

        QSet<QString> values;

        switch (index.column())
        {
        case TrackView::ColumnTitle:
            for (int i=0; i<disk->count(); ++i)
                values << disk->track(i)->title();
            break;

        case TrackView::ColumnArtist:
            for (int i=0; i<disk->count(); ++i)
                values << disk->track(i)->artist();
            break;

        case TrackView::ColumnAlbum:
            for (int i=0; i<disk->count(); ++i)
                values << disk->track(i)->album();
            break;
        }

        if (values.count() > 1)
        {
            return QVariant(tr("Multiple values"));
        }
        else if (values.count() == 1)
        {
            return QVariant(*(values.begin()));
        }

        return QVariant();
    }

    // ToolTip ::::::::::::::::::::::::::::::::::::::::::
    if (role == Qt::ToolTipRole)
    {
        QString s;
        if (!disk->canConvert(&s))
            return QVariant(tr("The conversion is not possible.\n%1").arg(s));
        else
            return QVariant();

    }

//# StatusPercent ::::::::::::::::::::::::::::::::::::
//elif (role == self.StatusPercentRole):
//    try:
//        return QVariant(self._downloadsStates[index.row()])
//    except KeyError:
//        return QVariant()

//# Download pixmap ::::::::::::::::::::::::::::::::::
//elif role == self.DownloadPxmapRole:
//    try:
//        self._downloadsStates[index.row()]
//        return QVariant(self._downloadMovie.currentPixmap())
//    except KeyError:
//        return QVariant()


    return QVariant();

}
Beispiel #27
0
void Render::renderizaFaces()
{
    HalfEdge *partida;
    HalfEdge::iterator it;
    bool renderizaExterna = false;

    if(vsel != NULL)
        partida = vsel->getEdge();
    if(hsel != NULL)
        partida = hsel;
    if(fsel != NULL)
        partida = fsel->getHalfEdge();

    if(vsel != NULL)
    {
        if(interface.isExterna(partida->getFace()))
            renderizaExterna = true;
        else
            renderizaFace(partida, frontBuffer,vizinhoScreen);
        for(it = partida->v_begin(); it != partida->v_end(); ++it)
        {
            if(interface.isExterna(it->getFace()))
                renderizaExterna = true;
            else
                renderizaFace(&it, frontBuffer,vizinhoScreen);
        }
    }

    if(hsel != NULL)
    {
        if(interface.isExterna(partida->getFace()))
            renderizaExterna = true;
        else
            renderizaFace(partida, frontBuffer,vizinhoScreen);

        if(interface.isExterna(partida->getTwin()->getFace()))
            renderizaExterna = true;
        else
            renderizaFace(partida->getTwin(), frontBuffer,vizinhoScreen);
    }

    QVector<HalfEdge *> *v;
    QSet<Face*> f;
    if(fsel != NULL)
    {
        if(interface.isExterna(fsel))
            v = &(interface.componentesFaceExterna);
        else
        {
            v = new QVector<HalfEdge *>();
            v->push_back(partida->getTwin());
        }
        for(int i = 0; i < v->size(); ++i)
        {
            partida = v->at(i)->getTwin();

            if(interface.isExterna(partida->getTwin()->getFace()))
                renderizaExterna = true;
            else
                renderizaFace(partida->getTwin(), frontBuffer,vizinhoScreen);
            for(it = partida->f_begin(); it != partida->f_end(); ++it)
            {
                if(interface.isExterna(it->getTwin()->getFace()))
                    renderizaExterna = true;
                else
                    f.insert(it->getTwin()->getFace());
            }
        }
        if(!interface.isExterna(fsel))
            delete v;
        QSet<Face*>::iterator jt;
        for(jt = f.begin(); jt != f.end(); ++jt)
            renderizaFace((*jt)->getHalfEdge(), frontBuffer,vizinhoScreen);
    }


    if(renderizaExterna)
        renderizaFaceExterna(&vizinhoScreen);
}
Beispiel #28
0
/**
 * Updates the property editor to contain the properties of the
 * property owners that are selected for editing in the given
 * property owner container.
 */
void RPropertyEditor::updateFromDocument(RDocument* document,
    bool onlyChanges, RS::EntityType entityTypeFilter) {

    if (updatesDisabled) {
        return;
    }

    if (document == NULL) {
        clearEditor();
        return;
    }

    combinedProperties.clear();
    combinedTypes.clear();
    propertyOrder.clear();
    groupOrder.clear();

    updatesDisabled = true;

    // add all properties of the entities in the given document:
    QSet<RObject::Id> entityIds = document->querySelectedEntities();
    QSet<RObject::Id>::iterator it;
    for (it = entityIds.begin(); it != entityIds.end(); ++it) {
        QSharedPointer<REntity> entity = document->queryEntityDirect(*it);
        if (entity.isNull()) {
            continue;
        }
        if (entityTypeFilter!=RS::EntityAll && entity->getType()!=entityTypeFilter) {
            continue;
        }

        updateEditor(*entity.data(), false, document);
    }

    // remove properties that are not shared by all selected entities:
    for (it = entityIds.begin(); it != entityIds.end(); ++it) {
        QSharedPointer<REntity> entity = document->queryEntityDirect(*it);
        if (entity.isNull()) {
            continue;
        }

        QPair<QVariant, RPropertyAttributes> p = entity->getProperty(REntity::PropertyType);
        RS::EntityType type = (RS::EntityType)p.first.toInt();
        if (combinedTypes.contains(type)) {
            combinedTypes[type]++;
        }
        else {
            combinedTypes.insert(type, 1);
        }

        if (entityTypeFilter!=RS::EntityAll && entity->getType()!=entityTypeFilter) {
            continue;
        }

        QSet<RPropertyTypeId> propertyTypeIds = entity->getPropertyTypeIds();
        QMultiMap<QString, QString> propertiesToKeep;
        QSet<RPropertyTypeId>::iterator it;
        for (it = propertyTypeIds.begin(); it != propertyTypeIds.end(); ++it) {
            propertiesToKeep.insert(it->getPropertyGroupTitle(),
                                    it->getPropertyTitle());
        }
        removeAllButThese(propertiesToKeep);
    }

    updateGui(onlyChanges, entityTypeFilter);

    updatesDisabled = false;
}
Beispiel #29
0
/**
 * Calls \ref exportEntity() for all given entities.
 */
void RExporter::exportEntities(QSet<REntity::Id>& entityIds, bool allBlocks) {
    QSet<REntity::Id>::iterator it;
    for (it=entityIds.begin(); it!=entityIds.end(); ++it) {
        exportEntity(*it, allBlocks);
    }
}
Beispiel #30
0
TagEditor::TagEditor(QWidget *parent, const QList<Song> &songs,
                     const QSet<QString> &existingArtists, const QSet<QString> &existingAlbumArtists, const QSet<QString> &existingComposers,
                     const QSet<QString> &existingAlbums, const QSet<QString> &existingGenres, const QString &udi)
    : Dialog(parent, "TagEditor", QSize(500, 200))
    #ifdef ENABLE_DEVICES_SUPPORT
    , deviceUdi(udi)
    #endif
    , currentSongIndex(-1)
    , updating(false)
    , haveArtists(false)
    , haveAlbumArtists(false)
    , haveComposers(false)
    , haveAlbums(false)
    , haveGenres(false)
    , saving(false)
{
    iCount++;
    foreach (const Song &s, songs) {
        if (CueFile::isCue(s.file)) {
            continue;
        }
        if (s.guessed) {
            Song song(s);
            song.revertGuessedTags();
            original.append(song);
        } else {
            original.append(s);
        }
    }

    if (original.isEmpty()) {
        deleteLater();
        return;
    }

    #ifdef ENABLE_DEVICES_SUPPORT
    if (deviceUdi.isEmpty()) {
        baseDir=MPDConnection::self()->getDetails().dir;
    } else {
        Device *dev=getDevice(udi, parentWidget());

        if (!dev) {
            deleteLater();
            return;
        }

        baseDir=dev->path();
    }
    #else
    Q_UNUSED(udi)
    baseDir=MPDConnection::self()->getDetails().dir;
    #endif
    qSort(original);

    QWidget *mainWidet = new QWidget(this);
    setupUi(mainWidet);
    track->setAllowEmpty();
    disc->setAllowEmpty();
    year->setAllowEmpty();
    setMainWidget(mainWidet);
    ButtonCodes buttons=Ok|Cancel|Reset|User3;
    if (songs.count()>1) {
        buttons|=User2|User1;
    }
    setButtons(buttons);
    setCaption(i18n("Tags"));
    progress->setVisible(false);
    if (songs.count()>1) {
        setButtonGuiItem(User2, StdGuiItem::back(true));
        setButtonGuiItem(User1,StdGuiItem::forward(true));
        enableButton(User1, false);
        enableButton(User2, false);
    }
    setButtonGuiItem(Ok, StdGuiItem::save());
    setButtonGuiItem(User3, GuiItem(i18n("Tools"), "tools-wizard"));
    QMenu *toolsMenu=new QMenu(this);
    toolsMenu->addAction(i18n("Apply \"Various Artists\" Workaround"), this, SLOT(applyVa()));
    toolsMenu->addAction(i18n("Revert \"Various Artists\" Workaround"), this, SLOT(revertVa()));
    toolsMenu->addAction(i18n("Set 'Album Artist' from 'Artist'"), this, SLOT(setAlbumArtistFromArtist()));
    toolsMenu->addAction(i18n("Capitalize"), this, SLOT(capitalise()));
    toolsMenu->addAction(i18n("Adjust Track Numbers"), this, SLOT(adjustTrackNumbers()));
    setButtonMenu(User3, toolsMenu, InstantPopup);
    enableButton(Ok, false);
    enableButton(Reset, false);

    setAttribute(Qt::WA_DeleteOnClose);

    QStringList strings=existingArtists.toList();
    strings.sort();
    artist->clear();
    artist->insertItems(0, strings);

    strings=existingAlbumArtists.toList();
    strings.sort();
    albumArtist->clear();
    albumArtist->insertItems(0, strings);

    strings=existingComposers.toList();
    strings.sort();
    composer->clear();
    composer->insertItems(0, strings);

    strings=existingAlbums.toList();
    strings.sort();
    album->clear();
    album->insertItems(0, strings);

    strings=existingGenres.toList();
    strings.sort();
    genre->clear();
    genre->insertItems(0, strings);

    trackName->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    trackName->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength);
    trackName->view()->setTextElideMode(Qt::ElideLeft);

    if (original.count()>1) {
        QSet<QString> songArtists;
        QSet<QString> songAlbumArtists;
        QSet<QString> songAlbums;
        QSet<QString> songGenres;
        QSet<QString> songComposers;
        QSet<int> songYears;
        QSet<int> songDiscs;

        foreach (const Song &s, original) {
            if (!s.artist.isEmpty()) {
                songArtists.insert(s.artist);
            }
            if (!s.albumartist.isEmpty()) {
                songAlbumArtists.insert(s.albumartist);
            }
            if (!s.album.isEmpty()) {
                songAlbums.insert(s.album);
            }
            if (!s.genre.isEmpty()) {
                songGenres.insert(s.genre);
            }
            if (!s.composer.isEmpty()) {
                songComposers.insert(s.composer);
            }
            songYears.insert(s.year);
            songDiscs.insert(s.disc);
            if (songArtists.count()>1 && songAlbumArtists.count()>1 && songAlbums.count()>1 &&
                songGenres.count()>1 && songYears.count()>1 && songDiscs.count()>1 && songComposers.count()>=1) {
                break;
            }
        }
        Song all;
        all.file.clear();
        all.title.clear();
        all.track=0;
        all.artist=1==songArtists.count() ? *(songArtists.begin()) : QString();
        all.composer=1==songComposers.count() ? *(songComposers.begin()) : QString();
        all.albumartist=1==songAlbumArtists.count() ? *(songAlbumArtists.begin()) : QString();
        all.album=1==songAlbums.count() ? *(songAlbums.begin()) : QString();
        all.genre=1==songGenres.count() ? *(songGenres.begin()) : QString();
        all.year=1==songYears.count() ? *(songYears.begin()) : 0;
        all.disc=1==songDiscs.count() ? *(songDiscs.begin()) : 0;
        original.prepend(all);
        artist->setFocus();
        haveArtists=!songArtists.isEmpty();
        haveAlbumArtists=!songAlbumArtists.isEmpty();
        haveAlbums=!songAlbums.isEmpty();
        haveGenres=!songGenres.isEmpty();
        haveComposers=!songComposers.isEmpty();
    } else {