Ejemplo n.º 1
0
ErrorList topolTest::checkyLineEndsCoveredByPoints( double tolerance, QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  Q_UNUSED( tolerance );

  int i = 0;
  ErrorList errorList;


  if ( layer1->geometryType() != QgsWkbTypes::LineGeometry )
  {
    return errorList;
  }

  if ( layer2->geometryType() != QgsWkbTypes::PointGeometry )
  {
    return errorList;
  }

  QgsSpatialIndex *index = mLayerIndexes[layer2->id()];

  QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( qgsInterface->mapCanvas()->extent().asWktPolygon() );

  QList<FeatureLayer>::Iterator it;
  for ( it = mFeatureList1.begin(); it != mFeatureList1.end(); ++it )
  {
    if ( !( ++i % 100 ) )
      emit progress( i );
    if ( testCanceled() )
      break;
    QgsGeometry g1 = it->feature.geometry();

    QgsPolylineXY g1Polyline = g1.asPolyline();
    QgsGeometry startPoint = QgsGeometry::fromPointXY( g1Polyline.at( 0 ) );
    QgsGeometry endPoint = QgsGeometry::fromPointXY( g1Polyline.last() );

    QgsRectangle bb = g1.boundingBox();
    QList<QgsFeatureId> crossingIds;
    crossingIds = index->intersects( bb );
    QList<QgsFeatureId>::ConstIterator cit = crossingIds.begin();
    QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.end();
    bool touched = false;

    bool touchStartPoint = false;
    bool touchEndPoint = false;

    for ( ; cit != crossingIdsEnd; ++cit )
    {
      QgsFeature &f = mFeatureMap2[*cit].feature;
      QgsGeometry g2 = f.geometry();
      if ( g2.isNull() || !_canExportToGeos( g2 ) )
      {
        QgsMessageLog::logMessage( tr( "Second geometry missing or GEOS import failed." ), tr( "Topology plugin" ) );
        continue;
      }


      if ( g2.intersects( startPoint ) )
      {
        touchStartPoint = true;
      }

      if ( g2.intersects( endPoint ) )
      {
        touchEndPoint = true;
      }

      if ( touchStartPoint && touchEndPoint )
      {
        touched = true;
        break;
      }

    }

    if ( !touched )
    {
      QgsGeometry conflictGeom = g1;

      if ( isExtent )
      {
        if ( canvasExtentPoly.disjoint( conflictGeom ) )
        {
          continue;
        }
        if ( canvasExtentPoly.crosses( conflictGeom ) )
        {
          conflictGeom = conflictGeom.intersection( canvasExtentPoly );
        }
      }
      QList<FeatureLayer> fls;
      fls << *it << *it;
      //bb.scale(10);

      TopolErrorLineEndsNotCoveredByPoints *err = new TopolErrorLineEndsNotCoveredByPoints( bb, conflictGeom, fls );
      errorList << err;
    }
  }
  return errorList;
}
Ejemplo n.º 2
0
//Note: no guarantee of selection order???
void MDIViewPage::setTreeToSceneSelect(void)
{
    bool saveBlock = blockConnection(true); // block selectionChanged signal from Tree/Observer
    blockSelection(true);
    Gui::Selection().clearSelection();
//    QList<QGraphicsItem*> sceneSel = m_view->scene()->selectedItems();   //"no particular order"!!!
    QList<QGraphicsItem*> sceneSel = m_sceneSelected;
    for (QList<QGraphicsItem*>::iterator it = sceneSel.begin(); it != sceneSel.end(); ++it) {
        QGIView *itemView = dynamic_cast<QGIView *>(*it);
        if(itemView == 0) {
            QGIEdge *edge = dynamic_cast<QGIEdge *>(*it);
            if(edge) {
                QGraphicsItem*parent = edge->parentItem();
                if(!parent)
                    continue;

                QGIView *viewItem = dynamic_cast<QGIView *>(parent);
                if(!viewItem)
                  continue;

                TechDraw::DrawView *viewObj = viewItem->getViewObject();

                std::stringstream ss;
                ss << "Edge" << edge->getProjIndex();
                //bool accepted =
                static_cast<void> (Gui::Selection().addSelection(viewObj->getDocument()->getName(),
                                              viewObj->getNameInDocument(),
                                              ss.str().c_str()));
                showStatusMsg(viewObj->getDocument()->getName(),
                                              viewObj->getNameInDocument(),
                                              ss.str().c_str());
                continue;
            }

            QGIVertex *vert = dynamic_cast<QGIVertex *>(*it);
            if(vert) {
                QGraphicsItem*parent = vert->parentItem();
                if(!parent)
                    continue;

                QGIView *viewItem = dynamic_cast<QGIView *>(parent);
                if(!viewItem)
                  continue;

                TechDraw::DrawView *viewObj = viewItem->getViewObject();

                std::stringstream ss;
                ss << "Vertex" << vert->getProjIndex();
                //bool accepted =
                static_cast<void> (Gui::Selection().addSelection(viewObj->getDocument()->getName(),
                                              viewObj->getNameInDocument(),
                                              ss.str().c_str()));
                showStatusMsg(viewObj->getDocument()->getName(),
                                              viewObj->getNameInDocument(),
                                              ss.str().c_str());
                continue;
            }

            QGIFace *face = dynamic_cast<QGIFace *>(*it);
            if(face) {
                QGraphicsItem*parent = face->parentItem();
                if(!parent)
                    continue;

                QGIView *viewItem = dynamic_cast<QGIView *>(parent);
                if(!viewItem)
                  continue;

                TechDraw::DrawView *viewObj = viewItem->getViewObject();

                std::stringstream ss;
                ss << "Face" << face->getProjIndex();
                //bool accepted =
                static_cast<void> (Gui::Selection().addSelection(viewObj->getDocument()->getName(),
                                              viewObj->getNameInDocument(),
                                              ss.str().c_str()));
                showStatusMsg(viewObj->getDocument()->getName(),
                                              viewObj->getNameInDocument(),
                                              ss.str().c_str());
                continue;
            }

            QGIDatumLabel *dimLabel = dynamic_cast<QGIDatumLabel*>(*it);
            if(dimLabel) {
                QGraphicsItem*dimParent = dimLabel->QGraphicsItem::parentItem();
                if(!dimParent)
                    continue;

                QGIView *dimItem = dynamic_cast<QGIView *>(dimParent);

                if(!dimItem)
                  continue;

                TechDraw::DrawView *dimObj = dimItem->getViewObject();
                if (!dimObj) {
                    continue;
                }
                const char* name = dimObj->getNameInDocument();
                if (!name) {                                   //can happen during undo/redo if Dim is selected???
                    //Base::Console().Log("INFO - MDIVP::sceneSelectionChanged - dimObj name is null!\n");
                    continue;
                }

                //bool accepted =
                static_cast<void> (Gui::Selection().addSelection(dimObj->getDocument()->getName(),dimObj->getNameInDocument()));
            }
        } else {
            TechDraw::DrawView *viewObj = itemView->getViewObject();
            if (viewObj && !viewObj->isRemoving()) {
                std::string doc_name = viewObj->getDocument()->getName();
                std::string obj_name = viewObj->getNameInDocument();

                Gui::Selection().addSelection(doc_name.c_str(), obj_name.c_str());
                showStatusMsg(doc_name.c_str(),
                              obj_name.c_str(),
                              "");
            }
        }
    }

    blockSelection(false);
    blockConnection(saveBlock);
}
Ejemplo n.º 3
0
void Highlighter::iterateThroughRules(const QString &text,
                                      const int length,
                                      ProgressData *progress,
                                      const bool childRule,
                                      const QList<QSharedPointer<Rule> > &rules)
{
    typedef QList<QSharedPointer<Rule> >::const_iterator RuleIterator;

    bool contextChanged = false;
    bool atLeastOneMatch = false;

    RuleIterator it = rules.begin();
    RuleIterator endIt = rules.end();
    while (it != endIt && progress->offset() < length) {
        int startOffset = progress->offset();
        const QSharedPointer<Rule> &rule = *it;
        if (rule->matchSucceed(text, length, progress)) {
            atLeastOneMatch = true;

            if (!m_indentationBasedFolding) {
                if (!rule->beginRegion().isEmpty()) {
                    blockData(currentBlockUserData())->m_foldingRegions.push(rule->beginRegion());
                    ++m_regionDepth;
                    if (progress->isOpeningBraceMatchAtFirstNonSpace())
                        ++blockData(currentBlockUserData())->m_foldingIndentDelta;
                }
                if (!rule->endRegion().isEmpty()) {
                    QStack<QString> *currentRegions =
                        &blockData(currentBlockUserData())->m_foldingRegions;
                    if (!currentRegions->isEmpty() && rule->endRegion() == currentRegions->top()) {
                        currentRegions->pop();
                        --m_regionDepth;
                        if (progress->isClosingBraceMatchAtNonEnd())
                            --blockData(currentBlockUserData())->m_foldingIndentDelta;
                    }
                }
                progress->clearBracesMatches();
            }

            if (progress->isWillContinueLine()) {
                createWillContinueBlock();
                progress->setWillContinueLine(false);
            } else {
                if (rule->hasChildren())
                    iterateThroughRules(text, length, progress, true, rule->children());

                if (!rule->context().isEmpty() && contextChangeRequired(rule->context())) {
                    m_currentCaptures = progress->captures();
                    changeContext(rule->context(), rule->definition());
                    contextChanged = true;
                }
            }

            // Format is not applied to child rules directly (but relative to the offset of their
            // parent) nor to look ahead rules.
            if (!childRule && !rule->isLookAhead()) {
                if (rule->itemData().isEmpty())
                    applyFormat(startOffset, progress->offset() - startOffset,
                                m_currentContext->itemData(), m_currentContext->definition());
                else
                    applyFormat(startOffset, progress->offset() - startOffset, rule->itemData(),
                                rule->definition());
            }

            // When there is a match of one child rule the others should be skipped. Otherwise
            // the highlighting would be incorret in a case like 9ULLLULLLUULLULLUL, for example.
            if (contextChanged || childRule) {
                break;
            } else {
                it = rules.begin();
                continue;
            }
        }
        ++it;
    }

    if (!childRule && !atLeastOneMatch) {
        if (m_currentContext->isFallthrough()) {
            handleContextChange(m_currentContext->fallthroughContext(),
                                m_currentContext->definition());
            iterateThroughRules(text, length, progress, false, m_currentContext->rules());
        } else {
            applyFormat(progress->offset(), 1, m_currentContext->itemData(),
                        m_currentContext->definition());
            if (progress->isOnlySpacesSoFar() && !text.at(progress->offset()).isSpace())
                progress->setOnlySpacesSoFar(false);
            progress->incrementOffset();
        }
    }
}
Ejemplo n.º 4
0
void ShaderProgram::setupParameterUI(QWidget* parentWidget)
{
    QFormLayout* layout = new QFormLayout(parentWidget);
    QList<QPair<ShaderParam,QVariant> > paramsOrdered;
    for (auto p = m_params.begin(); p != m_params.end(); ++p)
    {
        paramsOrdered.push_back(qMakePair(p.key(), p.value()));
    }
    qSort(paramsOrdered.begin(), paramsOrdered.end(), paramOrderingLess);
    for (int i = 0; i < paramsOrdered.size(); ++i)
    {
        QWidget* edit = 0;
        const ShaderParam& parDesc = paramsOrdered[i].first;
        const QVariant& parValue = paramsOrdered[i].second;
        switch (parDesc.type)
        {
            case ShaderParam::Float:
                {
                    bool expScaling = parDesc.kvPairs.value("scaling", "exponential").
                                      startsWith("exp");
                    double speed = parDesc.kvPairs.value("speed", "1").toDouble();
                    if (speed == 0)
                        speed = 1;
                    DragSpinBox* spin = new DragSpinBox(expScaling, speed, parentWidget);
                    double min = parDesc.getDouble("min", 0);
                    double max = parDesc.getDouble("max", 100);
                    if (expScaling)
                    {
                        // Prevent min or max == 0 for exp scaling which would be invalid
                        if (max == 0) max = 100;
                        if (min == 0) min = max > 0 ? 1e-8 : -1e-8;
                        spin->setDecimals((int)floor(std::max(0.0, -log(min)/log(10.0)) + 0.5) + 2);
                    }
                    else
                    {
                        double m = std::max(fabs(min), fabs(max));
                        spin->setDecimals((int)floor(std::max(0.0, -log(m)/log(10.0)) + 0.5) + 2);
                    }
                    spin->setMinimum(min);
                    spin->setMaximum(max);
                    spin->setValue(parValue.toDouble());
                    connect(spin, SIGNAL(valueChanged(double)),
                            this, SLOT(setUniformValue(double)));
                    edit = spin;
                }
                break;
            case ShaderParam::Int:
                if (parDesc.kvPairs.contains("enum"))
                {
                    // Parameter is an enumeration variable
                    QComboBox* box = new QComboBox(parentWidget);
                    QStringList names = parDesc.kvPairs.value("enum").split('|');
                    box->insertItems(0, names);
                    box->setCurrentIndex(parValue.toInt());
                    connect(box, SIGNAL(currentIndexChanged(int)),
                            this, SLOT(setUniformValue(int)));
                    edit = box;
                }
                else
                {
                    // Parameter is a freely ranging integer
                    QSpinBox* spin = new QSpinBox(parentWidget);
                    spin->setMinimum(parDesc.getInt("min", 0));
                    spin->setMaximum(parDesc.getInt("max", 100));
                    spin->setValue(parValue.toInt());
                    connect(spin, SIGNAL(valueChanged(int)),
                            this, SLOT(setUniformValue(int)));
                    edit = spin;
                }
                break;
            default:
                // FIXME
                continue;
        }
Ejemplo n.º 5
0
QString PopplerExtractor::parseFirstPage(Poppler::Document* pdfDoc, const QString& fileUrl)
{
    QScopedPointer<Poppler::Page> p(pdfDoc->page(0));

    if (!p) {
        qWarning() << "Could not read page content from" << fileUrl;
        return QString();
    }

    QList<Poppler::TextBox*> tbList = p->textList();
    QMap<int, QString> possibleTitleMap;

    int currentLargestChar = 0;
    int skipTextboxes = 0;

    // Iterate over all textboxes. Each textbox can be a single character/word or textblock
    // Here we combine the etxtboxes back together based on the textsize
    // Important are the words with the biggest font size
    foreach(Poppler::TextBox * tb, tbList) {

        // if we added followup words, skip the textboxes here now
        if (skipTextboxes > 0) {
            skipTextboxes--;
            continue;
        }

        int height = tb->charBoundingBox(0).height();

        // if the following text is smaller than the biggest we found up to now, ignore it
        if (height >= currentLargestChar) {
            QString possibleTitle;
            possibleTitle.append(tb->text());
            currentLargestChar = height;

            // if the text has follow up words add them to to create the full title
            Poppler::TextBox* next = tb->nextWord();
            while (next) {
                possibleTitle.append(QLatin1Char(' '));
                possibleTitle.append(next->text());
                next = next->nextWord();
                skipTextboxes++;
            }

            // now combine text for each font size together, very likeley it must be connected
            QString existingTitlePart = possibleTitleMap.value(currentLargestChar, QString());
            existingTitlePart.append(QLatin1Char(' '));
            existingTitlePart.append(possibleTitle);
            possibleTitleMap.insert(currentLargestChar, existingTitlePart);
        }
    }

    qDeleteAll(tbList);

    QList<int> titleSizes = possibleTitleMap.keys();
    qSort(titleSizes.begin(), titleSizes.end(), qGreater<int>());

    QString newPossibleTitle;

    // find the text with the largest font that is not just 1 character
    foreach(int i, titleSizes) {
        QString title = possibleTitleMap.value(i);

        // sometime the biggest part is a single letter
        // as a starting paragraph letter
        if (title.size() < 5) {
            continue;
        } else {
            newPossibleTitle = title.trimmed();
            break;
        }
    }
void AnnotationWorkstationExtensionPlugin::onLoadButtonPressed(const std::string& filePath) {
  QString fileName;
  if (filePath.empty()) {
    fileName = QFileDialog::getOpenFileName(NULL, tr("Load annotations"), _settings->value("lastOpenendPath", QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)).toString(), tr("Annotation files(*.xml;*.ndpa)"));
  }
  else {
    fileName = QString::fromStdString(filePath);
  }
  if (!fileName.isEmpty()) {
    onClearButtonPressed();
    if (!_annotationService->loadRepositoryFromFile(fileName.toStdString())) {
      int ret = QMessageBox::warning(NULL, tr("ASAP"),
        tr("The annotations could not be loaded."),
        QMessageBox::Ok);
    }
    // Check if it is an ImageScopeRepository, if so, offer the user the chance to reload with new closing distance
    std::shared_ptr<ImageScopeRepository> imscRepo = std::dynamic_pointer_cast<ImageScopeRepository>(_annotationService->getRepository());
    if (imscRepo) {
      bool ok = false;
      float newClosingDistance = QInputDialog::getDouble(_viewer, tr("Enter the annotation closing distance."), tr("Please provide the maximal distance for which annotations are automatically closed by ASAP if they remain open."), 30., 0, 1000, 1, &ok);
      float closingDistance = imscRepo->getClosingDistance();
      if (ok && newClosingDistance != closingDistance) {
        _annotationService->getList()->removeAllAnnotations();
        _annotationService->getList()->removeAllGroups();
        imscRepo->setClosingDistance(newClosingDistance);
        imscRepo->load();
      }
    }
    // Add loaded groups to treewidget
    QList<QtAnnotationGroup* > childGroups;
    std::map<std::shared_ptr<AnnotationGroup>, QTreeWidgetItem*> annotToWidget;
    std::vector<std::shared_ptr<AnnotationGroup> > grps = _annotationService->getList()->getGroups();
    for (std::vector<std::shared_ptr<AnnotationGroup> >::const_iterator it = grps.begin(); it != grps.end(); ++it) {
      QtAnnotationGroup *grp = new QtAnnotationGroup(*it, this);
      if ((*it)->getGroup() == NULL) {
        _qtAnnotationGroups.append(grp);
        QTreeWidgetItem* newAnnotationGroup = new QTreeWidgetItem(_treeWidget);
        newAnnotationGroup->setText(1, QString::fromStdString((*it)->getName()));
        newAnnotationGroup->setText(2, "Group");
        newAnnotationGroup->setData(1, Qt::UserRole, QVariant::fromValue<QtAnnotationGroup*>(grp));
        newAnnotationGroup->setFlags(newAnnotationGroup->flags() | Qt::ItemIsEditable);
        int cHeight = _treeWidget->visualItemRect(newAnnotationGroup).height();
        QPixmap iconPM(cHeight, cHeight);
        iconPM.fill(QColor((*it)->getColor().c_str()));
        QIcon color(iconPM);
        newAnnotationGroup->setIcon(0, color);
        newAnnotationGroup->setData(0, Qt::UserRole, QColor((*it)->getColor().c_str()));
        annotToWidget[grp->getAnnotationGroup()] = newAnnotationGroup;
      }
      else {
        childGroups.append(grp);
      }
    }
    while (!childGroups.empty()) {
      for (QList<QtAnnotationGroup*>::iterator it = childGroups.begin(); it != childGroups.end();) {
        if (annotToWidget.find((*it)->getAnnotationGroup()->getGroup()) != annotToWidget.end()) {
          _qtAnnotationGroups.append((*it));
          QTreeWidgetItem* newAnnotationGroup = new QTreeWidgetItem(annotToWidget[(*it)->getAnnotationGroup()->getGroup()]);
          newAnnotationGroup->setText(1, QString::fromStdString((*it)->getAnnotationGroup()->getName()));
          newAnnotationGroup->setText(2, "Group");
          newAnnotationGroup->setData(1, Qt::UserRole, QVariant::fromValue<QtAnnotationGroup*>((*it)));
          newAnnotationGroup->setFlags(newAnnotationGroup->flags() | Qt::ItemIsEditable);
          int cHeight = _treeWidget->visualItemRect(newAnnotationGroup).height();
          QPixmap iconPM(cHeight, cHeight);
          iconPM.fill(QColor((*it)->getAnnotationGroup()->getColor().c_str()));
          QIcon color(iconPM);
          newAnnotationGroup->setIcon(0, color);
          newAnnotationGroup->setData(0, Qt::UserRole, QColor((*it)->getAnnotationGroup()->getColor().c_str()));
          annotToWidget[(*it)->getAnnotationGroup()] = newAnnotationGroup;
          it = childGroups.erase(it);
        }
        else{
          ++it;
        }
      }
    }
    std::vector<std::shared_ptr<Annotation> > annots = _annotationService->getList()->getAnnotations();
    for (std::vector<std::shared_ptr<Annotation> >::const_iterator it = annots.begin(); it != annots.end(); ++it) {
      QTreeWidgetItem* prnt = _treeWidget->invisibleRootItem();
      if ((*it)->getGroup()) {
        prnt = annotToWidget[(*it)->getGroup()];
      }
      std::string key = "Annotation " + QString::number(_annotationIndex).toStdString() + "_annotation";
      
      // Add QtAnnotation
      QtAnnotation* annot = NULL;
      if ((*it)->getType() == Annotation::Type::DOT) {
        annot = new DotQtAnnotation((*it), this, _viewer->getSceneScale());
      }
      else if ((*it)->getType() == Annotation::Type::POLYGON) {
        annot = new PolyQtAnnotation((*it), this, _viewer->getSceneScale());
        dynamic_cast<PolyQtAnnotation*>(annot)->setInterpolationType("linear");
      }
      else if ((*it)->getType() == Annotation::Type::SPLINE) {
        annot = new PolyQtAnnotation((*it), this, _viewer->getSceneScale());
        dynamic_cast<PolyQtAnnotation*>(annot)->setInterpolationType("spline");
      }
      else if ((*it)->getType() == Annotation::Type::POINTSET) {
        annot = new PointSetQtAnnotation((*it), this, _viewer->getSceneScale());
      }
      if (annot) {
        annot->finish();
        _qtAnnotations.append(annot);
        _viewer->scene()->addItem(annot);
        annot->setZValue(20.);


        _annotationIndex += 1;
        QTreeWidgetItem* newAnnotation = new QTreeWidgetItem(prnt);
        newAnnotation->setText(1, QString::fromStdString((*it)->getName()));
        newAnnotation->setText(2, QString::fromStdString((*it)->getTypeAsString()));
        newAnnotation->setFlags(newAnnotation->flags() & ~Qt::ItemIsDropEnabled);
        newAnnotation->setFlags(newAnnotation->flags() | Qt::ItemIsEditable);
        newAnnotation->setData(1, Qt::UserRole, QVariant::fromValue<QtAnnotation*>(annot));
        int cHeight = _treeWidget->visualItemRect(newAnnotation).height();
        if (_treeWidget->topLevelItemCount() > 0) {
          cHeight = _treeWidget->visualItemRect(_treeWidget->topLevelItem(0)).height();
        }
        QPixmap iconPM(cHeight, cHeight);
        iconPM.fill(QColor((*it)->getColor().c_str()));
        QIcon color(iconPM);
        newAnnotation->setIcon(0, color);
        newAnnotation->setData(0, Qt::UserRole, QColor((*it)->getColor().c_str()));
        _annotToItem[annot] = newAnnotation;
        updateAnnotationToolTip(annot);
        connect(annot, SIGNAL(coordinatesChanged(QtAnnotation*)), this, SLOT(updateAnnotationToolTip(QtAnnotation*)));
      }
    }
    _treeWidget->resizeColumnToContents(0);
    _treeWidget->resizeColumnToContents(1);
  }
Ejemplo n.º 7
0
int main ( int argc, char **argv )
{
  QCoreApplication app ( argc, argv );

  QHash<int, QImage> imagesToUse;
  QList<QImage> images;
  const QSize size16 ( 16,16 );
  const QSize size32 ( 32,32 );
  const QSize size48 ( 48,48 );
  if ( argc < 3 )
    usage ( "To few arguments" );

  QString rcFileName;
  QString icoFileName;
  int hotspotx = 0;
  int hotspoty = 0;
  int framerate = 3;
  for ( int i = 1; i < argc; i++ ) {
    const QString arg = app.arguments() [i];
    if ( arg == QLatin1String ( "--rcfile" ) ) {
      if ( i + 1 < argc ) {
        rcFileName = app.arguments() [i+1];
        i++;
        continue;
      } else {
        usage ( "option '--rcfile' without filename" );
      }
    } else if (arg == "--hotspotx") {
       if ( i + 1 < argc ) {
        hotspotx = app.arguments()[i+1].toInt();
        i++;
        continue;
       } else {
        usage ( "option '--hotspotx' without value" );
       }
    } else if (arg == "--hotspoty") {
       if ( i + 1 < argc ) {
        hotspoty = app.arguments()[i+1].toInt();
        i++;
        continue;
    } else {
        usage ( "option '--hotspoty' without value" );
       }
    } else if (arg == "--framerate") {
       if ( i + 1 < argc ) {
        framerate = app.arguments()[i+1].toInt();
        i++;
        continue;
    } else {
        usage ( "option '--framerate' without value" );
       }
    }

    if ( icoFileName.isEmpty() ) {
      icoFileName = arg;
      continue;
    }
    QImage img;
    img.load ( arg );
    if ( img.isNull() ) {
      warning ( QString ( "Can not load image %1" ).arg ( arg ) );
      continue;
    }

    if (icoFileName.endsWith(".ico", Qt::CaseInsensitive)) {
        images += img;
        if ( img.size() == size16 ) {
        if ( imagesToUse.contains ( 16 ) ) {
            warning ( QString ( "Already have an Image with 16x16 - overwriting with %1" ).arg ( arg ) );
        }
        imagesToUse.insert ( 16, img );
        continue;
        }
        if ( img.size() == size32 ) {
        if ( imagesToUse.contains ( 32 ) ) {
            warning ( QString ( "Already have an Image with 32x32 - overwriting with %1" ).arg ( arg ) );
        }
        imagesToUse.insert ( 32, img );
        continue;
        }
        if ( img.size() == size48 ) {
        if ( imagesToUse.contains ( 48 ) ) {
            warning ( QString ( "Already have an Image with 48x48- overwriting with %1" ).arg ( arg ) );
        }
        imagesToUse.insert ( 48, img );
        continue;
        }
    } else {
        if (img.size() != QSize(32, 32)) {
            img = scaleImage(img);
        }

        images += img;
    }
  }
  if ( images.count() == 0 )
    usage ( "No valid images found!" );
  if (icoFileName.endsWith(".ico", Qt::CaseInsensitive)) {
    qSort ( images.begin(), images.end(), sortQImageForSize );
    // 48x48 available -> if not create one
    if ( !imagesToUse.contains ( 48 ) ) {
        QImage img;
        Q_FOREACH ( const QImage &i, images ) {
        if ( img.width() >= 32 && img.height() >= 32 ) {
            img = i;
        }
        }
        if ( img.isNull() ) {
        // none found -> use the last (==biggest) available
        img = images.last();
        }
        imagesToUse.insert ( 48, img.scaled ( 48, 48, Qt::IgnoreAspectRatio, Qt::SmoothTransformation ) );
    }
Ejemplo n.º 8
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void RotateSampleRefFrame::execute()
{
  setErrorCondition(0);
  dataCheck();
  if(getErrorCondition() < 0) { return; }

  DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getCellAttributeMatrixPath().getDataContainerName());

  float rotAngle = m_RotationAngle * SIMPLib::Constants::k_Pi / 180.0;

  int64_t xp = 0, yp = 0, zp = 0;
  float xRes = 0.0f, yRes = 0.0f, zRes = 0.0f;
  int64_t xpNew = 0, ypNew = 0, zpNew = 0;
  float xResNew = 0.0f, yResNew = 0.0f, zResNew = 0.0f;
  RotateSampleRefFrameImplArg_t params;

  xp = static_cast<int64_t>(m->getGeometryAs<ImageGeom>()->getXPoints());
  xRes = m->getGeometryAs<ImageGeom>()->getXRes();
  yp = static_cast<int64_t>(m->getGeometryAs<ImageGeom>()->getYPoints());
  yRes = m->getGeometryAs<ImageGeom>()->getYRes();
  zp = static_cast<int64_t>(m->getGeometryAs<ImageGeom>()->getZPoints());
  zRes = m->getGeometryAs<ImageGeom>()->getZRes();

  params.xp = xp;
  params.xRes = xRes;
  params.yp = yp;
  params.yRes = yRes;
  params.zp = zp;
  params.zRes = zRes;

  size_t col = 0, row = 0, plane = 0;
  float rotMat[3][3] = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } };
  float coords[3] = { 0.0f, 0.0f, 0.0f };
  float newcoords[3] = { 0.0f, 0.0f, 0.0f };
  float xMin = std::numeric_limits<float>::max();
  float xMax = std::numeric_limits<float>::min();
  float yMin = std::numeric_limits<float>::max();
  float yMax = std::numeric_limits<float>::min();
  float zMin = std::numeric_limits<float>::max();
  float zMax = std::numeric_limits<float>::min();

  FOrientArrayType om(9);
  FOrientTransformsType::ax2om(FOrientArrayType(m_RotationAxis.x, m_RotationAxis.y, m_RotationAxis.z, rotAngle), om);
  om.toGMatrix(rotMat);
  for (int32_t i = 0; i < 8; i++)
  {
    if (i == 0) { col = 0, row = 0, plane = 0; }
    if (i == 1) { col = xp - 1, row = 0, plane = 0; }
    if (i == 2) { col = 0, row = yp - 1, plane = 0; }
    if (i == 3) { col = xp - 1, row = yp - 1, plane = 0; }
    if (i == 4) { col = 0, row = 0, plane = zp - 1; }
    if (i == 5) { col = xp - 1, row = 0, plane = zp - 1; }
    if (i == 6) { col = 0, row = yp - 1, plane = zp - 1; }
    if (i == 7) { col = xp - 1, row = yp - 1, plane = zp - 1; }
    coords[0] = static_cast<float>(col * xRes);
    coords[1] = static_cast<float>(row * yRes);
    coords[2] = static_cast<float>(plane * zRes);
    MatrixMath::Multiply3x3with3x1(rotMat, coords, newcoords);
    if (newcoords[0] < xMin) { xMin = newcoords[0]; }
    if (newcoords[0] > xMax) { xMax = newcoords[0]; }
    if (newcoords[1] < yMin) { yMin = newcoords[1]; }
    if (newcoords[1] > yMax) { yMax = newcoords[1]; }
    if (newcoords[2] < zMin) { zMin = newcoords[2]; }
    if (newcoords[2] > zMax) { zMax = newcoords[2]; }
  }
  float xAxis[3] = {1, 0, 0};
  float yAxis[3] = {0, 1, 0};
  float zAxis[3] = {0, 0, 1};
  float xAxisNew[3] = { 0.0f, 0.0f, 0.0f };
  float yAxisNew[3] = { 0.0f, 0.0f, 0.0f };
  float zAxisNew[3] = { 0.0f, 0.0f, 0.0f };
  MatrixMath::Multiply3x3with3x1(rotMat, xAxis, xAxisNew);
  MatrixMath::Multiply3x3with3x1(rotMat, yAxis, yAxisNew);
  MatrixMath::Multiply3x3with3x1(rotMat, zAxis, zAxisNew);
  float closestAxis = 0.0f;
  xResNew = xRes;
  closestAxis = fabs(GeometryMath::CosThetaBetweenVectors(xAxis, xAxisNew));
  if (fabs(GeometryMath::CosThetaBetweenVectors(yAxis, xAxisNew)) > closestAxis) { xResNew = yRes, closestAxis = fabs(GeometryMath::CosThetaBetweenVectors(yAxis, xAxisNew)); }
  if (fabs(GeometryMath::CosThetaBetweenVectors(zAxis, xAxisNew)) > closestAxis) { xResNew = zRes, closestAxis = fabs(GeometryMath::CosThetaBetweenVectors(zAxis, xAxisNew)); }
  yResNew = yRes;
  closestAxis = fabs(GeometryMath::CosThetaBetweenVectors(yAxis, yAxisNew));
  if (fabs(GeometryMath::CosThetaBetweenVectors(xAxis, yAxisNew)) > closestAxis) { yResNew = xRes, closestAxis = fabs(GeometryMath::CosThetaBetweenVectors(xAxis, yAxisNew)); }
  if (fabs(GeometryMath::CosThetaBetweenVectors(zAxis, yAxisNew)) > closestAxis) { yResNew = zRes, closestAxis = fabs(GeometryMath::CosThetaBetweenVectors(zAxis, yAxisNew)); }
  zResNew = zRes;
  closestAxis = fabs(GeometryMath::CosThetaBetweenVectors(zAxis, zAxisNew));
  if (fabs(GeometryMath::CosThetaBetweenVectors(xAxis, zAxisNew)) > closestAxis) { zResNew = xRes, closestAxis = fabs(GeometryMath::CosThetaBetweenVectors(xAxis, zAxisNew)); }
  if (fabs(GeometryMath::CosThetaBetweenVectors(yAxis, zAxisNew)) > closestAxis) { zResNew = yRes, closestAxis = fabs(GeometryMath::CosThetaBetweenVectors(yAxis, zAxisNew)); }

  xpNew = static_cast<int64_t>(nearbyint((xMax - xMin) / xResNew) + 1);
  ypNew = static_cast<int64_t>(nearbyint((yMax - yMin) / yResNew) + 1);
  zpNew = static_cast<int64_t>(nearbyint((zMax - zMin) / zResNew) + 1);

  params.xpNew = xpNew;
  params.xResNew = xResNew;
  params.xMinNew = xMin;
  params.ypNew = ypNew;
  params.yResNew = yResNew;
  params.yMinNew = yMin;
  params.zpNew = zpNew;
  params.zResNew = zResNew;
  params.zMinNew = zMin;

  int64_t newNumCellTuples = params.xpNew * params.ypNew * params.zpNew;

  DataArray<int64_t>::Pointer newIndiciesPtr = DataArray<int64_t>::CreateArray(newNumCellTuples, "_INTERNAL_USE_ONLY_RotateSampleRef_NewIndicies");
  newIndiciesPtr->initializeWithValue(-1);
  int64_t* newindicies = newIndiciesPtr->getPointer(0);

#ifdef SIMPLib_USE_PARALLEL_ALGORITHMS
  tbb::task_scheduler_init init;
  bool doParallel = true;
#endif

#ifdef SIMPLib_USE_PARALLEL_ALGORITHMS
  if (doParallel == true)
  {
    tbb::parallel_for(tbb::blocked_range3d<int64_t, int64_t, int64_t>(0, params.zpNew, 0, params.ypNew, 0, params.xpNew),
                      RotateSampleRefFrameImpl(newIndiciesPtr, &params, rotMat, m_SliceBySlice), tbb::auto_partitioner());
  }
  else
#endif
  {
    RotateSampleRefFrameImpl serial(newIndiciesPtr, &params, rotMat, m_SliceBySlice);
    serial.convert(0, params.zpNew, 0, params.ypNew, 0, params.xpNew);
  }

  // This could technically be parallelized also where each thread takes an array to adjust. Except
  // that the DataContainer is NOT thread safe or re-entrant so that would actually be a BAD idea.
  QString attrMatName = getCellAttributeMatrixPath().getAttributeMatrixName();
  QList<QString> voxelArrayNames = m->getAttributeMatrix(attrMatName)->getAttributeArrayNames();

  // resize attribute matrix
  QVector<size_t> tDims(3);
  tDims[0] = params.xpNew;
  tDims[1] = params.ypNew;
  tDims[2] = params.zpNew;
  m->getAttributeMatrix(attrMatName)->resizeAttributeArrays(tDims);

  for (QList<QString>::iterator iter = voxelArrayNames.begin(); iter != voxelArrayNames.end(); ++iter)
  {
    IDataArray::Pointer p = m->getAttributeMatrix(attrMatName)->getAttributeArray(*iter);
    // Make a copy of the 'p' array that has the same name. When placed into
    // the data container this will over write the current array with
    // the same name.
    IDataArray::Pointer data = p->createNewArray(newNumCellTuples, p->getComponentDimensions(), p->getName());
    void* source = NULL;
    void* destination = NULL;
    int64_t newIndicies_I = 0;
    int32_t nComp = data->getNumberOfComponents();
    for (size_t i = 0; i < static_cast<size_t>(newNumCellTuples); i++)
    {
      newIndicies_I = newindicies[i];
      if(newIndicies_I >= 0)
      {
        source = p->getVoidPointer((nComp * newIndicies_I));
        if (NULL == source)
        {
          QString ss = QObject::tr("The index is outside the bounds of the source array");
          setErrorCondition(-11004);
          notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
          return;
        }
        destination = data->getVoidPointer((data->getNumberOfComponents() * i));
        ::memcpy(destination, source, p->getTypeSize() * data->getNumberOfComponents());
      }
      else
      {
        data->initializeTuple(i, 0);
      }
    }
    m->getAttributeMatrix(attrMatName)->addAttributeArray(*iter, data);
  }
  m->getGeometryAs<ImageGeom>()->setResolution(params.xResNew, params.yResNew, params.zResNew);
  m->getGeometryAs<ImageGeom>()->setDimensions(params.xpNew, params.ypNew, params.zpNew);
  m->getGeometryAs<ImageGeom>()->setOrigin(xMin, yMin, zMin);

  notifyStatusMessage(getHumanLabel(), "Complete");
}
Ejemplo n.º 9
0
RipCDDialog::RipCDDialog(QWidget* parent)
    : QDialog(parent),
      ui_(new Ui_RipCDDialog),
      ripper_(new Ripper(this)),
      working_(false) {
  // Init
  ui_->setupUi(this);

  // Set column widths in the QTableWidget.
  ui_->tableWidget->horizontalHeader()->setResizeMode(
      kCheckboxColumn, QHeaderView::ResizeToContents);
  ui_->tableWidget->horizontalHeader()->setResizeMode(
      kTrackNumberColumn, QHeaderView::ResizeToContents);
  ui_->tableWidget->horizontalHeader()->setResizeMode(kTrackTitleColumn,
                                                      QHeaderView::Stretch);

  // Add a rip button
  rip_button_ = ui_->button_box->addButton(tr("Start ripping"),
                                           QDialogButtonBox::ActionRole);
  cancel_button_ = ui_->button_box->button(QDialogButtonBox::Cancel);
  close_button_ = ui_->button_box->button(QDialogButtonBox::Close);

  // Hide elements
  cancel_button_->hide();
  ui_->progress_group->hide();

  connect(ui_->select_all_button, SIGNAL(clicked()), SLOT(SelectAll()));
  connect(ui_->select_none_button, SIGNAL(clicked()), SLOT(SelectNone()));
  connect(ui_->invert_selection_button, SIGNAL(clicked()),
          SLOT(InvertSelection()));
  connect(rip_button_, SIGNAL(clicked()), SLOT(ClickedRipButton()));
  connect(cancel_button_, SIGNAL(clicked()), ripper_, SLOT(Cancel()));
  connect(close_button_, SIGNAL(clicked()), SLOT(hide()));

  connect(ui_->options, SIGNAL(clicked()), SLOT(Options()));
  connect(ui_->select, SIGNAL(clicked()), SLOT(AddDestination()));

  connect(ripper_, SIGNAL(Finished()), SLOT(Finished()));
  connect(ripper_, SIGNAL(Cancelled()), SLOT(Cancelled()));
  connect(ripper_, SIGNAL(ProgressInterval(int, int)),
          SLOT(SetupProgressBarLimits(int, int)));
  connect(ripper_, SIGNAL(Progress(int)), SLOT(UpdateProgressBar(int)));

  setWindowTitle(tr("Rip CD"));
  AddDestinationDirectory(QDir::homePath());

  // Get presets
  QList<TranscoderPreset> presets = Transcoder::GetAllPresets();
  qSort(presets.begin(), presets.end(), ComparePresetsByName);
  for (const TranscoderPreset& preset : presets) {
    ui_->format->addItem(
        QString("%1 (.%2)").arg(preset.name_).arg(preset.extension_),
        QVariant::fromValue(preset));
  }

  // Load settings
  QSettings s;
  s.beginGroup(kSettingsGroup);
  last_add_dir_ = s.value("last_add_dir", QDir::homePath()).toString();

  QString last_output_format = s.value("last_output_format", "ogg").toString();
  for (int i = 0; i < ui_->format->count(); ++i) {
    if (last_output_format ==
        ui_->format->itemData(i).value<TranscoderPreset>().extension_) {
      ui_->format->setCurrentIndex(i);
      break;
    }
  }
}
Ejemplo n.º 10
0
void TriggerSkillSorter::sort(QList<const TriggerSkill *> &skills){
    qStableSort(skills.begin(), skills.end(), *this);
}
Ejemplo n.º 11
0
bool Tessellation::accept()
{
    if (ui->treeWidget->selectedItems().isEmpty()) {
        QMessageBox::critical(this, windowTitle(),
            tr("Select a shape for meshing, first."));
        return false;
    }

    App::Document* activeDoc = App::GetApplication().getDocument((const char*)this->document.toLatin1());
    if (!activeDoc) {
        QMessageBox::critical(this, windowTitle(),
            tr("No such document '%1'.").arg(this->document));
        return false;
    }

    try {
        QString shape, label;
        Gui::WaitCursor wc;

        int method = buttonGroup->checkedId();

        activeDoc->openTransaction("Meshing");
        QList<QTreeWidgetItem *> items = ui->treeWidget->selectedItems();
        std::vector<Part::Feature*> shapes = Gui::Selection().getObjectsOfType<Part::Feature>();
        for (QList<QTreeWidgetItem *>::iterator it = items.begin(); it != items.end(); ++it) {
            shape = (*it)->data(0, Qt::UserRole).toString();
            label = (*it)->text(0);

            QString cmd;
            if (method == 0) { // Standard
                double devFace = ui->spinSurfaceDeviation->value().getValue();
                cmd = QString::fromLatin1(
                    "__doc__=FreeCAD.getDocument(\"%1\")\n"
                    "__mesh__=__doc__.addObject(\"Mesh::Feature\",\"Mesh\")\n"
                    "__mesh__.Mesh=Mesh.Mesh(__doc__.getObject(\"%2\").Shape.tessellate(%3))\n"
                    "__mesh__.Label=\"%4 (Meshed)\"\n"
                    "__mesh__.ViewObject.CreaseAngle=25.0\n"
                    "del __doc__, __mesh__\n")
                    .arg(this->document)
                    .arg(shape)
                    .arg(devFace)
                    .arg(label);
            }
            else if (method == 1) { // Mefisto
                double maxEdge = ui->spinMaximumEdgeLength->value().getValue();
                if (!ui->spinMaximumEdgeLength->isEnabled())
                    maxEdge = 0;
                cmd = QString::fromLatin1(
                    "__doc__=FreeCAD.getDocument(\"%1\")\n"
                    "__mesh__=__doc__.addObject(\"Mesh::Feature\",\"Mesh\")\n"
                    "__mesh__.Mesh=MeshPart.meshFromShape(Shape=__doc__.getObject(\"%2\").Shape,MaxLength=%3)\n"
                    "__mesh__.Label=\"%4 (Meshed)\"\n"
                    "__mesh__.ViewObject.CreaseAngle=25.0\n"
                    "del __doc__, __mesh__\n")
                    .arg(this->document)
                    .arg(shape)
                    .arg(maxEdge)
                    .arg(label);
            }
            else if (method == 2) { // Netgen
                int fineness = ui->comboFineness->currentIndex();
                double growthRate = ui->doubleGrading->value();
                double nbSegPerEdge = ui->spinEdgeElements->value();
                double nbSegPerRadius = ui->spinCurvatureElements->value();
                bool secondOrder = ui->checkSecondOrder->isChecked();
                bool optimize = ui->checkOptimizeSurface->isChecked();
                bool allowquad = ui->checkQuadDominated->isChecked();
                if (fineness < 5) {
                    cmd = QString::fromLatin1(
                        "__doc__=FreeCAD.getDocument(\"%1\")\n"
                        "__mesh__=__doc__.addObject(\"Mesh::Feature\",\"Mesh\")\n"
                        "__mesh__.Mesh=MeshPart.meshFromShape(Shape=__doc__.getObject(\"%2\").Shape,"
                        "Fineness=%3,SecondOrder=%4,Optimize=%5,AllowQuad=%6)\n"
                        "__mesh__.Label=\"%7 (Meshed)\"\n"
                        "__mesh__.ViewObject.CreaseAngle=25.0\n"
                        "del __doc__, __mesh__\n")
                        .arg(this->document)
                        .arg(shape)
                        .arg(fineness)
                        .arg(secondOrder ? 1 : 0)
                        .arg(optimize ? 1 : 0)
                        .arg(allowquad ? 1 : 0)
                        .arg(label);
                }
                else {
                    cmd = QString::fromLatin1(
                        "__doc__=FreeCAD.getDocument(\"%1\")\n"
                        "__mesh__=__doc__.addObject(\"Mesh::Feature\",\"Mesh\")\n"
                        "__mesh__.Mesh=MeshPart.meshFromShape(Shape=__doc__.getObject(\"%2\").Shape,"
                        "GrowthRate=%3,SegPerEdge=%4,SegPerRadius=%5,SecondOrder=%6,Optimize=%7,AllowQuad=%8)\n"
                        "__mesh__.Label=\"%9 (Meshed)\"\n"
                        "__mesh__.ViewObject.CreaseAngle=25.0\n"
                        "del __doc__, __mesh__\n")
                        .arg(this->document)
                        .arg(shape)
                        .arg(growthRate)
                        .arg(nbSegPerEdge)
                        .arg(nbSegPerRadius)
                        .arg(secondOrder ? 1 : 0)
                        .arg(optimize ? 1 : 0)
                        .arg(allowquad ? 1 : 0)
                        .arg(label);
                }
            }
            Gui::Command::doCommand(Gui::Command::Doc, (const char*)cmd.toUtf8());
        }
        activeDoc->commitTransaction();
    }
    catch (const Base::Exception& e) {
        Base::Console().Error(e.what());
    }

    return true;
}
Ejemplo n.º 12
0
ErrorList topolTest::checkPointCoveredBySegment( double tolerance, QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  Q_UNUSED( tolerance );

  int i = 0;

  ErrorList errorList;

  if ( layer1->geometryType() != QgsWkbTypes::PointGeometry )
  {
    return errorList;
  }
  if ( layer2->geometryType() == QgsWkbTypes::PointGeometry )
  {
    return errorList;
  }

  QgsSpatialIndex *index = mLayerIndexes[layer2->id()];
  QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( qgsInterface->mapCanvas()->extent().asWktPolygon() );

  QList<FeatureLayer>::Iterator it;
  for ( it = mFeatureList1.begin(); it != mFeatureList1.end(); ++it )
  {
    if ( !( ++i % 100 ) )
      emit progress( i );

    if ( testCanceled() )
      break;

    QgsGeometry g1 = it->feature.geometry();
    QgsRectangle bb = g1.boundingBox();

    QList<QgsFeatureId> crossingIds;
    crossingIds = index->intersects( bb );

    QList<QgsFeatureId>::ConstIterator cit = crossingIds.begin();
    QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.end();

    bool touched = false;

    for ( ; cit != crossingIdsEnd; ++cit )
    {
      QgsFeature &f = mFeatureMap2[*cit].feature;
      QgsGeometry g2 = f.geometry();

      if ( g2.isNull() )
      {
        QgsMessageLog::logMessage( tr( "Invalid geometry in covering test." ), tr( "Topology plugin" ) );
        continue;
      }

      // test if point touches other geometry
      if ( g1.touches( g2 ) )
      {
        touched = true;
        break;
      }
    }

    if ( !touched )
    {
      QgsGeometry conflictGeom = QgsGeometry( g1 );

      if ( isExtent )
      {
        if ( canvasExtentPoly.disjoint( conflictGeom ) )
        {
          continue;
        }
      }

      QList<FeatureLayer> fls;
      fls << *it << *it;
      //bb.scale(10);

      TopolErrorCovered *err = new TopolErrorCovered( bb, conflictGeom, fls );

      errorList << err;
    }
  }
  return errorList;
}
Ejemplo n.º 13
0
ErrorList topolTest::checkOverlaps( double tolerance, QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  Q_UNUSED( tolerance );
  Q_UNUSED( layer2 );
  int i = 0;
  ErrorList errorList;

  // could be enabled for lines and points too
  // so duplicate rule may be removed?

  if ( layer1->geometryType() != QgsWkbTypes::PolygonGeometry )
  {
    return errorList;
  }

  QList<QgsFeatureId> *duplicateIds = new QList<QgsFeatureId>();

  QgsSpatialIndex *index = mLayerIndexes[layer1->id()];
  if ( !index )
  {
    qDebug() << "no index present";
    delete duplicateIds;
    return errorList;
  }

  QMap<QgsFeatureId, FeatureLayer>::const_iterator it;
  for ( it = mFeatureMap2.constBegin(); it != mFeatureMap2.constEnd(); ++it )
  {
    if ( !( ++i % 100 ) )
      emit progress( i );

    QgsFeatureId currentId = it->feature.id();

    if ( duplicateIds->contains( currentId ) )
    {
      //is already a duplicate geometry..skip..
      continue;
    }

    if ( testCanceled() )
      break;

    QgsGeometry g1 = it->feature.geometry();

    if ( !g1.isGeosValid() )
    {
      qDebug() << "invalid geometry(g1) found..skipping.." << it->feature.id();
      continue;
    }

    QgsRectangle bb = g1.boundingBox();

    QList<QgsFeatureId> crossingIds;
    crossingIds = index->intersects( bb );

    QList<QgsFeatureId>::ConstIterator cit = crossingIds.begin();
    QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.end();

    bool duplicate = false;

    QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( qgsInterface->mapCanvas()->extent().asWktPolygon() );

    for ( ; cit != crossingIdsEnd; ++cit )
    {
      duplicate = false;
      // skip itself
      if ( mFeatureMap2[*cit].feature.id() == it->feature.id() )
        continue;

      QgsGeometry g2 = mFeatureMap2[*cit].feature.geometry();
      if ( g2.isNull() )
      {
        QgsMessageLog::logMessage( tr( "Invalid second geometry in overlaps test." ), tr( "Topology plugin" ) );
        continue;
      }

      if ( !_canExportToGeos( g2 ) )
      {
        QgsMessageLog::logMessage( tr( "Failed to import second geometry into GEOS in overlaps test." ), tr( "Topology plugin" ) );
        continue;
      }

      if ( !g2.isGeosValid() )
      {
        QgsMessageLog::logMessage( tr( "Skipping invalid second geometry of feature %1 in overlaps test." ).arg( it->feature.id() ), tr( "Topology plugin" ) );
        continue;
      }


      qDebug() << "checking overlap for" << it->feature.id();
      if ( g1.overlaps( g2 ) )
      {
        duplicate = true;
        duplicateIds->append( mFeatureMap2[*cit].feature.id() );
      }

      if ( duplicate )
      {
        QList<FeatureLayer> fls;
        fls << *it << *it;
        QgsGeometry conflictGeom = g1.intersection( g2 );

        if ( isExtent )
        {
          if ( canvasExtentPoly.disjoint( conflictGeom ) )
          {
            continue;
          }
          if ( canvasExtentPoly.crosses( conflictGeom ) )
          {
            conflictGeom = conflictGeom.intersection( canvasExtentPoly );
          }
        }

        TopolErrorOverlaps *err = new TopolErrorOverlaps( bb, conflictGeom, fls );

        errorList << err;
      }

    }
  }

  delete duplicateIds;

  return errorList;
}
Ejemplo n.º 14
0
ErrorList topolTest::checkCloseFeature( double tolerance, QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  Q_UNUSED( isExtent );
  ErrorList errorList;
  QgsSpatialIndex *index = 0;

  bool badG1 = false, badG2 = false;
  bool skipItself = layer1 == layer2;

  int i = 0;
  QList<FeatureLayer>::Iterator it;
  QList<FeatureLayer>::ConstIterator FeatureListEnd = mFeatureList1.end();
  for ( it = mFeatureList1.begin(); it != FeatureListEnd; ++it )
  {
    if ( !( ++i % 100 ) )
      emit progress( i );

    if ( testCanceled() )
      break;

    QgsGeometry *g1 = it->feature.geometry();
    if ( !g1 || !g1->asGeos() )
    {
      badG1 = true;
      continue;
    }

    QgsRectangle bb = g1->boundingBox();

    // increase bounding box by tolerance
    QgsRectangle frame( bb.xMinimum() - tolerance, bb.yMinimum() - tolerance, bb.xMaximum() + tolerance, bb.yMaximum() + tolerance );

    QList<QgsFeatureId> crossingIds;
    crossingIds = index->intersects( frame );

    QList<QgsFeatureId>::Iterator cit = crossingIds.begin();
    QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.end();

    for ( ; cit != crossingIdsEnd; ++cit )
    {
      QgsFeature &f = mFeatureMap2[*cit].feature;
      QgsGeometry *g2 = f.geometry();

      // skip itself, when invoked with the same layer
      if ( skipItself && f.id() == it->feature.id() )
        continue;

      if ( !g2 || !g2->asGeos() )
      {
        badG2 = true;
        continue;
      }

      if ( g1->distance( *g2 ) < tolerance )
      {
        QgsRectangle r = g2->boundingBox();
        r.combineExtentWith( &bb );

        QList<FeatureLayer> fls;
        FeatureLayer fl;
        fl.feature = f;
        fl.layer = layer2;
        fls << *it << fl;
        QgsGeometry *conflict = new QgsGeometry( *g2 );
        TopolErrorClose *err = new TopolErrorClose( r, conflict, fls );
        //TopolErrorClose* err = new TopolErrorClose(r, g2, fls);

        errorList << err;
      }
    }
  }

  if ( badG2 )
    QgsMessageLog::logMessage( tr( "Invalid second geometry." ), tr( "Topology plugin" ) );

  if ( badG1 )
    QgsMessageLog::logMessage( tr( "Invalid first geometry." ), tr( "Topology plugin" ) );

  return errorList;
}
Ejemplo n.º 15
0
void QgsMapToolNodeTool::canvasPressEvent( QMouseEvent * e )
{
  QgsDebugCall;

  mClicked = true;
  mPressCoordinates = e->pos();
  QList<QgsSnappingResult> snapResults;
  if ( !mSelectedFeature )
  {
    QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );
    if ( !vlayer )
      return;

    mSelectAnother = false;
    mSnapper.snapToCurrentLayer( e->pos(), snapResults, QgsSnapper::SnapToVertexAndSegment, -1 );

    if ( snapResults.size() < 1 )
    {
      displaySnapToleranceWarning();
      return;
    }

    mSelectedFeature = new QgsSelectedFeature( snapResults[0].snappedAtGeometry, vlayer, mCanvas );
    connect( mSelectedFeature, SIGNAL( destroyed() ), this, SLOT( selectedFeatureDestroyed() ) );
    mIsPoint = vlayer->geometryType() == QGis::Point;
  }
  else
  {
    QgsVectorLayer *vlayer = mSelectedFeature->vlayer();
    Q_ASSERT( vlayer );

    // some feature already selected
    QgsPoint layerCoordPoint = toLayerCoordinates( vlayer, e->pos() );

    double tol = QgsTolerance::vertexSearchRadius( vlayer, mCanvas->mapRenderer() );

    // get geometry and find if snapping is near it
    int atVertex, beforeVertex, afterVertex;
    double dist;
    QgsPoint closestLayerVertex = mSelectedFeature->geometry()->closestVertex( layerCoordPoint, atVertex, beforeVertex, afterVertex, dist );
    dist = sqrt( dist );

    mSnapper.snapToCurrentLayer( e->pos(), snapResults, QgsSnapper::SnapToVertex, tol );
    if ( dist <= tol )
    {
      // some vertex selected
      mMoving = true;
      mClosestMapVertex = toMapCoordinates( vlayer, closestLayerVertex );
      if ( mMoving )
      {
        if ( mSelectedFeature->isSelected( atVertex ) )
        {
          mDeselectOnRelease = atVertex;
        }
        else if ( mCtrl )
        {
          mSelectedFeature->invertVertexSelection( atVertex );
        }
        else
        {
          mSelectedFeature->deselectAllVertexes();
          mSelectedFeature->selectVertex( atVertex );
        }
      }
      else
      {
        // select another feature
        mAnother = snapResults.first().snappedAtGeometry;
        mSelectAnother = true;
      }
    }
    else
    {
      // no near vertex to snap
      //  unless point layer, try segment
      if ( !mIsPoint )
        mSnapper.snapToCurrentLayer( e->pos(), snapResults, QgsSnapper::SnapToSegment, tol );

      if ( snapResults.size() > 0 )
      {
        // need to check all if there is a point in the feature
        mAnother = snapResults.first().snappedAtGeometry;
        mSelectAnother = true;
        QList<QgsSnappingResult>::iterator it = snapResults.begin();
        QgsSnappingResult snapResult;
        for ( ; it != snapResults.end(); ++it )
        {
          if ( it->snappedAtGeometry == mSelectedFeature->featureId() )
          {
            snapResult = *it;
            mAnother = 0;
            mSelectAnother = false;
            break;
          }
        }

        if ( !mSelectAnother )
        {
          mMoving = true;
          mClosestMapVertex = toMapCoordinates( vlayer, closestLayerVertex );

          if ( mIsPoint )
          {
            if ( !mCtrl )
            {
              mSelectedFeature->deselectAllVertexes();
              mSelectedFeature->selectVertex( snapResult.snappedVertexNr );
            }
            else
            {
              mSelectedFeature->invertVertexSelection( snapResult.snappedVertexNr );
            }
          }
          else
          {
            if ( !mCtrl )
            {
              mSelectedFeature->deselectAllVertexes();
              mSelectedFeature->selectVertex( snapResult.afterVertexNr );
              mSelectedFeature->selectVertex( snapResult.beforeVertexNr );
            }
            else
            {
              mSelectedFeature->invertVertexSelection( snapResult.afterVertexNr );
              mSelectedFeature->invertVertexSelection( snapResult.beforeVertexNr );
            }
          }
        }
      }
      else if ( !mCtrl )
      {
        mSelectedFeature->deselectAllVertexes();
      }
    }
  }
}
Ejemplo n.º 16
0
SCgBaseCommand* SCgScene::deleteSelObjectsCommand(SCgBaseCommand* parentCmd, bool addToStack)
{
    QList<QGraphicsItem*> selObjects = selectedItems();
    QList<QGraphicsItem*>::iterator it = selObjects.begin();

    SCgBaseCommand *cmd = 0;

    for (; it != selObjects.end(); ++it)
    {
        // skip none sc.g-objects
        if ( !SCgObject::isSCgObjectType((*it)->type()) )
            continue;

        SCgObject *obj = static_cast<SCgObject*>(*it);

        if (!cmd)
            cmd = new SCgCommandObjectDelete(this, obj, parentCmd);
        else
            new SCgCommandObjectDelete(this, obj, cmd);
    }
    // Delete points only if object is not deleted by previous operations
    if(!cmd)
    {
        SCgPointObject* parent = 0;
        SCgPointObject::PointFVector newPoints;
        QList<int> delIndexes; //< list with indexes of points which will be deleted

        for (it = selObjects.begin(); it != selObjects.end(); ++it)
        {
            // skip none Point items
            if ( (*it)->type() != SCgPointGraphicsItem::Type)
                continue;

            SCgPointGraphicsItem *item = static_cast<SCgPointGraphicsItem*>(*it);
            if(!parent)
            {
                parent = item->parentSCgPointObject();
                newPoints = parent->points();
                if(newPoints.size() < 2 || (parent->type() == SCgContour::Type && newPoints.size() < 3))
                    break; //If there are not enough points, we  should do nothing.
            }
            //We expect, that at the same time only one SCgPointObject is editable.
            Q_ASSERT(parent == item->parentSCgPointObject());

            delIndexes.push_back(item->pointIndex());
        }
        if(parent)
        {
            // Sort list in back order. Because after erasing item from vector, indexes
            // can be wrong. So we should delete in back order.
            qSort(delIndexes.begin(), delIndexes.end(), qGreater<int>());

            foreach(const int& index, delIndexes)
            {
                int s = newPoints.size();
                if(s > 2 && (parent->type() != SCgContour::Type || s > 3))//< another checking of points count
                    newPoints.erase(newPoints.begin()+index);
            }

            if(newPoints != parent->points())
                cmd = new SCgCommandPointsChange(this, parent, newPoints, parentCmd);
        }
Ejemplo n.º 17
0
bool QgsComposerModel::dropMimeData( const QMimeData *data,
                                     Qt::DropAction action, int row, int column, const QModelIndex &parent )
{
  if ( column != ItemId )
  {
    return false;
  }

  if ( action == Qt::IgnoreAction )
  {
    return true;
  }

  if ( !data->hasFormat( "application/x-vnd.qgis.qgis.composeritemid" ) )
  {
    return false;
  }

  if ( parent.isValid() )
  {
    return false;
  }

  int beginRow = row != -1 ? row : rowCount( QModelIndex() );

  QByteArray encodedData = data->data( "application/x-vnd.qgis.qgis.composeritemid" );
  QDataStream stream( &encodedData, QIODevice::ReadOnly );
  QList<QgsComposerItem*> droppedItems;
  int rows = 0;

  while ( !stream.atEnd() )
  {
    QString text;
    stream >> text;
    const QgsComposerItem* item = mComposition->getComposerItemByUuid( text );
    if ( item )
    {
      droppedItems << const_cast<QgsComposerItem*>( item );
      ++rows;
    }
  }

  if ( droppedItems.length() == 0 )
  {
    //no dropped items
    return false;
  }

  //move dropped items

  //first sort them by z-order
  qSort( droppedItems.begin(), droppedItems.end(), zOrderDescending );

  //calculate position in z order list to drop items at
  int destPos = 0;
  if ( beginRow < rowCount() )
  {
    QgsComposerItem* itemBefore = mItemsInScene.at( beginRow );
    destPos = mItemZList.indexOf( itemBefore );
  }
  else
  {
    //place items at end
    destPos = mItemZList.size();
  }

  //calculate position to insert moved rows to
  int insertPos = destPos;
  QList<QgsComposerItem*>::iterator itemIt = droppedItems.begin();
  for ( ; itemIt != droppedItems.end(); ++itemIt )
  {
    int listPos = mItemZList.indexOf( *itemIt );
    if ( listPos == -1 )
    {
      //should be impossible
      continue;
    }

    if ( listPos < destPos )
    {
      insertPos--;
    }
  }

  //remove rows from list
  itemIt = droppedItems.begin();
  for ( ; itemIt != droppedItems.end(); ++itemIt )
  {
    mItemZList.removeOne( *itemIt );
  }

  //insert items
  itemIt = droppedItems.begin();
  for ( ; itemIt != droppedItems.end(); ++itemIt )
  {
    mItemZList.insert( insertPos, *itemIt );
    insertPos++;
  }

  rebuildSceneItemList();
  mComposition->updateZValues( false );

  return true;
}
Ejemplo n.º 18
0
  void OptBase::interpretKeyword_base(QString &line, Structure* structure)
  {
    QString rep = "";
    // User data
    if (line == "user1")                rep += optimizer()->getUser1();
    else if (line == "user2")           rep += optimizer()->getUser2();
    else if (line == "user3")           rep += optimizer()->getUser3();
    else if (line == "user4")           rep += optimizer()->getUser4();
    else if (line == "description")     rep += description;
    else if (line == "percent")         rep += "%";

    // Structure specific data
    if (line == "coords") {
      QList<Avogadro::Atom*> atoms = structure->atoms();
      QList<Avogadro::Atom*>::const_iterator it;
      int optIndex = -1;
      QHash<int, int> *lut = structure->getOptimizerLookupTable();
      lut->clear();
      const Eigen::Vector3d *vec;
      for (it  = atoms.begin();
           it != atoms.end();
           it++) {
        rep += QString(OpenBabel::etab.GetSymbol((*it)->atomicNumber()))+ " ";
        vec = (*it)->pos();
        rep += QString::number(vec->x()) + " ";
        rep += QString::number(vec->y()) + " ";
        rep += QString::number(vec->z()) + "\n";
        lut->insert(++optIndex, (*it)->index());
      }
    }
    else if (line == "coordsInternalFlags") {
      QList<Avogadro::Atom*> atoms = structure->atoms();
      QList<Avogadro::Atom*>::const_iterator it;
      const Eigen::Vector3d *vec;
      int optIndex = -1;
      QHash<int, int> *lut = structure->getOptimizerLookupTable();
      lut->clear();
      for (it  = atoms.begin();
           it != atoms.end();
           it++) {
        rep += QString(OpenBabel::etab.GetSymbol((*it)->atomicNumber()))+ " ";
        vec = (*it)->pos();
        rep += QString::number(vec->x()) + " 1 ";
        rep += QString::number(vec->y()) + " 1 ";
        rep += QString::number(vec->z()) + " 1\n";
        lut->insert(++optIndex, (*it)->index());
      }
    }
    else if (line == "coordsSuffixFlags") {
      QList<Avogadro::Atom*> atoms = structure->atoms();
      QList<Avogadro::Atom*>::const_iterator it;
      const Eigen::Vector3d *vec;
      int optIndex = -1;
      QHash<int, int> *lut = structure->getOptimizerLookupTable();
      lut->clear();
      for (it  = atoms.begin();
           it != atoms.end();
           it++) {
        rep += QString(OpenBabel::etab.GetSymbol((*it)->atomicNumber()))+ " ";
        vec = (*it)->pos();
        rep += QString::number(vec->x()) + " ";
        rep += QString::number(vec->y()) + " ";
        rep += QString::number(vec->z()) + " 1 1 1\n";
        lut->insert(++optIndex, (*it)->index());
      }
    }
    else if (line == "coordsId") {
      QList<Avogadro::Atom*> atoms = structure->atoms();
      QList<Avogadro::Atom*>::const_iterator it;
      const Eigen::Vector3d *vec;
      int optIndex = -1;
      QHash<int, int> *lut = structure->getOptimizerLookupTable();
      lut->clear();
      for (it  = atoms.begin();
           it != atoms.end();
           it++) {
        rep += QString(OpenBabel::etab.GetSymbol((*it)->atomicNumber()))+ " ";
        rep += QString::number((*it)->atomicNumber()) + " ";
        vec = (*it)->pos();
        rep += QString::number(vec->x()) + " ";
        rep += QString::number(vec->y()) + " ";
        rep += QString::number(vec->z()) + "\n";
        lut->insert(++optIndex, (*it)->index());
      }
    }
    else if (line == "numAtoms")	rep += QString::number(structure->numAtoms());
    else if (line == "numSpecies")	rep += QString::number(structure->getSymbols().size());
    else if (line == "filename")	rep += structure->fileName();
    else if (line == "rempath")       	rep += structure->getRempath();
    else if (line == "gen")           	rep += QString::number(structure->getGeneration());
    else if (line == "id")            	rep += QString::number(structure->getIDNumber());
    else if (line == "incar")         	rep += QString::number(structure->getCurrentOptStep());
    else if (line == "optStep")       	rep += QString::number(structure->getCurrentOptStep());

    if (!rep.isEmpty()) {
      // Remove any trailing newlines
      rep = rep.replace(QRegExp("\n$"), "");
      line = rep;
    }
  }
Ejemplo n.º 19
0
void HistoryManager::load()
{
    loadSettings();

    QFile historyFile(QDesktopServices::storageLocation(QDesktopServices::DataLocation)
                      + QLatin1String("/history"));
    if (!historyFile.exists())
        return;
    if (!historyFile.open(QFile::ReadOnly)) {
        qWarning() << "Unable to open history file" << historyFile.fileName();
        return;
    }

    QList<HistoryEntry> list;
    QDataStream in(&historyFile);
    // Double check that the history file is sorted as it is read in
    bool needToSort = false;
    HistoryEntry lastInsertedItem;
    QByteArray data;
    QDataStream stream;
    QBuffer buffer;
    QString string;
    stream.setDevice(&buffer);
    while (!historyFile.atEnd()) {
        in >> data;
        buffer.close();
        buffer.setBuffer(&data);
        buffer.open(QIODevice::ReadOnly);
        quint32 ver;
        stream >> ver;
        if (ver != HISTORY_VERSION)
            continue;
        HistoryEntry item;
        stream >> string;
        item.url = atomicString(string);
        stream >> item.dateTime;
        stream >> string;
        item.title = atomicString(string);

        if (!item.dateTime.isValid())
            continue;

        if (item == lastInsertedItem) {
            if (lastInsertedItem.title.isEmpty() && !list.isEmpty())
                list[0].title = item.title;
            continue;
        }

        if (!needToSort && !list.isEmpty() && lastInsertedItem < item)
            needToSort = true;

        list.prepend(item);
        lastInsertedItem = item;
    }
    if (needToSort)
        qSort(list.begin(), list.end());

    setHistory(list, true);

    // If we had to sort re-write the whole history sorted
    if (needToSort) {
        m_lastSavedUrl.clear();
        m_saveTimer->changeOccurred();
    }
}
Ejemplo n.º 20
0
qf::core::utils::TreeTable RelaysPlugin::nlegsResultsTable(int class_id, int leg_count, int places, bool exclude_not_finish)
{
	int max_leg = 0;
	qfs::Query q;
	{
		qfs::QueryBuilder qb;
		qb.select("relayLegCount")
			.from("classdefs")
			.where("classId=" QF_IARG(class_id));
		q.execThrow(qb.toString());
		if(q.next())
			max_leg = q.value(0).toInt();
	}
	if(max_leg == 0) {
		qfError() << "Leg count not defined for class id:" << class_id;
		return qf::core::utils::TreeTable();
	}
	if(leg_count > max_leg)
		leg_count = max_leg;

	QList<Relay> relays;
	//QStringList relay_ids;
	{
		qfs::QueryBuilder qb;
		qb.select2("relays", "id, club, name, number")
				.select2("clubs", "name")
				.from("relays")
				.join("relays.club", "clubs.abbr")
				.where("relays.classId=" QF_IARG(class_id));
		q.execThrow(qb.toString());
		while(q.next()) {
			Relay r;
			r.relayId = q.value("relays.id").toInt();
			r.name = (q.value("relays.number").toString()
					+ ' ' + q.value("relays.club").toString()
					+ ' ' + q.value("relays.name").toString()
					+ ' ' + q.value("clubs.name").toString()).trimmed();
			for (int i = 0; i < leg_count; ++i)
				r.legs << Leg();
			relays << r;
			//relay_ids << QString::number(r.relayId);
		}
	}
	{
		qfs::QueryBuilder qb;
		qb.select2("competitors", "id, registration")
				.select2("runs", "id, relayId, leg")
				.select("COALESCE(competitors.lastName, '') || ' ' || COALESCE(competitors.firstName, '') AS competitorName")
				.from("runs")
				.join("runs.competitorId", "competitors.id")
				.joinRestricted("runs.relayId", "relays.id", "relays.classId=" QF_IARG(class_id), qfs::QueryBuilder::INNER_JOIN)
				//.where("runs.relayId IN (" + relay_ids.join(',') + ")")
				.where("runs.leg>0 AND runs.leg<=" + QString::number(leg_count))
				.orderBy("runs.relayId, runs.leg");
		q.execThrow(qb.toString());
		while(q.next()) {
			int relay_id = q.value("runs.relayId").toInt();
			for (int i = 0; i < relays.count(); ++i) {
				if(relays[i].relayId == relay_id) {
					Relay &relay = relays[i];
					int legno = q.value("runs.leg").toInt();
					Leg &leg = relay.legs[legno - 1];
					leg.name = q.value("competitorName").toString();
					leg.runId = q.value("runs.id").toInt();
					leg.reg = q.value("competitors.registration").toString();
					break;
				}
			}
		}
	}
	for (int legno = 1; legno <= leg_count; ++legno) {
		qfs::QueryBuilder qb;
		qb.select2("runs", "id, relayId, timeMs, disqualified")
				.from("runs")
				.joinRestricted("runs.relayId", "relays.id",
								"relays.classId=" QF_IARG(class_id)
								" AND runs.leg=" QF_IARG(legno)
								" AND runs.isRunning"
								" AND NOT runs.notCompeting"
								" AND runs.finishTimeMs>0"
								, qfs::QueryBuilder::INNER_JOIN)
				.orderBy("runs.disqualified, runs.timeMs");
		q.execThrow(qb.toString());
		int run_pos = 1;
		while(q.next()) {
			int relay_id = q.value("runs.relayId").toInt();
			for (int i = 0; i < relays.count(); ++i) {
				if(relays[i].relayId == relay_id) {
					int run_id = q.value("runs.id").toInt();
					Relay &relay = relays[i];
					Leg &leg = relay.legs[legno - 1];
					if(leg.runId != run_id) {
						qfError() << "internal error, leg:" << legno << "runId check:" << leg.runId << "should equal" << run_id;
					}
					else {
						leg.notfinish = false;
						leg.disq = q.value("runs.disqualified").toBool();
						leg.time = q.value("timeMs").toInt();
						leg.pos = leg.disq? 0: run_pos;
						run_pos++;
					}
					break;
				}
			}
		}
	}
	/// compute overal legs positions
	for (int legno = 1; legno <= leg_count; ++legno) {
		QList<QPair<int, int>> relay_stime;
		for (int i = 0; i < relays.count(); ++i) {
			Relay &relay = relays[i];
			Leg &leg = relay.legs[legno - 1];
			if(!leg.notfinish && !leg.disq) {
				if(legno == 1)
					leg.stime = leg.time;
				else if(relay.legs[legno-2].stime > 0)
					leg.stime = leg.time + relay.legs[legno-2].stime;
			}
			if(leg.stime > 0)
				relay_stime << QPair<int, int>(relay.relayId, leg.stime);
		}
		std::sort(relay_stime.begin(), relay_stime.end(), [](const QPair<int, int> &a, const QPair<int, int> &b) {return a.second < b.second;});
		int pos = 0;
		for(const QPair<int, int> &p : relay_stime) {
			int relay_id = p.first;
			for (int i = 0; i < relays.count(); ++i) {
				if(relays[i].relayId == relay_id) {
					Relay &relay = relays[i];
					Leg &leg = relay.legs[legno - 1];
					leg.spos = ++pos;
					break;
				}
			}
		}
	}
	if(exclude_not_finish) {
		/*
		relays.erase(std::remove_if(relays.begin(),
									  relays.end(),
									  [](const Relay &r){return r.time(leg_count) == TIME_NOT_FINISH;}),
					   relays.end());
		*/
		QMutableListIterator<Relay> i(relays);
		while (i.hasNext()) {
			const Relay &r = i.next();
			if(r.time(leg_count) == qog::TimeMs::NOT_FINISH_TIME_MSEC)
				i.remove();
		}
	}
	/// sort relays
	std::sort(relays.begin(), relays.end(), [leg_count](const Relay &a, const Relay &b) {
		return a.time(leg_count) < b.time(leg_count);
	});

	int time0 = 0;
	qf::core::utils::TreeTable tt;
	tt.appendColumn("pos", QVariant::Int);
	tt.appendColumn("name", QVariant::String);
	tt.appendColumn("time", QVariant::Int);
	tt.appendColumn("loss", QVariant::Int);
	for (int i = 0; i < qMin(relays.count(), places); ++i) {
		qf::core::utils::TreeTableRow rr = tt.appendRow();
		Relay &relay = relays[i];
		int time = relay.time(leg_count);
		if(i == 0)
			time0 = time;
		int prev_time = (i > 0)? relays[i-1].time(leg_count): 0;
		rr.setValue("pos", (time <= qog::TimeMs::MAX_REAL_TIME_MSEC && time > prev_time)? i+1: 0);
		rr.setValue("name", relay.name);
		rr.setValue("time", time);
		rr.setValue("loss", (time <= qog::TimeMs::MAX_REAL_TIME_MSEC)?time - time0: 0);
		qf::core::utils::TreeTable tt2;
		tt.appendColumn("name", QVariant::String);
		tt.appendColumn("reg", QVariant::String);
		tt.appendColumn("time", QVariant::Int);
		tt.appendColumn("pos", QVariant::Int);
		tt.appendColumn("stime", QVariant::Int);
		tt.appendColumn("spos", QVariant::Int);
		//tt.appendColumn("disq", QVariant::Bool);
		for (int j = 0; j < relay.legs.count(); ++j) {
			Leg &leg = relay.legs[j];
			qf::core::utils::TreeTableRow rr2 = tt2.appendRow();
			rr2.setValue("competitorName", leg.name);
			rr2.setValue("registration", leg.reg);
			rr2.setValue("time",
						 leg.disq? qog::TimeMs::DISQ_TIME_MSEC
								: (leg.time == 0)? qog::TimeMs::NOT_FINISH_TIME_MSEC
												: leg.time);
			rr2.setValue("pos", leg.pos);
			rr2.setValue("stime", leg.stime);
			rr2.setValue("spos", leg.spos);
			//rr2.setValue("disq", leg.disq);
		}
		rr.appendTable(tt2);
	}
	//qfInfo() << tt.toString();
	return tt;
}
void QgsSingleBandPseudoColorRendererWidget::on_mClassifyButton_clicked()
{
  int bandComboIndex = mBandComboBox->currentIndex();
  if ( bandComboIndex == -1 || !mRasterLayer )
  {
    return;
  }

  //int bandNr = mBandComboBox->itemData( bandComboIndex ).toInt();
  //QgsRasterBandStats myRasterBandStats = mRasterLayer->dataProvider()->bandStatistics( bandNr );
  int numberOfEntries;

  QgsColorRampShader::ColorRamp_TYPE interpolation = static_cast< QgsColorRampShader::ColorRamp_TYPE >( mColorInterpolationComboBox->itemData( mColorInterpolationComboBox->currentIndex() ).toInt() );
  bool discrete = interpolation == QgsColorRampShader::DISCRETE;

  QList<double> entryValues;
  QVector<QColor> entryColors;

  double min = lineEditValue( mMinLineEdit );
  double max = lineEditValue( mMaxLineEdit );

  QScopedPointer< QgsVectorColorRampV2 > colorRamp( mColorRampComboBox->currentColorRamp() );

  if ( mClassificationModeComboBox->itemData( mClassificationModeComboBox->currentIndex() ).toInt() == Continuous )
  {
    if ( colorRamp.data() )
    {
      numberOfEntries = colorRamp->count();
      entryValues.reserve( numberOfEntries );
      if ( discrete )
      {
        double intervalDiff = max - min;

        // remove last class when ColorRamp is gradient and discrete, as they are implemented with an extra stop
        QgsVectorGradientColorRampV2* colorGradientRamp = dynamic_cast<QgsVectorGradientColorRampV2*>( colorRamp.data() );
        if ( colorGradientRamp != NULL && colorGradientRamp->isDiscrete() )
        {
          numberOfEntries--;
        }
        else
        {
          // if color ramp is continuous scale values to get equally distributed classes.
          // Doesn't work perfectly when stops are non equally distributed.
          intervalDiff *= ( numberOfEntries - 1 ) / ( double )numberOfEntries;
        }

        // skip first value (always 0.0)
        for ( int i = 1; i < numberOfEntries; ++i )
        {
          double value = colorRamp->value( i );
          entryValues.push_back( min + value * intervalDiff );
        }
        entryValues.push_back( std::numeric_limits<double>::infinity() );
      }
      else
      {
        for ( int i = 0; i < numberOfEntries; ++i )
        {
          double value = colorRamp->value( i );
          entryValues.push_back( min + value * ( max - min ) );
        }
      }
      // for continuous mode take original color map colors
      for ( int i = 0; i < numberOfEntries; ++i )
      {
        entryColors.push_back( colorRamp->color( colorRamp->value( i ) ) );
      }
    }
  }
  else // for other classification modes interpolate colors linearly
  {
    numberOfEntries = mNumberOfEntriesSpinBox->value();
    if ( numberOfEntries < 2 )
      return; // < 2 classes is not useful, shouldn't happen, but if it happens save it from crashing

    if ( mClassificationModeComboBox->itemData( mClassificationModeComboBox->currentIndex() ).toInt() == Quantile )
    { // Quantile
      int bandNr = mBandComboBox->itemData( bandComboIndex ).toInt();
      //QgsRasterHistogram rasterHistogram = mRasterLayer->dataProvider()->histogram( bandNr );

      double cut1 = std::numeric_limits<double>::quiet_NaN();
      double cut2 = std::numeric_limits<double>::quiet_NaN();

      QgsRectangle extent = mMinMaxWidget->extent();
      int sampleSize = mMinMaxWidget->sampleSize();

      // set min and max from histogram, used later to calculate number of decimals to display
      mRasterLayer->dataProvider()->cumulativeCut( bandNr, 0.0, 1.0, min, max, extent, sampleSize );

      entryValues.reserve( numberOfEntries );
      if ( discrete )
      {
        double intervalDiff = 1.0 / ( numberOfEntries );
        for ( int i = 1; i < numberOfEntries; ++i )
        {
          mRasterLayer->dataProvider()->cumulativeCut( bandNr, 0.0, i * intervalDiff, cut1, cut2, extent, sampleSize );
          entryValues.push_back( cut2 );
        }
        entryValues.push_back( std::numeric_limits<double>::infinity() );
      }
      else
      {
        double intervalDiff = 1.0 / ( numberOfEntries - 1 );
        for ( int i = 0; i < numberOfEntries; ++i )
        {
          mRasterLayer->dataProvider()->cumulativeCut( bandNr, 0.0, i * intervalDiff, cut1, cut2, extent, sampleSize );
          entryValues.push_back( cut2 );
        }
      }
    }
    else // EqualInterval
    {
      entryValues.reserve( numberOfEntries );
      if ( discrete )
      {
        // in discrete mode the lowest value is not an entry and the highest
        // value is inf, there are ( numberOfEntries ) of which the first
        // and last are not used.
        double intervalDiff = ( max - min ) / ( numberOfEntries );

        for ( int i = 1; i < numberOfEntries; ++i )
        {
          entryValues.push_back( min + i * intervalDiff );
        }
        entryValues.push_back( std::numeric_limits<double>::infinity() );
      }
      else
      {
        //because the highest value is also an entry, there are (numberOfEntries - 1) intervals
        double intervalDiff = ( max - min ) / ( numberOfEntries - 1 );

        for ( int i = 0; i < numberOfEntries; ++i )
        {
          entryValues.push_back( min + i * intervalDiff );
        }
      }
    }

    if ( !colorRamp.data() )
    {
      //hard code color range from blue -> red (previous default)
      int colorDiff = 0;
      if ( numberOfEntries != 0 )
      {
        colorDiff = ( int )( 255 / numberOfEntries );
      }

      entryColors.reserve( numberOfEntries );
      for ( int i = 0; i < numberOfEntries; ++i )
      {
        QColor currentColor;
        int idx = mInvertCheckBox->isChecked() ? numberOfEntries - i - 1 : i;
        currentColor.setRgb( colorDiff*idx, 0, 255 - colorDiff * idx );
        entryColors.push_back( currentColor );
      }
    }
    else
    {
      entryColors.reserve( numberOfEntries );
      for ( int i = 0; i < numberOfEntries; ++i )
      {
        int idx = mInvertCheckBox->isChecked() ? numberOfEntries - i - 1 : i;
        entryColors.push_back( colorRamp->color((( double ) idx ) / ( numberOfEntries - 1 ) ) );
      }
    }
  }

  mColormapTreeWidget->clear();

  QList<double>::const_iterator value_it = entryValues.begin();
  QVector<QColor>::const_iterator color_it = entryColors.begin();

  // calculate a reasonable number of decimals to display
  double maxabs = log10( qMax( qAbs( max ), qAbs( min ) ) );
  int nDecimals = qRound( qMax( 3.0 + maxabs - log10( max - min ), maxabs <= 15.0 ? maxabs + 0.49 : 0.0 ) );

  for ( ; value_it != entryValues.end(); ++value_it, ++color_it )
  {
    QgsTreeWidgetItem* newItem = new QgsTreeWidgetItem( mColormapTreeWidget );
    newItem->setText( ValueColumn, QString::number( *value_it, 'g', nDecimals ) );
    newItem->setBackground( ColorColumn, QBrush( *color_it ) );
    newItem->setText( LabelColumn, QString() );
    newItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable );
    connect( newItem, SIGNAL( itemEdited( QTreeWidgetItem*, int ) ),
             this, SLOT( mColormapTreeWidget_itemEdited( QTreeWidgetItem*, int ) ) );
  }
  autoLabel();
  emit widgetChanged();
}
Ejemplo n.º 22
0
void LogScene::createBackground() {
    QBrush brush(QColor("white"));
    QPen pen(QColor("white"));
    // Background color
    QList<QGraphicsView*> views = this->views();
    int maxWidth = 0;
    double minuteSize = (double)BLOCKSIZE / (double)60;
    int maxHeight = minuteSize * 25 * 60;
    for (QList<QGraphicsView*>::iterator iter = views.begin(); iter != views.end(); iter++) {
        QGraphicsView* view = *iter;
//        int viewHeight = view->height();
        int viewWidth = view->width();
//        if (viewHeight > maxHeight) {
//            maxHeight = viewHeight;
//        }
        if (viewWidth > maxWidth) {
            maxWidth = viewWidth;
        }
    }
//    if (_viewSizeHeight > maxHeight) {
//        maxHeight = _viewSizeHeight;
//    }
    if (_viewSizeWidth > maxWidth) {
        maxWidth = _viewSizeWidth;
    }
    _viewSizeHeight = BLOCKSIZE*25;
    _viewSizeWidth = maxWidth;

    this->addRect(0, 0, maxWidth, maxHeight, pen, brush);

    //    int columnSize = geometry().width() / NU_COLS;
    int textSize = 30;
    int margin = 15;
    int cols = _totalDays;

    if ((cols * dayWidth()) < maxWidth) {
        cols = (maxWidth / dayWidth()) + 10;
        _totalDays = cols;
    }
    DateTime startDate = this->_startDate;
    DateTime today;
    today.setHour(0);
    today.setMin(0);
    today.setSecs(0);
    for (int x = 0; x < (cols + 1); x++) {
        QColor barcolor;
        if ((x % 2) > 0) {
            barcolor = QColor("white");
        } else {
            barcolor = QColor(240, 240, 240);
        }
        QBrush brushBar(barcolor);
        QPen penBar(barcolor);
        int left = (x* dayWidth()) + 0;
        int top = 0;
        int heigth = maxHeight;
        addRect(left, top, dayWidth(), heigth, penBar, brushBar);

        QPen pen(QColor(200, 200, 200));
        pen.setStyle(Qt::DashLine);

        addLine(x*dayWidth(), 0 , x*dayWidth(), heigth, pen);
        if (startDate == today) {
            barcolor = QColor(230, 230, 250);
            addRect(left, top, dayWidth(), heigth, penBar, QBrush(barcolor));
        }
        startDate = startDate.addDays(1);
    }
}
Ejemplo n.º 23
0
/**
  * This method is called several times, one by received entries. The entries are inserted into the model.
  * The given entries are sorted by their level, we will keep the sort when inserting the entry but with some modifications :
  * - The directories are put first.
  * - All entries with the same level are sorted first by their path (prefixed with the shared directory name) and then by their name.
  * - All file entries with the same chunks (identical data) are grouped. They can be owned by different peer.
  */
void SearchModel::result(const Protos::Common::FindResult& findResult)
{
   if (findResult.entry_size() == 0)
      return;

   QList<const Protos::Common::FindResult_EntryLevel*> sortedEntries;
   for (int i = 0; i < findResult.entry_size(); i++)
      sortedEntries << &findResult.entry(i);
   qSort(sortedEntries.begin(), sortedEntries.end(), &findEntryLessThan);

   int currentIndex = 0;

   bool maxLevelChange = false;

   for (QListIterator<const Protos::Common::FindResult_EntryLevel*> i(sortedEntries); i.hasNext();)
   {
      const Protos::Common::FindResult_EntryLevel* entry = i.next();
      if (this->setMaxLevel(entry->level()))
         maxLevelChange = true;

      // Search if a similar entry already exists. If so then insert the new tree as child.
      if (entry->entry().type() == Protos::Common::Entry_Type_FILE && entry->entry().chunk_size() > 0)
      {
         Common::Hash firstChunk = entry->entry().chunk(0).hash();
         SearchTree* similarTree = 0;
         if ((similarTree = this->indexedFile.value(firstChunk)) && similarTree->isSameAs(entry->entry()))
         {
            if (similarTree->getNbChildren() == 0)
            {
               this->beginInsertRows(this->createIndex(0, 0, similarTree), 0, 0);
               similarTree->insertChild(similarTree);
               this->endInsertRows();
            }

            // Search the better name (tree with the lowest level) to display it on the top.
            for (int i = 0; i <= similarTree->getNbChildren(); i++)
            {
               if (i == similarTree->getNbChildren() || static_cast<SearchTree*>(similarTree->getChild(i))->getLevel() > static_cast<int>(entry->level()))
               {
                  this->beginInsertRows(this->createIndex(0, 0, similarTree), i, i);
                  Common::Hash peerID = findResult.peer_id().hash();
                  SearchTree* newTree = similarTree->insertChild(i, *entry, peerID, this->peerListModel.getNick(peerID, tr("<unknown>")));
                  this->endInsertRows();

                  if (static_cast<int>(entry->level()) < similarTree->getLevel())
                  {
                     const int row = similarTree->getOwnPosition();
                     similarTree->copyFrom(newTree);
                     emit dataChanged(this->createIndex(row, 0, similarTree), this->createIndex(row, 3, similarTree));
                  }

                  break;
               }
            }

            continue;
         }
      }

      currentIndex = this->insertTree(*entry, findResult.peer_id().hash(), currentIndex);
   }

   if (maxLevelChange && this->rowCount() > 0)
      emit dataChanged(this->createIndex(0, 2), this->createIndex(this->rowCount() - 1, 2));
}
void QgsGraduatedSymbolRendererV2::updateClasses( QgsVectorLayer *vlayer, Mode mode, int nclasses )
{
  if ( mAttrName.isEmpty() )
    return;

  setMode( mode );
  // Custom classes are not recalculated
  if ( mode == Custom )
    return;

  if ( nclasses < 1 )
    nclasses = 1;

  QList<double> values;
  bool valuesLoaded = false;
  double minimum;
  double maximum;

  int attrNum = vlayer->fieldNameIndex( mAttrName );

  if ( attrNum == -1 )
  {
    values = getDataValues( vlayer );
    if ( values.isEmpty() )
      return;

    qSort( values );
    minimum = values.first();
    maximum = values.last();
    valuesLoaded = true;
  }
  else
  {
    minimum = vlayer->minimumValue( attrNum ).toDouble();
    maximum = vlayer->maximumValue( attrNum ).toDouble();
  }

  QgsDebugMsg( QString( "min %1 // max %2" ).arg( minimum ).arg( maximum ) );
  QList<double> breaks;
  QList<double> labels;
  if ( mode == EqualInterval )
  {
    breaks = _calcEqualIntervalBreaks( minimum, maximum, nclasses );
  }
  else if ( mode == Pretty )
  {
    breaks = _calcPrettyBreaks( minimum, maximum, nclasses );
  }
  else if ( mode == Quantile || mode == Jenks || mode == StdDev )
  {
    // get values from layer
    if ( !valuesLoaded )
    {
      values = getDataValues( vlayer );
    }

    // calculate the breaks
    if ( mode == Quantile )
    {
      breaks = _calcQuantileBreaks( values, nclasses );
    }
    else if ( mode == Jenks )
    {
      breaks = _calcJenksBreaks( values, nclasses, minimum, maximum );
    }
    else if ( mode == StdDev )
    {
      breaks = _calcStdDevBreaks( values, nclasses, labels );
    }
  }
  else
  {
    Q_ASSERT( false );
  }

  double lower, upper = minimum;
  QString label;
  deleteAllClasses();

  // "breaks" list contains all values at class breaks plus maximum as last break

  int i = 0;
  for ( QList<double>::iterator it = breaks.begin(); it != breaks.end(); ++it, ++i )
  {
    lower = upper; // upper border from last interval
    upper = *it;

    // Label - either StdDev label or default label for a range
    if ( mode == StdDev )
    {
      if ( i == 0 )
      {
        label = "< " + QString::number( labels[i], 'f', 2 ) + " Std Dev";
      }
      else if ( i == labels.count() - 1 )
      {
        label = ">= " + QString::number( labels[i-1], 'f', 2 ) + " Std Dev";
      }
      else
      {
        label = QString::number( labels[i-1], 'f', 2 ) + " Std Dev" + " - " + QString::number( labels[i], 'f', 2 ) + " Std Dev";
      }
    }
    else
    {
      label = mLabelFormat.labelForRange( lower, upper );
    }
    QgsSymbolV2* newSymbol = mSourceSymbol ? mSourceSymbol->clone() : QgsSymbolV2::defaultSymbol( vlayer->geometryType() );
    addClass( QgsRendererRangeV2( lower, upper, newSymbol, label ) );
  }
  updateColorRamp( 0, mInvertedColorRamp );
}
Ejemplo n.º 25
0
    /* 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)
    {
        OutputDebugStringF("updateWallet %s %i\n", hash.ToString().c_str(), status);
        {
            LOCK(wallet->cs_wallet);

            // Find transaction in wallet
            std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
            bool inWallet = mi != wallet->mapWallet.end();

            // 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);

            // Determine whether to show transaction or not
            bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second));

            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 */
            }

            OutputDebugStringF("   inWallet=%i inModel=%i Index=%i-%i showTransaction=%i derivedStatus=%i\n",
                     inWallet, inModel, lowerIndex, upperIndex, showTransaction, status);

            switch(status)
            {
            case CT_NEW:
                if(inModel)
                {
                    OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is already in model\n");
                    break;
                }
                if(!inWallet)
                {
                    OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is not in wallet\n");
                    break;
                }
                if(showTransaction)
                {
                    // 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;
                        foreach(const TransactionRecord &rec, toInsert)
                        {
                            cachedWallet.insert(insert_idx, rec);
                            insert_idx += 1;
                        }
                        parent->endInsertRows();
                    }
                }
                break;
            case CT_DELETED:
                if(!inModel)
                {
                    OutputDebugStringF("Warning: updateWallet: Got CT_DELETED, but transaction is not in model\n");
                    break;
                }
                // Removed -- remove entire transaction from table
                parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
                cachedWallet.erase(lower, upper);
                parent->endRemoveRows();
                break;
            case CT_UPDATED:
                // Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for
                // visible transactions.
                break;
            }
