Example #1
0
bool QgsRelief::calculateRegression( const QList< QPair < int, double > > &input, double &a, double &b )
{
  double xMean, yMean;
  double xSum = 0;
  double ySum = 0;
  QList< QPair < int, double > >::const_iterator inputIt = input.constBegin();
  for ( ; inputIt != input.constEnd(); ++inputIt )
  {
    xSum += inputIt->first;
    ySum += inputIt->second;
  }
  xMean = xSum / input.size();
  yMean = ySum / input.size();

  double sumCounter = 0;
  double sumDenominator = 0;
  inputIt = input.constBegin();
  for ( ; inputIt != input.constEnd(); ++inputIt )
  {
    sumCounter += ( ( inputIt->first - xMean ) * ( inputIt->second - yMean ) );
    sumDenominator += ( ( inputIt->first - xMean ) * ( inputIt->first - xMean ) );
  }

  a = sumCounter / sumDenominator;
  b = yMean - a * xMean;

  return true;
}
Example #2
0
qint32 QSerialPortPrivate::baudRateFromSetting(qint32 setting)
{
    const QList<qint32> baudRatePairs = standardBaudRatePairList();
    const QList<qint32>::const_iterator baudRatePairListConstIterator
            = std::find(baudRatePairs.constBegin(), baudRatePairs.constEnd(), setting);

    return (baudRatePairListConstIterator != baudRatePairs.constEnd()) ? *baudRatePairListConstIterator : 0;
}
Example #3
0
qint32 QSerialPortPrivate::settingFromBaudRate(qint32 baudRate)
{
    const QList<qint32> baudRatePairList = standardBaudRatePairList();
    const QList<qint32>::const_iterator baudRatePairListConstIterator
            = std::find(baudRatePairList.constBegin(), baudRatePairList.constEnd(), baudRate);

    return (baudRatePairListConstIterator != baudRatePairList.constEnd()) ? *baudRatePairListConstIterator : 0;
}
void PluginManager::loadAllPlugins()
{
	// FIXME: We need session management here - Martijn

	KSharedConfig::Ptr config = KGlobal::config();
	if ( config->hasGroup( QLatin1String( "Plugins" ) ) )
	{
		QMap<QString, bool> pluginsMap;

		QMap<QString, QString> entries = config->entryMap( QLatin1String( "Plugins" ) );
		QMap<QString, QString>::Iterator it;
		for ( it = entries.begin(); it != entries.end(); ++it )
		{
			QString key = it.key();
			if ( key.endsWith( QLatin1String( "Enabled" ) ) )
				pluginsMap.insert( key.left(key.length() - 7), (it.value() == QLatin1String( "true" )) );
		}

		QList<KPluginInfo> plugins = availablePlugins( QString::null );	//krazy:exclude=nullstrassign for old broken gcc
		QList<KPluginInfo>::ConstIterator it2 = plugins.constBegin();
		QList<KPluginInfo>::ConstIterator end = plugins.constEnd();
		for ( ; it2 != end; ++it2 )
		{
			// Protocols are loaded automatically so they aren't always in Plugins group. (fixes bug 167113)
			if ( it2->category() == QLatin1String( "Protocols" ) )
				continue;

			QString pluginName = it2->pluginName();
			if ( pluginsMap.value( pluginName, it2->isPluginEnabledByDefault() ) )
			{
				if ( !plugin( pluginName ) )
					_kpmp->pluginsToLoad.push( pluginName );
			}
			else
			{
				//This happens if the user unloaded plugins with the config plugin page.
				// No real need to be assync because the user usually unload few plugins
				// compared tto the number of plugin to load in a cold start. - Olivier
				if ( plugin( pluginName ) )
					unloadPlugin( pluginName );
			}
		}
	}
	else
	{
		// we had no config, so we load any plugins that should be loaded by default.
		QList<KPluginInfo> plugins = availablePlugins( QString::null );	//krazy:exclude=nullstrassign for old broken gcc
		QList<KPluginInfo>::ConstIterator it = plugins.constBegin();
		QList<KPluginInfo>::ConstIterator end = plugins.constEnd();
		for ( ; it != end; ++it )
		{
			if ( it->isPluginEnabledByDefault() )
				_kpmp->pluginsToLoad.push( it->pluginName() );
		}
	}
	// Schedule the plugins to load
	QTimer::singleShot( 0, this, SLOT(slotLoadNextPlugin()) );
}
void QgsPointDisplacementRenderer::drawSymbols( QgsRenderContext& context, const QList<QgsMarkerSymbolV2*>& symbolList, const QList<QPointF>& symbolPositions, bool selected )
{
  QList<QPointF>::const_iterator symbolPosIt = symbolPositions.constBegin();
  QList<QgsMarkerSymbolV2*>::const_iterator symbolIt = symbolList.constBegin();
  for ( ; symbolPosIt != symbolPositions.constEnd() && symbolIt != symbolList.constEnd(); ++symbolPosIt, ++symbolIt )
  {
    if ( *symbolIt )
    {
      ( *symbolIt )->renderPoint( *symbolPosIt, context, -1, selected );
    }
  }
}
void FuzzyProcessorWidget::createANewAttribute(){
    Q_ASSERT(m_pCurrentFuzzyOntologyClass);

    QModelIndex index = m_pAvailableAttributesListView->currentIndex();

    if(!index.isValid())
        return;

    QString name = m_pAvailableAttributesModel->data(index).toString();

    int lastIndexOfSemicolon = name.lastIndexOf(":");
    QString newName = name;
    newName = newName.insert(lastIndexOfSemicolon+1,QLatin1String("Fuzzy"));

    // parse all the class and attributes in order to get the number of attriutes already assigned to this kind of available attribute
    int counter = 1;
    QList<FuzzyOntologyClass*> oclasslist = FUZZYONTOLOGYCLASSMANAGER->fuzzyOntologyClasses();
    QList<FuzzyOntologyClass*>::const_iterator o;
    for(o = oclasslist.constBegin(); o != oclasslist.constEnd(); o++){
        FuzzyOntologyClass *pClass = *o;
        QList<FuzzyAttribute*> list = pClass->fuzzyAttributes();
        QList<FuzzyAttribute*>::const_iterator i;

        // now parse the attributes in order check for same name
        for(i = list.constBegin(); i != list.constEnd(); i++){
            FuzzyAttribute *pAttribute = *i;

            QString atName = pAttribute->valueName();

            if(atName.contains(newName))
                counter++;
        }
    }

    // then just append the counter number to the string
    newName = newName.append(QString::number(counter));

    // create a new attribute
    FuzzyAttribute *pFuzzyAttribute = new FuzzyAttribute(name,newName,this);
    m_pCurrentFuzzyOntologyClass->addFuzzyAttribute(pFuzzyAttribute);

    // create a new item
    QStandardItem *pItem = new QStandardItem();
    pItem->setText(name);
    pItem->setData(newName,Qt::UserRole);

    // append a new row to the model based on the item previously created
    m_pFuzzyAttributesModel->appendRow(pItem);

    m_pFuzzyAttributesTableView->resizeColumnToContents(0);
}
Example #7
0
void QgsLegendModel::setLayerSetAndGroups( const QStringList& layerIds, const QList< GroupLayerInfo >& groupInfo )
{
  setLayerSet( layerIds );

  QStandardItem* currentItem = 0;
  QStandardItem* currentGroupItem = 0;
  int i = 0;

  QList< GroupLayerInfo >::const_iterator infoIt = groupInfo.constBegin();
  for ( ; infoIt != groupInfo.constEnd() && i < invisibleRootItem()->rowCount(); )
  {
    currentItem = invisibleRootItem()->child( i, 0 );
    QString infoKey = infoIt->first;
    if ( infoKey.isNull() ) //a toplevel layer
    {
      ++i;
    }
    else //a group
    {
      currentGroupItem = addGroup( infoKey, i );
      ++i;
      QList<QString> layerList = infoIt->second;
      QList<QString>::const_iterator groupLayerIt = layerList.constBegin();
      for ( ; currentItem && ( groupLayerIt != layerList.constEnd() ); ++groupLayerIt )
      {
        //check if current item is contained in this group
        QgsComposerLayerItem* layerItem = dynamic_cast<QgsComposerLayerItem*>( currentItem );
        if ( !layerItem )
        {
          return; //should never happen
        }
        //QString layerID = currentItem->data(Qt::UserRole + 2).toString();
        QString layerID = layerItem->layerID();
        if ( layerList.contains( layerID ) )
        {
          takeRow( i );
          currentGroupItem->setChild( currentGroupItem->rowCount(), 0, currentItem );
        }
        else
        {
          ++i;
        }
        currentItem = invisibleRootItem()->child( i, 0 );
      }
    }
    ++infoIt;
  }
}
void ListView::dropEvent(QDropEvent *event)
{
  const QMimeData *mimeData = event->mimeData();

  QStringList imagePaths;
  QList<QUrl> imageUrls = mimeData->urls();
  QList<QUrl>::const_iterator end = imageUrls.constEnd();

  for (QList<QUrl>::const_iterator count = imageUrls.constBegin(); count != end; count++) {
    QString path = (*count).toLocalFile();
    if (!path.isEmpty() && path.contains(GCore::Data::self()->supportedFormats()))
      imagePaths << path;
  }

  QString image = imagePaths.first();
  image.remove(QRegExp("^.+/"));
  QString path = imagePaths.first();
  path.remove(image);

  QStringList pictures = imagePaths;
  pictures.replaceInStrings(path, QString());

  QAction *choice = Data::self()->dropContextMenu()->exec(mapToGlobal(event->pos()));

  if (!choice)
    return;

  if (choice->data().toInt() == 0) {
    NewGalleryWizard *wizard = new NewGalleryWizard(path, pictures, this);
    wizard->show();
  } else if (choice->data().toInt() == 1) {
    Job job = JobManager::self()->addImages(rootIndex(), imagePaths);
    connect(job.jobPtr(), SIGNAL(progress(int, int, const QString&, const QImage&)), GCore::Data::self()->imageAddProgress(), SLOT(setProgress(int, int, const QString&, const QImage&)));
  }
EditIndexDialog::EditIndexDialog(DBBrowserDB& db, const QString& indexName, bool createIndex, QWidget* parent)
    : QDialog(parent),
      pdb(db),
      curIndex(indexName),
      index(indexName),
      newIndex(createIndex),
      ui(new Ui::EditIndexDialog),
      m_sRestorePointName(pdb.generateSavepointName("editindex"))
{
    // Create UI
    ui->setupUi(this);

    // Get list of tables, sort it alphabetically and fill the combobox
    objectMap dbobjs;
    QList<sqlb::ObjectPtr> tables = pdb.objMap.values("table");
    for(auto it=tables.constBegin();it!=tables.constEnd();++it)
        dbobjs.insert((*it)->name(), (*it));
    ui->comboTableName->blockSignals(true);
    for(auto it=dbobjs.constBegin();it!=dbobjs.constEnd();++it)
        ui->comboTableName->addItem(QIcon(QString(":icons/table")), (*it)->name());
    ui->comboTableName->blockSignals(false);

    QHeaderView *tableHeaderView = ui->tableIndexColumns->horizontalHeader();
    tableHeaderView->setSectionResizeMode(0, QHeaderView::Stretch);

    // Editing an existing index?
    if(!newIndex)
    {
        // Load the current layout and fill in the dialog fields
        index = *(pdb.getObjectByName(curIndex).dynamicCast<sqlb::Index>());

        ui->editIndexName->blockSignals(true);
        ui->editIndexName->setText(index.name());
        ui->editIndexName->blockSignals(false);
        ui->checkIndexUnique->blockSignals(true);
        ui->checkIndexUnique->setChecked(index.unique());
        ui->checkIndexUnique->blockSignals(false);
        ui->comboTableName->blockSignals(true);
        ui->comboTableName->setCurrentText(index.table());
        ui->comboTableName->blockSignals(false);
        ui->editPartialClause->blockSignals(true);
        ui->editPartialClause->setText(index.whereExpr());
        ui->editPartialClause->blockSignals(false);

        tableChanged(index.table(), true);
    } else {
        tableChanged(ui->comboTableName->currentText(), false);
    }

    // Add event handler for index column name changes. These are only allowed for expression columns, though.
    connect(ui->tableIndexColumns, static_cast<void(QTableWidget::*)(QTableWidgetItem*)>(&QTableWidget::itemChanged),
            [=](QTableWidgetItem* item)
    {
        index.columns().at(item->row())->setName(item->text());
        updateSqlText();
    });

    // Create a savepoint to revert back to
    pdb.setSavepoint(m_sRestorePointName);
}
Example #10
0
Card::Difficulty Card::getDifficulty() const
{
    const QList<Point*> points = history.getPoints();

    int level = 0;
    int success = 0;
    for (auto it=points.constBegin();
        it!=points.constEnd(); ++it) {
        if((*it)->level > level)
            success++;
        else if((*it)->level < level)
            success--;
        else {
            if(level==0)
                success--;
            else
                success++;
        }
        level = (*it)->level;
    }

    if(success>5) {
        return Easy;
    } else if(success<-5) {
        return Hard;
    }

    return Normal;
}
GroupCreationWizardPageInfo::GroupCreationWizardPageInfo(ClientConfiguration* clientConfiguration, QWidget *parent) : QWizardPage(parent), ui(new Ui::GroupCreationWizardPageInfo), clientConfiguration(clientConfiguration) {
    ui->setupUi(this);

	nameValidator = new QRegExpValidator(QRegExp(".+", Qt::CaseInsensitive, QRegExp::RegExp2), ui->edtName);
	ui->edtName->setValidator(nameValidator);

	ui->listWidget->clear();
	ui->listWidget->setSelectionMode(QListWidget::SelectionMode::MultiSelection);

	OPENMITTSU_CONNECT(ui->listWidget, itemSelectionChanged(), this, onListWidgetItemSelectionChanged());

	// Load all Identities
	ContactRegistry* contactRegistry = ContactRegistry::getInstance();
	QList<ContactId> knownIdentities = contactRegistry->getIdentities();
	QList<ContactId>::const_iterator it = knownIdentities.constBegin();
	QList<ContactId>::const_iterator end = knownIdentities.constEnd();

	ContactId const selfIdentity = (clientConfiguration == nullptr) ? ContactId(0) : clientConfiguration->getClientIdentity();
	for (; it != end; ++it) {
		if (*it == selfIdentity) {
			continue;
		}
		ContactListWidgetItem* clwi = new ContactListWidgetItem(contactRegistry->getIdentity(*it), contactRegistry->getNickname(*it));
		ui->listWidget->addItem(clwi);
	}
	ui->listWidget->clearSelection();
	isSelectionOkay = false;

	registerField("edtName*", ui->edtName);
	registerField("listWidget*", ui->listWidget);
}
int QgsVectorLayerEditUtils::boundingBoxFromPointList( const QList<QgsPoint>& list, double& xmin, double& ymin, double& xmax, double& ymax ) const
{
  if ( list.size() < 1 )
  {
    return 1;
  }

  xmin = std::numeric_limits<double>::max();
  xmax = -std::numeric_limits<double>::max();
  ymin = std::numeric_limits<double>::max();
  ymax = -std::numeric_limits<double>::max();

  for ( QList<QgsPoint>::const_iterator it = list.constBegin(); it != list.constEnd(); ++it )
  {
    if ( it->x() < xmin )
    {
      xmin = it->x();
    }
    if ( it->x() > xmax )
    {
      xmax = it->x();
    }
    if ( it->y() < ymin )
    {
      ymin = it->y();
    }
    if ( it->y() > ymax )
    {
      ymax = it->y();
    }
  }

  return 0;
}
Example #13
0
bool QgsComposerTable::calculateMaxColumnWidths( QMap<int, double>& maxWidthMap, const QList<QgsAttributeMap>& attributeMaps ) const
{
  maxWidthMap.clear();
  QList<QgsComposerTableColumn*>::const_iterator columnIt = mColumns.constBegin();

  int col = 0;
  for ( ; columnIt != mColumns.constEnd(); ++columnIt )
  {
    maxWidthMap.insert( col, QgsComposerUtils::textWidthMM( mHeaderFont, ( *columnIt )->heading() ) );
    col++;
  }

  //go through all the attributes and adapt the max width values
  QList<QgsAttributeMap>::const_iterator attIt = attributeMaps.constBegin();

  double currentAttributeTextWidth;

  for ( ; attIt != attributeMaps.constEnd(); ++attIt )
  {
    QgsAttributeMap::const_iterator attIt2 = attIt->constBegin();
    for ( ; attIt2 != attIt->constEnd(); ++attIt2 )
    {
      currentAttributeTextWidth = QgsComposerUtils::textWidthMM( mContentFont, attIt2.value().toString() );
      if ( currentAttributeTextWidth > maxWidthMap[ attIt2.key()] )
      {
        maxWidthMap[ attIt2.key()] = currentAttributeTextWidth;
      }
    }
  }
  return true;
}
Example #14
0
ErrorList topolTest::checkPolygonContainsPoint( double tolerance, QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  Q_UNUSED( tolerance );
  Q_UNUSED( isExtent );

  int i = 0;
  ErrorList errorList;

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

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

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

  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.constEnd();
    bool touched = 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 ( g1.contains( g2 ) )
      {
        touched = true;
        break;
      }
    }
    if ( !touched )
    {
      QList<FeatureLayer> fls;
      fls << *it << *it;
      //bb.scale(10);
      TopolErrorPolygonContainsPoint *err = new TopolErrorPolygonContainsPoint( bb, g1, fls );
      errorList << err;
    }
  }
  return errorList;
}
Example #15
0
int QgsLegendModel::addRasterLayerItems( QStandardItem* layerItem, QgsMapLayer* rlayer )
{
  if ( !layerItem || !rlayer )
  {
    return 1;
  }

  QgsRasterLayer* rasterLayer = qobject_cast<QgsRasterLayer *>( rlayer );
  if ( !rasterLayer )
  {
    return 2;
  }

  QList< QPair< QString, QColor > > rasterItemList = rasterLayer->legendSymbologyItems();
  QList< QPair< QString, QColor > >::const_iterator itemIt = rasterItemList.constBegin();
  for ( ; itemIt != rasterItemList.constEnd(); ++itemIt )
  {
    QgsComposerRasterSymbolItem* currentSymbolItem = new QgsComposerRasterSymbolItem( itemIt->first );
    if ( mHasTopLevelWindow )
    {
      QPixmap itemPixmap( 20, 20 );
      itemPixmap.fill( itemIt->second );
      currentSymbolItem->setIcon( QIcon( itemPixmap ) );
    }
    currentSymbolItem->setLayerID( rasterLayer->id() );
    currentSymbolItem->setColor( itemIt->second );
    int currentRowCount = layerItem->rowCount();
    layerItem->setChild( currentRowCount, 0, currentSymbolItem );
  }

  return 0;
}
Example #16
0
void KNMusicModel::appendRows(const QList<KNMusicDetailInfo> &detailInfos)
{
    //Ignore the empty adding request.
    if(detailInfos.isEmpty())
    {
        return;
    }
    //Follow the documentation, we have to do this.
    beginInsertRows(QModelIndex(),
                    m_detailInfos.size(),
                    m_detailInfos.size() + detailInfos.size() - 1);
    //Append the data at the end of the rows.
    m_detailInfos.append(detailInfos);
    //Add all the duration to the total duration counter.
    for(auto i=detailInfos.constBegin(); i!=detailInfos.constEnd(); ++i)
    {
        //Add each duration to the total duration.
        m_totalDuration+=(*i).duration;
    }
    //As the documentation said, called this after insert rows.
    endInsertRows();
    //Because this operation change the row count, the row count changed signal
    //will be emitted.
    emit rowCountChanged();
}
Example #17
0
void QgsRasterShader::writeXML( QDomDocument& doc, QDomElement& parent ) const
{
  if ( parent.isNull() || !mRasterShaderFunction )
  {
    return;
  }

  QDomElement rasterShaderElem = doc.createElement( "rastershader" );
  QgsColorRampShader* colorRampShader = dynamic_cast<QgsColorRampShader*>( mRasterShaderFunction );
  if ( colorRampShader )
  {
    QDomElement colorRampShaderElem = doc.createElement( "colorrampshader" );
    colorRampShaderElem.setAttribute( "colorRampType", colorRampShader->colorRampTypeAsQString() );
    colorRampShaderElem.setAttribute( "clip", colorRampShader->clip() );
    //items
    QList<QgsColorRampShader::ColorRampItem> itemList = colorRampShader->colorRampItemList();
    QList<QgsColorRampShader::ColorRampItem>::const_iterator itemIt = itemList.constBegin();
    for ( ; itemIt != itemList.constEnd(); ++itemIt )
    {
      QDomElement itemElem = doc.createElement( "item" );
      itemElem.setAttribute( "label", itemIt->label );
      itemElem.setAttribute( "value", QString::number( itemIt->value ) );
      itemElem.setAttribute( "color", itemIt->color.name() );
      itemElem.setAttribute( "alpha", itemIt->color.alpha() );
      colorRampShaderElem.appendChild( itemElem );
    }
    rasterShaderElem.appendChild( colorRampShaderElem );
  }
  parent.appendChild( rasterShaderElem );
}
Example #18
0
/* private slots */
qint64 ShredThread::getDirSize(QString &dir)
{
    uint _size = 0;
    QDir::Filters flags =
            QDir::AllEntries |
            QDir::NoDotAndDotDot |
            QDir::Hidden |
            QDir::System |
            QDir::AllDirs;
    QDir d;
    d.setPath(dir);
    QList<QFileInfo> entry = d.entryInfoList(flags);
    if ( !entry.isEmpty() ) {
        QList<QFileInfo>::const_iterator i;
        for ( i=entry.constBegin(); i<entry.constEnd(); i++ ) {
            QFileInfo item = *i;
            if ( !item.exists() ) continue;
            QString path = item.canonicalFilePath();
            if ( path==d.absoluteFilePath(dir)
                 || item.isSymLink() )
                continue;
            if ( item.isDir() ) {
                _size += getDirSize(path);
            } else {
                _size += item.size();
            };
        };
    };
    return _size;
}
Example #19
0
  void CETranslateWidget::checkSelection()
  {
    // User closed the dialog:
    if (this->isHidden()) {
      m_selectionTimer.stop();
      return;
    }

    // Improper initialization
    if (m_gl == NULL)
      return setError(tr("No GLWidget?"));

    QList<Primitive*> atoms = m_gl->selectedPrimitives().subList
      (Primitive::AtomType);

    // No selection
    if (!atoms.size())
      return setError(tr("Please select one or more atoms."));

    clearError();

    // Calculate centroid of selection
    m_vector = Eigen::Vector3d::Zero();
    for (QList<Primitive*>::const_iterator
           it = atoms.constBegin(),
           it_end = atoms.constEnd();
         it != it_end; ++it) {
      m_vector += (*qobject_cast<Atom* const>(*it)->pos());
    }
    m_vector /= -static_cast<double>(atoms.size());

    updateGui();
  }
bool QgsCoordinateTransform::setFromCache( const QgsCoordinateReferenceSystem &src, const QgsCoordinateReferenceSystem &dest, int srcDatumTransform, int destDatumTransform )
{
  if ( !src.isValid() || !dest.isValid() )
    return false;

  sCacheLock.lockForRead();
  const QList< QgsCoordinateTransform > values = sTransforms.values( qMakePair( src.authid(), dest.authid() ) );
  for ( auto valIt = values.constBegin(); valIt != values.constEnd(); ++valIt )
  {
    if ( ( *valIt ).sourceDatumTransformId() == srcDatumTransform &&
         ( *valIt ).destinationDatumTransformId() == destDatumTransform )
    {
      // need to save, and then restore the context... we don't want this to be cached or to use the values from the cache
      QgsCoordinateTransformContext context = mContext;
#ifdef QGISDEBUG
      bool hasContext = mHasContext;
#endif
      *this = *valIt;
      sCacheLock.unlock();

      mContext = context;
#ifdef QGISDEBUG
      mHasContext = hasContext;
#endif

      return true;
    }
  }
  sCacheLock.unlock();
  return false;
}
QString MainWindow::FeatureDialog::featureString()
{
    QList<Data> features;
    features << Data( i18n("Plug-ins available"), QString::fromLatin1("#kipi"),  hasKIPISupport() );
    features << Data( i18n("EXIF info supported"), QString::fromLatin1("#exiv2"), hasEXIV2Support() );
    features << Data( i18n( "Sqlite database support (used for EXIF searches)" ), QString::fromLatin1("#database"), hasEXIV2DBSupport() );
    features << Data( i18n( "Face detection and recognition support" ), QString::fromLatin1("#kface"),  hasKfaceSupport() );
    features << Data( i18n( "Map view for geotagged images." ), QString::fromLatin1("#geomap"),  hasGeoMapSupport() );
    features << Data( i18n( "Video support" ), QString::fromLatin1("#video"),  !supportedVideoMimeTypes().isEmpty() );

    QString result = QString::fromLatin1("<p><table>");
    const QString red = QString::fromLatin1("<font color=\"red\">%1</font>");
    const QString yes = i18nc("Feature available","Yes");
    const QString no =  red.arg( i18nc("Feature not available","No") );
    const QString formatString = QString::fromLatin1( "<tr><td><a href=\"%1\">%2</a></td><td><b>%3</b></td></tr>" );
    for( QList<Data>::ConstIterator featureIt = features.constBegin(); featureIt != features.constEnd(); ++featureIt ) {
        result += formatString
                  .arg( (*featureIt).tag ).arg( (*featureIt).title ).arg( (*featureIt).featureFound ? yes : no  );
    }

    QString thumbnailSupport = mplayerBinary().isNull() ? no : ( isMplayer2() ? yes : red.arg(i18n("Only with MPlayer1")));
    result += formatString.arg(QString::fromLatin1("#videoPreview")).arg(i18n("Video thumbnail support")).arg(thumbnailSupport);
    result += QString::fromLatin1( "</table></p>" );

    return result;
}
void 
DataVisualizer::setItemPos(QGraphicsItem * item, QPointF pos)
{
	typedef QList<QGraphicsItem *> QGraphicsItemList;
	SceneType scene(gvDisplay->scene());
	if (!item || !scene) return;
	// set the desired position
	item->setPos(pos);
	// check for collisions with other items
	QList<QGraphicsItem *> collides = scene->collidingItems(item);
	if (collides.size() == 0) return;
	QGraphicsItem * cItem = 0;
	QGraphicsItemList::const_iterator it = collides.constBegin();
	while(it != collides.constEnd()) {
		cItem = *it;
		if (cItem && !cItem->parentItem()) break;
		it++;
	}
	if (!cItem || cItem->parentItem()) return;
	// item has no parent => top-level, bounding rect
	qreal newYPos = cItem->y() + 
			0.5*cItem->boundingRect().height() + 
			0.5*item->boundingRect().height() +
			itemMargin;
	QPointF newPos(pos);
	newPos.setY(newYPos);
	setItemPos(item, newPos);
}
Example #23
0
void QgsSnapper::cleanResultList( QMultiMap<double, QgsSnappingResult>& list, const QList<QgsPoint>& excludeList ) const
{
  QgsPoint currentResultPoint;
  QgsSnappingResult currentSnappingResult;
  QList<double> keysToRemove;

  QMultiMap<double, QgsSnappingResult>::iterator result_it = list.begin();
  for ( ; result_it != list.end(); ++result_it )
  {
    currentSnappingResult = result_it.value();
    if ( currentSnappingResult.snappedVertexNr != -1 )
    {
      currentResultPoint = currentSnappingResult.snappedVertex;
      if ( excludeList.contains( currentResultPoint ) )
      {
        keysToRemove.push_back( result_it.key() );
      }
    }
  }

  QList<double>::const_iterator remove_it = keysToRemove.constBegin();
  for ( ; remove_it != keysToRemove.constEnd(); ++remove_it )
  {
    list.remove( *remove_it );
  }
}
Example #24
0
void QFontDialogPrivate::updateSizes()
{
    Q_Q(QFontDialog);

    if (!familyList->currentText().isEmpty()) {
        QList<int> sizes = fdb.pointSizes(familyList->currentText(), styleList->currentText());

        int i = 0;
        int current = -1;
        QStringList str_sizes;
        for(QList<int>::const_iterator it = sizes.constBegin(); it != sizes.constEnd(); ++it) {
            str_sizes.append(QString::number(*it));
            if (current == -1 && *it >= size)
                current = i;
            ++i;
        }
        sizeList->model()->setStringList(str_sizes);
        if (current == -1) {
            // we request a size bigger than the ones in the list, select the biggest one
            current = sizeList->count() - 1;
        }
        sizeList->setCurrentItem(current);

        sizeEdit->blockSignals(true);
        sizeEdit->setText((smoothScalable ? QString::number(size) : sizeList->currentText()));
        if (q->style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, q)
                && sizeList->hasFocus())
            sizeEdit->selectAll();
        sizeEdit->blockSignals(false);
    } else {
        sizeEdit->clear();
    }

    _q_updateSample();
}
Example #25
0
void KArchiveDirectory::copyTo(const QString& dest, bool recursiveCopy ) const
{
  QDir root;

  QList<const KArchiveFile*> fileList;
  QMap<qint64, QString> fileToDir;

  // placeholders for iterated items
  QStack<const KArchiveDirectory *> dirStack;
  QStack<QString> dirNameStack;

  dirStack.push( this );     // init stack at current directory
  dirNameStack.push( dest ); // ... with given path
  do {
	const KArchiveDirectory* curDir = dirStack.pop();
	const QString curDirName = dirNameStack.pop();
	root.mkdir(curDirName);

	const QStringList dirEntries = curDir->entries();
	for ( QStringList::const_iterator it = dirEntries.begin(); it != dirEntries.end(); ++it ) {
	  const KArchiveEntry* curEntry = curDir->entry(*it);
	  if (!curEntry->symLinkTarget().isEmpty()) {
		  const QString linkName = curDirName+'/'+curEntry->name();
#ifdef Q_OS_UNIX
		  if (!::symlink(curEntry->symLinkTarget().toLocal8Bit(), linkName.toLocal8Bit())) {
			  qDebug() << "symlink(" << curEntry->symLinkTarget() << ',' << linkName << ") failed:" << strerror(errno);
		  }
#else
		  // TODO - how to create symlinks on other platforms?
#endif
	  } else {
		  if ( curEntry->isFile() ) {
			  const KArchiveFile* curFile = dynamic_cast<const KArchiveFile*>( curEntry );
			  if (curFile) {
				  fileList.append( curFile );
				  fileToDir.insert( curFile->position(), curDirName );
			  }
		  }

		  if ( curEntry->isDirectory() && recursiveCopy ) {
			  const KArchiveDirectory *ad = dynamic_cast<const KArchiveDirectory*>( curEntry );
			  if (ad) {
				  dirStack.push( ad );
				  dirNameStack.push( curDirName + '/' + curEntry->name() );
			  }
		  }
	  }
	}
  } while (!dirStack.isEmpty());

  qSort( fileList.begin(), fileList.end(), sortByPosition );  // sort on d->pos, so we have a linear access

  for ( QList<const KArchiveFile*>::const_iterator it = fileList.constBegin(), end = fileList.constEnd() ;
		it != end ; ++it ) {
	  const KArchiveFile* f = *it;
	  qint64 pos = f->position();
	  f->copyTo( fileToDir[pos] );
  }
}
Example #26
0
int qDBusParametersForMethod(const QList<QByteArray> &parameterTypes, QVector<int>& metaTypes)
{
    QDBusMetaTypeId::init();
    metaTypes.clear();

    metaTypes.append(0);        // return type
    int inputCount = 0;
    bool seenMessage = false;
    QList<QByteArray>::ConstIterator it = parameterTypes.constBegin();
    QList<QByteArray>::ConstIterator end = parameterTypes.constEnd();
    for ( ; it != end; ++it) {
        const QByteArray &type = *it;
        if (type.endsWith('*')) {
            //qWarning("Could not parse the method '%s'", mm.methodSignature().constData());
            // pointer?
            return -1;
        }

        if (type.endsWith('&')) {
            QByteArray basictype = type;
            basictype.truncate(type.length() - 1);

            int id = QMetaType::type(basictype);
            if (id == 0) {
                //qWarning("Could not parse the method '%s'", mm.methodSignature().constData());
                // invalid type in method parameter list
                return -1;
            } else if (QDBusMetaType::typeToSignature(id) == 0)
                return -1;

            metaTypes.append( id );
            seenMessage = true; // it cannot appear anymore anyways
            continue;
        }

        if (seenMessage) {      // && !type.endsWith('&')
            //qWarning("Could not parse the method '%s'", mm.methodSignature().constData());
            // non-output parameters after message or after output params
            return -1;          // not allowed
        }

        int id = QMetaType::type(type);
        if (id == QMetaType::UnknownType) {
            //qWarning("Could not parse the method '%s'", mm.methodSignature().constData());
            // invalid type in method parameter list
            return -1;
        }

        if (id == QDBusMetaTypeId::message())
            seenMessage = true;
        else if (QDBusMetaType::typeToSignature(id) == 0)
            return -1;

        metaTypes.append(id);
        ++inputCount;
    }

    return inputCount;
}
Example #27
0
bool haveGoodTranslition(const QList<Word> &text)
{
    bool res = true;
    for (QList<Word>::const_iterator i = text.constBegin(); i != text.constEnd(); ++i){
        res &= i->haveGoodTranslition;
    }
    return res;
}
Example #28
0
int QgsLegendModel::addVectorLayerItems( QStandardItem* layerItem, QgsVectorLayer* vlayer )
{
  if ( !layerItem || !vlayer )
  {
    return 1;
  }

  int opacity = vlayer->getTransparency();

  const QgsRenderer* vectorRenderer = vlayer->renderer();
  if ( !vectorRenderer )
  {
    return 3;
  }

  //text field that describes classification attribute?
  QSettings settings;
  if ( settings.value( "/qgis/showLegendClassifiers", false ).toBool() )
  {
    QgsFieldMap layerFields = vlayer->pendingFields();
    QgsAttributeList attributes = vectorRenderer->classificationAttributes();
    QgsAttributeList::const_iterator att_it = attributes.constBegin();
    for ( ; att_it != attributes.constEnd(); ++att_it )
    {
      QgsFieldMap::const_iterator fieldIt = layerFields.find( *att_it );
      if ( fieldIt != layerFields.constEnd() )
      {
        QString attributeName = vlayer->attributeDisplayName( fieldIt.key() );
        QStandardItem* attributeItem = new QStandardItem( attributeName );
        attributeItem->setData( QgsLegendModel::ClassificationItem, Qt::UserRole + 1 ); //first user data stores the item type
        attributeItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable );
        layerItem->setChild( layerItem->rowCount(), 0, attributeItem );
      }
    }
  }

  const QList<QgsSymbol*> vectorSymbols = vectorRenderer->symbols();
  QList<QgsSymbol*>::const_iterator symbolIt = vectorSymbols.constBegin();

  for ( ; symbolIt != vectorSymbols.constEnd(); ++symbolIt )
  {
    if ( !( *symbolIt ) )
    {
      continue;
    }

    QStandardItem* currentSymbolItem = itemFromSymbol( *symbolIt, opacity, vlayer->id() );
    if ( !currentSymbolItem )
    {
      continue;
    }

    layerItem->setChild( layerItem->rowCount(), 0, currentSymbolItem );

  }

  return 0;
}
void ImgurImagesList::slotAddImages(const QList<QUrl>& list)
{
    /* Replaces the KPImagesList::slotAddImages method, so that
     * ImgurImageListViewItems can be added instead of ImagesListViewItems */

    // Figure out which of the supplied URL's should actually be added and which
    // of them already exist.
    bool found;

    for (QList<QUrl>::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it)
    {
        QUrl imageUrl = *it;
        found         = false;

        if (iface())
        {
            QPointer<MetadataProcessor> meta = iface()->createMetadataProcessor();

            if (meta && meta->load(imageUrl))
            {
                const QString sUrl       = meta->getXmpTagString(QLatin1String("Xmp.kipi.Imgur.Hash"));
                const QString sDeleteUrl = meta->getXmpTagString(QLatin1String("Xmp.kipi.Imgur.Delete"));

                for (int i = 0; i < listView()->topLevelItemCount(); ++i)
                {
                    ImgurImageListViewItem* const currItem = dynamic_cast<ImgurImageListViewItem*>(listView()->topLevelItem(i));

                    if (currItem && currItem->url() == imageUrl)
                    {
                        found = true;

                        if (!sUrl.isEmpty())
                        {
                            currItem->setUrl(sUrl);
                        }

                        if (!sDeleteUrl.isEmpty())
                        {
                            currItem->setDeleteUrl(sDeleteUrl);
                        }

                        break;
                    }
                }

                if (!found)
                {
                    new ImgurImageListViewItem(listView(), imageUrl);
                }
            }
        }
    }

    // Duplicate the signalImageListChanged of the ImageWindow, to enable the
    // upload button again.
    emit signalImageListChanged();
    emit signalAddItems(list);
}
Example #30
0
// Check if all values are convertable to strings
// @input:
// - values - list of values
// @output:
// - bool - True is all values are convertable to strings, False otherwise
bool VariantData::VariantDataPrivate::isConvertableToString(const QList<QVariant> &values) const {
    for (QList<QVariant>::const_iterator iter = values.constBegin();
         iter != values.constEnd(); ++iter) {
        if (!(*iter).canConvert<QString>()) {
            return false;
        }
    }
    return true;
}