Ejemplo n.º 26
0
void DlgRevolution::accept()
{
    if (!this->validate())
        return;
    Gui::WaitCursor wc;
    App::Document* activeDoc = App::GetApplication().getActiveDocument();
    activeDoc->openTransaction("Revolve");

    try{
        QString shape, type, name, solid;
        QList<QTreeWidgetItem *> items = ui->treeWidget->selectedItems();
        if (ui->checkSolid->isChecked()) {
            solid = QString::fromLatin1("True");}
        else {
            solid = QString::fromLatin1("False");}

        App::PropertyLinkSub axisLink;
        this->getAxisLink(axisLink);
        QString strAxisLink;
        if (axisLink.getValue()){
            strAxisLink = QString::fromLatin1("(App.ActiveDocument.%1, %2)")
                    .arg(QString::fromLatin1(axisLink.getValue()->getNameInDocument()))
                    .arg(axisLink.getSubValues().size() ==  1 ?
                             QString::fromLatin1("\"%1\"").arg(QString::fromLatin1(axisLink.getSubValues()[0].c_str()))
                             : QString() );
        } else {
            strAxisLink = QString::fromLatin1("None");
        }

        QString symmetric;
        if (ui->checkSymmetric->isChecked()) {
            symmetric = QString::fromLatin1("True");}
        else {
            symmetric = QString::fromLatin1("False");}

        for (QList<QTreeWidgetItem *>::iterator it = items.begin(); it != items.end(); ++it) {
            shape = (*it)->data(0, Qt::UserRole).toString();
            type = QString::fromLatin1("Part::Revolution");
            name = QString::fromLatin1(activeDoc->getUniqueObjectName("Revolve").c_str());
            Base::Vector3d axis = this->getDirection();
            Base::Vector3d pos = this->getPosition();


            QString code = QString::fromLatin1(
                "FreeCAD.ActiveDocument.addObject(\"%1\",\"%2\")\n"
                "FreeCAD.ActiveDocument.%2.Source = FreeCAD.ActiveDocument.%3\n"
                "FreeCAD.ActiveDocument.%2.Axis = (%4,%5,%6)\n"
                "FreeCAD.ActiveDocument.%2.Base = (%7,%8,%9)\n"
                "FreeCAD.ActiveDocument.%2.Angle = %10\n"
                "FreeCAD.ActiveDocument.%2.Solid = %11\n"
                "FreeCAD.ActiveDocument.%2.AxisLink = %12\n"
                "FreeCAD.ActiveDocument.%2.Symmetric = %13\n"
                "FreeCADGui.ActiveDocument.%3.Visibility = False\n")
                .arg(type).arg(name).arg(shape) //%1, 2, 3
                .arg(axis.x,0,'f',15) //%4
                .arg(axis.y,0,'f',15) //%5
                .arg(axis.z,0,'f',15) //%6
                .arg(pos.x, 0,'f',15) //%7
                .arg(pos.y, 0,'f',15) //%8
                .arg(pos.z, 0,'f',15) //%9
                .arg(getAngle(),0,'f',15) //%10
                .arg(solid) //%11
                .arg(strAxisLink) //%12
                .arg(symmetric) //13
                ;
            Gui::Command::runCommand(Gui::Command::App, code.toLatin1());
            QByteArray to = name.toLatin1();
            QByteArray from = shape.toLatin1();
            Gui::Command::copyVisual(to, "ShapeColor", from);
            Gui::Command::copyVisual(to, "LineColor", from);
            Gui::Command::copyVisual(to, "PointColor", from);
        }

        activeDoc->commitTransaction();
        activeDoc->recompute();
    } catch (Base::Exception &err) {
        QMessageBox::critical(this, windowTitle(),
            tr("Creating Revolve failed.\n\n%1").arg(QString::fromUtf8(err.what())));
        return;
    } catch (...){
        QMessageBox::critical(this, windowTitle(),
            tr("Creating Revolve failed.\n\n%1").arg(QString::fromUtf8("Unknown error")));
        return;
    }

    QDialog::accept();
}
Ejemplo n.º 27
0
void old_tesselate_polygon(QVector<XTrapezoid> *traps, const QPointF *pg, int pgSize,
                           bool winding)
{
    QVector<QEdge> edges;
    edges.reserve(128);
    qreal ymin(INT_MAX/256);
    qreal ymax(INT_MIN/256);

    //painter.begin(pg, pgSize);
    Q_ASSERT(pg[0] == pg[pgSize-1]);
    // generate edge table
//     qDebug() << "POINTS:";
    for (int x = 0; x < pgSize-1; ++x) {
	QEdge edge;
        QPointF p1(Q27Dot5ToDouble(FloatToQ27Dot5(pg[x].x())),
                   Q27Dot5ToDouble(FloatToQ27Dot5(pg[x].y())));
        QPointF p2(Q27Dot5ToDouble(FloatToQ27Dot5(pg[x+1].x())),
                   Q27Dot5ToDouble(FloatToQ27Dot5(pg[x+1].y())));

//         qDebug() << "    "
//                  << p1;
	edge.winding = p1.y() > p2.y() ? 1 : -1;
	if (edge.winding > 0)
            qSwap(p1, p2);
        edge.p1.x = XDoubleToFixed(p1.x());
        edge.p1.y = XDoubleToFixed(p1.y());
        edge.p2.x = XDoubleToFixed(p2.x());
        edge.p2.y = XDoubleToFixed(p2.y());

	edge.m = (p1.y() - p2.y()) / (p1.x() - p2.x()); // line derivative
	edge.b = p1.y() - edge.m * p1.x(); // intersection with y axis
	edge.m = edge.m != 0.0 ? 1.0 / edge.m : 0.0; // inverted derivative
	edges.append(edge);
        ymin = qMin(ymin, qreal(XFixedToDouble(edge.p1.y)));
        ymax = qMax(ymax, qreal(XFixedToDouble(edge.p2.y)));
    }

    QList<const QEdge *> et; 	    // edge list
    for (int i = 0; i < edges.size(); ++i)
        et.append(&edges.at(i));

    // sort edge table by min y value
    qSort(et.begin(), et.end(), compareEdges);

    // eliminate shared edges
    for (int i = 0; i < et.size(); ++i) {
	for (int k = i+1; k < et.size(); ++k) {
            const QEdge *edgeI = et.at(i);
            const QEdge *edgeK = et.at(k);
            if (edgeK->p1.y > edgeI->p1.y)
                break;
   	    if (edgeI->winding != edgeK->winding &&
                isEqual(edgeI->p1, edgeK->p1) && isEqual(edgeI->p2, edgeK->p2)
		) {
 		et.removeAt(k);
		et.removeAt(i);
		--i;
		break;
	    }
	}
    }

    if (ymax <= ymin)
	return;
    QList<const QEdge *> aet; 	    // edges that intersects the current scanline

//     if (ymin < 0)
// 	ymin = 0;
//     if (paintEventClipRegion) // don't scan more lines than we have to
// 	ymax = paintEventClipRegion->boundingRect().height();

#ifdef QT_DEBUG_TESSELATOR
    qDebug("==> ymin = %f, ymax = %f", ymin, ymax);
#endif // QT_DEBUG_TESSELATOR

    currentY = ymin; // used by the less than op
    for (qreal y = ymin; y < ymax;) {
	// fill active edge table with edges that intersect the current line
	for (int i = 0; i < et.size(); ++i) {
            const QEdge *edge = et.at(i);
            if (edge->p1.y > XDoubleToFixed(y))
                break;
            aet.append(edge);
            et.removeAt(i);
            --i;
	}

	// remove processed edges from active edge table
	for (int i = 0; i < aet.size(); ++i) {
	    if (aet.at(i)->p2.y <= XDoubleToFixed(y)) {
		aet.removeAt(i);
 		--i;
	    }
	}
        if (aet.size()%2 != 0) {
#ifndef QT_NO_DEBUG
            qWarning("QX11PaintEngine: aet out of sync - this should not happen.");
#endif
            return;
        }

	// done?
	if (!aet.size()) {
            if (!et.size()) {
                break;
	    } else {
 		y = currentY = XFixedToDouble(et.at(0)->p1.y);
                continue;
	    }
        }

        // calculate the next y where we have to start a new set of trapezoids
	qreal next_y(INT_MAX/256);
 	for (int i = 0; i < aet.size(); ++i) {
            const QEdge *edge = aet.at(i);
 	    if (XFixedToDouble(edge->p2.y) < next_y)
 		next_y = XFixedToDouble(edge->p2.y);
        }

	if (et.size() && next_y > XFixedToDouble(et.at(0)->p1.y))
	    next_y = XFixedToDouble(et.at(0)->p1.y);

        int aetSize = aet.size();
	for (int i = 0; i < aetSize; ++i) {
	    for (int k = i+1; k < aetSize; ++k) {
                const QEdge *edgeI = aet.at(i);
                const QEdge *edgeK = aet.at(k);
		qreal m1 = edgeI->m;
		qreal b1 = edgeI->b;
		qreal m2 = edgeK->m;
		qreal b2 = edgeK->b;

		if (qAbs(m1 - m2) < 0.001)
                    continue;

                // ### intersect is not calculated correctly when optimized with -O2 (gcc)
                volatile qreal intersect = 0;
                if (!qIsFinite(b1))
                    intersect = (1.f / m2) * XFixedToDouble(edgeI->p1.x) + b2;
                else if (!qIsFinite(b2))
                    intersect = (1.f / m1) * XFixedToDouble(edgeK->p1.x) + b1;
                else
                    intersect = (b1*m1 - b2*m2) / (m1 - m2);

 		if (intersect > y && intersect < next_y)
		    next_y = intersect;
	    }
	}

        XFixed yf, next_yf;
        yf = qrealToXFixed(y);
        next_yf = qrealToXFixed(next_y);

        if (yf == next_yf) {
            y = currentY = next_y;
            continue;
        }

#ifdef QT_DEBUG_TESSELATOR
        qDebug("###> y = %f, next_y = %f, %d active edges", y, next_y, aet.size());
        qDebug("===> edges");
        dump_edges(et);
        qDebug("===> active edges");
        dump_edges(aet);
#endif
	// calc intersection points
 	QVarLengthArray<QIntersectionPoint> isects(aet.size()+1);
 	for (int i = 0; i < isects.size()-1; ++i) {
            const QEdge *edge = aet.at(i);
 	    isects[i].x = (edge->p1.x != edge->p2.x) ?
			  ((y - edge->b)*edge->m) : XFixedToDouble(edge->p1.x);
	    isects[i].edge = edge;
	}

	Q_ASSERT(isects.size()%2 == 1);

	// sort intersection points
 	qSort(&isects[0], &isects[isects.size()-1], compareIntersections);
//         qDebug() << "INTERSECTION_POINTS:";
//  	for (int i = 0; i < isects.size(); ++i)
//             qDebug() << isects[i].edge << isects[i].x;

        if (winding) {
            // winding fill rule
            for (int i = 0; i < isects.size()-1;) {
                int winding = 0;
                const QEdge *left = isects[i].edge;
                const QEdge *right = 0;
                winding += isects[i].edge->winding;
                for (++i; i < isects.size()-1 && winding != 0; ++i) {
                    winding += isects[i].edge->winding;
                    right = isects[i].edge;
                }
                if (!left || !right)
                    break;
                //painter.addTrapezoid(&toXTrapezoid(yf, next_yf, *left, *right));
                traps->append(toXTrapezoid(yf, next_yf, *left, *right));
            }
        } else {
            // odd-even fill rule
            for (int i = 0; i < isects.size()-2; i += 2) {
                //painter.addTrapezoid(&toXTrapezoid(yf, next_yf, *isects[i].edge, *isects[i+1].edge));
                traps->append(toXTrapezoid(yf, next_yf, *isects[i].edge, *isects[i+1].edge));
            }
        }
	y = currentY = next_y;
    }

#ifdef QT_DEBUG_TESSELATOR
    qDebug("==> number of trapezoids: %d - edge table size: %d\n", traps->size(), et.size());

    for (int i = 0; i < traps->size(); ++i)
        dump_trap(traps->at(i));
#endif

    // optimize by unifying trapezoids that share left/right lines
    // and have a common top/bottom edge
//     for (int i = 0; i < tps.size(); ++i) {
// 	for (int k = i+1; k < tps.size(); ++k) {
// 	    if (i != k && tps.at(i).right == tps.at(k).right
// 		&& tps.at(i).left == tps.at(k).left
// 		&& (tps.at(i).top == tps.at(k).bottom
// 		    || tps.at(i).bottom == tps.at(k).top))
// 	    {
// 		tps[i].bottom = tps.at(k).bottom;
// 		tps.removeAt(k);
//                 i = 0;
// 		break;
// 	    }
// 	}
//     }
    //static int i = 0;
    //QImage img = painter.end();
    //img.save(QString("res%1.png").arg(i++), "PNG");
}
    /* 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 std::string &hash, int status)
    {
        LOG_PRINT_L2("TransactionTablePriv::updateWallet : " << hash << " " << status);
        {
            LOG_PRINT_L4("LOCK2(cs_main, wallet->cs_wallet) updateWallet");
            LOCK2(cs_main, wallet->cs_wallet);
            LOG_PRINT_L4("LOCK2(cs_main, wallet->cs_wallet) updateWallet acquired");

            // Find transaction in wallet
            auto mi = wallet->mapWallet.find(GetCryptoHash(hash));
            bool inWallet = mi != wallet->mapWallet.end();

            // 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);

            // Determine whether to show transaction or not
            bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second));

            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() << "   inWallet=" + QString::number(inWallet) + " 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)
                {
                    LOG_PRINT_L1("TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is already in model");
                    break;
                }
                if(!inWallet)
                {
                    LOG_PRINT_L1("TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is not in wallet");
                    break;
                }
                if(showTransaction)
                {
                    // 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;
                        foreach(const TransactionRecord &rec, toInsert)
                        {
                            cachedWallet.insert(insert_idx, rec);
                            insert_idx += 1;
                        }
                        parent->endInsertRows();
                    }
                }
                break;
            case CT_DELETED:
                if(!inModel)
                {
                    LOG_PRINT_L1("TransactionTablePriv::updateWallet : Warning: Got CT_DELETED, but transaction is not in model");
                    break;
                }
                // Removed -- remove entire transaction from table
                parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
                cachedWallet.erase(lower, upper);
                parent->endRemoveRows();
                break;
            case CT_UPDATED:
                // Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for
                // visible transactions.
                break;
            }
void CleverApplicationIconPresenterSortingDelegate::_sortTheseByFiltersImplementation(QList<IdBasedWidgetBase *> allItems, QString filterText, bool isOnlyAutostartOnes, bool isOnlyHiddenOnes, bool isAllowHiddenOnes, bool isAllowNotInstalledOnes, bool isCaseSensitive, bool isCompareWithoutSpaces)
{    
    WidgetListSnapshot resultItems;
    QList<QWidget *> resultIconPresenterList;

    QString normalizedFilterText = filterText;
    if(!isCaseSensitive) {
        normalizedFilterText = normalizedFilterText.toLower();
    }

    if(isCompareWithoutSpaces) {
        normalizedFilterText = normalizedFilterText.replace(" ", "");
    }


    //
    // first, filter the items
    {
        QList<IdBasedWidgetBase *>::const_iterator it = allItems.begin();
        QList<IdBasedWidgetBase *>::const_iterator eit = allItems.end();
        for( ; it != eit; ++it )
        {
            bool isAddCurrItemToResultList = false;
            AppIconAndButtonPresenterWidget *castedIconPresenterWidget = dynamic_cast<AppIconAndButtonPresenterWidget *>( (*it) );
            if(castedIconPresenterWidget == NULL) {
                WLog("Cannot cast the widget to icon-presenter-widget. Cannot sort it.");
            }
            else {
                QString currItem = castedIconPresenterWidget->getRelatedAppName();
                if(isCompareWithoutSpaces) {
                    currItem = currItem.replace(" ", "");
                }
                if(!isCaseSensitive) {
                    currItem = currItem.toLower();
                }

                if(isMachesFilter(currItem, normalizedFilterText))
                {
                    // maches the filter-text, filter by other filters

                    bool isHidden = castedIconPresenterWidget->getRelatedAppDescriptionModel().getDynamicDescription_ReadOnly()->getIsHidden();

                    if(!isHidden) {
                        isAddCurrItemToResultList = true;
                    } else if(isAllowHiddenOnes) {
                        isAddCurrItemToResultList = true;
                    }

                    if(isAddCurrItemToResultList) {
                        if(isOnlyHiddenOnes && !isHidden) {
                            isAddCurrItemToResultList = false;
                        }
                    }


                    if(isAddCurrItemToResultList) {
                        if(isOnlyAutostartOnes) {
                            bool isStartThisAppWhenClientStarts = castedIconPresenterWidget->getRelatedAppDescriptionModel().getDynamicDescription_ReadOnly()->getIsStartWhenClientStarts();
                            if(!isStartThisAppWhenClientStarts) {
                                isAddCurrItemToResultList = false;
                            }
                        }
                    }

                    if(isAddCurrItemToResultList) {
                        if(!isAllowNotInstalledOnes) {
                            AppWhirr::ApplicationGrabStates::ApplicationGrabStatesEnum currState = castedIconPresenterWidget->getRelatedAppDescriptionModel().getDynamicDescription_ReadOnly()->getAppState();
                            if((int)currState < (int)AppWhirr::ApplicationGrabStates::Installed) {
                                isAddCurrItemToResultList = false;
                            }
                        }
                    }
                }
            }

            if(isAddCurrItemToResultList) {
                resultIconPresenterList << *it;
            }
        }
    }



    //
    // sort them
    {
        //    QString filterMatchItem;
        //    SortingDatabaseManager *sortingDbManager = new SortingDatabaseManager;
        //    bool isSuccess = sortingDbManager->getValueForKey(filterText, filterMatchItem);
        //    delete sortingDbManager;

        QString filterMatchItem = this->_filterKeyValueMap.value(filterText, QString());

        // filter match test
        if(!filterMatchItem.isEmpty())
        {
            // filter match found!!
            qDebug("!! filter match found !!");
            int idx = -1;
            IdBasedWidgetBase *foundFilterMatchItem = NULL;

            // search
            {
                int foundItemCnt = resultIconPresenterList.size();
                for(int i = 0; i < foundItemCnt && idx == -1; i++) {
                    AppIconAndButtonPresenterWidget *castedItem = dynamic_cast<AppIconAndButtonPresenterWidget *>(resultIconPresenterList[i]);
                    if(castedItem != NULL &&
                       castedItem->getRelatedAppName() == filterMatchItem) {
                        idx = i;
                        foundFilterMatchItem = castedItem;
                    }
                }
            }

            if(idx != -1)
            {
                // move to the front
                resultIconPresenterList.removeAt(idx);
                resultIconPresenterList.insert(0, foundFilterMatchItem);
            }
        }
    }


    // and Q_EMIT and update
    resultItems._setItems(resultIconPresenterList);
    Q_EMIT sortingHappened(resultItems);

    //return resultItems;
}
Ejemplo n.º 30
0
ErrorList topolTest::checkOverlapWithLayer( double tolerance, QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  Q_UNUSED( tolerance );

  int i = 0;
  ErrorList errorList;

  bool skipItself = layer1 == layer2;
  QgsSpatialIndex *index = mLayerIndexes[layer2->id()];

  QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( qgsInterface->mapCanvas()->extent().asWktPolygon() );

  QList<FeatureLayer>::iterator it;
  for ( it = mFeatureList1.begin(); it != mFeatureList1.end(); ++it )
  {
    if ( !( ++i % 100 ) )
      emit progress( i );

    if ( testCanceled() )
      break;

    QgsGeometry g1 = it->feature.geometry();
    QgsRectangle bb = g1.boundingBox();

    QList<QgsFeatureId> crossingIds;
    crossingIds = index->intersects( bb );

    QList<QgsFeatureId>::ConstIterator cit = crossingIds.begin();
    QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.end();
    for ( ; cit != crossingIdsEnd; ++cit )
    {
      QgsFeature &f = mFeatureMap2[*cit].feature;
      QgsGeometry g2 = f.geometry();

      // skip itself, when invoked with the same layer
      if ( skipItself && f.id() == it->feature.id() )
        continue;

      if ( g2.isNull() )
      {
        QgsMessageLog::logMessage( tr( "Second geometry missing." ), tr( "Topology plugin" ) );
        continue;
      }

      if ( g1.overlaps( g2 ) )
      {
        QgsRectangle r = bb;
        QgsRectangle r2 = g2.boundingBox();
        r.combineExtentWith( r2 );

        QgsGeometry conflictGeom = g1.intersection( g2 );
        // could this for some reason return NULL?
        if ( conflictGeom.isNull() )
        {
          continue;
        }

        if ( isExtent )
        {
          if ( canvasExtentPoly.disjoint( conflictGeom ) )
          {
            continue;
          }
          if ( canvasExtentPoly.crosses( conflictGeom ) )
          {
            conflictGeom = conflictGeom.intersection( canvasExtentPoly );
          }
        }

        //c = new QgsGeometry;

        QList<FeatureLayer> fls;
        FeatureLayer fl;
        fl.feature = f;
        fl.layer = layer2;
        fls << *it << fl;
        TopolErrorIntersection *err = new TopolErrorIntersection( r, conflictGeom, fls );

        errorList << err;
      }
    }
  }
  return errorList;
}